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 |
|---|---|---|---|---|
run.go | // Licensed to Apache Software Foundation (ASF) under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Apache Software Foundation (ASF) licenses this file to you under
// the Apache License, Version 2.0 (the "Li... | (units ...Unit) []bool {
g.log = logger.GetLogger(g.name)
hasRegistered := make([]bool, len(units))
for idx := range units {
if !g.configured {
// if RunConfig has been called we can no longer register Config
// phases of Units
if c, ok := units[idx].(Config); ok {
g.c = append(g.c, c)
hasRegister... | Register | identifier_name |
run.go | // Licensed to Apache Software Foundation (ASF) under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Apache Software Foundation (ASF) licenses this file to you under
// the Apache License, Version 2.0 (the "Li... |
// WaitTillReady blocks the goroutine till all modules are ready.
func (g *Group) WaitTillReady() {
<-g.readyCh
}
| {
var (
s string
t = "cli"
)
if len(g.c) > 0 {
s += "\n- config: "
for _, u := range g.c {
if u != nil {
s += u.Name() + " "
}
}
}
if len(g.p) > 0 {
s += "\n- prerun: "
for _, u := range g.p {
if u != nil {
s += u.Name() + " "
}
}
}
if len(g.s) > 0 {
s += "\n- serve : "
f... | identifier_body |
run.go | // Licensed to Apache Software Foundation (ASF) under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Apache Software Foundation (ASF) licenses this file to you under
// the Apache License, Version 2.0 (the "Li... | fmt.Println(g.ListUnits())
return true, nil
}
// Validate Config inputs
for idx := range g.c {
// a Config might have been deregistered during Run
if g.c[idx] == nil {
g.log.Debug().Uint32("ran", uint32(idx+1)).Msg("skipping validate")
continue
}
g.log.Debug().Str("name", g.c[idx].Name()).Uint32("... | case g.showRunGroup: | random_line_split |
run.go | // Licensed to Apache Software Foundation (ASF) under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Apache Software Foundation (ASF) licenses this file to you under
// the Apache License, Version 2.0 (the "Li... |
if len(g.p) > 0 {
s += "\n- prerun: "
for _, u := range g.p {
if u != nil {
s += u.Name() + " "
}
}
}
if len(g.s) > 0 {
s += "\n- serve : "
for _, u := range g.s {
if u != nil {
t = "svc"
s += u.Name() + " "
}
}
}
return fmt.Sprintf("Group: %s [%s]%s", g.name, t, s)
}
// Wait... | {
s += "\n- config: "
for _, u := range g.c {
if u != nil {
s += u.Name() + " "
}
}
} | conditional_block |
test.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: test.proto
/*
Package grpctest is a generated protocol buffer package.
It is generated from these files:
test.proto
It has these top-level messages:
TestRequest
TestResponse
PrintKVRequest
PrintKVResponse
*/
package grpctest
import proto "github.com/g... |
func (m *PrintKVRequest) GetValueInt() int32 {
if x, ok := m.GetValue().(*PrintKVRequest_ValueInt); ok {
return x.ValueInt
}
return 0
}
// XXX_OneofFuncs is for the internal use of the proto package.
func (*PrintKVRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message,... | {
if x, ok := m.GetValue().(*PrintKVRequest_ValueString); ok {
return x.ValueString
}
return ""
} | identifier_body |
test.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: test.proto
/*
Package grpctest is a generated protocol buffer package.
It is generated from these files:
test.proto
It has these top-level messages:
TestRequest
TestResponse
PrintKVRequest
PrintKVResponse
*/
package grpctest
import proto "github.com/g... |
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/grpctest.Test/Double",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(TestServer).Double(ctx, req.(*TestRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Test_PrintKV_Handler(srv interface... | {
return srv.(TestServer).Double(ctx, in)
} | conditional_block |
test.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: test.proto
/*
Package grpctest is a generated protocol buffer package.
It is generated from these files:
test.proto
It has these top-level messages:
TestRequest
TestResponse
PrintKVRequest
PrintKVResponse
*/
package grpctest
import proto "github.com/g... | }
// Server API for Test service
type TestServer interface {
Double(context.Context, *TestRequest) (*TestResponse, error)
PrintKV(context.Context, *PrintKVRequest) (*PrintKVResponse, error)
}
func RegisterTestServer(s *grpc.Server, srv TestServer) {
s.RegisterService(&_Test_serviceDesc, srv)
}
func _Test_Double_... | random_line_split | |
test.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: test.proto
/*
Package grpctest is a generated protocol buffer package.
It is generated from these files:
test.proto
It has these top-level messages:
TestRequest
TestResponse
PrintKVRequest
PrintKVResponse
*/
package grpctest
import proto "github.com/g... | () ([]byte, []int) { return fileDescriptor0, []int{3} }
func init() {
proto.RegisterType((*TestRequest)(nil), "grpctest.TestRequest")
proto.RegisterType((*TestResponse)(nil), "grpctest.TestResponse")
proto.RegisterType((*PrintKVRequest)(nil), "grpctest.PrintKVRequest")
proto.RegisterType((*PrintKVResponse)(nil), "... | Descriptor | identifier_name |
mesintiket-gen3.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore, QtNetwork
import time
from datetime import datetime
import simplejson
import zlib
import sha
import base64
import config
import configusb
import binascii
import uuid
from decimal import Decimal
import zmq
import redis
import subproces... | (QtCore.QThread):
update = QtCore.pyqtSignal(str)
def __init__(self, tosay):
QtCore.QThread.__init__(self)
self.tosay = tosay
def __del__(self):
self.wait()
def run(self):
subprocess.call('espeak -vid+f3 "%s"' % self.tosay, shell=True)
#~ self.terminate()
class MainApp(QtCore.QObject):
def __init__(se... | SpeechThread | identifier_name |
mesintiket-gen3.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore, QtNetwork
import time
from datetime import datetime
import simplejson
import zlib
import sha
import base64
import config
import configusb
import binascii
import uuid
from decimal import Decimal
import zmq
import redis
import subproces... |
self.redis.set(curdt.strftime('%Y%m%d:setoran'), int(self.redis.get(curdt.strftime('%Y%m%d:setoran'))) + self.currentPrice)
self.redis.rpush('mq', '$TIKET%s,%s,%s,%s,%s,%s,%s,%s,%s,%s\r\n' % (
config.bus_plateno,
gpsdt,
self.redis.get(curdt.strftime('%Y%m%d:ticket_no')),
self.redis.... | self.redis.set(curdt.strftime('%Y%m%d:setoran'), 0) | conditional_block |
mesintiket-gen3.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore, QtNetwork
import time
from datetime import datetime
import simplejson
import zlib
import sha
import base64
import config
import configusb
import binascii
import uuid
from decimal import Decimal
import zmq
import redis
import subproces... |
import logging
import logging.handlers
logger = logging.getLogger('')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(thread)d %(levelname)-5s %(message)s')
fh = logging.handlers.RotatingFileHandler('log.txt', maxBytes=10000000, backupCount=5)
fh.setFormatter(formatter)
ch = logging.Stream... | from gpslistener import GpsListener
from gpiolistener import GPIOListener
from LCD40X4 import GPIO, lcd_init, lcd_goto, lcd_string, GPIO | random_line_split |
mesintiket-gen3.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui, QtCore, QtNetwork
import time
from datetime import datetime
import simplejson
import zlib
import sha
import base64
import config
import configusb
import binascii
import uuid
from decimal import Decimal
import zmq
import redis
import subproces... |
def gpsReceived(self, gpsPos):
#~ print newpos
logger.debug('type of gpsPos: %s %s' % (type(gpsPos), repr(gpsPos)))
if gpsPos['type'] == 0:
if gpsPos['lon'] and gpsPos['lat']:
#self.updateTrackPosition(gpsPos)
#lcd_goto( 'Lon: {0:.6f} Lat: {1:.6f}'.format(gpsPos['lon'], gpsPos['lat']), 0, 3)
s... | try:
if self.gpsThread.lastpos:
# ITPRO861001000786141,11025.595867,-659.625256,31,20121008035615.000,15,0,13,1,
gprmclon = 100 *(int(self.gpsThread.lastpos['lon']) + ((self.gpsThread.lastpos['lon'] - int(self.gpsThread.lastpos['lon'])) / 100 * 60))
gprmclat = 100 *(int(self.gpsThread.lastpos['lat']) + (... | identifier_body |
lp.go | // Copyright 2017 Fabian Wenzelmann <fabianwen@posteo.eu>, Christian Schilling,
// Jan-Georg Smaus
//
// 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/... | ewDNF = make([]br.Clause, len(phi))
// clone each clause
// we'll do that concurrently
var wg sync.WaitGroup
wg.Add(len(phi))
for i := 0; i < len(phi); i++ {
go func(index int) {
clause := phi[index]
var newClause br.Clause = make([]int, len(clause))
for j, oldID := range clause {
newClaus... | renaming[row[len(row)-1]] = newVariableId
reverseRenaming[newVariableId] = row[len(row)-1]
}
n | conditional_block |
lp.go | // Copyright 2017 Fabian Wenzelmann <fabianwen@posteo.eu>, Christian Schilling,
// Jan-Georg Smaus
//
// 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/... | if err := lp.AddConstraintSparse([]golp.Entry{entry1, entry2}, golp.EQ, 0); err != nil {
return nil, err
}
}
// for all remaining j simply add ≥ constraint
for ; j < nbvar; j++ {
entry2.Col = j
if err := lp.AddConstraintSparse([]golp.Entry{entry1, entry2}, golp.GE, 0); err != nil {
re... | // add eq constraing
entry2.Col = j | random_line_split |
lp.go | // Copyright 2017 Fabian Wenzelmann <fabianwen@posteo.eu>, Christian Schilling,
// Jan-Georg Smaus
//
// 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/... |
// TightenMode describes different modes to tighten the linear program
// before solving it.
//
// There are three different modes described below.
type TightenMode int
const (
TightenNone TightenMode = iota // Add only constraings necessary for solving the problem
TightenNeighbours // Add... | {
numRuns := tree.Nbvar - 1
res := true
// we will do this concurrently:
// for each mtp iterate over all variable combinations and perform the test
// and write the result to a channel
// this also has some drawback: we need to wait for all mtps to finish
// otherwise we would need some context wish would be to... | identifier_body |
lp.go | // Copyright 2017 Fabian Wenzelmann <fabianwen@posteo.eu>, Christian Schilling,
// Jan-Georg Smaus
//
// 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/... | r.ClauseSet, nbvar int) []br.BooleanVector {
res := make([]br.BooleanVector, len(phi))
for i, clause := range phi {
point := br.NewBooleanVector(nbvar)
res[i] = point
for _, v := range clause {
point[v] = true
}
}
return res
}
// TODO test this with 0, I don't know what happens to the wait group
// othe... | eMTPs(phi b | identifier_name |
nexus_label.rs | //! GPT labeling for Nexus devices. The primary partition
//! (/dev/x1) will be used for meta data during, rebuild. The second
//! partition contains the file system.
//!
//! The nexus will adjust internal data structures to offset the IO to the
//! right partition. put differently, when connecting to this device via
/... | (Debug, PartialEq, Default, Clone)]
pub struct GptName {
pub name: String,
}
impl GptName {
pub fn as_str(&self) -> &str {
&self.name
}
}
| t mut out = Vec::new();
let mut end = false;
loop {
match seq.next_element()? {
Some(0) => {
end = true;
}
Some(e) if !end => out.push(e),
_ => break,
}
}
if end {
Ok(... | identifier_body |
nexus_label.rs | //! GPT labeling for Nexus devices. The primary partition
//! (/dev/x1) will be used for meta data during, rebuild. The second
//! partition contains the file system.
//!
//! The nexus will adjust internal data structures to offset the IO to the
//! right partition. put differently, when connecting to this device via
/... | impl GptGuid {
pub(crate) fn new_random() -> Self {
let fields = uuid::Uuid::new_v4();
let fields = fields.as_fields();
GptGuid {
time_low: fields.0,
time_mid: fields.1,
time_high: fields.2,
node: *fields.3,
}
}
}
#[derive(Debug, D... | .to_string()
)
}
}
| random_line_split |
nexus_label.rs | //! GPT labeling for Nexus devices. The primary partition
//! (/dev/x1) will be used for meta data during, rebuild. The second
//! partition contains the file system.
//!
//! The nexus will adjust internal data structures to offset the IO to the
//! right partition. put differently, when connecting to this device via
/... | mut fmt::Formatter) -> fmt::Result {
writeln!(f, "GUID: {}", self.primary.guid.to_string())?;
writeln!(f, "\tHeader crc32 {}", self.primary.self_checksum)?;
writeln!(f, "\tPartition table crc32 {}", self.primary.table_crc)?;
for i in 0 .. self.partitions.len() {
writeln!(f, ... | : & | identifier_name |
jira-api.service.ts | import { Injectable } from '@angular/core';
import { nanoid } from 'nanoid';
import { ChromeExtensionInterfaceService } from '../../../../core/chrome-extension-interface/chrome-extension-interface.service';
import {
JIRA_ADDITIONAL_ISSUE_FIELDS,
JIRA_DATETIME_FORMAT,
JIRA_MAX_RESULTS,
JIRA_REQUEST_TIMEOUT_DURAT... | else {
const loginUrl = `${cfg.host}`;
const apiUrl = `${cfg.host}/rest/api/${API_VERSION}/myself`;
const val = await this._matDialog
.open(DialogPromptComponent, {
data: {
// TODO add message to translations
placeholder: 'Insert Cookie String',
... | {
return ssVal;
} | conditional_block |
jira-api.service.ts | import { Injectable } from '@angular/core';
import { nanoid } from 'nanoid';
import { ChromeExtensionInterfaceService } from '../../../../core/chrome-extension-interface/chrome-extension-interface.service';
import {
JIRA_ADDITIONAL_ISSUE_FIELDS,
JIRA_DATETIME_FORMAT,
JIRA_MAX_RESULTS,
JIRA_REQUEST_TIMEOUT_DURAT... | (): void {
this._isBlockAccess = false;
sessionStorage.removeItem(BLOCK_ACCESS_KEY);
}
issuePicker$(searchTerm: string, cfg: JiraCfg): Observable<SearchResultItem[]> {
const searchStr = `${searchTerm}`;
return this._sendRequest$({
jiraReqCfg: {
pathname: 'issue/picker',
follo... | unblockAccess | identifier_name |
jira-api.service.ts | import { Injectable } from '@angular/core';
import { nanoid } from 'nanoid';
import { ChromeExtensionInterfaceService } from '../../../../core/chrome-extension-interface/chrome-extension-interface.service';
import {
JIRA_ADDITIONAL_ISSUE_FIELDS,
JIRA_DATETIME_FORMAT,
JIRA_MAX_RESULTS,
JIRA_REQUEST_TIMEOUT_DURAT... |
getIssueById$(issueId: string, cfg: JiraCfg): Observable<JiraIssue> {
return this._getIssueById$(issueId, cfg, true);
}
getReducedIssueById$(issueId: string, cfg: JiraCfg): Observable<JiraIssueReduced> {
return this._getIssueById$(issueId, cfg, false);
}
getCurrentUser$(cfg: JiraCfg, isForce: bool... | {
const options = {
maxResults,
fields: [
...JIRA_ADDITIONAL_ISSUE_FIELDS,
...(cfg.storyPointFieldId ? [cfg.storyPointFieldId] : []),
],
};
const searchQuery = cfg.autoAddBacklogJqlQuery;
if (!searchQuery) {
this._snackService.open({
type: 'ERROR',
... | identifier_body |
jira-api.service.ts | import { Injectable } from '@angular/core';
import { nanoid } from 'nanoid';
import { ChromeExtensionInterfaceService } from '../../../../core/chrome-extension-interface/chrome-extension-interface.service';
import {
JIRA_ADDITIONAL_ISSUE_FIELDS,
JIRA_DATETIME_FORMAT,
JIRA_MAX_RESULTS,
JIRA_REQUEST_TIMEOUT_DURAT... | }
} else {
currentRequest.resolve(res);
}
}
// delete entry for promise afterwards
delete this._requestsLog[res.requestId];
} else {
console.warn('Jira: Response Request ID not existing', res && res.requestId);
}
}
private _blockAccess(): void {
... | }); | random_line_split |
home.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Copyright 2019 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package user
import (
"bytes"
"fmt"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
activities_model "code.gitea.io/gitea/models/activities"
asymkey_model "code.g... |
// Pulls renders the user's pull request overview page
func Pulls(ctx *context.Context) {
if unit.TypePullRequests.UnitGlobalDisabled() {
log.Debug("Pull request overview page not available as it is globally disabled.")
ctx.Status(http.StatusNotFound)
return
}
ctx.Data["Title"] = ctx.Tr("pull_requests")
ct... | {
if unit.TypeIssues.UnitGlobalDisabled() && unit.TypePullRequests.UnitGlobalDisabled() {
log.Debug("Milestones overview page not available as both issues and pull requests are globally disabled")
ctx.Status(http.StatusNotFound)
return
}
ctx.Data["Title"] = ctx.Tr("milestones")
ctx.Data["PageIsMilestonesDash... | identifier_body |
home.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Copyright 2019 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package user
import (
"bytes"
"fmt"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
activities_model "code.gitea.io/gitea/models/activities"
asymkey_model "code.g... | ctx.ServerError("SearchMilestones", err)
return
}
showRepos, _, err := repo_model.SearchRepositoryByCondition(ctx, &repoOpts, userRepoCond, false)
if err != nil {
ctx.ServerError("SearchRepositoryByCondition", err)
return
}
sort.Sort(showRepos)
for i := 0; i < len(milestones); {
for _, repo := range s... | if err != nil { | random_line_split |
home.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Copyright 2019 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package user
import (
"bytes"
"fmt"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
activities_model "code.gitea.io/gitea/models/activities"
asymkey_model "code.g... |
}
opts.LabelIDs = labelIDs
// Parse ctx.FormString("repos") and remember matched repo IDs for later.
// Gets set when clicking filters on the issues overview page.
selectedRepoIDs := getRepoIDs(ctx.FormString("repos"))
// Remove repo IDs that are not accessible to the user.
selectedRepoIDs = util.SliceRemoveAl... | {
ctx.ServerError("StringsToInt64s", err)
return
} | conditional_block |
home.go | // Copyright 2014 The Gogs Authors. All rights reserved.
// Copyright 2019 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package user
import (
"bytes"
"fmt"
"net/http"
"regexp"
"sort"
"strconv"
"strings"
activities_model "code.gitea.io/gitea/models/activities"
asymkey_model "code.g... | (ctx *context.Context, unitType unit.Type) {
// ----------------------------------------------------
// Determine user; can be either user or organization.
// Return with NotFound or ServerError if unsuccessful.
// ----------------------------------------------------
ctxUser := getDashboardContextUser(ctx)
if ct... | buildIssueOverview | identifier_name |
lib.rs | #![allow(unused_imports)]
#[macro_use]
extern crate log;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use bytes::{BufMut, BytesMut};
use tokio::net::TcpStream;
use byteorder::{ByteOrder, BigEndian};
use futures::try_ready;
use futures::future::Either;
use tokio::prelude::*;
use chrono::naive::NaiveDateT... | pub fn send(&self, t: T) -> Result<(), ()> {
match self {
Transmitter::Synchronous(sender) => sender.send(t).map_err(|_| ()),
Transmitter::Asynchronous(sender) => {
tokio::spawn({
let sender = sender.clone();
sender.send(t).into... | Asynchronous(futures::sync::mpsc::Sender<T>)
}
impl<T> Transmitter<T> where T: 'static + Send {
/// Send a message through the underlying Sender | random_line_split |
lib.rs | #![allow(unused_imports)]
#[macro_use]
extern crate log;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use bytes::{BufMut, BytesMut};
use tokio::net::TcpStream;
use byteorder::{ByteOrder, BigEndian};
use futures::try_ready;
use futures::future::Either;
use tokio::prelude::*;
use chrono::naive::NaiveDateT... |
}
#[cfg(feature = "master")]
type EncryptedStream = tokio_tls::TlsStream<TcpStream>;
/// A TCP stream adapter to convert between byte stream and objects
#[cfg(feature = "master")]
#[derive(Debug)]
pub struct SprinklerProto {
socket: EncryptedStream,
read_buffer: BytesMut,
}
#[cfg(feature = "master")]
impl S... | {
let next = self.counter;
self.counter += 1;
T::build(SprinklerOptions {
_id: next,
_hostname: hostname,
..self.params.clone()
})
} | identifier_body |
lib.rs | #![allow(unused_imports)]
#[macro_use]
extern crate log;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use bytes::{BufMut, BytesMut};
use tokio::net::TcpStream;
use byteorder::{ByteOrder, BigEndian};
use futures::try_ready;
use futures::future::Either;
use tokio::prelude::*;
use chrono::naive::NaiveDateT... | (&self) -> AnomalyTransition {
(*self >> Anomaly::Negative).unwrap()
}
}
#[derive(PartialEq, Debug, Copy, Clone)]
pub enum AnomalyTransition {
Normal, // Negative -> Negative
Occurred, // Negative -> Positive
Unhandled, // Positive -> Positive
Disappeared, // Positive ... | diminish | identifier_name |
lib.rs | // Copyright (c) Facebook, Inc. and its affiliates.
use anyhow::{anyhow, bail, Result};
use crossbeam::channel::Sender;
use glob::glob;
use log::{info, warn};
use scan_fmt::scan_fmt;
use simplelog as sl;
use std::cell::RefCell;
use std::collections::HashMap;
use std::env;
use std::ffi::{CString, OsStr, OsString};
use s... | let mut path = dir.to_owned();
path.push(name);
if let Ok(path) = path.canonicalize() {
if is_executable(&path) {
return Some(path);
}
}
}
None
}
pub fn chgrp<P: AsRef<Path>>(path_in: P, gid: u32) -> Result<bool> {
let path = path_in.a... | random_line_split | |
lib.rs | // Copyright (c) Facebook, Inc. and its affiliates.
use anyhow::{anyhow, bail, Result};
use crossbeam::channel::Sender;
use glob::glob;
use log::{info, warn};
use scan_fmt::scan_fmt;
use simplelog as sl;
use std::cell::RefCell;
use std::collections::HashMap;
use std::env;
use std::ffi::{CString, OsStr, OsString};
use s... | {
Running,
Exiting,
Kicked,
}
pub fn wait_prog_state(dur: Duration) -> ProgState {
let mut first = true;
let mut state = PROG_STATE.lock().unwrap();
loop {
if state.exiting {
return ProgState::Exiting;
}
if LOCAL_KICK_SEQ.with(|seq| {
if *seq.bor... | ProgState | identifier_name |
trie.rs | use crate::config::*;
use crate::louds_dense::LoudsDense;
use crate::louds_sparse::LoudsSparse;
use crate::builder;
pub struct Trie {
louds_dense: LoudsDense,
louds_sparse: LoudsSparse,
suffixes: Vec<Suffix>,
}
// 生ポインタを使えばもっと速くなる
// ベクタofベクタだとキャッシュにも乗らない
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
s... | <u8>>) -> Self {
let include_dense = K_INCLUDE_DENSE;
let sparse_dense = K_SPARSE_DENSE_RATIO;
let mut builder = builder::Builder::new(include_dense, sparse_dense);
builder.build(&keys);
let louds_dense = LoudsDense::new(&builder);
let louds_sparse = LoudsSparse::new(&bu... | ec<Vec | identifier_name |
trie.rs | use crate::config::*;
use crate::louds_dense::LoudsDense;
use crate::louds_sparse::LoudsSparse;
use crate::builder;
pub struct Trie {
louds_dense: LoudsDense,
louds_sparse: LoudsSparse,
suffixes: Vec<Suffix>,
}
// 生ポインタを使えばもっと速くなる
// ベクタofベクタだとキャッシュにも乗らない
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
s... | d_key(key, ret.2);
}
return (ret.0, ret.1);
}
fn _traverse(
&self,
key: &key_t,
) -> (position_t, level_t) {
let ret = self.louds_dense.find_key(key);
if ret.0 != K_NOT_FOUND {
return (ret.0, ret.1);
}
if ret.2 != K_NOT_FOUND {
... | OT_FOUND {
return louds_sparse.fin | conditional_block |
trie.rs | use crate::config::*;
use crate::louds_dense::LoudsDense;
use crate::louds_sparse::LoudsSparse;
use crate::builder;
pub struct Trie {
louds_dense: LoudsDense,
louds_sparse: LoudsSparse,
suffixes: Vec<Suffix>,
}
// 生ポインタを使えばもっと速くなる
// ベクタofベクタだとキャッシュにも乗らない
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
s... | identifier_body | ||
trie.rs | use crate::config::*;
use crate::louds_dense::LoudsDense;
use crate::louds_sparse::LoudsSparse;
use crate::builder;
pub struct Trie {
louds_dense: LoudsDense,
louds_sparse: LoudsSparse,
suffixes: Vec<Suffix>,
}
// 生ポインタを使えばもっと速くなる
// ベクタofベクタだとキャッシュにも乗らない
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
s... | }
},
0 => {},
1 => {
for mask in self.mask_lists[dimension].iter() {
if value & mask == 0 {
updated |= mask;
break;
} else {
... | break;
} else {
updated |= mask;
} | random_line_split |
tau0305.py | from numba import jit, njit,prange
from numba import cuda, int32, complex128, float64, int64
import numpy as np
import threading
import math
import random
import torch
import weibull
import itertools
from scipy.spatial import distance as compute_distance
from scipy.spatial.distance import squareform
import scipy
import... | tw = weibull.weibull()
nbin=200
nscale = 10
#fullrange = torch.linspace(0,torch.max(ijbbdata),nbin)
fullrange = torch.linspace(0,maxval,nbin)
torch.Tensor.ndim = property(lambda self: len(self.shape))
#print( name , "Data mean, max", torch.mean(ijbbdata),torch.max(ijbbdata))
imean = torc... | return torch.tensor(mynan)
return torch.cat([nan_to_num(l).unsqueeze(0) for l in t],0)
def get_tau(data,maxval,tailfrac=.25,pcent=.999):
#tw = weibull.weibull(translateAmountTensor=.001) | random_line_split |
tau0305.py | from numba import jit, njit,prange
from numba import cuda, int32, complex128, float64, int64
import numpy as np
import threading
import math
import random
import torch
import weibull
import itertools
from scipy.spatial import distance as compute_distance
from scipy.spatial.distance import squareform
import scipy
import... | (X, Y, out):
i, j = cuda.grid(2)
if i < out.shape[0] and j < out.shape[1]:
u = X[i]
v = Y[j]
out[i, j] = euclidean_gpu(u, v)
#####################################################################################
def tau(args, features, gpus):
#Now only support Cosine and Euclidean on... | euclidean_dis_gpu | identifier_name |
tau0305.py | from numba import jit, njit,prange
from numba import cuda, int32, complex128, float64, int64
import numpy as np
import threading
import math
import random
import torch
import weibull
import itertools
from scipy.spatial import distance as compute_distance
from scipy.spatial.distance import squareform
import scipy
import... |
@cuda.jit
def euclidean_dis_gpu(X, Y, out):
i, j = cuda.grid(2)
if i < out.shape[0] and j < out.shape[1]:
u = X[i]
v = Y[j]
out[i, j] = euclidean_gpu(u, v)
#####################################################################################
def tau(args, features, gpus):
#Now onl... | i, j = cuda.grid(2)
if i < out.shape[0] and j < out.shape[1]:
u = X[i]
v = Y[j]
out[i, j] = cosine_gpu(u, v) | identifier_body |
tau0305.py | from numba import jit, njit,prange
from numba import cuda, int32, complex128, float64, int64
import numpy as np
import threading
import math
import random
import torch
import weibull
import itertools
from scipy.spatial import distance as compute_distance
from scipy.spatial.distance import squareform
import scipy
import... |
#Number of threads depend on how many gpus you have
for t in threads:
t.setDaemon(True)
t.start()
#Re-group final distance data from gpus
for t in threads:
whole_distances = []
t.join()
distances.extend(np.array(whole_distances... | whole_distances = []
split = split_double(args, mutilple_features[p])
n = int(len(mutilple_features[p]) / split)
chunks = [mutilple_features[p][i * n:(i + 1) * n] for i in range((len(mutilple_features[p]) + n - 1) // n )]
step_i = 0
threads.append(threading.Th... | conditional_block |
verifier.rs | use argon2::{defaults, Argon2, ParamErr, Variant, Version};
use std::error::Error;
/// The main export here is `Encoded`. See `examples/verify.rs` for usage
/// examples.
use std::{fmt, str};
macro_rules! maybe {
($e: expr) => {
match $e {
None => return None,
Some(v) => v,
... | if bytes.len() % 4 != 1 && bytes.len() > 0 {
let mut rv = vec![];
let mut pos = 0;
while pos + 4 <= bytes.len() {
let s = maybe!(triplet(&bytes[pos..pos + 4]));
rv.extend_from_slice(&s);
pos += 4;
}
if bytes.len() - pos == 2 {
... | rv
}
fn debase64_no_pad(bytes: &[u8]) -> Option<Vec<u8>> { | random_line_split |
verifier.rs | use argon2::{defaults, Argon2, ParamErr, Variant, Version};
use std::error::Error;
/// The main export here is `Encoded`. See `examples/verify.rs` for usage
/// examples.
use std::{fmt, str};
macro_rules! maybe {
($e: expr) => {
match $e {
None => return None,
Some(v) => v,
... |
struct Parser<'a> {
enc: &'a [u8],
pos: usize,
}
impl<'a> fmt::Debug for Parser<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", String::from_utf8_lossy(&self.enc[..self.pos]))?;
write!(f, "<-- {} -->", self.pos)?;
write!(f, "{:?}", String::from_utf8_... | {
if bytes.len() % 4 != 1 && bytes.len() > 0 {
let mut rv = vec![];
let mut pos = 0;
while pos + 4 <= bytes.len() {
let s = maybe!(triplet(&bytes[pos..pos + 4]));
rv.extend_from_slice(&s);
pos += 4;
}
if bytes.len() - pos == 2 {
... | identifier_body |
verifier.rs | use argon2::{defaults, Argon2, ParamErr, Variant, Version};
use std::error::Error;
/// The main export here is `Encoded`. See `examples/verify.rs` for usage
/// examples.
use std::{fmt, str};
macro_rules! maybe {
($e: expr) => {
match $e {
None => return None,
Some(v) => v,
... | (&self) -> Vec<u8> {
let vcode = |v| match v {
Variant::Argon2i => "i",
Variant::Argon2d => "d",
Variant::Argon2id => "id",
};
let b64 = |x| String::from_utf8(base64_no_pad(x)).unwrap();
let k_ = match &b64(&self.key[..]) {
bytes if bytes.l... | to_u8 | identifier_name |
disk.rs | // Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! VM disk image file format I/O.
use std::cmp::min;
use std::fmt::Debug;
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use s... | (&self, file_offset: u64, length: u64) -> Result<()> {
if self
.inner
.fallocate(file_offset, length, AllocateMode::ZeroRange)
.await
.is_ok()
{
return Ok(());
}
// Fall back to writing zeros if fallocate doesn't work.
... | write_zeroes_at | identifier_name |
disk.rs | // Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! VM disk image file format I/O.
use std::cmp::min;
use std::fmt::Debug;
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use s... | // max_nesting_depth is only used if the composite-disk or qcow features are enabled.
#[allow(unused_variables)] mut max_nesting_depth: u32,
// image_path is only used if the composite-disk feature is enabled.
#[allow(unused_variables)] image_path: &Path,
) -> Result<Box<dyn DiskFile>> {
if max_nest... | /// Inspect the image file type and create an appropriate disk file to match it.
pub fn create_disk_file(
raw_image: File,
is_sparse_file: bool, | random_line_split |
disk.rs | // Copyright 2019 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! VM disk image file format I/O.
use std::cmp::min;
use std::fmt::Debug;
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use s... |
#[cfg(feature = "qcow")]
ImageType::Qcow2 => {
Box::new(QcowFile::from(raw_image, max_nesting_depth).map_err(Error::QcowError)?)
as Box<dyn DiskFile>
}
#[cfg(feature = "composite-disk")]
ImageType::CompositeDisk => {
// Valid composite dis... | {
sys::apply_raw_disk_file_options(&raw_image, is_sparse_file)?;
Box::new(raw_image) as Box<dyn DiskFile>
} | conditional_block |
gen_functionalization_type.py | from tools.codegen.api import cpp
from tools.codegen.api.types import (
DispatcherSignature, Binding, FunctionalizationLambda, ViewInverseSignature
)
from tools.codegen.api.translate import translate
from tools.codegen.context import with_native_function
from tools.codegen.model import (
Argument, NativeFunctio... |
mutable_input_post_processing = '\n'.join([
f"""
auto {a.name}_functional = at::functionalization::impl::unsafeGetFunctionalWrapper({a.name});
{a.name}_functional->replace_(tmp_output);
{a.name}_functional->commit_update();"""
for a in f.func.arguments.flat_non_out
if a.an... | functional_exprs = [keyset] + [e.expr for e in translate(unwrapped_args_ctx, functional_sig.arguments(), method=False)] | random_line_split |
gen_functionalization_type.py | from tools.codegen.api import cpp
from tools.codegen.api.types import (
DispatcherSignature, Binding, FunctionalizationLambda, ViewInverseSignature
)
from tools.codegen.api.translate import translate
from tools.codegen.context import with_native_function
from tools.codegen.model import (
Argument, NativeFunctio... | (
selector: SelectiveBuilder,
f: NativeFunction,
composite_implicit_autograd_index: BackendIndex
) -> Optional[str]:
@with_native_function
def emit_registration_helper(f: NativeFunction) -> Optional[str]:
# Note: for now, this logic is meant to avoid registering functionalization kernels for... | gen_functionalization_registration | identifier_name |
gen_functionalization_type.py | from tools.codegen.api import cpp
from tools.codegen.api.types import (
DispatcherSignature, Binding, FunctionalizationLambda, ViewInverseSignature
)
from tools.codegen.api.translate import translate
from tools.codegen.context import with_native_function
from tools.codegen.model import (
Argument, NativeFunctio... |
# Generates the Functionalization kernel for inplace ops
def emit_inplace_functionalization_body(
f: NativeFunction,
functional_op: Optional[NativeFunction]
) -> str:
# mutation case
assert(modifies_arguments(f))
dispatcher_sig = DispatcherSignature.from_schema(f.func)
keyset = 'disp... | assert f.is_view_op
if f.tag is Tag.inplace_view:
# This op is both an inplace op AND a view op.
# See Note [Functionalization Pass - Inplace View Ops] for details.
# I currently have the view meta call into the out-of-place variant of the view, to avoid
# having to define an extra ... | identifier_body |
gen_functionalization_type.py | from tools.codegen.api import cpp
from tools.codegen.api.types import (
DispatcherSignature, Binding, FunctionalizationLambda, ViewInverseSignature
)
from tools.codegen.api.translate import translate
from tools.codegen.context import with_native_function
from tools.codegen.model import (
Argument, NativeFunctio... |
if f.is_view_op and f.has_composite_implicit_autograd_kernel:
metadata = composite_implicit_autograd_index.get_kernel(f)
assert metadata is not None
native_api_name = metadata.kernel
sig = DispatcherSignature.from_schema(f.func)
# Note [Composite view... | return None | conditional_block |
iterative_gmm.py |
import os, shutil
import itertools
import imageio
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.io import loadmat
from scipy.ndimage import gaussian_filter1d
from scipy import interpolate
from scipy import linalg
from sklearn.covariance import EmpiricalCovar... | :
def __init__(self):
self.XY = None
def plot_cov(self,means, covariances,ct):
if ct == 'spherical':
return
color_iter = itertools.cycle(['navy', 'navy', 'cornflowerblue', 'gold',
'darkorange'])
ax =plt.gca()
for i, (... | I_gmm | identifier_name |
iterative_gmm.py |
import os, shutil
import itertools
import imageio
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.io import loadmat
from scipy.ndimage import gaussian_filter1d
from scipy import interpolate
from scipy import linalg
from sklearn.covariance import EmpiricalCovar... |
self.plot_cov(gmm1.means_, gmm1.covariances_,ct)
ax0.scatter(X3[:,0],X3[:,1],c='k',alpha = 0.1)
ax0.set_title('New Method')
ax0.set_xlim(xlim)
ax0.set_ylim(ylim)
plt.text(.5*xlim[-1], ylim[0] + .005,'bad pts = {}'.format(format(len(c),"03")))
... | print(jj)
b = a == jj
b = [i for i, x in enumerate(b) if x]
if jj == 0:
c = b
ax0.scatter(X1[b,0],X1[b,1],c=colorz[(jj-a.min())]) | conditional_block |
iterative_gmm.py |
import os, shutil
import itertools
import imageio
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.io import loadmat
from scipy.ndimage import gaussian_filter1d
from scipy import interpolate
from scipy import linalg
from sklearn.covariance import EmpiricalCovar... |
def iterative_gmm(self,dataset = 'bb',fake = True,mode = 'gmm',binary = False,im_dir = './images/',savegif = False,title ='temp',bic_thresh = 0,maxiter = 40,nc =5,v_and_1 = False,thresh = 0.9,cov=[],n_components=2,covt='spherical',ra=False,pca = True):
'''
dataset: string
... | if ct == 'spherical':
return
color_iter = itertools.cycle(['navy', 'navy', 'cornflowerblue', 'gold',
'darkorange'])
ax =plt.gca()
for i, (mean, covar, color) in enumerate(zip(
means, covariances, color_iter)):
... | identifier_body |
iterative_gmm.py | import os, shutil
import itertools
import imageio
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.io import loadmat
from scipy.ndimage import gaussian_filter1d
from scipy import interpolate
from scipy import linalg
from sklearn.covariance import EmpiricalCovaria... | colorz = ['b','r','g','m']
for jj,color in zip(range(a.min(),a.max()+1),colorz):
print(jj)
b = a == jj
b = [i for i, x in enumerate(b) if x]
if jj == 0:
c = b
ax0.scatter(X1[b,0],X1[b,1],c=colorz[... |
a = -(y_pred - label_true.squeeze())
y_reshape = np.reshape(a, (20,length), order="F")
| random_line_split |
error_format.rs | pub mod data;
use crate::data::tokens::Span;
use crate::data::{position::Position, warnings::Warnings, Interval};
use nom::{
error::{ContextError, ErrorKind, ParseError},
*,
};
pub use crate::data::error_info::ErrorInfo;
pub use data::CustomError;
// TODO: add link to docs
// Parsing Errors
pub const ERROR_... |
pub fn gen_nom_failure<'a, E>(span: Span<'a>, error: &'static str) -> Err<E>
where
E: ParseError<Span<'a>> + ContextError<Span<'a>>,
{
Err::Failure(E::add_context(
span,
error,
E::from_error_kind(span, ErrorKind::Tag),
))
}
pub fn convert_error_from_span<'a>(flow_slice: Span<'a>, ... | {
Err::Error(E::add_context(
span,
error,
E::from_error_kind(span, ErrorKind::Tag),
))
} | identifier_body |
error_format.rs | pub mod data;
use crate::data::tokens::Span;
use crate::data::{position::Position, warnings::Warnings, Interval};
use nom::{
error::{ContextError, ErrorKind, ParseError},
*,
};
pub use crate::data::error_info::ErrorInfo;
pub use data::CustomError;
// TODO: add link to docs
// Parsing Errors
pub const ERROR_... | "JWT(jwt).decode(algo, secret) expect second argument 'claims' of type String";
pub const ERROR_JWT_VALIDATION_CLAIMS: &str =
"JWT(jwt).verify(claims, algo, secret) expect first argument 'claims' of type Object";
pub const ERROR_JWT_VALIDATION_ALGO: &str =
"JWT(jwt).verify(claims, algo, secret) expect seco... | random_line_split | |
error_format.rs | pub mod data;
use crate::data::tokens::Span;
use crate::data::{position::Position, warnings::Warnings, Interval};
use nom::{
error::{ContextError, ErrorKind, ParseError},
*,
};
pub use crate::data::error_info::ErrorInfo;
pub use data::CustomError;
// TODO: add link to docs
// Parsing Errors
pub const ERROR_... | <'a, E>(span: Span<'a>, error: &'static str) -> Err<E>
where
E: ParseError<Span<'a>> + ContextError<Span<'a>>,
{
Err::Failure(E::add_context(
span,
error,
E::from_error_kind(span, ErrorKind::Tag),
))
}
pub fn convert_error_from_span<'a>(flow_slice: Span<'a>, e: CustomError<Span<'a>>... | gen_nom_failure | identifier_name |
types.go | // Copyright 2015 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, ... | else {
b.writeByte(0)
}
case *ast.DInt:
switch t.Oid() {
case oid.T_int2:
b.putInt32(2)
b.putInt16(int16(*v))
case oid.T_int4:
b.putInt32(4)
b.putInt32(int32(*v))
case oid.T_int8:
b.putInt32(8)
b.putInt64(int64(*v))
default:
b.setError(errors.Errorf("unsupported int oid: %v", t.Oi... | {
b.writeByte(1)
} | conditional_block |
types.go | // Copyright 2015 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, ... |
// writeBinaryDatum writes d to the buffer. Type t must be specified for types
// that have various width encodings (floats, ints, chars). It is ignored
// (and can be nil) for types with a 1:1 datum:type mapping.
func (b *writeBuffer) writeBinaryDatum(
ctx context.Context, d ast.Datum, sessionLoc *time.Location, t ... | {
if log.V(2) {
log.Infof(ctx, "pgwire writing TEXT datum of type: %T, %#v", d, d)
}
if d == ast.DNull {
// NULL is encoded as -1; all other values have a length prefix.
b.putInt32(-1)
return
}
switch v := ast.UnwrapDatum(nil, d).(type) {
case *ast.DBitArray:
b.textFormatter.FormatNode(v)
b.writeFromF... | identifier_body |
types.go | // Copyright 2015 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, ... | oid oid.Oid
// Variable-size types have size=-1.
// Note that the protocol has both int16 and int32 size fields,
// so this attribute is an unsized int and should be cast
// as needed.
// This field does *not* correspond to the encoded length of a
// data type, so it's unclear what, if anything, it is used for.... | )
// pgType contains type metadata used in RowDescription messages.
type pgType struct { | random_line_split |
types.go | // Copyright 2015 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, ... | (t timetz.TimeTZ, tmp []byte) []byte {
ret := t.ToTime().AppendFormat(tmp, pgTimeTZFormat)
// time.Time's AppendFormat does not recognize 2400, so special case it accordingly.
if t.TimeOfDay == timeofday.Time2400 {
// It instead reads 00:00:00. Replace that text.
var newRet []byte
newRet = append(newRet, pgTim... | formatTimeTZ | identifier_name |
lmdb_backend.rs | // Copyright 2018 The Grin Developers
//
// 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 agree... | (&mut self, parent_key_id: &Identifier) -> Result<u32> {
let tx_id_key = to_key(TX_LOG_ID_PREFIX, &mut parent_key_id.to_bytes().to_vec());
let last_tx_log_id = match self.db.borrow().as_ref().unwrap().get_ser(&tx_id_key)? {
Some(t) => t,
None => 0,
};
self.db
.borrow()
.as_ref()
.unwrap()
.put... | next_tx_log_id | identifier_name |
lmdb_backend.rs | // Copyright 2018 The Grin Developers
//
// 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 agree... | fn check_repair(&mut self, delete_unconfirmed: bool) -> Result<()> {
restore::check_repair(self, delete_unconfirmed).context(ErrorKind::Restore)?;
Ok(())
}
fn calc_commit_for_cache(&mut self, amount: u64, id: &Identifier) -> Result<Option<String>> {
if self.config.no_commit_cache == Some(true) {
Ok(None)
... | Ok(())
}
| random_line_split |
lmdb_backend.rs | // Copyright 2018 The Grin Developers
//
// 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 agree... |
self.db = Some(store);
Ok(())
}
/// Disconnect from backend
fn disconnect(&mut self) -> Result<()> {
self.db = None;
Ok(())
}
/// Set password
fn set_password(&mut self, password: ZeroingString) -> Result<()> {
let _ = WalletSeed::from_file(&self.config, password.deref())?;
self.password = Some(pa... | {
let batch = store.batch()?;
batch.put_ser(&acct_key, &default_account)?;
batch.commit()?;
} | conditional_block |
lmdb_backend.rs | // Copyright 2018 The Grin Developers
//
// 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 agree... |
fn accounts<'a>(&'a self) -> Result<Box<dyn Iterator<Item = AcctPathMapping> + 'a>> {
Ok(Box::new(
self.db()?
.iter(&[ACCOUNT_PATH_MAPPING_PREFIX])
.unwrap()
.map(|x| x.1),
))
}
fn get_acct_path(&self, label: &str) -> Result<Option<AcctPathMapping>> {
let acct_key = to_key(ACCOUNT_PATH_MAPPIN... | {
let ctx_key = to_key_u64(
PRIVATE_TX_CONTEXT_PREFIX,
&mut slate_id.to_vec(),
participant_id as u64,
);
let (blind_xor_key, nonce_xor_key) = private_ctx_xor_keys(self.keychain(), slate_id)?;
let mut ctx: Context = option_to_not_found(self.db()?.get_ser(&ctx_key), || {
format!("Slate id: {:x?}", sl... | identifier_body |
lib.rs | //! Welcome to CCP.
//!
//! This crate, portus, implements a CCP. This includes:
//! 1. An interface definition for external types wishing to implement congestion control
//! algorithms (`CongAlg`).
//! 2. A [compiler](lang/index.html) for datapath programs.
//! 3. An IPC and serialization [layer](ipc/index.html) fo... | fn update_field(&self, sc: &Scope, update: &[(&str, u32)]) -> Result<()>;
}
/// A collection of methods to interact with the datapath.
#[derive(Clone)]
pub struct Datapath<T: Ipc> {
sock_id: u32,
sender: BackendSender<T>,
programs: Rc<HashMap<String, Scope>>,
}
impl<T: Ipc> DatapathTrait for Datapath<... | ) -> Result<Scope>;
/// Update the value of a register in an already-installed fold function. | random_line_split |
lib.rs | //! Welcome to CCP.
//!
//! This crate, portus, implements a CCP. This includes:
//! 1. An interface definition for external types wishing to implement congestion control
//! algorithms (`CongAlg`).
//! 2. A [compiler](lang/index.html) for datapath programs.
//! 3. An IPC and serialization [layer](ipc/index.html) fo... | {
pub sock_id: u32,
pub init_cwnd: u32,
pub mss: u32,
pub src_ip: u32,
pub src_port: u32,
pub dst_ip: u32,
pub dst_port: u32,
}
/// Contains the values of the pre-defined Report struct from the fold function.
/// Use `get_field` to query its values using the names defined in the fold funct... | DatapathInfo | identifier_name |
lib.rs | //! Welcome to CCP.
//!
//! This crate, portus, implements a CCP. This includes:
//! 1. An interface definition for external types wishing to implement congestion control
//! algorithms (`CongAlg`).
//! 2. A [compiler](lang/index.html) for datapath programs.
//! 3. An IPC and serialization [layer](ipc/index.html) fo... |
/// Configuration parameters for the portus runtime.
/// Defines a `slog::Logger` to use for (optional) logging
#[derive(Clone, Default)]
pub struct Config {
pub logger: Option<slog::Logger>,
}
/// The set of information passed by the datapath to CCP
/// when a connection starts. It includes a unique 5-tuple (CC... | {
let msg = serialize::install::Msg {
sid: sock_id,
program_uid: sc.program_uid,
num_events: bin.events.len() as u32,
num_instrs: bin.instrs.len() as u32,
instrs: bin,
};
let buf = serialize::serialize(&msg)?;
sender.send_msg(&buf[..])?;
Ok(())
} | identifier_body |
models.py | """passbook core models"""
from datetime import timedelta
from random import SystemRandom
from time import sleep
from typing import Any, Optional
from uuid import uuid4
from django.contrib.auth.models import AbstractUser
from django.contrib.postgres.fields import JSONField
from django.core.exceptions import Validation... | :
permissions = (("reset_user_password", "Reset Password"),)
class Provider(ExportModelOperationsMixin("provider"), models.Model):
"""Application-independent Provider instance. For example SAML2 Remote, OAuth2 Application"""
property_mappings = models.ManyToManyField(
"PropertyMapping", defa... | Meta | identifier_name |
models.py | """passbook core models"""
from datetime import timedelta
from random import SystemRandom
from time import sleep
from typing import Any, Optional
from uuid import uuid4
from django.contrib.auth.models import AbstractUser
from django.contrib.postgres.fields import JSONField
from django.core.exceptions import Validation... |
class DebugPolicy(Policy):
"""Policy used for debugging the PolicyEngine. Returns a fixed result,
but takes a random time to process."""
result = models.BooleanField(default=False)
wait_min = models.IntegerField(default=5)
wait_max = models.IntegerField(default=30)
form = "passbook.core.for... | """Check if user instance passes this policy"""
raise PolicyException() | identifier_body |
models.py | """passbook core models"""
from datetime import timedelta
from random import SystemRandom
from time import sleep
from typing import Any, Optional
from uuid import uuid4
from django.contrib.auth.models import AbstractUser
from django.contrib.postgres.fields import JSONField
from django.core.exceptions import Validation... | """Policy used for debugging the PolicyEngine. Returns a fixed result,
but takes a random time to process."""
result = models.BooleanField(default=False)
wait_min = models.IntegerField(default=5)
wait_max = models.IntegerField(default=30)
form = "passbook.core.forms.policies.DebugPolicyForm"
... | raise PolicyException()
class DebugPolicy(Policy): | random_line_split |
models.py | """passbook core models"""
from datetime import timedelta
from random import SystemRandom
from time import sleep
from typing import Any, Optional
from uuid import uuid4
from django.contrib.auth.models import AbstractUser
from django.contrib.postgres.fields import JSONField
from django.core.exceptions import Validation... |
return super().__str__()
class PolicyModel(UUIDModel, CreatedUpdatedModel):
"""Base model which can have policies applied to it"""
policies = models.ManyToManyField("Policy", blank=True)
class Factor(ExportModelOperationsMixin("factor"), PolicyModel):
"""Authentication factor, multiple instanc... | return getattr(self, "name") | conditional_block |
Ui_Offer_Home.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\Administrator\Desktop\Python\ERP\Offer_Home.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import pymysql
from functools import... | self.Box_group.setToolTip(_translate("Offer_Home", "分组"))
self.Box_filter.setToolTip(_translate("Offer_Home", "筛选"))
self.Line_search.setToolTip(_translate("Offer_Home", "搜索"))
self.Line_search.setPlaceholderText(_translate("Offer_Home", "搜索...."))
if __name__ == "__main__":
import sys
... | j in range(vol_3):
temp_data = data_3[i][j] # 临时记录,不能直接插入表格
data3 = QTableWidgetItem(str(temp_data)) # 转换后可插入表格
self.Widget_details.setItem(i, j, data3)
self.Widget_details.resizeColumnsToContents() #自适应宽度
self.Widget_de... | identifier_body |
Ui_Offer_Home.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\Administrator\Desktop\Python\ERP\Offer_Home.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import pymysql
from functools import... | identifier_name | ||
Ui_Offer_Home.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\Administrator\Desktop\Python\ERP\Offer_Home.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import pymysql
from functools import... | conn = db.cursor()
sql = "SELECT * FROM 报价明细 WHERE 报价单号 LIKE 'BJ18011516'" #'%"+bjdh+"%'"
conn.execute(sql)
col_lst_1 = [tup[0] for tup in conn.description] #数据列字段名 tup:数组 #description:种类
vol_1 = len(conn.description) #获得data的卷数.第一行的数量(... | og.resizeRowsToContents() #自适应行高,这两句放最后可以等数据写入后自动适应表格数据宽度
db.close
cur.close
#报价明细区域
# db = pymysql.connect(host='127.0.0.1', port=3308, user='root', password='root', db='mrp',charset='utf8',)
| conditional_block |
Ui_Offer_Home.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'C:\Users\Administrator\Desktop\Python\ERP\Offer_Home.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import pymysql
from functools import... | self.verticalLayout.setObjectName("verticalLayout")
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setObjectName("horizontalLayout")
self.Button_offernew = QtWidgets.QPushButton(Offer_Home)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("images/A... | self.verticalLayout = QtWidgets.QVBoxLayout(Offer_Home) | random_line_split |
utils.rs | pub const PLUMO_SETUP_PERSONALIZATION: &[u8] = b"PLUMOSET";
pub const ADDRESS_LENGTH: usize = 20;
pub const ADDRESS_LENGTH_IN_HEX: usize = 42;
pub const SIGNATURE_LENGTH_IN_HEX: usize = 130;
pub const DEFAULT_MAX_RETRIES: usize = 5;
pub const ONE_MB: usize = 1024 * 1024;
pub const DEFAULT_CHUNK_SIZE: u64 = 1 * (ONE_MB ... |
pub fn trim_newline(s: &mut String) {
if s.ends_with('\n') {
s.pop();
if s.ends_with('\r') {
s.pop();
}
}
}
pub fn compute_hash_from_file(fname: &str) -> Result<String> {
let challenge_contents = std::fs::read(fname)?;
Ok(hex::encode(setup_utils::calculate_hash(
... | {
File::create(path)?.write_all(
format_attestation(
&attestation.id,
&attestation.address,
&attestation.signature,
)
.as_bytes(),
)?;
Ok(())
} | identifier_body |
utils.rs | pub const PLUMO_SETUP_PERSONALIZATION: &[u8] = b"PLUMOSET";
pub const ADDRESS_LENGTH: usize = 20;
pub const ADDRESS_LENGTH_IN_HEX: usize = 42;
pub const SIGNATURE_LENGTH_IN_HEX: usize = 130;
pub const DEFAULT_MAX_RETRIES: usize = 5;
pub const ONE_MB: usize = 1024 * 1024;
pub const DEFAULT_CHUNK_SIZE: u64 = 1 * (ONE_MB ... | .parse::<u64>()?)
}
pub async fn get_ceremony(url: &str) -> Result<Ceremony> {
let response = reqwest::get(url).await?.error_for_status()?;
let data = response.text().await?;
let ceremony: Ceremony = serde_json::from_str::<Response<Ceremony>>(&data)?.result;
Ok(ceremony)
}
use crate::transcrip... | .to_str()? | random_line_split |
utils.rs | pub const PLUMO_SETUP_PERSONALIZATION: &[u8] = b"PLUMOSET";
pub const ADDRESS_LENGTH: usize = 20;
pub const ADDRESS_LENGTH_IN_HEX: usize = 42;
pub const SIGNATURE_LENGTH_IN_HEX: usize = 130;
pub const DEFAULT_MAX_RETRIES: usize = 5;
pub const ONE_MB: usize = 1024 * 1024;
pub const DEFAULT_CHUNK_SIZE: u64 = 1 * (ONE_MB ... | (transcript: &Transcript) -> Result<()> {
let filename = format!("transcript_{}", chrono::Utc::now().timestamp_nanos());
let mut file = File::create(filename)?;
file.write_all(serde_json::to_string_pretty(transcript)?.as_bytes())?;
Ok(())
}
pub fn format_attestation(attestation_message: &str, address:... | backup_transcript | identifier_name |
schema.py | import uuid
import django_filters
import graphene
import graphql_geojson
from django.apps import apps
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from graphene import ID, ObjectType, relay, String
from graphen... | ngoObjectType):
"""Tags are associated with things (like features)."""
class Meta:
model = models.Tag
fields = ("id", "features")
name = graphene.String(required=True, description=_("Display name of the tag"))
class OpeningHoursPeriod(DjangoObjectType):
"""A period during which certa... | Dja | identifier_name |
schema.py | import uuid
import django_filters
import graphene
import graphql_geojson
from django.apps import apps
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from graphene import ID, ObjectType, relay, String
from graphen... |
def resolve_feature(self, info, id=None, ahti_id=None, **kwargs):
if id:
return relay.Node.get_node_from_global_id(info, id, only_type=Feature)
if ahti_id:
try:
return Feature.get_queryset(models.Feature.objects, info).ahti_id(
ahti_id=aht... | ahti_id=String(description=_("Ahti ID of the object")),
description=_("Retrieve a single feature"),
)
tags = graphene.List(Tag, description=_("Retrieve all tags")) | random_line_split |
schema.py | import uuid
import django_filters
import graphene
import graphql_geojson
from django.apps import apps
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from graphene import ID, ObjectType, relay, String
from graphen... | lass CreateFeatureMutation(relay.ClientIDMutation):
class Input:
translations = graphene.List(
graphene.NonNull(FeatureTranslationsInput), required=True
)
geometry = graphql_geojson.Geometry(required=True)
contact_info = ContactInfoInput()
category_id = graphene.S... | et_address = graphene.String()
postal_code = graphene.String()
municipality = graphene.String()
phone_number = graphene.String()
email = graphene.String()
c | identifier_body |
schema.py | import uuid
import django_filters
import graphene
import graphql_geojson
from django.apps import apps
from django.db import transaction
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from graphene import ID, ObjectType, relay, String
from graphen... | if ahti_id:
try:
return Feature.get_queryset(models.Feature.objects, info).ahti_id(
ahti_id=ahti_id
)
except models.Feature.DoesNotExist:
return None
raise GraphQLError("You must provide either `id` or `ahtiId`.")
... | rn relay.Node.get_node_from_global_id(info, id, only_type=Feature)
| conditional_block |
config.go | package config
import (
"encoding/json"
"fmt"
"io"
"net"
"os"
"strings"
cnitypes "github.com/containernetworking/cni/pkg/types"
types020 "github.com/containernetworking/cni/pkg/types/020"
"github.com/imdario/mergo"
netutils "k8s.io/utils/net"
"github.com/k8snetworkplumbingwg/whereabouts/pkg/logging"
"gi... | else {
firstip, ipNet, err := netutils.ParseCIDRSloppy(n.IPAM.IPRanges[idx].Range)
if err != nil {
return nil, "", fmt.Errorf("invalid CIDR %s: %s", n.IPAM.IPRanges[idx].Range, err)
}
n.IPAM.IPRanges[idx].Range = ipNet.String()
if n.IPAM.IPRanges[idx].RangeStart == nil {
firstip = netutils.Parse... | {
firstip := netutils.ParseIPSloppy(r[0])
if firstip == nil {
return nil, "", fmt.Errorf("invalid range start IP: %s", r[0])
}
lastip, ipNet, err := netutils.ParseCIDRSloppy(r[1])
if err != nil {
return nil, "", fmt.Errorf("invalid CIDR (do you have the 'range' parameter set for Whereabouts?) '%s... | conditional_block |
config.go | package config
import (
"encoding/json"
"fmt"
"io"
"net"
"os"
"strings"
cnitypes "github.com/containernetworking/cni/pkg/types"
types020 "github.com/containernetworking/cni/pkg/types/020"
"github.com/imdario/mergo"
netutils "k8s.io/utils/net"
"github.com/k8snetworkplumbingwg/whereabouts/pkg/logging"
"gi... | // as `bytes`. At the moment values provided in envArgs are ignored so there
// is no possibility to overload the json configuration using envArgs
func LoadIPAMConfig(bytes []byte, envArgs string, extraConfigPaths ...string) (*types.IPAMConfig, string, error) {
var n types.Net
if err := json.Unmarshal(bytes, &n); er... | }
return fmt.Errorf("IP %s not v4 nor v6", *ip)
}
// LoadIPAMConfig creates IPAMConfig using json encoded configuration provided | random_line_split |
config.go | package config
import (
"encoding/json"
"fmt"
"io"
"net"
"os"
"strings"
cnitypes "github.com/containernetworking/cni/pkg/types"
types020 "github.com/containernetworking/cni/pkg/types/020"
"github.com/imdario/mergo"
netutils "k8s.io/utils/net"
"github.com/k8snetworkplumbingwg/whereabouts/pkg/logging"
"gi... | (bytes []byte, envArgs string, extraConfigPaths ...string) (*types.IPAMConfig, string, error) {
var n types.Net
if err := json.Unmarshal(bytes, &n); err != nil {
return nil, "", fmt.Errorf("LoadIPAMConfig - JSON Parsing Error: %s / bytes: %s", err, bytes)
}
if n.IPAM == nil {
return nil, "", fmt.Errorf("IPAM ... | LoadIPAMConfig | identifier_name |
config.go | package config
import (
"encoding/json"
"fmt"
"io"
"net"
"os"
"strings"
cnitypes "github.com/containernetworking/cni/pkg/types"
types020 "github.com/containernetworking/cni/pkg/types/020"
"github.com/imdario/mergo"
netutils "k8s.io/utils/net"
"github.com/k8snetworkplumbingwg/whereabouts/pkg/logging"
"gi... |
func pathExists(path string) bool {
_, err := os.Stat(path)
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
return true
}
func configureStatic(n *types.Net, args types.IPAMEnvArgs) error {
// Validate all ranges
numV4 := 0
numV6 := 0
for i := range n.IPAM.Addresses {
ip, addr, ... | {
var n types.Net
if err := json.Unmarshal(bytes, &n); err != nil {
return nil, "", fmt.Errorf("LoadIPAMConfig - JSON Parsing Error: %s / bytes: %s", err, bytes)
}
if n.IPAM == nil {
return nil, "", fmt.Errorf("IPAM config missing 'ipam' key")
} else if !isNetworkRelevant(n.IPAM) {
return nil, "", NewInval... | identifier_body |
ontology.js | /*
__author__ = "Jesse Stombaugh"
__copyright__ = "Copyright 2010, Qiime Web Analysis"
__credits__ = ["Jesse Stombaugh", "Emily TerAvest"]
__license__ = "GPL"
__version__ = "1.0.0.dev"
__maintainer__ = ["Jesse Stombaugh"]
__email__ = "jesse.stombaugh@colorado.edu"
__status__ = "Production"
*/
var xmlhttp
var geoco... |
function displayGeography(){
document.getElementById("ontology_lookup").style.display='none';
document.getElementById("geographic_location").style.display='';
document.getElementById("map_canvas").style.visibility='visible';
}
/* Initializes the Google Map. */
function initialize(){
geocoder = new go... | {
document.getElementById("ontology_lookup").style.display='';
document.getElementById("geographic_location").style.display='none';
document.getElementById("map_canvas").style.visibility='hidden';
} | identifier_body |
ontology.js | /*
__author__ = "Jesse Stombaugh"
__copyright__ = "Copyright 2010, Qiime Web Analysis"
__credits__ = ["Jesse Stombaugh", "Emily TerAvest"]
__license__ = "GPL"
__version__ = "1.0.0.dev"
__maintainer__ = ["Jesse Stombaugh"]
__email__ = "jesse.stombaugh@colorado.edu"
__status__ = "Production"
*/
var xmlhttp
var geoco... | (){
//generate the output content
type=document.getElementById('latlngType').value
var content='';
for (var i=0; i<saved_address_array.length; i++) {
if (type=='Latitude'){
content=content+latitude[saved_address_array[i]]+'<br>';
}else if (type=='Longitude'){
... | output_latlong | identifier_name |
ontology.js | /*
__author__ = "Jesse Stombaugh"
__copyright__ = "Copyright 2010, Qiime Web Analysis"
__credits__ = ["Jesse Stombaugh", "Emily TerAvest"]
__license__ = "GPL"
__version__ = "1.0.0.dev"
__maintainer__ = ["Jesse Stombaugh"]
__email__ = "jesse.stombaugh@colorado.edu"
__status__ = "Production"
*/
var xmlhttp
var geoco... | output_array.push(updated_unique_terms[k]);
}
}
if(original_ont_term_array[j]=='' && j!=0){
output_array.push(output_array[j-1]);
}else if(original_ont_term_array[j]=='' && j==0){
output_array.push('n/a');
}
}
//write the a... | if (original_ont_term_array[j]==original_unique_terms[k]){ | random_line_split |
ontology.js | /*
__author__ = "Jesse Stombaugh"
__copyright__ = "Copyright 2010, Qiime Web Analysis"
__credits__ = ["Jesse Stombaugh", "Emily TerAvest"]
__license__ = "GPL"
__version__ = "1.0.0.dev"
__maintainer__ = ["Jesse Stombaugh"]
__email__ = "jesse.stombaugh@colorado.edu"
__status__ = "Production"
*/
var xmlhttp
var geoco... | else if (validity=='Invalid' || validity=='Invalid\n'){
alert('You have invalid terms!');
return;
}
}
}
//generate a new array with update terms based on the valid input boxes
output_array=new Array();
//using length-1 since we appended an empty e... | {
alert('You need choose valid terms!');
return;
} | conditional_block |
render.js | import * as THREE from "three";
import Stats from "stats.js";
import * as d3 from "d3";
import seedrandom from "seedrandom";
import * as dat from "exdat";
import noise from "fast-simplex-noise";
import Terrain from "../lib/terrain.js";
var style = document.createElement("style");
style.type = "text/css";
// TODO remov... |
function makeFlat(f) {
function mf(g) {
if (!g.old) {
g.old = g.vertices.map(function(v,i) {
return v.y;
});
}
g.vertices.map(function (v, i) {
if (f) { v.y = 0; } else { v.y = g.old[i]; }
});
g.dynamic = g.vertic... | {
if (!map) {
return;
}
var cells = map.voronoi.cells;
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
var faces = cell.faces;
for (var j = 0; j < faces.length; j++) {
var f = faces[j];
var c = f.color;
c... | identifier_body |
render.js | import * as THREE from "three";
import Stats from "stats.js";
import * as d3 from "d3";
import seedrandom from "seedrandom";
import * as dat from "exdat";
import noise from "fast-simplex-noise";
import Terrain from "../lib/terrain.js";
var style = document.createElement("style");
style.type = "text/css";
// TODO remov... | this.seaLevel = 0.45;
this.heightFrequency = 1.2;
this.heightScale = 0.3;
this.render = "biome";
}
var gui = new dat.GUI();
var settings = new Settings();
gui.add(settings, "sites", 0).step(50).onFinishChange(newVoronoi);
gui.add(settings, "heightScale", 0, 1).step(0.01);
gui.add(settings, "heightFreque... | this.flat = false; | random_line_split |
render.js | import * as THREE from "three";
import Stats from "stats.js";
import * as d3 from "d3";
import seedrandom from "seedrandom";
import * as dat from "exdat";
import noise from "fast-simplex-noise";
import Terrain from "../lib/terrain.js";
var style = document.createElement("style");
style.type = "text/css";
// TODO remov... | (f) {
function mf(g) {
if (!g.old) {
g.old = g.vertices.map(function(v,i) {
return v.y;
});
}
g.vertices.map(function (v, i) {
if (f) { v.y = 0; } else { v.y = g.old[i]; }
});
g.dynamic = g.verticesNeedUpdate = true... | makeFlat | identifier_name |
build_all.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Run docker build -> test -> push workflow for all repositories and images.
"""
import hashlib
import json
import logging
import os
import re
import subprocess
from datetime import datetime
import docker
from pynamodb.attributes import UnicodeAttribute
from pynamodb.e... |
logger.info("--- build plan summary ---")
if len(image_list):
logger.info("we got these images to build")
for image in image_list:
logger.info(f" {image.local_identifier}")
else:
logger.info("we got NO image to build")
return image_list
def run_and_log_command(c... | image_list.append(image) | conditional_block |
build_all.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Run docker build -> test -> push workflow for all repositories and images.
"""
import hashlib
import json
import logging
import os
import re
import subprocess
from datetime import datetime
import docker
from pynamodb.attributes import UnicodeAttribute
from pynamodb.e... | image.identifier = image.local_identifier
image.md5 = image.dockerfile_md5
image.is_state_exists = False
except Exception as e:
raise e
if is_todo:
image_list.append(image)
logger.info("--- build plan summary -... | random_line_split | |
build_all.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Run docker build -> test -> push workflow for all repositories and images.
"""
import hashlib
import json
import logging
import os
import re
import subprocess
from datetime import datetime
import docker
from pynamodb.attributes import UnicodeAttribute
from pynamodb.e... | (string, comment_symbols=frozenset(('#', '//'))):
"""
Strip comments from json string.
:param string: A string containing json with comments started by comment_symbols.
:param comment_symbols: Iterable of symbols that start a line comment (default # or //).
:return: The string with the comments remo... | strip_comments | identifier_name |
build_all.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Run docker build -> test -> push workflow for all repositories and images.
"""
import hashlib
import json
import logging
import os
import re
import subprocess
from datetime import datetime
import docker
from pynamodb.attributes import UnicodeAttribute
from pynamodb.e... |
dockerhub_username = DOCKER_HUB_USERNAME # type: str
dir_repo_root = None # type: str
dir_tag_root = None # type: str
is_state_exists = None # type: bool
_repo_name = None # type: str
@property
def repo_name(self):
if self._repo_name is None:
self._repo_name = re... | """
datetime type of ``last_update``
"""
return datetime.strptime(self.last_update, "%Y-%m-%d %H:%M:%S.%f") | identifier_body |
admission_test.go | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
}
controller, err := newControllerWithTestServer(serve, true)
if err != nil {
t.Errorf("%v: Unexpected error while creating test admission controller/server: %v", tc.note, err)
continue
}
obj := makeReplicaSet()
attrs := admission.NewAttributesRecord(obj, nil, obj.GroupVersionKind(), obj.Namespace... | {
w.Write([]byte(tc.body))
} | conditional_block |
admission_test.go | /*
Copyright 2017 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
configFile, err := makeAdmissionControlConfigFile(kubeConfigFile)
if err != nil {
return nil, err
}
defer os.Remove(configFile)
file, err := os.Open(configFile)
if err != nil {
return nil, err
}
controller, err := newAdmissionController(file)
if err != nil {
return nil, err
}
mockClient := &fake.C... | }
defer os.Remove(kubeConfigFile) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.