file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
client.rs | // #[macro_use]
extern crate actix;
// extern crate byteorder;
// extern crate bytes;
extern crate futures;
extern crate serde;
extern crate serde_json;
// extern crate tokio_io;
// extern crate tokio_tcp;
extern crate awc;
extern crate rustls;
extern crate structopt;
#[macro_use]
extern crate log;
extern crate env_log... | else {
addr.do_send(ClientCommand(opt.msg));
sys.stop();
}
})
}));
})
// ).unwrap();
// sys.block_on(
// ).unwrap();
// Arbiter::spawn(
// TcpStream::connect(&addr)
// .and_then(|stream| {... | {
addr.do_send(ClientCommand(read_stdin()));
sys.stop();
} | conditional_block |
base.py | """
Common and utility functions/classes for vulnerability-manager
"""
import base64
import csv
from io import StringIO
import json
from math import floor
from os import environ
from distutils.util import strtobool # pylint: disable=import-error, no-name-in-module
import requests
import connexion
from flask import R... | (Exception):
"""manager is running in read-only mode"""
def basic_auth(username, password, required_scopes=None): # pylint: disable=unused-argument
"""
Basic auth is done on 3scale level.
"""
raise MissingEntitlementException
def auth(x_rh_identity, required_scopes=None): # pylint: disable=unu... | ReadOnlyModeException | identifier_name |
base.py | """
Common and utility functions/classes for vulnerability-manager
"""
import base64
import csv
from io import StringIO
import json
from math import floor
from os import environ
from distutils.util import strtobool # pylint: disable=import-error, no-name-in-module
import requests
import connexion
from flask import R... |
if errors:
raise ApplicationException({'errors': errors}, 400)
return retval
@classmethod
def vmaas_call(cls, endpoint, data):
"""Calls vmaas and retrieves data from it"""
headers = {'Content-type': 'application/json',
'Accept': 'application/json'... | retval[arg['arg_name']] = kwargs.get(arg['arg_name'], None)
if retval[arg['arg_name']]:
try:
if arg['convert_func'] is not None:
retval[arg['arg_name']] = arg['convert_func'](retval[arg['arg_name']])
except ValueError:
... | conditional_block |
base.py | """
Common and utility functions/classes for vulnerability-manager
"""
import base64
import csv
from io import StringIO
import json
from math import floor
from os import environ
from distutils.util import strtobool # pylint: disable=import-error, no-name-in-module
import requests
import connexion
from flask import R... |
@staticmethod
def hide_satellite_managed():
"""Parses hide-satellite-managed from headers"""
try:
return strtobool(connexion.request.headers.get('Hide-Satellite-Managed', 'false'))
except ValueError:
return False
@staticmethod
def _parse_arguments(kwarg... | """Formats error message to desired format"""
return {"errors": [{"status": str(status_code), "detail": text}]}, status_code | identifier_body |
base.py | """
Common and utility functions/classes for vulnerability-manager
"""
import base64
import csv
from io import StringIO
import json
from math import floor
from os import environ
from distutils.util import strtobool # pylint: disable=import-error, no-name-in-module
import requests
import connexion
from flask import R... | return cls.format_exception('Internal server error', 500)
@classmethod
def handle_patch(cls, **kwargs):
"""To be implemented in child classes"""
raise NotImplementedError
class PostRequest(Request):
"""general class for processing POST requests"""
@classmethod
def pos... | return cls.format_exception(str(exc), 503)
except Exception: # pylint: disable=broad-except
LOGGER.exception('Unhandled exception: ') | random_line_split |
plot_inv_1_dcr_sounding.py | # -*- coding: utf-8 -*-
"""
Least-Squares 1D Inversion of Sounding Data
===========================================
Here we use the module *SimPEG.electromangetics.static.resistivity* to invert
DC resistivity sounding data and recover a 1D electrical resistivity model.
In this tutorial, we focus on the following:
... |
# Define survey
survey = dc.Survey(source_list)
# Plot apparent resistivities on sounding curve as a function of Wenner separation
# parameter.
electrode_separations = 0.5 * np.sqrt(
np.sum((survey.locations_a - survey.locations_b) ** 2, axis=1)
)
fig = plt.figure(figsize=(11, 5))
mpl.rcParams.update({"font.siz... | M_locations = M_electrodes[k[ii] : k[ii + 1], :]
N_locations = N_electrodes[k[ii] : k[ii + 1], :]
receiver_list = [
dc.receivers.Dipole(
M_locations,
N_locations,
data_type="apparent_resistivity",
)
]
# AB electrode locations for source. Each is a (1,... | conditional_block |
plot_inv_1_dcr_sounding.py | # -*- coding: utf-8 -*-
"""
Least-Squares 1D Inversion of Sounding Data
===========================================
Here we use the module *SimPEG.electromangetics.static.resistivity* to invert
DC resistivity sounding data and recover a 1D electrical resistivity model.
In this tutorial, we focus on the following:
... |
from discretize import TensorMesh
from SimPEG import (
maps,
data,
data_misfit,
regularization,
optimization,
inverse_problem,
inversion,
directives,
utils,
)
from SimPEG.electromagnetics.static import resistivity as dc
from SimPEG.utils import plot_1d_layer_model
mpl.rcParams.upd... | import matplotlib as mpl
import matplotlib.pyplot as plt
import tarfile | random_line_split |
ListBlock.js | "use strict";
const h = require('react-hyperscript')
, R = require('ramda')
, React = require('react')
, natsort = require('natsort')
, { Flex, Box, Text, Select } = require('periodo-ui')
, { colors } = require('periodo-ui').theme
, { Button, DropdownMenu, DropdownMenuItem, Link } = require('pe... |
prevPage() {
const limit = parseInt(this.props.limit)
this.setState(prev => {
let start = prev.start - limit
if (start < 0) start = 0;
return { start }
})
}
render() {
const items = this.props.data
, { shownColumns, sortBy, sortDirection, update... | })
} | random_line_split |
ListBlock.js | "use strict";
const h = require('react-hyperscript')
, R = require('ramda')
, React = require('react')
, natsort = require('natsort')
, { Flex, Box, Text, Select } = require('periodo-ui')
, { colors } = require('periodo-ui').theme
, { Button, DropdownMenu, DropdownMenuItem, Link } = require('pe... | rops) {
super(props);
this.state = {
start: withDefaults(props).start,
}
this.firstPage = this.firstPage.bind(this);
this.lastPage = this.lastPage.bind(this);
this.nextPage = this.nextPage.bind(this);
this.prevPage = this.prevPage.bind(this);
}
componentWillR... | nstructor(p | identifier_name |
main.rs | extern crate sdl2;
extern crate ears;
mod chart;
mod guitarplaythrough;
use std::time::{Duration, Instant};
use sdl2::event::Event;
use sdl2::pixels;
use sdl2::keyboard::Keycode;
use sdl2::gfx::primitives::DrawRenderer;
use ears::{AudioController};
use guitarplaythrough::*;
const SCREEN_WIDTH: u32 = 800;
const S... | .map(|e| GameInputEffect::GuitarEffect(e))
.map(|effect: GameInputEffect| {
match effect {
GameInputEffect::Quit => run = false,
GameInputEffect::GuitarEffect(effect) => match effect {
Hit => (),
... | }
}
});
playthrough.update_time(song_time_ms) | random_line_split |
main.rs | extern crate sdl2;
extern crate ears;
mod chart;
mod guitarplaythrough;
use std::time::{Duration, Instant};
use sdl2::event::Event;
use sdl2::pixels;
use sdl2::keyboard::Keycode;
use sdl2::gfx::primitives::DrawRenderer;
use ears::{AudioController};
use guitarplaythrough::*;
const SCREEN_WIDTH: u32 = 800;
const S... | {
Quit,
GuitarEffect(GuitarGameEffect),
}
fn draw_fret<T: sdl2::render::RenderTarget>(canvas: &sdl2::render::Canvas<T>, enabled: bool, x: i16, y: i16, radius: i16, color: pixels::Color) -> Result<(), String> {
if enabled {
canvas.filled_circle(x, y, radius, color)
} else {
canvas.circl... | GameInputEffect | identifier_name |
main.rs | extern crate sdl2;
extern crate ears;
mod chart;
mod guitarplaythrough;
use std::time::{Duration, Instant};
use sdl2::event::Event;
use sdl2::pixels;
use sdl2::keyboard::Keycode;
use sdl2::gfx::primitives::DrawRenderer;
use ears::{AudioController};
use guitarplaythrough::*;
const SCREEN_WIDTH: u32 = 800;
const S... |
enum FrameLimit {
Vsync,
Cap(u32),
}
fn main() -> Result<(), String> {
let sdl_context = sdl2::init()?;
/* joystick initialization */
let joystick_subsystem = sdl_context.joystick()?;
let available = joystick_subsystem.num_joysticks()
.map_err(|e| format!("can't enumerate joysticks... | {
if enabled {
canvas.filled_circle(x, y, radius, color)
} else {
canvas.circle(x, y, radius, color)
}
} | identifier_body |
script.js | let footer = document.getElementsByTagName('footer')[0];
let searchInput = document.getElementById('searchInput');
document.addEventListener('DOMContentLoaded', start); // когда HTML будет подготовлен и загружен, вызвать функцию start
function start() {
let bookTitle;
if (searchInput.value == '') {
le... | requestButton.addEventListener('click', toRequest);
let bookingButtons = document.querySelectorAll('input[value="Забронировать"]');
if (bookingButtons.length > 0) {
for (var i = 0; i < bookingButtons.length; i++) {
... | // Обработка кнопок для запроса и бронирования книги
let requestButton = document.getElementById('toRequest');
if (requestButton != null) | random_line_split |
script.js | let footer = document.getElementsByTagName('footer')[0];
let searchInput = document.getElementById('searchInput');
document.addEventListener('DOMContentLoaded', start); // когда HTML будет подготовлен и загружен, вызвать функцию start
function start() {
let bookTitle;
if (searchInput.value == '') {
le... | ist.add('timetableLinkClosed');
schedule.style.display = 'none';
}
}
function showSearchAlert(alertID, content) { // ПОКАЗ УВЕДОМЛЕНИЯ
alertID.style.display='flex';
alertID.style.animationName='showSearchAlert';
alertID.innerHTML='<div>'+content+'</div>'+'<svg viewBox="0 0 10 10" class="closeBt... |
if (link.classList.contains('timetableLinkClosed')) {
link.classList.remove('timetableLinkClosed');
link.classList.add('timetableLinkOpened');
schedule.style.display = 'block';
}
else {
link.classList.remove('timetableLinkOpened');
link.classL | conditional_block |
script.js | let footer = document.getElementsByTagName('footer')[0];
let searchInput = document.getElementById('searchInput');
document.addEventListener('DOMContentLoaded', start); // когда HTML будет подготовлен и загружен, вызвать функцию start
function start() {
let bookTitle;
if (searchInput.value == '') {
le... | t i = 0; i < timetableLinks.length; i++) {
let timetableLink = timetableLinks[i];
timetableLink.addEventListener('click', {
handleEvent: controlSchedule,
link: timetableLink,
... | for (le | identifier_name |
script.js | let footer = document.getElementsByTagName('footer')[0];
let searchInput = document.getElementById('searchInput');
document.addEventListener('DOMContentLoaded', start); // когда HTML будет подготовлен и загружен, вызвать функцию start
function start() {
let bookTitle;
if (searchInput.value == '') {
le... | er('click',()=>{closeSearchAlert(alertID);clearTimeout(aTimer);});
}
function closeSearchAlert(alertID) { // СКРЫТИЕ УВЕДОМЛЕНИЯ
alertID.style.animationName='closeSearchAlert';
setTimeout(()=>{alertID.style.display=''},1000)
} | d="M2,2 L8,8" class="closeBtn_p2"></path></svg>';
let aTimer=setTimeout(closeSearchAlert, 15000, alertID);
document.querySelector('.closeBtn').addEventListen | identifier_body |
elasticsearch.rs | use crate::{
buffers::Acker,
event::Event,
sinks::util::{
http::{HttpRetryLogic, HttpService},
retries::FixedRetryPolicy,
BatchServiceSink, Buffer, Compression, SinkExt,
},
template::Template,
topology::config::{DataType, SinkConfig},
};
use futures::{stream::iter_ok, Fut... |
})
}
}
| {
Err(format!("Unexpected status: {}", response.status()))
} | conditional_block |
elasticsearch.rs | use crate::{
buffers::Acker,
event::Event,
sinks::util::{
http::{HttpRetryLogic, HttpService},
retries::FixedRetryPolicy,
BatchServiceSink, Buffer, Compression, SinkExt,
},
template::Template,
topology::config::{DataType, SinkConfig},
};
use futures::{stream::iter_ok, Fut... | maybe_set_id(id_key, &mut action, &event);
assert_eq!(json!({}), action);
}
#[test]
fn doesnt_set_id_when_not_configured() {
let id_key: Option<&str> = None;
let mut event = Event::from("butts");
event
.as_mut_log()
.insert_explicit("foo".int... | .insert_explicit("not_foo".into(), "bar".into());
let mut action = json!({});
| random_line_split |
elasticsearch.rs | use crate::{
buffers::Acker,
event::Event,
sinks::util::{
http::{HttpRetryLogic, HttpService},
retries::FixedRetryPolicy,
BatchServiceSink, Buffer, Compression, SinkExt,
},
template::Template,
topology::config::{DataType, SinkConfig},
};
use futures::{stream::iter_ok, Fut... |
#[test]
fn doesnt_set_id_when_field_missing() {
let id_key = Some("foo");
let mut event = Event::from("butts");
event
.as_mut_log()
.insert_explicit("not_foo".into(), "bar".into());
let mut action = json!({});
maybe_set_id(id_key, &mut action, &... | {
let id_key = Some("foo");
let mut event = Event::from("butts");
event
.as_mut_log()
.insert_explicit("foo".into(), "bar".into());
let mut action = json!({});
maybe_set_id(id_key, &mut action, &event);
assert_eq!(json!({"_id": "bar"}), action);
... | identifier_body |
elasticsearch.rs | use crate::{
buffers::Acker,
event::Event,
sinks::util::{
http::{HttpRetryLogic, HttpService},
retries::FixedRetryPolicy,
BatchServiceSink, Buffer, Compression, SinkExt,
},
template::Template,
topology::config::{DataType, SinkConfig},
};
use futures::{stream::iter_ok, Fut... | (host: String) -> impl Future<Item = (), Error = String> {
let uri = format!("{}/_flush", host);
let request = Request::post(uri).body(Body::empty()).unwrap();
let https = HttpsConnector::new(4).expect("TLS initialization failed");
let client = Client::builder().build(https);
cl... | flush | identifier_name |
session.go | package netutil
import (
"crypto/rc4"
"encoding/binary"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/zxfonline/misc/golangtrace"
"github.com/zxfonline/misc/chanutil"
"github.com/zxfonline/misc/expvar"
"github.com/zxfonline/misc/log"
"github.com/zxfonline/misc/timefix"
"github.com/zxfonline/misc/t... | ption
// (NOT_ENCRYPTED) -> KEYEXCG -> ENCRYPT
if s.Flag&SESS_ENCRYPT != 0 { // encryption is enabled
encoder, _ := rc4.NewCipher(s.EncodeKey)
data := s.sendCache[HEAD_SIZE:totalSize]
encoder.XORKeyStream(data, data)
} else if s.Flag&SESS_KEYEXCG != 0 { // key is exchanged, encryption is not yet enabled
//s.... |
// encry | identifier_name |
session.go | package netutil
import (
"crypto/rc4"
"encoding/binary"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/zxfonline/misc/golangtrace"
"github.com/zxfonline/misc/chanutil"
"github.com/zxfonline/misc/expvar"
"github.com/zxfonline/misc/log"
"github.com/zxfonline/misc/timefix"
"github.com/zxfonline/misc/t... | rr := net.SplitHostPort(conn.RemoteAddr().String())
if err != nil {
log.Error("cannot get remote address:", err)
return nil, err
}
s.IP = net.ParseIP(host)
//log.Debugf("new connection from:%v port:%v", host, port)
return s, nil
}
func (s *TCPSession) TraceStart(family, title string, expvar bool) {
if trace.... | .NewDoneChan(),
}
host, _, e | conditional_block |
session.go | package netutil
import (
"crypto/rc4"
"encoding/binary"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/zxfonline/misc/golangtrace"
"github.com/zxfonline/misc/chanutil"
"github.com/zxfonline/misc/expvar"
"github.com/zxfonline/misc/log"
"github.com/zxfonline/misc/timefix"
"github.com/zxfonline/misc/t... | identifier_body | ||
session.go | package netutil
import (
"crypto/rc4"
"encoding/binary"
"io"
"net"
"sync"
"sync/atomic"
"time"
"github.com/zxfonline/misc/golangtrace"
"github.com/zxfonline/misc/chanutil"
"github.com/zxfonline/misc/expvar"
"github.com/zxfonline/misc/log"
"github.com/zxfonline/misc/timefix"
"github.com/zxfonline/misc/t... | }
type NetConnIF interface {
SetReadDeadline(t time.Time) error
SetWriteDeadline(t time.Time) error
Close() error
SetWriteBuffer(bytes int) error
SetReadBuffer(bytes int) error
Write(b []byte) (n int, err error)
RemoteAddr() net.Addr
Read(p []byte) (n int, err error)
}
type TCPSession struct {
//Conn *net.TC... | ReceiveTime time.Time | random_line_split |
batcher.go | // Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
func (p *pool) newBatch(now time.Time) *batch {
ba := p.batchPool.Get().(*batch)
*ba = batch{
startTime: now,
idx: -1,
}
return ba
}
func (p *pool) putBatch(b *batch) {
*b = batch{}
p.batchPool.Put(b)
}
// batchQueue is a container for batch objects which offers O(1) get based on
// rangeID and peek... | {
*r = request{}
p.requestPool.Put(r)
} | identifier_body |
batcher.go | // Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... | (cfg *Config) roachpb.BatchRequest {
req := roachpb.BatchRequest{
// Preallocate the Requests slice.
Requests: make([]roachpb.RequestUnion, 0, len(b.reqs)),
}
for _, r := range b.reqs {
req.Add(r.req)
}
if cfg.MaxKeysPerBatchReq > 0 {
req.MaxSpanRequestKeys = int64(cfg.MaxKeysPerBatchReq)
}
return req
}
... | batchRequest | identifier_name |
batcher.go | // Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... |
return b.requestChan
}
sendBatch = func(ba *batch) {
inFlight++
if inFlight >= b.cfg.InFlightBackpressureLimit {
inBackPressure = true
}
b.sendBatch(sendCtx, ba)
}
handleSendDone = func() {
inFlight--
if inFlight < recoveryThreshold {
inBackPressure = false
}
}
handleRequest... | {
return nil
} | conditional_block |
batcher.go | // Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, ... | // client is responsible for ensuring that the passed respChan has a buffer at
// least as large as the number of responses it expects to receive. Using an
// insufficiently buffered channel can lead to deadlocks and unintended delays
// processing requests inside the RequestBatcher.
func (b *RequestBatcher) SendWithCh... | }
}
// SendWithChan sends a request with a client provided response channel. The | random_line_split |
lib.rs | mod pixel;
mod y4m;
use self::pixel::*;
use ::y4m::{Colorspace, Decoder};
use std::cmp;
use std::collections::{BTreeMap, BTreeSet};
use std::io::Read;
/// Options determining how to run scene change detection.
pub struct DetectionOptions {
/// Whether or not to analyze the chroma planes.
/// Enabling this is ... | let mut keyframes = BTreeSet::new();
let mut frameno = 0;
loop {
let mut next_input_frameno = frame_queue
.keys()
.last()
.copied()
.map(|key| key + 1)
.unwrap_or(0);
while next_input_frameno < frameno + opts.lookahead_distance {
... | let mut detector = SceneChangeDetector::new(bit_depth, chroma_sampling, &opts);
let mut frame_queue = BTreeMap::new(); | random_line_split |
lib.rs | mod pixel;
mod y4m;
use self::pixel::*;
use ::y4m::{Colorspace, Decoder};
use std::cmp;
use std::collections::{BTreeMap, BTreeSet};
use std::io::Read;
/// Options determining how to run scene change detection.
pub struct DetectionOptions {
/// Whether or not to analyze the chroma planes.
/// Enabling this is ... | else {
frame_queue.get(&(frameno - 1))
},
&frame_set,
frameno,
&mut keyframes,
);
if frameno > 0 {
frame_queue.remove(&(frameno - 1));
}
frameno += 1;
if let Some(ref progress_fn) = opts.progress_callb... | {
None
} | conditional_block |
lib.rs | mod pixel;
mod y4m;
use self::pixel::*;
use ::y4m::{Colorspace, Decoder};
use std::cmp;
use std::collections::{BTreeMap, BTreeSet};
use std::io::Read;
/// Options determining how to run scene change detection.
pub struct DetectionOptions {
/// Whether or not to analyze the chroma planes.
/// Enabling this is ... |
/// Run a comparison between two frames to determine if they qualify for a scenecut.
///
/// The current algorithm detects fast cuts using changes in colour and intensity between frames.
/// Since the difference between frames is used, only fast cuts are detected
/// with this method. This is inten... | {
let lookahead_distance = cmp::min(self.opts.lookahead_distance, frame_subset.len() - 1);
// Where A and B are scenes: AAAAAABBBAAAAAA
// If BBB is shorter than lookahead_distance, it is detected as a flash
// and not considered a scenecut.
for j in 1..=lookahead_distance {
... | identifier_body |
lib.rs | mod pixel;
mod y4m;
use self::pixel::*;
use ::y4m::{Colorspace, Decoder};
use std::cmp;
use std::collections::{BTreeMap, BTreeSet};
use std::io::Read;
/// Options determining how to run scene change detection.
pub struct DetectionOptions {
/// Whether or not to analyze the chroma planes.
/// Enabling this is ... | <'a> {
/// Minimum average difference between YUV deltas that will trigger a scene change.
threshold: u8,
opts: &'a DetectionOptions,
/// Frames that cannot be marked as keyframes due to the algorithm excluding them.
/// Storing the frame numbers allows us to avoid looking back more than one frame.
... | SceneChangeDetector | identifier_name |
debugger.rs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use std::collections::BTreeMap;
use std::io::Read;
use std::process::{Child, Command};
use anyhow::{bail, format_err, Result};
use debuggable_module::path::FilePath;
use debuggable_module::Address;
use pete::{Ptracer, Restart, Signal, Stop, Tr... |
pub fn spawn(&mut self, cmd: Command) -> Result<Child> {
Ok(self.context.tracer.spawn(cmd)?)
}
pub fn wait(self, mut child: Child) -> Result<Output> {
if let Err(err) = self.wait_on_stops() {
// Ignore error if child already exited.
let _ = child.kill();
... | {
let context = DebuggerContext::new();
Self {
context,
event_handler,
}
} | identifier_body |
debugger.rs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use std::collections::BTreeMap;
use std::io::Read;
use std::process::{Child, Command};
use anyhow::{bail, format_err, Result};
use debuggable_module::path::FilePath;
use debuggable_module::Address;
use pete::{Ptracer, Restart, Signal, Stop, Tr... |
#[cfg(target_arch = "aarch64")]
let instruction_pointer = &mut regs.pc;
// Compute what the last PC would have been _if_ we stopped due to a soft breakpoint.
//
// If we don't have a registered breakpoint, then we will not use this value.
let pc = Address(instruction_po... | #[cfg(target_arch = "x86_64")]
let instruction_pointer = &mut regs.rip; | random_line_split |
debugger.rs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use std::collections::BTreeMap;
use std::io::Read;
use std::process::{Child, Command};
use anyhow::{bail, format_err, Result};
use debuggable_module::path::FilePath;
use debuggable_module::Address;
use pete::{Ptracer, Restart, Signal, Stop, Tr... | (self, mut child: Child) -> Result<Output> {
if let Err(err) = self.wait_on_stops() {
// Ignore error if child already exited.
let _ = child.kill();
return Err(err);
}
// Currently unavailable on Linux.
let status = None;
let stdout = if let... | wait | identifier_name |
debugger.rs | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use std::collections::BTreeMap;
use std::io::Read;
use std::process::{Child, Command};
use anyhow::{bail, format_err, Result};
use debuggable_module::path::FilePath;
use debuggable_module::Address;
use pete::{Ptracer, Restart, Signal, Stop, Tr... |
// Cannot panic due to initial length check.
let first = &maps[0];
let path = if let MMapPath::Path(path) = &first.pathname {
FilePath::new(path.to_string_lossy())?
} else {
bail!("module image mappings must be file-backed");
};
for map in &map... | {
bail!("no executable mapping for module image");
} | conditional_block |
lib.rs | //! [![license:MIT/Apache-2.0][1]](https://github.com/uazu/stakker)
//! [![github:uazu/stakker][2]](https://github.com/uazu/stakker)
//! [![crates.io:stakker][3]](https://crates.io/crates/stakker)
//! [![docs.rs:stakker][4]](https://docs.rs/stakker)
//! [![uazu.github.io:stakker][5]](https://uaz... | //!
//! If no inter-thread operations are active, then **Stakker** will
//! never do locking or any atomic operations, nor block for any
//! reason. So the code can execute at full speed without triggering
//! any CPU memory fences or whatever. Usually the only thing that
//! blocks would be the external I/O poller w... | //! provided with arguments. These are also efficient due to
//! inlining. In this case two chunks of inlined code are generated
//! for each by the compiler: the first which accepts arguments and
//! pushes the second one onto the queue. | random_line_split |
decisiontree.rs | //! llvm/decisiontree.rs - Defines how to codegen a decision tree
//! via `codegen_tree`. This decisiontree is the result of compiling
//! a match expression into a decisiontree during type inference.
use crate::llvm::{ Generator, CodeGen };
use crate::types::pattern::{ DecisionTree, Case, VariantTag };
use crate::type... | cases.last().unwrap().tag == None
}
/// codegen an else/match-all case of a particular constructor in a DecisionTree.
/// If there is no MatchAll case (represented by a None value for case.tag) then
/// a block is created with an llvm unreachable assertion.
fn codegen_match_else_block<'c>(&... | }
}
/// When creating a decision tree, any match all case is always last in the case list.
fn has_match_all_case(&self, cases: &[Case]) -> bool { | random_line_split |
decisiontree.rs | //! llvm/decisiontree.rs - Defines how to codegen a decision tree
//! via `codegen_tree`. This decisiontree is the result of compiling
//! a match expression into a decisiontree during type inference.
use crate::llvm::{ Generator, CodeGen };
use crate::types::pattern::{ DecisionTree, Case, VariantTag };
use crate::type... | <'c>(&mut self, tag: &VariantTag, cache: &mut ModuleCache<'c>) -> Option<BasicValueEnum<'g>> {
match tag {
VariantTag::True => Some(self.bool_value(true)),
VariantTag::False => Some(self.bool_value(false)),
VariantTag::Unit => Some(self.unit_value()),
// TODO: Re... | get_constructor_tag | identifier_name |
decisiontree.rs | //! llvm/decisiontree.rs - Defines how to codegen a decision tree
//! via `codegen_tree`. This decisiontree is the result of compiling
//! a match expression into a decisiontree during type inference.
use crate::llvm::{ Generator, CodeGen };
use crate::types::pattern::{ DecisionTree, Case, VariantTag };
use crate::type... |
/// Performs the union downcast, binding each field of the downcasted variant
/// the the appropriate DefinitionInfoIds held within the given Case.
fn bind_pattern_fields<'c>(&mut self, case: &Case, matched_value: BasicValueEnum<'g>, cache: &mut ModuleCache<'c>) {
let variant = self.cast_to_varian... | {
for id in field {
let typ = self.follow_bindings(cache.definition_infos[id.0].typ.as_ref().unwrap(), cache);
self.definitions.insert((*id, typ), value);
}
} | identifier_body |
main.rs | // -- SymSpell --
// Explanation at
// https://medium.com/@wolfgarbe/1000x-faster-spelling-correction-algorithm-2012-8701fcd87a5f
// TL;DR, HashTable keys are generated
// from all words + all possible
// permutations of those words with up
// to two deletes, and the data held
// in each key is the correctly spelled
/... |
fn generate_permutations(&self, word: &str) -> Vec<String> {
let mut permutations: Vec<String> = Vec::new();
// Generate permutations of this word
for i in 0..word.len() {
let mut permuted: Vec<char> = word.chars().collect();
permuted.remove(i);
permutat... | {
// Vec<String>
// Must only contain inserts of
// correct words
let permuted_keys = self.permutations_of(word);
for i in permuted_keys {
// if error key exists
if let Some(x) = self.error_map.get_mut(&i) {
let mut new_set: HashMap<String,... | identifier_body |
main.rs | // -- SymSpell --
// Explanation at
// https://medium.com/@wolfgarbe/1000x-faster-spelling-correction-algorithm-2012-8701fcd87a5f
// TL;DR, HashTable keys are generated
// from all words + all possible
// permutations of those words with up
// to two deletes, and the data held
// in each key is the correctly spelled
/... | match d.check(&cmd.trim()) {
Some(x) => println!("Did you mean {}?", x),
_ => println!("Not found :(")
};
}
}
} | io::stdin().read_line(&mut word).expect("no work... >:(");
println!("value? ");
io::stdin().read_line(&mut value).expect("no work... >:(");
d.insert_with_permutations_and_count(word.trim().as_ref(), value.trim().parse().expect("not a number"));
} else { | random_line_split |
main.rs | // -- SymSpell --
// Explanation at
// https://medium.com/@wolfgarbe/1000x-faster-spelling-correction-algorithm-2012-8701fcd87a5f
// TL;DR, HashTable keys are generated
// from all words + all possible
// permutations of those words with up
// to two deletes, and the data held
// in each key is the correctly spelled
/... | () -> Dictionary {
Dictionary {
word_map: HashMap::new(),
error_map: HashMap::new(),
error_distance: 2
}
}
fn insert(&mut self, word: &str) {
if let Some(x) = self.word_map.get_mut(word) {
x.score += 1;
} else {
self.wo... | new | identifier_name |
main.rs | // -- SymSpell --
// Explanation at
// https://medium.com/@wolfgarbe/1000x-faster-spelling-correction-algorithm-2012-8701fcd87a5f
// TL;DR, HashTable keys are generated
// from all words + all possible
// permutations of those words with up
// to two deletes, and the data held
// in each key is the correctly spelled
/... | else if let Some(x) = self.error_map.get(word) {
if x.len() > 1 {
Some(self.find_best_match(x.to_vec()))
} else {
Some(x[0].clone())
}
} else {
None
}
};
if let Some(x) = fin... | {
Some(x.word.clone())
} | conditional_block |
consumer.rs | use super::{
delegate::DelegateMut,
observer::{DelegateObserver, Observer},
utils::modulus,
};
use crate::utils::{slice_assume_init_mut, slice_assume_init_ref, write_uninit_slice};
use core::{iter::Chain, mem::MaybeUninit, ptr, slice};
#[cfg(feature = "std")]
use std::io::{self, Write};
/// Consumer part o... | <'a, C: Consumer> {
target: &'a C,
slices: (&'a [MaybeUninit<C::Item>], &'a [MaybeUninit<C::Item>]),
len: usize,
}
impl<'a, C: Consumer> PopIter<'a, C> {
pub fn new(target: &'a mut C) -> Self {
let slices = target.occupied_slices();
Self {
len: slices.0.len() + slices.1.len()... | PopIter | identifier_name |
consumer.rs | use super::{
delegate::DelegateMut,
observer::{DelegateObserver, Observer},
utils::modulus,
};
use crate::utils::{slice_assume_init_mut, slice_assume_init_ref, write_uninit_slice};
use core::{iter::Chain, mem::MaybeUninit, ptr, slice};
#[cfg(feature = "std")]
use std::io::{self, Write};
/// Consumer part o... |
#[inline]
fn try_pop(&mut self) -> Option<Self::Item> {
self.base_mut().try_pop()
}
#[inline]
fn pop_slice(&mut self, elems: &mut [Self::Item]) -> usize
where
Self::Item: Copy,
{
self.base_mut().pop_slice(elems)
}
#[inline]
fn iter(&self) -> Iter<'_, Se... | self.base_mut().as_mut_slices()
} | random_line_split |
consumer.rs | use super::{
delegate::DelegateMut,
observer::{DelegateObserver, Observer},
utils::modulus,
};
use crate::utils::{slice_assume_init_mut, slice_assume_init_ref, write_uninit_slice};
use core::{iter::Chain, mem::MaybeUninit, ptr, slice};
#[cfg(feature = "std")]
use std::io::{self, Write};
/// Consumer part o... |
};
unsafe { self.advance_read_index(count) };
count
}
fn into_iter(self) -> IntoIter<Self> {
IntoIter::new(self)
}
/// Returns an iterator that removes items one by one from the ring buffer.
fn pop_iter(&mut self) -> PopIter<'_, Self> {
PopIter::new(self)
... | {
unsafe { write_uninit_slice(elems.get_unchecked_mut(..right.len()), right) };
right.len()
} | conditional_block |
v4.rs | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed un... | egacy_table_definition: &DefinitionV4) -> Self {
let mut definition = Self::new(legacy_table_definition.version, None);
let fields = legacy_table_definition.fields.iter().map(From::from).collect::<Vec<FieldV5>>();
definition.set_fields(fields);
let fields = legacy_table_definition.loca... | om(l | identifier_name |
v4.rs | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed un... | lse { None })
.for_each(|(name, definitions)| {
definitions.iter().for_each(|definition| {
schema.add_definition(name, &From::from(definition));
})
});
schema
}
}
impl From<&DefinitionV4> for DefinitionV5 {
fn from(legacy_table... | Some((name, definitions)) } e | conditional_block |
v4.rs | //---------------------------------------------------------------------------//
// Copyright (c) 2017-2023 Ismael Gutiérrez González. All rights reserved.
//
// This file is part of the Rusted PackFile Manager (RPFM) project,
// which can be found here: https://github.com/Frodo45127/rpfm.
//
// This file is licensed un... | FieldTypeV4::I16 => Self::I16,
FieldTypeV4::I32 => Self::I32,
FieldTypeV4::I64 => Self::I64,
FieldTypeV4::F32 => Self::F32,
FieldTypeV4::F64 => Self::F64,
FieldTypeV4::ColourRGB => Self::ColourRGB,
FieldTypeV4::StringU8 => Self::StringU... | random_line_split | |
service.go | // Copyright © 2020, 2021 Attestant Limited.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | accountsMu.Unlock()
log.Trace().Dur("elapsed", time.Since(started)).Int("accounts", len(walletAccounts)).Msg("Imported accounts")
}(ctx, sem, &wg, i, &accountsMu)
}
wg.Wait()
log.Trace().Int("accounts", len(accounts)).Msg("Obtained accounts")
if len(accounts) == 0 && len(s.accounts) != 0 {
log.Warn().Msg... |
accounts[k] = v
}
| conditional_block |
service.go | // Copyright © 2020, 2021 Attestant Limited.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... |
// Refresh refreshes the accounts from Dirk, and account validator state from
// the validators provider.
// This is a relatively expensive operation, so should not be run in the validating path.
func (s *Service) Refresh(ctx context.Context) {
if err := s.refreshAccounts(ctx); err != nil {
log.Error().Err(err).Msg... |
parameters, err := parseAndCheckParameters(params...)
if err != nil {
return nil, errors.Wrap(err, "problem with parameters")
}
// Set logging.
log = zerologger.With().Str("service", "accountmanager").Str("impl", "dirk").Logger()
if parameters.logLevel != log.GetLevel() {
log = log.Level(parameters.logLevel... | identifier_body |
service.go | // Copyright © 2020, 2021 Attestant Limited.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | eth2client "github.com/attestantio/go-eth2-client"
api "github.com/attestantio/go-eth2-client/api/v1"
"github.com/attestantio/go-eth2-client/spec/phase0"
"github.com/attestantio/vouch/services/chaintime"
"github.com/attestantio/vouch/services/metrics"
"github.com/attestantio/vouch/services/validatorsmanager"
"gi... | "time"
| random_line_split |
service.go | // Copyright © 2020, 2021 Attestant Limited.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or a... | ctx context.Context) error {
// Create the relevant wallets.
wallets := make([]e2wtypes.Wallet, 0, len(s.accountPaths))
pathsByWallet := make(map[string][]string)
for _, path := range s.accountPaths {
pathBits := strings.Split(path, "/")
var paths []string
var exists bool
if paths, exists = pathsByWallet[p... | efreshAccounts( | identifier_name |
pinhole.go | package pinhole
import (
"fmt"
"image"
"image/color"
"image/png"
"io"
"io/ioutil"
"math"
"os"
"sort"
"strconv"
"strings"
"golang.org/x/image/font/gofont/goregular"
"github.com/fogleman/gg"
"github.com/golang/freetype/truetype"
"github.com/google/btree"
)
const circleSteps = 45
var gof = func() *true... |
if imax[i] < jmax[i] {
return i != 2
}
if imin[i] > jmin[i] {
return i == 2
}
if imin[i] < jmin[i] {
return i != 2
}
}
return false
}
func (a byDistance) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (p *Pinhole) Image(width, height int, opts *ImageOptions) *image.RGBA {
if opts == nil {
... | {
return i == 2
} | conditional_block |
pinhole.go | package pinhole
import (
"fmt"
"image"
"image/color"
"image/png"
"io"
"io/ioutil"
"math"
"os"
"sort"
"strconv"
"strings"
"golang.org/x/image/font/gofont/goregular"
"github.com/fogleman/gg"
"github.com/golang/freetype/truetype"
"github.com/google/btree"
)
const circleSteps = 45
var gof = func() *true... | () []float64 {
min, max := l.Rect()
return []float64{
(max[0] + min[0]) / 2,
(max[1] + min[1]) / 2,
(max[2] + min[2]) / 2,
}
}
type Pinhole struct {
lines []*line
stack []int
}
func New() *Pinhole {
return &Pinhole{}
}
func (p *Pinhole) Begin() {
p.stack = append(p.stack, len(p.lines))
}
func (p *Pinhole... | Center | identifier_name |
pinhole.go | package pinhole
import (
"fmt"
"image"
"image/color"
"image/png"
"io"
"io/ioutil"
"math"
"os"
"sort"
"strconv"
"strings"
"golang.org/x/image/font/gofont/goregular"
"github.com/fogleman/gg"
"github.com/golang/freetype/truetype"
"github.com/google/btree"
)
const circleSteps = 45
var gof = func() *true... | c.LineTo(dx2, dy2)
}
c.LineTo(dx3, dy3)
if cap2 {
ax1, ay1 := destination(dx3, dy3, a-math.Pi*2, -t2*cubicCorner)
ax2, ay2 := destination(dx4, dy4, a-math.Pi*2, -t2*cubicCorner)
c.CubicTo(ax1, ay1, ax2, ay2, dx4, dy4)
} else {
c.LineTo(dx4, dy4)
}
c.LineTo(dx1, dy1)
c.ClosePath()
return nil
}
func ons... | c.CubicTo(ax1, ay1, ax2, ay2, dx2, dy2)
} else { | random_line_split |
pinhole.go | package pinhole
import (
"fmt"
"image"
"image/color"
"image/png"
"io"
"io/ioutil"
"math"
"os"
"sort"
"strconv"
"strings"
"golang.org/x/image/font/gofont/goregular"
"github.com/fogleman/gg"
"github.com/golang/freetype/truetype"
"github.com/google/btree"
)
const circleSteps = 45
var gof = func() *true... |
type Pinhole struct {
lines []*line
stack []int
}
func New() *Pinhole {
return &Pinhole{}
}
func (p *Pinhole) Begin() {
p.stack = append(p.stack, len(p.lines))
}
func (p *Pinhole) End() {
if len(p.stack) > 0 {
p.stack = p.stack[:len(p.stack)-1]
}
}
func (p *Pinhole) Rotate(x, y, z float64) {
var i int
if l... | {
min, max := l.Rect()
return []float64{
(max[0] + min[0]) / 2,
(max[1] + min[1]) / 2,
(max[2] + min[2]) / 2,
}
} | identifier_body |
Tools.py | """
Created on Wed Jun 21 09:50:15 2017
@author: cwvanmierlo
"""
import time;
import sys;
import os;
def resource_path(relative_path):
#This function is needed for PyInstaller, without this function the
#incorrect path will be pulled while compiling the .EXE
if hasattr(sys, '_MEIPASS'):
return o... |
def __repr__(self):
return "ord:%d\t|\tchr:%s\t|\tline:%d\t|\tcolumn:%d\t\n" % (self.ordNumber, self.ordCharacter, self.lineOccurence, self.colOccurence);
f = open(fileName, "r");
lines = f.readlines();
f.close();
errorArray = []
for i in range(len(lines)... | turn self.sourceLine;
| identifier_body |
Tools.py | """
Created on Wed Jun 21 09:50:15 2017
@author: cwvanmierlo
"""
import time;
import sys;
import os;
def resource_path(relative_path):
#This function is needed for PyInstaller, without this function the
#incorrect path will be pulled while compiling the .EXE
if hasattr(sys, '_MEIPASS'):
return o... | elf):
return self.ordNumber;
def getOrdCharacter(self):
return self.ordCharacter;
def getLineOccurence(self):
return self.lineOccurence;
def getColOccurence(self):
return self.colOccurence;
def getSourceL... | tOrdNumber(s | identifier_name |
Tools.py | """
Created on Wed Jun 21 09:50:15 2017
@author: cwvanmierlo
"""
import time;
import sys;
import os;
def resource_path(relative_path):
#This function is needed for PyInstaller, without this function the
#incorrect path will be pulled while compiling the .EXE
if hasattr(sys, '_MEIPASS'):
return o... |
fNew.close();
sortOrder = lines[0];
exVarIndex1 = sortOrder.split(";").index("username");
exVarIndex2 = sortOrder.split(";").index("grouphand");
fExisting = open(newFile + "_existing" + ".txt", "w");
fExisting.write(lines[0].split(";")[exVarIndex1] + ";" + lines[0].split... | fNew.write(newUser); | conditional_block |
Tools.py | """
Created on Wed Jun 21 09:50:15 2017
@author: cwvanmierlo
"""
import time;
import sys;
import os;
def resource_path(relative_path):
#This function is needed for PyInstaller, without this function the
#incorrect path will be pulled while compiling the .EXE
if hasattr(sys, '_MEIPASS'):
return o... |
time.sleep(1);
waitForGroupsLoaded();
############################## create subgroups ################################
for i in range(len(subGroupNames)):
createSubGroup(subGroupNames[i]);
waitForGroupsLoaded();
return driver; |
waitForInCourseId(); | random_line_split |
traits.rs | /// One of the great discoveries in programming is that it’s possible to write code that operates on
/// values of many different types, even types that haven’t been invented yet.
///
/// It’s called "polymorphism".
///
/// # Traits and Generics
///
/// Rust supports polymorphism with two related features: traits and g... | fn name(&self) -> &'static str {
"Dave"
}
fn noise(&self) -> &'static str {
"Moo"
}
}
pub fn random_animal(random_number: f64) -> Box<dyn Animal> {
if random_number < 0.5 {
Box::new(Sheep {
name: "Bob",
naked: true,
})
} else {
Bo... | pub struct Cow {}
impl Animal for Cow { | random_line_split |
traits.rs | /// One of the great discoveries in programming is that it’s possible to write code that operates on
/// values of many different types, even types that haven’t been invented yet.
///
/// It’s called "polymorphism".
///
/// # Traits and Generics
///
/// Rust supports polymorphism with two related features: traits and g... | f.state.take() {
self.state = Some(s.reject());
}
}
pub fn approve(&mut self) {
if let Some(s) = self.state.take() {
self.state = Some(s.approve());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_min() {
assert_eq!(min(3, 5... | = sel | identifier_name |
traits.rs | /// One of the great discoveries in programming is that it’s possible to write code that operates on
/// values of many different types, even types that haven’t been invented yet.
///
/// It’s called "polymorphism".
///
/// # Traits and Generics
///
/// Rust supports polymorphism with two related features: traits and g... | ent any trait on any type, as long as either the trait or the type is
/// introduced in the current crate. This means that any time you want to add a method to any type,
/// you can use a trait to do it. This is called an "extension trait".
pub trait IsEmoji {
fn is_emoji(&self) -> bool;
}
impl IsEmoji for char {
... | t lets you implem | conditional_block |
traits.rs | /// One of the great discoveries in programming is that it’s possible to write code that operates on
/// values of many different types, even types that haven’t been invented yet.
///
/// It’s called "polymorphism".
///
/// # Traits and Generics
///
/// Rust supports polymorphism with two related features: traits and g... | State for Published {
fn request_review(self: Box<Self>) -> Box<dyn State> {
self
}
fn approve(self: Box<Self>) -> Box<dyn State> {
self
}
fn reject(self: Box<Self>) -> Box<dyn State> {
self
}
fn content<'a>(&self, post: &'a Post) -> &'a str {
post.content.as_... | }
}
struct Published {}
impl | identifier_body |
message.rs | //! Definitions of network messages.
use std::error::Error;
use std::{net, sync::Arc};
use chrono::{DateTime, Utc};
use zebra_chain::block::{Block, BlockHeader, BlockHeaderHash};
use zebra_chain::{transaction::Transaction, types::BlockHeight};
use super::inv::InventoryHash;
use super::types::*;
use crate::meta_addr... | (e: E) -> Self {
Message::Reject {
message: e.to_string(),
// The generic case, impls for specific error types should
// use specific varieties of `RejectReason`.
ccode: RejectReason::Other,
reason: e.source().unwrap().to_string(),
// Al... | from | identifier_name |
message.rs | //! Definitions of network messages.
use std::error::Error;
use std::{net, sync::Arc};
use chrono::{DateTime, Utc};
use zebra_chain::block::{Block, BlockHeader, BlockHeaderHash};
use zebra_chain::{transaction::Transaction, types::BlockHeight};
use super::inv::InventoryHash;
use super::types::*;
use crate::meta_addr... | },
/// A `headers` message.
///
/// Returns block headers in response to a getheaders packet.
///
/// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#headers)
// Note that the block headers in this packet include a
// transaction count (a var_int, so there can be m... | ///
/// Set to zero to get as many blocks as possible (500).
hash_stop: BlockHeaderHash, | random_line_split |
openqabot.py | # -*- coding: utf-8 -*-
from collections import namedtuple
from datetime import date
import md5
from pprint import pformat
import re
from urllib2 import HTTPError
import requests
import osc.core
import ReviewBot
from osclib.comments import CommentAPI
from suse import SUSEUpdate
try:
from xml.etree import cElem... | (self):
if self.ibs:
self.check_suse_incidents()
# first calculate the latest build number for current jobs
self.gather_test_builds()
started = []
# then check progress on running incidents
for req in self.requests:
jobs = self.request_get_openq... | check_requests | identifier_name |
openqabot.py | # -*- coding: utf-8 -*-
from collections import namedtuple
from datetime import date
import md5
from pprint import pformat
import re
from urllib2 import HTTPError
import requests
import osc.core
import ReviewBot
from osclib.comments import CommentAPI
from suse import SUSEUpdate
try:
from xml.etree import cElem... |
# if there is something to report, hold the request
# TODO: what is this ?
# qa_state = QA_FAILED
# gmsg = groups[gl]
groups[gl]['failed'].append(job_summary)
msg = ''
for group in sorted(groups.keys()):
msg += "\n\n" + groups[gr... | groups[gl]['passed'] = groups[gl]['passed'] + 1
continue | conditional_block |
openqabot.py | # -*- coding: utf-8 -*-
from collections import namedtuple
from datetime import date
import md5
from pprint import pformat
import re
from urllib2 import HTTPError
import requests
import osc.core
import ReviewBot
from osclib.comments import CommentAPI
from suse import SUSEUpdate
try:
from xml.etree import cElem... |
def calculate_incidents(self, incidents):
"""
get incident numbers from SUSE:Maintenance:Test project
returns dict with openQA var name : string with numbers
"""
self.logger.debug("calculate_incidents: {}".format(pformat(incidents)))
l_incidents = []
for kin... | project = 'SUSE:Maintenance:{}'.format(incident)
xpath = "(state/@name='review') and (action/source/@project='{}' and action/@type='maintenance_release')".format(project)
res = osc.core.search(self.apiurl, request=xpath)['request']
# return the one and only (or None)
return res.find('re... | identifier_body |
openqabot.py | # -*- coding: utf-8 -*-
from collections import namedtuple
from datetime import date
import md5
from pprint import pformat
import re
from urllib2 import HTTPError
import requests
import osc.core
import ReviewBot
from osclib.comments import CommentAPI
from suse import SUSEUpdate
try:
from xml.etree import cElem... | types = {a.type for a in req.actions}
if 'maintenance_release' in types:
src_prjs = {a.src_project for a in req.actions}
if len(src_prjs) != 1:
raise Exception("can't handle maintenance_release from different incidents")
build = src_prjs.pop()
... | def request_get_openqa_jobs(self, req, incident=True, test_repo=False):
ret = None | random_line_split |
all.js |
//子弹: 类(构造函数)
function Bullet() {
//属性:
this.ele = document.createElement("div");
//当前子弹所在gameEngine.bullets对象中的id
this.id = parseInt(Math.random()*100000) + "";
//方法:
//初始化方法init
this.init = function() {
this.ele.className = "bullet";
gameEngine.ele.appendChild(this.ele); //添加到游戏界面main上
gameEngine... | .ele.appendChild(this.scoreNode);
},
//让背景图移动
move: function() {
var y = 0;
setInterval(function(){
gameEngine.ele.style.backgroundPositionY = y++ + "px";
}, 30);
}
}
//我的飞机:(对象)
var myPlane = {
//属性ele: 我的飞机div节点
ele: null,
fireInterval: 80, //发射子弹的频率
//方法:
//初始化方法init:
init: funct... | alert("Game Over!");
location.reload();
});
}
}
}, 30);
},
//显示分数
showScore: function() {
this.scoreNode = document.createElement("div");
this.scoreNode.className = "score";
this.scoreNode.innerHTML = "0";
gameEngine | identifier_body |
all.js |
//子弹: 类(构造函数)
function Bullet() {
//属性:
this.ele = document.createElement("div");
//当前子弹所在gameEngine.bullets对象中的id
this.id = parseInt(Math.random()*100000) + "";
//方法:
//初始化方法init
this.init = function() {
this.ele.className = "bullet";
gameEngine.ele.appendChild(this.ele); //添加到游戏界面main上
gameEngine... | - obj1.offsetHeight/2;
var downSide = obj2.offsetTop + obj2.offsetHeight + obj1.offsetHeight/2;
var x = obj1.offsetLeft+obj1.offsetWidth/2;
var y = obj1.offsetTop + obj1.offsetHeight/2;
if(x > leftSide && x < rightSide && y > upSide && y < downSide){
return true;
}
}
return false;
}
... | tSide = obj2.offsetLeft+obj2.offsetWidth+obj1.offsetWidth/2;
var upSide = obj2.offsetTop | conditional_block |
all.js | //子弹: 类(构造函数)
function Bullet() {
//属性:
this.ele = document.createElement("div");
//当前子弹所在gameEngine.bullets对象中的id
this.id = parseInt(Math.random()*100000) + "";
//方法:
//初始化方法init
this.init = function() {
this.ele.className = "bullet";
gameEngine.ele.appendChild(this.ele); //添加到游戏界面main上
gameEngine.bu... | }
}, 30);
}
//受到一点伤害
this.hurt = function() {
this.hp--; //掉一点血
if (this.hp == 0) { //当血量为0时
this.boom(); //爆炸
//把分数添加
gameEngine.scoreNode.innerHTML = (gameEngine.scoreNode.innerHTML-0) + this.score;
}
}
//爆炸
this.boom = function() {
clearInterval(this.timer); //关闭move中的定时器, 让敌机停止移动
... | self.ele.style.top = self.ele.offsetTop + self.speed + "px"; | random_line_split |
all.js |
//子弹: 类(构造函数)
function Bullet() {
//属性:
this.ele = document.createElement("div");
//当前子弹所在gameEngine.bullets对象中的id
this.id = parseInt(Math.random()*100000) + "";
//方法:
//初始化方法init
this.init = function() {
this.ele.className = "bullet";
gameEngine.ele.appendChild(this.ele); //添加到游戏界面main上
gameEngine... | eight + obj1.offsetHeight/2;
var x = obj1.offsetLeft+obj1.offsetWidth/2;
var y = obj1.offsetTop + obj1.offsetHeight/2;
if(x > leftSide && x < rightSide && y > upSide && y < downSide){
return true;
}
}
return false;
}
//敌机: 类(构造函数)
function Enemy(type) {
//属性:
this.ele = document.crea... | offsetH | identifier_name |
main.rs | use random_fast_rng::{FastRng, Random};
use rusqlite::{params, Connection, DropBehavior};
use std::fs;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant};
const ITER_SECS: u64 = 5;
const USE_RWLOCK: bool = false;
c... | else { "!" }
}
perf_vec.push(PerfRecord {
config: format!("{}wal, {}shared_cache", not_str(options.wal), not_str(options.shared_cache)),
readers: 1,
writers,
reads_per_sec: total_reads as f64 / ITER_SECS as f64,
wr... | { "" } | conditional_block |
main.rs | use random_fast_rng::{FastRng, Random};
use rusqlite::{params, Connection, DropBehavior};
use std::fs;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant};
const ITER_SECS: u64 = 5;
const USE_RWLOCK: bool = false;
c... |
pub fn seed(&mut self) -> std::io::Result<Vec<u16>> {
let mut transaction = self
.conn
.transaction()
.expect("Could not open DB transaction");
transaction.set_drop_behavior(DropBehavior::Commit);
let mut query = transaction
.prepare(
... | {
if options.wal {
self.conn
.pragma_update(None, "journal_mode", &"WAL".to_owned())
.expect("Error applying WAL journal_mode");
}
self.conn
.execute(
r#"
CREATE TABLE "kv" (
"key" INTEGER NOT NULL,
"value" BLOB NOT NULL,... | identifier_body |
main.rs | use random_fast_rng::{FastRng, Random};
use rusqlite::{params, Connection, DropBehavior};
use std::fs;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant};
const ITER_SECS: u64 = 5;
const USE_RWLOCK: bool = false;
c... | {
conn: rusqlite::Connection,
}
#[derive(Copy, Clone, Debug)]
struct DbOptions {
wal: bool,
shared_cache: bool,
}
impl DbOptions {
fn db_flags(&self) -> rusqlite::OpenFlags {
use rusqlite::OpenFlags;
let mut flags = OpenFlags::empty();
flags.set(OpenFlags::SQLITE_OPEN_CREATE,... | Database | identifier_name |
main.rs | use random_fast_rng::{FastRng, Random};
use rusqlite::{params, Connection, DropBehavior};
use std::fs;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{mpsc, Arc, RwLock};
use std::thread;
use std::time::{Duration, Instant};
const ITER_SECS: u64 = 5;
const USE_RWLOCK: bool = false;
c... | let key = rng.get_u16();
let timer = Instant::now();
let _guard;
if USE_RWLOCK {
_guard = rwlock.write().expect("Cannot unlock for read!");
}
let rows_updated = query
.execute(params![key, value])
.expect("Failed to issue update query!... | rng.fill_bytes(&mut value);
while !stop.load(Ordering::Relaxed) { | random_line_split |
lib.rs | //! Extensions for [glutin](https://crates.io/crates/glutin) to initialize & update old school
//! [gfx](https://crates.io/crates/gfx). _An alternative to gfx_window_glutin_.
//!
//! # Example
//! ```no_run
//! type ColorFormat = gfx::format::Srgba8;
//! type DepthFormat = gfx::format::DepthStencil;
//!
//! # fn main()... |
}
/// Recreate and replace gfx views if the dimensions have changed.
pub fn resize_views<Color: RenderFormat, Depth: DepthFormat>(
new_size: winit::dpi::PhysicalSize<u32>,
color_view: &mut RenderTargetView<R, Color>,
depth_view: &mut DepthStencilView<R, Depth>,
) {
if let Some((cv, dv)) = resized_view... | {
Init {
window: self.window,
gl_config: self.gl_config,
gl_surface: self.gl_surface,
gl_context: self.gl_context,
device: self.device,
factory: self.factory,
color_view: Typed::new(self.color_view),
depth_view: Type... | identifier_body |
lib.rs | //! Extensions for [glutin](https://crates.io/crates/glutin) to initialize & update old school
//! [gfx](https://crates.io/crates/gfx). _An alternative to gfx_window_glutin_.
//!
//! # Example
//! ```no_run
//! type ColorFormat = gfx::format::Srgba8;
//! type DepthFormat = gfx::format::DepthStencil;
//!
//! # fn main()... | () -> Self {
Self::Specific(0)
}
}
impl From<u8> for NumberOfSamples {
fn from(val: u8) -> Self {
Self::Specific(val)
}
}
impl NumberOfSamples {
fn find<'a>(
self,
mut configs: impl Iterator<Item = (usize, &'a glutin::config::Config)>,
) -> Option<(usize, &'a glutin... | default | identifier_name |
lib.rs | //! Extensions for [glutin](https://crates.io/crates/glutin) to initialize & update old school
//! [gfx](https://crates.io/crates/gfx). _An alternative to gfx_window_glutin_.
//!
//! # Example
//! ```no_run
//! type ColorFormat = gfx::format::Srgba8;
//! type DepthFormat = gfx::format::DepthStencil;
//!
//! # fn main()... | .with_stencil_size(stencil_bits);
let mut no_suitable_config = false;
let (window, gl_config) = glutin_winit::DisplayBuilder::new()
.with_window_builder(Some(self.winit))
.build(self.event_loop, config_attrs, |configs| {
let mut configs: Vec<_> = conf... | .config_attrs
.with_alpha_size(alpha_bits)
.with_depth_size(depth_total_bits - stencil_bits) | random_line_split |
__init___.py | # -*- coding: utf-8 -*-
import shutil
import os
import datetime
from config import BaseConfig
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from form import LoginForm, SignUpForm
from flask.ext.mail import Mail, Message
from werkzeug import secure_filename
from flask.ext.script import... | if current_user.admin != 1:
return redirect(url_for('index'))
users = User.query.filter_by(admin=0).all()
return render_template('lista.html', usuarios=users, admin=1)
@app.route('/datos/<estudiante>', methods=['GET'])
@login_required
def datos(estudiante):
if current_user.admin != 1:
retur... | identifier_name | |
__init___.py | # -*- coding: utf-8 -*-
import shutil
import os
import datetime
from config import BaseConfig
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from form import LoginForm, SignUpForm
from flask.ext.mail import Mail, Message
from werkzeug import secure_filename
from flask.ext.script import... | if item[1] == "1":
aceptados.append(doc)
with engine.connect() as connection:
engine.execute("update users set status_"+doc+"=1 where email ='"+u.email+"'")
else:
rechazados.append(doc)
with engine.connect() as connection:
e... | doc = item[0].split('_')[1]
revisados.append(doc.title()) | random_line_split |
__init___.py | # -*- coding: utf-8 -*-
import shutil
import os
import datetime
from config import BaseConfig
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from form import LoginForm, SignUpForm
from flask.ext.mail import Mail, Message
from werkzeug import secure_filename
from flask.ext.script import... |
@login_manager.user_loader
def load_user(user_id):
return User.query.get(unicode(user_id))
@app.route('/inicio/<success>')
@login_required
def inicio(success):
user = current_user
status = False
if user.status == 'Listo':
status = True
files = {'Acta': user.acta, 'Credencial': user.cred,... | return "Acceso no autorizado, favor de iniciar sesión.".decode('utf8'), 401
| identifier_body |
__init___.py | # -*- coding: utf-8 -*-
import shutil
import os
import datetime
from config import BaseConfig
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from form import LoginForm, SignUpForm
from flask.ext.mail import Mail, Message
from werkzeug import secure_filename
from flask.ext.script import... | w = engine.execute("select status_acta, status_credencial, status_foto from users where email='"+u.email+"'")
estados = tuple(row.fetchone())
# return "<script type=\"text/javascript\">\
# alert(\""+str(estados)+"\");\
# window.location.href = '/admin'\
# </script>"
if l... | em[0].split('_')[1]
revisados.append(doc.title())
if item[1] == "1":
aceptados.append(doc)
with engine.connect() as connection:
engine.execute("update users set status_"+doc+"=1 where email ='"+u.email+"'")
else:
rechazados.append(doc)
... | conditional_block |
ply_loader.rs | use std::io::{Read, Seek, BufReader, BufRead, SeekFrom};
use std::error;
use std::fmt;
use crate::model::ply::{PlyFileHeader, PlyElementDescriptor, standard_formats, PlyPropertyDescriptor, PlyScalar, PlyDatatype};
use std::str::{SplitAsciiWhitespace, FromStr};
use byteorder::{LittleEndian, ByteOrder};
use num::{self, N... | a.unwrap()
};
// Make new descriptor
let elem_index = element_vec.len() as u32;
current_element = Some(PlyElementDescriptor::new(elem_index, elem_name, num_entries));
}
// Property descriptor
else if line.starts_with("property") {
// Check that we are actually in an elem... | let a = a.parse::<u32>();
if a.is_err() {
return ply_err("Invalid element descriptor");
} | random_line_split |
ply_loader.rs | use std::io::{Read, Seek, BufReader, BufRead, SeekFrom};
use std::error;
use std::fmt;
use crate::model::ply::{PlyFileHeader, PlyElementDescriptor, standard_formats, PlyPropertyDescriptor, PlyScalar, PlyDatatype};
use std::str::{SplitAsciiWhitespace, FromStr};
use byteorder::{LittleEndian, ByteOrder};
use num::{self, N... | (&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "PlyError: {}", self.message)
}
}
impl fmt::Debug for PlyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
<Self as fmt::Display>::fmt(self, f)
}
}
pub fn dump_ply_header(header: &PlyFileHeader) {
for element... | fmt | identifier_name |
ply_loader.rs | use std::io::{Read, Seek, BufReader, BufRead, SeekFrom};
use std::error;
use std::fmt;
use crate::model::ply::{PlyFileHeader, PlyElementDescriptor, standard_formats, PlyPropertyDescriptor, PlyScalar, PlyDatatype};
use std::str::{SplitAsciiWhitespace, FromStr};
use byteorder::{LittleEndian, ByteOrder};
use num::{self, N... | else {
return Err(PlyReadError::Other(Box::new(PlyError::new("Invalid entry line: Missing property value"))));
};
let val: T = match value_str.parse::<T>() {
Ok(val) => val,
Err(_err) => return Err(PlyReadError::Other(Box::new(PlyError::new("Invalid entry line: Failed to parse value")))),
... | {
s
} | conditional_block |
main.rs | mod xcb_util;
use log::debug;
use crate::xcb_util::{
geometry::*,
window::WindowExt,
};
use std::str;
use anyhow::{
anyhow,
Error,
};
use structopt::StructOpt;
use xcb::{
base as xbase,
randr as xrandr,
xproto,
};
#[derive(StructOpt)]
struct GlobalOptions {}
#[derive(StructOpt)]
struct Fract {
num... | let pct = DisplayPercentageSpaceRect::new(
DisplayPercentageSpacePoint::new(self.x.value(), self.y.value()),
DisplayPercentageSpaceSize::new(self.w.value(), self.h.value()),
);
let new_rect = pct
.to_rect(display_frame)
.inner_rect(geom.active_window_insets);
dbg!(&new_rect);
... | let display_frame = get_output_available_rect(&conn)?;
let geom = get_geometry(&conn)?;
| random_line_split |
main.rs | mod xcb_util;
use log::debug;
use crate::xcb_util::{
geometry::*,
window::WindowExt,
};
use std::str;
use anyhow::{
anyhow,
Error,
};
use structopt::StructOpt;
use xcb::{
base as xbase,
randr as xrandr,
xproto,
};
#[derive(StructOpt)]
struct GlobalOptions {}
#[derive(StructOpt)]
struct | {
num: f32,
denom: f32,
}
impl Fract {
fn value(&self) -> f32 { self.num / self.denom }
}
impl std::str::FromStr for Fract {
type Err = Error;
fn from_str(s: &str) -> Result<Fract, Error> {
let parts = s.split('/').collect::<Vec<_>>();
Ok(Fract {
num: f32::from_str(parts[0])?,
denom: f3... | Fract | identifier_name |
lib.rs | // Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
pub mod bitvec_serde;
pub mod rleplus;
pub use bitvec;
use bitvec::prelude::*;
use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
use fnv::FnvHashSet;
use std::iter::FromIterator;
type BitVec = bitvec::prelude::BitVec<Lsb0, ... |
BitField::Decoded(bv) => {
if let Some(true) = bv.get(index as usize) {
Ok(true)
} else {
Ok(false)
}
}
}
}
/// Retrieves the index of the first set bit, and error if invalid encoding or no ... | {
if set.contains(&index) {
return Ok(true);
}
if unset.contains(&index) {
return Ok(false);
}
// Check in encoded for the given bit
// This can be changed to not flush changes
... | conditional_block |
lib.rs | // Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
pub mod bitvec_serde;
pub mod rleplus;
pub use bitvec;
use bitvec::prelude::*;
use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
use fnv::FnvHashSet;
use std::iter::FromIterator;
type BitVec = bitvec::prelude::BitVec<Lsb0, ... | () -> Self {
Self::Decoded(BitVec::new())
}
}
impl BitField {
pub fn new() -> Self {
Self::default()
}
/// Generates a new bitfield with a slice of all indexes to set.
pub fn new_from_set(set_bits: &[u64]) -> Self {
let mut vec = match set_bits.iter().max() {
So... | default | identifier_name |
lib.rs | // Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
pub mod bitvec_serde;
pub mod rleplus;
pub use bitvec;
use bitvec::prelude::*;
use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
use fnv::FnvHashSet;
use std::iter::FromIterator;
type BitVec = bitvec::prelude::BitVec<Lsb0, ... | // TODO this probably should not require mut self and RLE decode bits
pub fn get(&mut self, index: u64) -> Result<bool> {
match self {
BitField::Encoded { set, unset, .. } => {
if set.contains(&index) {
return Ok(true);
}
i... | random_line_split | |
lib.rs | // Copyright 2020 ChainSafe Systems
// SPDX-License-Identifier: Apache-2.0, MIT
pub mod bitvec_serde;
pub mod rleplus;
pub use bitvec;
use bitvec::prelude::*;
use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not};
use fnv::FnvHashSet;
use std::iter::FromIterator;
type BitVec = bitvec::prelude::BitVec<Lsb0, ... |
/// Intersection of two bitfields and assigns to self (equivalent of bit AND `&`)
pub fn intersect_assign(&mut self, other: &Self) -> Result<()> {
match other {
BitField::Encoded { bv, set, unset } => {
*self.as_mut_flushed()? &= decode_and_apply_cache(bv, set, unset)?
... | {
self.intersect_assign(other)?;
Ok(self)
} | identifier_body |
pymines.py | #!/usr/bin/env python3
import random
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
__all__ = ['Mines']
class _CoordsFormatter():
"""
Formats coordinates in the interactive plot mode
"""
def __init__(self, width, height):
self.width ... |
def count_neighbor_flags(self, i, j):
"""
Counts the number of flags in the neighboring cells
"""
return np.count_nonzero(self.flags[(i-1 if i > 0 else 0):i+2, (j-1 if j > 0 else 0):j+2])
def update_revealed(self, i, j):
"""
Updates revealed cells by checking i,... | ""
Counts the number of mines in the neighboring cells
"""
n_neighbor_mines = -1
if not self.mines[i, j]:
n_neighbor_mines = np.count_nonzero(
self.mines[(i-1 if i > 0 else 0):i+2, (j-1 if j > 0 else 0):j+2])
return n_neighbor_mines
| identifier_body |
pymines.py | #!/usr/bin/env python3
import random
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
__all__ = ['Mines']
class _CoordsFormatter():
"""
Formats coordinates in the interactive plot mode
"""
def __init__(self, width, height):
self.width ... | mport argparse
parser = argparse.ArgumentParser()
parser.add_argument('-l', metavar='level (b, i, e)', default='beginner', help='level, i.e., '
'beginner (8 x 8, 10 mines), intermediate (16 x 16, 40 mines), expert (30 '
'x 16, 99 mines)')
parser.add_argument(... | conditional_block | |
pymines.py | #!/usr/bin/env python3
import random
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
__all__ = ['Mines']
class _CoordsFormatter():
"""
Formats coordinates in the interactive plot mode
"""
def __init__(self, width, height):
self.width ... | :
"""
Minesweeper
Parameters
----------
width : int
Width of minefield
height : int
Height of minefield
n_mines : int
Number of mines
show : bool (optional)
If True, displays game when initialized
"""
# Colormap object used for showing wrong cell... | Mines | identifier_name |
pymines.py | #!/usr/bin/env python3
import random
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
__all__ = ['Mines']
class _CoordsFormatter():
"""
Formats coordinates in the interactive plot mode
"""
def __init__(self, width, height):
self.width ... | # number of mines in the neighboring cells
self.mines_count = np.full((self.height, self.width), 0, dtype=int)
self.flags = np.full((self.height, self.width), False, dtype=bool) # mine flags
self.revealed = np.full((self.height, self.width), False, dtype=bool) # revealed cells
... |
self.mines = np.full((self.height, self.width), False, dtype=bool) # boolean, mine or not | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.