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 |
|---|---|---|---|---|
client_enum_component_type.go |
ComponentsCharacterActivitiesKey = 204
ComponentsCharacterEquipmentKey = 205
ComponentsItemInstancesKey = 300
ComponentsItemObjectivesKey = 301
ComponentsItemPerksKey = 302
ComponentsItemRenderDataKey = 303
ComponentsItemStatsKey = 304
ComponentsItemSocketsKey... | (key int) (ComponentType, string, error) {
switch key {
case ComponentsNoneKey:
return "None", "", nil
case ComponentsProfilesKey:
description := `
Profiles is the most basic component, only relevant when calling GetProfile.
This returns basic information about the profile, which is almost nothing:
- a list of c... | ComponentTypesE | identifier_name |
client_enum_component_type.go |
ComponentsCharacterActivitiesKey = 204
ComponentsCharacterEquipmentKey = 205
ComponentsItemInstancesKey = 300
ComponentsItemObjectivesKey = 301
ComponentsItemPerksKey = 302
ComponentsItemRenderDataKey = 303
ComponentsItemStatsKey = 304
ComponentsItemSocketsKey... |
return out
}
func ComponentTypes(key int) ComponentType {
out, _, _ := ComponentTypesE(key)
return out
}
func ComponentTypesE(key int) (ComponentType, string, error) {
switch key {
case ComponentsNoneKey:
return "None", "", nil
case ComponentsProfilesKey:
description := `
Profiles is the most basic compone... | {
eout, _, _ := ComponentTypesE(key)
out = append(out, eout)
} | conditional_block |
client_enum_component_type.go |
ComponentsCharacterActivitiesKey = 204
ComponentsCharacterEquipmentKey = 205
ComponentsItemInstancesKey = 300
ComponentsItemObjectivesKey = 301
ComponentsItemPerksKey = 302
ComponentsItemRenderDataKey = 303
ComponentsItemStatsKey = 304
ComponentsItemSocketsKey... | Asking for this will get you the profile-level inventories, such as your Vault buckets
(yeah, the Vault is really inventory buckets located on your Profile)
`
return "ProfileInventories", description, nil
case ComponentsProfileCurrenciesKey:
description := `
This will get you a summary of items on your Profile tha... | {
switch key {
case ComponentsNoneKey:
return "None", "", nil
case ComponentsProfilesKey:
description := `
Profiles is the most basic component, only relevant when calling GetProfile.
This returns basic information about the profile, which is almost nothing:
- a list of characterIds,
- some information about the... | identifier_body |
mysql.rs | If set, connected to the database through a Unix socket.
pub fn socket(&self) -> &Option<String> {
&self.query_params.socket
}
/// The database port, defaults to `3306`.
pub fn port(&self) -> u16 {
self.url.port().unwrap_or(3306)
}
fn default_connection_limit() -> usize {
... |
}
impl TransactionCapable for Mysql {}
impl Queryable for Mysql {
fn query<'a>(&'a self, q: Query<'a>) -> DBIO<'a, ResultSet> {
let (sql, params) = visitor::Mysql::build(q);
DBIO::new(async move { self.query_raw(&sql, ¶ms).await })
}
fn execute<'a>(&'a self, q: Query<'a>) -> DBIO<'a,... | {
match self.socket_timeout {
Some(duration) => match timeout(duration, f).await {
Ok(Ok(result)) => Ok(result),
Ok(Err(err)) => Err(err.into()),
Err(to) => Err(to.into()),
},
None => match f.await {
Ok(result) =... | identifier_body |
mysql.rs | fn timeout<T, F, E>(&self, f: F) -> crate::Result<T>
where
F: Future<Output = std::result::Result<T, E>>,
E: Into<Error>,
{
match self.socket_timeout {
Some(duration) => match timeout(duration, f).await {
Ok(Ok(result)) => Ok(result),
Ok(Err(e... | test_null_constraint_violation | identifier_name | |
mysql.rs | use url::Url;
use crate::{
ast::{ParameterizedValue, Query},
connector::{metrics, queryable::*, ResultSet, DBIO},
error::{Error, ErrorKind},
visitor::{self, Visitor},
};
/// A connector interface for the MySQL database.
#[derive(Debug)]
pub struct Mysql {
pub(crate) pool: my::Pool,
pub(crate) ... | use percent_encoding::percent_decode;
use std::{borrow::Cow, future::Future, path::Path, time::Duration};
use tokio::time::timeout; | random_line_split | |
Bijlage_D.py | = context.scene.bond_distance
global draw_lattice
draw_lattice = context.scene.draw_lattice
global atom_name
atom_name = context.scene.atom_name
global print_data
print_data = context.scene.print_data
global draw_style
... | # Panel to display add-on in Blender environment
class Panel(bpy.types.Panel):
bl_idname = "CDTB_Panel"
bl_label = "CDTB_Panel"
bl_space_type = "VIEW_3D"
bl_region_type = "TOOLS"
bl_context = "objectmode"
bl_category = "CDTB"
def draw(self,context):
scn = context.scene
lay... | int("Unregistered class: %s " % cls.bl_label)
| identifier_body |
Bijlage_D.py | 100):
layout.label(text = str(i),icon_value =i)
'''
box = layout.box()
row = box.row()
splitrow = row.split(factor=0.075)
left_col = splitrow.column()
right_col = splitrow.column()
left_col.operator('error.scan_file',icon_value=108,text="")
ri... | okCurve(s | identifier_name | |
Bijlage_D.py | = context.scene.bond_distance
global draw_lattice
draw_lattice = context.scene.draw_lattice
global atom_name
atom_name = context.scene.atom_name
global print_data
print_data = context.scene.print_data
global draw_style
... | # draw lines
for i,j in zip([0,0,0,1,1,2,2,3,4,4 | r k in range(2):
bpy.ops.mesh.primitive_uv_sphere_add(size=lattice_size,location=toCarth(self.ftoc,[i,j,k]))
activeObject = bpy.context.active_object # Set active object to variable
cell_corners.append(activeObject)
mat = bpy.data.materials... | conditional_block |
Bijlage_D.py | _distance = context.scene.bond_distance
global draw_lattice
draw_lattice = context.scene.draw_lattice
global atom_name
atom_name = context.scene.atom_name
global print_data
print_data = context.scene.print_data
global draw_style
... | r[2, 1] = float(0)
r[2, 2] = float(volume / (a*b*sing))
return r
def drawCrystal(self):
if draw_lattice:
self.drawCell()
print("Lattice drawn after {:.3f} seconds".format((time.time()-self.start)))
self.drawAtoms()
print("Atoms drawn after {... | random_line_split | |
gopro.py | timestamp(time_stamp)) if time_stamp is not None else None
def to_timestamp(start_utc):
return start_utc.timestamp() if start_utc is not None else None
class GoProCacheEncoder(JSONEncoder):
# Override the default method
def default(self, obj):
if isinstance(obj, (date, datetime)):
re... | (self, sd_card_dir, work_dir):
cache_dir = work_dir + os.sep + 'gopro'
os.makedirs(cache_dir, exist_ok=True)
self.instr_data = []
# Build the list of clips
clips = []
print(f'Looking for GOPRO clips in {sd_card_dir} ...')
for root, dirs_list, files_list in os.wa... | __init__ | identifier_name |
gopro.py | timestamp(time_stamp)) if time_stamp is not None else None
def to_timestamp(start_utc):
return start_utc.timestamp() if start_utc is not None else None
class GoProCacheEncoder(JSONEncoder):
# Override the default method
def default(self, obj):
if isinstance(obj, (date, datetime)):
re... | clips = []
for start_idx in range(len(self.clips)):
clip = self.clips[start_idx]
if clip['start_utc'] <= start_utc <= clip['stop_utc']:
in_time = (start_utc - clip['start_utc']).seconds
# Now find the clip containing the stop time
for stop_... | identifier_body | |
gopro.py | None
class GoProCacheEncoder(JSONEncoder):
# Override the default method
def default(self, obj):
if isinstance(obj, (date, datetime)):
return obj.isoformat()
elif isinstance(obj, Location):
if obj.elevation is None:
return {'lat': obj.latitude, 'lon': o... | in_time = (start_utc - clip['start_utc']).seconds
# Now find the clip containing the stop time
for stop_idx in range(start_idx, len(self.clips)):
clip = self.clips[stop_idx]
if stop_utc <= clip['stop_utc']: # Last clip found
... | conditional_block | |
gopro.py | timestamp(time_stamp)) if time_stamp is not None else None
def to_timestamp(start_utc):
return start_utc.timestamp() if start_utc is not None else None
class GoProCacheEncoder(JSONEncoder):
# Override the default method
def default(self, obj):
if isinstance(obj, (date, datetime)):
re... | ii.sow = h['sow']
ii.hdg = h['hdg']
ii.n2k_epoch = h['n2k_epoch']
ii_list.append(ii)
d[k] = ii_list
return d
class GoPro:
def __init__(self, sd_card_dir, work_dir):
cache_dir = work_dir + os.sep + 'gopro'
os.makedirs(... | ii.twa = h['twa']
ii.tws = h['tws'] | random_line_split |
Octagoat.py | for player
def move():
# This function includes movement, and collision with the ramp
global direction, ramp, score, sprite, speed, paused
if paused == 0:
if direction == "left":
canvas.move(sprite, -speed, 0)
elif direction == "right":
canvas.move(sprite, speed, 0)
... | global boss, width
canvas.move(boss, 0, width) | identifier_body | |
Octagoat.py | width="17", height="3",
font=('terminal', 20), command=lambda: tutorial())
start6.place(x=50, y=50)
boss = canvas.create_image(0, -width, anchor='nw', image=bosspic)
# Tutorial explaining different game elements and how to play.
def tutorial():
messagebox.showinfo("Welcome to Octagoat... |
if g4[2] > (width-100):
dir4 = "right"
if dir4 == "right":
mov2 = -mov2
if g2[0] < 100:
dir2 = "left"
if g2[2] > (width-100):
dir2 = "right"
if dir2 == "right":
mov1 = -mov1
canvas.move(enemy2, ... | dir4 = "left" | conditional_block |
Octagoat.py |
# The goat pixel drawings and the cage were produced
# using PixilArt online tool and modified using GIMP.
from tkinter import Tk, PhotoImage, Button
from tkinter import Menu, messagebox, Canvas, Label
from PIL import Image, ImageTk
import time
# Window dimensions.
def setWindowDimensions(w, h):
window.title("... |
# The goat background picture was taken on the
# 23rd of November 2019 at Snowdon, Wales by the author. | random_line_split | |
Octagoat.py | move your goat from\
side to side or jump. To get on the ramp jump to the top\
from underneath it. To get off the ramp simply walk off the sides")
messagebox.showinfo("Welcome to Octagoat",
"Press B if someone passes. C stands for cheat and ... | pause | identifier_name | |
main.py | , must use "import math" to start-----
#pi = 3.14
#x, y, z = 1, 2, 3
#print(round(pi)) # rounds the number
#print(math.ceil(pi)) # rounds the number up
#print(math.floor(pi)) # rounds the number down
#print(abs(-pi)) # returns the absolute value of the number
#print(pow(pi, 2)) # takes the first argument to the ... |
return sum
print(add(5,5,5,5,5,5,5))
#-----**kwargs, packs all arguments into a dictionary-----
def hello(**kwargs):
print("hello", end = " ")
for key,value in kwargs.items():
print(value, end=" ")
hello(first="ben", middle = "charles", last = "rafalski")
... | sum += i | conditional_block |
main.py | range(1,21):
# if i == 13:
# pass # does nothing, place holder for the word 'nothing'
# else:
# print(i)
#-----lists, like arrays-----
#food = ["pizza", "cookies", "hamburger", "hot dog"]
#food.append("ice cream") # adds the element to the end of the list
#food.remove("hot dog") # removes... | fly | identifier_name | |
main.py |
#-----variables-----
def variables():
name = "Ben Rafalski" # can use single or double quotes for a string in python
age = 20
height = 250.5
alive = True # booleans start with a capital letter
print("hello " + name + " who is: " + str(age) + " years old and " + str(250.5) + "cm tall, is ben... | print("hello world") # how to print
| identifier_body | |
main.py |
#print(min(x,y,z)) # returns the min number from a set of numbers
#-----string slicing, creating a substring from a string-----
#name = "Ben Rafalski"
#first_name = name[0:3:1] # indexing[start(inclusive):stop(exclusive):step]
#last_name = name[4:12:1]
#reverse_name = name[::-1] # returns the string in reverse... | text = "this is my written text\nThis is a newline"
| random_line_split | |
client.go | vr, name)
}
func (t *FakeObjectTracker) watchReactionFunc(action k8stesting.Action) (bool, watch.Interface, error) {
if t.FakeWatcher == nil {
return false, nil, errors.New("cannot watch on a tracker with no watch support")
}
switch a := action.(type) {
case k8stesting.WatchAction:
w := &watcher{
FakeWatch... | } | random_line_split | |
client.go | }
}
return t.delegatee.Get(gvr, ns, name)
}
// Create receives a create event with the object. Not needed for CA.
func (t *FakeObjectTracker) Create(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error {
return nil
}
// Update receives an update event with the object
func (t *FakeObjectTracker... | {
var err error
if t.fakingOptions.failAll != nil {
err = t.fakingOptions.failAll.RunFakeInvocations()
if err != nil {
return nil, err
}
}
if t.fakingOptions.failAt != nil {
if gvr.Resource == "nodes" {
err = t.fakingOptions.failAt.Node.Get.RunFakeInvocations()
} else if gvr.Resource == "machines" {... | identifier_body | |
client.go | if t.fakingOptions.failAt != nil {
if gvr.Resource == "nodes" {
err = t.fakingOptions.failAt.Node.Get.RunFakeInvocations()
} else if gvr.Resource == "machines" {
err = t.fakingOptions.failAt.Machine.Get.RunFakeInvocations()
} else if gvr.Resource == "machinesets" {
err = t.fakingOptions.failAt.MachineSe... | (event *watch.Event) {
for _, w := range t.watchers {
go w.dispatch(event)
}
}
// Stop terminates tracking of an FakeObjectTracker
func (t *FakeObjectTracker) Stop() {
if t.FakeWatcher == nil {
panic(errors.New("tracker has no watch support"))
}
t.trackerMutex.Lock()
defer t.trackerMutex.Unlock()
t.FakeWa... | dispatch | identifier_name |
client.go | if t.fakingOptions.failAt != nil {
if gvr.Resource == "nodes" {
err = t.fakingOptions.failAt.Node.Get.RunFakeInvocations()
} else if gvr.Resource == "machines" {
err = t.fakingOptions.failAt.Machine.Get.RunFakeInvocations()
} else if gvr.Resource == "machinesets" {
err = t.fakingOptions.failAt.MachineSe... |
}
return t.delegatee.Get(gvr, ns, name)
}
// Create receives a create event with the object. Not needed for CA.
func (t *FakeObjectTracker) Create(gvr schema.GroupVersionResource, obj runtime.Object, ns string) error {
return nil
}
// Update receives an update event with the object
func (t *FakeObjectTracker) Up... | {
return nil, err
} | conditional_block |
xf_numba.py | chi is a value... compute output
cx = np.cos(chi)
sx = np.sin(chi)
for i in range(n):
cw = np.cos(omes[i])
sw = np.sin(omes[i])
out[i, 0, 0] = cw; out[i, 0, 1] = 0.; out[i, 0, 2] = sw
out[i, 1, 0] = sx*sw; o... | """
normalize array of column vectors (hstacked, axis = 0)
"""
if vec_in.ndim == 1:
out = _unit_vector_single(vec_in)
elif vec_in.ndim == 2:
out = _unit_vector_multi(vec_in)
else:
raise ValueError(
"incorrect arg shape; must be 1-d or 2-d, yours is %d-d"
... | identifier_body | |
xf_numba.py | (fn):
out = numba.jit(fn)
out.__signature__ = get_signature(fn)
return out
@numba.njit
def _angles_to_gvec_helper(angs, out=None):
"""
angs are vstacked [2*theta, eta, omega], although omega is optional
This should be equivalent to the one-liner numpy version:
out = np.vstack([[np.cos(0.... | xfapi_jit | identifier_name | |
xf_numba.py | if out is not None else np.empty((dim, 3), dtype=angs.dtype)
for i in range(len(angs)):
ca0 = np.cos(angs[i, 0])
sa0 = np.sin(angs[i, 0])
ca1 = np.cos(angs[i, 1])
sa1 = np.sin(angs[i, 1])
out[i, 0] = sa0 * ca1
out[i, 1] = sa0 * sa1
out[i, 2] = -ca0
retur... | out[:] = a[:] | conditional_block | |
xf_numba.py | i in range(len(angs)):
ca0 = np.cos(angs[i, 0])
sa0 = np.sin(angs[i, 0])
ca1 = np.cos(angs[i, 1])
sa1 = np.sin(angs[i, 1])
out[i, 0] = sa0 * ca1
out[i, 1] = sa0 * sa1
out[i, 2] = -ca0
return out
@numba.njit
def _rmat_s_helper(chi=None, omes=None, out=None):... |
@numba.njit
def _unit_vector_multi(a, out=None): | random_line_split | |
report_errors_service.pb.go | () string { return proto.CompactTextString(m) }
func (*ReportErrorEventResponse) ProtoMessage() {}
func (*ReportErrorEventResponse) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{1} }
// An error event which is reported to the Error Reporting system.
type ReportedErrorEvent struc... | String | identifier_name | |
report_errors_service.pb.go | ) Reset() { *m = ReportedErrorEvent{} }
func (m *ReportedErrorEvent) String() string { return proto.CompactTextString(m) }
func (*ReportedErrorEvent) ProtoMessage() {}
func (*ReportedErrorEvent) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{2} }
func (m *Repor... | func RegisterReportErrorsServiceServer(s *grpc.Server, srv ReportErrorsServiceServer) {
s.RegisterService(&_ReportErrorsService_serviceDesc, srv)
}
func _ReportErrorsService_ReportErrorEvent_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{... | random_line_split | |
report_errors_service.pb.go |
return nil
}
// Response for reporting an individual error event.
// Data may be added to this message in the future.
type ReportErrorEventResponse struct {
}
func (m *ReportErrorEventResponse) Reset() { *m = ReportErrorEventResponse{} }
func (m *ReportErrorEventResponse) String() string ... | {
return m.Event
} | conditional_block | |
report_errors_service.pb.go | Reset() { *m = ReportedErrorEvent{} }
func (m *ReportedErrorEvent) String() string { return proto.CompactTextString(m) }
func (*ReportedErrorEvent) ProtoMessage() {}
func (*ReportedErrorEvent) Descriptor() ([]byte, []int) { return fileDescriptor3, []int{2} }
func (m *Report... |
var fileDescriptor3 = []byte{
// 490 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xa4, 0x93, 0xcd, 0x8a, 0x13, 0x41,
0x10, 0xc7, 0x99, 0xf8, 0xb1, 0x6c, 0x47, 0x54, 0xda, 0x83, 0xc3, 0x20, 0xb8, 0xc6, 0xcb, 0xa2,
0x30, 0x6d, 0xe2, 0xc5, 0xec, 0x22, 0x0b, 0x59... | {
proto.RegisterFile("google/devtools/clouderrorreporting/v1beta1/report_errors_service.proto", fileDescriptor3)
} | identifier_body |
crunchauto.py |
else:
if endofdate:
dt = datetime.datetime.combine(dt,datetime.time(hour=23,minute=59,second=59,tzinfo=to_zone))
else:
dt = datetime.datetime.combine(dt,datetime.time(tzinfo=to_zone))
return dt
weekday=['Sun','Mon','Tues','Wed','Thurs','Fri','Sat'] # OUR Sunday=0 Convention!!
def crunch_calend... | dt = dt.astimezone(to_zone) | conditional_block | |
crunchauto.py | (rundate,"%Y-%m-%d").replace(tzinfo=tz.gettz('America/New York'))
else:
now = datetime.datetime.now().replace(tzinfo=tz.gettz('America/New York'))
#print "CRUNCH EFFECTIVE RUNDATE",rundate
## ADJUST HERE FOR TZ! (i.e. If we run Midnight on Sunday don't want LAST week's run
dow = now.weekday() # 0=Monday
d... | lastItem=None
pendingleases={}
while True:
ii= stripe.InvoiceItem.list(
limit=2,
#customer="cus_J0mrDmtpzbfYOk", # Stripe Test Customer
customer=customer, # MIL Brad Goodman
starting_after=lastItem
)
#print "EXISTING ITEMS"
#print ii
if ii:
... | errors=[]
warnings=[]
debug=[]
stripe.api_key = current_app.config['globalConfig'].Config.get('autoplot','stripe_token')
#stripe.api_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" # TEST KEY
#print stripe.SKU.list(limit=99)
#print stripe.Customer.list(limit=99)
debug.append("Process Payment customer {0} Price ... | identifier_body |
crunchauto.py | undate,"%Y-%m-%d").replace(tzinfo=tz.gettz('America/New York'))
else:
now = datetime.datetime.now().replace(tzinfo=tz.gettz('America/New York'))
#print "CRUNCH EFFECTIVE RUNDATE",rundate
## ADJUST HERE FOR TZ! (i.e. If we run Midnight on Sunday don't want LAST week's run
dow = now.weekday() # 0=Monday
dow... | (customer,price,leaseid,description,test=False,pay=False):
errors=[]
warnings=[]
debug=[]
stripe.api_key = current_app.config['globalConfig'].Config.get('autoplot','stripe_token')
#stripe.api_key = "sk_test_4eC39HqLyjWDarjtT1zdp7dc" # TEST KEY
#print stripe.SKU.list(limit=99)
#print stripe.Customer.list(l... | do_payment | identifier_name |
crunchauto.py | (rundate,"%Y-%m-%d").replace(tzinfo=tz.gettz('America/New York'))
else:
now = datetime.datetime.now().replace(tzinfo=tz.gettz('America/New York'))
#print "CRUNCH EFFECTIVE RUNDATE",rundate
## ADJUST HERE FOR TZ! (i.e. If we run Midnight on Sunday don't want LAST week's run
dow = now.weekday() # 0=Monday | weekstart = weekstart.replace(hour=0,minute=0,second=0,microsecond=0)
weekend = weekstart + datetime.timedelta(days=7)
weekend = weekend - datetime.timedelta(seconds=1)
#print "WEEKSTART",weekstart,"through",weekend
errors=[]
warnings=[]
billables=[]
summaries=[]
debug=[]
data={}
debug.append("{2... | dow = (dow+1) %7 #0=Sunday
weeknum = int(now.strftime("%U"))
#print "weeknum",weeknum,"Weekday",weekday[dow],"DOW",dow
weekstart = (now - datetime.timedelta(days=dow)) | random_line_split |
lib.rs | can return random values.
//! * `random.u8`
//! * `random.u16`
//! * `random.u32`
//! * `random.u64`
//! * `random.u128`
//! * `random.usize`
//! * `random.i8`
//! * `random.i16`
//! * `random.i32`
//! * `random.i64`
//! * `random.i128`
//! * `random.isize`
//! 2. Custom arguments s... | get | identifier_name | |
lib.rs | `
//! * `random.i128`
//! * `random.isize`
//! 2. Custom arguments source. [`SalakBuilder::set()`] can set a single kv,
//! and [`SalakBuilder::set_args()`] can set a group of kvs.
//! 3. System environment source. Implemented by [`source::system_environment`].
//! 4. Profile specified file source, eg. `app-dev.t... | iorefs: &'a Mutex<Vec<Box<dyn IORefT + Send>>>,
key: &'a mut Key<'a>, | random_line_split | |
lib.rs | random.u32`
//! * `random.u64`
//! * `random.u128`
//! * `random.usize`
//! * `random.i8`
//! * `random.i16`
//! * `random.i32`
//! * `random.i64`
//! * `random.i128`
//! * `random.isize`
//! 2. Custom arguments source. [`SalakBuilder::set()`] can set a single kv,
//! and [`SalakBuilder::set_... | {
self.require::<T>(T::prefix())
} | identifier_body | |
core.py | .get('EDITOR', 'vim'))
subprocess.run([editor, filename], check=True)
def _write_template_to_tempfile(
self, f: IO[str], entry: model.JMESLogEntry
) -> None:
contents = DEFAULT_TEMPLATE.format(
type=entry.type,
category=entry.category,
description=ent... | query_last_release_version | identifier_name | |
core.py | =True)
def _write_template_to_tempfile(
self, f: IO[str], entry: model.JMESLogEntry
) -> None:
contents = DEFAULT_TEMPLATE.format(
type=entry.type,
category=entry.category,
description=entry.description,
)
f.write(contents)
f.flush()
... | return find_last_released_version(self._change_dir) | identifier_body | |
core.py | def prompt_entry_values(self, entry: model.JMESLogEntry) -> None:
with tempfile.NamedTemporaryFile('w') as f:
self._write_template_to_tempfile(f, entry)
self._open_tempfile_in_editor(f.name)
contents = self._read_tempfile(f.name)
return self._parse_filled_in_cont... | f'The "{schema_field.name}" value must be one of: '
f'{", ".join(allowed_values)}, received: "{value}"'
)
for key, value in entry_dict.items():
if not value:
errors.append(f'The "{key}" value cannot be empty.')
if errors:
raise ValidationEr... | random_line_split | |
core.py | def prompt_entry_values(self, entry: model.JMESLogEntry) -> None:
with tempfile.NamedTemporaryFile('w') as f:
self._write_template_to_tempfile(f, entry)
self._open_tempfile_in_editor(f.name)
contents = self._read_tempfile(f.name)
return self._parse_filled_in_cont... |
class EntryFileParser:
def parse_contents(self, contents: str) -> model.JMESLogEntry:
entry = model.JMESLogEntry.empty()
if not contents.strip():
return entry
field_names = [f.name for f in fields(entry)]
line_starts = tuple([f'{name}:' for name in field_names])
... | setattr(entry, key, value) | conditional_block |
mod.rs | rc<Tensor>),
}
impl TensorView {
/// Creates a shared TensorView from any TensorView.
pub fn into_shared(self) -> TensorView {
match self {
TensorView::Owned(m) => TensorView::Shared(Arc::new(m)),
TensorView::Shared(_) => self,
}
}
/// Creates a Tensor from a Te... | (&self) -> &Tensor {
match self {
&TensorView::Owned(ref m) => &m,
&TensorView::Shared(ref m) => m.as_ref(),
}
}
/// Returns a shared copy of the TensorView, turning the one passed
/// as argument into a TensorView::Shared if necessary.
pub fn share(&mut self) ->... | as_tensor | identifier_name |
mod.rs | rc<Tensor>),
}
impl TensorView {
/// Creates a shared TensorView from any TensorView.
pub fn into_shared(self) -> TensorView {
match self {
TensorView::Owned(m) => TensorView::Shared(Arc::new(m)),
TensorView::Shared(_) => self,
}
}
/// Creates a Tensor from a Te... | bail!("Streaming is not available for operator {:?}", self)
}
/// Infers properties about the input and output tensors.
///
/// The `inputs` and `outputs` arguments correspond to properties about
/// the input and output tensors that are already known.
///
/// Returns Err in case of... | fn step(
&self,
_inputs: Vec<(Option<usize>, Option<TensorView>)>,
_buffer: &mut Box<OpBuffer>,
) -> Result<Option<Vec<TensorView>>> { | random_line_split |
mod.rs | <Tensor>),
}
impl TensorView {
/// Creates a shared TensorView from any TensorView.
pub fn into_shared(self) -> TensorView |
/// Creates a Tensor from a TensorView.
pub fn into_tensor(self) -> Tensor {
match self {
TensorView::Owned(m) => m,
TensorView::Shared(m) => m.as_ref().clone(),
}
}
/// Returns a reference to the Tensor wrapped inside a TensorView.
pub fn as_tensor(&self) ... | {
match self {
TensorView::Owned(m) => TensorView::Shared(Arc::new(m)),
TensorView::Shared(_) => self,
}
} | identifier_body |
import.go | ([]string, 0)
s.imports["routes"] = make([]string, 0)
s.imports["plugins"] = make([]string, 0)
s.imports["consumers"] = make([]string, 0)
} else if err := json.Unmarshal(raw, &s.imports); err != nil {
return err
}
}
return nil
}
func (s *kongState) discover() error {
if consumers, err := s.client.G... | {
namePrefix := ""
if plugin.ServiceId != "" {
for _, service := range s.services {
if service.Id == plugin.ServiceId {
namePrefix = service.Name
break
}
}
} else if plugin.RouteId != "" {
for _, route := range s.routes {
if route.Id == plugin.RouteId {
namePrefix = getResourceNameForRout... | identifier_body | |
import.go | ry-run",
false,
"List the resources that will be imported, but do not actually import them.",
)
flags.StringVar(
&cmd.importFileName,
"state",
"import-state.json",
"Holds the current import state and any exclusions",
)
flags.StringVar(
&cmd.tfConfigPath,
"tf-config",
"",
"Path to Terraform confi... | fmt.Println("\nImporting services:")
for _, service := range s.services {
resource := &resourceImport{
kongResourceType: "service",
terraformResourceType: "kong_service",
resourceName: service.Name,
resourceId: service.Id,
dryRun: cmd.isDryRun,... | {
fmt.Println("\nImporting consumers:")
for _, consumer := range s.consumers {
resource := &resourceImport{
kongResourceType: "consumer",
terraformResourceType: "kong_consumer",
resourceName: getResourceNameForConsumer(&consumer),
resourceId: consumer.Id,
dryRun: ... | conditional_block |
import.go | ry-run",
false,
"List the resources that will be imported, but do not actually import them.",
)
flags.StringVar(
&cmd.importFileName,
"state",
"import-state.json",
"Holds the current import state and any exclusions",
)
flags.StringVar(
&cmd.tfConfigPath,
"tf-config",
"",
"Path to Terraform confi... | (resourceImport *resourceImport) error {
if s.hasResourceBeenImported(resourceImport) {
return nil
}
terraformResourceName := fmt.Sprintf("%s.%s", resourceImport.terraformResourceType, createHclSafeName(resourceImport.resourceName))
if !resourceImport.dryRun {
// ex: terraform import -config=examples/import ko... | importResource | identifier_name |
import.go | ry-run",
false,
"List the resources that will be imported, but do not actually import them.",
)
flags.StringVar(
&cmd.importFileName,
"state",
"import-state.json",
"Holds the current import state and any exclusions",
)
flags.StringVar(
&cmd.tfConfigPath,
"tf-config",
"",
"Path to Terraform confi... | if len(s.consumers) > 0 {
fmt.Println("\nImporting consumers:")
for _, consumer := range s.consumers {
resource := &resourceImport{
kongResourceType: "consumer",
terraformResourceType: "kong_consumer",
resourceName: getResourceNameForConsumer(&consumer),
resourceId: con... |
return nil
}
func (s *kongState) importResources(cmd *importCommand) error { | random_line_split |
mtcnn.py | = self.conv4_2(x)
return b, a
class RNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 28, kernel_size=3)
self.prelu1 = nn.PReLU(28)
self.pool1 = nn.MaxPool2d(3, 2, ceil_mode=True)
self.conv2 = nn.Conv2d(28, 48, kernel_size=3)
self.prelu2 = nn.PReLU(48)
self.pool2 = ... |
else:
if not isinstance(imgs, (list, tuple)):
imgs = [imgs]
if any(img.size != imgs[0].size for img in imgs):
raise Exception("MTCNN batch processing only compatible with equal-dimension images.")
imgs = np.stack([np.uint8(img) for img in imgs])
imgs = torch.as_tensor(imgs, device=device)
model_dtype ... | imgs = torch.as_tensor(imgs, device=device)
if len(imgs.shape) == 3:
imgs = imgs.unsqueeze(0) | conditional_block |
mtcnn.py | [:, 8] * regh
boxes = torch.stack([qq1, qq2, qq3, qq4, boxes[:, 4]]).permute(1, 0)
boxes = rerec(boxes)
y, ey, x, ex = pad(boxes, w, h)
# Second stage
if len(boxes) > 0:
im_data = []
for k in range(len(y)):
if ey[k] > (y[k] - 1) and ex[k] > (x[k] - 1):
img_k = imgs[image_inds[k], :, (y[k] - 1):ey[k], (... | pad | identifier_name | |
mtcnn.py | = self.conv4_2(x)
return b, a
class RNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 28, kernel_size=3)
self.prelu1 = nn.PReLU(28)
self.pool1 = nn.MaxPool2d(3, 2, ceil_mode=True)
self.conv2 = nn.Conv2d(28, 48, kernel_size=3)
self.prelu2 = nn.PReLU(48)
self.pool2 = ... |
def forward(self, x):
x = self.conv1(x)
x = self.prelu1(x)
x = self.pool1(x)
x = self.conv2(x)
x = self.prelu2(x)
x = self.pool2(x)
x = self.conv3(x)
x = self.prelu3(x)
x = self.pool3(x)
x = self.conv4(x)
x = self.prelu4(x)
x = x.permute(0, 3, 2, 1).contiguous()
x = self.dense5(x.view(x.shap... | def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3)
self.prelu1 = nn.PReLU(32)
self.pool1 = nn.MaxPool2d(3, 2, ceil_mode=True)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
self.prelu2 = nn.PReLU(64)
self.pool2 = nn.MaxPool2d(3, 2, ceil_mode=True)
self.conv3 = nn.Conv2d(... | identifier_body |
mtcnn.py | = self.conv4_2(x)
return b, a
class RNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 28, kernel_size=3)
self.prelu1 = nn.PReLU(28)
self.pool1 = nn.MaxPool2d(3, 2, ceil_mode=True)
self.conv2 = nn.Conv2d(28, 48, kernel_size=3)
self.prelu2 = nn.PReLU(48)
self.pool2 = ... |
class ONet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3)
self.prelu1 = nn.PReLU(32)
self.pool1 = nn.MaxPool2d(3, 2, ceil_mode=True)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
self.prelu2 = nn.PReLU(64)
self.pool2 = nn.MaxPool2d(3, 2, ceil_mode=True... | a = self.dense5_1(x)
a = self.softmax5_1(a)
b = self.dense5_2(x)
return b, a | random_line_split |
lambdaFunction.go | Pull != nil && int64(now.Sub(*f.lastPull)) < cacheNs {
return nil
}
// is there new code?
rtType, codeDir, err := f.lmgr.HandlerPuller.Pull(f.name)
if err != nil {
return err
}
if codeDir == f.codeDir {
return nil
}
f.rtType = rtType
defer func() {
if err != nil {
if err := os.RemoveAll(codeDir)... | {
done := make(chan bool)
f.killChan <- done
<-done
} | identifier_body | |
lambdaFunction.go | }
func (f *LambdaFunc) Invoke(w http.ResponseWriter, r *http.Request) {
t := common.T0("LambdaFunc.Invoke")
defer t.T1()
done := make(chan bool)
req := &Invocation{w: w, r: r, done: done}
// send invocation to lambda func task, if room in queue
select {
case f.funcChan <- req:
// block until it's done
<-d... | if oldCodeDir != "" && oldCodeDir != f.codeDir {
el := f.instances.Front()
for el != nil {
waitChan := el.Value.(*LambdaInstance).AsyncKill()
cleanupChan <- waitChan
el = el.Next()
}
f.instances = list.New()
// cleanupChan is a FIFO, so this will
// happen after the cleanup ta... | {
select {
case <-timeout.C:
if f.codeDir == "" {
continue
}
case req := <-f.funcChan:
// msg: client -> function
// check for new code, and cleanup old code
// (and instances that use it) if necessary
oldCodeDir := f.codeDir
if err := f.pullHandlerIfStale(); err != nil {
f.printf("E... | conditional_block |
lambdaFunction.go | is any error:
// 1. we won't switch to the new code
// 2. we won't update pull time (so well check for a fix next time)
func (f *LambdaFunc) pullHandlerIfStale() (err error) {
// check if there is newer code, download it if necessary
now := time.Now()
cacheNs := int64(common.Conf.Registry_cache_ms) * 1000000
// s... | newInstance | identifier_name | |
lambdaFunction.go | }
func (f *LambdaFunc) Invoke(w http.ResponseWriter, r *http.Request) {
t := common.T0("LambdaFunc.Invoke")
defer t.T1()
done := make(chan bool)
req := &Invocation{w: w, r: r, done: done}
// send invocation to lambda func task, if room in queue
select {
case f.funcChan <- req:
// block until it's done
<-d... |
// this Task receives lambda requests, fetches new lambda code as
// needed, and dispatches to a set of lambda instances. Task also
// monitors outstanding requests, and scales the number of instances
// up or down as needed.
//
// communication for a given request is as follows (each of the four
// transfers are com... |
f.codeDir = codeDir
f.lastPull = &now
return nil
} | random_line_split |
lib.rs | threshold: slow_threshold,
inner: drain,
};
let filtered = drain.filter(filter).fuse();
slog::Logger::root(filtered, slog_o!())
};
set_global_logger(level, init_stdlog, logger)
}
pub fn set_global_logger(
level: Level,
init_stdlog: bool,
logger: slog::Logger,
)... | random_line_split | ||
lib.rs | pub fn init_log<D>(
drain: D,
level: Level,
use_async: bool,
init_stdlog: bool,
mut disabled_targets: Vec<String>,
slow_threshold: u64,
) -> Result<(), SetLoggerError>
where
D: Drain + Send + 'static,
<D as Drain>::Err: std::fmt::Display,
{
// Set the initial log level used by the Dr... |
// Converts `slog::Level` to unified log level format.
fn get_unified_log_level(lv: Level) -> &'static str {
match lv {
Level::Critical => "FATAL",
Level::Error => "ERROR",
Level::Warning => "WARN",
Level::Info => "INFO",
Level::Debug => "DEBUG",
Level::Trace => "TR... | {
match lv {
Level::Critical => "critical",
Level::Error => "error",
Level::Warning => "warning",
Level::Debug => "debug",
Level::Trace => "trace",
Level::Info => "info",
}
} | identifier_body |
lib.rs | let filtered = drain.filter(filter).fuse();
slog::Logger::root(filtered, slog_o!())
};
set_global_logger(level, init_stdlog, logger)
}
pub fn set_global_logger(
level: Level,
init_stdlog: bool,
logger: slog::Logger,
) -> Result<(), SetLoggerError> {
slog_global::set_global(logg... | log | identifier_name | |
animLib.py | weights can result
#in the tangent types being ignored (for the case of stepped mainly, but subtle weirdness with flat happens too)
cmd.keyTangent( attrpath, t=(time,), ix=ix, iy=iy, ox=ox, oy=oy, l=isLocked, wl=isWeighted )
cmd.keyTangent( attrpath, t=(time,), itt=itt, ott=ott )
else:
... | global kEXT
clips = {LOCAL: [], GLOBAL: []}
for locale in LOCAL, GLOBAL:
localeClips = clips[locale]
for dir in getPresetDirs(locale, TOOL_NAME):
dir += library
if not dir.exists:
continue
for f in dir.files():
if f.hasExtension( kEXT ):
f = f.setExtension()
na... | identifier_body | |
animLib.py | .AddKey( time, value, ix, iy, ox, oy )
attrPath = '%s.%s' % (o, a)
try: self.curvePairs[attrPath].append( curve )
except KeyError: self.curvePairs[attrPath] = [ curve ]
#now iterate over each curve pair and make sure they both have keys on the same frames...
for attrPath, curves in self.curv... | return self.keys()
def generatePreArgs( self ):
return tuple()
def getObjAttrNames( obj, attrNamesToSkip=() ):
#grab attributes
objAttrs = cmd.listAttr( obj, keyable=True, visible=True, scalar=True ) or []
#also grab alias' - its possible to pass in an alias name, so we need to test against them a... | '''
pass
def getObjects( self ):
| random_line_split |
animLib.py |
time = cmd.currentTime(q=True)
#make sure the icon is open for edit if its a global clip
if preset.locale == GLOBAL and preset.icon.exists:
preset.edit()
icon = cmd.playblast(st=time, et=time, w=kICON_W_H[0], h=kICON_W_H[1], fo=True, fmt="image", v=0, p=100, orn=0, cf=str(preset.icon.resolve()))
ico... | mel.eval("modelEditor -e %s 0 %s;" % (setting, panel)) | conditional_block | |
animLib.py | ( self, pct, mapping=None, attributes=None ):
BaseBlender.__call__(self, pct, mapping)
cmdQueue = api.CmdQueue()
if mapping is None:
mapping = self.getMapping()
if attributes is None:
attributes = self.attributes
mappingDict = mapping.asDict()
for clipAObj, attrDictA in self.clipA.iterit... | __call__ | identifier_name | |
textboardcomponent.js | leties when using transparent backgrounds.
The shader discards fragments with alpha <0.9, so you need to set the alpha value of the bg to something less than that.
The canvas rendering uses a blend function that dithers between the foreground color and the background color, including the relative alpha values. ... |
TextBoard.prototype.setText = function (lines) {
this.currentTextLines = lines;
this.reset();
this.renderTextLines(this.currentTextLines);
}
TextBoard.prototype.prepare = function () {
var board = this;
board.drawable.texture = board.getTexture();
bo... | }
// this.currentTextLines.push(line);
this.reset();
this.renderTextLines(this.currentTextLines);
} | random_line_split |
textboardcomponent.js | ies when using transparent backgrounds.
The shader discards fragments with alpha <0.9, so you need to set the alpha value of the bg to something less than that.
The canvas rendering uses a blend function that dithers between the foreground color and the background color, including the relative alpha values.
... | board.cursor.y += rstate.lineHeight;
}
}
board.updateTexture();
}
TextBoard.prototype.addTextLines = function (lines) {
for (var i = 0; i < lines.length; i++) {
this.currentTextLines.push(lines[i... | {
var line = textLines[i];
rstate.font = line.font || rstate.font;
rstate.fontSize = line.fontSize || rstate.fontSize;
rstate.textColor = line.textColor || rstate.textColor;
rstate.backgroundColor = line.backgroundColor || rstate.backgroundColor;
r... | conditional_block |
section_0771_to_0788.rs | |fin_col|, |fin_row|, |fin_align|.
//!
//! @ When \.{\\halign} or \.{\\valign} has been scanned in an appropriate
//! mode, \TeX\ calls |init_align|, whose task is to get everything off to a
//! good start. This mostly involves scanning the preamble and putting its
//! information into the preamble list.
//! @^preambl... | //! procedure@?align_peek; forward;@t\2@>@/
//! procedure@?normal_paragraph; forward;@t\2@>@/
//! procedure init_align;
//! label done, done1, done2, continue;
//! var save_cs_ptr:pointer; {|warning_index| value for error messages}
//! @!p:pointer; {for short-term temporary use}
//! begin save_cs_ptr:=cur_cs; {\.{\\hal... | //! @p @t\4@>@<Declare the procedure called |get_preamble_token|@>@t@>@/ | random_line_split |
http.rs | .send_request(request).await
},
}
}
/// Sends an HTTP request message and reads the response, returning its body.
async fn send_request(&mut self, request: &str) -> std::io::Result<Vec<u8>> {
self.write_request(request).await?;
self.read_response().await
}
/// Writes an HTTP request message.
async fn w... |
// Decode the chunk header to obtain the chunk size.
let mut buffer = Vec::new();
let mut decoder = chunked_transfer::Decoder::new(chunk_header.as_bytes());
decoder.read_to_end(&mut buffer)?;
// Read the chunk body.
let chunk_size = match decoder.remaining_chunks_size() {
... | {
// Read the terminator chunk since the decoder consumes the CRLF
// immediately when this chunk is encountered.
reader.read_line(&mut chunk_header).await?;
} | conditional_block |
http.rs | .send_request(request).await
},
}
}
/// Sends an HTTP request message and reads the response, returning its body.
async fn send_request(&mut self, request: &str) -> std::io::Result<Vec<u8>> {
self.write_request(request).await?;
self.read_response().await
}
/// Writes an HTTP request message.
async fn w... | if chunk_header == "0\r\n" {
// Read the terminator chunk since the decoder consumes the CRLF
// immediately when this chunk is encountered.
reader.read_line(&mut chunk_header).await?;
}
// Decode the chunk header to obtain the chunk size.
let mut buffer = Vec::new()... | random_line_split | |
http.rs | <F>(&mut self, uri: &str, host: &str, auth: &str, content: serde_json::Value) -> std::io::Result<F>
where F: TryFrom<Vec<u8>, Error = std::io::Error> {
let content = content.to_string();
let request = format!(
"POST {} HTTP/1.1\r\n\
Host: {}\r\n\
Authorization: {}\r\n\
Connection: keep-alive\r\n\
... | post | identifier_name | |
coref.py | soup = BeautifulSoup(f.read(),'lxml')
f.close()
soup_all = []
stack = []
coreList = []
core_all = []
coref = []
wrapped = False
for siru in soup.findAll('coref'):
soupList = []
soupList.append(siru.attrs.get('id'))
soupList.append(siru.attrs.get('type'))
... | random_line_split | ||
coref.py | (Dir):
r = Dir + '/'
cors = []
cons = []
data = []
genre = []
dirs = [x for x in glob.glob(r + '*')]
for d in dirs:
for _r, _d, files in os.walk(d):
for f in files:
if f.endswith('_cors'):
cors.append([os.path.join(_r, f),d])
... | load_dir | identifier_name | |
coref.py | stack.append([co,corefno])
core_all.append([index,0,0,sentno])
if wrapped:
core_all[corefno][2]
corefno = corefno + 1
if len(stack) == 0:
wrapped = False
elif len(stack) == 1:
wra... |
elif genre == 'bn':
param = 1
elif genre == 'mz':
param = 2
elif genre == 'nw':
param = 3
elif genre == 'pt':
param = 4
elif genre == 'tc':
param = 5
elif genre == 'wb':
param = 6
return [param]
def getWordEmbedding(info_words):
dic = she... | param = 0 | conditional_block |
coref.py | stack.append([co,corefno])
core_all.append([index,0,0,sentno])
if wrapped:
core_all[corefno][2]
corefno = corefno + 1
if len(stack) == 0:
wrapped = False
elif len(stack) == 1:
wrapped = True
... | nre):
print('begin')
vector = []
vectors = []
labels = []
costs = []
antecedents = ['NA']
total = len(mentions)
print(total)
Wembed = Wembedave[0]
ave_all = Wembedave[1]
for m in mentions:
for a in antecedents:
if a == 'NA':
tm... | pMatch = 1
break
return [pMatch]
def getInclude(include):
if include:
return [1]
else:
return [0]
def getVectors(mentions,words,Wembedave,ge | identifier_body |
avito-lightgbm-with-ridge-feature-1.py | Fold
# Tf-Idf
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.pipeline import FeatureUnion
from scipy.sparse import hstack, csr_matrix
from nltk.corpus import stopwords
# Viz
import seaborn as sns
import matplotlib.pyplot as plt
import re
import string
NFOLDS ... |
oof_test[:] = oof_test_skf.mean(axis=0)
return oof_train.reshape(-1, 1), oof_test.reshape(-1, 1)
def cleanName(text):
try:
textProc = text.lower()
# textProc = " ".join(map(str.strip, re.split('(\d+)',textProc)))
#regex = re.compile(u'[^[:alpha:]]')
#textProc... | print('\nFold {}'.format(i))
x_tr = x_train[train_index]
y_tr = y[train_index]
x_te = x_train[test_index]
clf.train(x_tr, y_tr)
oof_train[test_index] = clf.predict(x_te)
oof_test_skf[i, :] = clf.predict(x_test) | conditional_block |
avito-lightgbm-with-ridge-feature-1.py | Fold
# Tf-Idf
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.pipeline import FeatureUnion
from scipy.sparse import hstack, csr_matrix
from nltk.corpus import stopwords
# Viz
import seaborn as sns
import matplotlib.pyplot as plt
import re
import string
NFOLDS ... | lbl = preprocessing.LabelEncoder()
for col in categorical:
df[col].fillna('Unknown')
df[col] = lbl.fit_transform(df[col].astype(str))
print("\nText Features")
# Feature Engineering
# Meta Text Features
textfeats = ["description", "title"]
df['desc_punc'] = df['description'].apply(lambda x: le... | categorical = ["user_id","region","city","parent_category_name","category_name","user_type","image_top_1","param_1","param_2","param_3"]
print("Encoding :",categorical)
# Encoder:
| random_line_split |
avito-lightgbm-with-ridge-feature-1.py |
# Tf-Idf
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.pipeline import FeatureUnion
from scipy.sparse import hstack, csr_matrix
from nltk.corpus import stopwords
# Viz
import seaborn as sns
import matplotlib.pyplot as plt
import re
import string
NFOLDS = 5
... | da x: x[col_name]
##I added to the max_features of the description. It did not change my score much but it may be worth investigating
vectorizer = FeatureUnion([
('description',TfidfVectorizer(
ngram_range=(1, 2),
max_features=17000,
**tfidf_para,
preproces... | rn lamb | identifier_name |
avito-lightgbm-with-ridge-feature-1.py | Fold
# Tf-Idf
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.pipeline import FeatureUnion
from scipy.sparse import hstack, csr_matrix
from nltk.corpus import stopwords
# Viz
import seaborn as sns
import matplotlib.pyplot as plt
import re
import string
NFOLDS ... | Stage")
training = pd.read_csv('../input/train.csv', index_col = "item_id", parse_dates = ["activation_date"])
traindex = training.index
testing = pd.read_csv('../input/test.csv', index_col = "item_id", parse_dates = ["activation_date"])
testdex = testing.index
ntrain = training.shape[0]
ntest = testing.shape[0... | )
return np.sqrt(np.mean(np.power((y - y0), 2)))
print("\nData Load | identifier_body |
uiLibFlexbox.go | GetOrder() int {
return slot.Order
}
func (slot FlexboxSlot) fyRespectMinimumSize() bool {
return slot.RespectMinimumSize
}
// -- Solver --
func fyFlexboxGetPreferredSize(details FlexboxContainer) frenyard.Vec2i {
// Do note, this is in main/cross format.
mainCrossSize := frenyard.Vec2i{}
for _, v := range detai... | func (slot fyFlexboxRow) fyCalcBasis(cross int32, vertical bool) int32 {
return slot.fyMainCrossSizeForMainCrossLimits(frenyard.Vec2i{X: frenyard.SizeUnlimited, Y: cross}, vertical, false).X
}
func (slot fyFlexboxRow) fyGetOrder() int {
return 0
}
func (slot fyFlexboxRow) fyRespectMinimumSize() bool {
return false
}... | random_line_split | |
uiLibFlexbox.go | GetOrder() int {
return slot.Order
}
func (slot FlexboxSlot) fyRespectMinimumSize() bool {
return slot.RespectMinimumSize
}
// -- Solver --
func fyFlexboxGetPreferredSize(details FlexboxContainer) frenyard.Vec2i {
// Do note, this is in main/cross format.
mainCrossSize := frenyard.Vec2i{}
for _, v := range detai... |
return frenyard.Vec2i{X: maximumMain, Y: presentAreaCross}
}
func (slot fyFlexboxRow) fyCalcBasis(cross int32, vertical bool) int32 {
return slot.fyMainCrossSizeForMainCrossLimits(frenyard.Vec2i{X: frenyard.SizeUnlimited, Y: cross}, vertical, false).X
}
func (slot fyFlexboxRow) fyGetOrder() int {
return 0
}
func (s... | {
fmt.Print(" }")
} | conditional_block |
uiLibFlexbox.go | GetOrder() int {
return slot.Order
}
func (slot FlexboxSlot) fyRespectMinimumSize() bool {
return slot.RespectMinimumSize
}
// -- Solver --
func fyFlexboxGetPreferredSize(details FlexboxContainer) frenyard.Vec2i {
// Do note, this is in main/cross format.
mainCrossSize := frenyard.Vec2i{}
for _, v := range detai... | () int {
return len(sc.slots)
}
func (sc fyFlexboxSortingCollection) Less(i int, j int) bool {
order1 := sc.slots[i].fyGetOrder()
order2 := sc.slots[j].fyGetOrder()
// Order1 != order2?
if order1 < order2 {
return true
}
if order1 > order2 {
return false
}
// No, they're equal. Sort by original index.
if ... | Len | identifier_name |
uiLibFlexbox.go | GetOrder() int {
return slot.Order
}
func (slot FlexboxSlot) fyRespectMinimumSize() bool {
return slot.RespectMinimumSize
}
// -- Solver --
func fyFlexboxGetPreferredSize(details FlexboxContainer) frenyard.Vec2i {
// Do note, this is in main/cross format.
mainCrossSize := frenyard.Vec2i{}
for _, v := range detai... |
func fyFlexboxSolveLayout(details FlexboxContainer, limits frenyard.Vec2i) []frenyard.Area2i {
// Stage 1. Element order pre-processing (DirReverse)
slots := make([]fyFlexboxSlotlike, len(details.Slots))
originalToDisplayIndices := make([]int, len(details.Slots))
displayToOriginalIndices := make([]int, len(detail... | {
backup := sc.slots[i]
backup2 := sc.originalToDisplayIndices[i]
backup3 := sc.displayToOriginalIndices[i]
sc.slots[i] = sc.slots[j]
sc.originalToDisplayIndices[i] = sc.originalToDisplayIndices[j]
sc.displayToOriginalIndices[i] = sc.displayToOriginalIndices[j]
sc.slots[j] = backup
sc.originalToDisplayIndices... | identifier_body |
typegenAutoConfig.ts | : 'string',
Float: 'number',
Boolean: 'boolean',
}
export interface SourceTypeModule {
/**
* The module for where to look for the types. This uses the node resolution algorithm via require.resolve,
* so if this lives in node_modules, you can just provide the module name otherwise you should provide the
... | }
const forceImports = new Set(
objValues(sourceTypeMap)
.concat(typeof contextType === 'string' ? contextType || '' : '')
.map((t) => {
const match = t.match(/^(\w+)\./)
return match ? match[1] : null
})
.filter((f) => f)
)
skipTypes.forEach((... | const importsMap: Record<string, [string, boolean]> = {}
const sourceTypeMap: Record<string, string> = {
...SCALAR_TYPES,
..._sourceTypeMap, | random_line_split |
typegenAutoConfig.ts | 'string',
Float: 'number',
Boolean: 'boolean',
}
export interface SourceTypeModule {
/**
* The module for where to look for the types. This uses the node resolution algorithm via require.resolve,
* so if this lives in node_modules, you can just provide the module name otherwise you should provide the
*... | if (debug) {
log(`Matched type - ${typeName} in "${importPath}" - ${alias}.${matched[1]}`)
}
importsMap[alias] = [importPath, glob]
sourceTypeMap[typeName] = `${alias}.${matched[1]}`
} else {
if (debug) {
log(`No match for... | {
const typeSource = typeSources[i]
if (!typeSource) {
continue
}
// If we've specified an array of "onlyTypes" to match ensure the
// `typeName` falls within that list.
if (typeSource.onlyTypes) {
if (
!typeSource.onlyTyp... | conditional_block |
typegenAutoConfig.ts | 'string',
Float: 'number',
Boolean: 'boolean',
}
export interface SourceTypeModule {
/**
* The module for where to look for the types. This uses the node resolution algorithm via require.resolve,
* so if this lives in node_modules, you can just provide the module name otherwise you should provide the
*... | const forceImports = new Set(
objValues(sourceTypeMap)
.concat(typeof contextType === 'string' ? contextType || '' : '')
.map((t) => {
const match = t.match(/^(\w+)\./)
return match ? match[1] : null
})
.filter((f) => f)
)
skipTypes.forEach((skip) =... | {
return async (schema: GraphQLSchema, outputPath: string): Promise<TypegenInfo> => {
const {
headers,
skipTypes = ['Query', 'Mutation', 'Subscription'],
mapping: _sourceTypeMap,
debug,
} = options
const typeMap = schema.getTypeMap()
const typesToIgnore = new Set<string>()
... | identifier_body |
typegenAutoConfig.ts | 'string',
Float: 'number',
Boolean: 'boolean',
}
export interface SourceTypeModule {
/**
* The module for where to look for the types. This uses the node resolution algorithm via require.resolve,
* so if this lives in node_modules, you can just provide the module name otherwise you should provide the
*... | (options: SourceTypesConfigOptions, contextType: TypingImport | undefined) {
return async (schema: GraphQLSchema, outputPath: string): Promise<TypegenInfo> => {
const {
headers,
skipTypes = ['Query', 'Mutation', 'Subscription'],
mapping: _sourceTypeMap,
debug,
} = options
const ty... | typegenAutoConfig | identifier_name |
csbref.go | }, {5425, 2838}}}
var possibleMapCount = len(possibleMaps)
func (p *point) dot(n point) float64 {
return p.x*n.x + p.y*n.y
}
func (p *point) norm() float64 {
return (math.Sqrt(((p.x * p.x) + (p.y * p.y))))
}
func (g *game) nextTurn() {
t := 1.0
curps := [4]point{g[0].p, g[1].p, g[2].p, g[3].p}
for t > 0.0 {
f... | ob.s.x += -impulse.x * m2
ob.s.y += -impulse.y * m2
if dd <= 800 {
dd -= 800
oa.p.x += (normal.x * -(-dd/2 + EPSILON))
oa.p.y += (normal.y * -(-dd/2 + EPSILON))
ob.p.x += (normal.x * (-dd/2 + EPSILON))
ob.p.y += (normal.y * (-dd/2 + EPSILON))
}
}
func getAngle(start point, end point) float64 {
dx := (e... | impulse := normal
impulse.x *= -force
impulse.y *= -force
oa.s.x += impulse.x * m1
oa.s.y += impulse.y * m1 | random_line_split |
csbref.go | {5425, 2838}}}
var possibleMapCount = len(possibleMaps)
func (p *point) dot(n point) float64 {
return p.x*n.x + p.y*n.y
}
func (p *point) norm() float64 {
return (math.Sqrt(((p.x * p.x) + (p.y * p.y))))
}
func (g *game) nextTurn() {
t := 1.0
curps := [4]point{g[0].p, g[1].p, g[2].p, g[3].p}
for t > 0.0 {
fir... |
}
func getAngle(start point, end point) float64 {
dx := (end.x - start.x)
dy := (end.y - start.y)
a := (math.Atan2(dy, dx))
return a
}
func distance2(p1 point, p2 point) distanceSqType {
x := distanceSqType(p2.x - p1.x)
x = x * x
y := distanceSqType(p2.y - p1.y)
y = y * y
return x + y
}
func distance(p1 p... | {
dd -= 800
oa.p.x += (normal.x * -(-dd/2 + EPSILON))
oa.p.y += (normal.y * -(-dd/2 + EPSILON))
ob.p.x += (normal.x * (-dd/2 + EPSILON))
ob.p.y += (normal.y * (-dd/2 + EPSILON))
} | conditional_block |
csbref.go | py float64
var thrust string
var t int
scanner.Scan()
fmt.Sscan(scanner.Text(), &px, &py, &thrust)
t, err := strconv.Atoi(thrust)
if err != nil {
t = 0
if thrust == "SHIELD" {
g[i].shieldtimer = 4
} else if thrust == "BOOST" {
t = 650
if g[i].boosted == 0 {
g[i].boost... | {
pm := [2]playerMove{}
valid := true
fmt.Printf("###Output %d 2\n", player)
for i := range pm {
if scanner.Scan() == false {
os.Exit(0)
}
var thrust string
fmt.Sscanf(scanner.Text(), "%f %f %s\n", &pm[i].target.x, &pm[i].target.y, &thrust)
pm[i].thrust = 0
switch thrust {
case "SHIELD":
pm[i].... | identifier_body | |
csbref.go | t = 0
if thrust == "SHIELD" {
g[i].shieldtimer = 4
} else if thrust == "BOOST" {
t = 650
if g[i].boosted == 0 {
g[i].boosted = 1
} else {
t = 200
}
}
}
if g[i].shieldtimer > 0 {
t = 0
}
dest := point{px, py}
if dest == g[i].p {
continue
}
... | outputSetup | identifier_name | |
mod.rs | Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.
//! Handling of communication with Buttplug Server.
pub mod messagesorter;
#[cfg(any(feature = "client-ws", feature = "client-ws-ssl"))]
pub mod websocket;
#[cfg(feature... | (&self) -> Sender<ButtplugRemoteClientConnectorMessage> {
self.remote_send.clone()
}
pub async fn send(
&mut self,
msg: &ButtplugMessageUnion,
state: &ButtplugClientMessageStateShared,
) {
self.internal_send.send((msg.clone(), state.clone())).await;
}
pub as... | get_remote_send | identifier_name |
mod.rs | -ws-ssl"))]
pub mod websocket;
#[cfg(feature = "server")]
use crate::server::ButtplugServer;
use crate::{
client::internal::{
ButtplugClientFuture, ButtplugClientFutureState, ButtplugClientFutureStateShared,
ButtplugClientMessageStateShared,
},
core::messages::ButtplugMessageUnion,
};
use a... | {
remote_sender.send(buttplug_fut_msg.0.clone());
} | conditional_block | |
mod.rs | Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.
//! Handling of communication with Buttplug Server.
pub mod messagesorter;
#[cfg(any(feature = "client-ws", feature = "client-ws-ssl"))]
pub mod websocket;
#[cfg(feature... | // We use two Options instead of an enum because we may never
// get anything.
let mut stream_return: StreamValue = async {
match remote_recv.next().await {
Some(msg) => StreamValue::Incoming(msg),
None =... | loop { | random_line_split |
mod.rs | Labs LLC. All rights reserved.
//
// Licensed under the BSD 3-Clause license. See LICENSE file in the project root
// for full license information.
//! Handling of communication with Buttplug Server.
pub mod messagesorter;
#[cfg(any(feature = "client-ws", feature = "client-ws-ssl"))]
pub mod websocket;
#[cfg(feature... | loop {
// We use two Options instead of an enum because we may never
// get anything.
let mut stream_return: StreamValue = async {
match remote_recv.next().await {
Some(msg) => StreamValue::Incoming(msg),
... | {
// Set up a way to get futures in and out of the sorter, which will live
// in our connector task.
let event_send = self.event_send.take().unwrap();
// Remove the receivers we need to move into the task.
let mut remote_recv = self.remote_recv.take().unwrap();
let mut i... | identifier_body |
main.rs | distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate clap;
extern crate env_logger;
extern crate habitat_core a... | ;
// To allow multiple instances of Habitat application in Kubernetes,
// random suffix in metadata_name is needed.
let metadata_name = format!(
"{}-{}{}",
pkg_ident.name,
rand::thread_rng()
.gen_ascii_chars()
.filter(|c| c.is_lowercase() || c.is_numeric())
... | {
PackageIdent::from_str(pkg_ident_str)?
} | conditional_block |
main.rs | distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate clap;
extern crate env_logger;
extern crate habitat_core a... | (ui: &mut UI) -> Result<()> {
let m = cli().get_matches();
debug!("clap cli args: {:?}", m);
if !m.is_present("NO_DOCKER_IMAGE") {
gen_docker_img(ui, &m)?;
}
gen_k8s_manifest(ui, &m)
}
fn gen_docker_img(ui: &mut UI, matches: &clap::ArgMatches) -> Result<()> {
let default_channel = chan... | start | identifier_name |
main.rs | IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
extern crate clap;
extern crate env_logger;
extern crate habitat_core as hcore;
extern crate habitat_common as common;
extern ... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.