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 |
|---|---|---|---|---|
sampleMultiMCTSAgentTrajectory.py | import time
import sys
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
DIRNAME = os.path.dirname(__file__)
sys.path.append(os.path.join(DIRNAME, '..', '..'))
import json
import numpy as np
from collections import OrderedDict
import pandas as pd
import mujoco_py as mujoco
from src.constrainedChasingEscapingEnv.env... | (self, multiAgentNNModel):
multiAgentApproximatePolicy = np.array([self.approximatePolicy(NNModel) for NNModel in multiAgentNNModel])
otherAgentPolicyForMCTSAgents = np.array([np.concatenate([multiAgentApproximatePolicy[:agentId], multiAgentApproximatePolicy[agentId + 1:]])
... | __call__ | identifier_name |
sampleMultiMCTSAgentTrajectory.py | import time
import sys
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
DIRNAME = os.path.dirname(__file__)
sys.path.append(os.path.join(DIRNAME, '..', '..'))
import json
import numpy as np
from collections import OrderedDict
import pandas as pd
import mujoco_py as mujoco
from src.constrainedChasingEscapingEnv.env... |
# sample and save trajectories
policy = prepareMultiAgentPolicy(multiAgentNNmodel)
trajectories = [sampleTrajectory(policy) for sampleIndex in range(startSampleIndex, endSampleIndex)]
saveToPickle(trajectories, trajectorySavePath)
if __name__ == '__main__':
main()
| modelPath = generateNNModelSavePath({'iterationIndex': iterationIndex, 'agentId': agentId})
restoredNNModel = restoreVariables(multiAgentNNmodel[agentId], modelPath)
multiAgentNNmodel[agentId] = restoredNNModel | conditional_block |
sampleMultiMCTSAgentTrajectory.py | import time
import sys
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
DIRNAME = os.path.dirname(__file__)
sys.path.append(os.path.join(DIRNAME, '..', '..'))
import json
import numpy as np
from collections import OrderedDict
import pandas as pd
import mujoco_py as mujoco
from src.constrainedChasingEscapingEnv.env... | numAgents = 2
qVelInitNoise = 8
qPosInitNoise = 9.7
reset = ResetUniform(physicsSimulation, qPosInit, qVelInit, numAgents, qPosInitNoise, qVelInitNoise)
agentIds = list(range(numAgents))
sheepId = 0
wolfId = 1
xPosIndex = [2, 3]
getSheepXPos = Get... | random_line_split | |
ballot.rs | use indexmap::IndexMap;
use prost::Message;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Ballot {
pub id: String,
pub contests: Vec<u32>, // List of contest indexes
/// Application specific properties.
///
/// Hashmaps are not allowed because their unstable ordering leads to non-dete... | #[serde(default)]
pub write_in: bool,
/// Score has different meanings depending on the tally type:
/// STV, Condorcet, Borda and Schulze: `score` means candidate rank, where a zero is the best rank that can be assigned to a candidate.
/// Score: `score` is the points assinged to this candidate. Ze... | #[derive(Serialize, Deserialize, Clone, Message, PartialEq, Eq)]
pub struct Selection {
/// true if the `selection` field is a free-form write-in, false if the `selection` field corresponds to a known candidate-id
#[prost(bool)] | random_line_split |
ballot.rs | use indexmap::IndexMap;
use prost::Message;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct | {
pub id: String,
pub contests: Vec<u32>, // List of contest indexes
/// Application specific properties.
///
/// Hashmaps are not allowed because their unstable ordering leads to non-determinism.
#[serde(default)]
#[serde(skip_serializing_if = "IndexMap::is_empty")]
pub properties: In... | Ballot | identifier_name |
universe.rs | /*!
# RS Mate Poe: Universe
*/
use crate::{
Frame,
Position,
State,
};
#[cfg(feature = "director")] use crate::{Animation, dom};
use std::sync::atomic::{
AtomicU8,
AtomicU32,
AtomicU64,
Ordering::SeqCst,
};
#[cfg(feature = "director")] use std::sync::atomic::AtomicU16;
#[cfg(target_arch = "wasm32")] use wasm_bi... | [cfg(feature = "firefox")]
/// # Fix Element Bindings?
///
/// Returns `true` if one or both elements seem to have disappeared from
/// the document body since the last time this method was called.
pub(crate) fn fix_bindings() -> bool {
let old = FLAGS.fetch_and(! Self::FIX_BINDINGS, SeqCst);
let expected = Se... | let old = FLAGS.fetch_and(! Self::ASSIGN_CHILD, SeqCst);
Self::ASSIGN_CHILD == old & Self::ASSIGN_CHILD
}
# | identifier_body |
universe.rs | /*!
# RS Mate Poe: Universe
*/
use crate::{
Frame,
Position,
State,
};
#[cfg(feature = "director")] use crate::{Animation, dom};
use std::sync::atomic::{
AtomicU8,
AtomicU32,
AtomicU64,
Ordering::SeqCst,
};
#[cfg(feature = "director")] use std::sync::atomic::AtomicU16;
#[cfg(target_arch = "wasm32")] use wasm_bi... | > bool {
let old = FLAGS.fetch_and(! Self::ASSIGN_CHILD, SeqCst);
Self::ASSIGN_CHILD == old & Self::ASSIGN_CHILD
}
#[cfg(feature = "firefox")]
/// # Fix Element Bindings?
///
/// Returns `true` if one or both elements seem to have disappeared from
/// the document body since the last time this method was cal... | gn_child() - | identifier_name |
universe.rs | /*!
# RS Mate Poe: Universe
*/
use crate::{
Frame,
Position,
State,
};
#[cfg(feature = "director")] use crate::{Animation, dom};
use std::sync::atomic::{
AtomicU8,
AtomicU32,
AtomicU64,
Ordering::SeqCst,
};
#[cfg(feature = "director")] use std::sync::atomic::AtomicU16;
#[cfg(target_arch = "wasm32")] use wasm_bi... | assert_eq!(Universe::rand_mod(0), 0, "Random zero broke!");
let set = (0..5000_u16).into_iter()
.map(|_| Universe::rand_mod(100))
.collect::<HashSet<u16>>();
assert!(set.iter().all(|n| *n < 100), "Value(s) out of range.");
assert_eq!(
set.len(),
100,
"Failed to collect 100/100 possibilities in ... | use super::*;
use std::collections::HashSet;
#[test]
fn t_rand() { | random_line_split |
visual_functions-checkpoint.py | import numpy as np
from sklearn.metrics import roc_curve, auc, f1_score, accuracy_score, precision_recall_curve
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib
import seaborn as sns
#sns.color_palette('husl', n_colors=20)
from sklearn.metrics import confusion_mat... |
else:
OFFSET = 0
plt.text(av,OFFSET,b,color='darkorange')
ax.set_ylabel("")
ax.tick_params(axis='both', which='major')
leg=legend(ax,ncol=2, pos=(0.5, -0.2))
return leg
def get_model_results(dataset="plaid", model_name='CNN', width=50,run_id=1, cv=10, fig_path=None):
mul... | OFFSET = -0.7
plt.text(av-5,OFFSET,b,color='darkorange') | conditional_block |
visual_functions-checkpoint.py | import numpy as np
from sklearn.metrics import roc_curve, auc, f1_score, accuracy_score, precision_recall_curve
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib
import seaborn as sns
#sns.color_palette('husl', n_colors=20)
from sklearn.metrics import confusion_mat... | (ax):
for spine in ['top', 'right']:
ax.spines[spine].set_visible(False)
for spine in ['left', 'bottom']:
ax.spines[spine].set_color(SPINE_COLOR)
ax.spines[spine].set_linewidth(0.5)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')... | format_axes | identifier_name |
visual_functions-checkpoint.py | import numpy as np
from sklearn.metrics import roc_curve, auc, f1_score, accuracy_score, precision_recall_curve
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib
import seaborn as sns
#sns.color_palette('husl', n_colors=20)
from sklearn.metrics import confusion_mat... |
def get_Fmeasure(cm, n):
av = 0
p = []
for i in range(len(n)):
teller = 2 * cm[i,i]
noemer = sum(cm[:,i]) + sum(cm[i,:])
F = float(teller) / float(noemer)
av += F
#print('{0} {1:.2f}'.format(names[i],F*100))
p.append(F*100)
av = av/len(n)*... | av = 0
p = []
for i in range(len(n)):
teller = 2 * cm[i,i]
noemer = sum(cm[:,i]) + sum(cm[i,:])
F = float(teller) / float(noemer)
av += F
#print('{0} {1:.2f}'.format(names[i],F*100))
p.append(F*100)
av = av/len(n)*100
p = np.array(p)
volgorde = n... | identifier_body |
visual_functions-checkpoint.py | import numpy as np
from sklearn.metrics import roc_curve, auc, f1_score, accuracy_score, precision_recall_curve
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib
import seaborn as sns
#sns.color_palette('husl', n_colors=20)
from sklearn.metrics import confusion_mat... | volgorde = np.argsort(p)
fig, ax = plt.subplots(figsize=(6, 5))
sns.set_color_codes("pastel")
sns.barplot(x=p[volgorde],
y=np.array(n)[volgorde], color='b')
plt.axvline(x=av,color='orange', linewidth=1.0, linestyle="--")
a = '{0:0.02f}'.format(av)
b = '$Fmacro =\ $'+a
i... | p.append(F*100)
av = av/len(n)*100
p = np.array(p)
| random_line_split |
lib.rs | //working off example (spi): https://github.com/japaric/mfrc522/blob/master/src/lib.rs
//another example: https://github.com/JohnDoneth/hd44780-driver/blob/master/examples/raspberrypi/src/main.rs
//#![no_std] //FIXME TODO remove all std lib dependencies
extern crate embedded_hal as hal;
#[macro_use]
extern crate bitfl... | (&mut self) -> Result<(),&'static str> {
//self.cs.set_high();
//check if the radio responds by seeing if we can change a register
let mut synced = false;
for _attempt in 0..100 {
self.write_reg(Register::Syncvalue1, 0xAA); //170
self.delay.delay_ms(1);
if self.read_reg(Register::Syncvalue1) == 0xAA {... | init | identifier_name |
lib.rs | //working off example (spi): https://github.com/japaric/mfrc522/blob/master/src/lib.rs
//another example: https://github.com/JohnDoneth/hd44780-driver/blob/master/examples/raspberrypi/src/main.rs
//#![no_std] //FIXME TODO remove all std lib dependencies
extern crate embedded_hal as hal;
#[macro_use]
extern crate bitfl... |
fn switch_transceiver_mode(&mut self, new_mode: RadioMode) {
use registers::OpMode;
let old_flag = self.register_flags.mode - OpMode::Mode;
self.register_flags.mode = match new_mode {
RadioMode::Sleep => old_flag | OpMode::Sleep, // Xtal Off
RadioMode::Standby => old_flag | OpMode::Standby, // Xtal On
... | {
if !self.register_flags.mode.contains(registers::OpMode::Sequencer_Off) {
self.register_flags.mode |= registers::OpMode::Sequencer_Off;
self.write_reg(Register::Opmode, self.register_flags.mode.bits());
self.switch_freq()?;
self.register_flags.mode -= registers::OpMode::Sequencer_Off;
self.wr... | identifier_body |
lib.rs | //working off example (spi): https://github.com/japaric/mfrc522/blob/master/src/lib.rs
//another example: https://github.com/JohnDoneth/hd44780-driver/blob/master/examples/raspberrypi/src/main.rs
//#![no_std] //FIXME TODO remove all std lib dependencies
extern crate embedded_hal as hal;
#[macro_use]
extern crate bitfl... | //self.cs.set_high();
//check if the radio responds by seeing if we can change a register
let mut synced = false;
for _attempt in 0..100 {
self.write_reg(Register::Syncvalue1, 0xAA); //170
self.delay.delay_ms(1);
if self.read_reg(Register::Syncvalue1) == 0xAA {
synced = true;
break;
}
}
... | random_line_split | |
http_service_util.rs | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
failure::{bail, Error, ResultExt},
fidl_fuchsia_net_oldhttp::{self as http, HttpServiceProxy},
fuchsia_async as fasync,
fuchsia_syslo... |
#[test]
fn zero_byte_download_triggers_error() {
let test_url = "https://test.example/sample/url";
let url_req = create_url_request(test_url.to_string());
// creating a response with some bytes "downloaded"
let bytes = "".as_bytes();
let (s1, s2) = zx::Socket::create(z... | {
let test_url = "https://test.example/sample/url";
let url_req = create_url_request(test_url.to_string());
// creating a response with some bytes "downloaded"
let bytes = "there are some bytes".as_bytes();
let (s1, s2) = zx::Socket::create(zx::SocketOpts::STREAM).unwrap();
... | identifier_body |
http_service_util.rs | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
failure::{bail, Error, ResultExt},
fidl_fuchsia_net_oldhttp::{self as http, HttpServiceProxy},
fuchsia_async as fasync,
fuchsia_syslo... | (
request: UrlRequest,
mut response: UrlResponse,
) -> Result<IndividualDownload, Error> {
let mut exec = fasync::Executor::new().expect("failed to create an executor");
let (http_service, server) = create_http_service_util();
let mut next_http_service_req = server.into_futur... | trigger_download_with_supplied_response | identifier_name |
http_service_util.rs | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
failure::{bail, Error, ResultExt},
fidl_fuchsia_net_oldhttp::{self as http, HttpServiceProxy},
fuchsia_async as fasync,
fuchsia_syslo... |
// Object to hold results of a single download
#[derive(Default)]
pub struct IndividualDownload {
pub bytes: u64,
pub nanos: u64,
pub goodput_mbps: f64,
}
// TODO (NET-1664): verify checksum on data received
pub async fn fetch_and_discard_url(
http_service: &HttpServiceProxy,
mut url_request: http... | auto_follow_redirects: true,
cache_mode: http::CacheMode::Default,
response_body_mode: http::ResponseBodyMode::Stream,
}
} | random_line_split |
sumtree.rs | // Copyright 2016 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 agreed t... | (node: &NodeData<T>) -> NodeData<T> {
if node.full {
// replaces full internal nodes, leaves and already pruned nodes are full
// as well
NodeData {
full: true,
node: Node::Pruned(node.sum()),
hash: node.hash,
depth: node.depth,
}
} else {
if let Node::... | clone_pruned_recurse | identifier_name |
sumtree.rs | // Copyright 2016 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 agreed t... | TestElem([0, 0, 0, 3]),
TestElem([0, 0, 0, 4]),
TestElem([0, 0, 0, 5]),
TestElem([0, 0, 0, 6]),
TestElem([0, 0, 0, 7]),
TestElem([1, 0, 0, 0]),
];
assert_eq!(tree.root_sum(), None);
assert_eq!(tree.root_sum(), compute_root(elems[0..0].iter()));
assert_eq!(tree.len(), 0);
assert_eq!(tree.con... | TestElem([0, 0, 0, 2]), | random_line_split |
ply.rs | // Copyright 2016 Google Inc.
//
// 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... | {
format: Format,
elements: Vec<Element>,
offset: Vector3<f64>,
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum DataType {
Int8,
Uint8,
Int16,
Uint16,
Int32,
Uint32,
Float32,
Float64,
}
impl DataType {
fn from_str(input: &str) -> Result<Self> {
match input {
... | Header | identifier_name |
ply.rs | // Copyright 2016 Google Inc.
//
// 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... | create_and_return_reading_fn!($assign, $size, 8, LittleEndian::read_f64)
}
}
};
}
// Similar to 'create_and_return_reading_fn', but creates a function that just advances the read
// pointer.
macro_rules! create_skip_fn {
(&mut $size:ident, $num_bytes:expr) => {{
$siz... | }
DataType::Float64 => { | random_line_split |
ply.rs | // Copyright 2016 Google Inc.
//
// 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... |
"end_header" => break,
"comment" => {
if entries.len() == 5 && entries[1] == "offset:" {
let x = entries[2]
.parse::<f64>()
.chain_err(|| InvalidInput(format!("Invalid offset: {}", entries[2])))?;
... | {
if current_element.is_none() {
return Err(
InvalidInput(format!("property outside of element: {}", line)).into(),
);
};
let property = match entries[1] {
"list" if entries.len() == 5 => ... | conditional_block |
CO542_project.py | # -*- coding: utf-8 -*-
"""proj.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1HZAHtZ5EyfBGqT_9kt3rIWTo1YS9iYpg
"""
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
# import k... |
print(" ")
images = np.array(images)
classNo = np.array(classNo)
############################### Split Data
X_train, X_test, y_train, y_test = train_test_split(images, classNo, test_size=testRatio)
X_train, X_validation, y_train, y_validation = train_test_split(X_train, y_train, test_size=validationRatio)
# X_train... | myPicList = os.listdir(path+"/"+str(count))
for y in myPicList:
curImg = cv2.imread(path+"/"+str(count)+"/"+y)
images.append(curImg)
classNo.append(count)
print(count, end =" ")
count +=1 | conditional_block |
CO542_project.py | # -*- coding: utf-8 -*-
"""proj.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1HZAHtZ5EyfBGqT_9kt3rIWTo1YS9iYpg
"""
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
# import k... | (img):
img =cv2.equalizeHist(img)
return img
def preprocessing(img):
img = grayscale(img)
img = equalize(img)
img = img/255
return img
import cv2
import matplotlib.pyplot as plt
import numpy as np
testImgPath = r'Test/006.jpeg'
imgOrignal = cv2.imread(testImgPath)
# cv2.imshow("Processed Image"... | equalize | identifier_name |
CO542_project.py | # -*- coding: utf-8 -*-
"""proj.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1HZAHtZ5EyfBGqT_9kt3rIWTo1YS9iYpg
"""
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
# import k... | model.add((Conv2D(no_Of_Filters // 2, size_of_Filter2, activation='relu')))
model.add(MaxPooling2D(pool_size=size_of_pool))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(no_Of_Nodes,activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(noOfClasses,activation='softmax')... | model.add((Conv2D(no_Of_Filters//2, size_of_Filter2,activation='relu'))) | random_line_split |
CO542_project.py | # -*- coding: utf-8 -*-
"""proj.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1HZAHtZ5EyfBGqT_9kt3rIWTo1YS9iYpg
"""
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
# import k... |
def equalize(img):
img =cv2.equalizeHist(img)
return img
def preprocessing(img):
img = grayscale(img) # CONVERT TO GRAYSCALE
img = equalize(img) # STANDARDIZE THE LIGHTING IN AN IMAGE
img = img/255 # TO NORMALIZE VALUES BETWEEN 0 AND 1 INSTEAD OF 0 TO 255
return img
X_trai... | img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
return img | identifier_body |
proxyws.go | package proxy
import (
"crypto/tls"
"errors"
"github.com/gorilla/websocket"
"github.com/nothollyhigh/kiss/log"
knet "github.com/nothollyhigh/kiss/net"
"github.com/nothollyhigh/kiss/util"
"github.com/tomasen/realip"
"go_gate/config"
"net"
"net/http"
"sync/atomic"
"time"
)
var (
DefaultSocketOpt = &knet.S... | }
nwrite = len(message)
clientRecv += int64(nwrite)
ConnMgr.UpdateClientInSize(int64(nwrite))
if err = serverConn.SetWriteDeadline(time.Now().Add(pws.SendBlockTime)); err != nil {
log.Info("Session(%s -> %s, TLS: %v) Closed, Client SetWriteDeadline Err: %s",
wsaddr, line.Remote, pws.EnableTls,... | wsaddr, line.Remote, pws.EnableTls, err.Error())
break
}
util.Go(s2c) | random_line_split |
proxyws.go | package proxy
import (
"crypto/tls"
"errors"
"github.com/gorilla/websocket"
"github.com/nothollyhigh/kiss/log"
knet "github.com/nothollyhigh/kiss/net"
"github.com/nothollyhigh/kiss/util"
"github.com/tomasen/realip"
"go_gate/config"
"net"
"net/http"
"sync/atomic"
"time"
)
var (
DefaultSocketOpt = &knet.S... | ,
SendBufLen: DEFAULT_TCP_WRITE_BUF_LEN,
linelay: DEFAULT_TCP_NODELAY,
Certs: certs,
Routes: map[string]func(w http.ResponseWriter, r *http.Request){},
RealIpMode: realIpModel,
ProxyBase: &ProxyBase{
name: name,
ptype: PT_WEBSOCKET,
local: local,
lines: []*Line{},
}... | identifier_body | |
proxyws.go | package proxy
import (
"crypto/tls"
"errors"
"github.com/gorilla/websocket"
"github.com/nothollyhigh/kiss/log"
knet "github.com/nothollyhigh/kiss/net"
"github.com/nothollyhigh/kiss/util"
"github.com/tomasen/realip"
"go_gate/config"
"net"
"net/http"
"sync/atomic"
"time"
)
var (
DefaultSocketOpt = &knet.S... | etWriteDeadline Err: %s",
wsaddr, line.Remote, pws.EnableTls, err.Error())
break
}
err = serverConn.WriteMessage(websocket.BinaryMessage, message)
if err != nil {
log.Info("Session(%s -> %s, TLS: %v) Closed, Client Write len:%v Err: %s ",
wsaddr, line.Remote, pws.EnableTls, nwrite, err.Error(... | f pws.EnableTls {
dialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
addr = "wss://" + line.Remote
}
serverConn, _, err = dialer.Dial(addr, nil)
if err != nil {
log.Info("Session(%s -> %s, TLS: %v) DialTCP Err: %s",
wsaddr, line.Remote, pws.EnableTls, err.Error())
wsCo... | conditional_block |
proxyws.go | package proxy
import (
"crypto/tls"
"errors"
"github.com/gorilla/websocket"
"github.com/nothollyhigh/kiss/log"
knet "github.com/nothollyhigh/kiss/net"
"github.com/nothollyhigh/kiss/util"
"github.com/tomasen/realip"
"go_gate/config"
"net"
"net/http"
"sync/atomic"
"time"
)
var (
DefaultSocketOpt = &knet.S... | ttp.ResponseWriter, r *http.Request) {
defer util.HandlePanic()
atomic.AddUint64(&(pws.ConnCount), 1)
var (
serverConn *websocket.Conn
//tcpAddr *net.TCPAddr
wsaddr = r.RemoteAddr
)
//获取客户端的serverID 从http.head的Sec-Websocket-Protocol字段中获取,是与客户端商定的
whead := w.Header()
serverID := r.Header.Get("Sec-Web... | w(w h | identifier_name |
MAIN PROGRAMME.py | '''
27/09/2017
This program is designed to help me speed up my US stock trading research by
automating web searches through web scraping methods.
It asks for a US stock ticker and returns the stock's chart (in different time
frames), key financials, recent SEC quarterly/yearly reports and
the three most recent ne... | (self): #, chart_type='yearly'):
''' gets the chart: currently: daily chart from bigcharts
to do: specify which chart we want '''
ticker = str(self.ticker.get()).upper()
urls = {'yearly': 'http://bigcharts.marketwatch.com/quickchart/quickchart.asp?symb=' + ticker + '&insttype=&freq=&show=',
'1 Month': 'http:... | get_chart | identifier_name |
MAIN PROGRAMME.py | '''
27/09/2017
This program is designed to help me speed up my US stock trading research by
automating web searches through web scraping methods.
It asks for a US stock ticker and returns the stock's chart (in different time
frames), key financials, recent SEC quarterly/yearly reports and
the three most recent ne... |
def callback4_1(self, x):
''' creates hyperlink for press releases '''
ticker = str(self.ticker.get()).upper()
webbrowser.open_new(self.press[1][1])
def callback4_2(self, x):
''' creates hyperlink for press releases '''
ticker = str(self.ticker.get()).upper()
webbrowser.open_new(self.press[2][1])
def... | ''' creates hyperlink for press releases '''
ticker = str(self.ticker.get()).upper()
webbrowser.open_new(self.press[0][1]) | identifier_body |
MAIN PROGRAMME.py | '''
27/09/2017
This program is designed to help me speed up my US stock trading research by
automating web searches through web scraping methods.
It asks for a US stock ticker and returns the stock's chart (in different time
frames), key financials, recent SEC quarterly/yearly reports and
the three most recent ne... |
else:
n = ('{:.1f}K'.format(int(number)/1000))
except ValueError:
n = 'N/A'
return n
def two_decimals(self, number):
''' takes a float and formats it to only two decimals '''
return ('{:.2f}'.format(float(number)))
def display_yahoo(self):
''' opens the yahoo information, also closes the old ... | n = ('{:.1f}M'.format(int(number)/1000000)) | conditional_block |
MAIN PROGRAMME.py | '''
27/09/2017
This program is designed to help me speed up my US stock trading research by
automating web searches through web scraping methods.
It asks for a US stock ticker and returns the stock's chart (in different time
frames), key financials, recent SEC quarterly/yearly reports and
the three most recent ne... | self.label_2.grid(row=3, column=0, sticky = W)
self.label_3 = Label(self.root, text=self.volume)
self.label_3.grid(row=4, column=0, sticky = W)
self.label_4 = Label(self.root, text=self.high_52)
self.label_4.grid(row=5, column=0, sticky = W)
self.label_6 = Label(self.root, text=self.low_52)
self.label_6.g... | self.label_2 =Label(self.root, text=self.change) | random_line_split |
types.go | package gen
import (
"context"
"fmt"
"time"
"github.com/ergo-services/ergo/etf"
)
// EnvKey
type EnvKey string
// Process
type Process interface {
Core
// Spawn create a new process with parent
Spawn(name string, opts ProcessOptions, object ProcessBehavior, args ...etf.Term) (Process, error)
// RemoteSpaw... | (message etf.Term) (MessageDown, bool) {
var md MessageDown
switch m := message.(type) {
case MessageDown:
return m, true
}
return md, false
}
// IsMessageExit
func IsMessageExit(message etf.Term) (MessageExit, bool) {
var me MessageExit
switch m := message.(type) {
case MessageExit:
return m, true
}
ret... | IsMessageDown | identifier_name |
types.go | package gen
import (
"context"
"fmt"
"time"
"github.com/ergo-services/ergo/etf"
)
// EnvKey
type EnvKey string
// Process
type Process interface {
Core
// Spawn create a new process with parent
Spawn(name string, opts ProcessOptions, object ProcessBehavior, args ...etf.Term) (Process, error)
// RemoteSpaw... |
// IsMessageExit
func IsMessageExit(message etf.Term) (MessageExit, bool) {
var me MessageExit
switch m := message.(type) {
case MessageExit:
return m, true
}
return me, false
}
// IsMessageProxyDown
func IsMessageProxyDown(message etf.Term) (MessageProxyDown, bool) {
var mpd MessageProxyDown
switch m := me... | {
var md MessageDown
switch m := message.(type) {
case MessageDown:
return m, true
}
return md, false
} | identifier_body |
types.go | package gen
import (
"context"
"fmt"
"time"
"github.com/ergo-services/ergo/etf"
)
// EnvKey
type EnvKey string
// Process
type Process interface {
Core
// Spawn create a new process with parent
Spawn(name string, opts ProcessOptions, object ProcessBehavior, args ...etf.Term) (Process, error)
// RemoteSpaw... | From etf.Pid
Message interface{}
}
// ProcessDirectMessage
type ProcessDirectMessage struct {
Ref etf.Ref
Message interface{}
Err error
}
// ProcessGracefulExitRequest
type ProcessGracefulExitRequest struct {
From etf.Pid
Reason string
}
// ProcessState
type ProcessState struct {
Process
State ... | // ProcessMailboxMessage
type ProcessMailboxMessage struct { | random_line_split |
ai.py | from joueur.base_ai import BaseAI
from math import inf
from timeit import default_timer as timer
from collections import namedtuple, defaultdict
from itertools import count
from random import getrandbits
from operator import xor
import re
'''
This board representation is based off the Sunfish Python Chess Engine
Seve... |
def rotate(self):
# Rotates the board, preserving enpassant
# Allows logic to be reused, as only one board configuration must be considered
return Position(
self.board[::-1].swapcase(), -self.score, self.bc, self.wc,
119 - self.ep if self.ep else 0,
119 ... | for j in count(i + d, d):
# j - final position index
# q - occupying piece code
q = self.board[j]
# Stay inside the board, and off friendly pieces
if q.isspace() or q.isupper(): break
# Pawn move, dou... | conditional_block |
ai.py | from joueur.base_ai import BaseAI
from math import inf
from timeit import default_timer as timer
from collections import namedtuple, defaultdict
from itertools import count
from random import getrandbits
from operator import xor
import re
'''
This board representation is based off the Sunfish Python Chess Engine
Seve... | (board, alpha=(-inf), beta=(inf)):
if board.depth >= l_depth:
return board.value()
best_score = -inf
for move in board.gen_moves():
next_board = board.move(move)
if next_board.is_check(): continue
if next_board.is_quiesc... | max_play | identifier_name |
ai.py | from joueur.base_ai import BaseAI
from math import inf
from timeit import default_timer as timer
from collections import namedtuple, defaultdict
from itertools import count
from random import getrandbits
from operator import xor
import re
'''
This board representation is based off the Sunfish Python Chess Engine
Seve... | file_names = ["a", "b", "c", "d", "e", "f", "g", "h"]
return file_names[(square_index % 10) - 1]
def square_rank(square_index):
return 10 - (square_index // 10)
def square_san(square_index):
# convert square index (21 - 98) to Standard Algebraic Notation
square = namedtuple('square', 'file rank'... | return A1 + file_index - (10 * rank_index)
def square_file(square_index): | random_line_split |
ai.py | from joueur.base_ai import BaseAI
from math import inf
from timeit import default_timer as timer
from collections import namedtuple, defaultdict
from itertools import count
from random import getrandbits
from operator import xor
import re
'''
This board representation is based off the Sunfish Python Chess Engine
Seve... |
def run_turn(self):
""" This is called every time it is this AI.player's turn.
Returns:
bool: Represents if you want to end your turn. True means end your
turn, False means to keep your turn going and re-call this
function.
"""
# He... | """ This is called when the game ends, you can clean up your data and
dump files here if need be.
Args:
won (bool): True means you won, False means you lost.
reason (str): The human readable string explaining why you won or
lost.
"""
pas... | identifier_body |
helper.py | import ipaddress
import getpass
import hashlib
import json
import logging
import os
import re
import requests
import sys
import time
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib3.exceptions import InsecureRequestWarning
def get_user_response(message=''):
|
def create_dir(directory):
"""
create directory recursively
"""
try:
os.makedirs(directory)
logging.info('successfully created directory {}'.format(directory))
except OSError:
logging.error('creating directory {} failed'.format(directory))
def check_path(path, isfi... | """
User response invoked when error exists
"""
valid_responses = ['y', 'NO']
response = ''
while response not in valid_responses:
logging.error('{}'.format(message))
response = input('Do you want to continue (y/NO): ')
if response not in valid_responses:
logging... | identifier_body |
helper.py | import ipaddress
import getpass
import hashlib
import json
import logging
import os
import re
import requests
import sys
import time
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib3.exceptions import InsecureRequestWarning
def get_user_response(message=''):
"""
User response... |
return ip
def validate_file(directory, filename, url):
re_hash = ''
hash_value = False
logging.info('validating file {} in {}'.format(filename, directory))
with open('{}/{}'.format(directory, filename), 'rb') as f:
bytes = f.read()
re_hash = hashlib.sha256(bytes).hexdigest()
... | ip = input('ip address for {} in {} node: '.format(ip_type, node_name))
ip_check = validate_ip(ip)
if ip_check:
break
else:
logging.warn('ip address should be in format: x.x.x.x') | conditional_block |
helper.py | import ipaddress
import getpass
import hashlib
import json
import logging
import os
import re
import requests
import sys
import time
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib3.exceptions import InsecureRequestWarning
def get_user_response(message=''):
"""
User response... | logging.error('creating directory {} failed'.format(directory))
def check_path(path, isfile=False, isdir=False):
"""
returns if path given is a file or directory
"""
return os.path.isfile(path) if isfile else os.path.isdir(path)
def set_values(user_input, default, check=''):
"""
... | except OSError: | random_line_split |
helper.py | import ipaddress
import getpass
import hashlib
import json
import logging
import os
import re
import requests
import sys
import time
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib3.exceptions import InsecureRequestWarning
def get_user_response(message=''):
"""
User response... | (selected_network_device, base_api_url, user, passwd):
"""
get mac address for a selected network device
"""
url = '{}/{}'.format(base_api_url, selected_network_device)
device_mac_address = ''
try:
response = requests.get(url, verify=False, auth=(user, passwd),
... | get_mac_address | identifier_name |
main.rs | use anyhow::{anyhow, Context, Result};
use std::cmp::max;
use std::io::BufRead;
use wayland_client::protocol::{
wl_compositor::WlCompositor,
wl_pointer,
wl_seat::{self, WlSeat},
wl_shm::{self, WlShm},
wl_surface::WlSurface,
};
use wayland_client::EventQueue;
use wayland_client::{self, Display, Filte... |
}
mod pixbuf {
use super::Data;
use anyhow::{Context, Result};
use wayland_client::protocol::{
wl_buffer::{self, WlBuffer},
wl_shm::{self, WlShm},
};
use wayland_client::{Filter, Main};
#[derive(Debug)]
pub struct ShmPixelBuffer {
pub wl: Main<WlBuffer>,
pu... | {
if self.buffer.locked {
return;
}
let shm = &mut self.buffer;
let (bw, bh) = self.cfg.button_dim;
let focus = {
let cfg = &self.cfg;
(self.ptr.btn)
.filter(|s| s == &wl_pointer::ButtonState::Pressed)
.and(self... | identifier_body |
main.rs | use anyhow::{anyhow, Context, Result};
use std::cmp::max;
use std::io::BufRead;
use wayland_client::protocol::{
wl_compositor::WlCompositor,
wl_pointer,
wl_seat::{self, WlSeat},
wl_shm::{self, WlShm},
wl_surface::WlSurface,
};
use wayland_client::EventQueue;
use wayland_client::{self, Display, Filte... |
Surface {
wl,
layer,
committed: false,
configured: false,
}
}
fn render(&mut self) {
if self.buffer.locked {
return;
}
let shm = &mut self.buffer;
let (bw, bh) = self.cfg.button_dim;
let focus ... | random_line_split | |
main.rs | use anyhow::{anyhow, Context, Result};
use std::cmp::max;
use std::io::BufRead;
use wayland_client::protocol::{
wl_compositor::WlCompositor,
wl_pointer,
wl_seat::{self, WlSeat},
wl_shm::{self, WlShm},
wl_surface::WlSurface,
};
use wayland_client::EventQueue;
use wayland_client::{self, Display, Filte... | (pub u32);
static ARGB_FORMAT_MSG: &str =
"Argb must be specified by a '#' followed by exactly 3, 4, 6, or 8 digits";
impl FromStr for Argb {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self> {
if !s.starts_with('#') || !s[1..].chars().all(|c| c.is_ascii_hexdig... | Argb | identifier_name |
lib.rs | #![cfg_attr(feature = "nightly", feature(const_panic))]
extern crate proc_macro;
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::parse_macro_input;
use syn::Item;
/// Generate B1, B2, .., B64 with implementation of the Specifier trait
#[proc_macro]
pub fn generate_bit_specifiers(_input: pro... |
}
None
});
let getters_setters = define_getters_setters(&s.fields);
// Total size calculated as the sum of the inner `<T as Specifier>::BITS` associated consts
let total_bit_size = quote!(0 #(+ <#fields_ty as Specifier>::BITS)... | {
// At this point `attr.tokens` is the following part of the attribute:
// #[bits=..]
// ^^^
let bits = syn::parse2::<BitAttribute>(attr.tokens.clone()).ok()?.bits;
return S... | conditional_block |
lib.rs | #![cfg_attr(feature = "nightly", feature(const_panic))]
extern crate proc_macro;
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::parse_macro_input;
use syn::Item;
/// Generate B1, B2, .., B64 with implementation of the Specifier trait
#[proc_macro]
pub fn generate_bit_specifiers(_input: pro... |
// Check that fields with #[bits=X] attribute have a type of size `X`
// We use an array size check to validate the size is correct
let bits_attrs_check = s
.fields
.iter()
.filter_map(|field| {
let ty = &field.ty;
... | random_line_split | |
lib.rs | #![cfg_attr(feature = "nightly", feature(const_panic))]
extern crate proc_macro;
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::parse_macro_input;
use syn::Item;
/// Generate B1, B2, .., B64 with implementation of the Specifier trait
#[proc_macro]
pub fn generate_bit_specifiers(_input: pro... | () -> TokenStream {
quote!(
#[doc = "Simple trait to extract bits from primitive integer type"]
trait BitOps {
fn first(self, n: usize) -> u8;
fn last(self, n: usize) -> u8;
fn mid(self, start: usize, len: usize) -> u8;
}
#[doc = "Ops to extract b... | bit_ops_impl | identifier_name |
lib.rs | #![cfg_attr(feature = "nightly", feature(const_panic))]
extern crate proc_macro;
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::parse_macro_input;
use syn::Item;
/// Generate B1, B2, .., B64 with implementation of the Specifier trait
#[proc_macro]
pub fn generate_bit_specifiers(_input: pro... |
fn define_getters_setters(fields: &syn::Fields) -> TokenStream {
let getters = fields.iter().scan(quote!(0), |offset, field| {
let ident = field.ident.as_ref().expect("Namef field");
// get_[field name] and set_[field name] idents
let get_ident = quote::format_ident!("get_{}", ident);
... | {
let _ = args;
let item = parse_macro_input!(input as syn::Item);
match item {
Item::Struct(s) => {
let ident = &s.ident;
let fields_ty = s.fields.iter().map(|field| &field.ty);
// Check that fields with #[bits=X] attribute have a type of size `X`
/... | identifier_body |
signalStream.js | 'use strict';
const coreUtils = require('./coreUtils');
const coreEvents = require('./coreEvents');
const globalObject = require('./globalObject');
const nodeObjects = require('./nodeObjects');
const signaling = require('./signaling');
const signalStreamModule = {};
let clientId;
coreEvents.addEventListener('populate... |
const wantToStreamCallbacks = new Map();
const wantToListenCallbacks = new Map();
const webrtcClients = new Map();
function WebRTCClient(ownId, recipientId, clientRecipientId, node, { listener, streamer }) {
let active = false, peerConnection, onRemoteStreamCallback, onConnectCallback, onCloseCallback;
const star... | {
const node = coreUtils.getElementByWid(wid);
if (message.requestForStreams) {
Array.from(wantToStreamCallbacks.get(wid).keys()).forEach(ownId => {
node.webstrate.signal({
__internal_webrtc: true,
wantToStream: true,
senderId: ownId,
recipientId: message.senderId
}, senderClientId);
});
... | identifier_body |
signalStream.js | 'use strict';
const coreUtils = require('./coreUtils');
const coreEvents = require('./coreEvents');
const globalObject = require('./globalObject');
const nodeObjects = require('./nodeObjects');
const signaling = require('./signaling');
const signalStreamModule = {};
let clientId;
coreEvents.addEventListener('populate... | (wid, senderClientId, message) {
const node = coreUtils.getElementByWid(wid);
if (message.requestForStreams) {
Array.from(wantToStreamCallbacks.get(wid).keys()).forEach(ownId => {
node.webstrate.signal({
__internal_webrtc: true,
wantToStream: true,
senderId: ownId,
recipientId: message.senderId
... | handleSignal | identifier_name |
signalStream.js | 'use strict';
const coreUtils = require('./coreUtils');
const coreEvents = require('./coreEvents');
const globalObject = require('./globalObject');
const nodeObjects = require('./nodeObjects');
const signaling = require('./signaling');
const signalStreamModule = {};
let clientId;
coreEvents.addEventListener('populate... |
const ownId = coreUtils.randomString();
wantToListenCallbacks.get(wid).set(ownId, callback);
node.webstrate.signal({
__internal_webrtc: true,
requestForStreams: true,
senderId: ownId
});
},
removeListener: (callback) => {
// Find the ownId that was generated when adding this callback.
... | {
signaling.subscribe(wid);
} | conditional_block |
signalStream.js | 'use strict';
const coreUtils = require('./coreUtils');
const coreEvents = require('./coreEvents');
const globalObject = require('./globalObject');
const nodeObjects = require('./nodeObjects');
const signaling = require('./signaling');
const signalStreamModule = {};
let clientId;
coreEvents.addEventListener('populate... | if(event.candidate != null) {
node.webstrate.signal({
ice: event.candidate,
__internal_webrtc: true,
senderId: ownId,
recipientId
}, clientRecipientId);
}
};
const gotStateChange = event => {
switch (peerConnection.iceConnectionState) {
case 'connected':
onConnectCallback && onConn... | };
const gotIceCandidate = (event) => { | random_line_split |
gfsworkflow.py | import logging
import shutil
import sys
import datetime
import os
import netCDF4
import numpy
import pandas as pd
import rasterio
import rasterstats
import requests
import xarray
from rasterio.enums import Resampling
FFGS_REGIONS = [('Hispaniola', 'hispaniola'), ('Central America', 'centralamerica')]
def setenviron... |
return False
logging.info('Finished Downloads')
return True
def gfs_tiffs(threddspath, wrksppath, timestamp, region, model):
"""
Script to combine 6-hr accumulation grib files into 24-hr accumulation geotiffs.
Dependencies: datetime, os, numpy, rasterio
"""
logging.info('\nSta... | logging.info('Probably a problem with the URL. Check the log and try the link') | conditional_block |
gfsworkflow.py | import logging
import shutil
import sys
import datetime
import os
import netCDF4
import numpy
import pandas as pd
import rasterio
import rasterstats
import requests
import xarray
from rasterio.enums import Resampling
FFGS_REGIONS = [('Hispaniola', 'hispaniola'), ('Central America', 'centralamerica')]
def setenviron... | fc_date = datetime.datetime.strptime(timestamp, "%Y%m%d%H").strftime("%Y%m%d")
# This is the List of forecast timesteps for 5 days (6-hr increments). download them all
fc_steps = ['006', '012', '018', '024', '030', '036', '042', '048', '054', '060', '066', '072', '078', '084',
'090', '096',... | time = datetime.datetime.strptime(timestamp, "%Y%m%d%H").strftime("%H") | random_line_split |
gfsworkflow.py | import logging
import shutil
import sys
import datetime
import os
import netCDF4
import numpy
import pandas as pd
import rasterio
import rasterstats
import requests
import xarray
from rasterio.enums import Resampling
FFGS_REGIONS = [('Hispaniola', 'hispaniola'), ('Central America', 'centralamerica')]
def setenviron... | (threddspath, timestamp, region, model):
"""
Description: Intended to make a THREDDS data server compatible netcdf file out of an incorrectly structured
netcdf file.
Author: Riley Hales, 2019
Dependencies: netCDF4, os, datetime
see github/rileyhales/datatools for more details
"""
log... | nc_georeference | identifier_name |
gfsworkflow.py | import logging
import shutil
import sys
import datetime
import os
import netCDF4
import numpy
import pandas as pd
import rasterio
import rasterstats
import requests
import xarray
from rasterio.enums import Resampling
FFGS_REGIONS = [('Hispaniola', 'hispaniola'), ('Central America', 'centralamerica')]
def setenviron... |
def cleanup(threddspath, timestamp, region, model):
# delete anything that isn't the new folder of data (named for the timestamp) or the new wms.ncml file
logging.info('Getting rid of old ' + model + ' data folders')
path = os.path.join(threddspath, region, model)
files = os.listdir(path)
files.r... | logging.info('\nGenerating a new color scale csv for the ' + model + ' results')
colorscales = os.path.join(wrksppath, region, model + 'colorscales.csv')
results = os.path.join(wrksppath, region, model + 'results.csv')
logging.info(results)
answers = pd.DataFrame(columns=['cat_id', 'cum_mean', 'mean', '... | identifier_body |
frontend.rs | //! General algorithms for frontends.
//!
//! The frontend is concerned with executing the abstract behaviours given by the backend in terms
//! of the actions of the frontend types. This means translating Redirect errors to the correct
//! Redirect http response for example or optionally sending internal errors to log... | pub enum Authentication {
Failed,
InProgress,
Authenticated(String),
}
struct AccessTokenParameter<'a> {
valid: bool,
client_id: Option<Cow<'a, str>>,
redirect_url: Option<Cow<'a, str>>,
grant_type: Option<Cow<'a, str>>,
code: Option<Cow<'a, str>>,
authorization: Option<(String, Vec... | #[derive(Clone)] | random_line_split |
frontend.rs | //! General algorithms for frontends.
//!
//! The frontend is concerned with executing the abstract behaviours given by the backend in terms
//! of the actions of the frontend types. This means translating Redirect errors to the correct
//! Redirect http response for example or optionally sending internal errors to log... |
}
impl<'s> AuthorizationParameter<'s> {
fn invalid() -> Self {
AuthorizationParameter { valid: false, method: None, client_id: None, scope: None,
redirect_url: None, state: None }
}
}
impl AuthorizationFlow {
/// Idempotent data processing, checks formats.
pub fn prepare<W: WebReq... | { self.method.as_ref().map(|c| c.as_ref().into()) } | identifier_body |
frontend.rs | //! General algorithms for frontends.
//!
//! The frontend is concerned with executing the abstract behaviours given by the backend in terms
//! of the actions of the frontend types. This means translating Redirect errors to the correct
//! Redirect http response for example or optionally sending internal errors to log... | <'l, Req> where
Req: WebRequest + 'l,
{
request: &'l mut Req,
urldecoded: AuthorizationParameter<'l>,
}
fn extract_parameters(params: HashMap<String, Vec<String>>) -> AuthorizationParameter<'static> {
let map = params.iter()
.filter(|&(_, v)| v.len() == 1)
.map(|(k, v)| (k.as_str(), v[0... | PreparedAuthorization | identifier_name |
wx.py | import logging
import re
import sys
from glob import glob
from os import path
from pprint import pprint
from lepl import *
from lxml.etree import Element, tostring
#logging.basicConfig(level=logging.DEBUG)
proper_header = """<Ui xmlns="http://www.blizzard.com/wow/ui" xmlns:xsi="http://www.w3.org/2001/XMLSchema-insta... | (source):
assignments = {}
ui = Element('Ui')
for element in parser(source):
if isinstance(element, dict):
assignments.update(element)
else:
ui.append(construct_element(*element))
xml = tostring(ui, pretty_print=True)
xml = script_pattern.sub(_format_script, ... | construct | identifier_name |
wx.py | import logging
import re
import sys
from glob import glob
from os import path
from pprint import pprint
from lepl import *
from lxml.etree import Element, tostring
#logging.basicConfig(level=logging.DEBUG)
proper_header = """<Ui xmlns="http://www.blizzard.com/wow/ui" xmlns:xsi="http://www.w3.org/2001/XMLSchema-insta... | parse(source_file, xmlfile)
def process_files(source_dir, target_dir):
for candidate in glob(path.join(source_dir, '*.wx')):
process_file(candidate, target_dir)
if __name__ == '__main__':
if len(sys.argv) == 3:
source, target = sys.argv[1], sys.argv[2]
if source.endswith('.wx'):
... | xmlfile = path.join(target_dir, path.basename(source_file).replace('.wx', '.xml')) | random_line_split |
wx.py | import logging
import re
import sys
from glob import glob
from os import path
from pprint import pprint
from lepl import *
from lxml.etree import Element, tostring
#logging.basicConfig(level=logging.DEBUG)
proper_header = """<Ui xmlns="http://www.blizzard.com/wow/ui" xmlns:xsi="http://www.w3.org/2001/XMLSchema-insta... |
lines[-1] = indent + lines[-1]
return '\n'.join(lines)
def construct(source):
assignments = {}
ui = Element('Ui')
for element in parser(source):
if isinstance(element, dict):
assignments.update(element)
else:
ui.append(construct_element(*element))
xml =... | lines[i] = indent + ' ' + lines[i] | conditional_block |
wx.py | import logging
import re
import sys
from glob import glob
from os import path
from pprint import pprint
from lepl import *
from lxml.etree import Element, tostring
#logging.basicConfig(level=logging.DEBUG)
proper_header = """<Ui xmlns="http://www.blizzard.com/wow/ui" xmlns:xsi="http://www.w3.org/2001/XMLSchema-insta... |
candidates = flag | keyvalue | parent | parentkey | token | value
arguments = ~Token('\(') & Extend(candidates[:, comma]) & ~Token('\)') > _parse_arguments
declaration = token[1:] & arguments[0:1]
assignment_line = Line(Token('%[A-Za-z]+') & ~Token('=') & value) > (lambda v: {v[0]: v[1]})
blank_line = ~Line(Empty(),... | offset = 1
if tokens[0][1] == ' ':
offset = 2
return '\n'.join([token[offset:] for token in tokens]) | identifier_body |
writer.go | package loggo
import (
"compress/gzip"
"fmt"
"github.com/robfig/cron"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
const (
printTimeFormat = "2006-01-02 15:04:05.000"
backupTimeFormat = "2006-01-02T15-04-05.000"
compressSuffix = ".gz"
defaultLogName = "./log/default.l... | () error {
l.mu.Lock()
defer l.mu.Unlock()
return l.close()
}
// rotate
func (l *FileWriter) startRotateCron() {
c := cron.New()
c.AddFunc(l.RotateCron, func() {
if l.rotateRunning {
return
}
l.rotateRunning = true
if err := l.Rotate(); err != nil {
}
l.rotateRunning = false
})
c.Start()
}
// cl... | Close | identifier_name |
writer.go | package loggo
import (
"compress/gzip"
"fmt"
"github.com/robfig/cron"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
const (
printTimeFormat = "2006-01-02 15:04:05.000"
backupTimeFormat = "2006-01-02T15-04-05.000"
compressSuffix = ".gz"
defaultLogName = "./log/default.l... | }
if err != nil {
return fmt.Errorf("error getting log file info: %s", err)
}
file, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
// if we fail to open the old log file for some reason, just ignore
// it and open a new log file.
return l.openNew()
}
l.file = file
l.size = ... |
filename := l.filename()
info, err := os_Stat(filename)
if os.IsNotExist(err) {
return l.openNew() | random_line_split |
writer.go | package loggo
import (
"compress/gzip"
"fmt"
"github.com/robfig/cron"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
const (
printTimeFormat = "2006-01-02 15:04:05.000"
backupTimeFormat = "2006-01-02T15-04-05.000"
compressSuffix = ".gz"
defaultLogName = "./log/default.l... |
// prefixAndExt returns the filename part and extension part from the FileWriter's
// filename.
func (l *FileWriter) prefixAndExt() (prefix, ext string) {
filename := filepath.Base(l.filename())
ext = filepath.Ext(filename)
prefix = filename[:len(filename)-len(ext)] + "-"
return prefix, ext
}
// compressLogFile ... | {
return filepath.Dir(l.filename())
} | identifier_body |
writer.go | package loggo
import (
"compress/gzip"
"fmt"
"github.com/robfig/cron"
"io"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
)
const (
printTimeFormat = "2006-01-02 15:04:05.000"
backupTimeFormat = "2006-01-02T15-04-05.000"
compressSuffix = ".gz"
defaultLogName = "./log/default.l... |
l.rotateRunning = false
})
c.Start()
}
// close closes the file if it is open.
func (l *FileWriter) close() error {
if l.file == nil {
return nil
}
err := l.file.Close()
l.file = nil
return err
}
// Rotate causes FileWriter to close the existing log file and immediately create a
// new one. This is a hel... | {
} | conditional_block |
converter.go | package api
import (
"fmt"
"os"
"regexp"
"strings"
"github.com/hashicorp/nomad/plugins/drivers"
)
const (
CPUModeHostModel = "host-model"
CPUModeHostPassthrough = "host-passthrough"
DefaultBridgeName = "default"
DefaultNetworkName = "default"
)
func ConvertTaskConfigToDomainSpec(cfg *drivers... |
func setDiskSpec(cfg *DiskConfig, devicePerBus map[string]int) (Disk, error) {
if cfg == nil {
return Disk{}, fmt.Errorf("disk config cannot be nil")
}
disk := Disk{}
switch cfg.Device {
case "disk":
disk.Device = "disk"
disk.Type = cfg.Type
disk.Target.Bus = cfg.TargetBus
disk.Target.Device = makeDev... | {
if cfg.Value < 0 {
return Memory{Unit: "B"}, fmt.Errorf("Memory size '%d' must be greater than or equal to 0", cfg.Value)
}
var memorySize uint64
switch cfg.Unit {
case "gib":
memorySize = cfg.Value * 1024 * 1024 * 1024
case "mib":
memorySize = cfg.Value * 1024 * 1024
case "kib":
memorySize = cfg.Valu... | identifier_body |
converter.go | package api
import (
"fmt"
"os"
"regexp"
"strings"
"github.com/hashicorp/nomad/plugins/drivers"
)
const (
CPUModeHostModel = "host-model"
CPUModeHostPassthrough = "host-passthrough"
DefaultBridgeName = "default"
DefaultNetworkName = "default"
)
func ConvertTaskConfigToDomainSpec(cfg *drivers... |
return nil
}
// SetDefaultsDomainSpec set default values for domain spec that are not set by user
func SetDefaultsDomainSpec(domainSpec *DomainSpec) {
domainSpec.XmlNS = "http://libvirt.org/schemas/domain/qemu/1.0"
if domainSpec.Type == "" {
domainSpec.Type = "kvm"
}
if domainSpec.Clock == nil {
domainSpec.C... | {
return &ReadOnly{}
} | conditional_block |
converter.go | package api
import (
"fmt"
"os"
"regexp"
"strings"
"github.com/hashicorp/nomad/plugins/drivers"
)
const (
CPUModeHostModel = "host-model"
CPUModeHostPassthrough = "host-passthrough"
DefaultBridgeName = "default"
DefaultNetworkName = "default"
)
func ConvertTaskConfigToDomainSpec(cfg *drivers... | (cfg *DiskConfig, devicePerBus map[string]int) (Disk, error) {
if cfg == nil {
return Disk{}, fmt.Errorf("disk config cannot be nil")
}
disk := Disk{}
switch cfg.Device {
case "disk":
disk.Device = "disk"
disk.Type = cfg.Type
disk.Target.Bus = cfg.TargetBus
disk.Target.Device = makeDeviceName(cfg.Target... | setDiskSpec | identifier_name |
converter.go | package api
import (
"fmt"
"os"
"regexp"
"strings"
"github.com/hashicorp/nomad/plugins/drivers"
)
const (
CPUModeHostModel = "host-model"
CPUModeHostPassthrough = "host-passthrough"
DefaultBridgeName = "default"
DefaultNetworkName = "default"
)
func ConvertTaskConfigToDomainSpec(cfg *drivers... | for _, deviceCfg := range taskCfg.HostDevices {
if newHostDevice, err := setHostDeviceSpec(&deviceCfg); err == nil {
domainSpec.Devices.HostDevices = append(domainSpec.Devices.HostDevices, newHostDevice)
} else {
return err
}
}
return nil
}
func setMemorySpec(cfg MemoryConfig) (Memory, error) {
if cfg... | random_line_split | |
router.rs | //! Top-level semantic block verification for Zebra.
//!
//! Verifies blocks using the [`CheckpointVerifier`] or full [`SemanticBlockVerifier`],
//! depending on the config and block height.
//!
//! # Correctness
//!
//! Block and transaction verification requests should be wrapped in a timeout, because:
//! - checkpoi... | <S>(
config: Config,
network: Network,
mut state_service: S,
debug_skip_parameter_preload: bool,
) -> (
Buffer<BoxService<Request, block::Hash, RouterError>, Request>,
Buffer<
BoxService<transaction::Request, transaction::Response, TransactionError>,
transaction::Request,
>,
... | init | identifier_name |
router.rs | //! Top-level semantic block verification for Zebra.
//!
//! Verifies blocks using the [`CheckpointVerifier`] or full [`SemanticBlockVerifier`],
//! depending on the config and block height.
//!
//! # Correctness
//!
//! Block and transaction verification requests should be wrapped in a timeout, because:
//! - checkpoi... | Err(e) => {
#[cfg(not(test))]
tracing::warn!(
"unexpected error: {e:?} in state request while verifying previous \
state checkpoints. Is Zebra shutting down?"
);
... | unreachable!("unexpected response type: {response:?} from state request")
}
| conditional_block |
router.rs | //! Top-level semantic block verification for Zebra.
//!
//! Verifies blocks using the [`CheckpointVerifier`] or full [`SemanticBlockVerifier`],
//! depending on the config and block height.
//!
//! # Correctness
//!
//! Block and transaction verification requests should be wrapped in a timeout, because:
//! - checkpoi... |
// # Consensus
//
// We want to verify all available checkpoints, even if the node is not configured
// to use them for syncing. Zebra's checkpoints are updated with every release,
// which makes sure they include the latest settled network upgrade.
... | tracing::info!("starting state checkpoint validation"); | random_line_split |
javascript.rs | mod expression;
mod pattern;
#[cfg(test)]
mod tests;
use crate::{ast::*, error::GleamExpect, fs::Utf8Writer, line_numbers::LineNumbers, pretty::*};
use itertools::Itertools;
const INDENT: isize = 2;
const DEEP_EQUAL: &str = "
function $equal(x, y) {
let toCheck = [x, y];
while (toCheck) {
let a = toCheck.po... |
fn imported_external_function(
&mut self,
public: bool,
name: &'a str,
module: &'a str,
fun: &'a str,
) -> Document<'a> {
let import = if name == fun {
docvec!["import { ", name, r#" } from ""#, module, r#"";"#]
} else {
docvec![
... | {
if module.is_empty() {
self.global_external_function(public, name, arguments, fun)
} else {
self.imported_external_function(public, name, module, fun)
}
} | identifier_body |
javascript.rs | mod expression;
mod pattern;
#[cfg(test)]
mod tests;
use crate::{ast::*, error::GleamExpect, fs::Utf8Writer, line_numbers::LineNumbers, pretty::*};
use itertools::Itertools;
const INDENT: isize = 2;
const DEEP_EQUAL: &str = "
function $equal(x, y) {
let toCheck = [x, y];
while (toCheck) {
let a = toCheck.po... | <'a>(
items: impl Iterator<Item = (Document<'a>, Option<Document<'a>>)>,
) -> Document<'a> {
let fields = items.map(|(key, value)| match value {
Some(value) => docvec![key, ": ", value,],
None => key.to_doc(),
});
docvec![
docvec![
"{",
break_("", " "),
... | wrap_object | identifier_name |
javascript.rs | mod expression;
mod pattern;
#[cfg(test)]
mod tests;
use crate::{ast::*, error::GleamExpect, fs::Utf8Writer, line_numbers::LineNumbers, pretty::*};
use itertools::Itertools;
const INDENT: isize = 2;
const DEEP_EQUAL: &str = "
function $equal(x, y) {
let toCheck = [x, y];
while (toCheck) {
let a = toCheck.po... | "export function "
} else {
"function "
};
Ok(docvec![
head,
maybe_escape_identifier(name),
fun_args(args),
" {",
docvec![line(), generator.function_body(body)?]
.nest(INDENT)
.gro... | &mut self.object_equality_used,
self.module_scope.clone(),
);
let head = if public { | random_line_split |
benchmarks.rs | use std::time::{Instant, Duration};
use ordered_float::OrderedFloat;
use rand::seq::SliceRandom;
use crate::actions::*;
use crate::simulation::*;
use crate::simulation_state::*;
use crate::start_and_strategy_ai::{Strategy, FastStrategy, CombatResult, play_out, collect_starting_points};
use crate::neural_net_ai::Neural... | let mut fast_genetic: ExplorationOptimizer<FastStrategy, _> = ExplorationOptimizer::new (| candidates: & [CandidateStrategy <FastStrategy>] | {
if candidates.len() < 2 {
FastStrategy::random()
}
else {
FastStrategy::offspring(& candidates.choose_multiple(&mut rand::thread_rng(), 2).map (| cand... | random_line_split | |
benchmarks.rs | use std::time::{Instant, Duration};
use ordered_float::OrderedFloat;
use rand::seq::SliceRandom;
use crate::actions::*;
use crate::simulation::*;
use crate::simulation_state::*;
use crate::start_and_strategy_ai::{Strategy, FastStrategy, CombatResult, play_out, collect_starting_points};
use crate::neural_net_ai::Neural... | <T> {
strategy: T,
playouts: usize,
total_score: f64,
}
fn playout_result(state: & CombatState, strategy: & impl Strategy)->CombatResult {
let mut state = state.clone();
play_out (
&mut Runner::new (&mut state, true, false),
strategy,
);
CombatResult::new (& state)
}
... | CandidateStrategy | identifier_name |
benchmarks.rs | use std::time::{Instant, Duration};
use ordered_float::OrderedFloat;
use rand::seq::SliceRandom;
use crate::actions::*;
use crate::simulation::*;
use crate::simulation_state::*;
use crate::start_and_strategy_ai::{Strategy, FastStrategy, CombatResult, play_out, collect_starting_points};
use crate::neural_net_ai::Neural... | let mut neural_random_only: ExplorationOptimizer<NeuralStrategy, _> = ExplorationOptimizer::new (|_: &[CandidateStrategy <NeuralStrategy>] | NeuralStrategy::new_random(&ghost_state, 16));
let mut neural_training_only = NeuralStrategy::new_random(&ghost_state, 16);
let mut neural_random_training: ExplorationOpt... | stStrategy::offspring(& candidates.choose_multiple(&mut rand::thread_rng(), 2).map (| candidate | & candidate.strategy).collect::<Vec<_>>())
}
});
| conditional_block |
benchmarks.rs | use std::time::{Instant, Duration};
use ordered_float::OrderedFloat;
use rand::seq::SliceRandom;
use crate::actions::*;
use crate::simulation::*;
use crate::simulation_state::*;
use crate::start_and_strategy_ai::{Strategy, FastStrategy, CombatResult, play_out, collect_starting_points};
use crate::neural_net_ai::Neural... | timization_playouts = 1000000;
let test_playouts = 10000;
let ghost_file = std::fs::File::open ("data/hexaghost.json").unwrap();
let ghost_state: CombatState = serde_json::from_reader (std::io::BufReader::new (ghost_file)).unwrap();
let mut fast_random: ExplorationOptimizer<FastStrategy, _> = ExplorationOpti... | identifier_body | |
project-payment-record.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
impo... | on.yemindream.com/mamon/customer/addPayMent';
if (!invoiceData['realPrice'] || !invoiceData['payer'] || !invoiceData['payerBank'] || !invoiceData['payerAccount']) {
this.tipstext = '请填写完整信息';
this.isFailed = true
return;
}
this.tipstext = '确认提交支付信息吗?'
this.isFailed = false
return
... | ata;
// let projectInvoiceDetailUrl = 'http://mam | conditional_block |
project-payment-record.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
impo... | value) {
this.paymentRecordData['payer'] = value.name;
this.paymentRecordData['payerBank'] = value.bankName;
this.paymentRecordData['payerAccount'] = value.account;
} else {
this.paymentRecordData[field] = value;
}
}
getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=(... | ntRecordData, type: 'clientType', cid: cid });
} else {
this.navCtrl.push(FormEditPage, { callback: this.setValue, value: value, field: field, type: type });
}
}
/*设置值(回调函数)*/
// setValue = (field,value)=> {
// this.paymentRecordData[field] = value;
// }
/*设置值(回调函数)*/
setValue = (field,... | identifier_body |
project-payment-record.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
impo... | bj.fileSize / 1048576;
this.filesize = (obj.fileSize / 1048576).toPrecision(3);
this.fileurl = obj.url;
this.paymentRecordData['sourceName'] = this.filetitle
this.paymentRecordData['size'] = this.filesize
this.paymentRecordData['certifiedUrl'] = this.fileurl
this.paymentRecordData['fid'] = obj.f... | // var a = o | identifier_name |
project-payment-record.ts | import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
impo... | // let data = { url: url };
this.http.get(hideAttentionMenuUrl).subscribe(res => {
if (res['code'] == 200) {
wx.config({
debug: false,
appId: res['data'].appid,
timestamp: res['data'].timestamp,
nonceStr: res['data'].nonceStr,
signature: res['data'... | //隐藏底部分享菜单
isAttention() {
// let url = location.href.split('#')[0]; // 当前网页的URL,不包含#及其后面部分 | random_line_split |
odor-finder.py | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import io
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import matplotlib.pyplot as plt
import math
import random
import pickle
from captum.attr i... | df_topk.to_csv(result_file, index=False)
| _topk.loc[0]=['Empty','Empty']
| conditional_block |
odor-finder.py | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import io
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import matplotlib.pyplot as plt
import math
import random
import pickle
from captum.attr i... |
TRAIN_DATA_FILE= getConfig("Task","train_data_file")
apply_data_file= getConfig("Task","apply_data_file")
result_file= getConfig("Task","result_file")
smile_l=int(getConfig("Task","smile_length","75"))
seq_l=int(getConfig("Task","sequence_length","315"))
filename=getConfig("Task","filename")
model_filename = getConfi... | try:
return config[section][attribute]
except:
return default | identifier_body |
odor-finder.py | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import io
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import matplotlib.pyplot as plt
import math
import random
import pickle
from captum.attr i... | eq):
key="ABCDEFGHIJKLMNOPQRSTUVWXYZ^"
seq=seq.upper()
test_list=list(key)
res = {val : idx for idx, val in enumerate(test_list)}
threshold=seq_l
if len(seq)<=threshold:
seq=seq+("^"*(threshold-len(seq)))
else:
seq=seq[0:threshold]
array=[[0 for j in range(len(key))] fo... | e_hot_seq(s | identifier_name |
odor-finder.py | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import io
import sys
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import matplotlib.pyplot as plt
import math
import random
import pickle
from captum.attr i... | sym = c + n
sym = sym.strip()
com = sym.upper()
if com == "BR" or com == "CL" or com == "NA":
i = i + 1
else:
com = c.upper()
sym = c
if com == labels[k]:
color = "0xBBBBBB"
... | if c.upper() not in "CBONSPFIK":
print(mol[i], 0.0, "0xFFFFFF")
else:
if i + 1 < len(mol):
n = mol[i+1] | random_line_split |
record_trace.go | /*
Copyright The Accelerated Container Image 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 ... |
func collectTrace(traceFile string) {
lockFile := traceFile + ".lock"
okFile := traceFile + ".ok"
if err := os.Remove(lockFile); err != nil && !os.IsNotExist(err) {
fmt.Printf("Remove lock file %s failed: %v\n", lockFile, err)
return
}
for {
time.Sleep(time.Second)
if _, err := os.Stat(okFile); err == n... | {
// Allow termination by user signals
sigStop := make(chan bool)
sigChan := registerSignals(ctx, task, sigStop)
select {
case <-sigStop:
timer.Stop()
break
case <-watchStop:
break
case <-timer.C:
fmt.Println("Timeout, stop recording ...")
break
}
signal.Stop(sigChan)
close(sigChan)
st, err := t... | identifier_body |
record_trace.go | /*
Copyright The Accelerated Container Image 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 ... | // Create container and run task
container, err := createContainer(ctx, client, cliCtx, image, traceFile)
if err != nil {
return err
}
defer container.Delete(ctx, containerd.WithSnapshotCleanup)
task, err := tasks.NewTask(ctx, client, container, "", con, false, "", nil)
if err != nil {
return err
... | random_line_split | |
record_trace.go | /*
Copyright The Accelerated Container Image 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 ... | (ctx context.Context, cs content.Store, oldManifest ocispec.Manifest, l layer) (ocispec.Descriptor, error) {
oldConfigData, err := content.ReadBlob(ctx, cs, oldManifest.Config)
if err != nil {
return emptyDesc, err
}
var oldConfig ocispec.Image
if err := json.Unmarshal(oldConfigData, &oldConfig); err != nil {
... | createImageWithAccelLayer | identifier_name |
record_trace.go | /*
Copyright The Accelerated Container Image 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 ... |
}()
cniObj, err := createIsolatedNetwork(cliCtx)
if err != nil {
return err
}
defer func() {
if nextErr := cniObj.Remove(ctx, networkNamespace, namespacePath); err == nil && nextErr != nil {
err = errors.Wrapf(nextErr, "failed to teardown network")
}
}()
if _, err = cniObj.Setup(c... | {
err = errors.Wrapf(err, "failed to delete netns")
} | conditional_block |
parser.js | var xhrgoform = require('xhrgoform');
var querystring = require('querystring');
var http = require('http');
var request = require('request');
var jsdom = require('jsdom');
var fs = require('fs');
var baseLink2013 = "http://registration.baa.org/cfm_Archive/iframe_ArchiveSearch.cfm?mode=results&criteria=&StoredProcParam... |
function doNext() {
if (currentYearIndex >= years.length) {
console.log("Done");
callback(runners);
return;
}
runYearSafe(
handleError,
function () {
currentYearIndex += 1;
doNext();
},
years[currentYearIndex]
);
}
doNext();
}
function runAllYearsSafe(error, callback) {
runYe... | {
currentYearIndex += 1;
} | identifier_body |
parser.js | var xhrgoform = require('xhrgoform');
var querystring = require('querystring');
var http = require('http');
var request = require('request');
var jsdom = require('jsdom');
var fs = require('fs');
var baseLink2013 = "http://registration.baa.org/cfm_Archive/iframe_ArchiveSearch.cfm?mode=results&criteria=&StoredProcParam... | }
}
});
callback(runners);
}
}
);
}
);
}
function runYear(error, callback, year) {
var url = "http://registration.baa.org/cfm_Archive/iframe_ArchiveSearch.cfm?mode=results&criteria=&StoredProcParamsOn=yes&VarAgeLowID=0&VarAgeHighID=0&VarGenderID=0&VarBibNumber=&VarLastName=... | } else {
var runner = parseRunnerBody($, row, lastRunnerWithHeader);
if (runner) {
runner.year = year;
runners.push(runner); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.