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 |
|---|---|---|---|---|
tls.go | // Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wri... | // HTTPS or TLS ports without associated virtual service
if !hasTLSMatch {
var sniHosts []string
// In case of a sidecar config with user defined port, if the user specified port is not the same as the
// service's port, then pick the service port if and only if the service has only one port. If service
// h... | random_line_split | |
tls.go | // Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wri... |
}
// HTTPS or TLS ports without associated virtual service
if !hasTLSMatch {
var sniHosts []string
// In case of a sidecar config with user defined port, if the user specified port is not the same as the
// service's port, then pick the service port if and only if the service has only one port. If service
... | {
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 | // Copyright Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in wri... | (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 | use cssparser::{self, BasicParseError, CompactCowStr, DeclarationListParser, Parser, ParseError, ParserInput, Token};
use orbclient::Color;
use std::collections::HashSet;
use std::sync::Arc;
use std::mem;
use std::ops::Add;
use std::path::Path;
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
static DEFA... | (data: u32) -> Color {
Color { data: 0xFF000000 | data }
}
| hex | identifier_name |
theme.rs | use cssparser::{self, BasicParseError, CompactCowStr, DeclarationListParser, Parser, ParseError, ParserInput, Token};
use orbclient::Color;
use std::collections::HashSet;
use std::sync::Arc;
use std::mem;
use std::ops::Add;
use std::path::Path;
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
static DEFA... | ,
_ => return Err(CustomParseError::InvalidColorHex(hash.into_owned()).into()),
}
}
t => {
let basic_error = BasicParseError::UnexpectedToken(t);
return Err(basic_error.into());
}
})
}
fn parse(s: &str) -> Vec<Rule> {
let mut input... | {
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 | use cssparser::{self, BasicParseError, CompactCowStr, DeclarationListParser, Parser, ParseError, ParserInput, Token};
use orbclient::Color;
use std::collections::HashSet;
use std::sync::Arc;
use std::mem;
use std::ops::Add;
use std::path::Path;
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
static DEFA... | }
#[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 | use cssparser::{self, BasicParseError, CompactCowStr, DeclarationListParser, Parser, ParseError, ParserInput, Token};
use orbclient::Color;
use std::collections::HashSet;
use std::sync::Arc;
use std::mem;
use std::ops::Add;
use std::path::Path;
use std::fs::File;
use std::io::BufReader;
use std::io::Read;
static DEFA... |
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 |
#[cfg(target_os = "linux")]
pub mod dynamic_lib_loading{
#![allow(unused_imports)]
#![allow(non_camel_case_types)]
#![allow(dead_code)]
use std::ffi::CString;
use std::ptr;
use std::os::raw::{c_int, c_char, c_void};
//
//This is a lib of dlopen and dlclose using rust
//Comments copied from the following source file... |
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 |
#[cfg(target_os = "linux")]
pub mod dynamic_lib_loading{
#![allow(unused_imports)]
#![allow(non_camel_case_types)]
#![allow(dead_code)]
use std::ffi::CString;
use std::ptr;
use std::os::raw::{c_int, c_char, c_void};
//
//This is a lib of dlopen and dlclose using rust
//Comments copied from the following source file... | (){
//TODO rename
use memory_tools::{GlobalStorage, DyArray};
let mut gls = GlobalStorage::new();
let mut a = gls.alloc(123.09f32);
let mut dy = DyArray::<u32>::new(&mut gls);
let mut b = gls.alloc(123i32);
dy.push(12);
dy.push(123);
dy.push(1231);
//let a = dy.get(0);
//... | global_storage_vec2 | identifier_name |
lib.rs | #[cfg(target_os = "linux")]
pub mod dynamic_lib_loading{
#![allow(unused_imports)]
#![allow(non_camel_case_types)]
#![allow(dead_code)]
use std::ffi::CString;
use std::ptr;
use std::os::raw::{c_int, c_char, c_void};
//
//This is a lib of dlopen and dlclose using rust
//Comments copied from the following source files... | 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 | use serde_json::Value;
use specs::prelude::*;
use std::collections::HashMap;
use std::path::Path;
use super::super::super::prelude::{
hex_color, Attribute, Attributes, BackgroundColor, CanBeEmpty, Color,
GlobalTileIndex, InventoryLayer, ItemRecord, Layer, LayerData, Object,
Position, Screen, Sprite, Tiledmap, To... | }
}
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 | use serde_json::Value;
use specs::prelude::*;
use std::collections::HashMap;
use std::path::Path;
use super::super::super::prelude::{
hex_color, Attribute, Attributes, BackgroundColor, CanBeEmpty, Color,
GlobalTileIndex, InventoryLayer, ItemRecord, Layer, LayerData, Object,
Position, Screen, Sprite, Tiledmap, To... | (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 | use serde_json::Value;
use specs::prelude::*;
use std::collections::HashMap;
use std::path::Path;
use super::super::super::prelude::{
hex_color, Attribute, Attributes, BackgroundColor, CanBeEmpty, Color,
GlobalTileIndex, InventoryLayer, ItemRecord, Layer, LayerData, Object,
Position, Screen, Sprite, Tiledmap, To... |
_ => 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 | use serde_json::Value;
use specs::prelude::*;
use std::collections::HashMap;
use std::path::Path;
use super::super::super::prelude::{
hex_color, Attribute, Attributes, BackgroundColor, CanBeEmpty, Color,
GlobalTileIndex, InventoryLayer, ItemRecord, Layer, LayerData, Object,
Position, Screen, Sprite, Tiledmap, To... |
}
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 | package main
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/opsgenie/opsgenie-go-sdk-v2/alert"
"github.com/opsgenie/opsgenie-go-sdk-v2/client"
"github.com/sensu-community/sensu-plugin-sdk/sensu"
"github.com/sensu-community/sensu-plugin-sdk/templates"
"github.com/sensu/sensu-go/types"... |
// time func returns only the first n bytes of a string
func trim(s string, n int) string {
if len(s) > n {
return s[:n]
}
return s
}
| {
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 | package main
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/opsgenie/opsgenie-go-sdk-v2/alert"
"github.com/opsgenie/opsgenie-go-sdk-v2/client"
"github.com/sensu-community/sensu-plugin-sdk/sensu"
"github.com/sensu-community/sensu-plugin-sdk/templates"
"github.com/sensu/sensu-go/types"... | },
{
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 | package main
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/opsgenie/opsgenie-go-sdk-v2/alert"
"github.com/opsgenie/opsgenie-go-sdk-v2/client"
"github.com/sensu-community/sensu-plugin-sdk/sensu"
"github.com/sensu-community/sensu-plugin-sdk/templates"
"github.com/sensu/sensu-go/types"... |
// 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 | package main
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/opsgenie/opsgenie-go-sdk-v2/alert"
"github.com/opsgenie/opsgenie-go-sdk-v2/client"
"github.com/sensu-community/sensu-plugin-sdk/sensu"
"github.com/sensu-community/sensu-plugin-sdk/templates"
"github.com/sensu/sensu-go/types"... | (alertClient *alert.Client, event *types.Event) (string, error) {
_, title, _ := parseEventKeyTags(event)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
fmt.Printf("Checking for alert %s \n", title)
getResult, err := alertClient.Get(ctx, &alert.GetAlertRequest{
Identifier... | getAlert | identifier_name |
pages.py | """
Page objects for interacting with the test site.
"""
from __future__ import absolute_import
import os
import time
from bok_choy.page_object import PageObject
from bok_choy.promise import EmptyPromise
from bok_choy.javascript import js_defined, requirejs, wait_for_js
class SitePage(PageObject):
"""
Base c... | (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 | """
Page objects for interacting with the test site.
"""
from __future__ import absolute_import
import os
import time
from bok_choy.page_object import PageObject
from bok_choy.promise import EmptyPromise
from bok_choy.javascript import js_defined, requirejs, wait_for_js
class SitePage(PageObject):
"""
Base c... | 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 | """
Page objects for interacting with the test site.
"""
from __future__ import absolute_import
import os
import time
from bok_choy.page_object import PageObject
from bok_choy.promise import EmptyPromise
from bok_choy.javascript import js_defined, requirejs, wait_for_js
class SitePage(PageObject):
"""
Base c... |
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 | """
Page objects for interacting with the test site.
"""
from __future__ import absolute_import
import os
import time
from bok_choy.page_object import PageObject
from bok_choy.promise import EmptyPromise
from bok_choy.javascript import js_defined, requirejs, wait_for_js
class SitePage(PageObject):
"""
Base c... |
@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 | import numpy as np
import sys
sys.path.append("game/")
import skimage
from skimage import transform, color, exposure
import keras
from keras.models import Sequential, Model, load_model
from keras.layers import Dense, Flatten, Activation, Input
from keras.layers.convolutional import Convolution2D
from keras.optimizers i... |
EPISODE += 1
| model.save("saved_models/model_updates" + str(EPISODE)) | conditional_block |
Train_Trader.py | import numpy as np
import sys
sys.path.append("game/")
import skimage
from skimage import transform, color, exposure
import keras
from keras.models import Sequential, Model, load_model
from keras.layers import Dense, Flatten, Activation, Input
from keras.layers.convolutional import Convolution2D
from keras.optimizers i... | 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 | import numpy as np
import sys
sys.path.append("game/")
import skimage
from skimage import transform, color, exposure
import keras
from keras.models import Sequential, Model, load_model
from keras.layers import Dense, Flatten, Activation, Input
from keras.layers.convolutional import Convolution2D
from keras.optimizers i... |
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 | import numpy as np
import sys
sys.path.append("game/")
import skimage
from skimage import transform, color, exposure
import keras
from keras.models import Sequential, Model, load_model
from keras.layers import Dense, Flatten, Activation, Input
from keras.layers.convolutional import Convolution2D
from keras.optimizers i... | (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 | # -*- coding: utf-8 -*-
"""
# Task 1
"""
# Commented out IPython magic to ensure Python compatibility.
#import all libraries we will use for task 1
# %pylab inline --no-import-all
import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
from sklearn.model_selection import train_test_spli... | (data):
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 = []
#cr... | image_crop | identifier_name |
code.py | # -*- coding: utf-8 -*-
"""
# Task 1
"""
# Commented out IPython magic to ensure Python compatibility.
#import all libraries we will use for task 1
# %pylab inline --no-import-all
import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
from sklearn.model_selection import train_test_spli... |
testing_cropped = image_crop(testing_filtered)
print(len(testing_cropped)) #10000 images
# let's see an example letter from testing_cropped dataset
plt.imshow(testing_cropped[420][0])
plt.show()
#most of images are separated into 4 letters, but still many are into 3 or 5 letters
l=[]
for i in range(len(testing_crop... | 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 | # -*- coding: utf-8 -*-
"""
# Task 1
"""
# Commented out IPython magic to ensure Python compatibility.
#import all libraries we will use for task 1
# %pylab inline --no-import-all
import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
from sklearn.model_selection import train_test_spli... |
if bboxes[j][2] >= 30:
split.append(j)
#modifying bboxes to get half w and move x to (x + w/2)
for g in split:
bboxes[g] = (bboxes[g][0], bboxes[g][1], int(bboxes[g][2]/2), bboxes[g][3])
modified_bboxes = bboxes[g]
modified_bboxes = (int(bboxes[g][0]) + int(bboxes[g][2]), int(... | to_remove.append(bboxes[j]) | conditional_block |
code.py | # -*- coding: utf-8 -*-
"""
# Task 1
"""
# Commented out IPython magic to ensure Python compatibility.
#import all libraries we will use for task 1
# %pylab inline --no-import-all
import numpy as np
import matplotlib.pyplot as plt
from keras.models import load_model
from sklearn.model_selection import train_test_spli... | imbw1 = remove_small_objects(imbw, 10, connectivity=1)
roi = imbw1
roi = roi.reshape((roi.shape[0],roi.shape[1],1))
roi = tf.image.resize_with_crop_or_pad(roi, 28, 28).numpy()
image = roi.reshape(28, 28)
pre = model.predict(image.reshape(-1,28,28,1))
for i in pre:
'''i is the pro... | for sample in testing_cropped[i]:
imbw = sample > threshold_local(sample, block_size, method = 'mean') | random_line_split |
longestCommonSubsequence.py | #!/usr/bin/env python
__author__ = 'greg'
from copy import deepcopy
import numpy as np
import matplotlib.pyplot as plt
import datetime
import os
import itertools
#important cases
# ('gold but black', 'gold out flack', 'Gold ')
# [4, 3, 2, 1]
# [8, 3, 2, 1]
# [4, 3, 2, 1]
# [False, True, False]
# [['g', 'old ', 'but bl... | 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 | #!/usr/bin/env python
__author__ = 'greg'
from copy import deepcopy
import numpy as np
import matplotlib.pyplot as plt
import datetime
import os
import itertools
#important cases
# ('gold but black', 'gold out flack', 'Gold ')
# [4, 3, 2, 1]
# [8, 3, 2, 1]
# [4, 3, 2, 1]
# [False, True, False]
# [['g', 'old ', 'but bl... | (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 | #!/usr/bin/env python
__author__ = 'greg'
from copy import deepcopy
import numpy as np
import matplotlib.pyplot as plt
import datetime
import os
import itertools
#important cases
# ('gold but black', 'gold out flack', 'Gold ')
# [4, 3, 2, 1]
# [8, 3, 2, 1]
# [4, 3, 2, 1]
# [False, True, False]
# [['g', 'old ', 'but bl... |
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 | #!/usr/bin/env python
__author__ = 'greg'
from copy import deepcopy
import numpy as np
import matplotlib.pyplot as plt
import datetime
import os
import itertools
#important cases
# ('gold but black', 'gold out flack', 'Gold ')
# [4, 3, 2, 1]
# [8, 3, 2, 1]
# [4, 3, 2, 1]
# [False, True, False]
# [['g', 'old ', 'but bl... |
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 | package telegram
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"log"
)
// SerializeRequestMessage serializes the request message to w.
func SerializeRequestMessage(w io.Writer, rm RequestMessage) (int, error) {
msg := string(StartChar) +
string(RequestCommandChar) +
rm.deviceAddress +
string(EndChar) +
... | 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 | package telegram
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"log"
)
// SerializeRequestMessage serializes the request message to w.
func SerializeRequestMessage(w io.Writer, rm RequestMessage) (int, error) {
msg := string(StartChar) +
string(RequestCommandChar) +
rm.deviceAddress +
string(EndChar) +
... |
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 | package telegram
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"log"
)
// SerializeRequestMessage serializes the request message to w.
func SerializeRequestMessage(w io.Writer, rm RequestMessage) (int, error) {
msg := string(StartChar) +
string(RequestCommandChar) +
rm.deviceAddress +
string(EndChar) +
... |
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 | package telegram
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"log"
)
// SerializeRequestMessage serializes the request message to w.
func SerializeRequestMessage(w io.Writer, rm RequestMessage) (int, error) {
msg := string(StartChar) +
string(RequestCommandChar) +
rm.deviceAddress +
string(EndChar) +
... | (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 | // 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 {
anyhow::{format_err, Error},
fidl::encoding::Decodable as FidlDecodable,
fidl::endpoints::{create_proxy, create_request_stream},
fidl... | (
&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 | // 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 {
anyhow::{format_err, Error},
fidl::encoding::Decodable as FidlDecodable,
fidl::endpoints::{create_proxy, create_request_stream},
fidl... | }
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 | // 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 {
anyhow::{format_err, Error},
fidl::encoding::Decodable as FidlDecodable,
fidl::endpoints::{create_proxy, create_request_stream},
fidl... | 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 | // 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 {
anyhow::{format_err, Error},
fidl::encoding::Decodable as FidlDecodable,
fidl::endpoints::{create_proxy, create_request_stream},
fidl... |
}
| {} | identifier_body |
zhtta.rs | //
// zhtta.rs
//
// Starting code for PA3
// Revised to run on Rust 1.0.0 nightly - built 02-21
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// Brandeis University - cs146a Spring 2015
// Dimokritos Stamatakis and Brionne Godby
// Ve... |
// 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 | //
// zhtta.rs
//
// Starting code for PA3
// Revised to run on Rust 1.0.0 nightly - built 02-21
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// Brandeis University - cs146a Spring 2015
// Dimokritos Stamatakis and Brionne Godby
// Ve... | });
}
});
}
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 | //
// zhtta.rs
//
// Starting code for PA3
// Revised to run on Rust 1.0.0 nightly - built 02-21
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// Brandeis University - cs146a Spring 2015
// Dimokritos Stamatakis and Brionne Godby
// Ve... | rogram: &str) {
println!("Usage: {} [options]", program);
println!("--ip \tIP address, \"{}\" by default.", IP);
println!("--port \tport number, \"{}\" by default.", PORT);
println!("--www \tworking directory, \"{}\" by default", WWW_DIR);
println!("-h --help \tUsage");
... | int_usage(p | identifier_name |
zhtta.rs | //
// zhtta.rs
//
// Starting code for PA3
// Revised to run on Rust 1.0.0 nightly - built 02-21
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// Brandeis University - cs146a Spring 2015
// Dimokritos Stamatakis and Brionne Godby
// Ve... | lse {
IP.to_owned()
};
let port:usize = if matches.opt_present("port") {
let input_port = matches.opt_str("port").expect("Invalid port number?").trim().parse::<usize>().ok();
match input_port {
Some(port) => port,
None => panic!("Inva... | matches.opt_str("ip").expect("invalid ip address?").to_owned()
} e | conditional_block |
176_main_448.py | from model.DFL import DFL_VGG16
from utils.util import *
from utils.transform import *
from train import *
from validate import *
from utils.init import *
import sys
import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import numpy... |
if __name__ == '__main__':
main()
| 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 | from model.DFL import DFL_VGG16
from utils.util import *
from utils.transform import *
from train import *
from validate import *
from utils.init import *
import sys
import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import numpy... | ():
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 | from model.DFL import DFL_VGG16
from utils.util import *
from utils.transform import *
from train import *
from validate import *
from utils.init import *
import sys
import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import numpy... |
if __name__ == '__main__':
main()
| 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 | from model.DFL import DFL_VGG16
from utils.util import *
from utils.transform import *
from train import *
from validate import *
from utils.init import *
import sys
import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import numpy... | model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
print('DFL-CNN <==> Part2 : Load Network <==> Continue from {} epoch {}'.format(args.resume,
... | args.start_epoch = checkpoint['epoch']
best_prec1 = checkpoint['best_prec1'] | random_line_split |
ansi_up.ts | /* ansi_up.js
* author : Dru Nelson
* license : MIT
* http://github.com/drudru/ansi_up
*/
"use strict";
interface AU_Color
{
rgb:number[];
class_name:string;
}
// Represents the output of process_ansi(): a snapshot of the AnsiUp state machine
// at a given point in time, which wraps a fragment of text. T... |
}
}
return this.with_state(orig_txt);
}
}
| {
// 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 | /* ansi_up.js
* author : Dru Nelson
* license : MIT
* http://github.com/drudru/ansi_up
*/
"use strict";
interface AU_Color
{
rgb:number[];
class_name:string;
}
// Represents the output of process_ansi(): a snapshot of the AnsiUp state machine
// at a given point in time, which wraps a fragment of text. T... | // Ok - we have a valid "SGR" (Select Graphic Rendition)
let sgr_cmds = matches[2].split(';');
// Each of these params affects the SGR state
// Why do we shift through the array instead of a forEach??
// ... because some commands consume the params that follow !
while (sgr_cmds.le... | random_line_split | |
ansi_up.ts | /* ansi_up.js
* author : Dru Nelson
* license : MIT
* http://github.com/drudru/ansi_up
*/
"use strict";
interface AU_Color
{
rgb:number[];
class_name:string;
}
// Represents the output of process_ansi(): a snapshot of the AnsiUp state machine
// at a given point in time, which wraps a fragment of text. T... |
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 | /* ansi_up.js
* author : Dru Nelson
* license : MIT
* http://github.com/drudru/ansi_up
*/
"use strict";
interface AU_Color
{
rgb:number[];
class_name:string;
}
// Represents the output of process_ansi(): a snapshot of the AnsiUp state machine
// at a given point in time, which wraps a fragment of text. T... | ():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 | package docker
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/containers/image/docker/reference"
"github.com/containers/image/pkg/docker/config"
"github.com/containers/image/pkg/tlsclientconfig"
"... | context.Context, realm, service, scope string) (*bearerToken, error) {
authReq, err := http.NewRequest("GET", realm, nil)
if err != nil {
return nil, err
}
authReq = authReq.WithContext(ctx)
getParams := authReq.URL.Query()
if c.username != "" {
getParams.Add("account", c.username)
}
if service != "" {
g... | earerToken(ctx | identifier_name |
docker_client.go | package docker
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/containers/image/docker/reference"
"github.com/containers/image/pkg/docker/config"
"github.com/containers/image/pkg/tlsclientconfig"
"... | return true
}
isV1 := pingV1("https")
if !isV1 && c.sys != nil && c.sys.DockerInsecureSkipTLSVerify {
isV1 = pingV1("http")
}
if isV1 {
err = ErrV1NotSupported
}
}
return err
}
// getExtensionsSignatures returns signatures from the X-Registry-Supports-Signatures API extension,
// using the original... | return false
}
| conditional_block |
docker_client.go | package docker
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/containers/image/docker/reference"
"github.com/containers/image/pkg/docker/config"
"github.com/containers/image/pkg/tlsclientconfig"
"... | // 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 | package docker
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/containers/image/docker/reference"
"github.com/containers/image/pkg/docker/config"
"github.com/containers/image/pkg/tlsclientconfig"
"... | we're using the challenges from the /v2/ ping response and not the one from the destination
// URL in this request because:
//
// 1) docker does that as well
// 2) gcr.io is sending 401 without a WWW-Authenticate header in the real request
//
// debugging: https://github.com/containers/image/pull/211#issuecomment-2734... | 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 | jQuery(function($) {
"use strict";
/**
* Bootstrap Tooltip
*/
$('[data-toggle="tooltip"]').tooltip();
/**
* Sticky Header
*/
$(window).scroll(function(){
if( $(window).scrollTop() > 10 ){
$('.navbar').addClass('navbar-sticky')
} else {
$('.navbar').removeClass('na... | $(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 | jQuery(function($) {
"use strict";
/**
* Bootstrap Tooltip
*/
$('[data-toggle="tooltip"]').tooltip();
/**
* Sticky Header
*/
$(window).scroll(function(){
if( $(window).scrollTop() > 10 ){
$('.navbar').addClass('navbar-sticky')
} else {
$('.navbar').removeClass('na... |
/**
* 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 | jQuery(function($) {
"use strict";
/**
* Bootstrap Tooltip
*/
$('[data-toggle="tooltip"]').tooltip();
/**
* Sticky Header
*/
$(window).scroll(function(){
if( $(window).scrollTop() > 10 ){
$('.navbar').addClass('navbar-sticky')
} else {
$('.navbar').removeClass('na... |
});
$(".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 | jQuery(function($) {
"use strict";
/**
* Bootstrap Tooltip
*/
$('[data-toggle="tooltip"]').tooltip();
/**
* Sticky Header
*/
$(window).scroll(function(){
if( $(window).scrollTop() > 10 ){
$('.navbar').addClass('navbar-sticky')
} else {
$('.navbar').removeClass('na... | ($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 | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package recombine // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/transformer/recombine"
import (
"bytes"
"context"
"fmt"
"sync"
"time"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/... | () {
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 | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package recombine // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/transformer/recombine"
import (
"bytes"
"context"
"fmt"
"sync"
"time"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/... | }
// 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 | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package recombine // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/transformer/recombine"
import (
"bytes"
"context"
"fmt"
"sync"
"time"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/... |
func (r *Transformer) matchIndicatesFirst() bool {
return r.matchFirstLine
}
func (r *Transformer) matchIndicatesLast() bool {
return !r.matchFirstLine
}
// addToBatch adds the current entry to the current batch of entries that will be combined
func (r *Transformer) addToBatch(_ context.Context, e *entry.Entry, s... | {
// 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 | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package recombine // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/transformer/recombine"
import (
"bytes"
"context"
"fmt"
"sync"
"time"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/... |
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 | package document
import (
"bytes"
"go/ast"
"go/doc"
"go/parser"
"go/token"
"strings"
"time"
)
// Module go mod info type
type Module struct {
Path string `json:",omitempty"` // module path
Version string `json:",omitempty"` // module version
Versions []string `json:",omitempty"` // a... | (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 | package document
import (
"bytes"
"go/ast"
"go/doc"
"go/parser"
"go/token"
"strings"
"time"
)
// Module go mod info type
type Module struct {
Path string `json:",omitempty"` // module path
Version string `json:",omitempty"` // module version
Versions []string `json:",omitempty"` // a... |
// --------------------------------------------------------------------
// TypeFields get type fields
func TypeFields(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); o... | {
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 | package document
import (
"bytes"
"go/ast"
"go/doc"
"go/parser"
"go/token"
"strings"
"time"
)
// Module go mod info type
type Module struct {
Path string `json:",omitempty"` // module path
Version string `json:",omitempty"` // module version
Versions []string `json:",omitempty"` // a... |
// 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 | package document
import (
"bytes"
"go/ast"
"go/doc"
"go/parser"
"go/token"
"strings"
"time"
)
// Module go mod info type
type Module struct {
Path string `json:",omitempty"` // module path
Version string `json:",omitempty"` // module version
Versions []string `json:",omitempty"` // a... |
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 | // +build !cassandra
// Copyright (C) 2017 ScyllaDB
package gocql
import (
"encoding/binary"
"encoding/json"
"fmt"
"io"
"sort"
"strconv"
"strings"
"text/template"
)
// ToCQL returns a CQL query that ca be used to recreate keyspace with all
// user defined types, tables, indexes, functions, aggregates and vie... |
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 | // +build !cassandra
// Copyright (C) 2017 ScyllaDB
package gocql
import (
"encoding/binary"
"encoding/json"
"fmt"
"io"
"sort"
"strconv"
"strings"
"text/template"
)
// ToCQL returns a CQL query that ca be used to recreate keyspace with all
// user defined types, tables, indexes, functions, aggregates and vie... |
func (h toCQLHelpers) tableExtensionsToCQL(extensions map[string]interface{}) ([]string, error) {
exts := map[string]interface{}{}
if blob, ok := extensions["scylla_encryption_options"]; ok {
encOpts := &scyllaEncryptionOptions{}
if err := encOpts.UnmarshalBinary(blob.([]byte)); 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 | // +build !cassandra
// Copyright (C) 2017 ScyllaDB
package gocql
import (
"encoding/binary"
"encoding/json"
"fmt"
"io"
"sort"
"strconv"
"strings"
"text/template"
)
// ToCQL returns a CQL query that ca be used to recreate keyspace with all
// user defined types, tables, indexes, functions, aggregates and vie... | "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 | // +build !cassandra
// Copyright (C) 2017 ScyllaDB
package gocql
import (
"encoding/binary"
"encoding/json"
"fmt"
"io"
"sort"
"strconv"
"strings"
"text/template"
)
// ToCQL returns a CQL query that ca be used to recreate keyspace with all
// user defined types, tables, indexes, functions, aggregates and vie... | (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 | import axios, { AxiosRequestConfig, CancelTokenSource, CancelToken, AxiosInstance, AxiosResponse, AxiosError } from 'axios'
import isRetryAllowed from 'is-retry-allowed'
import extend from 'js-cool/lib/extend'
import getRandomStr from 'js-cool/lib/getRandomStr'
export const namespace = 'axios-extend'
const SAFE_HTTP_M... | 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 | import axios, { AxiosRequestConfig, CancelTokenSource, CancelToken, AxiosInstance, AxiosResponse, AxiosError } from 'axios'
import isRetryAllowed from 'is-retry-allowed'
import extend from 'js-cool/lib/extend'
import getRandomStr from 'js-cool/lib/getRandomStr'
export const namespace = 'axios-extend'
const SAFE_HTTP_M... | 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 | import axios, { AxiosRequestConfig, CancelTokenSource, CancelToken, AxiosInstance, AxiosResponse, AxiosError } from 'axios'
import isRetryAllowed from 'is-retry-allowed'
import extend from 'js-cool/lib/extend'
import getRandomStr from 'js-cool/lib/getRandomStr'
export const namespace = 'axios-extend'
const SAFE_HTTP_M... | 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 | import { ProductItem } from './product-item';
export let products: ProductItem[] = [
{
id: 1.1,
productId: 'phones',
name: 'Apple iPhone 11 64 GB',
price: 499.9,
description: 'The iPhone 11 is a smartphone designed, developed, and marketed by Apple Inc. It is the 13th generation, lower-priced ... | 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 | import pandas as pd
import time
import calendar
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all_months" to apply no month filter
(str) day - name o... | (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 | import pandas as pd
import time
import calendar
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all_months" to apply no month filter
(str) day - name o... |
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 | import pandas as pd
import time
import calendar
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all_months" to apply no month filter
(str) day - name o... |
# I guess the program would crash if 0+i > number of rows in the data and:
#a) i think i could prevent it somehow handling IndexError but...
#b) i find it unnecessary to do so
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)... | 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 | import pandas as pd
import time
import calendar
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all_months" to apply no month filter
(str) day - name o... | 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").replace(",", "\n").replac... | def show_entries_washington(df): # no info on gender and age for washington
i = -1
while True: | random_line_split |
deps.rs | use std::{
collections::{HashMap, HashSet},
path::PathBuf,
};
use crate::{
error::{Error, Result, UserError},
target::Target,
util::ResultIterator,
};
use daggy::{petgraph::visit::IntoNeighborsDirected, NodeIndex as Nx};
type DependencyDag = daggy::Dag<Node, ()>;
type Identifier = PathBuf;
type F... | (
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 | use std::{
collections::{HashMap, HashSet},
path::PathBuf,
};
use crate::{
error::{Error, Result, UserError},
target::Target,
util::ResultIterator,
};
use daggy::{petgraph::visit::IntoNeighborsDirected, NodeIndex as Nx};
type DependencyDag = daggy::Dag<Node, ()>;
type Identifier = PathBuf;
type F... | .map(|target| target.identifier)
.collect::<Vec<_>>();
let expected_target_sequence: Vec<PathBuf> =
vec!["b2".into(), "a2".into()];
assert_eq!(target_sequence, expected_target_sequence);
}
#[test]
fn test_find_obsolete_targets() {
// helper funct... | random_line_split | |
deps.rs | use std::{
collections::{HashMap, HashSet},
path::PathBuf,
};
use crate::{
error::{Error, Result, UserError},
target::Target,
util::ResultIterator,
};
use daggy::{petgraph::visit::IntoNeighborsDirected, NodeIndex as Nx};
type DependencyDag = daggy::Dag<Node, ()>;
type Identifier = PathBuf;
type F... |
pub(super) fn add_leaf_node(
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 no... | {
// 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 | package deb
import (
"fmt"
"sort"
"strings"
"github.com/aptly-dev/aptly/aptly"
"github.com/aptly-dev/aptly/utils"
)
// Dependency options
const (
// DepFollowSource pulls source packages when required
DepFollowSource = 1 << iota
// DepFollowSuggests pulls from suggests
DepFollowSuggests
// DepFollowRecomme... | 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 | package deb
import (
"fmt"
"sort"
"strings"
"github.com/aptly-dev/aptly/aptly"
"github.com/aptly-dev/aptly/utils"
)
// Dependency options
const (
// DepFollowSource pulls source packages when required
DepFollowSource = 1 << iota
// DepFollowSuggests pulls from suggests
DepFollowSuggests
// DepFollowRecomme... |
// 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
}
}
return err
}
// ForEachIndexed calls handler for each package in list in indexed order
func (... | {
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 | package deb
import (
"fmt"
"sort"
"strings"
"github.com/aptly-dev/aptly/aptly"
"github.com/aptly-dev/aptly/utils"
)
// Dependency options
const (
// DepFollowSource pulls source packages when required
DepFollowSource = 1 << iota
// DepFollowSuggests pulls from suggests
DepFollowSuggests
// DepFollowRecomme... | () bool {
return true
}
// SearchByKey looks up package by exact key reference
func (l *PackageList) SearchByKey(arch, name, version string) (result *PackageList) {
result = NewPackageListWithDuplicates(l.duplicatesAllowed, 0)
pkg := l.packages["P"+arch+" "+name+" "+version]
if pkg != nil {
result.Add(pkg)
}
... | SearchSupported | identifier_name |
list.go | package deb
import (
"fmt"
"sort"
"strings"
"github.com/aptly-dev/aptly/aptly"
"github.com/aptly-dev/aptly/utils"
)
// Dependency options
const (
// DepFollowSource pulls source packages when required
DepFollowSource = 1 << iota
// DepFollowSuggests pulls from suggests
DepFollowSuggests
// DepFollowRecomme... |
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 | import logging
import math
from decimal import Decimal
from typing import Any
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
from service_capacity_modeling.interface import AccessConsistency
from service_capacity_modeling.interface import AccessPattern
from ser... | # 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 | import logging
import math
from decimal import Decimal
from typing import Any
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
from service_capacity_modeling.interface import AccessConsistency
from service_capacity_modeling.interface import AccessPattern
from ser... |
class NflxElasticsearchCapacityModel(CapacityModel):
@staticmethod
def capacity_plan(
instance: Instance,
drive: Drive,
context: RegionContext,
desires: CapacityDesires,
extra_model_arguments: Dict[str, Any],
) -> Optional[CapacityPlan]:
# (FIXME): Need ela... | 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 | import logging
import math
from decimal import Decimal
from typing import Any
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
from service_capacity_modeling.interface import AccessConsistency
from service_capacity_modeling.interface import AccessPattern
from ser... |
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 | import logging
import math
from decimal import Decimal
from typing import Any
from typing import Dict
from typing import Optional
from typing import Sequence
from typing import Tuple
from service_capacity_modeling.interface import AccessConsistency
from service_capacity_modeling.interface import AccessPattern
from ser... | (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 | function tree()
{
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 -... | 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 | function tree()
|
function printNodeInfo(d)
{
var location = document.getElementById("infoField");
location.innerHTML = " name: " + d.data.name+"<br/>"
+ " value: " + d.data.value;
}
function loadOtherTree(value)
{
// remove svg
d3.select("svg").remove();
// build new tree object
myTree = tr... | {
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 | function tree()
{
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 -... |
else
{
console.log("For some reason, I don't discover hidden children");
}
update(paths[i]);
}
}
}
chart.getCurrentRoot = function()
{
return root;
}
chart.centerNode = function(d)
... | {
console.log("There are children here, tralalalala");
} | conditional_block |
script.js | function tree()
{
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 -... | (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 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
# Modifications Copyright 2017 Abigail See
#
# 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... | 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 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
# Modifications Copyright 2017 Abigail See
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses... |
if 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 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
# Modifications Copyright 2017 Abigail See
#
# 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... | (abstract):
"""Splits abstract text from datafile into list of sentences.
Args:
abstract: string containing <s> and </s> tags for starts and ends of sentences
Returns:
sents: List of sentence strings (no tags)"""
cur = 0
sents = []
while True:
try:
start_p = abstract.index(SENTENCE_START, cur)
end_p... | abstract2sents | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.