file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
tls.go | traffic comes in, the gateway on which the rule is being
// bound, etc. All these can be checked statically, since we are generating the configuration for a proxy
// with predefined labels, on a specific port.
func matchTCP(match *v1alpha3.L4MatchAttributes, proxyLabels labels.Collection, gateways map[string]bool, por... | networkFilters: buildOutboundNetworkFilters(node, tls.Route, push, listenPort, cfg.ConfigMeta),
})
hasTLSMatch = true
}
matchHasBeenHandled[matchHash] = true
}
}
}
}
// HTTPS or TLS ports without associated virtual service
if !hasTLSMatch {
var sniHosts []string
// In c... | {
for _, match := range tls.Match {
if matchTLS(match, labels.Collection{node.Metadata.Labels}, gateways, listenPort.Port, node.Metadata.Namespace) {
// Use the service's CIDRs.
// But if a virtual service overrides it with its own destination subnet match
// give preference to the user provided o... | conditional_block |
tls.go | (match *v1alpha3.TLSMatchAttributes, proxyLabels labels.Collection, gateways map[string]bool, port int, proxyNamespace string) bool {
if match == nil {
return true
}
gatewayMatch := len(match.Gateways) == 0
for _, gateway := range match.Gateways {
gatewayMatch = gatewayMatch || gateways[gateway]
}
labelMatc... | matchTLS | identifier_name | |
theme.rs | >>(mut self, pseudo_class: S) -> Self {
self.pseudo_classes.remove(&pseudo_class.into());
self
}
}
impl Selector {
pub fn is_empty(&self) -> bool {
self.element.is_none() && self.classes.is_empty() && self.pseudo_classes.is_empty()
}
}
#[derive(Clone, Debug)]
pub struct Declaration... | hex | identifier_name | |
theme.rs | self.relation {
match **relation {
SelectorRelation::Ancestor(ref x) | SelectorRelation::Parent(ref x) => return x.specificity() + s,
}
}
s
}
pub fn matches(&self, other: &Selector) -> bool {
if self.element.is_some() && self.element != other.el... | {
let mut x = match u32::from_str_radix(&hash, 16) {
Ok(x) => x,
Err(_) => return Err(CustomParseError::InvalidColorHex(hash.into_owned()).into()),
};
if hash.len() == 6 {
x |= 0xFF000000... | conditional_block | |
theme.rs | <Value> {
let mut matches: Vec<(bool, Specificity, Value)> = Vec::new();
for rule in self.all_rules().iter().rev() {
let matching_selectors = rule.selectors.iter().filter(|x| x.matches(query)).collect::<Vec<_>>();
if matching_selectors.len() > 0 {
if let Some(de... | }
#[derive(Clone, Debug, Default)]
pub struct Selector {
pub element: Option<String>,
pub classes: HashSet<String>,
pub pseudo_classes: HashSet<String>,
pub relation: Option<Box<SelectorRelation>>,
}
impl Selector {
pub fn new<S: Into<String>>(element: Option<S>) -> Self {
Selector {
... | self.0[2] + rhs.0[2],
])
} | random_line_split |
theme.rs | <Value> {
let mut matches: Vec<(bool, Specificity, Value)> = Vec::new();
for rule in self.all_rules().iter().rev() {
let matching_selectors = rule.selectors.iter().filter(|x| x.matches(query)).collect::<Vec<_>>();
if matching_selectors.len() > 0 {
if let Some(de... |
pub fn without_pseudo_class<S: Into<String>>(mut self, pseudo_class: S) -> Self {
self.pseudo_classes.remove(&pseudo_class.into());
self
}
}
impl Selector {
pub fn is_empty(&self) -> bool {
self.element.is_none() && self.classes.is_empty() && self.pseudo_classes.is_empty()
}
}... | {
self.pseudo_classes.insert(pseudo_class.into());
self
} | identifier_body |
lib.rs | _lib_handle.is_null() |
else{
Ok( DyLib(shared_lib_handle) )
}
}}
//Example
//let function : fn()->i32= transmute_copy((dlsym(shared_lib_handle, CString::new(name).unwrap().as_ptr()) as *mut ()).as_mut());
pub fn get_fn( shared_lib_handle: &DyLib, name: &str)-> Result<*mut (), String>{ unsafe{
... | {
println!("{:?}", get_error());
Err(format!("Shared lib is null! {} Check file path/name.", lib_path))
} | conditional_block |
lib.rs | }}
pub fn new(gs: &mut GlobalStorage)->DyArray<T>{
DyArray::<T>::with_capacity(gs, 5)
}
pub fn with_capacity(gs: &mut GlobalStorage, size: usize)->DyArray<T>{
let ptr = gs.alloc_multi_empty::<T>( size );
DyArray{
ptr: ptr,
... | global_storage_vec2 | identifier_name | |
lib.rs | _lib_handle.is_null(){
println!("{:?}", get_error());
Err(format!("Shared lib is null! {} Check file path/name.", lib_path))
}
else{
Ok( DyLib(shared_lib_handle) )
}
}}
//Example
//let function : fn()->i32= transmute_copy((dlsym(shared_lib_handl... | pub new_width: Option<f32>,// NOTE Testing out using a factional new width
pub new_height: Option<f32>,// NOTE Testing out using a factional new height
//Stings
pub char_buffer: String,
pub font_size: u32
}
#[derive(Default)]
pub struct RenderInstructions{
... |
//image related things
pub color_buffer: Vec<u8>,
pub rgba_type: RGBA, | random_line_split |
map_loader.rs | (|world| {
let mut loader = MapLoader::new(world);
let file = file;
let map: &Tiledmap = loader.load_map(&file);
// Get the background color based on the loaded map
let bg: Color = map
.backgroundcolor
.as_ref()
.map(|s: &String| {
hex_color(s.as_str())
... | }
}
if let Some(ndx) = mndx {
let inv_layer = layers.remove(ndx);
layers.insert(0, inv_layer);
}
}
pub fn insert_map(
&mut self,
map: &mut Tiledmap,
layer_group: Option<String>,
sprite: Option<Entity>,
) -> Result<LoadedLayers, String> {
self.sort_layers(&mut ma... | if let LayerData::Objects(_) = layer.layer_data {
if layer.name == "inventories" {
mndx = Some(i);
break 'find_ndx;
} | random_line_split |
map_loader.rs | (file: String, lazy: &LazyUpdate) {
lazy.exec_mut(|world| {
let mut loader = MapLoader::new(world);
let file = file;
let map: &Tiledmap = loader.load_map(&file);
// Get the background color based on the loaded map
let bg: Color = map
.backgroundcolor
.as_ref()
.... | load_it | identifier_name | |
map_loader.rs | world| {
let mut loader = MapLoader::new(world);
let file = file;
let map: &Tiledmap = loader.load_map(&file);
// Get the background color based on the loaded map
let bg: Color = map
.backgroundcolor
.as_ref()
.map(|s: &String| {
hex_color(s.as_str())
... |
_ => None,
}
} else {
None
}
})
.flatten()
.collect()
} else {
// Return the layers as normal
layers.iter().collect()
};
let mut layers = LoadedLayers::new();
for layer in layers_to_load.iter() {
self.i... | {
let variant_layers: Vec<&Layer> =
variant_layers.layers.iter().collect();
Some(variant_layers)
} | conditional_block |
map_loader.rs |
}
pub struct MapLoader<'a> {
loaded_maps: HashMap<String, Tiledmap>,
pub z_level: ZLevel,
pub world: &'a mut World,
pub origin: V2,
pub layer_group: Option<String>,
pub sprite: Option<Entity>,
}
impl<'a> MapLoader<'a> {
pub fn load_it(file: String, lazy: &LazyUpdate) {
lazy.exec_mut(|world| {
... | {
let other_tops = other.top_level_entities.into_iter();
let other_groups = other.groups.into_iter();
self.top_level_entities.extend(other_tops);
self.groups.extend(other_groups);
} | identifier_body | |
main.go | .Execute()
}
func checkArgs(_ *types.Event) error {
if len(plugin.AuthToken) == 0 {
return fmt.Errorf("authentication token is empty")
}
if len(plugin.Team) == 0 {
return fmt.Errorf("team is empty")
}
return nil
}
// eventPriority func read priority in the event and return alerts.PX
// check.Annotations over... | {
eventJSON, err := json.Marshal(event)
if err != nil {
return "", err
}
return fmt.Sprintf("Event data update:\n\n%s", eventJSON), nil
} | identifier_body | |
main.go | Usage: "The OpsGenie API authentication token, use default from OPSGENIE_AUTHTOKEN env var",
Value: &plugin.AuthToken,
},
{
Path: "team",
Env: "OPSGENIE_TEAM",
Argument: "team",
Shorthand: "t",
Default: "",
Usage: "The OpsGenie Team, use default from OPSGENIE_TEAM env ... | },
{
Path: "sensuDashboard",
Env: "OPSGENIE_SENSU_DASHBOARD",
Argument: "sensuDashboard",
Shorthand: "s",
Default: "disabled",
Usage: "The OpsGenie Handler will use it to create a source Sensu Dashboard URL. Use OPSGENIE_SENSU_DASHBOARD. Example: http://sensu-dashboard.example.lo... | Value: &plugin.Priority, | random_line_split |
main.go | Usage: "The OpsGenie API authentication token, use default from OPSGENIE_AUTHTOKEN env var",
Value: &plugin.AuthToken,
},
{
Path: "team",
Env: "OPSGENIE_TEAM",
Argument: "team",
Shorthand: "t",
Default: "",
Usage: "The OpsGenie Team, use default from OPSGENIE_TEAM env ... |
// only if true
if plugin.WithAnnotations {
if event.Check.Annotations != nil {
for key, value := range event.Check.Annotations {
if !strings.Contains(key, "sensu.io/plugins/sensu-opsgenie-handler/config") {
checkKey := fmt.Sprintf("%s_annotation_%s", "check", key)
details[checkKey] = value
}
... | {
details["output"] = event.Check.Output
details["command"] = event.Check.Command
details["proxy_entity_name"] = event.Check.ProxyEntityName
details["state"] = event.Check.State
details["ttl"] = fmt.Sprintf("%d", event.Check.Ttl)
details["occurrences"] = fmt.Sprintf("%d", event.Check.Occurrences)
details[... | conditional_block |
main.go | Default: 15000,
Usage: "The maximum length of the description field",
Value: &plugin.DescriptionLimit,
},
{
Path: "includeEventInNote",
Env: "",
Argument: "includeEventInNote",
Shorthand: "i",
Default: false,
Usage: "Include the event JSON in the payload sent t... | getAlert | identifier_name | |
pages.py | ):
"""
Base class for all pages in the test site.
"""
# Get the server port from the environment
# (set by the test runner script)
SERVER_PORT = os.environ.get("SERVER_PORT", 8005)
def is_browser_on_page(self):
title = self.name.lower().replace('_', ' ')
return title in sel... | (self, text):
"""
Input `text` into the text field on the page.
"""
self.q(css='#fixture input').fill(text)
class SelectPage(SitePage):
"""
Page for testing select input interactions.
"""
name = "select"
def select_car(self, car_value):
"""
Select t... | enter_text | identifier_name |
pages.py | ):
"""
Base class for all pages in the test site.
"""
# Get the server port from the environment
# (set by the test runner script)
SERVER_PORT = os.environ.get("SERVER_PORT", 8005)
def is_browser_on_page(self):
title = self.name.lower().replace('_', ' ')
return title in sel... | with self.handle_alert(confirm=True):
self.q(css='button#confirm').first.click()
def cancel(self):
"""
Click the ``Confirm`` button and cancel the dialog.
"""
with self.handle_alert(confirm=False):
self.q(css='button#confirm').first.click()
def d... | """
Click the ``Confirm`` button and confirm the dialog.
""" | random_line_split |
pages.py | ):
"""
Base class for all pages in the test site.
"""
# Get the server port from the environment
# (set by the test runner script)
SERVER_PORT = os.environ.get("SERVER_PORT", 8005)
def is_browser_on_page(self):
title = self.name.lower().replace('_', ' ')
return title in sel... |
return text_list[0]
class ButtonPage(SitePage):
"""
Page for testing button interactions.
"""
name = "button"
def click_button(self):
"""
Click the button on the page, which should cause the JavaScript
to update the #output div.
"""
self.q(css='div... | return None | conditional_block |
pages.py | ):
"""
Base class for all pages in the test site.
"""
# Get the server port from the environment
# (set by the test runner script)
SERVER_PORT = os.environ.get("SERVER_PORT", 8005)
def is_browser_on_page(self):
title = self.name.lower().replace('_', ' ')
return title in sel... |
@js_defined('something.SomethingThatDoesntExist')
class JavaScriptUndefinedPage(SitePage):
"""
Page for testing asynchronous JavaScript, where the
javascript that we wait for is never defined.
"""
name = "javascript"
@wait_for_js
def trigger_output(self):
"""
Click a but... | """
Reload the page, wait for JS, then trigger the output.
"""
self.browser.refresh()
self.wait_for_js() # pylint: disable=no-member
self.q(css='div#fixture button').first.click() | identifier_body |
Train_Trader.py | ', bias_initializer = 'random_uniform') (h5)
model = Model(inputs = S, outputs = [P,V])
rms = RMSprop(lr = LEARNING_RATE, rho = 0.99, epsilon = 0.1)
model.compile(loss = {'o_P': logloss, 'o_V': sumofsquares}, loss_weights = {'o_P': 1., 'o_V' : 0.5}, optimizer = rms)
return model
# --------------------... | model.save("saved_models/model_updates" + str(EPISODE)) | conditional_block | |
Train_Trader.py | # Discount value
BETA = 0.01 # Regularisation coefficient
IMAGE_ROWS = 84
IMAGE_COLS = 84
IMAGE_CHANNELS = 4
LEARNING_RATE = 7e-4
EPISODE = 0
THREADS = 8
t_max = 5
const = 1e-5
T = 0
episode_r = []
episode_state = np.zeros((0, IMAGE_ROWS, IMAGE_COLS, IMAGE_CHANNELS))
episode_output = []... | mat = mat[0, :, :, 0]
myCount += 1
# SAVE TO CSV
#fileName = "C:/Users/Treebeard/PycharmProjects/A3C_Keras_FlappyBird/spitout/img_" + str(myCount) + ".csv"
#np.savetxt(fileName, mat, fmt='%2.0f', delimiter=",")
#PLOT
... | if 1==0:
if thread_id == 0:
mat = x_t | random_line_split |
Train_Trader.py | # Discount value
BETA = 0.01 # Regularisation coefficient
IMAGE_ROWS = 84
IMAGE_COLS = 84
IMAGE_CHANNELS = 4
LEARNING_RATE = 7e-4
EPISODE = 0
THREADS = 8
t_max = 5
const = 1e-5
T = 0
episode_r = []
episode_state = np.zeros((0, IMAGE_ROWS, IMAGE_COLS, IMAGE_CHANNELS))
episode_output = []
episode_critic... |
def run(self):
global episode_output
global episode_r
global episode_critic
global episode_state
threadLock.acquire()
self.next_state, state_store, output_store, r_store, critic_store = runprocess(self.thread_id, self.next_state)
self.next_state = self.next | threading.Thread.__init__(self)
self.thread_id = thread_id
self.next_state = s_t | identifier_body |
Train_Trader.py | # Discount value
BETA = 0.01 # Regularisation coefficient
IMAGE_ROWS = 84
IMAGE_COLS = 84
IMAGE_CHANNELS = 4
LEARNING_RATE = 7e-4
EPISODE = 0
THREADS = 8
t_max = 5
const = 1e-5
T = 0
episode_r = []
episode_state = np.zeros((0, IMAGE_ROWS, IMAGE_COLS, IMAGE_CHANNELS))
episode_output = []
episode_critic... | (self,thread_id, s_t):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.next_state = s_t
def run(self):
global episode_output
global episode_r
global episode_critic
global episode_state
threadLock.acquire()
self.next_state, sta... | __init__ | identifier_name |
code.py | )
scores = cross_val_score(knn, X_train, d_y_train, cv = 3) #3 folds
cv_score = np.mean(scores)
print('k = {}, accuracy on validation set = {:.3f}'.format(k, cv_score))
cv_scores.append((k, cv_score))
#selecting k that gave the best accuracy on validation set
best_k = max(cv_scores, key = lambda x:x[-1])
print... | (data):
testing_cropped = []
for i in range(len(data)):
#threshold each image and find contours
img = (data[i]).astype('uint8')
_, threshold = | image_crop | identifier_name |
code.py | nn_model.fit(X_train, d_y_train)
#evaluate fitted KNN on test data
knn_y_pred = knn_model.predict(X_test)
test_accuracy = accuracy_score(d_y_test, knn_y_pred)
print(test_accuracy)
"""## Model 2: CNN
"""
#tune hyperparameters, here we tune batch size, dropout rate and learning rate
settings = []
for batch in ... | testing_cropped = []
for i in range(len(data)):
#threshold each image and find contours
img = (data[i]).astype('uint8')
_, threshold = cv2.threshold(img.copy(), 10, 255, 0)
contours, _ = cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)[-2:]
bboxes = []
#creating boundi... | identifier_body | |
code.py | _train)
#evaluate fitted KNN on test data
knn_y_pred = knn_model.predict(X_test)
test_accuracy = accuracy_score(d_y_test, knn_y_pred)
print(test_accuracy)
"""## Model 2: CNN
"""
#tune hyperparameters, here we tune batch size, dropout rate and learning rate
settings = []
for batch in [64, 100, 128]:
for dro... | to_remove.append(bboxes[j]) | conditional_block | |
code.py | 'min')
#reducing learning rate
reduce_lr = ReduceLROnPlateau(monitor='val_loss',
factor = 0.1,
patience = 1,
verbose = 1,
mode = 'min',
... | for sample in testing_cropped[i]:
imbw = sample > threshold_local(sample, block_size, method = 'mean') | random_line_split | |
longestCommonSubsequence.py | lines to be transcribed | imageIndex = 1
lineIndex = 4
#which input files do you want to read in- need to be of the form transcribe$i.txt
#right now can handle at most only 3 or so files - NP-hard problem. Future work might be to make this
#code more scalable - probably with branch and bound approach
inputFiles = [1,2,3,4,5]
def load_file(fna... | #give the index of the image and the line | random_line_split |
longestCommonSubsequence.py | to be transcribed
#give the index of the image and the line
imageIndex = 1
lineIndex = 4
#which input files do you want to read in- need to be of the form transcribe$i.txt
#right now can handle at most only 3 or so files - NP-hard problem. Future work might be to make this
#code more scalable - probably with branch a... | (lines):
#find the length of each string
stringLength = [len(l)+1 for l in lines]
#record the length of longest common subsequence - assumes unique LCS
#that is there might be more than one longest common subsequence. Have encountered this in practice
#but the strings are usually similar enough tha... | lcs | identifier_name |
longestCommonSubsequence.py | to be transcribed
#give the index of the image and the line
imageIndex = 1
lineIndex = 4
#which input files do you want to read in- need to be of the form transcribe$i.txt
#right now can handle at most only 3 or so files - NP-hard problem. Future work might be to make this
#code more scalable - probably with branch a... |
def lcs(lines):
#find the length of each string
stringLength = [len(l)+1 for l in lines]
#record the length of longest common subsequence - assumes unique LCS
#that is there might be more than one longest common subsequence. Have encountered this in practice
#but the strings are usually similar ... | currentImage = 0
currentLine = -1
individual_transcriptions = {}
with open(fname,"rb") as f:
for l in f.readlines():
if l == "\n":
currentImage += 1
currentLine = -1
continue
currentLine += 1
individual_transcript... | identifier_body |
longestCommonSubsequence.py | to be transcribed
#give the index of the image and the line
imageIndex = 1
lineIndex = 4
#which input files do you want to read in- need to be of the form transcribe$i.txt
#right now can handle at most only 3 or so files - NP-hard problem. Future work might be to make this
#code more scalable - probably with branch a... |
if currentIndex == [[1,] for l in lines]:
break
#check to see if the last tuple of characters is a match
lastCharacter = [t[-1] for t in lines]
s = [[] for t in lines]
lcs_length = 0
if min(lastCharacter) == max(lastCharacter):
lcs_length += 1
for i,w in enum... | break | conditional_block |
messages.go | (br BaudrateIdentification) int {
switch rune(br) {
case '0':
return 300
case 'A', '1':
return 600
case 'B', '2':
return 1200
case 'C', '3':
return 2400
case 'D', '4':
return 4800
case 'E', '5':
return 9600
case 'F', '6':
return 19200
} | AckModeDataReadOut = AcknowledgeMode(byte('0'))
AckModeProgramming = AcknowledgeMode(byte('1'))
AckModeBinary = AcknowledgeMode(byte('2'))
AckModeReserved = AcknowledgeMode(byte('3'))
AckModeManufacture = AcknowledgeMode(byte('6'))
AckModeIllegalMode = AcknowledgeMode(byte(' '))
)
const (
CR ... | return 0
}
const ( | random_line_split |
messages.go | (br BaudrateIdentification) int {
switch rune(br) {
case '0':
return 300
case 'A', '1':
return 600
case 'B', '2':
return 1200
case 'C', '3':
return 2400
case 'D', '4':
return 4800
case 'E', '5':
return 9600
case 'F', '6':
return 19200
}
return 0
}
const (
AckModeDataReadOut = AcknowledgeMode(b... |
if b != LF {
if verbose {
log.Println("ParseDataMessageEnd, error parsing LF")
}
return nil, ErrFormatError
}
bcc.Digest(b)
b, err = r.ReadByte()
if err != nil {
return nil, err
}
if b != EtxChar {
if verbose {
log.Println("ParseDataMessageEnd, error parsing EtxChar")
}
return nil, ErrForma... | {
return nil, err
} | conditional_block |
messages.go | (br BaudrateIdentification) int |
const (
AckModeDataReadOut = AcknowledgeMode(byte('0'))
AckModeProgramming = AcknowledgeMode(byte('1'))
AckModeBinary = AcknowledgeMode(byte('2'))
AckModeReserved = AcknowledgeMode(byte('3'))
AckModeManufacture = AcknowledgeMode(byte('6'))
AckModeIllegalMode = AcknowledgeMode(byte(' '))
)
const (
CR ... | {
switch rune(br) {
case '0':
return 300
case 'A', '1':
return 600
case 'B', '2':
return 1200
case 'C', '3':
return 2400
case 'D', '4':
return 4800
case 'E', '5':
return 9600
case 'F', '6':
return 19200
}
return 0
} | identifier_body |
messages.go | (br BaudrateIdentification) int {
switch rune(br) {
case '0':
return 300
case 'A', '1':
return 600
case 'B', '2':
return 1200
case 'C', '3':
return 2400
case 'D', '4':
return 4800
case 'E', '5':
return 9600
case 'F', '6':
return 19200
}
return 0
}
const (
AckModeDataReadOut = AcknowledgeMode(b... | (b byte) bool {
switch b {
case FrontBoundaryChar, UnitSeparator, RearBoundaryChar, StartChar, EndChar:
return false
default:
return true
}
}
func ValidUnitChar(b byte) bool {
return ValidAddressChar(b)
}
// AcknowledgeModeFromByte returns the acknowledge mode from the given byte value.
func AcknowledgeModeF... | ValidValueChar | identifier_name |
media_sessions.rs | (
&self,
event_id: fidl_avrcp::NotificationEvent,
current: Notification,
pos_change_interval: u32,
responder: fidl_avrcp::TargetHandlerWatchNotificationResponder,
) -> Result<(), fidl::Error> {
let mut write = self.inner.write();
write.register_notification(ev... | register_notification | identifier_name | |
media_sessions.rs | responder: fidl_avrcp::TargetHandlerWatchNotificationResponder,
) -> Result<(), fidl::Error> {
let mut write = self.inner.write();
write.register_notification(event_id, current, pos_change_interval, responder) | }
async fn watch_media_sessions(
discovery: DiscoveryProxy,
mut watcher_requests: SessionsWatcherRequestStream,
sessions_inner: Arc<RwLock<MediaSessionsInner>>,
) -> Result<(), anyhow::Error> {
while let Some(req) =
watcher_requests.try_next().await.expect("Faile... | random_line_split | |
media_sessions.rs | : fidl_avrcp::TargetHandlerWatchNotificationResponder,
) -> Result<(), fidl::Error> {
let mut write = self.inner.write();
write.register_notification(event_id, current, pos_change_interval, responder)
}
async fn watch_media_sessions(
discovery: DiscoveryProxy,
mut watcher_re... | else {
return;
};
self.notifications = self
.notifications
.drain()
.map(|(event_id, queue)| {
let curr_value = state.session_info().get_notification_value(&event_id);
(
event_id,
qu... | {
state.clone()
} | conditional_block |
media_sessions.rs | fn create_or_update_session<F>(
&mut self,
discovery: DiscoveryProxy,
id: u64,
delta: SessionInfoDelta,
create_fn: F,
) -> Result<(), Error>
where
F: Fn(DiscoveryProxy, u64) -> Result<SessionControlProxy, Error>,
{
self.map
.entry(id)
... | {} | identifier_body | |
zhtta.rs | Server {
let (notify_tx, notify_rx) = channel();
let www_dir_path = Path::new(www_dir);
os::change_dir(&www_dir_path);
WebServer {
ip:ip,
port: port,
www_dir_path: www_dir_path,
request_queue_arc: Arc::new(... |
// TODO: Streaming file.
// TODO: Application-layer file caching.
fn respond_with_static_file(stream: std::old_io::net::tcp::TcpStream, path: &Path,cache : Arc<RwLock<HashMap<Path,(String,Mutex<usize>,u64)>>>,cache_len :Arc<Mutex<usize>>) {
let mut stream = stream;
let mut cache_str=S... | {
let mut stream = stream;
let response: String =
format!("{}{}<h1>Greetings, Krusty!</h1><h2>Visitor count: {}</h2></body></html>\r\n",
HTTP_OK, COUNTER_STYLE,
unsafe { visitor_count } );
debug!("Responding to counter request");
stream.write(respons... | identifier_body |
zhtta.rs | Server {
let (notify_tx, notify_rx) = channel();
let www_dir_path = Path::new(www_dir);
os::change_dir(&www_dir_path);
WebServer {
ip:ip,
port: port,
www_dir_path: www_dir_path,
request_queue_arc: Arc::new(... | });
}
});
}
fn respond_with_error_page(stream: std::old_io::net::tcp::TcpStream, path: &Path) {
let mut stream = stream;
let msg: String= format!("Cannot open: {}", path.as_str().expect("invalid path"));
stream.write(HTTP_BAD.as_bytes());
stream.write(msg.as_bytes());
... |
}
}
} | random_line_split |
zhtta.rs | ());
return;
}
else{
debug!("reading from disk!");
let mut file_reader = File::open(path).unwrap();
stream.write(HTTP_OK.as_bytes());
/*let mut buf:[u8;1048576]=[0;1048576];
loop{
... | int_usage(p | identifier_name | |
zhtta.rs | debug!("updating cache....");
{
let mut write_hash=local_cache.write().unwrap();
let time=std::fs::metadata(path).unwrap().modified();
write_hash.insert(path.clone(),(cache_str,Mutex::new(0),time));
}
*cache_len.lock().unwrap()+=1;
{
... | matches.opt_str("ip").expect("invalid ip address?").to_owned()
} e | conditional_block | |
176_main_448.py | .48828125, 1.984375, 1.5875, 1.831730769, 1.092316514, 1.469907407, 1.26662234, 1.5875,
0.661458333, 2.088815789, 1.725543478, 1.725543478, 0.376780063, 1.384447674, 1.630993151,
2.9765625, 0.607461735, 0.888526119, 2.645833333, 2.334558824, 1.777052239, 0.519923581,
... | adjust_learning_rate(args, optimizer, epoch, gamma=0.1)
# train for one epoch
train(args, train_loader, model, criterion, optimizer, epoch)
# evaluate on validation set
if epoch % args.eval_epoch == 0:
prec1 = validate_simple(args, test_loader_simple, model, criterion, epoc... | conditional_block | |
176_main_448.py | ')
parser.add_argument('--seed', default=None, type=int,
help='seed for initializing training. ')
parser.add_argument('--gpu', default=4, type=int,
help='GPU nums to use.')
parser.add_argument('--log_train_dir', default='log_train', type=str,
help='log for tra... | ():
print('DFL-CNN <==> Part1 : prepare for parameters <==> Begin')
global args, best_prec1
args = parser.parse_args()
print('DFL-CNN <==> Part1 : prepare for parameters <==> Done')
print('DFL-CNN <==> Part2 : Load Network <==> Begin')
model = DFL_VGG16(k=10, nclass=176)
if args.gpu is not... | main | identifier_name |
176_main_448.py | ')
parser.add_argument('--seed', default=None, type=int,
help='seed for initializing training. ')
parser.add_argument('--gpu', default=4, type=int,
help='GPU nums to use.')
parser.add_argument('--log_train_dir', default='log_train', type=str,
help='log for tra... | 0.592350746, 0.262252203, 1.123231132, 0.308452073, 1.280241935, 1.009004237,
1.725543478, 1.308379121, 0.265172606, 1.777052239, 1.469907407, 1.00052521,
1.803977273, 0.470602767, 0.960181452, 1.67693662, 1.608952703, 0.280807783,
... | print('DFL-CNN <==> Part1 : prepare for parameters <==> Begin')
global args, best_prec1
args = parser.parse_args()
print('DFL-CNN <==> Part1 : prepare for parameters <==> Done')
print('DFL-CNN <==> Part2 : Load Network <==> Begin')
model = DFL_VGG16(k=10, nclass=176)
if args.gpu is not None:
... | identifier_body |
176_main_448.py | 09004237,
1.725543478, 1.308379121, 0.265172606, 1.777052239, 1.469907407, 1.00052521,
1.803977273, 0.470602767, 0.960181452, 1.67693662, 1.608952703, 0.280807783,
0.9921875, 0.466911765, 1.112733645, 2.903963415, 2.768895349, 0.295440447,
... | args.start_epoch = checkpoint['epoch']
best_prec1 = checkpoint['best_prec1'] | random_line_split | |
ansi_up.ts | this.palette_256.push(gry);
}
}
private old_escape_for_html(txt:string):string
{
return txt.replace(/[&<>]/gm, (str) => {
if (str === "&") return "&";
if (str === "<") return "<";
if (str === ">") return ">";
});
}
private old_linki... | {
// extend color (38=fg, 48=bg)
let is_foreground = (num === 38);
let mode_cmd = sgr_cmds.shift();
// MODE '5' - 256 color palette
if (mode_cmd === '5' && sgr_cmds.length > 0) {
let palette_index = parseIn... | conditional_block | |
ansi_up.ts | string {
return segments.join("");
}
};
textFormatter:Formatter = {
transform(fragment:TextWithAttr, instance:AnsiUp):string {
return fragment.text;
},
compose(segments:string[], instance:AnsiUp):string {
return segments.join("");
}
... | random_line_split | ||
ansi_up.ts | },
{ rgb: [255, 255, 255], class_name: "ansi-white" }
],
// Bright colors
[
{ rgb: [ 85, 85, 85], class_name: "ansi-bright-black" },
{ rgb: [255, 85, 85], class_name: "ansi-bright-red" },
{ rgb: [ 0, 255, 0], class_name: "ansi-bright-green"... |
private setup_256_palette():void
{
this.palette_256 = [];
// Index 0..15 : Ansi-Colors
this.ansi_colors.forEach( palette => {
palette.forEach( rec => {
this.palette_256.push(rec);
});
});
// Index 16..231 : RGB 6x6x6
// ... | {
return this._escape_for_html;
} | identifier_body |
ansi_up.ts | },
{ rgb: [255, 255, 255], class_name: "ansi-white" }
],
// Bright colors
[
{ rgb: [ 85, 85, 85], class_name: "ansi-bright-black" },
{ rgb: [255, 85, 85], class_name: "ansi-bright-red" },
{ rgb: [ 0, 255, 0], class_name: "ansi-bright-green"... | ():void
{
this.palette_256 = [];
// Index 0..15 : Ansi-Colors
this.ansi_colors.forEach( palette => {
palette.forEach( rec => {
this.palette_256.push(rec);
});
});
// Index 16..231 : RGB 6x6x6
// https://gist.github.com/jasonm2... | setup_256_palette | identifier_name |
docker_client.go | Details(sys, registry, username, password, "", nil, "")
if err != nil {
return errors.Wrapf(err, "error creating new docker client")
}
resp, err := newLoginClient.makeRequest(ctx, "GET", "/v2/", nil, nil, v2Auth)
if err != nil {
return err
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.Statu... | earerToken(ctx | identifier_name | |
docker_client.go | Decode(v1Res); err != nil {
return nil, err
}
return v1Res.Results, nil
}
}
}
logrus.Debugf("trying to talk to v2 search endpoint\n")
resp, err := client.makeRequest(ctx, "GET", "/v2/_catalog", nil, nil, v2Auth)
if err != nil {
logrus.Debugf("error getting search results from v2 endpoint %q: %v... | return false
}
| conditional_block | |
docker_client.go | }
if token.ExpiresIn < minimumTokenLifetimeSeconds {
token.ExpiresIn = minimumTokenLifetimeSeconds
logrus.Debugf("Increasing token expiration to: %d seconds", token.ExpiresIn)
}
if token.IssuedAt.IsZero() {
token.IssuedAt = time.Now().UTC()
}
return token, nil
}
// this is cloned from docker/go-connections ... | // IsOfficial states whether the image is an official build
IsOfficial bool `json:"is_official"`
}
// SearchRegistry queries a registry for images that contain "image" in their name
// The limit is the max number of results desired
// Note: The limit value doesn't work with all registries
// for example registry.acc... | IsAutomated bool `json:"is_automated"` | random_line_split |
docker_client.go | username and password")
}
sigBase, err := configuredSignatureStorageBase(sys, ref, write)
if err != nil {
return nil, err
}
remoteName := reference.Path(ref.ref)
return newDockerClientWithDetails(sys, registry, username, password, actions, sigBase, remoteName)
}
// newDockerClientWithDetails returns a new do... | eq, err := http.NewRequest(method, url, stream)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
if streamLen != -1 { // Do not blindly overwrite if streamLen == -1, http.NewRequest above can figure out the length of bytes.Reader and similar objects without us having to compute it.
req.ContentLength... | identifier_body | |
customs.js | label:""
});
var $slicknav_label;
$('#responsive-menu').slicknav({
duration: 500,
easingOpen: 'easeInExpo',
easingClose: 'easeOutExpo',
closedSymbol: '<i class="fa fa-plus"></i>',
openedSymbol: '<i class="fa fa-minus"></i>',
prependTo: '#slicknav-mobile',
allowParentLinks: true,
label:"... | $(this).next('.label').text($(this).val());
});
/**
* Sign-in Modal
*/
var $formLogin = $('#login-form');
var $formLost = $('#lost-form');
var $formRegister = $('#register-form');
var $divForms = $('#modal-login-form-wrapper');
var $modalAnimateTime = 300;
$('#login_register_btn').on("... | });
selected4.on('change', function () { | random_line_split |
customs.js | :""
});
var $slicknav_label;
$('#responsive-menu').slicknav({
duration: 500,
easingOpen: 'easeInExpo',
easingClose: 'easeOutExpo',
closedSymbol: '<i class="fa fa-plus"></i>',
openedSymbol: '<i class="fa fa-minus"></i>',
prependTo: '#slicknav-mobile',
allowParentLinks: true,
label:""
}... |
/**
* Read more-less paragraph
*/
var showTotalChar = 130, showChar = "read more +", hideChar = "read less -";
$('.read-more-less').each(function() {
var content = $(this).text();
if (content.length > showTotalChar) {
var con = content.substr(0, showTotalChar);
var hcon = content.substr... | {
var $oldH = $oldForm.height();
var $newH = $newForm.height();
$divForms.css("height",$oldH);
$oldForm.fadeToggle($modalAnimateTime, function(){
$divForms.animate({height: $newH}, $modalAnimateTime, function(){
$newForm.fadeToggle($modalAnimateTime);
});
});
} | identifier_body |
customs.js | :""
});
var $slicknav_label;
$('#responsive-menu').slicknav({
duration: 500,
easingOpen: 'easeInExpo',
easingClose: 'easeOutExpo',
closedSymbol: '<i class="fa fa-plus"></i>',
openedSymbol: '<i class="fa fa-minus"></i>',
prependTo: '#slicknav-mobile',
allowParentLinks: true,
label:""
}... |
});
$(".showmoretxt").on("click",function() {
if ($(this).hasClass("sample")) {
$(this).removeClass("sample");
$(this).text(showChar);
} else {
$(this).addClass("sample");
$(this).text(hideChar);
}
$(this).parent().prev().toggle();
$(this).prev().toggle();
return false;
});
/... | {
var con = content.substr(0, showTotalChar);
var hcon = content.substr(showTotalChar, content.length - showTotalChar);
var txt= con + '<span class="dots">...</span><span class="morectnt"><span>' + hcon + '</span> <a href="" class="showmoretxt">' + showChar + '</a></span>';
$(this).html(txt);... | conditional_block |
customs.js | label:""
});
var $slicknav_label;
$('#responsive-menu').slicknav({
duration: 500,
easingOpen: 'easeInExpo',
easingClose: 'easeOutExpo',
closedSymbol: '<i class="fa fa-plus"></i>',
openedSymbol: '<i class="fa fa-minus"></i>',
prependTo: '#slicknav-mobile',
allowParentLinks: true,
label:"... | ($oldForm, $newForm) {
var $oldH = $oldForm.height();
var $newH = $newForm.height();
$divForms.css("height",$oldH);
$oldForm.fadeToggle($modalAnimateTime, function(){
$divForms.animate({height: $newH}, $modalAnimateTime, function(){
$newForm.fadeToggle($modalAnimateTime);
});
});
}
... | modalAnimate | identifier_name |
recombine.go |
func NewConfigWithID(operatorID string) *Config {
return &Config{
TransformerConfig: helper.NewTransformerConfig(operatorID, operatorType),
MaxBatchSize: 1000,
MaxSources: 1000,
CombineWith: defaultCombineWith,
OverwriteWith: "oldest",
ForceFlushTimeout: 5 * time.Second,
SourceIden... | () {
for {
select {
case <-r.ticker.C:
r.Lock()
timeNow := time.Now()
for source, batch := range r.batchMap {
timeSinceFirstEntry := timeNow.Sub(batch.firstEntryObservedTime)
if timeSinceFirstEntry < r.forceFlushTimeout {
continue
}
if err := r.flushSource(source, true); err != nil {
... | flushLoop | identifier_name |
recombine.go | }
// NewConfigWithID creates a new recombine config with default values
func NewConfigWithID(operatorID string) *Config {
return &Config{
TransformerConfig: helper.NewTransformerConfig(operatorID, operatorType),
MaxBatchSize: 1000,
MaxSources: 1000,
CombineWith: defaultCombineWith,
Overwri... | return NewConfigWithID(operatorType) | random_line_split | |
recombine.go |
func NewConfigWithID(operatorID string) *Config {
return &Config{
TransformerConfig: helper.NewTransformerConfig(operatorID, operatorType),
MaxBatchSize: 1000,
MaxSources: 1000,
CombineWith: defaultCombineWith,
OverwriteWith: "oldest",
ForceFlushTimeout: 5 * time.Second,
SourceIden... | err = e.Read(r.sourceIdentifier, &s)
if err != nil {
r.Warn("entry does not contain the source_identifier, so it may be pooled with other sources")
s = DefaultSourceIdentifier
}
if s == "" {
s = DefaultSourceIdentifier
}
switch {
// This is the first entry in the next batch
case matches && r.matchIndica... | {
// Lock the recombine operator because process can't run concurrently
r.Lock()
defer r.Unlock()
// Get the environment for executing the expression.
// In the future, we may want to provide access to the currently
// batched entries so users can do comparisons to other entries
// rather than just use absolute... | identifier_body |
recombine.go |
func NewConfigWithID(operatorID string) *Config {
return &Config{
TransformerConfig: helper.NewTransformerConfig(operatorID, operatorType),
MaxBatchSize: 1000,
MaxSources: 1000,
CombineWith: defaultCombineWith,
OverwriteWith: "oldest",
ForceFlushTimeout: 5 * time.Second,
SourceIden... |
if c.IsLastEntry == "" && c.IsFirstEntry == "" {
return nil, fmt.Errorf("one of is_first_entry and is_last_entry must be set")
}
var matchesFirst bool
var prog *vm.Program
if c.IsFirstEntry != "" {
matchesFirst = true
prog, err = helper.ExprCompileBool(c.IsFirstEntry)
if err != nil {
return nil, fmt.... | {
return nil, fmt.Errorf("only one of is_first_entry and is_last_entry can be set")
} | conditional_block |
package.go | if m.Version != "" {
s += " " + m.Version
if m.Update != nil {
s += " [" + m.Update.Version + "]"
}
}
if m.Replace != nil {
s += " => " + m.Replace.Path
if m.Replace.Version != "" {
s += " " + m.Replace.Version
if m.Replace.Update != nil {
s += " [" + m.Replace.Update.Version + "]"
}
}
}... | (t *Type) (fields []*Field) {
if t == nil {
return
}
for _, spec := range t.Decl.Specs {
typeSpec := spec.(*ast.TypeSpec)
// struct type
if str, ok := typeSpec.Type.(*ast.StructType); ok {
for _, f := range str.Fields.List {
fields = append(fields, &Field{
Field: f,
Type: t,
})
... | TypeFields | identifier_name |
package.go | if m.Version != "" {
s += " " + m.Version
if m.Update != nil {
s += " [" + m.Update.Version + "]"
}
}
if m.Replace != nil {
s += " => " + m.Replace.Path
if m.Replace.Version != "" {
s += " " + m.Replace.Version
if m.Replace.Update != nil {
s += " [" + m.Replace.Update.Version + "]"
}
}
}... |
p.Doc = d.Doc
p.Name = d.Name
p.ImportPath = d.ImportPath
p.Imports = d.Imports
p.Filenames = d.Filenames
p.Notes = d.Notes
p.Consts = d.Consts
p.Vars = d.Vars
p.Examples = d.Examples
// set package types
for _, t := range d.Types {
p.Types = append(p.Types, NewTypeWithDoc(t))
}
// set package funcs
... | {
p.FSet = token.NewFileSet() // positions are relative to fset
pkgs, err := parser.ParseDir(p.FSet, p.Dir, nil, parser.ParseComments)
if err != nil {
return
}
var astPackage *ast.Package
for name, apkg := range pkgs {
if strings.HasSuffix(name, "_test") { // skip test package
continue
}
astPackage ... | identifier_body |
package.go | if m.Version != "" {
s += " " + m.Version
if m.Update != nil {
s += " [" + m.Update.Version + "]"
}
}
if m.Replace != nil {
s += " => " + m.Replace.Path
if m.Replace.Version != "" {
s += " " + m.Replace.Version
if m.Replace.Update != nil {
s += " [" + m.Replace.Update.Version + "]"
}
}
}... |
// TypeSpec type spec
type TypeSpec string
const (
// StructType struct type spec
StructType TypeSpec = "struct"
// InterfaceType interface type spec
InterfaceType TypeSpec = "interface"
)
// Type type
type Type struct {
// doc.Type
Doc string
Name string
Decl *ast.GenDecl
Documentation Documentation
... | }
return
} | random_line_split |
package.go | if m.Version != "" {
s += " " + m.Version
if m.Update != nil {
s += " [" + m.Update.Version + "]"
}
}
if m.Replace != nil {
s += " => " + m.Replace.Path
if m.Replace.Version != "" {
s += " " + m.Replace.Version
if m.Replace.Update != nil {
s += " [" + m.Replace.Update.Version + "]"
}
}
}... |
astPackage = apkg
}
d := doc.New(astPackage, p.ImportPath, doc.AllDecls)
p.DocPackage = d
p.Doc = d.Doc
p.Name = d.Name
p.ImportPath = d.ImportPath
p.Imports = d.Imports
p.Filenames = d.Filenames
p.Notes = d.Notes
p.Consts = d.Consts
p.Vars = d.Vars
p.Examples = d.Examples
// set package types
for ... | { // skip test package
continue
} | conditional_block |
recreate.go | "tablePropertiesToCQL": cqlHelpers.tablePropertiesToCQL,
}).
Parse(`
CREATE TABLE {{ .KeyspaceName }}.{{ .Tm.Name }} (
{{ tableColumnToCQL .Tm }}
) WITH {{ tablePropertiesToCQL .Tm.ClusteringColumns .Tm.Options .Tm.Flags .Tm.Extensions }};
`))
func (km *KeyspaceMetadata) tableToCQL(w io.Writer, kn string, tm *... |
return m
}
func (h toCQLHelpers) escape(e interface{}) string {
switch v := e.(type) {
case int, float64:
return fmt.Sprint(v)
case bool:
if v {
return "true"
}
return "false"
case string:
return "'" + strings.ReplaceAll(v, "'", "''") + "'"
case []byte:
return string(v)
}
return ""
}
func (h t... | {
m[i] = []string{a[i], b[i]}
} | conditional_block |
recreate.go | "tablePropertiesToCQL": cqlHelpers.tablePropertiesToCQL,
}).
Parse(`
CREATE TABLE {{ .KeyspaceName }}.{{ .Tm.Name }} (
{{ tableColumnToCQL .Tm }}
) WITH {{ tablePropertiesToCQL .Tm.ClusteringColumns .Tm.Options .Tm.Flags .Tm.Extensions }};
`))
func (km *KeyspaceMetadata) tableToCQL(w io.Writer, kn string, tm *... |
opts["compaction"], err = json.Marshal(ops.Compaction)
if err != nil {
return nil, err
}
opts["compression"], err = json.Marshal(ops.Compression)
if err != nil {
return nil, err
}
cdc, err := json.Marshal(ops.CDC)
if err != nil {
return nil, err
| {
opts := map[string]interface{}{
"bloom_filter_fp_chance": ops.BloomFilterFpChance,
"comment": ops.Comment,
"crc_check_chance": ops.CrcCheckChance,
"dclocal_read_repair_chance": ops.DcLocalReadRepairChance,
"default_time_to_live": ops.DefaultTimeToLive,
"gc_grac... | identifier_body |
recreate.go | ,
"tablePropertiesToCQL": cqlHelpers.tablePropertiesToCQL,
}).
Parse(`
CREATE TABLE {{ .KeyspaceName }}.{{ .Tm.Name }} (
{{ tableColumnToCQL .Tm }}
) WITH {{ tablePropertiesToCQL .Tm.ClusteringColumns .Tm.Options .Tm.Flags .Tm.Extensions }};
`))
func (km *KeyspaceMetadata) tableToCQL(w io.Writer, kn string, tm... | "keyspaceName": keyspaceName,
}); err != nil {
return err
}
return nil
}
var viewTemplate = template.Must(template.New("views").
Funcs(map[string]interface{}{
"zip": cqlHelpers.zip,
"partitionKeyString": cqlHelpers.partitionKeyString,
"tablePropertiesToCQL": cqlHelpers.tablePropertiesT... | random_line_split | |
recreate.go | "tablePropertiesToCQL": cqlHelpers.tablePropertiesToCQL,
}).
Parse(`
CREATE TABLE {{ .KeyspaceName }}.{{ .Tm.Name }} (
{{ tableColumnToCQL .Tm }}
) WITH {{ tablePropertiesToCQL .Tm.ClusteringColumns .Tm.Options .Tm.Flags .Tm.Extensions }};
`))
func (km *KeyspaceMetadata) tableToCQL(w io.Writer, kn string, tm *... | (w io.Writer, vm *ViewMetadata) error {
if err := viewTemplate.Execute(w, map[string]interface{}{
"vm": vm,
"flags": []string{},
}); err != nil {
return err
}
return nil
}
var aggregatesTemplate = template.Must(template.New("aggregate").
Funcs(map[string]interface{}{
"stripFrozen": cqlHelpers.stripFroz... | viewToCQL | identifier_name |
index.ts | IDEMPOTENT_HTTP_METHODS = SAFE_HTTP_METHODS.concat(['put', 'delete'])
export interface AxiosExtendObject {
promiseKey: string
url: string
promise: Promise<any>
source: CancelTokenSource
}
export interface AxiosExtendCurrentStateType {
lastRequestTime: number
retryCount: number
}
export inter... | tion isRetryableError(error: AxiosError): boolean {
return error.code !== 'ECONNABORTED' && (!error.response || (error.response.status >= 500 && error.response.status <= 599))
}
/**
* axios封装
*
* @return Promise
*/
class AxiosExtend {
waiting: Array<AxiosExtendObject> = [] // 请求队列
maxConnections: numbe... | randomSum = delay * 0.5 * Math.random() // 0-50% of the delay
return delay + randomSum
}
/**
* @param error - 错误类型
* @return boolean
*/
export func | identifier_body |
index.ts | IDEMPOTENT_HTTP_METHODS = SAFE_HTTP_METHODS.concat(['put', 'delete'])
export interface AxiosExtendObject {
promiseKey: string
url: string
promise: Promise<any>
source: CancelTokenSource
}
export interface AxiosExtendCurrentStateType {
lastRequestTime: number
retryCount: number
}
export inter... | this.unique = unique ?? false
this.retries = retries ?? 0
this.onCancel = onCancel ?? null
// 初始化方法
this.init(defaultOptions)
}
/**
* 初始化
*/
public init(defaultOptions: AxiosExtendConfig): void {
const { setHeaders, onRequest, onRequestError, onResponse, onR... | ue
| identifier_name |
index.ts | const IDEMPOTENT_HTTP_METHODS = SAFE_HTTP_METHODS.concat(['put', 'delete'])
export interface AxiosExtendObject {
promiseKey: string
url: string
promise: Promise<any>
source: CancelTokenSource
}
export interface AxiosExtendCurrentStateType {
lastRequestTime: number
retryCount: number
}
export ... | export function isSafeRequestError(error: any): boolean {
// Cannot determine if the request can be retried
if (!error.config) return false
return isRetryableError(error) && SAFE_HTTP_METHODS.indexOf(error.config.method) !== -1
}
/**
* @param error - 错误类型
* @return boolean
*/
export function isIdempotent... | /**
* @param error - 错误类型
* @return boolean
*/ | random_line_split |
products.ts | 27-32-Inch-1080p-Smart/dp/B07F981R8M/ref=sr_1_1?dchild=1&field-shipping_option-bin=3242350011&pf_rd_i=16225009011&pf_rd_m=ATVPDKIKX0DER&pf_rd_p=85a9188d-dbd5-424e-9512-339a1227d37c&pf_rd_r=SREFZAEZSX9R1FG29V2H&pf_rd_s=merchandised-search-5&pf_rd_t=101&qid=1614698224&rnid=1266092011&s=electronics&sr=1-1',
likes: 55
... | rating: 4.5,
shareLink: 'https://www.amazon.com/TCL-Dolby-Vision-QLED-Smart/dp/B08857ZHY3/ref=sr_1_3?dchild=1&field-shipping_option-bin=3242350011&pf_rd_i=16225009011&pf_rd_m=ATVPDKIKX0DER&pf_rd_p=85a9188d-dbd5-424e-9512-339a1227d37c&pf_rd_r=SREFZAEZSX9R1FG29V2H&pf_rd_s=merchandised-search-5&pf_rd_t=101&qid=161... | imageUrl: 'https://m.media-amazon.com/images/I/91tMNAWWsPL._AC_UL320_.jpg', | random_line_split |
udacity_project_script.py | = ['Mon', 'Tue', 'Wed', 'Thu', 'Fry', 'Sat', 'Sun']
month, day = 'all_months', 'all_days'
if answer == 'both':
month = input("\nWhich month do you want to analyze? Jan, Feb ,.., Jun\n").capitalize()
while month not in legit_months:
print('There is no such month! Try again.')
... | (df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
df['time'] = df['End Time'] - df['Start Time']
# TO DO: display total travel time
print("Total travel time in that period of time: {}".format(df['time'].su... | trip_duration_stats | identifier_name |
udacity_project_script.py |
city = city.replace(" ", "_")
possible_answers = ['month', 'day', 'both', 'none'] # answers im gonna accept - 4 possibilities
answer = input("\nFilter by 'month','day' or 'both'? If you don't want to filter type 'none'\n").lower()
while answer not in possible_answers:
print("WAAT?!")
... | print("There is no such city in database!")
city = input("\nWhich city do you want to analyze?\n").lower() | conditional_block | |
udacity_project_script.py | month_dict = {"Jan":1, "Feb":2, "Mar":3, "Apr":4, "May":5, "Jun":6}
if month == 'all_months' and day != 'all_days': # filter just by day
day = day_dict.get(day)
df = data[data['weekday'] == day]
elif day == 'all_days' and month != 'all_months': # filter just by month
month = month_dict... | i = -1
while True:
i+=1
curious = input("Do you want to see five entries of raw data? Type 'yes' or 'no' \n")
if curious.lower() != 'yes':
break
else:
print(str(df.iloc[0+5*i:5+5*i, :6].to_json(orient = 'records',date_format = 'iso')).replace('},{', "\n\n").re... | identifier_body | |
udacity_project_script.py | format='%Y-%m-%d %H:%M:%S')
data['weekday'] = data['Start Time'].dt.dayofweek #0 - monday
data['month'] = data['Start Time'].dt.month #1 - january
data['hour'] = data['Start Time'].dt.hour # 1 - hour 1
day_dict = {"Mon":0, "Tue":1, "Wed":2, "Thu":3, "Fry":4, "Sat":5, "Sun":6}
month_dict = {"Jan"... | def show_entries_washington(df): # no info on gender and age for washington
i = -1
while True: | random_line_split | |
deps.rs | (
&self,
target_id: Identifier,
) -> Result<Vec<Target>> {
let graph = &self.graph;
let target_ix = *self
.id_to_ix_map
.get(&target_id)
.ok_or_else(|| UserError::NoSuchTarget(target_id))?;
let depth_map = util::generate_depth_map(graph, t... | (
graph: &mut DependencyDag,
id_to_ix_map: &mut HashMap<Identifier, Nx>,
dependency_identifier: Identifier,
) {
id_to_ix_map
.entry(dependency_identifier.clone())
.or_insert_with(|| {
// `.add_node()` returns node's index
graph.... | add_leaf_node | identifier_name |
deps.rs | _nodes(graph.graph())?;
let obsolete_targets =
util::find_obsolete_targets(graph.graph(), &obsolete_leaf_nodes);
util::get_target_sequence(graph.graph(), &depth_map, &obsolete_targets)
}
}
mod util {
use std::collections::{HashMap, VecDeque};
use super::*;
use daggy::petg... | random_line_split | ||
deps.rs | (
&self,
target_id: Identifier,
) -> Result<Vec<Target>> {
let graph = &self.graph;
let target_ix = *self
.id_to_ix_map
.get(&target_id)
.ok_or_else(|| UserError::NoSuchTarget(target_id))?;
let depth_map = util::generate_depth_map(graph, t... | while let Some(target_ix) = queue.pop_front() {
let has_just_been_found = obsolete_ixs.insert(target_ix);
if has_just_been_found {
let dependants = graph
.neighbors_directed(target_ix, Direction::Incoming);
queu... | {
// reverse short circuiting bfs:
// skip the dependants of the targets
// that have already been marked as obsolete
let mut queue = VecDeque::<Nx>::new();
let mut obsolete_ixs = HashSet::<Nx>::new();
for leaf_ix in obsolete_leaf_nodes {
// no need to clear ... | identifier_body |
list.go | ly.Progress) (*PackageList, error) {
// empty reflist
if reflist == nil {
return NewPackageList(), nil
}
result := NewPackageListWithDuplicates(false, reflist.Len())
if progress != nil {
progress.InitBar(int64(reflist.Len()), false, aptly.BarGeneralBuildPackageList)
}
err := reflist.ForEach(func(key []byt... | if err2 != nil {
return fmt.Errorf("unable to load package with key %s: %s", key, err2)
}
if progress != nil {
progress.AddBar(1)
}
return result.Add(p)
})
if progress != nil {
progress.ShutdownBar()
}
if err != nil {
return nil, err
}
return result, nil
}
// Has checks whether package is ... | random_line_split | |
list.go | .Progress) (*PackageList, error) {
// empty reflist
if reflist == nil {
return NewPackageList(), nil
}
result := NewPackageListWithDuplicates(false, reflist.Len())
if progress != nil {
progress.InitBar(int64(reflist.Len()), false, aptly.BarGeneralBuildPackageList)
}
err := reflist.ForEach(func(key []byte)... | copy(l.packagesIndex[i+1:], l.packagesIndex[i:])
l.packagesIndex[i] = p
}
return nil
}
// ForEach calls handler for each package in list
func (l *PackageList) ForEach(handler func(*Package) error) error {
var err error
for _, p := range l.packages {
err = handler(p)
if err != nil {
return err
}
}
r... | {
key := l.keyFunc(p)
existing, ok := l.packages[key]
if ok {
if !existing.Equals(p) {
return &PackageConflictError{fmt.Errorf("conflict in package %s", p)}
}
return nil
}
l.packages[key] = p
if l.indexed {
for _, provides := range p.Provides {
l.providesIndex[provides] = append(l.providesIndex[pro... | identifier_body |
list.go | }
i := sort.Search(len(l.packagesIndex), func(j int) bool { return l.lessPackages(p, l.packagesIndex[j]) })
// insert p into l.packagesIndex in position i
l.packagesIndex = append(l.packagesIndex, nil)
copy(l.packagesIndex[i+1:], l.packagesIndex[i:])
l.packagesIndex[i] = p
}
return nil
}
// ForEach call... | SearchSupported | identifier_name | |
list.go | .Progress) (*PackageList, error) {
// empty reflist
if reflist == nil {
return NewPackageList(), nil
}
result := NewPackageListWithDuplicates(false, reflist.Len())
if progress != nil {
progress.InitBar(int64(reflist.Len()), false, aptly.BarGeneralBuildPackageList)
}
err := reflist.ForEach(func(key []byte)... |
if progress != nil {
progress.AddBar(1)
}
return result.Add(p)
})
if progress != nil {
progress.ShutdownBar()
}
if err != nil {
return nil, err
}
return result, nil
}
// Has checks whether package is already in the list
func (l *PackageList) Has(p *Package) bool {
key := l.keyFunc(p)
_, ok := ... | {
return fmt.Errorf("unable to load package with key %s: %s", key, err2)
} | conditional_block |
elasticsearch.py | ) -> CapacityRequirement:
"""Estimate the capacity required for one zone given a regional desire
The input desires should be the **regional** desire, and this function will
return the zonal capacity requirement
"""
# Keep half of the cores free for background work (merging mostly)
needed_cores ... | # Generally speaking we want fewer than some number of reads per second
# hitting disk per instance. If we don't have many reads we don't need to
# hold much data in memory.
instance_rps = max(1, reads_per_second // rough_count)
disk_rps = instance_rps * _es_io_per_read(max(1, needed_disk // rough_c... | rough_count = math.ceil(needed_cores / instance.cpu)
| random_line_split |
elasticsearch.py | ) -> CapacityRequirement:
"""Estimate the capacity required for one zone given a regional desire
The input desires should be the **regional** desire, and this function will
return the zonal capacity requirement
"""
# Keep half of the cores free for background work (merging mostly)
needed_cores ... | estimated_working_set=desires.data_shape.estimated_working_set_percent,
# Elasticsearch has looser latency SLOs, target the 90th percentile of disk
# latency to keep in RAM.
target_percentile=0.90,
).mid
requirement = _estimate_elasticsearch_requirement(
instance=instanc... | if instance.cpu < 2 or instance.ram_gib < 14:
return None
# (FIXME): Need elasticsearch input
# Right now Elasticsearch doesn't deploy to cloud drives, just adding this
# here and leaving the capability to handle cloud drives for the future
if instance.drive is None:
return None
rp... | identifier_body |
elasticsearch.py | ) -> CapacityRequirement:
"""Estimate the capacity required for one zone given a regional desire
The input desires should be the **regional** desire, and this function will
return the zonal capacity requirement
"""
# Keep half of the cores free for background work (merging mostly)
needed_cores ... |
else:
cluster.cluster_params = params
# pylint: disable=too-many-locals
def _estimate_elasticsearch_cluster_zonal(
instance: Instance,
drive: Drive,
desires: CapacityDesires,
zones_per_region: int = 3,
copies_per_region: int = 3,
max_local_disk_gib: int = 4096,
max_regional_si... | cluster.cluster_params.update(params) | conditional_block |
elasticsearch.py | ) -> CapacityRequirement:
"""Estimate the capacity required for one zone given a regional desire
The input desires should be the **regional** desire, and this function will
return the zonal capacity requirement
"""
# Keep half of the cores free for background work (merging mostly)
needed_cores ... | (CapacityModel):
@staticmethod
def capacity_plan(
instance: Instance,
drive: Drive,
context: RegionContext,
desires: CapacityDesires,
extra_model_arguments: Dict[str, Any],
) -> Optional[CapacityPlan]:
# (FIXME): Need elasticsearch input
# TODO: Use du... | NflxElasticsearchCapacityModel | identifier_name |
script.js | update(root);
function expand(d)
{
if (d._children)
{
d.children = d._children;
d.children.forEach(expand);
d._children = null;
}
}
};
// collapse the node and all it's children
chart.collap... | return "lightsteelblue";
}
})
.attr('cursor', 'pointer')
.style("stroke", function(d)
{
if (d.data.class === "found")
{
return "#ff4136"; //red
}
;
... | }
else if(d._children)
{ | random_line_split |
script.js | .attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
// declares a tree layout and assigns the size of the... | {
var data, root, treemap, svg,
i = 0,
duration = 650,
// margin = {top: 20, right: 10, bottom: 20, left: 50},
margin = {top: 0, right: 0, bottom: 80, left: 50},
width = 960 - 4 - margin.left - margin.right, // fitting in block frame
height = 800 - 4 - margin.top - ma... | identifier_body | |
script.js | )
{
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
chart.collapseTree = function(value)
{
root.children.forEach(collapse);
update(root);
function collapse(d)
{
if (d.children)
... | {
console.log("There are children here, tralalalala");
} | conditional_block | |
script.js | update(root);
function expand(d)
{
if (d._children)
{
d.children = d._children;
d.children.forEach(expand);
d._children = null;
}
}
};
// collapse the node and all it's children
chart.collap... | (d)
{
toggleChildren(d);
printNodeInfo(d);
}
function toggleChildren(d)
{
if (d.children)
{
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
... | click | identifier_name |
data.py | return self._word_to_id[UNKNOWN_TOKEN]
return self._word_to_id[word]
def id2word(self, word_id):
"""Returns the word (string) corresponding to an id (integer)."""
if word_id not in self._id_to_word:
raise ValueError('Id not found in vocab: %d' % word_id)
return self._id_to_word[word_id]
def size(self)... | random_line_split | ||
data.py | writer.writerow({"word": self._id_to_word[i]})
def set_glove_embedding(self,fpath,embedding_dim):
""" Creates glove embedding_matrix from file path"""
emb = np.random.randn(self._count,embedding_dim)
# tf.logging.info(emb[0])
with open(fpath) as f: #python 3.x support
for k,line in enumerate(f):
fi... |
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
#new_tokens.append(self.index_map_glove_to_bert['[UNK]'])
new_token = new_token + self.index_map_glove_to_bert['[UNK]']
else:
sub_tokens_bert = [self.bert_vocab[s] for s in... | substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1 | conditional_block |
data.py | _bert
self.index_map_glove_to_bert[i] = new_tokens
tf.logging.info(not_found)
def convert_glove_to_bert_indices(self, token_ids):
"""
Converts words to their respective word-piece tokenized indices
token_ids : ids from the word
"""
new_tokens = [self.bert_vocab['[CLS]']] #As pert the bert re... | abstract2sents | identifier_name | |
data.py | for line in vocab_f:
pieces = line.split()
if len(pieces) != 2:
print ('Warning: incorrectly formatted line in vocabulary file: %s\n' % line)
continue
w = pieces[0]
if w in [SENTENCE_START, SENTENCE_END, UNKNOWN_TOKEN, PAD_TOKEN, START_DECODING, STOP_DECODING]:
raise Exception(
'... | """Vocabulary class for mapping between words and ids (integers)"""
def __init__(self, vocab_file, max_size):
"""Creates a vocab of up to max_size words, reading from the vocab_file. If max_size is 0, reads the entire vocab file.
Args:
vocab_file: path to the vocab file, which is assumed to contain "<word> <fr... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.