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 |
|---|---|---|---|---|
sevencow.py | '%s:%s:%s' % (self.access_key, token, info)
class Cow(object):
def __init__(self, access_key, secret_key):
self.access_key = access_key
self.secret_key = secret_key
self.upload_tokens = {}
self.stat = functools.partial(self._stat_rm_handler, 'stat')
self... | ucket, args[0])
@transform_argument
def delete(self, *args):
return self.cow.delete(self.bucket, args[0])
@transform_argument
def copy(self, *args):
return self.cow.copy(self._build_cp_mv_args(args[0]))
@transform_argument
def move(self, *args):
return self.cow... | identifier_body | |
sevencow.py | .qbox.me'
UP_HOST = 'http://up.qbox.me'
RSF_HOST = 'http://rsf.qbox.me'
class CowException(Exception):
def __init__(self, url, status_code, reason, content):
self.url = url
self.status_code = status_code
self.reason = reason
self.content = content
Exception.__init__(self, '... | = '%s/upload' % UP_HOST
token = self.generate_upload_token(scope)
names = names or {}
def _uploaded_name(filename):
return names.get(filename, None) or os.path.basename(filename)
def _put(filename):
files = {
'file': (filename, open(filen... | rl | identifier_name |
class_vertice_graph.py | .gare_name = None #nom de la gare
self.color = None #couleur de la gare
self.is_a_station= True # boolean True, si le noeud est veritablement une gare. False sinon
def get_lines_connected(self):
list_of_line = []
for edge in self._edges_list:
if edge.id not in list_of_li... | (self, edges_list):
""" An element of edges_list is an edge """
for e in edges_list:
exceptions.check_pertinent_edge(self, e)
self._edges_list = edges_list
def neighbours_list(self, list_tuple, id=0):
self._edges_list.clear()
"""interface with old constructor , t... | edges_list | identifier_name |
class_vertice_graph.py | self.gare_name = None #nom de la gare
self.color = None #couleur de la gare
self.is_a_station= True # boolean True, si le noeud est veritablement une gare. False sinon
def get_lines_connected(self):
list_of_line = []
for edge in self._edges_list:
if edge.id not in list_... | self.number_of_edges=0
def push_diplayable_edge(self,bidim_array):
self.connection_table_edge_and_diplayable_edge.append(copy.deepcopy(bidim_array))
self.number_of_disp_edges+=1
def push_edge(self,e):
self.number_of_edges+=1
self.list_of_edges.append(e)
def push_edg... | self.number_of_vertices = len(list_of_vertices)
self.connection_table_edge_and_diplayable_edge=[]
self.list_of_edges=[]
self.number_of_disp_edges=0 | random_line_split |
class_vertice_graph.py | (self):
list_of_line = []
for edge in self._edges_list:
if edge.id not in list_of_line:
list_of_line.append(edge.id)
return list_of_line
@property
def edges_list(self):
""" Returns the list of neighbour. """
return self._edges_list
# We s... | pairs_of_vertices.append((vertice, edge.linked[1])) | conditional_block | |
class_vertice_graph.py | .gare_name = None #nom de la gare
self.color = None #couleur de la gare
self.is_a_station= True # boolean True, si le noeud est veritablement une gare. False sinon
def get_lines_connected(self):
list_of_line = []
for edge in self._edges_list:
if edge.id not in list_of_li... |
def is_vertice_in_graph_based_on_xy_with_tolerance(self, vertice, epsilon):
for i in range(self.number_of_vertices):
v = self.list_of_vertices[i]
if ((v.coordinates[0] - vertice.coordinates[0])**2) + ((v.coordinates[1] - vertice.coordinates[1])**2) < epsilon:
return... | for i in range(self.number_of_vertices):
v = self.list_of_vertices[i]
if v.coordinates[0] == vertice.coordinates[0] and v.coordinates[1] == vertice.coordinates[1]:
return True,i
return False,None | identifier_body |
build.rs |
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set"));
let kernel = PathBuf::from(match env::var("KERNEL") {
Ok(kernel) => kernel,
Err(_) => {
eprintln!(
"The KERNEL environment variable must be set for building the bootl... | {
panic!(
"The {} bootloader must be compiled for the `{}` target.",
firmware, expected_target,
);
} | conditional_block | |
build.rs | of stripped kernel")
.len();
file.write_all(
format!(
"const KERNEL_SIZE: usize = {}; const KERNEL_BYTES: [u8; KERNEL_SIZE] = *include_bytes!(r\"{}\");",
kernel_size,
stripped_kernel.display(),
)
... | AlignedAddressVisitor | identifier_name | |
build.rs | kernel.display()
);
// get access to llvm tools shipped in the llvm-tools-preview rustup component
let llvm_tools = match llvm_tools::LlvmTools::new() {
Ok(tools) => tools,
Err(llvm_tools::Error::NotFound) => {
eprintln!("Error: llvm-tools not... | // Parse configuration from the kernel's Cargo.toml
let config = match env::var("KERNEL_MANIFEST") {
Err(env::VarError::NotPresent) => {
panic!("The KERNEL_MANIFEST environment variable must be set for building the bootloader.\n\n\
Please use `cargo builder` ... | kernel_file_name
);
}
| random_line_split |
state.rs | new_min.as_()
+ (new_max.as_() - new_min.as_())
* ((value - old_min.as_()) / (old_max.as_() - old_min.as_()))
}
pub fn remap_minz<
T: 'static + Float + Copy + AsPrimitive<T>,
OX: AsPrimitive<T> + Copy,
NX: AsPrimitive<T> + Copy,
>(
value: T,
old_max: OX,
new_max: NX,
) -> T... |
pub fn mouse_motion(&mut self, dx: i32) {
self.angle += MOUSE_SENSITIVITY * dx as f64;
}
fn calculate_collisions(&mut self) {
let mut current_angle = self.angle - (self.fov.to_radians() / 2.);
let end_angle = current_angle + (self.radian_per_column * self.resolution as f64);
... | {
self.wall_colors.get(index).copied().unwrap_or(Color::WHITE)
} | identifier_body |
state.rs | new_min.as_()
+ (new_max.as_() - new_min.as_())
* ((value - old_min.as_()) / (old_max.as_() - old_min.as_()))
}
pub fn remap_minz<
T: 'static + Float + Copy + AsPrimitive<T>,
OX: AsPrimitive<T> + Copy,
NX: AsPrimitive<T> + Copy,
>(
value: T,
old_max: OX,
new_max: NX,
) -... | pub fn update(&mut self) {
self.update_camera();
self.calculate_collisions();
}
pub fn draw_minimap(
&self,
canvas: &mut Canvas<Window>,
dims: (f64, f64),
) -> Result<(), String> {
let minimap_offset = (dims.0.max(dims.1) / 4.);
let minimap_base =... |
self.position.add_x_y_raw(delta.x_y());
self.position.clamp(self.map.dims, PLAYER_WALL_PADDING);
}
| random_line_split |
state.rs | new_min.as_()
+ (new_max.as_() - new_min.as_())
* ((value - old_min.as_()) / (old_max.as_() - old_min.as_()))
}
pub fn remap_minz<
T: 'static + Float + Copy + AsPrimitive<T>,
OX: AsPrimitive<T> + Copy,
NX: AsPrimitive<T> + Copy,
>(
value: T,
old_max: OX,
new_max: NX,
) -> T... |
}
if max_height.is_infinite() {
self.columns.push((0, 0));
} else {
self.columns
.push((wall_color_index, max_height.round() as u32));
}
current_angle += self.radian_per_column;
}
}
fn upda... | {
let raw_distance = ray.dist(&intersection_vector);
let delta = current_angle - self.angle;
let corrected_distance = raw_distance * (delta.cos() as f64);
let projected_height = self.projection_factor / corrected_distance;
... | conditional_block |
state.rs | ),
Color::RGB(255, 0, 128),
Color::RGB(0, 255, 0),
Color::RGB(0, 0, 255),
Color::WHITE,
];
// let map = Map::default();
let map = Map::load("./assets/maps/many_walls.json").unwrap();
let (w, h) = map.dims;
// let movement_vector = ... | draw | identifier_name | |
opdb.rs | row, &CfNameTypeCode::HaNodesInfo.get())?;
Ok(())
}
///
/// 编辑节点信息
pub fn edit(&mut self, info: &web::Json<EditInfo>) {
self.host = info.host.clone();
self.dbport = info.dbport.clone();
self.cluster_name = info.cluster_name.clone();
self.update_time = crate::time... | eCode::NodesState.get())?;
Ok(())
}
}
///
///
/// slave behind 配置结构体
#[derive(Serialize, Deserialize, Debug)]
pub struct SlaveBehindSetting{
| conditional_block | |
opdb.rs | ata: web::Data<DbInfo>, info: &web::Json<HostInfo>) -> Result<(), Box<dyn Error>> {
let check_unique = data.get(&info.host, &CfNameTypeCode::HaNodesInfo.get());
match check_unique {
Ok(v) => {
if v.value.len() > 0 {
let a = format!("this key: ({}) already exists in the databa... | sert_mysql_host_info(d | identifier_name | |
opdb.rs | 之前未进行binlog追加将保存新master读取到的binlog信息,在宕机节点恢复时会进行判断回滚
pub recovery_info: RecoveryInfo, //宕机恢复同步所需的新master信息
pub recovery_status: bool, //是否已恢复
pub switch_status: bool, //切换状态
}
impl HaChangeLog {
pub fn new() -> HaChangeLog {
HaChangeLog{
key: "".to_... | }
self.update_time = crate::timestamp();
}
///
/// 获取当前节点在db中保存的状态信息
pub fn get_state(&self, db: &web::Data<DbInfo>) -> Result<MysqlState, Box<dyn Error>> {
let kv = db.get(&self.host, &CfNameTypeCode::NodesState.get())?;
if kv.value.len() > 0 {
let state: My... | if info.maintain == "true".to_string() {
self.maintain = false;
}else {
self.maintain = true; | random_line_split |
opdb.rs | 未进行binlog追加将保存新master读取到的binlog信息,在宕机节点恢复时会进行判断回滚
pub recovery_info: RecoveryInfo, //宕机恢复同步所需的新master信息
pub recovery_status: bool, //是否已恢复
pub switch_status: bool, //切换状态
}
impl HaChangeLog {
pub fn new() -> HaChangeLog {
HaChangeLog{
key: "".to_st... | ult 3306
pub rtype: String, //db、route
pub cluster_name: String, //集群名称,route类型默认default
pub online: bool, //db是否在线, true、false
pub insert_time: i64,
pub update_time: i64,
pub maintain: bool, //是否处于维护模式,true、false
}
impl HostInfoValue {
pub fn new(info: &HostInfo) -> Result<HostInfoVal... | o.password.clone(),
hook_id: rand_string(),
create_time,
update_time
}
}
}
///
///
///
/// 节点基础信息, host做为key
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct HostInfoValue {
pub host: String, //127.0.0.1:3306
pub dbport: usize, //defa | identifier_body |
server_impl.go | },
writeRequest: &requestWrite{
ask: make(chan []byte),
connId: make(chan int),
response: make(chan error),
},
readList: list.New(),
writeList: list.New(),
flag: false,
// variables for window size
windowSize: params.WindowSize,
mapNeedSend: list.New(),
// variables for epoch
... |
func (s *server) sendData(dataMsg *Message) {
s.writeToClientChan <- dataMsg
}
func (s *server) addEpochNum() {
for connId, c := range s.clients {
c.epochNum += 1
if c.epochNum >= s.epochLimit {
c.lostConn = true
s.sendDeadMsg(connId)
}
}
}
func (s *server) sendDeadMsg(connId int) {
dataMsg := NewDa... | {
//////fmt.Println(connID)
client := s.clients[connID]
dataMsg := NewData(connID, client.nextSN, payload, payload)
////fmt.Println("Server: 197 write ", dataMsg)
go s.sendData(dataMsg)
client.nextSN += 1
return nil
} | identifier_body |
server_impl.go | : make(chan int),
epochMillis: params.EpochMillis,
epochLimit: params.EpochLimit,
// close
deleteClient: make(chan int),
closeConnRequest: &requestCloseConn{
ask: make(chan int),
getError: make(chan error),
},
waitToWriteFinish: false,
writeFinished: make(chan int),
waitToAckFinish:... | {
s.readList.PushBack(msg)
} | conditional_block | |
server_impl.go | fmt.Println("Server epoch: ", msg)
s.writeToClient(msg)
}
}
}
}
func (s *server) handleReadRequest() {
msg := s.getMessageFromReadList()
if msg != nil {
//////fmt.Println("101 no message")
/*elm := s.readList.Front()
msg := elm.Value.(*Message)*/
s.readRequest.response <- msg
} else {
s.fla... | Close | identifier_name | |
server_impl.go | ),
},
writeRequest: &requestWrite{
ask: make(chan []byte),
connId: make(chan int),
response: make(chan error),
},
readList: list.New(),
writeList: list.New(),
flag: false,
// variables for window size
windowSize: params.WindowSize,
mapNeedSend: list.New(),
// variables for epoch... | if s.waitToWriteFinish && s.writeList.Len() == 0 {
s.writeFinished <- 1
s.waitToWriteFinish = false
}
case <-s.readRequest.ask:
s.handleReadRequest()
case payload := <-s.writeRequest.ask:
connId := <-s.writeRequest.connId
var response = s.handleWriteRequest(connId, payload)
s.writeRequest.... | // ack/conn type: don't need to consider order
s.writeToClient(msg)
}
| random_line_split |
simulation.py | ride data
DATETIME_FORMAT = '%Y-%m-%d %H:%M'
#Function constants for reporting beggining and ending of rides
RIDE_BEGUN = True
RIDE_FINISHED = False
# Stock issues report
SUCCESSFUL_REPORT = 0
EMPTY_STATION_ISSUE = 1
FULL_STATION_ISSUE = 2
class Simulation:
"""Runs the core of the simulation through time.
=... | 'max_end': ('', -1),
'max_time_low_availability': ('', -1),
'max_time_low_unoccupied': ('', -1)
}
return {
'max_start': ('', -1),
'max_end': ('', -1),
'max_time_low_availability': ('', -1),
'max_time_low_unoccupied': ... | """Return a dictionary containing statistics for this simulation.
The returned dictionary has exactly four keys, corresponding
to the four statistics tracked for each station:
- 'max_start'
- 'max_end'
- 'max_time_low_availability'
- 'max_time_low_unoccupied'
... | identifier_body |
simulation.py | ride data
DATETIME_FORMAT = '%Y-%m-%d %H:%M'
#Function constants for reporting beggining and ending of rides
RIDE_BEGUN = True
RIDE_FINISHED = False
# Stock issues report
SUCCESSFUL_REPORT = 0
EMPTY_STATION_ISSUE = 1
FULL_STATION_ISSUE = 2
class | :
"""Runs the core of the simulation through time.
=== Attributes ===
all_rides:
A list of all the rides in this simulation.
Note that not all rides might be used, depending on the timeframe
when the simulation is run.
all_stations:
A dictionary containing all the statio... | Simulation | identifier_name |
simulation.py | ride data
DATETIME_FORMAT = '%Y-%m-%d %H:%M'
#Function constants for reporting beggining and ending of rides
RIDE_BEGUN = True
RIDE_FINISHED = False
# Stock issues report
SUCCESSFUL_REPORT = 0
EMPTY_STATION_ISSUE = 1
FULL_STATION_ISSUE = 2
class Simulation:
"""Runs the core of the simulation through time.
=... | 'max_end': ('', -1),
'max_time_low_availability': ('', -1),
'max_time_low_unoccupied': ('', -1)
}
def _update_active_rides_fast(self, time: datetime) -> None:
"""Update this simulation's list of active rides for the given time.
REQUIRED IMPLEMENTATION NO... | 'max_start': ('', -1), | random_line_split |
simulation.py | ride data
DATETIME_FORMAT = '%Y-%m-%d %H:%M'
#Function constants for reporting beggining and ending of rides
RIDE_BEGUN = True
RIDE_FINISHED = False
# Stock issues report
SUCCESSFUL_REPORT = 0
EMPTY_STATION_ISSUE = 1
FULL_STATION_ISSUE = 2
class Simulation:
"""Runs the core of the simulation through time.
=... |
def _update_active_rides(self, time: datetime) -> None:
"""Update this simulation's list of active rides for the given time.
REQUIRED IMPLEMENTATION NOTES:
- Loop through `self.all_rides` and compare each Ride's start and
end times with <time>.
If <time> is betw... | if self.visualizer.handle_window_events():
return # Stop the simulation | conditional_block |
conn.rs | Sender, UnboundedReceiver, UnboundedSender};
use tokio_core::net::TcpStream;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::io::{read_exact, write_all};
use tokio_timer::{Timer, TimerError};
use core::core::hash::Hash;
use core::ser;
use msg::*;
use types::Error;
use rate_limit::*;
use util::LOGGER;
/// Handler... | <W: ser::Writeable>(&self, t: Type, body: &W) -> Result<(), Error> {
let mut body_data = vec![];
try!(ser::serialize(&mut body_data, body));
let mut data = vec![];
try!(ser::serialize(
&mut data,
&MsgHeader::new(t, body_data.len() as u64),
));
data.append(&mut body_data);
self.outbound_chan
.unb... | send_msg | identifier_name |
conn.rs | Sender, UnboundedReceiver, UnboundedSender};
use tokio_core::net::TcpStream;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::io::{read_exact, write_all};
use tokio_timer::{Timer, TimerError};
use core::core::hash::Hash;
use core::ser;
use msg::*;
use types::Error;
use rate_limit::*;
use util::LOGGER;
/// Handler... | let (conn, fut) = Connection::listen(conn, move |sender, header: MsgHeader, data| {
let msg_type = header.msg_type;
let recv_h = try!(handler.handle(sender, | // Decorates the handler to remove the "subscription" from the expected
// responses. We got our replies, so no timeout should occur.
let exp = expects.clone(); | random_line_split |
conn.rs | , UnboundedReceiver, UnboundedSender};
use tokio_core::net::TcpStream;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::io::{read_exact, write_all};
use tokio_timer::{Timer, TimerError};
use core::core::hash::Hash;
use core::ser;
use msg::*;
use types::Error;
use rate_limit::*;
use util::LOGGER;
/// Handler to pr... |
}
/// A higher level connection wrapping the TcpStream. Maintains the amount of
/// data transmitted and deals with the low-level task of sending and
/// receiving data, parsing message headers and timeouts.
#[allow(dead_code)]
pub struct Connection {
// Channel to push bytes to the remote peer
outbound_chan: Unbou... | {
self(sender, header, body)
} | identifier_body |
conn.rs | , UnboundedReceiver, UnboundedSender};
use tokio_core::net::TcpStream;
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::io::{read_exact, write_all};
use tokio_timer::{Timer, TimerError};
use core::core::hash::Hash;
use core::ser;
use msg::*;
use types::Error;
use rate_limit::*;
use util::LOGGER;
/// Handler to pr... |
Ok(reader)
})
});
Box::new(read_msg)
}
/// Utility function to send any Writeable. Handles adding the header and
/// serialization.
pub fn send_msg<W: ser::Writeable>(&self, t: Type, body: &W) -> Result<(), Error> {
let mut body_data = vec![];
try!(ser::serialize(&mut body_data, body));
let mu... | {
debug!(LOGGER, "Invalid {:?} message: {}", msg_type, e);
return Err(Error::Serialization(e));
} | conditional_block |
dpkg_install.go | for sync
}
func (p *PackageInfo) Name() string {
// Extract the package name from its section in /var/lib/dpkg/status
return p.Paragraph.Value("Package")
}
func (p *PackageInfo) Version() string {
// Extract the package version from its section in /var/lib/dpkg/status
return p.Paragraph.Value("Version")
}
// is... | (filename string) string {
return filepath.Join("/var/lib/dpkg", p.Name()+"."+filename)
}
// We now add a method to change the package status
// and make sure the section in the status file is updated too.
// This method will be used several times at the different steps
// of the installation process.
func (p *Packa... | InfoPath | identifier_name |
dpkg_install.go | "prerm", "postrm"}
for _, script := range maintainerScripts {
scriptPath := pkg.InfoPath(script)
if _, err := os.Stat(scriptPath); !os.IsNotExist(err) {
content, err := os.ReadFile(scriptPath)
if err != nil {
return nil, err
}
pkg.MaintainerScripts[script] = string(content)
}
}
pack... | {
// This function synchronizes the files under /var/lib/dpkg/info
// for a single package.
// Write <package>.list
if err := os.WriteFile(p.InfoPath("list"),
[]byte(MergeLines(p.Files)), 0644); err != nil {
return err
}
// Write <package>.conffiles
if err := os.WriteFile(p.InfoPath("conffiles"),
[]byte(... | identifier_body | |
dpkg_install.go | for sync
}
func (p *PackageInfo) Name() string {
// Extract the package name from its section in /var/lib/dpkg/status
return p.Paragraph.Value("Package")
}
func (p *PackageInfo) Version() string {
// Extract the package version from its section in /var/lib/dpkg/status
return p.Paragraph.Value("Version")
}
// is... | var bufControl bytes.Buffer
io.Copy(&bufControl, reader)
pkg, err := parseControl(db, bufControl)
if err != nil {
return err
}
// Add the new package in the database
db.Packages = append(db.Packages, pkg)
db.Sync()
// data.tar
reader.Next()
var bufData bytes.Buffer
io.Copy(&bufData, reader)
fmt.Print... |
// control.tar
reader.Next() | random_line_split |
dpkg_install.go | for sync
}
func (p *PackageInfo) Name() string {
// Extract the package name from its section in /var/lib/dpkg/status
return p.Paragraph.Value("Package")
}
func (p *PackageInfo) Version() string {
// Extract the package version from its section in /var/lib/dpkg/status
return p.Paragraph.Value("Version")
}
// is... |
// Add the new package in the database
db.Packages = append(db.Packages, pkg)
db.Sync()
// data.tar
reader.Next()
var bufData bytes.Buffer
io.Copy(&bufData, reader)
fmt.Printf("Preparing to unpack %s ...\n", filepath.Base(archivePath))
if err := pkg.Unpack(bufData); err != nil {
return err
}
if err :=... | {
return err
} | conditional_block |
clarans.py | list of points (objects), each point should be represented by list or tuple.
@param[in] number_clusters (uint): Amount of clusters that should be allocated.
@param[in] numlocal (uint): The number of local minima obtained (amount of iterations for solving the problem).
@param[in] maxneighbor ... | """!
@brief Finds the another nearest medoid for the specified point that is different from the specified medoid.
@param[in] point_index: index of point in dataspace for that searching of medoid in current list of medoids is perfomed.
@param[in] current_medoid_index: index of medoid that sh... | identifier_body | |
clarans.py | s=500, color="red", marker="X", edgecolor="black")
xmin, xmax, ymin, ymax = plt.axis()
xwidth = xmax - xmin
ywidth = ymax - ymin
xw1 = xwidth*0.01
yw1 = ywidth*0.01
xw2 = xwidth*0.005
yw2 = ywidth*0.01
xw3 = xwidth*0.01
yw3 = ywidth*0.01
for i, txt in enumera... | candidate_cost += distance_nearest - distance_current | conditional_block | |
clarans.py | :"seagreen", 1:'beige', 2:'yellow', 3:'grey',
4:'pink', 5:'turquoise', 6:'orange', 7:'purple', 8:'yellowgreen', 9:'olive', 10:'brown',
11:'tan', 12: 'plum', 13:'rosybrown', 14:'lightblue', 15:"khaki", 16:"gainsboro", 17:"peachpuff"}
for i,el in enumerate(list(cl.values()))... | (self):
"""!
@brief Returns allocated clusters by the algorithm.
@remark Allocated clusters can be returned only after data processing (use method process()), otherwise empty list is returned.
@return (list) List of allocated clusters, each cluster contains indexes of objects in ... | get_clusters | identifier_name |
clarans.py | :"seagreen", 1:'beige', 2:'yellow', 3:'grey',
4:'pink', 5:'turquoise', 6:'orange', 7:'purple', 8:'yellowgreen', 9:'olive', 10:'brown',
11:'tan', 12: 'plum', 13:'rosybrown', 14:'lightblue', 15:"khaki", 16:"gainsboro", 17:"peachpuff"}
for i,el in enumerate(list(cl.values()))... |
@see get_clusters()
@see get_medoids()
"""
random.seed()
# loop for a numlocal number of times
for _ in range(0, self.__numlocal):
print("numlocal: ", _)
# set (current) random medoids
self.__current = random.sample(ra... | def process(self, plotting=False):
"""!
@brief Performs cluster analysis in line with rules of CLARANS algorithm.
@return (clarans) Returns itself (CLARANS instance).
| random_line_split |
client.rs | }
struct GrpcResponseHandlerTyped<Req : Send + 'static, Resp : Send + 'static> {
method: Arc<MethodDescriptor<Req, Resp>>,
complete: tokio_core::channel::Sender<ResultOrEof<Resp, GrpcError>>,
remaining_response: Vec<u8>,
}
impl<Req : Send + 'static, Resp : Send + 'static> GrpcResponseHandlerTrait for Grpc... |
fn data_frame(&mut self, chunk: Vec<u8>) -> bool {
self.tr.data_frame(chunk)
}
fn trailers(&mut self, headers: Vec<StaticHeader>) -> bool {
self.tr.trailers(headers)
}
fn end(&mut self) {
self.tr.end()
}
}
// Data sent from event loop to GrpcClient
struct LoopToClien... | } | random_line_split |
client.rs | }
struct GrpcResponseHandlerTyped<Req : Send + 'static, Resp : Send + 'static> {
method: Arc<MethodDescriptor<Req, Resp>>,
complete: tokio_core::channel::Sender<ResultOrEof<Resp, GrpcError>>,
remaining_response: Vec<u8>,
}
impl<Req : Send + 'static, Resp : Send + 'static> GrpcResponseHandlerTrait for Grpc... | <Req : Send + 'static, Resp : Send + 'static>(&self, req: GrpcStreamSend<Req>, method: Arc<MethodDescriptor<Req, Resp>>)
-> GrpcFutureSend<Resp>
{
stream_single_send(self.call_impl(req, method))
}
pub fn call_bidi<Req : Send + 'static, Resp : Send + 'static>(&self, req: GrpcStreamSend<Req>,... | call_client_streaming | identifier_name |
client.rs | io_core::channel::Sender<ResultOrEof<Resp, GrpcError>>,
remaining_response: Vec<u8>,
}
impl<Req : Send + 'static, Resp : Send + 'static> GrpcResponseHandlerTrait for GrpcResponseHandlerTyped<Req, Resp> {
}
impl<Req : Send + 'static, Resp : Send + 'static> HttpClientResponseHandler for GrpcResponseHandlerTyped<Req... | {
// ignore error because even loop may be already dead
self.loop_to_client.shutdown_tx.send(()).ok();
// do not ignore errors because we own event loop thread
self.thread_join_handle.take().expect("handle.take")
.join().expect("join thread");
} | identifier_body | |
fixed.rs | }
/// Encodes a value of a particular fixed width type into bytes according to the rules
/// described on [`super::RowConverter`]
pub trait FixedLengthEncoding: Copy {
const ENCODED_LEN: usize = 1 + std::mem::size_of::<Self::Encoded>();
type Encoded: Sized + Copy + FromSlice + AsRef<[u8]> + AsMut<[u8]>;
... | <T>(_col: &PrimitiveArray<T>) -> usize
where
T: ArrowPrimitiveType,
T::Native: FixedLengthEncoding,
{
T::Native::ENCODED_LEN
}
/// Fixed width types are encoded as
///
/// - 1 byte `0` if null or `1` if valid
/// - bytes of [`FixedLengthEncoding`]
pub fn encode<T: FixedLengthEncoding, I: IntoIterator<Item ... | encoded_len | identifier_name |
fixed.rs | }
/// Encodes a value of a particular fixed width type into bytes according to the rules
/// described on [`super::RowConverter`]
pub trait FixedLengthEncoding: Copy {
const ENCODED_LEN: usize = 1 + std::mem::size_of::<Self::Encoded>();
type Encoded: Sized + Copy + FromSlice + AsRef<[u8]> + AsMut<[u8]>;
... |
fn encode(self) -> [u8; 8] {
// https://github.com/rust-lang/rust/blob/9c20b2a8cc7588decb6de25ac6a7912dcef24d65/library/core/src/num/f32.rs#L1176-L1260
let s = self.to_bits() as i64;
let val = s ^ (((s >> 63) as u64) >> 1) as i64;
val.encode()
}
fn decode(encoded: Self::Enc... | impl FixedLengthEncoding for f64 {
type Encoded = [u8; 8]; | random_line_split |
fixed.rs | }
/// Encodes a value of a particular fixed width type into bytes according to the rules
/// described on [`super::RowConverter`]
pub trait FixedLengthEncoding: Copy {
const ENCODED_LEN: usize = 1 + std::mem::size_of::<Self::Encoded>();
type Encoded: Sized + Copy + FromSlice + AsRef<[u8]> + AsMut<[u8]>;
... |
to_write[1..].copy_from_slice(encoded.as_ref())
} else {
data[*offset] = null_sentinel(opts);
}
*offset = end_offset;
}
}
pub fn encode_fixed_size_binary(
data: &mut [u8],
offsets: &mut [usize],
array: &FixedSizeBinaryArray,
opts: SortOptions,
) {
... | {
// Flip bits to reverse order
encoded.as_mut().iter_mut().for_each(|v| *v = !*v)
} | conditional_block |
fixed.rs | }
/// Encodes a value of a particular fixed width type into bytes according to the rules
/// described on [`super::RowConverter`]
pub trait FixedLengthEncoding: Copy {
const ENCODED_LEN: usize = 1 + std::mem::size_of::<Self::Encoded>();
type Encoded: Sized + Copy + FromSlice + AsRef<[u8]> + AsMut<[u8]>;
... |
fn decode(encoded: Self::Encoded) -> Self {
encoded[0] != 0
}
}
macro_rules! encode_signed {
($n:expr, $t:ty) => {
impl FixedLengthEncoding for $t {
type Encoded = [u8; $n];
fn encode(self) -> [u8; $n] {
let mut b = self.to_be_bytes();
... | {
[self as u8]
} | identifier_body |
pop.py | (self, province, pop_job, population):
"""
Creates a new Pop.
manager (Historia)
province (SecondaryDivision)
culture (Culture)
religion (Religion)
language (Language)
job (Job)
"""
self.bankrupt_times = 0
self.home = provinc... | __init__ | identifier_name | |
pop.py | self.price_belief[good] = PriceRange(avg_price * 0.5, avg_price * 1.5)
# Merchant logic
self.trade_location = None # the province this Pop is traveling to
self.trade_good = None # what good we're trading in right now
self.trade_amount = 0 # amount of trade_good we should be trading
... |
def generate_orders(self, good):
"""
If the Pop needs a Good to perform production, buy it
If the Pop has surplus Resources, sell them
"""
surplus = self.inventory.surplus(good)
if surplus >= 1: # sell inventory
# the original only old one item here
... | "Determine how much goods to buy based on market conditions"
mean = self.market.avg_historial_price(good, 15)
trading_range = self.trading_range_extremes(good)
favoribility = 1 - position_in_range(mean, trading_range.low, trading_range.high)
amount_to_buy = round(favoribility * self.inv... | identifier_body |
pop.py | .price_belief[good] = PriceRange(avg_price * 0.5, avg_price * 1.5)
# Merchant logic
self.trade_location = None # the province this Pop is traveling to
self.trade_good = None # what good we're trading in right now
self.trade_amount = 0 # amount of trade_good we should be trading
... |
neighboring_markets = [p.market for p in self.location.owned_neighbors]
neighboring_markets = [m for m in neighboring_markets if m.supply_for(good) > self.trade_amount]
neighboring_markets.sort(key=lambda m: m.supply_for(good), reverse=True)
if len(neigh... | print("Good: {}, Demand: {}, Price: ${}".format(good.title, demand, price_at_home)) | conditional_block |
pop.py | self.price_belief = {}
# a dictionary of Goods to price list
# represents the prices of the good that the Pop has observed
# during the time they have been trading
self.observed_trading_range = {}
self.successful_trades = 0
self.failed_trades = 0
# make... | # represents the price range the agent considers valid for each Good | random_line_split | |
server.go | reflector server pointer.
func NewServer(underlying store.BlobStore, outer store.BlobStore) *Server {
return &Server{
Timeout: DefaultTimeout,
underlyingStore: underlying,
outerStore: outer,
grp: stop.New(),
}
}
// Shutdown shuts down the reflector server gracefully.
func (s *Server... | else if handshake.Version == nil {
return errors.Err("handshake is missing protocol version")
} else if *handshake.Version != protocolVersion1 && *handshake.Version != protocolVersion2 {
return errors.Err("protocol version not supported")
}
resp, err := json.Marshal(handshakeRequestResponse{Version: handshake.... | {
return err
} | conditional_block |
server.go | reflector server pointer.
func NewServer(underlying store.BlobStore, outer store.BlobStore) *Server {
return &Server{
Timeout: DefaultTimeout,
underlyingStore: underlying,
outerStore: outer,
grp: stop.New(),
}
}
// Shutdown shuts down the reflector server gracefully.
func (s *Server... |
func (s *Server) handleConn(conn net.Conn) {
// all this stuff is to close the connections correctly when we're shutting down the server
connNeedsClosing := make(chan struct{})
defer func() {
close(connNeedsClosing)
}()
s.grp.Add(1)
metrics.RoutinesQueue.WithLabelValues("reflector", "server-handleconn").Inc()... | {
for {
conn, err := listener.Accept()
if err != nil {
if s.quitting() {
return
}
log.Error(err)
} else {
s.grp.Add(1)
metrics.RoutinesQueue.WithLabelValues("reflector", "server-listenandserve").Inc()
go func() {
defer metrics.RoutinesQueue.WithLabelValues("reflector", "server-listenand... | identifier_body |
server.go | reflector", "start").Inc()
go func() {
defer metrics.RoutinesQueue.WithLabelValues("reflector", "start").Dec()
s.listenAndServe(l)
s.grp.Done()
}()
if s.EnableBlocklist {
if b, ok := s.underlyingStore.(store.Blocklister); ok {
s.grp.Add(1)
metrics.RoutinesQueue.WithLabelValues("reflector", "enablebloc... | }
| random_line_split | |
server.go | reflector server pointer.
func NewServer(underlying store.BlobStore, outer store.BlobStore) *Server {
return &Server{
Timeout: DefaultTimeout,
underlyingStore: underlying,
outerStore: outer,
grp: stop.New(),
}
}
// Shutdown shuts down the reflector server gracefully.
func (s *Server... | (conn net.Conn) error {
var handshake handshakeRequestResponse
err := s.read(conn, &handshake)
if err != nil {
return err
} else if handshake.Version == nil {
return errors.Err("handshake is missing protocol version")
} else if *handshake.Version != protocolVersion1 && *handshake.Version != protocolVersion2 {
... | doHandshake | identifier_name |
mod.rs | DurationVisitor;
impl<'de> de::Visitor<'de> for DurationVisitor {
type Value = Duration;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Duration as u64")
}
fn visit_u64<E>(self, v: u64) -> std::result::Result<Self::Value, ... | (
sender: AccountAddress,
sequence_number: u64,
script: Script,
max_gas_amount: u64,
gas_unit_price: u64,
expiration_time: Duration,
) -> Self {
RawUserTransaction {
sender,
sequence_number,
payload: TransactionPayload::Scri... | new_script | identifier_name |
mod.rs | expiration_time: Duration,
}
// TODO(#1307)
fn serialize_duration<S>(d: &Duration, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
serializer.serialize_u64(d.as_secs())
}
fn deserialize_duration<'de, D>(deserializer: D) -> std::result::Result<Duration, D::Error>
where
... | // A transaction that doesn't expire is represented by a very large value like
// u64::max_value().
#[serde(serialize_with = "serialize_duration")]
#[serde(deserialize_with = "deserialize_duration")] | random_line_split | |
mod.rs | Visitor;
impl<'de> de::Visitor<'de> for DurationVisitor {
type Value = Duration;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("Duration as u64")
}
fn visit_u64<E>(self, v: u64) -> std::result::Result<Self::Value, E>
... |
pub fn sender(&self) -> AccountAddress {
self.raw_txn.sender
}
pub fn into_raw_transaction(self) -> RawUserTransaction {
self.raw_txn
}
pub fn sequence_number(&self) -> u64 {
self.raw_txn.sequence_number
}
pub fn payload(&self) -> &TransactionPayload {
&s... | {
&self.raw_txn
} | identifier_body |
sorting.go | .sorted.topics = map[string][]sortedTriggerEntry{}
rs.sorted.thats = map[string][]sortedTriggerEntry{}
rs.say("Sorting triggers...")
// If there are no topics, give an error.
if len(rs.topics) == 0 {
return errors.New("SortReplies: no topics were found; did you load any RiveScript code?")
}
// Loop through al... | (dict map[string]string) []string {
output := []string{}
// Track by number of words.
track := map[int][]string{}
// Loop through each item | sortList | identifier_name |
sorting.go | ]*sortTrack{}
track[inherits] = initSortTrack()
// Loop through all the triggers.
for _, trig := range prior[p] {
pattern := trig.trigger
rs.say("Looking at trigger: %s", pattern)
// See if the trigger has an {inherits} tag.
match := reInherits.FindStringSubmatch(pattern)
if len(match) > 0 {
... | {
return &sortTrack{
atomic: map[int][]sortedTriggerEntry{},
option: map[int][]sortedTriggerEntry{},
alpha: map[int][]sortedTriggerEntry{},
number: map[int][]sortedTriggerEntry{},
wild: map[int][]sortedTriggerEntry{},
pound: []sortedTriggerEntry{},
under: []sortedTriggerEntry{},
star: []sortedTr... | identifier_body | |
sorting.go | .sorted.topics = map[string][]sortedTriggerEntry{}
rs.sorted.thats = map[string][]sortedTriggerEntry{}
rs.say("Sorting triggers...")
// If there are no topics, give an error.
if len(rs.topics) == 0 {
return errors.New("SortReplies: no topics were found; did you load any RiveScript code?")
}
// Loop through al... | track[inherits].atomic[cnt] = append(track[inherits].atomic[cnt], trig)
}
}
// Move the no-{inherits} triggers to the bottom of the stack.
track[highestInherits+1] = track[-1]
delete(track, -1)
// Sort the track from the lowest to the highest.
var trackSorted []int
for k := range track {
track... | rs.say("Totally atomic trigger with %d words", cnt)
if _, ok := track[inherits].atomic[cnt]; !ok {
track[inherits].atomic[cnt] = []sortedTriggerEntry{}
} | random_line_split |
sorting.go | p)
// So, some of these triggers may include an {inherits} tag, if they
// came from a topic which inherits another topic. Lower inherits values
// mean higher priority on the stack. Triggers that have NO inherits
// value at all (which will default to -1), will be moved to the END of
// the stack at the en... | {
continue
} | conditional_block | |
app.js | s*");
nameOne = re.exec(nameOne)[0];
nameTwo = re.exec(nameTwo)[0];
P1NAME = nameOne;
P2NAME = nameTwo;
coupleName = this.nameMash (nameOne, nameTwo);
COMBONAME = coupleName;
document.getElementById("player-1").innerHTML = (nameOne + "'s Score is:");
document.getElementById("player-2").innerHT... |
else {
trendValue2 = 1;
}
trendValue1 ? SCORE[0] += Math.round(trendValue1) : null;
trendValue2 ? SCORE[1] += Math.round(trendValue2) : null;
scoreRender();
}
}
function scoreRender () {
| {
trendValue2 = 5;
} | conditional_block |
app.js | s*");
nameOne = re.exec(nameOne)[0];
nameTwo = re.exec(nameTwo)[0];
P1NAME = nameOne;
P2NAME = nameTwo;
coupleName = this.nameMash (nameOne, nameTwo);
COMBONAME = coupleName;
document.getElementById("player-1").innerHTML = (nameOne + "'s Score is:");
document.getElementById("player-2").innerHT... |
function initialization () {//initializes the persistant dashboard metrics for the first time
//add all of the local storage variables
//localStorage.setItem("highScore", 0);
//localStorage.setItem("totalparticipants", 0);
//localStorage.setItem("average", 0);
//localStorage.s... | {//checks if any of the present SCOREs are higher than the all time high SCORE
var tempSCORE = parseInt(localStorage.getItem("highScore"));
if (SCORE[0] > tempSCORE) {
localStorage.setItem("highScore", SCORE[0]);
}
if (SCORE[1] > tempSCORE) {
localStorage.setItem("highScore", SCORE[1])... | identifier_body |
app.js | s*");
nameOne = re.exec(nameOne)[0];
nameTwo = re.exec(nameTwo)[0];
P1NAME = nameOne;
P2NAME = nameTwo;
coupleName = this.nameMash (nameOne, nameTwo);
COMBONAME = coupleName;
document.getElementById("player-1").innerHTML = (nameOne + "'s Score is:");
document.getElementById("player-2").innerHT... |
function highScore () {//checks if any of the present SCOREs are higher than the all time high SCORE
var tempSCORE = parseInt(localStorage.getItem("highScore"));
if (SCORE[0] > tempSCORE) {
localStorage.setItem("highScore", SCORE[0]);
}
if (SCORE[1] > tempSCORE) {
localStorage.setIte... | };
localStorage.setItem("finalobjects", JSON.stringify(totalFinalObjects));
} | random_line_split |
app.js | s*");
nameOne = re.exec(nameOne)[0];
nameTwo = re.exec(nameTwo)[0];
P1NAME = nameOne;
P2NAME = nameTwo;
coupleName = this.nameMash (nameOne, nameTwo);
COMBONAME = coupleName;
document.getElementById("player-1").innerHTML = (nameOne + "'s Score is:");
document.getElementById("player-2").innerHT... | () {
el = document.getElementById("overlay");
el.style.visibility = (el.style.visibility == "visible") ? "hidden" : "visible";
}
function pointGenerator () {//this function computes the points
//TODO: Make a funtion to check directional trends and integrate the result into this function
if (makePoint... | overlay | identifier_name |
XYRepresentation.py | if not distances:
distances.append(dist)
neighbors.append(pt)
else:
counter=0
while counter<len(distances) and dist>distances[counter]:
counter+=1
distances.insert(... |
def sample(self):
samp=self.mp.sample()
self.addVertex(samp)
return samp
class Map():
points=[] #PRM points
edges=[] #PRM edges
lines=[]
buff_lines=[]
obstacles=[]
buff=0
vis_graph=None
visibility=False
def __init__(self,lx=0,hx=0,ly=0,hy=0):
self... | if self.can_connect(a,q):
if (a,q) not in self.edges and (q,a) not in self.edges:
self.edges.append((a,q)) | identifier_body |
XYRepresentation.py | if not distances:
distances.append(dist)
neighbors.append(pt)
else:
counter=0
while counter<len(distances) and dist>distances[counter]:
counter+=1
distances.insert(... |
return False
def clear(self):
self.lines=[]
self.buff_lines=[]
self.obstacles=[]
"""vertices are of format [(a,b),(c,d)]"""
def add_Poly(self,vertices=[]):
if self.visibility:
init_poly=shapely.Polygon(vertices)
buff_poly=ini... | if obs[1].intersects(path) and not path.touches(obs[1]):
return True | conditional_block |
XYRepresentation.py | if not distances:
distances.append(dist)
neighbors.append(pt)
else:
counter=0
while counter<len(distances) and dist>distances[counter]:
counter+=1
distances.insert(... | (self,a,q):
if self.can_connect(a,q):
if (a,q) not in self.edges and (q,a) not in self.edges:
self.edges.append((a,q))
def sample(self):
samp=self.mp.sample()
self.addVertex(samp)
return samp
class Map():
points=[] #PRM points
edges=[] #PRM edges
... | connect | identifier_name |
XYRepresentation.py | ide(a,q)
def connect(self,a,q):
if self.can_connect(a,q):
if (a,q) not in self.edges and (q,a) not in self.edges:
self.edges.append((a,q))
def sample(self):
samp=self.mp.sample()
self.addVertex(samp)
return samp
class Map():
points=[] #PRM points
... | mp.add_Poly([(-1,-1), (-6,-2), (-5,2), (-3,2), (-4,0)])
mp.add_Poly([(6,5), (4,1), (5,-2), (2,-4), (1,2)])
mp.add_Poly([(0,-3) ,(0,-4) ,(1,-5) ,(-5,-5) ,(-5,-4) ])
mp.add_Poly([(6,6), (0,4) ,(-5,6) ,(0,6), (4,7)])
# mp.add_Poly([(-2,0),(-2,-1),(2,-1),(2,0)]) | random_line_split | |
loadout-builder-reducer.ts | -values';
import { DestinyClass } from 'bungie-api-ts/destiny2';
import _ from 'lodash';
import { useReducer } from 'react';
import { isLoadoutBuilderItem } from '../loadout/item-utils';
import {
lockedModsFromLoadoutParameters,
statFiltersFromLoadoutParamaters,
statOrderFromLoadoutParameters,
} from './loadout-p... | body: t('LoadoutBuilder.MissingClassDescription'),
});
}
const lbStateInit = ({
stores,
preloadedLoadout,
initialLoadoutParameters,
classType,
defs,
}: {
stores: DimStore[];
preloadedLoadout?: Loadout;
initialLoadoutParameters: LoadoutParameters;
classType: DestinyClass | undefined;
defs: D2M... |
showNotification({
type: 'error',
title: t('LoadoutBuilder.MissingClass', { className: missingClassName }), | random_line_split |
loadout-builder-reducer.ts | -values';
import { DestinyClass } from 'bungie-api-ts/destiny2';
import _ from 'lodash';
import { useReducer } from 'react';
import { isLoadoutBuilderItem } from '../loadout/item-utils';
import {
lockedModsFromLoadoutParameters,
statFiltersFromLoadoutParamaters,
statOrderFromLoadoutParameters,
} from './loadout-p... | (classType: DestinyClass, defs: D2ManifestDefinitions) {
const missingClassName = Object.values(defs.Class).find((c) => c.classType === classType)!
.displayProperties.name;
showNotification({
type: 'error',
title: t('LoadoutBuilder.MissingClass', { className: missingClassName }),
body: t('LoadoutBu... | warnMissingClass | identifier_name |
loadout-builder-reducer.ts | -values';
import { DestinyClass } from 'bungie-api-ts/destiny2';
import _ from 'lodash';
import { useReducer } from 'react';
import { isLoadoutBuilderItem } from '../loadout/item-utils';
import {
lockedModsFromLoadoutParameters,
statFiltersFromLoadoutParamaters,
statOrderFromLoadoutParameters,
} from './loadout-p... | [bucketHash]: item,
},
// Locking an item clears excluded items in this bucket
excludedItems: {
...state.excludedItems,
[bucketHash]: undefined,
},
};
}
case 'setPinnedItems': {
const { items } = action;
return {
...state,
... | {
switch (action.type) {
case 'changeCharacter':
return {
...state,
selectedStoreId: action.storeId,
pinnedItems: {},
excludedItems: {},
lockedExoticHash: undefined,
};
case 'statFiltersChanged':
return { ...state, statFilters: action.statFilters };
... | identifier_body |
loadout-builder-reducer.ts | -values';
import { DestinyClass } from 'bungie-api-ts/destiny2';
import _ from 'lodash';
import { useReducer } from 'react';
import { isLoadoutBuilderItem } from '../loadout/item-utils';
import {
lockedModsFromLoadoutParameters,
statFiltersFromLoadoutParamaters,
statOrderFromLoadoutParameters,
} from './loadout-p... | }
}
const statOrder = statOrderFromLoadoutParameters(loadoutParams);
const statFilters = statFiltersFromLoadoutParamaters(loadoutParams);
const lockedMods = lockedModsFromLoadoutParameters(loadoutParams, defs);
const lockItemEnergyType = Boolean(loadoutParams?.lockItemEnergyType);
// We need to handle... | {
const loadoutStore = stores.find((store) => store.classType === preloadedLoadout.classType);
if (!loadoutStore) {
warnMissingClass(preloadedLoadout.classType, defs);
} else {
selectedStoreId = loadoutStore.id;
// TODO: instead of locking items, show the loadout fixed at the top to compar... | conditional_block |
config.rs | _SECONDS: usize = 60;
/// This struct contains the configuration of the agent.
#[derive(Clone)]
pub struct Config {
/// the latching interval for stats
interval: u64,
/// sample rate for counters in Hz
sample_rate: f64,
/// the sampler timeout
sampler_timeout: Duration,
/// maximum consecut... | (&self, pkey: &str) -> bool {
self.data.get(pkey).is_some()
}
/// Remove a `pkey`+`lkey`
pub fn remove(&mut self, pkey: &str, lkey: &str) {
if let Some(entry) = self.data.get_mut(pkey) {
entry.remove(lkey);
}
}
/// Remove the `pkey` and all `lkey`s under it
... | contains_pkey | identifier_name |
config.rs | : usize = 60;
/// This struct contains the configuration of the agent.
#[derive(Clone)]
pub struct Config {
/// the latching interval for stats
interval: u64,
/// sample rate for counters in Hz
sample_rate: f64,
/// the sampler timeout
sampler_timeout: Duration,
/// maximum consecutive samp... |
/// the timeout for sampler execution
pub fn sampler_timeout(&self) -> Duration {
self.sampler_timeout
}
/// maximum consecutive sampler timeouts
pub fn max_sampler_timeouts(&self) -> usize {
self.max_sampler_timeouts
}
/// get listen address
pub fn listen(&self) -> S... | {
self.sample_rate
} | identifier_body |
config.rs | _SECONDS: usize = 60;
/// This struct contains the configuration of the agent.
#[derive(Clone)]
pub struct Config {
/// the latching interval for stats
interval: u64,
/// sample rate for counters in Hz
sample_rate: f64,
/// the sampler timeout
sampler_timeout: Duration,
/// maximum consecut... | else {
None
};
let sample_rate =
parse_float_arg(&matches, "sample-rate").unwrap_or(DEFAULT_SAMPLE_RATE_HZ);
let sampler_timeout = Duration::from_millis(
parse_numeric_arg(&matches, "sampler-timeout")
.unwrap_or(DEFAULT_SAMPLER_TIMEOUT_MILLIS... | {
let socket = sock.parse().unwrap_or_else(|_| {
println!("ERROR: memcache address is malformed");
process::exit(1);
});
Some(socket)
} | conditional_block |
config.rs | `
pub fn new() -> Self {
Self {
data: HashMap::new(),
}
}
/// Insert a `pkey`+`lkey` into the set
pub fn insert(&mut self, pkey: &str, lkey: &str) {
let mut entry = self.data.remove(pkey).unwrap_or_default();
entry.insert(lkey.to_owned());
self.data.i... | })
}) | random_line_split | |
tag.rs | 32 = tag!(b"Glat");
/// `Gloc`
pub const GLOC: u32 = tag!(b"Gloc");
/// `glyf`
pub const GLYF: u32 = tag!(b"glyf");
/// `GPOS`
pub const GPOS: u32 = tag!(b"GPOS");
/// `grek`
pub const GREK: u32 = tag!(b"grek");
/// `GSUB`
pub const GSUB: u32 = tag!(b"GSUB");
/// `gujr`
pub const GUJR: u32 = tag!(b"gujr");
/// `gur2`
p... | {
let tag = from_string("beng").expect("invalid tag");
assert_eq!(tag, 1650814567);
} | identifier_body | |
tag.rs | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let tag = self.0;
let bytes = tag.to_be_bytes();
if bytes.iter().all(|c| c.is_ascii() && !c.is_ascii_control()) {
let s = str::from_utf8(&bytes).unwrap(); // unwrap safe due to above check
s.fmt(f)
} else {
... | fmt | identifier_name | |
tag.rs | fmt::Display::fmt(self, f)
}
}
/// `abvf`
pub const ABVF: u32 = tag!(b"abvf");
/// `abvm`
pub const ABVM: u32 = tag!(b"abvm");
/// `abvs`
pub const ABVS: u32 = tag!(b"abvs");
/// `acnt`
pub const ACNT: u32 = tag!(b"acnt");
/// `afrc`
pub const AFRC: u32 = tag!(b"afrc");
/// `akhn`
pub const AKHN: u32 = tag... | pub const MKMK: u32 = tag!(b"mkmk");
/// `mlm2`
pub const MLM2: u32 = tag!(b"mlm2");
/// `mlym`
pub const M | pub const MEDI: u32 = tag!(b"medi");
/// `mkmk` | random_line_split |
tag.rs |
tag = (tag << 8) | (c as u32);
count += 1;
}
while count < 4 {
tag = (tag << 8) | (' ' as u32);
count += 1;
}
Ok(tag)
}
impl fmt::Display for DisplayTag {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let tag = self.0;
let bytes = tag... | {
return Err(ParseError::BadValue);
} | conditional_block | |
lib.rs | alter the User-Agent, Referer
* or Cookie headers that it will send and then call ``.call()`` to make the
* request, or you can call ``.post_body()`` to send the HTML yourself, if it
* is not publicly available to the wider Internet.
*
* Getting data out of the result
* ------------------------------
*
* At pr... | (&self, url: &Url, api: &str, fields: &[&str])
-> Result<json::Object, Error> {
call(url, self.token, api, fields, self.version)
}
/// Prepare a request to any Diffbot API with the stored token and API version.
///
/// See the ``call()`` function for an explanation of the paramet... | call | identifier_name |
lib.rs | alter the User-Agent, Referer
* or Cookie headers that it will send and then call ``.call()`` to make the
* request, or you can call ``.post_body()`` to send the HTML yourself, if it
* is not publicly available to the wider Internet.
*
* Getting data out of the result
* ------------------------------
*
* At pr... | let num = num as uint;
let msg = match o.pop(&~"error")
.expect("JSON had errorCode but not error") {
json::String(s) => s,
uh_oh => fail!("error was {} instead of a string", uh_oh.to_s... | match json {
json::Object(~mut o) => {
match o.pop(&~"errorCode") {
Some(json::Number(num)) => { | random_line_split |
lib.rs | alter the User-Agent, Referer
* or Cookie headers that it will send and then call ``.call()`` to make the
* request, or you can call ``.post_body()`` to send the HTML yourself, if it
* is not publicly available to the wider Internet.
*
* Getting data out of the result
* ------------------------------
*
* At pr... |
}
/// An in-progress Diffbot API call.
pub struct Request {
priv request: RequestWriter<TcpStream>,
}
impl Request {
/// Set the value for Diffbot to send as the ``User-Agent`` header when
/// making your request.
pub fn user_agent(&mut self, user_agent: ~str) {
self.request.headers.extension... | {
prepare_request(url, self.token, api, fields, self.version)
} | identifier_body |
main.rs |
// length: usize
// }
//
// impl<T> ImageDataIterator<T> {
// fn from_dynamic_image(img: &DynamicImage) -> ImageDataIterator<T> {
// let dimensions = img.dimensions();
//
// ImageDataIterator {
// originalIterator: img.to_rgba().pixels(),
// length: ( dimen... | () {
let img = match image::open("./media/autumn.png") {
Ok(image) => image,
Err(err) => panic!("{:?}", err)
};
{ // stdout image info
println!("color {:?}", img.color());
println!("dimensions {:?}", img.dimensions());
// println!("first pixel {:?}", img.pixels(... | main | identifier_name |
main.rs | {
// Some(pixel) => {
// let rgba = pixel.2;
// let data: [u8; 4] = [ rgba[0], rgba[1], rgba[2], rgba[3] ];
// return Some(data);
// },
// None => None
// }
// }
// }
//
// impl<'a, T> ExactSizeIterator for ImageDataIter... | Err(err) => panic!("{:?}", err)
}; | random_line_split | |
main.rs |
// length: usize
// }
//
// impl<T> ImageDataIterator<T> {
// fn from_dynamic_image(img: &DynamicImage) -> ImageDataIterator<T> {
// let dimensions = img.dimensions();
//
// ImageDataIterator {
// originalIterator: img.to_rgba().pixels(),
// length: ( dimen... |
//TODO: list devices, choose based on user input
for p in PhysicalDevice::enumerate(&instance) {
print!("{}", p.name());
println!(", driver version: {}", p.driver_version());
}
let physical = PhysicalDevice::enumerate(&instance)
.next()
.expect("no device available");
... | {
let img = match image::open("./media/autumn.png") {
Ok(image) => image,
Err(err) => panic!("{:?}", err)
};
{ // stdout image info
println!("color {:?}", img.color());
println!("dimensions {:?}", img.dimensions());
// println!("first pixel {:?}", img.pixels().n... | identifier_body |
main.rs | // }
// }
//
// impl<'a, T> Iterator for ImageDataIterator<'a, T> {
// type Item = [u8; 4];
// fn next(&mut self) -> Option<[u8; 4]> {
// return match self.originalIterator.next() {
// Some(pixel) => {
// let rgba = pixel.2;
// let data: [u8; 4] = [ rgba... | {
let dimensions: (u32, u32) = dimensions.to_physical(window.get_hidpi_factor()).into();
[dimensions.0, dimensions.1]
} | conditional_block | |
body.rs | } else if eccentricity == 1.0 {
return OrbitType::Parabolic;
} else {
return OrbitType::Hyperbolic;
}
}
}
#[derive(Debug)]
pub struct Body {
pub position: Vector3<f64>,
pub velocity: Vector3<f64>,
pub orbit_type: OrbitType,
}
/* Adds methods to Body stru... | (&self, angle: f64) -> (Vector3<f64>, Vector3<f64>) {
let r = self.position_at_angle(angle);
let v = self.velocity_at_angle(angle);
let tht = angle - self.true_anomaly();
let trans = Matrix3::from_rows(&[
Vector3::new(tht.cos(), -tht.sin(), 0.0).transpose(),
Vecto... | position_and_velocity | identifier_name |
body.rs | } else if eccentricity == 1.0 {
return OrbitType::Parabolic;
} else {
return OrbitType::Hyperbolic;
}
}
}
#[derive(Debug)]
pub struct Body {
pub position: Vector3<f64>,
pub velocity: Vector3<f64>,
pub orbit_type: OrbitType,
}
/* Adds methods to Body stru... |
}
/* points from focus to perigee if I'm not mistaken */
pub fn eccentricity_vector(&self) -> Vector3<f64> {
let veloc = self.velocity;
let posit = self.position;
let h = self.angular_momentum();
(veloc.cross(&h) / SOLARGM) - posit.normalize()
}
pub fn angular_mome... | {
return val.acos();
} | conditional_block |
body.rs | } else if eccentricity == 1.0 {
return OrbitType::Parabolic;
} else {
return OrbitType::Hyperbolic;
}
}
}
#[derive(Debug)]
pub struct Body {
pub position: Vector3<f64>, | impl Body {
pub fn new(position: Vector3<f64>, velocity: Vector3<f64>) -> Body {
// h and e are used for determining what kind of orbit the body is currently in
let h = position.cross(&velocity);
let e = ((velocity.cross(&h) / SOLARGM) - position.normalize()).norm();
Body {
... | pub velocity: Vector3<f64>,
pub orbit_type: OrbitType,
}
/* Adds methods to Body struct */ | random_line_split |
body.rs | } else if eccentricity == 1.0 {
return OrbitType::Parabolic;
} else {
return OrbitType::Hyperbolic;
}
}
}
#[derive(Debug)]
pub struct Body {
pub position: Vector3<f64>,
pub velocity: Vector3<f64>,
pub orbit_type: OrbitType,
}
/* Adds methods to Body stru... |
pub fn true_anomaly(&self) -> f64 {
let e_vec = self.eccentricity_vector();
let posit = self.position.normalize();
let val = e_vec.dot(&posit) / (e_vec.norm() * posit.norm());
if posit.dot(&self.velocity.normalize()) < 0.0 {
return 2.0 * PI - val.acos();
} else ... | {
self.omega().cross(&self.position)
} | identifier_body |
thermald.py | 12)
dat.thermal.mem = read_tz(2)
dat.thermal.gpu = read_tz(16)
dat.thermal.bat = read_tz(29)
return dat
LEON = False
def setup_eon_fan():
global LEON
os.system("echo 2 > /sys/module/dwc3_msm/parameters/otg_switch")
bus = SMBus(7, force=True)
try:
bus.write_byte_data(0x21, 0x10, 0xf) # mask all ... | last_eon_fan_val = val
# temp thresholds to control fan speed - high hysteresis
_TEMP_THRS_H = [50., 65., 80., 10000]
# temp thresholds to control fan speed - low hysteresis
_TEMP_THRS_L = [42.5, 57.5, 72.5, 10000]
# fan speed options
_FAN_SPEEDS = [0, 16384, 32768, 65535]
# max fan speed only allowed if battery ... | global LEON, last_eon_fan_val
if last_eon_fan_val is None or last_eon_fan_val != val:
bus = SMBus(7, force=True)
if LEON:
try:
i = [0x1, 0x3 | 0, 0x3 | 0x08, 0x3 | 0x10][val]
bus.write_i2c_block_data(0x3d, 0, [i])
except IOError:
# tusb320
if val == 0:
bu... | identifier_body |
thermald.py | 2 > /sys/module/dwc3_msm/parameters/otg_switch")
bus = SMBus(7, force=True)
try:
bus.write_byte_data(0x21, 0x10, 0xf) # mask all interrupts
bus.write_byte_data(0x21, 0x03, 0x1) # set drive current and global interrupt disable
bus.write_byte_data(0x21, 0x02, 0x2) # needed?
bus.write_byte_data... | params.delete("Offroad_ConnectivityNeededPrompt")
# start constellation of processes when the car starts | random_line_split | |
thermald.py | 2)
dat.thermal.mem = read_tz(2)
dat.thermal.gpu = read_tz(16)
dat.thermal.bat = read_tz(29)
return dat
LEON = False
def setup_eon_fan():
global LEON
os.system("echo 2 > /sys/module/dwc3_msm/parameters/otg_switch")
bus = SMBus(7, force=True)
try:
bus.write_byte_data(0x21, 0x10, 0xf) # mask all i... | (val):
global LEON, last_eon_fan_val
if last_eon_fan_val is None or last_eon_fan_val != val:
bus = SMBus(7, force=True)
if LEON:
try:
i = [0x1, 0x3 | 0, 0x3 | 0x08, 0x3 | 0x10][val]
bus.write_i2c_block_data(0x3d, 0, [i])
except IOError:
# tusb320
if val == 0:
... | set_eon_fan | identifier_name |
thermald.py | 12)
dat.thermal.mem = read_tz(2)
dat.thermal.gpu = read_tz(16)
dat.thermal.bat = read_tz(29)
return dat
LEON = False
def setup_eon_fan():
global LEON
os.system("echo 2 > /sys/module/dwc3_msm/parameters/otg_switch")
bus = SMBus(7, force=True)
try:
bus.write_byte_data(0x21, 0x10, 0xf) # mask all ... | with open("/sys/class/power_supply/battery/status") as f:
msg.thermal.batteryStatus = f.read().strip()
with open("/sys/class/power_supply/battery/current_now") as f:
msg.thermal.batteryCurrent = int(f.read())
with open("/sys/class/power_supply/battery/voltage_now") as f:
msg.thermal.batter... | health = messaging.recv_sock(health_sock, wait=True)
location = messaging.recv_sock(location_sock)
location = location.gpsLocation if location else None
msg = read_thermal()
# clear car params when panda gets disconnected
if health is None and health_prev is not None:
params.panda_disconnect(... | conditional_block |
falcon.py | salt)
s0 = sub_zq(hashed, mul_zq(s1, self.h))
s0 = [(coef + (q >> 1)) % q - (q >> 1) for coef in s0]
# Check that the (s0, s1) is short
norm_sign = sum(coef ** 2 for coef in s0)
norm_sign += sum(coef ** 2 for coef in s1)
if norm_sign > self.signature_bound:
... | random_line_split | ||
falcon.py | if elt < k * q:
hashed[i] = elt % q
i += 1
j += 1
return hashed
def verify(self, message, signature):
"""
Verify a signature.
"""
# Unpack the salt and the short polynomial s1
salt = signature[HEAD_LE... | return header + salt + enc_s | conditional_block | |
falcon.py | "n": 16,
"sigma": 151.78340713845503,
"sigmin": 1.170254078853483,
"sig_bound": 892039,
"sig_bytelen": 63,
},
# FalconParam(32, 8)
32: {
"n": 32,
"sigma": 154.6747794602761,
"sigmin": 1.1925466358390344,
"sig_bound": 1852696,
... | (self, message, signature):
"""
Verify a signature.
"""
# Unpack the salt and the short polynomial s1
salt = signature[HEAD_LEN:HEAD_LEN + SALT_LEN]
enc_s = signature[HEAD_LEN + SALT_LEN:]
s1 = decompress(enc_s, self.sig_bytelen - HEAD_LEN - SALT_LEN, self.... | verify | identifier_name |
falcon.py | "n": 16,
"sigma": 151.78340713845503,
"sigmin": 1.170254078853483,
"sig_bound": 892039,
"sig_bytelen": 63,
},
# FalconParam(32, 8)
32: {
"n": 32,
"sigma": 154.6747794602761,
"sigmin": 1.1925466358390344,
"sig_bound": 1852696,
... | rep = "Public for n = {n}:\n\n".format(n=self.n)
rep += "h = {h}\n".format(h=self.h)
return rep
def hash_to_point(self, message, salt):
"""
Hash a message to a point in Z[x] mod(Phi, q).
Inspired by the Parse function from NewHope.
"""
n = se... | """
This class contains methods for performing public key operations in Falcon.
"""
def __init__(self, sk=None, n=None, h=None):
"""Initialize a public key."""
if sk:
self.n = sk.n
self.h = sk.h
elif n and h:
self.n = n
self... | identifier_body |
cluster_feeder.go | State: m.ClusterState,
specClient: spec.NewSpecClient(m.PodLister),
selectorFetcher: m.SelectorFetcher,
memorySaveMode: m.MemorySaveMode,
controllerFetcher: m.ControllerFetcher,
recommenderName: m.RecommenderName,
}
}
// WatchEvictionEventsWithRetries watches new Events with r... |
for _, checkpoint := range checkpointList.Items {
klog.V(3).Infof("Loading VPA %s/%s checkpoint for %s", checkpoint.ObjectMeta.Namespace, checkpoint.Spec.VPAObjectName, checkpoint.Spec.ContainerName)
err = feeder.setVpaCheckpoint(&checkpoint)
if err != nil {
klog.Errorf("Error while loading checkpoint.... | {
klog.Errorf("Cannot list VPA checkpoints from namespace %v. Reason: %+v", namespace, err)
} | conditional_block |
cluster_feeder.go | clusterState: m.ClusterState,
specClient: spec.NewSpecClient(m.PodLister),
selectorFetcher: m.SelectorFetcher,
memorySaveMode: m.MemorySaveMode,
controllerFetcher: m.ControllerFetcher,
recommenderName: m.RecommenderName,
}
}
// WatchEvictionEventsWithRetries watches new Events... | klog.Errorf("Error while loading checkpoint. Reason: %+v", err)
}
}
}
}
func (feeder *clusterStateFeeder) GarbageCollectCheckpoints() {
klog.V(3).Info("Starting garbage collection of checkpoints")
feeder.LoadVPAs()
namespaceList, err := feeder.coreClient.Namespaces().List(context.TODO(), metav1.ListOpt... | {
klog.V(3).Info("Initializing VPA from checkpoints")
feeder.LoadVPAs()
namespaces := make(map[string]bool)
for _, v := range feeder.clusterState.Vpas {
namespaces[v.ID.Namespace] = true
}
for namespace := range namespaces {
klog.V(3).Infof("Fetching checkpoints from namespace %s", namespace)
checkpointLi... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.