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 |
|---|---|---|---|---|
lib.rs | fn from_str(raw: &str) -> Result<Mime, ()> {
if raw == "*/*" {
return Ok(mime!(Star/Star));
}
let ascii = raw.to_ascii_lowercase(); // lifetimes :(
let len = ascii.len();
let mut iter = ascii.chars().enumerate();
let mut params = vec![];
// toplevel
... | #[test]
fn test_case_sensitive_values() {
assert_eq!(Mime::from_str("multipart/form-data; boundary=ABCDEFG").unwrap(), | random_line_split | |
lib.rs | {
($enoom:ident::_) => (
$crate::$enoom::Star
);
($enoom:ident::($inner:expr)) => (
$crate::$enoom::Ext($inner.to_string())
);
($enoom:ident::$var:ident) => (
$crate::$enoom::$var
)
}
macro_rules! enoom {
(pub enum $en:ident; $ext:ident; $($ty:ident, $text:expr;)*) ... | else if let TopLevel::Star = self.0 {
if let SubLevel::Star = self.1 {
let attrs = self.2.as_ref();
if attrs.len() == 0 {
return f.write_str("*/*");
}
}
}
// slower general purpose fmt
try!(fmt::Display... | {
if let SubLevel::Json = self.1 {
let attrs = self.2.as_ref();
if attrs.len() == 0 {
return f.write_str("application/json");
}
}
} | conditional_block |
lib.rs | 8";
}
pub type Param = (Attr, Value);
impl<T: AsRef<[Param]>> fmt::Display for Mime<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// It's much faster to write a single string, as opposed to push
// several parts through f.write_str(). So, check for the most common
... | is_restricted_name_char | identifier_name | |
lib.rs | {
($enoom:ident::_) => (
$crate::$enoom::Star
);
($enoom:ident::($inner:expr)) => (
$crate::$enoom::Ext($inner.to_string())
);
($enoom:ident::$var:ident) => (
$crate::$enoom::$var
)
}
macro_rules! enoom {
(pub enum $en:ident; $ext:ident; $($ty:ident, $text:expr;)*) ... | } else if let TopLevel::Star = self.0 {
if let SubLevel::Star = self.1 {
let attrs = self.2.as_ref();
if attrs.len() == 0 {
return f.write_str("*/*");
}
}
}
// slower general purpose fmt
try!(fmt... | {
// It's much faster to write a single string, as opposed to push
// several parts through f.write_str(). So, check for the most common
// mime types, and fast track them.
if let TopLevel::Text = self.0 {
if let SubLevel::Plain = self.1 {
let attrs = self.2.a... | identifier_body |
utils.py | the features to unit variance
if data_opts['scale_features'][m]:
print("Scaling features for view " + str(m) + " to unit variance...")
Y[m] = Y[m] / np.std(Y[m], axis=0, )
print("\nAfter data processing:")
for m in range(M): print("view %d has %d samples and %d features..." % (... | """
| random_line_split | |
utils.py | idxMask = np.random.choice(N, size=Nsamples2Mask, replace = False)
# idxMask = np.arange(Nsamples2Mask)
# print idxMask
tmp = data[m].copy()
tmp.ix[idxMask,:] = pd.np.nan
data[m] = tmp
return data
# Function to load the data
def loadData(data... | (A,B):
""" Method to efficiently compute correlation coefficients between two matrices
PARMETERS
---------
A: np array
B: np array
"""
# Rowwise mean of input arrays & subtract from input arrays themeselves
A_mA = A - A.mean(1)[:,None]
B_mB = B - B.mean(1)[:,None]
# Sum o... | corr | identifier_name |
utils.py | :
idxMask = np.random.choice(N, size=Nsamples2Mask, replace = False)
# idxMask = np.arange(Nsamples2Mask)
# print idxMask
tmp = data[m].copy()
tmp.ix[idxMask,:] = pd.np.nan
data[m] = tmp
return data
# Function to load the data
def loadData(da... | # Read file
file = data_opts['input_files'][m]
Y[m] = pd.read_csv(file, delimiter=data_opts["delimiter"], header=data_opts["colnames"], index_col=data_opts["rownames"]).astype(pd.np.float32)
# Y[m] = pd.read_csv(file, delimiter=data_opts["delimiter"])
print("Loaded %s with %d sa... | """ Method to load the data
PARAMETERS
----------
data_opts: dic
verbose: boolean
"""
print ("\n")
print ("#"*18)
print ("## Loading data ##")
print ("#"*18)
print ("\n")
sleep(1)
M = len(data_opts['input_files'])
Y = [None]*M
for m in range(M):
| identifier_body |
utils.py |
data_filt = [None]*M
samples_to_keep = np.setdiff1d(range(N),samples_to_remove)
for m in range(M):
data_filt[m] = data[m].iloc[samples_to_keep]
return data_filt
def maskData(data, data_opts):
""" Method to mask values of the data,
It is mainly to test missing values and to evaluat... | print("A total of " + str(len(samples_to_remove)) + " sample(s) have at least a missing view and will be removed") | conditional_block | |
list.js | no, error) {
$('#googleMapError').text("There was an error loading resources. Please correct and try again");
$('#googleMapError').show();
}
// Thanks to the following link for help with this function.
//http://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function
// This fu... | (geocoderSearchResult) {
return new Promise(function(resolve, reject) {
if (geocoderSearchResult.geometry.location) {
map.setCenter(geocoderSearchResult.geometry.location);
// Create a list and display all the results.
var cll = geocoderSearchResult.geometry.location.lat... | getBookstores | identifier_name |
list.js | no, error) {
$('#googleMapError').text("There was an error loading resources. Please correct and try again");
$('#googleMapError').show();
}
// Thanks to the following link for help with this function.
//http://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function
// This fu... |
var Venue = function() {
this.tips = '';
this.name = '';
this.venueUrl = '';
this.venuePhotoUrl = '';
this.rating = 0.0;
this.lat = 0;
this.lng = 0;
this.index = '';
this.marker = {};
this.displaySelection = function() {
if(!infowindow.isOpen){
//The infowind... | random_line_split | |
list.js | no, error) {
$('#googleMapError').text("There was an error loading resources. Please correct and try again");
$('#googleMapError').show();
}
// Thanks to the following link for help with this function.
//http://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function
// This fu... |
});
return marker;
}
var stopAnimation = function(marker) {
setTimeout(function() {
marker.setAnimation(null);
}, 1400);
};
// code attribution: https://github.com/mdn/promises-test/blob/gh-pages/index.html
/*
This function takes the result from the geocoder request and subit... | {
infowindow.close();
infowindow.setContent(self.content);
infowindow.open(self.map, this);
infowindow.isOpen = true;
} | conditional_block |
list.js | no, error) {
$('#googleMapError').text("There was an error loading resources. Please correct and try again");
$('#googleMapError').show();
}
// Thanks to the following link for help with this function.
//http://stackoverflow.com/questions/14184956/async-google-maps-api-v3-undefined-is-not-a-function
// This fu... | if (items[i].venue.photos.count > 0) {
// there is at least one photo - so construct photo url.
var groups = items[i].venue.photos.groups;
// Some Foursquare 'venues' do not have photos, so check if the location has any photos
... | {
if (getBooksRequest.readyState === XMLHttpRequest.DONE) {
if (getBooksRequest.status === 200) {
var jsonResponse = JSON.parse(getBooksRequest.responseText);
var bkstr = []; // array, holds the frsqrItem object literal that is defined inside the loop below.
var frsqrBoo... | identifier_body |
shuf.rs | ),
Echo(Vec<String>),
InputRange((usize, usize)),
}
static USAGE: &str = help_usage!("shuf.md");
static ABOUT: &str = help_about!("shuf.md");
struct Options {
head_count: usize,
output: Option<String>,
random_source: Option<String>,
repeat: bool,
sep: u8,
}
mod options {
pub static EC... | .to_string(),
)
};
let options = Options {
head_count: {
let headcounts = matches
.get_many::<String>(options::HEAD_COUNT)
.unwrap_or_default()
.map(|s| s.to_owned())
.collect();
match parse_... | {
let args = args.collect_lossy();
let matches = uu_app().try_get_matches_from(args)?;
let mode = if let Some(args) = matches.get_many::<String>(options::ECHO) {
Mode::Echo(args.map(String::from).collect())
} else if let Some(range) = matches.get_one::<String>(options::INPUT_RANGE) {
m... | identifier_body |
shuf.rs | ),
Echo(Vec<String>),
InputRange((usize, usize)),
}
static USAGE: &str = help_usage!("shuf.md");
static ABOUT: &str = help_about!("shuf.md");
struct Options {
head_count: usize,
output: Option<String>,
random_source: Option<String>,
repeat: bool,
sep: u8,
}
mod options {
pub static EC... | (args: impl uucore::Args) -> UResult<()> {
let args = args.collect_lossy();
let matches = uu_app().try_get_matches_from(args)?;
let mode = if let Some(args) = matches.get_many::<String>(options::ECHO) {
Mode::Echo(args.map(String::from).collect())
} else if let Some(range) = matches.get_one::<... | uumain | identifier_name |
shuf.rs | ),
Echo(Vec<String>),
InputRange((usize, usize)),
}
static USAGE: &str = help_usage!("shuf.md");
static ABOUT: &str = help_about!("shuf.md");
struct Options {
head_count: usize,
output: Option<String>,
random_source: Option<String>,
repeat: bool,
sep: u8,
}
mod options {
pub static EC... | .override_usage(format_usage(USAGE))
.infer_long_args(true)
.args_override_self(true)
.arg(
Arg::new(options::ECHO)
.short('e')
.long(options::ECHO)
.value_name("ARG")
.help("treat each ARG as an input line")
... | .version(crate_version!()) | random_line_split |
eda.py | attributes out into year, month, date
# - Column 'relative_humidity' and 'psi' contains value 0 --> This is quite unrealistic, so we can treat them as missing value too
# %% [markdown]
# We will take a closer look at the 'weather' column
# %%
df['weather'].value_counts()
# %% [markdown]
# Looks like 'weather' column... | df['psi'].describe()
# %% [markdown]
# #### Task 4: Column 'date' - transform to numeric data e.g. year, month, date, day of week
# %%
# first we convert the date column to date object
dt=df['date']
df['date']=pd.to_datetime(dt)
# %%
type(df['date'].values[0])
# %% [markdown]
# Now we need to create new columns an... | # %%
df['psi'].replace(0,np.nan,inplace=True) | random_line_split |
form-field-config.type.ts | .
*
* OpenMediaVault is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
import { Constraint } from '~/app/shared/models/constraint.type... | // --- numberInput | password | textInput ---
autocomplete?: string;
// Note, this button is only visible if the browser supports
// that. The following requirements must be met:
// - The HTTPS protocol is used. localhost is also supported.
// - The site is not embedded in an iFrame.
hasCopyToClipboardBut... | random_line_split | |
lib.rs | ::fmt;
use issues::{BadIssueSeeker, Issue};
use filemap::FileMap;
use visitor::FmtVisitor;
use config::Config;
#[macro_use]
mod utils;
pub mod config;
pub mod filemap;
mod visitor;
mod checkstyle;
mod items;
mod missed_spans;
mod lists;
mod types;
mod expr;
mod imports;
mod issues;
mod rewrite;
mod string;
mod commen... | }
impl Sub for Indent {
type Output = Indent;
fn sub(self, rhs: Indent) -> Indent {
Indent::new(self.block_indent - rhs.block_indent,
self.alignment - rhs.alignment)
}
}
impl Add<usize> for Indent {
type Output = Indent;
fn add(self, rhs: usize) -> Indent {
In... | alignment: self.alignment + rhs.alignment,
}
} | random_line_split |
lib.rs | ::fmt;
use issues::{BadIssueSeeker, Issue};
use filemap::FileMap;
use visitor::FmtVisitor;
use config::Config;
#[macro_use]
mod utils;
pub mod config;
pub mod filemap;
mod visitor;
mod checkstyle;
mod items;
mod missed_spans;
mod lists;
mod types;
mod expr;
mod imports;
mod issues;
mod rewrite;
mod string;
mod commen... | (&self) -> Span {
self.span
}
}
impl Spanned for ast::Pat {
fn span(&self) -> Span {
self.span
}
}
impl Spanned for ast::Ty {
fn span(&self) -> Span {
self.span
}
}
impl Spanned for ast::Arg {
fn span(&self) -> Span {
if items::is_named_arg(self) {
... | span | identifier_name |
trajectory_tracking.py | errari')
data_pose_x = data.pose[indice].position.x
data_pose_y = data.pose[indice].position.y
self.data_pose= np.array([data_pose_x,data_pose_y])
return self.data_pose
def odometryCb(self,msg):
#current robot pose
x = round(msg.pose.pose.position.x,4)
... | print("y_d:{} and y_odom:{} sample:{}".format(self.y_d[T][0],y,T))
print("theta_d:{} and theta_odom:{} sample:{}".format(self.theta_d[T],theta,T))
return np.array([float(e1), float(e2), e3])
def unicicle_Linear_control(self,traj,zeta,a):
rospy.sleep(0.1) # need small time to ... | if(self.trajectory == "parallel_parking" ):
(x, y, theta) = self.get_pose() #NB: i punti x e y sono sull'asse posteriore, non è il centro della macchina
else:
(a, b, theta) = self.get_pose() #prendo solo theta
x=self.data_pose[0]
y=self.data_pose[1]
#compu... | identifier_body |
trajectory_tracking.py | ari')
data_pose_x = data.pose[indice].position.x
data_pose_y = data.pose[indice].position.y
self.data_pose= np.array([data_pose_x,data_pose_y])
return self.data_pose
def odometryCb(self,msg):
#current robot pose
x = round(msg.pose.pose.position.x,4)
... | f):
toltheta=0.2
tol=0.05
vel=2
q_i = self.get_pose()
if np.pi/2-toltheta<=q_i[2]<=toltheta+np.pi/2 or -np.pi/2-toltheta<=q_i[2]<=toltheta-np.pi/2:
while q_i[0]<=self.A_park[0][0]-tol or q_i[0]>=self.A_park[0][0]+tol:
q_i = self.get_pose()
... | oint(sel | identifier_name |
trajectory_tracking.py | errari')
data_pose_x = data.pose[indice].position.x
data_pose_y = data.pose[indice].position.y
self.data_pose= np.array([data_pose_x,data_pose_y])
return self.data_pose
def odometryCb(self,msg):
#current robot pose
x = round(msg.pose.pose.position.x,4)
... | y = round(posizione[1],1)
tg = Trajectory_generation()
q_i = self.get_pose()
self.trajectory=traj
if(self.trajectory == "parallel_parking" ):
(self.x_d, self.y_d,self.dotx_d,self.doty_d,self.v_d, self.w_d , self.theta_d , self.psi, self.A_park) =t... |
data = rospy.wait_for_message("/gazebo/model_states", ModelStates, timeout=5)
posizione = self.callback(data)
x = round(posizione[0],1) | random_line_split |
trajectory_tracking.py | 1],1)
tg = Trajectory_generation()
q_i = self.get_pose()
self.trajectory=traj
if(self.trajectory == "parallel_parking" ):
(self.x_d, self.y_d,self.dotx_d,self.doty_d,self.v_d, self.w_d , self.theta_d , self.psi, self.A_park) =tg.parallel_parking_trajector... | .data_pose[1] #estraggo y odometria
| conditional_block | |
srvcenter.go | func (self *Result) Error() string {
b, _ := json.Marshal(self)
return string(b)
}
type ServiceConfig struct {
MaxNrConns int
MaxNrUsers int
MaxNrConnsPerUser int
MsgCache msgcache.Cache
LoginHandler evthandler.LoginHandler
LogoutHandler evthandler.LogoutHandler
MessageHandler... | (maxNrConns, maxNrConnsPerUser, maxNrUsers int) {
connMap := newTreeBasedConnMap()
nrConns := 0
for {
select {
case connInEvt := <-self.connIn:
if maxNrConns > 0 && nrConns >= maxNrConns {
if connInEvt.errChan != nil {
connInEvt.errChan <- ErrTooManyConns
}
continue
}
err := connMap.Add... | process | identifier_name |
srvcenter.go | (self *Result) Error() string {
b, _ := json.Marshal(self)
return string(b)
}
type ServiceConfig struct {
MaxNrConns int
MaxNrUsers int
MaxNrConnsPerUser int
MsgCache msgcache.Cache
LoginHandler evthandler.LoginHandler
LogoutHandler evthandler.LogoutHandler
MessageHandler ... |
func getPushInfo(msg *proto.Message, extra map[string]string, fwd bool) map[string]string {
if extra == nil {
extra = make(map[string]string, len(msg.Header)+3)
}
if fwd {
for k, v := range msg.Header {
if strings.HasPrefix(k, "notif.") {
if strings.HasPrefix(k, "notif.uniqush.") {
// forward messa... | {
shouldFwd := false
if self.config != nil {
if self.config.ForwardRequestHandler != nil {
shouldFwd = self.config.ForwardRequestHandler.ShouldForward(fwdreq)
maxttl := self.config.ForwardRequestHandler.MaxTTL()
if fwdreq.TTL < 1*time.Second || fwdreq.TTL > maxttl {
fwdreq.TTL = maxttl
}
}
}
if ... | identifier_body |
srvcenter.go | ForwardRequestHandler evthandler.ForwardRequestHandler
ErrorHandler evthandler.ErrorHandler
// Push related web hooks
SubscribeHandler evthandler.SubscribeHandler
UnsubscribeHandler evthandler.UnsubscribeHandler
PushHandler evthandler.PushHandler
PushService push.Push
}
type writeMessageRequ... | {
msg := wreq.msg
extra := wreq.extra
username := wreq.user
service := self.serviceName
fwd := false
if len(msg.Sender) > 0 && len(msg.SenderService) > 0 {
if msg.Sender != username || msg.SenderService != service {
fwd = true
}
}
go func() {
should := self.shouldPus... | conditional_block | |
srvcenter.go | getPushInfo(fwdreq.Message, nil, true)
self.SendMessage(receiver, fwdreq.Message, extra, fwdreq.TTL)
}
func getPushInfo(msg *proto.Message, extra map[string]string, fwd bool) map[string]string {
if extra == nil {
extra = make(map[string]string, len(msg.Header)+3)
}
if fwd {
for k, v := range msg.Header {
i... | }
}
func (self *serviceCenter) NewConn(conn server.Conn) error { | random_line_split | |
wireguard.go | OrPromptImpl(ctx, nth, prompt, true)
}
func orgByArg(cmdCtx *cmdctx.CmdContext) (*api.Organization, error) {
ctx := cmdCtx.Command.Context()
client := cmdCtx.Client.API()
if len(cmdCtx.Args) == 0 {
org, err := selectOrganization(ctx, client, "", nil)
if err != nil {
return nil, err
}
return org, nil
}... |
fmt.Printf(`
!!!! WARNING: Output includes credential information. Credentials cannot !!!!
!!!! be recovered after creation; if you lose the token, you'll need to !!!!
!!!! remove and and re-add it. !!!!
To use a token to create a WireGuard connection, you can use curl:
curl -v --request... | {
return err
} | conditional_block |
wireguard.go | OrPromptImpl(ctx, nth, prompt, true)
}
func orgByArg(cmdCtx *cmdctx.CmdContext) (*api.Organization, error) {
ctx := cmdCtx.Command.Context()
client := cmdCtx.Client.API()
if len(cmdCtx.Args) == 0 {
org, err := selectOrganization(ctx, client, "", nil)
if err != nil {
return nil, err
}
return org, nil
}... | (ctx *cmdctx.CmdContext, idx int, prompt string) (w io.WriteCloser, mustClose bool, err error) {
var (
f *os.File
filename string
)
for {
filename, err = argOrPromptLoop(ctx, idx, prompt, filename)
if err != nil {
return nil, false, err
}
if filename == "" {
fmt.Println("Provide a filename... | resolveOutputWriter | identifier_name |
wireguard.go | argOrPromptImpl(ctx, nth, prompt, true)
}
func orgByArg(cmdCtx *cmdctx.CmdContext) (*api.Organization, error) {
ctx := cmdCtx.Command.Context()
client := cmdCtx.Client.API()
if len(cmdCtx.Args) == 0 {
org, err := selectOrganization(ctx, client, "", nil)
if err != nil {
return nil, err
}
return org, ni... | }
func runWireGuardStat(cmdCtx *cmdctx.CmdContext) error {
ctx := cmdCtx.Command.Context()
client := cmdCtx.Client.API()
org, err := orgByArg(cmdCtx)
if err != nil {
return err
}
var name string
if len(cmdCtx.Args) >= 2 {
name = cmdCtx.Args[1]
} else {
name, err = selectWireGuardPeer(ctx, cmdCtx.Clien... | fmt.Println("Removed peer.")
return wireguard.PruneInvalidPeers(ctx, cmdCtx.Client.API()) | random_line_split |
wireguard.go | != nil {
return err
}
fmt.Printf("New WireGuard peer for organization '%s': '%s'\n", org.Slug, conf.WireGuardState.Name)
return nil
}
func runWireGuardCreate(ctx *cmdctx.CmdContext) error {
org, err := orgByArg(ctx)
if err != nil {
return err
}
var region string
var name string
if len(ctx.Args) > 1 &&... | {
fmt.Printf(`
!!!! WARNING: Output includes private key. Private keys cannot be recovered !!!!
!!!! after creating the peer; if you lose the key, you'll need to rekey !!!!
!!!! the peering connection. !!!!
`)
w, shouldClose, err := resolveOutputWriter(ctx, idx, "Fi... | identifier_body | |
nba-game-list.ts | Date();
//we use America/Los_Angeles time zone because L.A. game start at last in one day.
let SpecificDateTimeArray: any[] = this.GetSpecificTimeZoneFormat(nowLocalTime, -7);
this.ChangedDate = SpecificDateTimeArray[0] + SpecificDateTimeArray[1] + SpecificDateTimeArray[2];
... | {
this.gameCount = 0;
let alert = this.GamealertCtrl.create({
title: 'Oops!',
subTitle: 'There are not any game today or the day you select.',
buttons: ['OK']
});
alert... | conditional_block | |
nba-game-list.ts | ameDetailPage } from '../nba-game-detail/nba-game-detail';
@Component({
templateUrl: 'build/pages/nba-game-list/nba-game-list.html'
})
export class NBAGameListPage implements OnInit{
NBATeamMapData: any[];
NBAGameList: any[] = []; //to avoid error: Cannot read property 'push' of undefined, so we g... | (event, GameItem) {
this.navCtrl.push(NBAGameDetailPage, {
GameItem: GameItem,
SelectedYear: this.selectedYear
});
}
/**
* @Param: nowDateTime, UTC
* @Example: UTC => +8: "Asia/Shanghai", -4: "America/New_York", -7: "America/Los_Angeles"
* @Remark: "Asia/S... | GameItemTapped | identifier_name |
nba-game-list.ts | DetailPage } from '../nba-game-detail/nba-game-detail';
@Component({
templateUrl: 'build/pages/nba-game-list/nba-game-list.html'
})
export class NBAGameListPage implements OnInit{
NBATeamMapData: any[];
NBAGameList: any[] = []; //to avoid error: Cannot read property 'push' of undefined, so we give... |
doRefresh(refresher: Refresher) {
this.GetNBAGameList(this.ChangedDate).then(() => refresher.complete()).catch(this.handleError);
}
OpenDatePicker(): void {
let options: DatePickerOptions;
if (this.platform.is('android')) {
options = {
... | {
let nowLocalTime: Date = new Date();
//we use America/Los_Angeles time zone because L.A. game start at last in one day.
let SpecificDateTimeArray: any[] = this.GetSpecificTimeZoneFormat(nowLocalTime, -7);
this.ChangedDate = SpecificDateTimeArray[0] + SpecificDat... | identifier_body |
nba-game-list.ts | ameDetailPage } from '../nba-game-detail/nba-game-detail';
@Component({
templateUrl: 'build/pages/nba-game-list/nba-game-list.html'
})
export class NBAGameListPage implements OnInit{
NBATeamMapData: any[];
NBAGameList: any[] = []; //to avoid error: Cannot read property 'push' of undefined, so we g... | GameProcess = EachGameitem['GameDate'].replace(/\s*ET\s*/, '');
break;
case 'live':
GameProcess = EachGameitem['process']['Quarter'] + ' ';
GameProcess += EachGamei... | random_line_split | |
ddglCtrl.js | ', function() {
$("input[name='orderid-query']").val('');
$("input[name='sender-query']").val('');
$("input[name='receiver-query']").val('');
$("input[name='username-query']").val('');
$("select[name='state-query']").val('');
$("select[name='iscreditapply-query']").val('');
$('.setTableLength').val(... | );
}
//placeholder兼容ie end
//清除按钮
$('.clearBtn').on('click | identifier_body | |
ddglCtrl.js | ender : $("input[name='sender-query']").val(),
receiver : $("input[name='receiver-query']").val(),
state : $("select[name='state-query").val(),
iscreditapply : $("select[name='iscreditapply-query").val(),
username : $("input[name='username-query']").val(),
},
function(data){
if($('.loading')... | );
$(".modal-edityd").find("select[name='dispatchtype']").val(data.dispatchtype);
$(".modal-edityd").find("input[name='agencyfund']").val(data.agencyfund);
$(".modal-edityd").find("input[name='receiptnum']").val(data.receiptnum);
$(".modal-edityd").find("input[name='receiptno']").val(data.receiptno);
$("... | conditional_block | |
ddglCtrl.js | ]{1}))+\d{8})$/.test(value))||/^((0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/.test(value);
}, "手机、电话格式不正确");
/** 添加验证start **/
$('#addStaffForm').validate({
rules: {
'nickname': {
required: true
},
'loginname': {
required: true
}... | }
var sumnum = 0;
var sumweight = 0.0;
var sumvalume = 0.0;
var sumorderfee = 0.0;
var sumagencyfund = 0.0;
var result = data.result;
if(result!=null && result=="noauthority") {
common.alert1('你无此权限!');
return;
}
if(data.result!=null && data.result=="againLogin") {
... | $('.loading').remove(); | random_line_split |
ddglCtrl.js | ut');
}
//placeholder兼容ie end
//清除按钮
$('.clearBtn').on('click', function() {
$("input[name='orderid-query']").val('');
$("input[name='sender-query']").val('');
$("input[name='receiver-query']").val('');
$("input[name='username-query']").val('');
$("select[name='state-query']").val('');
$("select[nam... | createElement('inp | identifier_name | |
SiteInfoDialog.py | , Qt
from PyQt5.QtGui import QPixmap, QImage, QPainter, QColor, QBrush
from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
from PyQt5.QtWidgets import (
QDialog, QTreeWidgetItem, QGraphicsScene, QMenu, QApplication,
QGraphicsPixmapItem
)
from E5Gui import E5MessageBox, E5FileDialog
from .Ui_SiteInfoDia... |
@pyqtSlot(QTreeWidgetItem, QTreeWidgetItem)
def on_imagesTree_currentItemChanged(self, current, previous):
"""
Private slot to show a preview of the selected image.
@param current current image entry (QTreeWidgetItem)
@param previous old current entry (QTreeWidgetI... | self.tagsTree.resizeColumnToContents(col) | conditional_block |
SiteInfoDialog.py | , Qt
from PyQt5.QtGui import QPixmap, QImage, QPainter, QColor, QBrush
from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
from PyQt5.QtWidgets import (
QDialog, QTreeWidgetItem, QGraphicsScene, QMenu, QApplication,
QGraphicsPixmapItem
)
from E5Gui import E5MessageBox, E5FileDialog
from .Ui_SiteInfoDia... | elif imageUrl.scheme() == "file":
pixmap = QPixmap(imageUrl.toLocalFile())
elif imageUrl.scheme() == "qrc":
pixmap = QPixmap(imageUrl.toString()[3:])
else:
if self.__imageReply is not None:
self.__imageReply.deleteLater()
self._... | """
Private slot to show a preview of the selected image.
@param current current image entry (QTreeWidgetItem)
@param previous old current entry (QTreeWidgetItem)
"""
if current is None:
return
imageUrl = QUrl(current.text(1))
if imag... | identifier_body |
SiteInfoDialog.py | , Qt
from PyQt5.QtGui import QPixmap, QImage, QPainter, QColor, QBrush
from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
from PyQt5.QtWidgets import (
QDialog, QTreeWidgetItem, QGraphicsScene, QMenu, QApplication,
QGraphicsPixmapItem
)
from E5Gui import E5MessageBox, E5FileDialog
from .Ui_SiteInfoDia... | (self):
"""
Private method to show some text while loading an image.
"""
self.imagePreview.setBackgroundBrush(
self.__imagePreviewStandardBackground)
scene = QGraphicsScene(self.imagePreview)
scene.addText(self.tr("Loading..."))
self.imagePreview.setSc... | __showLoadingText | identifier_name |
SiteInfoDialog.py | Url, Qt
from PyQt5.QtGui import QPixmap, QImage, QPainter, QColor, QBrush
from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
from PyQt5.QtWidgets import (
QDialog, QTreeWidgetItem, QGraphicsScene, QMenu, QApplication,
QGraphicsPixmapItem
)
from E5Gui import E5MessageBox, E5FileDialog
from .Ui_SiteInfo... |
pixmapItem = self.imagePreview.scene().items()[0]
if not isinstance(pixmapItem, QGraphicsPixmapItem):
return
if pixmapItem.pixmap().isNull():
E5MessageBox.warning(
self,
self.tr("Save Image"),
self.tr(
... | return | random_line_split |
kNN.py | normMat
def file2matrix(filename):
fr = open(filename)
lines = fr.readlines()
numberOfLines = len(lines)
dataMat = np.zeros((numberOfLines, 3))
classLabelVec = []
index = 0
for line in lines:
listFromLine = line.strip().split('\t')
dataMat[index, :] = listFromLine[0:3]
... |
return returnVec
def handwritingClassTest():
from os import listdir
from sklearn.neighbors import KNeighborsClassifier as kNN
hwLabels = []
# 目录下文件名
trainingFileList = listdir('trainingDigits')
m = len(trainingFileList)
trainingMat = np.zeros((m, 1024))
# 获取训练数据和标签
for i in ran... | ineStr[i]) | identifier_name |
kNN.py | Labels = len(datingLabels)
LabelsColors = []
for i in datingLabels:
if i == 1:
LabelsColors.append('black')
if i == 2:
LabelsColors.append('orange')
if i == 3:
LabelsColors.append('red')
#画出散点图,以datingDataMat矩阵的第一(飞行常客例程)、第二列(玩游戏)数据画散点数据,散点大小为15,透明... | idSpec(4, 4, wspace=0.0, hspace=0.0)
for i in range(16):
inner_grid = gridspec.GridSpecFromSubplotSpec(3, 3,
subplot_spec=outer_grid[i], wspace=0.0, hspace=0.0)
a, b = int(i/4)+1,i%4+1
for j, (c, d) in enumer | identifier_body | |
kNN.py | 14)
#将fig画布分隔成1行1列,不共享x轴和y轴,fig画布的大小为(13,8)
#当nrow=2,nclos=2时,代表fig画布被分为四个区域,axs[0][0]表示第一行第一个区域
fig, axs = plt.subplots(nrows=2, ncols=2,sharex=False, sharey=False, figsize=(13,8))
numberOfLabels = len(datingLabels)
LabelsColors = []
for i in datingLabels:
if i == 1:
Labels... |
fig = plt.figure(figsize=(8, 8))
# gridspec inside gridspec | random_line_split | |
kNN.py | normMat
def file2matrix(filename):
fr = open(filename)
lines = fr.readlines()
numberOfLines = len(lines)
dataMat = np.zeros((numberOfLines, 3))
classLabelVec = []
index = 0
for line in lines:
listFromLine = line.strip().split('\t')
dataMat[index, :] = listFromLine[0:3]
... | lineStr = fr.readline()
for j in range(32):
returnVec[0, i * 32 + j] = int(lineStr[i])
return returnVec
def handwritingClassTest():
from os import listdir
from sklearn.neighbors import KNeighborsClassifier as kNN
hwLabels = []
# 目录下文件名
trainingFileList = listdir('trainin... | ec[i])
if (classifierResult != datingLabelVec[i]):
errorCount += 1.0
print "the total error rate is:%f" % (errorCount/float(numTestVecs))
print errorCount
def img2vector(filename):
returnVec = np.zeros((1, 1024))
fr = open(filename)
for i in range(32):
| conditional_block |
chat-ui.js | Name);
var $roomItem = $(template(room));
$roomItem.children('a').bind('click', selectRoomListItem);
count++;
this.$roomList.append($roomItem.toggle(true));
}
_sortListLexicographically(self.$roomList);
cb();
};
NKChatUI.prototype.UIPaintUserList = function (users, cb) {... | {
var hash = 0;
if (str.length == 0) return hash;
for (var i = 0; i < str.length; i++) {
var char = str.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return ((hash + 2147483647 + 1) % 6) + 1;
} | identifier_body | |
chat-ui.js | this.maxUserSearchResults = 100;
this.urlPattern = /\b(?:https?|ftp):\/\/[a-z0-9-+&@#\/%?=~_|!:,.;]*[a-z0-9-+&@#\/%=~_|]/gim;
this.pseudoUrlPattern = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
var self = this;
// Initialize the UI
this.UIbindElements();
this.UIScrollToInput();
// Initi... | this.maxLengthUsername = 15;
this.maxLengthUsernameDisplay = 13;
this.maxLengthRoomName = 15;
this.maxLengthMessage = 120; | random_line_split | |
chat-ui.js | };
NKChatUI.prototype.UIScrollToInput = function() {
var element = this.$chatInput;
$('body, html').animate({
scrollTop: (element.offset().top - window.innerHeight + element[0].offsetHeight) + 20 + 'px'
});
};
NKChatUI.prototype.UIClearInput = function() {
this.$chatInput.val('');
};
NKChatUI... | {
var s = "0" + _hashCode(message.name);
message.avatar = s.substr(s.length - 2);
} | conditional_block | |
chat-ui.js | = Object.keys(rooms);
for (var i = keys.length - 1; i >= 0; i--) {
var roomId = keys[i];
var room = rooms[roomId];
if (room.name == "MyNewRoom")
room.name = "Public"
else if (room.name.substr(0, 2) == "NK" && room.name.length > 2)
room.name = room.name.subst... | _linkify | identifier_name | |
main.py | 0, 0))
text_line_2 = font_start.render("\\", 1, (0, 0, 0))
level_now = "00"
money_now = "00000"
live_now = "20"
sell_price = 0
# location = [window_size[0] * 0.5, window_size[1] * 0.5]
# dx_dy = [0,0,0,0]
clock = pygame.time.Clock()
playing = False
drop_it = False
tower_type_num = 0
tower_type = [lea... | gameDisplay.blit(text_line_1, (240, 340)) | random_line_split | |
main.py | move = [0,50]
if move != [0,0]:
rang = int(data[i+1])
if i+2 < len(data):
if data[i+2] in "0123456789":
rang = int(data[i+1:i+3])
for t in range(rang):
pos[0] += move[0]
pos[1] += move[1]
path.append(copy.copy(pos))
return path
def showMonsterWalkPath(data_list):
"""
sho... | """
Translate the monster_walk_path to a list and return it.
"""
path = []
pos = [0,0]
for i in range(len(data)):
if i == 0:
pos[0] = 50*(int(data[i])-1)
elif i == 1:
pos[1] = 50*(int(data[i])-1)
path.append(copy.copy(pos))
else:
move = [0,0]
if data[i] == "l":
move = [-50,0]
elif data[... | identifier_body | |
main.py | ,0]
for i in range(len(data_list)):
if i == 0:
pos = copy.copy(data_list[i])
gameDisplay.blit(monster_walk, pos)
else:
monster_move = False
num_cal = [1,0,0]
dx = (data_list[i][0] - pos[0])/50
dy = (data_list[i][1] - pos[1])/50
if dx < 0 or dy < 0:
num_cal[0] = -1
if dx != 0:
monste... |
elif not stop and not drop_it:
stop = True
if stop:
pass
else:
if event.type == pygame.MOUSEBUTTONUP:
if playing:
#-- Right frame:
# Tools
if pygame.Rect((676, 135), sell_0_size).collidepoint(mouse_pos):
money_temp = int(money_now) + sell_price
if money_... | drop_it = False | conditional_block |
main.py | ,0]
for i in range(len(data_list)):
if i == 0:
pos = copy.copy(data_list[i])
gameDisplay.blit(monster_walk, pos)
else:
monster_move = False
num_cal = [1,0,0]
dx = (data_list[i][0] - pos[0])/50
dy = (data_list[i][1] - pos[1])/50
if dx < 0 or dy < 0:
num_cal[0] = -1
if dx != 0:
monste... | (data_list, init_pos):
"""
createMonsterWalkPath(data_list, init_pos)
"""
path = []
pos = copy.copy(init_pos)
path.append(copy.copy(pos))
monster_size = 20
side_d = (50-monster_size)/2
for i in data_list:
pos_temp = [0,0]
pos_temp[0] = pos[0]-side_d
pos_temp[1] = pos[1]-side_d
dx = i[0] - pos_temp[0]... | createMonsterWalkPath | identifier_name |
Clout.js | property {number} CONFIG 5
* @property {number} MIDDLEWARE 10
* @property {number} MODEL 15
* @property {number} API 20
* @property {number} CONTROLLER 25
* @const
*/
const CORE_PRIORITY = {
CONFIG: 5,
MIDDLEWARE: 10,
MODEL: 15,
API: 20,
CONTROLLER: 25,
};
const CLOUT_MODULE_PATH = path.join(__dirname,... |
}
debug('push hook (lowest priority yet)');
this.hooks[event].push(fn);
}
/**
* Loads hooks from directory
* @param {Path} dir directory
* @return {Promise} promise
*/
loadHooksFromDir(dir) {
const glob = path.join(dir, '/hooks/**/*.js');
const files = utils.getGlobbedFiles(gl... | {
debug('push hook at index %s', String(i));
this.hooks[event].splice(i, 0, fn);
return;
} | conditional_block |
Clout.js | @property {number} CONFIG 5
* @property {number} MIDDLEWARE 10
* @property {number} MODEL 15
* @property {number} API 20
* @property {number} CONTROLLER 25
* @const
*/
const CORE_PRIORITY = {
CONFIG: 5,
MIDDLEWARE: 10,
MODEL: 15,
API: 20,
CONTROLLER: 25,
};
const CLOUT_MODULE_PATH = path.join(__dirnam... | * @param {Path} dir directory
* @return {Promise} promise
*/
loadHooksFromDir(dir) {
const glob = path.join(dir, '/hooks/**/*.js');
const files = utils.getGlobbedFiles(glob);
debug('loadHooksFromDir: %s', dir);
return new Promise((resolve, reject) => {
async.each(files, (file, next)... | }
/**
* Loads hooks from directory | random_line_split |
Clout.js | property {number} CONFIG 5
* @property {number} MIDDLEWARE 10
* @property {number} MODEL 15
* @property {number} API 20
* @property {number} CONTROLLER 25
* @const
*/
const CORE_PRIORITY = {
CONFIG: 5,
MIDDLEWARE: 10,
MODEL: 15,
API: 20,
CONTROLLER: 25,
};
const CLOUT_MODULE_PATH = path.join(__dirname,... |
/**
* Load clout-js node module
* @param {string} moduleName clout node module name
*/
addModule(moduleName) {
if (this.moduleCache.includes(moduleName)) {
debug('module: %s already loaded', moduleName);
return;
}
this.logger.debug('loading module: %s', moduleName);
this.modu... | {
debug('loading modules', JSON.stringify(modules));
modules.forEach(moduleName => this.addModule(moduleName));
} | identifier_body |
Clout.js | @property {number} CONFIG 5
* @property {number} MIDDLEWARE 10
* @property {number} MODEL 15
* @property {number} API 20
* @property {number} CONTROLLER 25
* @const
*/
const CORE_PRIORITY = {
CONFIG: 5,
MIDDLEWARE: 10,
MODEL: 15,
API: 20,
CONTROLLER: 25,
};
const CLOUT_MODULE_PATH = path.join(__dirnam... | (dir) {
const glob = path.join(dir, '/hooks/**/*.js');
const files = utils.getGlobbedFiles(glob);
debug('loadHooksFromDir: %s', dir);
return new Promise((resolve, reject) => {
async.each(files, (file, next) => {
debug('loading hooks from file: %s', String(file));
const hooks = r... | loadHooksFromDir | identifier_name |
htp1.py | name': self.__name,
'slots': [self.slot.as_dict()]
}
class Htp1(PersistentDevice[Htp1State]):
def __init__(self, name: str, config_path: str, cfg: dict, ws_server: WsServer, catalogue: CatalogueProvider):
super().__init__(config_path, name, ws_server)
self.__name = name
... | self.sendMessage('getmso'.encode('utf-8'), isBinary=False)
def onOpen(self):
logger.info("Connected to HTP1")
self.factory.register(self)
def onClose(self, was_clean, code, reason):
if was_clean:
logger.info(f"Disconnected code: {code} reason: {reason}")
els... | random_line_split | |
htp1.py | name': self.__name,
'slots': [self.slot.as_dict()]
}
class Htp1(PersistentDevice[Htp1State]):
def __init__(self, name: str, config_path: str, cfg: dict, ws_server: WsServer, catalogue: CatalogueProvider):
super().__init__(config_path, name, ws_server)
self.__name = name
... |
ops = [peq.as_ops(c, use_shelf=self.__supports_shelf) for peq in to_load for c in self.__peq.keys()]
ops = [op for slot_ops in ops for op in slot_ops if op]
if ops:
self.__client.send('changemso [{"op":"replace","path":"/peq/peqsw","value":true}]')
self.__client.send(f"c... | peq = PEQ(len(to_load), fc=100, q=1, gain=0, filter_type_name='PeakingEQ')
to_load.append(peq) | conditional_block |
htp1.py | name': self.__name,
'slots': [self.slot.as_dict()]
}
class Htp1(PersistentDevice[Htp1State]):
def __init__(self, name: str, config_path: str, cfg: dict, ws_server: WsServer, catalogue: CatalogueProvider):
super().__init__(config_path, name, ws_server)
self.__name = name
... |
def clientConnectionFailed(self, connector, reason):
logger.warning(f"Client connection failed {reason} .. retrying ..")
super().clientConnectionFailed(connector, reason)
def clientConnectionLost(self, connector, reason):
logger.warning(f"Client connection failed {reason} .. retrying ... | super(Htp1ClientFactory, self).__init__(*args, **kwargs)
self.__clients: List[Htp1Protocol] = []
self.listener = listener
self.setProtocolOptions(version=13) | identifier_body |
htp1.py | name': self.__name,
'slots': [self.slot.as_dict()]
}
class Htp1(PersistentDevice[Htp1State]):
def __init__(self, name: str, config_path: str, cfg: dict, ws_server: WsServer, catalogue: CatalogueProvider):
super().__init__(config_path, name, ws_server)
self.__name = name
... | (self, client: Htp1Protocol):
if client in self.__clients:
logger.info(f"Unregistering device {client.peer}")
self.__clients.remove(client)
else:
logger.info(f"Ignoring unregistered device {client.peer}")
def broadcast(self, msg):
if self.__clients:
... | unregister | identifier_name |
Final of the Electromagnet Project.py | tt = float(raw_input("Enter the thickness of the load in mm :"))
llcm = ll * float(2.54)
wwcm = ww * float(2.54)
ttcm = tt / float(10)
VV = float(llcm * wwcm * ttcm)
density = float(7.81)
mgg = VV * density
mg = mgg / float(1000)
elif material == 2:
ll = float(raw_input("Enter the le... | material = float(raw_input("The load material: "))
if material == 1:
ll = float(raw_input("Enter the length of the load in inches :"))
ww = float(raw_input("Enter the width of the load in inches :")) | random_line_split | |
Final of the Electromagnet Project.py | _Sum = Sum_{lengthofwire} * T $$
#
# The total resistance of the wire is calculated by using the AWG table.
# $$ R_{total} = Total_Sum * R_{ohm / m}$$
#
# The inductance of the coil is obtained as:
# $$ L = N \phi / I$$
# where:
# - L is the total inductance of the coil
# - I is the cu... | loat(raw_input("Enter the length of Electromagnet in mm "))
w = float(raw_input("Enter the Width between the electromagnet pole pieces in mm "))
h = float(raw_input("Enter the Height of the pole pieces above the yoke in mm "))
p = float(raw_input("Enter the Width of the pole pieces in mm "))
if l >= (2 ... | conditional_block | |
aa_changes.rs | ,
pos: AaRefPosition,
qry_seq: &[Nuc],
ref_seq: &[Nuc],
ref_tr: &CdsTranslation,
qry_tr: &CdsTranslation,
) -> Self {
let ref_aa = ref_tr.seq[pos.as_usize()];
let qry_aa = qry_tr.seq[pos.as_usize()];
let nuc_ranges = cds_codon_pos_to_ref_range(cds, pos);
let ref_triplet = nuc_rang... |
changes.aa_substitutions.sort();
changes.aa_deletions.sort();
changes.nuc_to_aa_muts.iter_mut().for_each(|(_, vals)| {
vals.sort();
vals.dedup();
});
Ok(changes)
}
/// Finds aminoacid substitutions and deletions in query peptides relative to reference peptides, in one gene
///
/// ## Precondition
... | {
let mut changes = qry_translation
.iter_cdses()
.map(|(qry_name, qry_cds_tr)| {
let ref_cds_tr = ref_translation.get_cds(qry_name)?;
let cds = gene_map.get_cds(&qry_cds_tr.name)?;
Ok(find_aa_changes_for_cds(
cds, qry_seq, ref_seq, ref_cds_tr, qry_cds_tr, nuc_subs, nuc_dels,
)... | identifier_body |
aa_changes.rs | ,
pos: AaRefPosition,
qry_seq: &[Nuc],
ref_seq: &[Nuc],
ref_tr: &CdsTranslation,
qry_tr: &CdsTranslation,
) -> Self {
let ref_aa = ref_tr.seq[pos.as_usize()];
let qry_aa = qry_tr.seq[pos.as_usize()];
let nuc_ranges = cds_codon_pos_to_ref_range(cds, pos);
let ref_triplet = nuc_rang... | // then append to the group.
if codon <= prev.pos + 2 {
// If previous codon in the group is not exactly adjacent, there is 1 item in between,
// then cover the hole by inserting previous codon.
if codon == prev.pos + 2 && is_codon_sequenced(aa_alignment_ranges, c... | random_line_split | |
aa_changes.rs | ,
pos: AaRefPosition,
qry_seq: &[Nuc],
ref_seq: &[Nuc],
ref_tr: &CdsTranslation,
qry_tr: &CdsTranslation,
) -> Self {
let ref_aa = ref_tr.seq[pos.as_usize()];
let qry_aa = qry_tr.seq[pos.as_usize()];
let nuc_ranges = cds_codon_pos_to_ref_range(cds, pos);
let ref_triplet = nuc_rang... |
// Current group is not empty
Some(prev) => {
// If previous codon in the group is adjacent or almost adjacent (there is 1 item in between),
// then append to the group.
if codon <= prev.pos + 2 {
// If previous codon in the group is not exactly adjacent, there... | {
if codon > 0 && is_codon_sequenced(aa_alignment_ranges, codon - 1) {
// Also prepend one codon to the left, for additional context, to start the group
curr_group.push(AaChangeWithContext::new(
cds,
codon - 1,
qry_seq,
ref_seq,
... | conditional_block |
aa_changes.rs | {
pub cds_name: String,
pub pos: AaRefPosition,
pub ref_aa: Aa,
pub qry_aa: Aa,
pub nuc_pos: NucRefGlobalPosition,
#[schemars(with = "String")]
#[serde(serialize_with = "serde_serialize_seq")]
#[serde(deserialize_with = "serde_deserialize_seq")]
pub ref_triplet: Vec<Nuc>,
#[schemars(with = "Strin... | AaChangeWithContext | identifier_name | |
lib.rs | inbound requests from other
/// instances.
///
/// The public listener forwards requests to a local socket (TCP or UNIX).
///
/// The private listener routes requests to service-discovery-aware load-balancer.
///
pub struct Main<G> {
config: config::Config,
control_listener: BoundPort,
inbound_listener... | {
error!("turning {} into 500", i);
http::StatusCode::INTERNAL_SERVER_ERROR
} | conditional_block | |
lib.rs | -discovery-aware load-balancer.
///
pub struct Main<G> {
config: config::Config,
control_listener: BoundPort,
inbound_listener: BoundPort,
outbound_listener: BoundPort,
metrics_listener: BoundPort,
get_original_dst: G,
runtime: MainRuntime,
}
impl<G> Main<G>
where
G: GetOriginalDst ... | {
let stack = Arc::new(NewServiceFn::new(move || {
// Clone the router handle
let router = router.clone();
// Map errors to appropriate response error codes.
let map_err = MapErr::new(router, |e| {
match e {
RouteError::Route(r) => {
e... | identifier_body | |
lib.rs | pub mod ctx;
mod dns;
mod drain;
pub mod fs_watch;
mod inbound;
mod logging;
mod map_err;
mod outbound;
pub mod stream;
pub mod task;
pub mod telemetry;
mod transparency;
mod transport;
pub mod timeout;
mod tower_fn; // TODO: move to tower-fn
mod watch_service; // TODO: move to tower
use bind::Bind;
use conditional::C... | pub mod control;
pub mod convert; | random_line_split | |
lib.rs | mod outbound;
pub mod stream;
pub mod task;
pub mod telemetry;
mod transparency;
mod transport;
pub mod timeout;
mod tower_fn; // TODO: move to tower-fn
mod watch_service; // TODO: move to tower
use bind::Bind;
use conditional::Conditional;
use connection::BoundPort;
use inbound::Inbound;
use map_err::MapErr;
use task... | (&self) -> SocketAddr {
self.inbound_listener.local_addr()
}
pub fn outbound_addr(&self) -> SocketAddr {
self.outbound_listener.local_addr()
}
pub fn metrics_addr(&self) -> SocketAddr {
self.metrics_listener.local_addr()
}
pub fn run_until<F>(self, shutdown_signal: F)
... | inbound_addr | identifier_name |
auto_aliasing.go | type changes from `T to List[T]` or vice versa. To
// avoid these breaking changes, this method undoes any upstream changes to MaxItems using
// [SchemaInfo.MaxItemsOne] overrides. This happens until a major version change is
// detected, and then overrides are cleared. Effectively this makes sure that upstream
// Max... |
func aliasResource(
p *ProviderInfo, res shim.Resource,
applyResourceAliases *[]func(),
hist map[string]*tokenHistory[tokens.Type], computed *ResourceInfo,
tfToken string, version int,
) {
prev, hasPrev := hist[tfToken]
if !hasPrev {
// It's not in the history, so it must be new. Stick it in the history for
... | {
hist, ok, err := md.Get[aliasHistory](artifact, aliasMetadataKey)
if err != nil {
return aliasHistory{}, err
}
if !ok {
hist = aliasHistory{
Resources: map[string]*tokenHistory[tokens.Type]{},
DataSources: map[string]*tokenHistory[tokens.ModuleMember]{},
}
}
return hist, nil
} | identifier_body |
auto_aliasing.go | MaxItems changes are deferred until the next major version.
//
// Implementation note: to operate correctly this method needs to keep a persistent track
// of a database of past decision history. This is currently done by doing reads and
// writes to `providerInfo.GetMetadata()`, which is assumed to be persisted acros... | applyMaxItemsOneAliasing | identifier_name | |
auto_aliasing.go | type changes from `T to List[T]` or vice versa. To
// avoid these breaking changes, this method undoes any upstream changes to MaxItems using
// [SchemaInfo.MaxItemsOne] overrides. This happens until a major version change is
// detected, and then overrides are cleared. Effectively this makes sure that upstream
// Max... |
return hist, nil
}
func aliasResource(
p *ProviderInfo, res shim.Resource,
applyResourceAliases *[]func(),
hist map[string]*tokenHistory[tokens.Type], computed *ResourceInfo,
tfToken string, version int,
) {
prev, hasPrev := hist[tfToken]
if !hasPrev {
// It's not in the history, so it must be new. Stick it ... | {
hist = aliasHistory{
Resources: map[string]*tokenHistory[tokens.Type]{},
DataSources: map[string]*tokenHistory[tokens.ModuleMember]{},
}
} | conditional_block |
auto_aliasing.go | the type changes from `T to List[T]` or vice versa. To
// avoid these breaking changes, this method undoes any upstream changes to MaxItems using
// [SchemaInfo.MaxItemsOne] overrides. This happens until a major version change is
// detected, and then overrides are cleared. Effectively this makes sure that upstream
//... | // the compilation of programs as the type changes from `T to List[T]` or vice versa. To
// avoid these breaking changes, this method undoes any upstream changes to MaxItems using
// [SchemaInfo.MaxItemsOne] overrides. This happens until a major version change is
// detected, and then overrides are cleared. Effectively... | // [SchemaInfo.MaxItemsOne] changes are also important because they involve flattening and
// pluralizing names. Collections (lists or sets) marked with MaxItems=1 are projected as
// scalar types in Pulumi SDKs. Therefore changes to the MaxItems property may be breaking | random_line_split |
cht.rs | <N>(cht_size: N, block_num: N) -> Option<N>
where
N: Clone + AtLeast32Bit,
{
let block_cht_num = block_to_cht_number(cht_size.clone(), block_num.clone())?;
let two = N::one() + N::one();
if block_cht_num < two {
return None
}
let cht_start = start_number(cht_size, block_cht_num.clone());
if cht_start != block_... | is_build_required | identifier_name | |
cht.rs |
/// Returns Some(cht_number) if CHT is need to be built when the block with given number is
/// canonized.
pub fn is_build_required<N>(cht_size: N, block_num: N) -> Option<N>
where
N: Clone + AtLeast32Bit,
{
let block_cht_num = block_to_cht_number(cht_size.clone(), block_num.clone())?;
let two = N::one() + N::one(... | {
SIZE.into()
} | identifier_body | |
cht.rs |
let cht_start = start_number(cht_size, block_cht_num.clone());
if cht_start != block_num {
return None
}
Some(block_cht_num - two)
}
/// Returns Some(max_cht_number) if CHT has ever been built given maximal canonical block number.
pub fn max_cht_number<N>(cht_size: N, max_canonical_block: N) -> Option<N>
where... | {
return None
} | conditional_block | |
cht.rs | 32Bit,
{
let max_cht_number = block_to_cht_number(cht_size, max_canonical_block)?;
let two = N::one() + N::one();
if max_cht_number < two {
return None
}
Some(max_cht_number - two)
}
| /// SIZE items. The items are assumed to proceed sequentially from `start_number(cht_num)`.
/// Discards the trie's nodes.
pub fn compute_root<Header, Hasher, I>(
cht_size: Header::Number,
cht_num: Header::Number,
hashes: I,
) -> ClientResult<Hasher::Out>
where
Header: HeaderT,
Hasher: hash_db::Hasher,
Hasher::Ou... | /// Compute a CHT root from an iterator of block hashes. Fails if shorter than | random_line_split |
utils.go | err = getTableIndex(db, table, queryMaxRetry)
if err != nil {
return nil, errors.Trace(err)
}
if len(table.Columns) == 0 {
return nil, errors.Errorf("invalid table %s.%s", schema, name)
}
return table, nil
}
func getTableColumns(db *sql.DB, table *models.Table, maxRetry int) error {
if table.Schema == "" ... |
defer rows.Close()
rowColumns, err := rows.Columns()
if err != nil {
return errors.Trace(err)
}
// Show an example.
/*
mysql> show index from test.t;
+-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
... | {
return errors.Trace(err)
} | conditional_block |
utils.go |
func querySQL(db *sql.DB, query string, maxRetry int) (*sql.Rows, error) {
// TODO: add retry mechanism
rows, err := db.Query(query)
if err != nil {
return nil, errors.Trace(err)
}
return rows, nil
}
func getTableFromDB(db *sql.DB, schema string, name string) (*models.Table, error) {
table := &models.Table{}... | {
return strings.Replace(name, "`", "``", -1)
} | identifier_body | |
utils.go | (name string) string {
return strings.Replace(name, "`", "``", -1)
}
func querySQL(db *sql.DB, query string, maxRetry int) (*sql.Rows, error) {
// TODO: add retry mechanism
rows, err := db.Query(query)
if err != nil {
return nil, errors.Trace(err)
}
return rows, nil
}
func getTableFromDB(db *sql.DB, schema st... | escapeName | identifier_name | |
utils.go | err = getTableIndex(db, table, queryMaxRetry)
if err != nil {
return nil, errors.Trace(err)
}
if len(table.Columns) == 0 {
return nil, errors.Errorf("invalid table %s.%s", schema, name)
}
return table, nil
}
func getTableColumns(db *sql.DB, table *models.Table, maxRetry int) error {
if table.Schema == "" ... | if err != nil {
return errors.Trace(err)
}
// Show an example.
/*
mysql> show columns from test.t;
+-------+---------+------+-----+---------+-------------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------------------+
| a ... | defer rows.Close()
rowColumns, err := rows.Columns() | random_line_split |
stimuli_LSL.py | filled contours
center_depth = obj_depths[np.where(obj_depths<1023)].mean() # take mean of non-white pixels (grayscale value < 1023)
cv2.circle(im_rgb, (cX, cY), 3, (255, 255, 255), -1)
depth_cm = int(100/((-0.00307*(center_depth))+3.33)) # convert pixel value to depth in cm, measurement not that accurate s... | sample = s.recv(104)
if len(sample) == 104:
sample = np.fromstring(sample) # recieve array of 13 elements (last 5 are metadata)
sample = sample[:-5]
sample_tot.append(sample)
if len(sample) == 0:
break | conditional_block | |
stimuli_LSL.py | # edge detection
contour_list = []
canny = cv2.Canny(res, lower_threshold, upper_threshold, apertureSize=sobel_size) # finds edges, but not always closed contours (needed for cv2.findContours)
dilated = cv2.dilate(canny, np.ones((3, 3))) # makes sure canny edges are closed for findContours
_, contours, hierarchy = cv2.... | rec = s.recv(12)
| random_line_split | |
descriptor.pb.go | i++
i = encodeVarintDescriptor(dAtA, i, uint64(len(m.MediaType)))
i += copy(dAtA[i:], m.MediaType)
}
if len(m.Digest) > 0 {
dAtA[i] = 0x12
i++
i = encodeVarintDescriptor(dAtA, i, uint64(len(m.Digest)))
i += copy(dAtA[i:], m.Digest)
}
if m.Size_ != 0 {
dAtA[i] = 0x18
i++
i = encodeVarintDescripto... |
func sovDescriptor(x uint64) (n int) {
for {
n++
x >>= 7
if x == 0 {
break
}
}
return n
}
func sozDescriptor(x uint64) (n int) {
return sovDescriptor(uint64((x << 1) ^ uint64((int64(x) >> 63))))
}
func (this *Descriptor) String() string {
if this == nil {
return "nil"
}
s := strings.Join([]string{... | {
var l int
_ = l
l = len(m.MediaType)
if l > 0 {
n += 1 + l + sovDescriptor(uint64(l))
}
l = len(m.Digest)
if l > 0 {
n += 1 + l + sovDescriptor(uint64(l))
}
if m.Size_ != 0 {
n += 1 + sovDescriptor(uint64(m.Size_))
}
return n
} | identifier_body |
descriptor.pb.go |
return dAtA[:n], nil
}
func (m *Descriptor) MarshalTo(dAtA []byte) (int, error) {
var i int
_ = i
var l int
_ = l
if len(m.MediaType) > 0 {
dAtA[i] = 0xa
i++
i = encodeVarintDescriptor(dAtA, i, uint64(len(m.MediaType)))
i += copy(dAtA[i:], m.MediaType)
}
if len(m.Digest) > 0 {
dAtA[i] = 0x12
i++
... | {
return nil, err
} | conditional_block | |
descriptor.pb.go |
i++
i = encodeVarintDescriptor(dAtA, i, uint64(len(m.MediaType)))
i += copy(dAtA[i:], m.MediaType)
}
if len(m.Digest) > 0 {
dAtA[i] = 0x12
i++
i = encodeVarintDescriptor(dAtA, i, uint64(len(m.Digest)))
i += copy(dAtA[i:], m.Digest)
}
if m.Size_ != 0 {
dAtA[i] = 0x18
i++
i = encodeVarintDescript... | if wireType != 0 {
return fmt.Errorf("proto: wrong wireType = %d for field Size_", wireType)
}
m.Size_ = 0
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return ErrIntOverflowDescriptor
}
if iNdEx >= l {
return io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
m... | m.Digest = github_com_opencontainers_go_digest.Digest(dAtA[iNdEx:postIndex])
iNdEx = postIndex
case 3: | random_line_split |
descriptor.pb.go | i++
i = encodeVarintDescriptor(dAtA, i, uint64(len(m.MediaType)))
i += copy(dAtA[i:], m.MediaType)
}
if len(m.Digest) > 0 {
dAtA[i] = 0x12
i++
i = encodeVarintDescriptor(dAtA, i, uint64(len(m.Digest)))
i += copy(dAtA[i:], m.Digest)
}
if m.Size_ != 0 {
dAtA[i] = 0x18
i++
i = encodeVarintDescripto... | (dAtA []byte) (n int, err error) {
l := len(dAtA)
iNdEx := 0
for iNdEx < l {
var wire uint64
for shift := uint(0); ; shift += 7 {
if shift >= 64 {
return 0, ErrIntOverflowDescriptor
}
if iNdEx >= l {
return 0, io.ErrUnexpectedEOF
}
b := dAtA[iNdEx]
iNdEx++
wire |= (uint64(b) & 0x7F) ... | skipDescriptor | identifier_name |
main.rs | "Tool for mopdifying system wide hosts file to simulate arbitrary DNS A and AAAA records.
Expects a hosts file at {:?} and a configuration in YAML format at {:?}. This
program is intended to be run by non-priviledged users with the help of setuid. It therefore has
some safety features.
Any modifications w... |
}
panic!("found_post != found_pre");
}
}
if opts.dry_run || opts.verbose {
println!("generated:\n>>>\n{}<<<", &buf_generate);
}
if opts.dry_run {
println!("DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN DRY-RUN");... | {
eprintln!("Difference: {:?}", DONT_TOUCH[i])
} | conditional_block |
main.rs | file at {:?} and a configuration in YAML format at {:?}. This
program is intended to be run by non-priviledged users with the help of setuid. It therefore has
some safety features.
Any modifications will not be persisted until the end of program execution. In the event of any
error, the original hosts file will not b... | {
'loop_actions: for action in &opts.actions {
match action {
Action::Define(ip, host) => {
if !config.whitelist.contains(host) {
return Err(format!("HOST {:?} not whitelisted!", host));
}
// eprintln!("defining additionally...:... | identifier_body | |
main.rs | ##"Tool for mopdifying system wide hosts file to simulate arbitrary DNS A and AAAA records.
Expects a hosts file at {:?} and a configuration in YAML format at {:?}. This
program is intended to be run by non-priviledged users with the help of setuid. It therefore has
some safety features.
Any modifications... | // eprintln!("matching entry: {:?}", part);
let matches_hostname = part | .enumerate()
.filter(|(_i, p)| p.matches_ip(ip) || p.matches_hostname(host))
{ | random_line_split |
main.rs | dt.hostname == RESERVED_HOSTNAME {
Cow::Borrowed(hostname)
} else {
Cow::Borrowed(dt.hostname.as_ref())
};
for part in &hosts_parts {
if part.matches_hostname(&dt_host) && part.matches_ip(&dt.ip) {
*found = true;
... | render_entry | identifier_name | |
game.rs | Game speed in addition to player's speed
pub jump_timeout: f64, // Count down to allow the next jump
pub rotate_cam: bool, // Allow rotation of camera or not
pub bullets: i64, // The number of bullets left
pub recharge: f64, // Bullets recharge time
pub fps: f64, // Real fps of game
pub last_fr... |
fn draw(&mut self, e: &Input) {
// Return a horizontal bar
macro_rules! bar {
($curr: expr, $full: expr) => {
[0.,
15.0,
self.config.screen_size.w as f64/2.*$curr/$full,
20.0,]
};
}
let jump_bar ... | {
match key {
Button::Keyboard(Key::A) => if let Turn::Left = self.state.turn {
self.state.turn = Turn::None;
},
Button::Keyboard(Key::D) => if let Turn::Right = self.state.turn {
self.state.turn = Turn::None;
},
Button:... | identifier_body |
game.rs | Game speed in addition to player's speed
pub jump_timeout: f64, // Count down to allow the next jump
pub rotate_cam: bool, // Allow rotation of camera or not
pub bullets: i64, // The number of bullets left
pub recharge: f64, // Bullets recharge time
pub fps: f64, // Real fps of game
pub last_fr... | <T: Car>(config: &GameConfig, player: &T) -> Camera {
Camera::new(
config.screen_size.clone(),
vec3(0., config.camera_height, -config.camera_distance) + player.pos()
)
}
// Re-calculate fps
fn update_fps(&mut self) {
let d = self.state.last_frame.elapsed();
... | new_camera | identifier_name |
game.rs | : f64, // Distance between each decoration
pub sprint_factor: f64,
pub spawn_time: (f64, f64),
pub game_sprint: f64, // The increase of game_speed
pub game_max_speed: f64,
pub player_jump_v: f64,
pub player_jump_a: f64,
pub jump_turn_decrease: f64,
pub jump_timeout: f64,
pub mouse_sp... | }
if self.state.sprint {
if self.world.player.speed < self.config.player_speed.1 { | random_line_split | |
graph.rs | : usize,
}
pub struct FrameGraph {
node_arena: RwLock<Arena<ConnectedNode>>,
edges_arena: RwLock<Arena<ConnectedEdges>>,
end_node: Index,
output_map: Vec<Vec<Option<FrameNodeValue>>>,
levels_map: MultiMap<usize, TraversedGraphNode>,
traversed_node_cache: HashMap<Index, usize>,
}
impl FrameGraph {
/// Cr... | optick::tag!("level", level as u32);
// Get rid of duplicated nodes.
let mut nodes_in_level = self.levels_map.get_vec_mut(&level).unwrap().clone();
nodes_in_level.sort_unstable_by_key(|x| x.index);
nodes_in_level.dedup_by_key(|x| x.index);
// Build cache for this level
... | optick::event!("FrameGraph::execute_level"); | random_line_split |
graph.rs | : usize,
}
pub struct | {
node_arena: RwLock<Arena<ConnectedNode>>,
edges_arena: RwLock<Arena<ConnectedEdges>>,
end_node: Index,
output_map: Vec<Vec<Option<FrameNodeValue>>>,
levels_map: MultiMap<usize, TraversedGraphNode>,
traversed_node_cache: HashMap<Index, usize>,
}
impl FrameGraph {
/// Creates a new empty graph.
pub fn... | FrameGraph | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.