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 |
|---|---|---|---|---|
viewsets.py | import codecs
import glob
import os
import re
import tarfile
from itertools import chain
from typing import Type, Callable, Optional
import toml
from asciinema import asciicast
from asciinema.commands.cat import CatCommand
from django.conf import settings
from django.db.models import F, Q
from django.http import Strea... | return queryset
@action(methods=['put'], detail=True)
def worker_upload(self, request, pk):
file_obj = request.data['file']
instance: Action = self.get_object()
directory = os.path.dirname(instance.get_data_directory())
os.makedirs(directory, exist_ok=True)
t = ta... | eryset = queryset.filter(Q(plugin='') | Q(is_last=True))
| conditional_block |
viewsets.py | import codecs
import glob
import os
import re
import tarfile
from itertools import chain
from typing import Type, Callable, Optional
import toml
from asciinema import asciicast
from asciinema.commands.cat import CatCommand
from django.conf import settings
from django.db.models import F, Q
from django.http import Strea... | filterset_class = ActionFilter
ordering_fields = ('parent', 'parent', 'created_at', 'updated_at')
detail_serializer_class = DetailActionSerializer
pagination_class = StandardResultsSetPagination
def get_queryset(self):
queryset = super(ActionViewSet, self).get_queryset()
if self.act... | queryset = Action.objects.order_by('-pk')
serializer_class = ActionSerializer
filter_backends = (filters.OrderingFilter, filters.SearchFilter, DjangoFilterBackend)
search_fields = ('name',) | random_line_split |
viewsets.py | import codecs
import glob
import os
import re
import tarfile
from itertools import chain
from typing import Type, Callable, Optional
import toml
from asciinema import asciicast
from asciinema.commands.cat import CatCommand
from django.conf import settings
from django.db.models import F, Q
from django.http import Strea... | @action(methods=['get'], detail=True)
def terminal_output(self, request, pk):
instance: Action = self.get_object()
file: str = instance.get_terminal_path()
if not os.path.lexists(file) or not os.path.getsize(file):
raise Http404
return StreamingHttpResponse(asciinema_... | stance: Action = self.get_object()
return serve_file(request, instance.get_terminal_path())
| identifier_body |
lib.rs | // Copyright 2018-2022 argmin developers
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according... | pub trait ArgminSub<T, U> {
/// Subtract a `T` from `self`
fn sub(&self, other: &T) -> U;
}
/// (Pointwise) Multiply a `T` with `self`
pub trait ArgminMul<T, U> {
/// (Pointwise) Multiply a `T` with `self`
fn mul(&self, other: &T) -> U;
}
/// (Pointwise) Divide a `T` by `self`
pub trait ArgminDiv<T, U... | fn add(&self, other: &T) -> U;
}
/// Subtract a `T` from `self` | random_line_split |
main.rs | #![allow(dead_code)]
extern crate doom_iow;
use doom_iow::*;
use std::f32;
use std::process::Command;
use minifb;
// returns the RGBA color corresponding to UV(hitx, hity) on tex_walls
fn wall_x_texcoord(hitx: f32, hity: f32, tex_walls: &Texture) -> i32 {
let x = hitx - f32::floor(hitx + 0.5);
let y = hity ... |
for frame in 0..360 {
// for frame in 0..5 {
// for frame in 0..1 {
let output_path = "./out/";
let ss = format!("{}{:05}.ppm", output_path, frame);
// player.a -= 2. * std::f32::consts::PI / 360.;
player.set_a( player.get_a() - (2. * std::f32::consts::PI / 360.) );
... | .arg("out")
.output()
.expect("failed to create directory"); | random_line_split |
main.rs | #![allow(dead_code)]
extern crate doom_iow;
use doom_iow::*;
use std::f32;
use std::process::Command;
use minifb;
// returns the RGBA color corresponding to UV(hitx, hity) on tex_walls
fn wall_x_texcoord(hitx: f32, hity: f32, tex_walls: &Texture) -> i32 {
let x = hitx - f32::floor(hitx + 0.5);
let y = hity ... |
}
| {
let r = 2;
let g = 4;
let b = 8;
let a = 255;
let color = utils::pack_color_rgba(r, g, b, a);
let (rc, gc, bc, ac) = utils::unpack_color(color);
assert_eq!(vec![r, g, b, a], vec![rc, gc, bc, ac]);
} | identifier_body |
main.rs | #![allow(dead_code)]
extern crate doom_iow;
use doom_iow::*;
use std::f32;
use std::process::Command;
use minifb;
// returns the RGBA color corresponding to UV(hitx, hity) on tex_walls
fn wall_x_texcoord(hitx: f32, hity: f32, tex_walls: &Texture) -> i32 {
let x = hitx - f32::floor(hitx + 0.5);
let y = hity ... |
let rect_x = i as usize * rect_w;
let rect_y = j as usize * rect_h;
let texid = map.get(i, j).expect("i, j not in map range");
fb.draw_rectangle(
rect_x,
rect_y,
rect_w,
rect_h,
tex_walls.get... | {
continue; //skip empty spaces
} | conditional_block |
main.rs | #![allow(dead_code)]
extern crate doom_iow;
use doom_iow::*;
use std::f32;
use std::process::Command;
use minifb;
// returns the RGBA color corresponding to UV(hitx, hity) on tex_walls
fn wall_x_texcoord(hitx: f32, hity: f32, tex_walls: &Texture) -> i32 {
let x = hitx - f32::floor(hitx + 0.5);
let y = hity ... | () {
let packed = 0b0001_0000_0000_1000_0000_0100_0000_0010;
let (r, g, b, a) = utils::unpack_color(packed);
assert_eq!(vec![2, 4, 8, 16], vec![r, g, b, a]);
}
#[test]
fn packs_ints_idempotently() {
let r = 2;
let g = 4;
let b = 8;
let a = 255;
... | unpacks_ints | identifier_name |
metrics.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: envoy/admin/v3/metrics.proto
package envoy_admin_v3
import (
fmt "fmt"
_ "github.com/cncf/udpa/go/udpa/annotations"
proto "github.com/gogo/protobuf/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they ar... |
const (
SimpleMetric_COUNTER SimpleMetric_Type = 0
SimpleMetric_GAUGE SimpleMetric_Type = 1
)
var SimpleMetric_Type_name = map[int32]string{
0: "COUNTER",
1: "GAUGE",
}
var SimpleMetric_Type_value = map[string]int32{
"COUNTER": 0,
"GAUGE": 1,
}
func (x SimpleMetric_Type) String() string {
return proto.En... | random_line_split | |
metrics.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: envoy/admin/v3/metrics.proto
package envoy_admin_v3
import (
fmt "fmt"
_ "github.com/cncf/udpa/go/udpa/annotations"
proto "github.com/gogo/protobuf/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they ar... | (dAtA []byte) (int, error) {
size := m.Size()
return m.MarshalToSizedBuffer(dAtA[:size])
}
func (m *SimpleMetric) MarshalToSizedBuffer(dAtA []byte) (int, error) {
i := len(dAtA)
_ = i
var l int
_ = l
if m.XXX_unrecognized != nil {
i -= len(m.XXX_unrecognized)
copy(dAtA[i:], m.XXX_unrecognized)
}
if len(m.... | MarshalTo | identifier_name |
metrics.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: envoy/admin/v3/metrics.proto
package envoy_admin_v3
import (
fmt "fmt"
_ "github.com/cncf/udpa/go/udpa/annotations"
proto "github.com/gogo/protobuf/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they ar... |
if m.XXX_unrecognized != nil {
n += len(m.XXX_unrecognized)
}
return n
}
func sovMetrics(x uint64) (n int) {
return (math_bits.Len64(x|1) + 6) / 7
}
func sozMetrics(x uint64) (n int) {
return sovMetrics(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (m *SimpleMetric) Unmarshal(dAtA []byte) error {
l := l... | {
n += 1 + l + sovMetrics(uint64(l))
} | conditional_block |
metrics.pb.go | // Code generated by protoc-gen-gogo. DO NOT EDIT.
// source: envoy/admin/v3/metrics.proto
package envoy_admin_v3
import (
fmt "fmt"
_ "github.com/cncf/udpa/go/udpa/annotations"
proto "github.com/gogo/protobuf/proto"
io "io"
math "math"
math_bits "math/bits"
)
// Reference imports to suppress errors if they ar... |
var (
ErrInvalidLengthMetrics = fmt.Errorf("proto: negative length found during unmarshaling")
ErrIntOverflowMetrics = fmt.Errorf("proto: integer overflow")
ErrUnexpectedEndOfGroupMetrics = fmt.Errorf("proto: unexpected end of group")
)
| {
l := len(dAtA)
iNdEx := 0
depth := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowMetrics
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) << shift
if b < 0x80 ... | identifier_body |
OceanFront_ViewshedNEW2.py | ##-------------------------------------------------------------------------------
#Name: OceanFront_Viewshed.py
#Purpose: Calculates viewshed, in degrees, for all points within a point file
#Author: Rachel Albritton
# Last Updated: October 19, 2013
#Inputs: This script takes NINE inputs. E... |
if not os.path.exists(Final_Floor_Viewsheds) : os.makedirs(Final_Floor_Viewsheds)
if not os.path.exists(SummaryTables) : os.makedirs(SummaryTables)
if not os.path.exists(ElevAvgTables): os.makedirs(ElevAvgTables)
if not os.path.exists(ArcLengths): os.makedirs(ArcLengths)
def outName(input,post="_Output"):
"""Retu... | os.makedirs(IntermediateFiles) | conditional_block |
OceanFront_ViewshedNEW2.py | ##-------------------------------------------------------------------------------
#Name: OceanFront_Viewshed.py
#Purpose: Calculates viewshed, in degrees, for all points within a point file
#Author: Rachel Albritton
# Last Updated: October 19, 2013
#Inputs: This script takes NINE inputs. E... |
shutil.rmtree(SummaryTables)
print SummaryTables, "folder successfully deleted from", outputWorkspace,"\n"
arcpy.AddMessage(os.path.basename(SummaryTables) + " folder successfully deleted from "+ outputWorkspace+"\n")
except:
print "\nERROR: Could not delete intermediate files from",outputWorkspace... | ##
#Delete individual summary tables
arcpy.SetProgressorLabel("Deleting Summary Tables... ")
try: | random_line_split |
OceanFront_ViewshedNEW2.py | ##-------------------------------------------------------------------------------
#Name: OceanFront_Viewshed.py
#Purpose: Calculates viewshed, in degrees, for all points within a point file
#Author: Rachel Albritton
# Last Updated: October 19, 2013
#Inputs: This script takes NINE inputs. E... | (input,post="_Output"):
"""Returns output name."""
outName=os.path.basename(input).split(".")[0]+post
return outName
def DegViewshed (FLOOR, HEIGHT):
"""Calculates a parcels viewshed, in degrees"""
#Select Record
arcpy.SelectLayerByAttribute_management(PointsFL,"NEW_SELECTION",SQL)
#S... | outName | identifier_name |
OceanFront_ViewshedNEW2.py | ##-------------------------------------------------------------------------------
#Name: OceanFront_Viewshed.py
#Purpose: Calculates viewshed, in degrees, for all points within a point file
#Author: Rachel Albritton
# Last Updated: October 19, 2013
#Inputs: This script takes NINE inputs. E... |
def DegViewshed (FLOOR, HEIGHT):
"""Calculates a parcels viewshed, in degrees"""
#Select Record
arcpy.SelectLayerByAttribute_management(PointsFL,"NEW_SELECTION",SQL)
#Set Observer Height (OffSETA)
arcpy.CalculateField_management(PointsFL,"OFFSETA",HEIGHT,"PYTHON_9.3")
#perform views... | """Returns output name."""
outName=os.path.basename(input).split(".")[0]+post
return outName | identifier_body |
container.rs | // Copyright 2021-2022 Sony Group Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
use crate::cgroup::{freeze, remove_cgroup_dir};
use crate::status::{self, get_current_container_state, Status};
use anyhow::{anyhow, Result};
use cgroups;
use cgroups::freezer::FreezerState;
use cgroups::hierarchies::is_cgroup2_... | use rustjail::container::EXEC_FIFO_FILENAME;
use std::path::PathBuf;
#[test]
fn test_get_config_path() {
let test_data = PathBuf::from(TEST_BUNDLE_PATH).join(CONFIG_FILE_NAME);
assert_eq!(get_config_path(TEST_BUNDLE_PATH), test_data);
}
#[test]
fn test_get_fifo_path() {
... |
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::test_utils::*; | random_line_split |
container.rs | // Copyright 2021-2022 Sony Group Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
use crate::cgroup::{freeze, remove_cgroup_dir};
use crate::status::{self, get_current_container_state, Status};
use anyhow::{anyhow, Result};
use cgroups;
use cgroups::freezer::FreezerState;
use cgroups::hierarchies::is_cgroup2_... | (&self) -> Result<()> {
if self.state != ContainerState::Running && self.state != ContainerState::Created {
return Err(anyhow!(
"failed to pause container: current status is: {:?}",
self.state
));
}
freeze(&self.cgroup, FreezerState::Frozen... | pause | identifier_name |
container.rs | // Copyright 2021-2022 Sony Group Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
use crate::cgroup::{freeze, remove_cgroup_dir};
use crate::status::{self, get_current_container_state, Status};
use anyhow::{anyhow, Result};
use cgroups;
use cgroups::freezer::FreezerState;
use cgroups::hierarchies::is_cgroup2_... |
freeze(&self.cgroup, FreezerState::Thawed)?;
Ok(())
}
pub fn destroy(&self) -> Result<()> {
remove_cgroup_dir(&self.cgroup)?;
self.status.remove_dir()
}
}
/// Used to run a process. If init is set, it will create a container and run the process in it.
/// If init is not se... | {
return Err(anyhow!(
"failed to resume container: current status is: {:?}",
self.state
));
} | conditional_block |
InceptionResNet_Image_Captioning.py |
import tensorflow as tf
import h5py
# You'll generate plots of attention in order to see which parts of an image
# our model focuses on during captioning
import matplotlib.pyplot as plt
# Scikit-learn includes many helpful utilities
from sklearn.model_selection import train_test_split
from sklearn.utils imp... |
class RNN_Decoder(tf.keras.Model):
# def __init__(self, embedding_dim, units, vocab_size, embedding_matrix):
def __init__(self, embedding_dim, units, vocab_size):
super(RNN_Decoder, self).__init__()
self.units = units
# self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim,embe... | x = self.fc(x)
x = tf.nn.relu(x)
return x | identifier_body |
InceptionResNet_Image_Captioning.py |
import tensorflow as tf
import h5py
# You'll generate plots of attention in order to see which parts of an image
# our model focuses on during captioning
import matplotlib.pyplot as plt
# Scikit-learn includes many helpful utilities
from sklearn.model_selection import train_test_split
from sklearn.utils imp... |
test_image_paths = []
for a in range(40504):
loc = testim_dir + 'im' + str(a) + ".png"
# loc = 'C:\\Users\\BARAN/Desktop/Dersler/EEE/EEE443/phtyon/finIm/im' + str(a) + ".png"
if (os.path.exists(loc)):
test_image_paths.append(loc)
# tot=0
# for a in range(40504):
# ... | loc = trainim_dir + 'im' + str(a) + ".png"
if (os.path.exists(loc)):
train_image_paths2.append(loc) | conditional_block |
InceptionResNet_Image_Captioning.py |
import tensorflow as tf
import h5py
# You'll generate plots of attention in order to see which parts of an image
# our model focuses on during captioning
import matplotlib.pyplot as plt
# Scikit-learn includes many helpful utilities
from sklearn.model_selection import train_test_split
from sklearn.utils imp... | (img_tensor, target):
loss = 0
# initializing the hidden state for each batch
# because the captions are not related from image to image
hidden = decoder.reset_state(batch_size=target.shape[0])
dec_input = tf.expand_dims([np.where(words == 'x_START_')[0][0]] * target.shape[0], 1)
with tf.Gradien... | train_step | identifier_name |
InceptionResNet_Image_Captioning.py | import tensorflow as tf
import h5py
# You'll generate plots of attention in order to see which parts of an image
# our model focuses on during captioning
import matplotlib.pyplot as plt
# Scikit-learn includes many helpful utilities
from sklearn.model_selection import train_test_split
from sklearn.utils impor... | print(i)
batch_features2 = image_features_extract_model2(img)
batch_features2 = tf.reshape(batch_features2,
(batch_features2.shape[0], -1, batch_features2.shape[3]))
for bf, p in zip(batch_features2, path):
path_of_feature = p.numpy().decode("utf-8")
n... | random_line_split | |
utils.go | // Copyright 2017, TCN Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the... | () string { return t.tm.GetProtoTypeName() }
type HasLabelAndType interface {
GetLabel() descriptor.FieldDescriptorProto_Label
GetType() descriptor.FieldDescriptorProto_Type
GetTypeName() string
}
// usualy typ is a *descriptor.FieldDescriptorProto, but it also could be a *TmAsField
fun... | GetTypeName | identifier_name |
utils.go | // Copyright 2017, TCN Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the... |
// TmAsField (TypeMappingAsField) Implements GetLabel and GetType, returning results from their GetProto equivalents
type TmAsField struct {
tm *persist.TypeMapping_TypeDescriptor
}
func (t TmAsField) GetLabel() descriptor.FieldDescriptorProto_Label { return t.tm.GetProtoLabel() }
func (t TmAsField) GetType() descr... | {
return f.GetGoTypeName(protoName)
} | identifier_body |
utils.go | // Copyright 2017, TCN Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met: | // * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materia... | random_line_split | |
utils.go | // Copyright 2017, TCN Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the... | else {
return "[]byte", nil
}
case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
if typ.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED {
return "[]float64", nil
} else {
return "float64", nil
}
case descriptor.FieldDescriptorProto_TYPE_FIXED32:
if typ.GetLabel() == descriptor.FieldDes... | {
return "[][]byte", nil
} | conditional_block |
feature_tracking.py | from enum import Enum
import cv2
import numpy as np
from scipy.stats.stats import pearsonr
def get_bounds(x, y, descriptor_offset, search_offset):
# For descriptor blocks, search_offset should be 1
# This defines bounds of sliding window
top = y - int(descriptor_offset * search_offset) - 1
bottom = y ... | (frame, points, color, radius):
for (x, y) in points:
draw_point(frame, x, y, color, radius)
current_frame_gui = None
clicked_points = []
display_keypoints = []
class Modes:
MOVIE = 1
IMAGE = 2
OTHER = 3
# POINTS SHOULD BE ADDED IN THE FOLLOWING ORDER:
#
# TOP LEFT, TOP RIGHT, BOTTOM LEFT,... | draw_points | identifier_name |
feature_tracking.py | from enum import Enum
import cv2
import numpy as np
from scipy.stats.stats import pearsonr
def get_bounds(x, y, descriptor_offset, search_offset):
# For descriptor blocks, search_offset should be 1
# This defines bounds of sliding window
top = y - int(descriptor_offset * search_offset) - 1
bottom = y ... |
def compute_harris(window):
gray_frame = cv2.cvtColor(window, cv2.COLOR_BGR2GRAY)
# result is dilated for marking the corners, not important
harris_frame = cv2.cornerHarris(gray_frame, 5, 3, 0.04)
harris_frame = cv2.dilate(harris_frame, None)
return harris_frame
def compute_orb(window):
det... | global curr_points, display_keypoints
curr_points = []
display_keypoints = []
for idx, (x_prev, y_prev) in enumerate(prev_frame_points):
# Create block of image intensities
# using neighboring pixels around each
# previously identified corner point
#20 works for bed scene
... | identifier_body |
feature_tracking.py | from enum import Enum
import cv2
import numpy as np
from scipy.stats.stats import pearsonr
def get_bounds(x, y, descriptor_offset, search_offset):
# For descriptor blocks, search_offset should be 1
# This defines bounds of sliding window
top = y - int(descriptor_offset * search_offset) - 1
bottom = y ... | cv2.putText(overlay, line, (c_x, c_y + i * dy), fontFace, fontScale, thickness)
# alpha blend overlay with frame
alpha = 0.8
frame = alpha * overlay + (1-alpha) * frame
return frame
def create_warp_comosite(composite_image,curr_frame_points_offset,current_frame):
# Create point corresponde... | c_y += text_vertical_offset
for i, line in enumerate(text.split('\n')): | random_line_split |
feature_tracking.py | from enum import Enum
import cv2
import numpy as np
from scipy.stats.stats import pearsonr
def get_bounds(x, y, descriptor_offset, search_offset):
# For descriptor blocks, search_offset should be 1
# This defines bounds of sliding window
top = y - int(descriptor_offset * search_offset) - 1
bottom = y ... |
####### MANUALLY SELECT POINTS
# Set mouse clip
cv2.namedWindow("Create Features To Track")
cv2.setMouseCallback("Create Features To Track", click)
# Get a video frame and select 4 points
# From here on out all frames will be tracked
ret, current_frame = track_cap.read()
if not ret:
... | composite_cap = cv2.VideoCapture("inputs/composite_videos/space.mp4") | conditional_block |
upload.py | """
Functions for connecting to the One Codex server; these should be rolled out
into the onecodex python library at some point for use across CLI and GUI clients
"""
from __future__ import print_function, division
from collections import OrderedDict
from math import floor
from multiprocessing import Value
import os
i... | if file_uuid:
uploading_uuids.append(file_uuid)
except Exception as e:
# handle inside the thread to prevent the exception message from leaking out
wrapped_args[-1].value = '{}'.format(e)
raise System... | random_line_split | |
upload.py | """
Functions for connecting to the One Codex server; these should be rolled out
into the onecodex python library at some point for use across CLI and GUI clients
"""
from __future__ import print_function, division
from collections import OrderedDict
from math import floor
from multiprocessing import Value
import os
i... |
except Exception as e:
# handle inside the thread to prevent the exception message from leaking out
wrapped_args[-1].value = '{}'.format(e)
raise SystemExit
semaphore.release()
# the thread error message must be th... | uploading_uuids.append(file_uuid) | conditional_block |
upload.py | """
Functions for connecting to the One Codex server; these should be rolled out
into the onecodex python library at some point for use across CLI and GUI clients
"""
from __future__ import print_function, division
from collections import OrderedDict
from math import floor
from multiprocessing import Value
import os
i... |
def upload_file(file_obj, filename, session, samples_resource, log_to, metadata, tags):
"""
Uploads a file to the One Codex server directly to the users S3 bucket by self-signing
"""
upload_args = {
'filename': filename,
'size': 1, # because we don't have the actually uploaded size y... | """
Uploads a file to the One Codex server via an intermediate S3 bucket (and handles files >5Gb)
"""
import boto3
from boto3.s3.transfer import TransferConfig
from boto3.exceptions import S3UploadFailedError
# first check with the one codex server to get upload parameters
try:
uplo... | identifier_body |
upload.py | """
Functions for connecting to the One Codex server; these should be rolled out
into the onecodex python library at some point for use across CLI and GUI clients
"""
from __future__ import print_function, division
from collections import OrderedDict
from math import floor
from multiprocessing import Value
import os
i... | (filename, logger=None, validate=True):
"""
A little helper to wrap a sequencing file (or join and wrap R1/R2 pairs)
and return a merged file_object
"""
if isinstance(filename, tuple):
if not validate:
raise UploadException('Validation is required in order to auto-interleave file... | _wrap_files | identifier_name |
event_queue.rs | use {Implementable, Proxy};
use std::any::Any;
use std::io::{Error as IoError, Result as IoResult};
use std::io::Write;
use std::ops::{Deref, DerefMut};
use std::os::raw::{c_int, c_void};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicPtr};
pub use token_store::{Store as State, StoreProxy as StateProxy, ... | Some(evtq) => ffi_dispatch!(
WAYLAND_CLIENT_HANDLE,
wl_display_prepare_read_queue,
self.display,
evtq
),
None => ffi_dispatch!(WAYLAND_CLIENT_HANDLE, wl_display_prepare_read, self.display),
... | match self.handle.wlevq { | random_line_split |
event_queue.rs | use {Implementable, Proxy};
use std::any::Any;
use std::io::{Error as IoError, Result as IoResult};
use std::io::Write;
use std::ops::{Deref, DerefMut};
use std::os::raw::{c_int, c_void};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicPtr};
pub use token_store::{Store as State, StoreProxy as StateProxy, ... |
}
/// An event queue managing wayland events
///
/// Each wayland object can receive events from the server. To handle these events
/// you must associate to these objects an implementation: a struct defined in their
/// respective module, in which you provide a set of functions that will handle each event.
///
/// Y... | {
&mut self.state
} | identifier_body |
event_queue.rs | use {Implementable, Proxy};
use std::any::Any;
use std::io::{Error as IoError, Result as IoResult};
use std::io::Write;
use std::ops::{Deref, DerefMut};
use std::os::raw::{c_int, c_void};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicPtr};
pub use token_store::{Store as State, StoreProxy as StateProxy, ... | (&mut self) -> &mut State {
&mut self.state
}
}
/// An event queue managing wayland events
///
/// Each wayland object can receive events from the server. To handle these events
/// you must associate to these objects an implementation: a struct defined in their
/// respective module, in which you provide ... | state | identifier_name |
horovod_patches.py | # Copyright 2018 BLEMUNDSBURY AI LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
trainer._build_train_ops = _build_train_ops
trainer._train = _train
trainer._train_async = _train_async
| """ Train while encoding batches on a seperate thread and storing them in a tensorflow Queue, can
be much faster then using the feed_dict approach """
train = data.get_train()
eval_datasets = data.get_eval()
loader = data.get_resource_loader()
print("Training on %d batches" % len(train))
prin... | identifier_body |
horovod_patches.py | # Copyright 2018 BLEMUNDSBURY AI LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | tf.get_default_graph().finalize()
if dry_run:
return
on_step = sess.run(global_step)
if save_start:
# summary_writer.add_graph(sess.graph, global_step=on_step)
if hvd.rank() == 0:
trainer.save_train_start(out.dir, data, sess.run(global_step), evaluators, train_para... | print("Initializing parameters...")
sess.run(tf.global_variables_initializer())
sess.run(bcast)
# Make sure no bugs occur that add to the graph in the train loop, that can cause (eventuall) OOMs | random_line_split |
horovod_patches.py | # Copyright 2018 BLEMUNDSBURY AI LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... | (train_params):
""" Bulid ops we should run during training, including learning, EMA, and summary ops"""
global_step = tf.get_variable('global_step', shape=[], dtype='int32',
initializer=tf.constant_initializer(0), trainable=False)
#global_step = tf.train.get_or_create_glob... | _build_train_ops | identifier_name |
horovod_patches.py | # Copyright 2018 BLEMUNDSBURY AI LIMITED
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
print("Evaluation took: %.3f seconds" % (time.perf_counter() - t0))
finally:
sess.run(train_close) # terminates the enqueue thread with an exception
train_enqueue_thread.join()
saver.save(sess, relpath(join(out.save_dir, "checkpoint-" + str(on_step))), global_step=gl... | print("Save weights with current best weights (%s vs %.5f)" % (
"None" if cur_best is None else ("%.5f" % cur_best), val))
best_weight_saver.save(sess, join(out.best_weight_dir, "best"), global_step=global_step)
... | conditional_block |
main.rs | #![feature(core)]
extern crate sdl2;
use std::rc::Rc;
use std::hash::{Hash, Hasher, Writer};
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::ops::Add;
use std::num::ToPrimitive;
use self::sdl2::render::RenderDrawer;
use self::sdl2::rect::{Rect, Point};
use self::sdl2::pi... |
}
fn test_gathering_resources() {
let mut player = Player{ id: PlayerId(1), resources: Resources::new() };
let mut universe = Starmap::generate_universe();
player.gather_resources(&universe);
assert!(player.resources == Resources::new());
assert!(universe.set_homeworlds(&[PlayerId(1), PlayerId(2... | {
let (x1, y1) = self.first.borrow().center();
let (x2, y2) = self.second.borrow().center();
drawer.draw_line(
Point{x: x1, y: y1},
Point{x: x2, y: y2});
} | identifier_body |
main.rs | #![feature(core)]
extern crate sdl2;
use std::rc::Rc;
use std::hash::{Hash, Hasher, Writer};
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::ops::Add;
use std::num::ToPrimitive;
use self::sdl2::render::RenderDrawer;
use self::sdl2::rect::{Rect, Point};
use self::sdl2::pi... | }
self.ships.get_mut(&ship.class).unwrap().push(ship);
}
fn merge(&mut self, fleet: Box<Fleet>) {
for (ship_class, ships) in fleet.ships.into_iter() {
for ship in ships.into_iter() {
self.add(ship);
}
}
}
fn size(&self) -> u32 {
... |
fn add(&mut self, ship: Ship) {
match self.ships.get(&ship.class) {
None => { self.ships.insert(ship.class, Vec::new()); },
Some(_) => () | random_line_split |
main.rs | #![feature(core)]
extern crate sdl2;
use std::rc::Rc;
use std::hash::{Hash, Hasher, Writer};
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::ops::Add;
use std::num::ToPrimitive;
use self::sdl2::render::RenderDrawer;
use self::sdl2::rect::{Rect, Point};
use self::sdl2::pi... | (self, other:Resources) -> Resources {
Resources {
food: self.food + other.food,
technology: self.technology + other.technology,
gold: self.gold + other.gold
}
}
}
impl Resources {
fn new() -> Resources {
Resources{food: 0, technology: 0, ... | add | identifier_name |
class_loader_context.go | // Copyright 2020 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | droid.Paths) {
var paths android.Paths
var clcsHost, clcsTarget []string
for _, clc := range clcs {
subClcHost, subClcTarget, subPaths := computeClassLoaderContextRec(clc.Subcontexts)
if subPaths != nil {
subClcHost = "{" + subClcHost + "}"
subClcTarget = "{" + subClcTarget + "}"
}
clcsHost = append(... | Context) (string, string, an | identifier_name |
class_loader_context.go | // Copyright 2020 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | n for Make.
func toJsonClassLoaderContext(clcMap ClassLoaderContextMap) jsonClassLoaderContextMap {
jClcMap := make(jsonClassLoaderContextMap)
for sdkVer, clcs := range clcMap {
sdkVerStr := fmt.Sprintf("%d", sdkVer)
jClcMap[sdkVerStr] = toJsonClassLoaderContextRec(clcs)
}
return jClcMap
}
// Recursive helper ... | lcs))
for _, clc := range jClcs {
clcs = append(clcs, &ClassLoaderContext{
Name: clc.Name,
Host: constructPath(ctx, clc.Host),
Device: clc.Device,
Subcontexts: fromJsonClassLoaderContextRec(ctx, clc.Subcontexts),
})
}
return clcs
}
// Convert Soong CLC map to JSON representatio | identifier_body |
class_loader_context.go | // Copyright 2020 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | AndroidHidlBase,
}
var OptionalCompatUsesLibs = append(android.CopyOf(OptionalCompatUsesLibs28), OptionalCompatUsesLibs30...)
var CompatUsesLibs = android.CopyOf(CompatUsesLibs29)
const UnknownInstallLibraryPath = "error"
// AnySdkVersion means that the class loader context is needed regardless of the targetSdkVersi... | AndroidHidlManager, | random_line_split |
class_loader_context.go | // Copyright 2020 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | paths are valid (including recursive subcontexts),
// otherwise return false. A build path is valid if it's not nil. An install path is valid if it's
// not equal to a special "error" value.
func validateClassLoaderContext(clcMap ClassLoaderContextMap) (bool, error) {
for sdkVer, clcs := range clcMap {
if valid, err... |
fixedClcs := []*ClassLoaderContext{}
for _, clc := range clcs {
if android.InList(clc.Name, usesLibs) {
// skip compatibility libraries that are already included in unconditional context
} else if clc.Name == AndroidTestMock && !android.InList("android.test.runner", usesLibs) {
// android.test.mock i... | conditional_block |
train_DQN_vs_overlap_rnn_no_perception_new.py | import cv2
import matplotlib.pyplot as plt
import numpy as np
import numpy.linalg as LA
import math
from math import sin, cos, pi, sqrt, atan2
import glob
import sys
import os, inspect, sys
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname... | reward, done, collision_done = decide_reward_and_done(previous_pose, current_pose, goal_pose, start_pose)
print('done = {}, collision_done = {}'.format(done, collision_done))
if i_step == seq_len-1:
print('used up all the steps ...')
done = 1
## execute one more action as the episode length is... | ax.imshow(ft_new_overlapArea.reshape(16, 16))
plt.show()
'''
## collision done only stops continuing the sequence, but won't affect reward computing | random_line_split |
train_DQN_vs_overlap_rnn_no_perception_new.py | import cv2
import matplotlib.pyplot as plt
import numpy as np
import numpy.linalg as LA
import math
from math import sin, cos, pi, sqrt, atan2
import glob
import sys
import os, inspect, sys
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname... |
state = new_state
episode_reward += reward
print('---------------- end of a action ------------------ ')
if done and i_step >= time_step-1:
break
print('---------------- end of a sequence ------------------ ')
assert len(local_memory) >= time_step
agent.memory.push(local_memory, len(lo... | agent.update(len(agent.memory), 3) | conditional_block |
train_DQN_vs_overlap_rnn_no_perception_new.py | import cv2
import matplotlib.pyplot as plt
import numpy as np
import numpy.linalg as LA
import math
from math import sin, cos, pi, sqrt, atan2
import glob
import sys
import os, inspect, sys
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname... | (self):
for target_param, param in zip(self.critic.parameters(), self.actor.parameters()):
target_param.data.copy_(param.data)
self.critic.eval()
## for collecting (state, action, next_state) tuples
#def select_action(self, state, hidden_state, cell_state, EPS_START=0.9, EPS_END... | update_critic | identifier_name |
train_DQN_vs_overlap_rnn_no_perception_new.py | import cv2
import matplotlib.pyplot as plt
import numpy as np
import numpy.linalg as LA
import math
from math import sin, cos, pi, sqrt, atan2
import glob
import sys
import os, inspect, sys
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname... |
def close_to_goal(pose1, pose2, thresh=0.15):
L2_dist = math.sqrt((pose1[0] - pose2[0])**2 + (pose1[1] - pose2[1])**2)
thresh_L2_dist = thresh
theta_change = abs(pose1[2] - pose2[2])/math.pi * 180
return (L2_dist < thresh_L2_dist) and (theta_change <= 30)
def compute_distance_old(left_pose, right_pose, lamb=0.5)... | pos, orn = func_pose2posAndorn(current_pose, mapper_scene2z[scene_name])
env.robot.reset_new_pose(pos, orn)
obs, _, _, _ = env.step(4)
obs_rgb = obs['rgb_filled']
obs_depth = obs['depth']
#obs_normal = obs['normal']
return obs_rgb, obs_depth#, obs_normal | identifier_body |
firebaseMap.js | // ****************************************************************
// ****************************************************************
// ********************** Fritz Gruppe ****************************
// ********************* Suliman Farzat ***************************
// *****************************************... | unixtime) {
var timestamp = parseInt(data.Zeit);
var u = new Date(unixtime);
return ('0' + u.getUTCDate()).slice(-2) +
'.' + ('0' + u.getUTCMonth() + 11 ).slice(-2)+
'.' + u.getUTCFullYear() +
' ' + ('0' + u.getUTCHours()+13 ).slice(-2) +
':' + ('0' + u.getUTCMinutes()).slice(-2) +
'... | nixTime( | identifier_name |
firebaseMap.js | // ****************************************************************
// ****************************************************************
// ********************** Fritz Gruppe ****************************
// ********************* Suliman Farzat ***************************
// *****************************************... | // google.maps.event.addDomListener(window, 'load', initMap);
//add firebase
/*function initFirebase(heatmap) {
var startTime = new Date().getTime() - (60 * 10 * 1000);
}*/
/*function getTimestamp(addClick) {
// Reference to location for saving the last click time.
... |
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 49.1833848,
lng: 9.17934696
},
zoom: 18,
styles: [{
featureType: 'poi',
stylers: [{
visibility: 'off'
}] ... | identifier_body |
firebaseMap.js | // ****************************************************************
// ****************************************************************
// ********************** Fritz Gruppe ****************************
// ********************* Suliman Farzat ***************************
// *****************************************... | //fahrer 1
const fahrer1OnOff = document.getElementById('fahrer1OnOff');
var fahrer1 = document.querySelector('fahrer1');
var mafiF1 = document.querySelector('mafiF1');
var trailerF1 = document.querySelector('trailerF1');
var zeitF1 = document.querySelector('zeitF1');
//fahrer 2
const fahrer2OnOff = document.get... | const liList = document.getElementById('listLi');
| random_line_split |
value.rs | use crate::css::CallArgs;
use crate::error::Error;
use crate::ordermap::OrderMap;
use crate::output::{Format, Formatted};
use crate::sass::Function;
use crate::value::{Color, ListSeparator, Number, Numeric, Operator, Quotes};
use std::convert::TryFrom;
/// A css value.
#[derive(Clone, Debug, Eq, PartialOrd)]
pub enum ... | (Value::UnaryOp(a, av), Value::UnaryOp(b, bv)) => {
a == b && av == bv
}
(
Value::BinOp(aa, _, ao, _, ab),
Value::BinOp(ba, _, bo, _, bb),
) => ao == bo && aa == ba && ab == bb,
(Value::UnicodeRange(a), Value::Un... | random_line_split | |
value.rs | use crate::css::CallArgs;
use crate::error::Error;
use crate::ordermap::OrderMap;
use crate::output::{Format, Formatted};
use crate::sass::Function;
use crate::value::{Color, ListSeparator, Number, Numeric, Operator, Quotes};
use std::convert::TryFrom;
/// A css value.
#[derive(Clone, Debug, Eq, PartialOrd)]
pub enum ... | (&self, other: &Value) -> bool {
match (&self, other) {
(Value::Bang(a), Value::Bang(b)) => a == b,
(Value::Numeric(a, _), Value::Numeric(b, _)) => a == b,
(Value::Literal(a, aq), Value::Literal(b, bq)) => {
if aq == bq {
a == b
... | eq | identifier_name |
main.rs | use lazy_static;
use permutator::Combination;
use serde::Deserialize;
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::error::Error;
fn mushes() -> Result<Vec<Mush>, Box<Error>> {
let f = std::fs::File::open("assets/agaricus-lepiota.data")?;
let mut rdr = csv::ReaderBuilder::new().has_headers(fals... | () {
let q = Question {
facet: 0,
vals: ['a', 'b', 'c'].iter().cloned().collect(),
};
let mushs = [
Mush {
poison: 'p',
attrs: ['a'; 22],
},
Mush {
poison: 'p',
attrs: ['b'; 22],
},
Mush {
poi... | test_answer | identifier_name |
main.rs | use lazy_static;
use permutator::Combination;
use serde::Deserialize;
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::error::Error;
fn mushes() -> Result<Vec<Mush>, Box<Error>> {
let f = std::fs::File::open("assets/agaricus-lepiota.data")?;
let mut rdr = csv::ReaderBuilder::new().has_headers(fals... | ("gill-size" ,"broad=b,narrow=n"),
("gill-color" ,"black=k,brown=n,buff=b,chocolate=h,gray=g,green=r,orange=o,pink=p,purple=u,red=e,white=w,yellow=y"),
("stalk-shape" ,"enlarging=e,tapering=t"),... | ("cap-color" ,"brown=n,buff=b,cinnamon=c,gray=g,green=r,pink=p,purple=u,red=e,white=w,yellow=y"),
("bruises?" ,"bruises=t,no=f"),
("odor" ,"almond=a,anise=l,creosote=c,fishy=y,foul=f,mu... | random_line_split |
main.rs | use lazy_static;
use permutator::Combination;
use serde::Deserialize;
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::error::Error;
fn mushes() -> Result<Vec<Mush>, Box<Error>> {
let f = std::fs::File::open("assets/agaricus-lepiota.data")?;
let mut rdr = csv::ReaderBuilder::new().has_headers(fals... | else { None })
.cloned()
.collect::<Vec<_>>()
.join(", ");
write!(
f,
"Examine '{}'. Is it {}{}?",
facet_name,
if self.vals.len() > 1 { "one of " } else { "" },
choices
)
}
}
#[test]
fn test_question_f... | { Some(v) } | conditional_block |
main.rs | use lazy_static;
use permutator::Combination;
use serde::Deserialize;
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::error::Error;
fn mushes() -> Result<Vec<Mush>, Box<Error>> {
let f = std::fs::File::open("assets/agaricus-lepiota.data")?;
let mut rdr = csv::ReaderBuilder::new().has_headers(fals... |
}
#[test]
fn test_question_fmt() {
use std::iter::FromIterator;
let q = Question {
facet: 0,
vals: BTreeSet::from_iter(['b', 'c', 'x'].iter().cloned()),
};
format!("{}", q);
}
lazy_static::lazy_static! {
static ref FACETS: Vec<(&'static str,HashMap<char,&'static str>)> = {
... | {
let (facet_name, facet_map) = &FACETS[self.facet];
let choices = facet_map
.iter()
.filter_map(|(k, v)| if self.vals.contains(k) { Some(v) } else { None })
.cloned()
.collect::<Vec<_>>()
.join(", ");
write!(
f,
... | identifier_body |
mod.rs | // Copyright 2015-2018 Aerospike, Inc.
//
// Portions may be licensed to Aerospike, Inc. under one or more contributor
// license agreements.
//
// 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 ... |
fn remove_alias(&self, host: &Host) {
let mut aliases = self.aliases.write();
aliases.remove(host);
}
fn add_aliases(&self, node: Arc<Node>) {
let mut aliases = self.aliases.write();
for alias in node.aliases() {
aliases.insert(alias, node.clone());
}
... | {
let mut aliases = self.aliases.write();
node.add_alias(host.clone());
aliases.insert(host, node);
} | identifier_body |
mod.rs | // Copyright 2015-2018 Aerospike, Inc.
//
// Portions may be licensed to Aerospike, Inc. under one or more contributor
// license agreements.
//
// 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 ... |
} else {
// Node not responding. Remove it.
remove_list.push(tnode);
}
}
}
}
}
remove_list
}
fn add_nodes_and_aliases(&self, friend_list: &[A... | {
remove_list.push(tnode);
} | conditional_block |
mod.rs | // Copyright 2015-2018 Aerospike, Inc.
//
// Portions may be licensed to Aerospike, Inc. under one or more contributor
// license agreements.
//
// 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 ... |
fn remove_nodes(&self, nodes_to_remove: &[Arc<Node>]) {
if nodes_to_remove.is_empty() {
return;
}
let nodes = self.nodes();
let mut node_array: Vec<Arc<Node>> = vec![];
for node in &nodes {
if !nodes_to_remove.contains(node) {
node_a... | } | random_line_split |
mod.rs | // Copyright 2015-2018 Aerospike, Inc.
//
// Portions may be licensed to Aerospike, Inc. under one or more contributor
// license agreements.
//
// 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 ... | (&self) -> bool {
let seed_array = self.seeds.read();
info!("Seeding the cluster. Seeds count: {}", seed_array.len());
let mut list: Vec<Arc<Node>> = vec![];
for seed in &*seed_array {
let mut seed_node_validator = NodeValidator::new(self);
if let Err(err) = see... | seed_nodes | identifier_name |
session.rs | //! Handle a game.
use std::num::NonZeroU8;
use std::fmt;
use derive_getters::Getters;
use rand::{rngs, Rng};
use crate::game::{self, Tree, Board, Players, Player, Choice, Action, Consequence, Holding};
fn roll_d6s<T: Rng>(d6s: u8, random: &mut T) -> usize {
(0..d6s)
.fold(0, |sum, _| -> usize {
... | choices,
);
};
Ok(state)
}
/// A game in progress. The `traversals` indicate how many turns have passed. Maintains
/// all state of the game.
///
/// ## Invariants
/// 1. The `Tree` will always be valid.
/// 2. The first `State` in the `turns` is the starting position sans any inital trave... | traversal.as_slice(),
current_board, | random_line_split |
session.rs | //! Handle a game.
use std::num::NonZeroU8;
use std::fmt;
use derive_getters::Getters;
use rand::{rngs, Rng};
use crate::game::{self, Tree, Board, Players, Player, Choice, Action, Consequence, Holding};
fn roll_d6s<T: Rng>(d6s: u8, random: &mut T) -> usize {
(0..d6s)
.fold(0, |sum, _| -> usize {
... |
pub fn reset(self) -> Self {
let first = self.turns.first().unwrap().board.to_owned();
Session::new(
first.clone(),
game::start_tree_horizon_limited(first, 1, self.move_limit.get()),
self.move_limit,
)
}
pub fn current_turn(&self) ->... | {
// The start may contain pass move. Cycle to get at the first true turn.
// This code is a copy of what's happening in `advance` below. TODO: Refactor me.
let mut tree = Some(tree);
let first_turn = loop {
match state_from_board(
start.clone(), tree... | identifier_body |
session.rs | //! Handle a game.
use std::num::NonZeroU8;
use std::fmt;
use derive_getters::Getters;
use rand::{rngs, Rng};
use crate::game::{self, Tree, Board, Players, Player, Choice, Action, Consequence, Holding};
fn roll_d6s<T: Rng>(d6s: u8, random: &mut T) -> usize {
(0..d6s)
.fold(0, |sum, _| -> usize {
... | (
attacker_dice: u8, attacker_rolled: usize, defender_dice: u8, defender_rolled: usize
) -> Self {
LastAttack { attacker_dice, attacker_rolled, defender_dice, defender_rolled }
}
}
impl fmt::Display for LastAttack {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.atta... | new | identifier_name |
global.js | /**
* @description 全局公共js
* @author yiwenjun
* @since 2015-03-31
*/
var Global = function() {
var t = {
appName : 'dsweb',
ccpartyGroup : 'Z000101', //党组代码
ccpartyCommitte : 'Z000102', //党委代码
ccpartyGeneral : 'Z000103', //总支代码
ccpartyBranch : 'Z000104', //支部代码
... | ear = currentYear - num + 1; year < currentYear + num; year++) {
options += '<option value=' + year + '>' + year + '</option>';
}
}
} else {
if (order == 1) {
for (var year = currentYear + num - 1; year >= ... | }
} else {
for (var y | conditional_block |
global.js | /**
* @description 全局公共js
* @author yiwenjun
* @since 2015-03-31
*/
var Global = function() {
var t = {
appName : 'dsweb',
ccpartyGroup : 'Z000101', //党组代码
ccpartyCommitte : 'Z000102', //党委代码
ccpartyGeneral : 'Z000103', //总支代码
ccpartyBranch : 'Z000104', //支部代码
... | exp.setTime(exp.getTime() + options.expires * 24 * 60 * 60 * 1000);
} else {
exp = options.expires;
}
expires = ';expires=' + exp.toUTCString();
}
path = options.path ? '; pa... | if (typeof options.expires == 'number') {
exp = new Date();
| random_line_split |
monitor.go | package booking
import (
"encoding/hex"
"fmt"
"net"
"server/facility"
"server/messagesocket"
"time"
)
// Singleton to obtain the monitor object from any class
var globalMonitor *MonitoringManager
// Enum to differentiate what action has been made when the monitor message is sent
const (
CreateBooking string =... | (address net.Addr, fac facility.Facility) int {
exist := -1
// Iterate through monitoring list of clients to find the IP combination
for i,v := range mgmt.MonitorList {
// If IP/Port matches and the facility being tracked also matches, returns the index of this item
if v.Message.Addr.String() == address.String(... | CheckIPExistIndex | identifier_name |
monitor.go | package booking
import (
"encoding/hex"
"fmt"
"net"
"server/facility"
"server/messagesocket"
"time"
)
// Singleton to obtain the monitor object from any class
var globalMonitor *MonitoringManager
// Enum to differentiate what action has been made when the monitor message is sent
const (
CreateBooking string =... | Message messagesocket.Message
// The start time of the monitor session
Start time.Time
// The end time of the monitor session
End time.Time
// The total duration the monitor session remain active
Interval time.Duration
// The facility the monitoring session is monitoring
Facility facility.Facility
... | }
// Monitor is the implementaion of a monitoring session
type Monitor struct {
// Store the client StartMonitoringMessage to identiy the client that initiate the monitoring session | random_line_split |
monitor.go | package booking
import (
"encoding/hex"
"fmt"
"net"
"server/facility"
"server/messagesocket"
"time"
)
// Singleton to obtain the monitor object from any class
var globalMonitor *MonitoringManager
// Enum to differentiate what action has been made when the monitor message is sent
const (
CreateBooking string =... | else {
marshalled = byteArr
}
// Broadcast the message to the clients
mgmt.BroadcastUsingMsgList(marshalled, messageList)
// Check if the unacknowledged messages handler is started
// If it is not started, start it up
if !mgmt.Start {
fmt.Println("Starting resend loop")
go mgmt.goStartCheckingResend()
}... | {
fmt.Printf("%s\n", err.Error())
return // Don't send availability on error
} | conditional_block |
monitor.go | package booking
import (
"encoding/hex"
"fmt"
"net"
"server/facility"
"server/messagesocket"
"time"
)
// Singleton to obtain the monitor object from any class
var globalMonitor *MonitoringManager
// Enum to differentiate what action has been made when the monitor message is sent
const (
CreateBooking string =... | {
payload := make([]byte, 0)
// We place the action string in front first (length of string 1 byte, string x byte)
fmt.Println(len(actionString))
// We obtain the length of the action string
asLen, _ := hex.DecodeString(fmt.Sprintf("%02x", len(actionString)))
// We append the action string length to the beginnin... | identifier_body | |
scene.py | # Import the Panda3D Python modules
from direct.task.Task import Task
from direct.gui.OnscreenImage import OnscreenImage
from direct.gui.DirectGui import *
from direct.actor.Actor import Actor
# Import the Panda3D C++ modules
from panda3d.core import *
# from panda3d.core import TransparencyAttrib, Vec3, Fog, LPoint3,... |
else:
# Parent the model to either the render tree or the parent
model.reparentTo(self.renderTree if parent is None else self.models.get(parent))
else:
# If the model is being instanced to an existing model
model = self.addInstance(pos, scale, instanceTo)
# Add the model to the scenes model dicti... | colliderNodePath.node().addSolid(collider) | conditional_block |
scene.py | # Import the Panda3D Python modules
from direct.task.Task import Task
from direct.gui.OnscreenImage import OnscreenImage
from direct.gui.DirectGui import *
from direct.actor.Actor import Actor
# Import the Panda3D C++ modules
from panda3d.core import *
# from panda3d.core import TransparencyAttrib, Vec3, Fog, LPoint3,... | model.reparentTo(self.renderTree if parent is None else self.models.get(parent))
else:
# If the model is being instanced to an existing model
model = self.addInstance(pos, scale, instanceTo)
# Add the model to the scenes model dictionary
self.models[key if key is not None else len(self.models)] = model... | if collider:
colliderNodePath.node().addSolid(collider)
else:
# Parent the model to either the render tree or the parent | random_line_split |
scene.py | # Import the Panda3D Python modules
from direct.task.Task import Task
from direct.gui.OnscreenImage import OnscreenImage
from direct.gui.DirectGui import *
from direct.actor.Actor import Actor
# Import the Panda3D C++ modules
from panda3d.core import *
# from panda3d.core import TransparencyAttrib, Vec3, Fog, LPoint3,... | (self, pos, scale, instanceTo):
'''
Adds an Instance of the chosen model to the scene.
'''
# Create a new empty node and attach it to the render tree
model = self.renderTree.attachNewNode("model_placeholder")
# Set the position and scale of the model
model.setPos(*pos)
model.setScale(*scale)
# Insta... | addInstance | identifier_name |
scene.py | # Import the Panda3D Python modules
from direct.task.Task import Task
from direct.gui.OnscreenImage import OnscreenImage
from direct.gui.DirectGui import *
from direct.actor.Actor import Actor
# Import the Panda3D C++ modules
from panda3d.core import *
# from panda3d.core import TransparencyAttrib, Vec3, Fog, LPoint3,... |
def exitScene(self):
'''
An event hook method for running events as the scene is exited
'''
pass
class IntroClipScene(Scene):
'''
A subclass of the Scene class to handle the intro clip
and all of it's required tasks + events
'''
def __init__(self, app):
'''
Initialise and run any events BEFORE load... | '''
A event hook method for running events when the scene is first loaded
'''
pass | identifier_body |
villager_bot.py | import asyncio
import random
from collections import defaultdict
from typing import Any, Optional
import aiohttp
import arrow
import captcha.image
import discord
import psutil
from captcha.image import ImageCaptcha
from discord.ext import commands
from common.coms.packet import PACKET_DATA_TYPES
from common.coms.pack... |
await self.karen.command_execution(
ctx.author.id, getattr(ctx.guild, "id", None), ctx.command.qualified_name, False
)
async def after_command_invoked(self, ctx: CustomContext):
try:
if ctx.command.qualified_name in self.d.concurrency_limited:
await... | await self.karen.lb_command_ran(ctx.author.id) | conditional_block |
villager_bot.py | import asyncio
import random
from collections import defaultdict
from typing import Any, Optional
import aiohttp
import arrow
import captcha.image
import discord
import psutil
from captcha.image import ImageCaptcha
from discord.ext import commands
from common.coms.packet import PACKET_DATA_TYPES
from common.coms.pack... |
async def start(self):
self.font_files = await FontHandler(
font_urls=self.d.font_urls, output_directory="fonts"
).retrieve()
self.captcha_generator = captcha.image.ImageCaptcha(fonts=self.font_files)
self.karen = KarenClient(self.k.karen, self.get_packet_handlers(), s... | return getattr(discord.Color, self.d.embed_color)() | identifier_body |
villager_bot.py | import asyncio
import random
from collections import defaultdict
from typing import Any, Optional
import aiohttp
import arrow
import captcha.image
import discord
import psutil
from captcha.image import ImageCaptcha
from discord.ext import commands
from common.coms.packet import PACKET_DATA_TYPES
from common.coms.pack... | ) -> None:
embed = discord.Embed(color=self.embed_color, description=message)
try:
await location.reply(embed=embed, mention_author=ping)
except discord.errors.HTTPException as e:
if (
e.code == 50035
): # invalid form body, happens somet... | raise
async def reply_embed(
self, location, message: str, ping: bool = False, *, ignore_exceptions: bool = False | random_line_split |
villager_bot.py | import asyncio
import random
from collections import defaultdict
from typing import Any, Optional
import aiohttp
import arrow
import captcha.image
import discord
import psutil
from captcha.image import ImageCaptcha
from discord.ext import commands
from common.coms.packet import PACKET_DATA_TYPES
from common.coms.pack... | (self):
return len(self.guilds)
@handle_packet(PacketType.UPDATE_SUPPORT_SERVER_ROLES)
async def packet_update_support_server_roles(self, user_id: int):
support_guild = self.get_guild(self.k.support_server_id)
if support_guild is not None:
member = support_guild.get_member(... | packet_fetch_guild_count | identifier_name |
panel-page-manager.js | /**
* di.shared.model.PanelPageManager
* Copyright 2012 Baidu Inc. All rights reserved.
*
* @file: [通用管理器] panel page关系页管理:
* 维护页面引用,页面打开先后顺序,当前页面等。适应不同的页面展现方式(如tab方式或窗口方式等)。
* @author: sushuang(sushuang)
*/
$namespace('di.shared.model');
/**
* [外部注入]
* {ecui.ui.Control} panelPageContainer 页面容器
... | /**
* 得到当前页面实例
*
* @public
* @return {PanelPage} panelPage
*/
PANEL_PAGE_MANAGER_CLASS.getCurrentPage = function() {
return this._oCurrPageWrap ? this._oCurrPageWrap.page : null;
};
/**
* 得到当前页面ID
*
* @public
* @return {string} pageId
*/
PANEL... | n {PanelPage} panelPage
*/
PANEL_PAGE_MANAGER_CLASS.getPage = function(pageId) {
return (this._oPanelPageSet.get(pageId) || {}).page;
};
| conditional_block |
panel-page-manager.js | /**
* di.shared.model.PanelPageManager
* Copyright 2012 Baidu Inc. All rights reserved.
*
* @file: [通用管理器] panel page关系页管理:
* 维护页面引用,页面打开先后顺序,当前页面等。适应不同的页面展现方式(如tab方式或窗口方式等)。
* @author: sushuang(sushuang)
*/
$namespace('di.shared.model');
/**
* [外部注入]
* {ecui.ui.Control} panelPageContainer 页面容器
... | }
// 选择激活
this.select(pageId, param);
return page;
};
/**
* 增加 panel pange
*
* @public
* @param {ecui.ui.PanelPage|Function} panelPage 要添加的panel page,
* 或者创建panel page的回调函数
* 如果为函数,则:
* @param {Object} options 参数
... | oncreate && oncreate(page); | random_line_split |
kvstore.go | package kvnode
import (
"encoding/binary"
"fmt"
"github.com/sniperHW/flyfish/conf"
"github.com/sniperHW/flyfish/dbmeta"
"github.com/sniperHW/flyfish/errcode"
"github.com/sniperHW/flyfish/net"
"github.com/sniperHW/flyfish/proto"
futil "github.com/sniperHW/flyfish/util"
"github.com/sniperHW/flyfish/util/str"
"... | util.BlockQueue, confChangeC chan *asynTaskConfChange) *kvstore {
s := &kvstore{
proposeC: proposeC,
confChangeC: confChangeC,
elements: map[string]*kv{},
readReqC: readReqC,
kvNode: kvNode,
storeMgr: storeMgr,
unCompressor: &net.ZipUnCompressor{},
}
s.lruHead.nnext = &s.lruTai... | qC * | identifier_name |
kvstore.go | package kvnode
import (
"encoding/binary"
"fmt"
"github.com/sniperHW/flyfish/conf"
"github.com/sniperHW/flyfish/dbmeta"
"github.com/sniperHW/flyfish/errcode"
"github.com/sniperHW/flyfish/net"
"github.com/sniperHW/flyfish/proto"
futil "github.com/sniperHW/flyfish/util"
"github.com/sniperHW/flyfish/util/str"
"... | re {
this.RLock()
defer this.RUnlock()
index := (futil.StringHash(uniKey) % this.mask) + 1
return this.stores[index]
}
func (this *storeMgr) addStore(index int, store *kvstore) bool {
if 0 == index || nil == store {
logger.Fatalln("0 == index || nil == store")
}
this.Lock()
defer this.Unlock()
_, ok := this... | = store.elements[uniKey]
if ok {
if !this.dbmeta.CheckMetaVersion(k.meta.Version()) {
newMeta := this.dbmeta.GetTableMeta(table)
if newMeta != nil {
atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&k.meta)), unsafe.Pointer(newMeta))
} else {
//log error
err = errcode.ERR_INVAILD_TA... | identifier_body |
kvstore.go | package kvnode
import (
"encoding/binary"
"fmt"
"github.com/sniperHW/flyfish/conf"
"github.com/sniperHW/flyfish/dbmeta"
"github.com/sniperHW/flyfish/errcode"
"github.com/sniperHW/flyfish/net"
"github.com/sniperHW/flyfish/proto"
futil "github.com/sniperHW/flyfish/util"
"github.com/sniperHW/flyfish/util/str"
"... |
func (this *kvstore) getRaftNode() *raftNode {
return this.rn
}
func (this *kvstore) removeKv(k *kv) {
processAgain := false
this.Lock()
k.Lock()
if !k.cmdQueue.empty() {
k.resetStatus()
processAgain = true
} else {
k.setStatus(cache_remove)
this.removeLRU(k)
delete(this.elements, k.uniKey)
}
k.... | return this.kvNode
} | random_line_split |
kvstore.go | package kvnode
import (
"encoding/binary"
"fmt"
"github.com/sniperHW/flyfish/conf"
"github.com/sniperHW/flyfish/dbmeta"
"github.com/sniperHW/flyfish/errcode"
"github.com/sniperHW/flyfish/net"
"github.com/sniperHW/flyfish/proto"
futil "github.com/sniperHW/flyfish/util"
"github.com/sniperHW/flyfish/util/str"
"... | {
table, key := splitUniKey(unikey)
meta := this.storeMgr.dbmeta.GetTableMeta(table)
if nil == meta {
return false
}
kv = newkv(this, meta, key, unikey, false)
this.elements[unikey] = kv
}
if version == 0 {
kv.setStatus(cache_missing)
kv.fields = nil
logger.... | es[1].(int64)
if !ok | conditional_block |
shortid.go | // Copyright (c) 2016-2017. Oleg Sklyar & teris.io. All rights reserved.
// See the LICENSE file in the project root for licensing information.
// Original algorithm:
// Copyright (c) 2015 Dylan Greene, contributors: https://github.com/dylang/shortid.
// MIT-license as found in the LICENSE file.
// Seed computation: ... |
// Epoch returns the value of epoch used as the beginning of millisecond counting (normally
// 2016-01-01 00:00:00 local time)
func (sid *Shortid) Epoch() time.Time {
return sid.epoch
}
// Worker returns the value of worker for this short Id generator.
func (sid *Shortid) Worker() uint {
return sid.worker
}
// Ne... | {
return sid.abc
} | identifier_body |
shortid.go | // Copyright (c) 2016-2017. Oleg Sklyar & teris.io. All rights reserved.
// See the LICENSE file in the project root for licensing information.
// Original algorithm:
// Copyright (c) 2015 Dylan Greene, contributors: https://github.com/dylang/shortid.
// MIT-license as found in the LICENSE file.
// Seed computation: ... | // uniqueness in case further data is added to the sequence. The value of digits [4,6] represents
// represents n in 2^n, which defines how much randomness flows into the algorithm: 4 -- every value
// can be represented by 4 symbols in the alphabet (permitting at most 16 values), 5 -- every value
// can be represented... |
// Encode encodes a given value into a slice of runes of length nsymbols. In case nsymbols==0, the
// length of the result is automatically computed from data. Even if fewer symbols is required to
// encode the data than nsymbols, all positions are used encoding 0 where required to guarantee | random_line_split |
shortid.go | // Copyright (c) 2016-2017. Oleg Sklyar & teris.io. All rights reserved.
// See the LICENSE file in the project root for licensing information.
// Original algorithm:
// Copyright (c) 2015 Dylan Greene, contributors: https://github.com/dylang/shortid.
// MIT-license as found in the LICENSE file.
// Seed computation: ... | (alphabet string, seed uint64) (Abc, error) {
runes := []rune(alphabet)
if len(runes) != len(DefaultABC) {
return Abc{}, fmt.Errorf("alphabet must contain %v unique characters", len(DefaultABC))
}
if nonUnique(runes) {
return Abc{}, errors.New("alphabet must contain unique characters only")
}
abc := Abc{alpha... | NewAbc | identifier_name |
shortid.go | // Copyright (c) 2016-2017. Oleg Sklyar & teris.io. All rights reserved.
// See the LICENSE file in the project root for licensing information.
// Original algorithm:
// Copyright (c) 2015 Dylan Greene, contributors: https://github.com/dylang/shortid.
// MIT-license as found in the LICENSE file.
// Seed computation: ... |
} else {
for i := range ints {
ints[i] = randm.Intn(0xff) & mask
}
}
return ints
}
// String returns a string representation of the Abc instance.
func (abc Abc) String() string {
return fmt.Sprintf("Abc{alphabet='%v')", abc.Alphabet())
}
// Alphabet returns the alphabet used as an immutable string.
func (... | {
ints[i] = int(b) & mask
} | conditional_block |
circuit.rs | use ff::{Field, PrimeField, PrimeFieldRepr, BitIterator};
use bellman::{Circuit, ConstraintSystem, SynthesisError};
use zcash_primitives::jubjub::{FixedGenerators, JubjubEngine, edwards, PrimeOrder, JubjubParams};
use zcash_primitives::constants;
use zcash_primitives::primitives::{PaymentAddress, ProofGenerationKey... |
let mut lhs: Vec<bool> = BitIterator::new(lhs.into_repr()).collect();
let mut rhs: Vec<bool> = BitIterator::new(rhs.into_repr()).collect();
lhs.reverse();
rhs.reverse();
cur = pedersen_hash::pedersen_hash::<Bls12, _>(
pedersen_hash::Personalization::MerkleTree(i),... | {
::std::mem::swap(&mut lhs, &mut rhs);
} | conditional_block |
circuit.rs | use ff::{Field, PrimeField, PrimeFieldRepr, BitIterator};
use bellman::{Circuit, ConstraintSystem, SynthesisError};
use zcash_primitives::jubjub::{FixedGenerators, JubjubEngine, edwards, PrimeOrder, JubjubParams};
use zcash_primitives::constants;
use zcash_primitives::primitives::{PaymentAddress, ProofGenerationKey... | <'a, E: JubjubEngine> { // TODO: name
// Jubjub curve parameters.
pub params: &'a E::Params,
// The secret key, an element of Jubjub scalar field.
pub sk: Option<E::Fs>,
// The VRF input, a point in Jubjub prime order subgroup.
pub vrf_input: Option<edwards::Point<E, PrimeOrder>>,
// The... | Ring | identifier_name |
circuit.rs | use ff::{Field, PrimeField, PrimeFieldRepr, BitIterator};
use bellman::{Circuit, ConstraintSystem, SynthesisError};
use zcash_primitives::jubjub::{FixedGenerators, JubjubEngine, edwards, PrimeOrder, JubjubParams};
use zcash_primitives::constants;
use zcash_primitives::primitives::{PaymentAddress, ProofGenerationKey... | use zcash_primitives::pedersen_hash;
use zcash_primitives::jubjub::{JubjubBls12, fs, edwards,};
use rand_core::{RngCore, SeedableRng,};
use rand_xorshift::XorShiftRng;
let params = &JubjubBls12::new();
let rng = &mut XorShiftRng::from_seed([
0x58, 0x62, 0xbe, 0x3d, 0x76, 0x3d, 0x31, 0x... |
#[test]
fn test_ring() {
use bellman::gadgets::test::TestConstraintSystem;
use pairing::bls12_381::{Bls12, Fr,}; | random_line_split |
blackjack.js | const { prefix } = require('../../config.json');
module.exports = {
name: "blackjack",
description: "play blackjack",
aliases: ['bj'],
cooldown: 0,
async execute(message) {
const DB = require('djs-economy');
const user = message.author;
const cash = await DB.GetCash... | function getValue (card) {
return { value: values[faces.indexOf(card.face)], card };
}
function addCards (type) {
return cards[type].sort((a, b) => getValue(b).value - getValue(a).value).reduce((p, c) => {
let newCard = getValue(c).value;
if (newCar... | {
switch (suit) {
case 'spades':
return '♠';
case 'hearts':
return '♥';
case 'diamonds':
return '♦';
case 'clubs':
return '♣';
}
}
| identifier_body |
blackjack.js | const { prefix } = require('../../config.json');
module.exports = {
name: "blackjack",
description: "play blackjack",
aliases: ['bj'],
cooldown: 0,
async | (message) {
const DB = require('djs-economy');
const user = message.author;
const cash = await DB.GetCash(message.author.id).cash;
const formatNumber = require('../../functions/regex');
const args = message.content.slice(prefix.length).trim().split(/ /g);
let be... | execute | identifier_name |
blackjack.js | const { prefix } = require('../../config.json');
module.exports = {
name: "blackjack",
description: "play blackjack",
aliases: ['bj'],
cooldown: 0,
async execute(message) {
const DB = require('djs-economy');
const user = message.author;
const cash = await DB.GetCash... |
function getRespectiveIcon (suit) {
switch (suit) {
case 'spades':
return '♠';
case 'hearts':
return '♥';
case 'diamonds':
return '♦';
case 'clubs':
return '♣';
... | { // redraw
cards = {
bot: [deal(), deal()],
user: [deal(), deal()]
};
} | conditional_block |
blackjack.js | const { prefix } = require('../../config.json');
module.exports = {
name: "blackjack",
description: "play blackjack",
aliases: ['bj'],
cooldown: 0,
async execute(message) {
const DB = require('djs-economy');
const user = message.author;
const cash = await DB.GetCash... | }
if (cash === 0) {
return message.reply('You dont have any cash to bet');
}
if (bet > cash) {
return message.reply(`You only have ${formatNumber(cash)}. You cant bet more than that`);
}
if (bet > 5000000) {
return message.rep... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.