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
tae-ui.js
var originalStyles = []; // Used to store the tagged paragraphs CSSstyles var simplifyBoxIdSuffix = '-simp-text-paragraph'; // Component-related methods and behaviour function initComponent(parameters) { primaryColor = parameters.primaryColor; secondaryColor = parameters.secondaryColor; ...
} return result; } // Method used to cancel the propagation of the events // - event: the event to cancel function cancelEventPropagation(event) { event = event || window.event // cross-browser event if (event.stopPropagation) { event.stopPropagation(); // W3C standa...
{ item = simplifications[i]; console.log(item); result = result.substring(0, item.start) + createSimplifiedWordLabel(item) + result.substring(item.end, result.length); }
conditional_block
tae-ui.js
// Component-related variables var primaryColor = ''; var secondaryColor = ''; var elementsToEnhanceClassName = ''; var simplifyBoxTitle = ''; var simplifyBoxClassName = ''; var wordPropertiesClassName = ''; var synonymLabel = ''; var definitionLabel = ''; var emptyText = ''; ...
var taeUI = (function () { var instance; // Singleton Instance of the UI component var featureEnabled = false; function Singleton () {
random_line_split
tae-ui.js
'Synonyms'; definitionLabel = parameters.definitionLabel || 'Definitions'; wikipediaLabel = parameters.wikipediaLabel || 'Wikipedia'; emptyText = parameters.emptyText || 'no simplification found for the text'; taeCORE.getInstance().init({ endpoint: parameters.endpoint, ...
showSimplificationBox
identifier_name
tae-ui.js
var originalStyles = []; // Used to store the tagged paragraphs CSSstyles var simplifyBoxIdSuffix = '-simp-text-paragraph'; // Component-related methods and behaviour function initComponent(parameters) { primaryColor = parameters.primaryColor; secondaryColor = parameters.secondaryColor; ...
// // paragraphs[i].style.padding = '0px 0px 0px 8px'; // paragraphs[i].style.margin = '0px 0px 8px 0px'; paragraphs[i].setAttribute("id", paragraphName); paragraphs[i].setAttribute("onclick", "taeUI.getInstance()." + "paragraphEvent('" + paragraphName + "');"); ...
{ if (featureEnabled) return; featureEnabled = true; // Gets the tagged paragraphs the first time if (paragraphs.length === 0) { paragraphs = document.getElementsByClassName(elementsToEnhanceClassName); } // Add special format and add a couple of attributes to the paragraph...
identifier_body
data_utils.py
.long) else: all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.float) all_seq_lengths = torch.tensor([f.seq_length for f in features], dtype=torch.long) all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_...
(x): t = sum(x) new_x = f"1 * {t}, 0 * {len(x) - t}" return new_x with open('/data/lxk/NLP/github/darts-KD/data/MRPC-nas/embedding/vocab.txt') as f: vocab1 = {i:x.strip() for i, x in enumerate(f.readlines())} with open('/data/lxk/NLP/github/darts-KD/teacher_utils/teacher_model/MR...
mask_replace
identifier_name
data_utils.py
.long) else: all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.float) all_seq_lengths = torch.tensor([f.seq_length for f in features], dtype=torch.long) all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_...
input_mask += padding segment_ids += padding assert len(input_ids) == max_seq_length assert len(input_mask) == max_seq_length assert len(segment_ids) == max_seq_length if output_mode == "classification": label_id = label_map[example.label] elif outpu...
padding = [0] * (max_seq_length - len(input_ids)) input_ids += padding
random_line_split
data_utils.py
def get_tensor_data(output_mode, features, ): if output_mode == "classification": all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.long) else: all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.float) all_seq_lengths = torch.tensor([f.seq_leng...
"""A single set of features of data.""" def __init__(self, input_ids, input_mask, segment_ids, label_id, seq_length=None, guid=None): self.input_ids = input_ids self.input_mask = input_mask self.segment_ids = segment_ids self.seq_length = seq_length self.label_id = label_id ...
identifier_body
data_utils.py
.long) else: all_label_ids = torch.tensor([f.label_id for f in features], dtype=torch.float) all_seq_lengths = torch.tensor([f.seq_length for f in features], dtype=torch.long) all_input_ids = torch.tensor([f.input_ids for f in features], dtype=torch.long) all_input_mask = torch.tensor([f.input_...
else: n_classes = 1 sids = dict() tokenizer = BertTokenizer.from_pretrained('teacher_utils/bert_base_uncased', do_lower_case=True) train_examples = processor.get_train_examples(config.data_src_path) train_features = convert_examples_to_features(train_examples, label_list, ...
n_classes = len(label_list)
conditional_block
d.rs
::*; use crate::util::codejam::run_cases; impl Tile { fn to_char(self) -> char { match self { Empty => '.', Building => '#', Soldier => 'S', Turret => 'T', } } } impl From<char> for Tile { fn from(item: char) -> Self { match i...
cycle_edges.push_back(edge); debug!( "pushed Edge {:?} ", format!("{}->{}", vertex_to_string(edge.0), vertex_to_string(edge.1)) ); //adj list returns an (internal edge index, next vertex) edge = (edge.1, H.adj_list_with_edges(ed...
while !visited[edge.0] { visited.set(edge.0, true);
random_line_split
d.rs
::*; use crate::util::codejam::run_cases; impl Tile { fn to_char(self) -> char { match self { Empty => '.', Building => '#', Soldier => 'S', Turret => 'T', } } } impl From<char> for Tile { fn from(item: char) -> Self { match i...
break; } } } r } /* impl<L, R> FromIterator<(L, R)> for BiMap<L, R> { fn from_iter<I: IntoIterator<Item = (L, R)>>(iter: I) -> Self { let mut c = BiMap::new(); for i in iter { c.insert(i.0, i.1); } c } }*/ fn solve...
{ let mut r = HashSet::new(); //debug!("\nTracing {} starting at {}", location, direction); for direction in DIRECTIONS.iter() { let mut loc: GridRowColVec = location.convert(); for _ in 0..=grid.R + grid.C { loc += direction; if let Some(tile) = grid.get_value(&lo...
identifier_body
d.rs
.iter() { if soldiers_in_m.contains(&s) { H.add_edge(s, t); } } for &(s, t) in M.iter() { H.add_edge(t, s); } debug!( "Current matching M =\n{}\n", M.iter() .map(|&(u, v)| format!("{}->{}", verte...
{ return Err(err); }
conditional_block
d.rs
::*; use crate::util::codejam::run_cases; impl Tile { fn to_char(self) -> char { match self { Empty => '.', Building => '#', Soldier => 'S', Turret => 'T', } } } impl From<char> for Tile { fn from(item: char) -> Self { match i...
<'a>(case_no: u32, grid: &mut Grid<Tile>, M_soldier_limit: usize) -> String { debug!( "Solving case {}\nM={}\n{}\n", case_no, M_soldier_limit, grid ); //original solider & turret index to location map let S_map = grid .filter_by_val(&Soldier) .enumerate() .collec...
solve
identifier_name
resource_fusion_sec_azure.go
.3" ) var fusionSECAzureTemplateTags = []string{ "Microsoft.Network/loadBalancers", "Microsoft.ManagedIdentity/userAssignedIdentities", } var fusionSECAzureParams = []interface{}{ "fusionSECName", "location", "loadBalancerNetworkRg", "loadBalancerNetworkName", "loadBalancerSubnet", } var renamedFusionSECAzure...
() *schema.Resource { return &schema.Resource{ CreateContext: resourceFusionSECAzureCreate, ReadContext: resourceFusionSECAzureRead, UpdateContext: resourceFusionSECAzureUpdate, DeleteContext: resourceFusionSECAzureDelete, Schema: map[string]*schema.Schema{ "resource_group_name": { Type: sch...
resourceFusionSECAzure
identifier_name
resource_fusion_sec_azure.go
3" ) var fusionSECAzureTemplateTags = []string{ "Microsoft.Network/loadBalancers", "Microsoft.ManagedIdentity/userAssignedIdentities", } var fusionSECAzureParams = []interface{}{ "fusionSECName", "location", "loadBalancerNetworkRg", "loadBalancerNetworkName", "loadBalancerSubnet", } var renamedFusionSECAzureP...
returnedDiags = setAzureJitAccessPolicy(&parameters, d) if v, ok := d.GetOk("tags"); ok { tags := v.(map[string]interface{}) tagsMap := make(map[string]interface{}) for _, tag := range fusionSECAzureTemplateTags { tagsMap[tag] = tags } setAppParameter("tagsByResource", tagsMap) } // Error out now, ...
{ valueStr := value.(string) setAppParameter(valueStr, d.Get(templateToTFParam(valueStr, renamedFusionSECAzureParams))) }
conditional_block
resource_fusion_sec_azure.go
.3" ) var fusionSECAzureTemplateTags = []string{ "Microsoft.Network/loadBalancers", "Microsoft.ManagedIdentity/userAssignedIdentities", } var fusionSECAzureParams = []interface{}{ "fusionSECName", "location", "loadBalancerNetworkRg", "loadBalancerNetworkName", "loadBalancerSubnet", } var renamedFusionSECAzure...
"fusion_sec_name": { Description: "The name of the Fusion Storage Endpoint Collection (SEC). 0-59 alphanumeric characters only.", Type: schema.TypeString, Required: true, ValidateFunc: validateAzureManagedApplicationName, }, "load_balancer_network_rg": { Type: schema.TypeS...
{ return &schema.Resource{ CreateContext: resourceFusionSECAzureCreate, ReadContext: resourceFusionSECAzureRead, UpdateContext: resourceFusionSECAzureUpdate, DeleteContext: resourceFusionSECAzureDelete, Schema: map[string]*schema.Schema{ "resource_group_name": { Type: schema.TypeString, ...
identifier_body
resource_fusion_sec_azure.go
.3" ) var fusionSECAzureTemplateTags = []string{ "Microsoft.Network/loadBalancers", "Microsoft.ManagedIdentity/userAssignedIdentities", } var fusionSECAzureParams = []interface{}{ "fusionSECName", "location", "loadBalancerNetworkRg", "loadBalancerNetworkName", "loadBalancerSubnet", } var renamedFusionSECAzure...
Description: "This is a list of Azure group object IDs for people who are allowed to approve JIT requests", Required: true, Type: schema.TypeList, Elem: &schema.Schema{ Type: schema.TypeString, ValidateFunc: validation.IsUUID, }, }, "plan": { Type: schema.T...
Type: schema.TypeString, Required: true, }, "jit_approval_group_object_ids": {
random_line_split
iter.go
: invalid whence") } if abs < 0 { return 0, fmt.Errorf("norm: negative position") } if int(abs) >= i.rb.nsrc { i.setDone() return int64(i.p), nil } i.p = int(abs) i.multiSeg = nil i.next = i.rb.f.nextMain i.info = i.rb.f.info(i.rb.src, i.p) i.rb.ss.first(i.info) return abs, nil } // returnSlice return...
{ return i.returnSlice(inCopyStart, i.p) }
conditional_block
iter.go
(i *Iter) Seek(offset int64, whence int) (int64, error) { var abs int64 switch whence { case 0: abs = offset case 1: abs = int64(i.p) + offset case 2: abs = int64(i.rb.nsrc) + offset default: return 0, fmt.Errorf("norm: invalid whence") } if abs < 0 { return 0, fmt.Errorf("norm: negative position") ...
() { i.next = nextDone i.p = i.rb.nsrc } // Done returns true if there is no more input to process. func (i *Iter) Done() bool { return i.p >= i.rb.nsrc } // Next returns f(i.input[i.Pos():n]), where n is a boundary of i.input. // For any input a and b for which f(a) == f(b), subsequent calls // to Next will retur...
setDone
identifier_name
iter.go
(i *Iter) Seek(offset int64, whence int) (int64, error) { var abs int64 switch whence { case 0: abs = offset case 1: abs = int64(i.p) + offset case 2: abs = int64(i.rb.nsrc) + offset default: return 0, fmt.Errorf("norm: invalid whence") } if abs < 0 { return 0, fmt.Errorf("norm: negative position") ...
if i.p >= i.rb.nsrc { i.setDone() return i.returnSlice(p, i.p) } else if i.rb.src._byte(i.p) < utf8.RuneSelf { i.next = i.asciiF return i.returnSlice(p, i.p) } outp++ } else if d := i.info.Decomposition(); d != nil { // Note: If leading CCC != 0, then len(d) == 2 and last is also non-ze...
random_line_split
iter.go
(i *Iter) Seek(offset int64, whence int) (int64, error) { var abs int64 switch whence { case 0: abs = offset case 1: abs = int64(i.p) + offset case 2: abs = int64(i.rb.nsrc) + offset default: return 0, fmt.Errorf("norm: invalid whence") } if abs < 0 { return 0, fmt.Errorf("norm: negative position") ...
// nextMultiNorm is used for iterating over multi-segment decompositions // for composing normal forms. func nextMultiNorm(i *Iter) []byte { j := 0 d := i.multiSeg for j < len(d) { info := i.rb.f.info(input{bytes: d}, j) if info.BoundaryBefore() { i.rb.compose() seg := i.buf[:i.rb.flushCopy(i.buf[:])] ...
{ j := 0 d := i.multiSeg // skip first rune for j = 1; j < len(d) && !utf8.RuneStart(d[j]); j++ { } for j < len(d) { info := i.rb.f.info(input{bytes: d}, j) if info.BoundaryBefore() { i.multiSeg = d[j:] return d[:j] } j += int(info.size) } // treat last segment as normal decomposition i.next = i....
identifier_body
consulta-ine.page.ts
/app/herramientas/imagen'; import { Camera, CameraOptions } from '@ionic-native/camera/ngx'; import { LoadingService } from 'src/app/services/loading.service'; import { Cliente } from '../../tipo-identificacion/consulta-similitud-confirmacion/model/Cliente.model'; import { JsonPersonalData } from 'src/app/services/acti...
event): void { let mensajeError = ''; const file: File = $event.target.files[0]; console.log('changeListenerF'); if ((file.type !== 'image/jpeg' && file.type !== 'image/png') || (file.size > 1000000)) { mensajeError = 'Formato y/o tamaño de imagen incorrecto'; } else { const myReader: FileReader = new...
angeListenerINE($
identifier_name
consulta-ine.page.ts
/app/herramientas/imagen'; import { Camera, CameraOptions } from '@ionic-native/camera/ngx'; import { LoadingService } from 'src/app/services/loading.service'; import { Cliente } from '../../tipo-identificacion/consulta-similitud-confirmacion/model/Cliente.model'; import { JsonPersonalData } from 'src/app/services/acti...
/* this.camera.getPicture(cameraOptions) .then(file_uri => this.frontImg = file_uri, err => console.log(err)); */ this.camera.getPicture(cameraOptions).then((imageData) => { this.frontImg = 'data:image/jpeg;base64,' + imageData; this.frontImg2 = imageData; this.saveS.guardarStorageImagen...
correctOrientation: true };
random_line_split
consulta-ine.page.ts
/app/herramientas/imagen'; import { Camera, CameraOptions } from '@ionic-native/camera/ngx'; import { LoadingService } from 'src/app/services/loading.service'; import { Cliente } from '../../tipo-identificacion/consulta-similitud-confirmacion/model/Cliente.model'; import { JsonPersonalData } from 'src/app/services/acti...
goCargarDocumento() { try { const imagen = new Imagen(); const blobAnverso = imagen.convertirImagenEnBlob(this.frontImg); console.log('blobAnverso'); console.log(blobAnverso); if (blobAnverso) { this.cargarDocumento(blobAnverso, this.saveS.getBearerToken()); } else { alert('Imagen Inv...
// disable the button this.isenabled = false; this.isValidoSpinnerFront = false; } }
conditional_block
consulta-ine.page.ts
/app/herramientas/imagen'; import { Camera, CameraOptions } from '@ionic-native/camera/ngx'; import { LoadingService } from 'src/app/services/loading.service'; import { Cliente } from '../../tipo-identificacion/consulta-similitud-confirmacion/model/Cliente.model'; import { JsonPersonalData } from 'src/app/services/acti...
getImagenFront() { this.isValidoSpinnerFront = true; const options: CameraOptions = { quality: 70, destinationType: this.camera.DestinationType.DATA_URL, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE }; this.camera.getPicture(options).then((imageData) => { t...
}
identifier_body
simple_http.rs
4) Parse into socket address. // At this point we either have <host_name> or <host_name_>:<port> // `std::net::ToSocketAddrs` requires `&str` to have <host_name_>:<port> format. let mut addr = match after_auth.to_socket_addrs() { Ok(addr) => addr, Err(_) => { // Invalid socket ad...
{ use self::Error::*; match *self { InvalidUrl { .. } | HttpResponseTooShort { .. } | HttpResponseNonAsciiHello(..) | HttpResponseBadHello { .. } | HttpRespons...
identifier_body
simple_http.rs
sock.get_mut().write_all(request_bytes.as_slice()).is_ok() && sock.get_mut().flush().is_ok(); // This indicates the socket is broken so let's retry the send once with a fresh socket if !write_success { *sock.get_mut() = self.fresh_socket()?; sock.get_mut().write_all...
(self) -> SimpleHttpTransport { self.tp } } impl Default for Builder { fn default() -> Self { Builder::new() } } impl crate::Client { /// Creates a new JSON-RPC client using a bare-minimum HTTP transport. pub fn simple_http( url
build
identifier_name
simple_http.rs
we can parse. needed: usize, }, /// The HTTP response started with a HTTP/1.1 line which was not ASCII. HttpResponseNonAsciiHello(Vec<u8>), /// The HTTP response did not start with HTTP/1.1 HttpResponseBadHello { /// Actual HTTP-whatever string. actual: String, /// T...
random_line_split
DataManager.py
j]) nodename = self.id_nodename_map[pred_ent] new_out.append(nodename) elif self.index2word[each] in entity_attr_list: attr_name = self.index2word[each] cnt = 0 suc_flag = False for id...
def __init__(self, src_seq_lens, src_seqs, trg_seqs, trg_stops, src_tfs, trg_ents, trg_ents_mask, trg_seqs_ori): self.src_seq_lens = src_seq_lens self.src_seqs = src_seqs self.trg_seqs = trg_seqs self.trg_stops = trg_stops self.src_tfs = src_tfs self.num_total_seqs = len(...
identifier_body
DataManager.py
self.word2index[key] = i + 4 #PAD,UNK,GO,EOS if value >= stopword_freq_lb: stopwords_self.add(key) # to add all entity name into vocab entity_list = json.load(open("./data/entity_list_simple.json")) start_idx = len(self.word2index) for entity_name...
self.word2index = {'<PAD>':0, '<UNK>':1, '<GO>':2, '<EOS>':3} stopwords_self = set() for i, (key, value) in enumerate(wordssorted): if value <= 5: break
random_line_split
DataManager.py
else: wordscount[word] = 1 wordssorted = sorted(wordscount.items(), key = lambda d: (d[1],d[0]), reverse=True) output = open("word_cnt_stat.txt", "w") for i, (key, value) in enumerate(wordssorted): output.write(str(value) + ":" ...
wordscount[word] += 1
conditional_block
DataManager.py
cnt += 1 continue for attr, val in self.nodename_attr_map[nodename].items(): if attr in attr_name: new_out.append(val) suc_flag = True ...
hierarchical_merge
identifier_name
compression_utils.py
stochastic rounding rounding. If `None`, defaults to `l2_norm(x)`. beta: A constant in [0, 1) controlling the concentration inequality for the probabilistic norm bound after rounding. Returns: The rounded tensor. """ def post_rounding_l2_norm_bound(x, l2_norm_bound, beta): """Computes th...
(repeat_index, x): # All sources of randomness depend on the input seed. cur_seed = seed_pair + repeat_index # Randomly flip signs. signs = sample_rademacher(tf.shape(x), dtype=x.dtype, seed_pair=cur_seed) rademacher_x = signs * x # Apply Hadamard (+ expand/squeeze dims). encoded_x = tf.sque...
apply_transform
identifier_name
compression_utils.py
]) return result_x def scaled_quantization(x, scale, stochastic, conditional, l2_norm_bound, beta=DEFAULT_BETA): """Scales the tensors and rounds to integers.""" scale = tf.cast(scale, x.dtyp...
x.set_shape(x_shape) # Failed shape inference in tf.while_loop. return x
random_line_split
compression_utils.py
stochastic rounding rounding. If `None`, defaults to `l2_norm(x)`. beta: A constant in [0, 1) controlling the concentration inequality for the probabilistic norm bound after rounding. Returns: The rounded tensor. """ def post_rounding_l2_norm_bound(x, l2_norm_bound, beta): """Computes th...
axis=0) return encoded_x tf.debugging.assert_type(x, tf.float32) padded_x = pad_zeros(x) # Hadamard transform requires vectors with 2^n dims. i, result_x = tf.constant(0), padded_x cond_fn = lambda i, _: tf.less(i, repeat) body_fn = lambda i, x: [tf.add(i, 1), apply_transform(i, x)] _, result_...
"""Applies randomized Hadamard transform to a vector with the given seed. Args: x: The input vector. seed_pair: The seed pair for generating randomness. repeat: Number of times to repeat the randomized Hadamard transform. Returns: The transformed vector. """ def apply_transform(repeat_index, ...
identifier_body
compression_utils.py
the L2 norm bound of a vector after rounding (Thm. 1, Eq. 2).""" beta = tf.cast(beta, x.dtype) dim = tf.cast(tf.size(x), x.dtype) if l2_norm_bound is None: x_norm = tf.norm(x, ord=2) else: x_norm = tf.cast(l2_norm_bound, x.dtype) # We consider 2 (scaled) norm bounds and take the min (P...
raise ValueError('Number of dimensions of x must be 2. Shape of x: %s' % x.shape)
conditional_block
import_openapi.go
chemas/"):] } return oasSchema.Ref //? } return "" } func convertOasType(name string, oasSchema *Schema) (sadl.TypeSpec, error) { var err error var ts sadl.TypeSpec if oasSchema.Example != nil { ex := &sadl.ExampleDef{ Target: name, Example: oasSchema.Example, } examples = append(examples, ex) }...
{ if op.RequestBody != nil { for contentType, mediadef := range op.RequestBody.Content { if contentType == "application/json" { //hack bodyType := oasTypeRef(mediadef.Schema) if bodyType != "" { spec := &sadl.HttpParamSpec{ StructFieldDef: sadl.StructFieldDef{ TypeSpec: sadl.Type...
conditional_block
import_openapi.go
.Name+"={"+name+"}") case "path": spec.Path = true if strings.Index(path, "{"+name+"}") < 0 { fmt.Println("WARNING: path param is not in path template:", path, name) panic("here") } case "header": spec.Header = param.Name case "cookie": return nil, fmt.Errorf("Cookie params NYI: %v", sadl.A...
}
random_line_split
import_openapi.go
(paths []string, conf *sadl.Data) (*sadl.Model, error) { if len(paths) != 1 { return nil, fmt.Errorf("Cannot merge multiple OpenAPI files") } path := paths[0] name := path n := strings.LastIndex(name, "/") // format := "" if n >= 0 { name = name[n+1:] } n = strings.LastIndex(name, ".") if n >= 0 { // f...
Import
identifier_name
import_openapi.go
} model, err := oas3.ToSadl(name) if err != nil { return nil, fmt.Errorf("Cannot convert to SADL: %v\n", err) } //err = model.ConvertInlineEnums() return model, err } /* func DetermineVersion(data []byte, format string) (string, error) { var raw map[string]interface{} var err error switch format { case "j...
{ if len(paths) != 1 { return nil, fmt.Errorf("Cannot merge multiple OpenAPI files") } path := paths[0] name := path n := strings.LastIndex(name, "/") // format := "" if n >= 0 { name = name[n+1:] } n = strings.LastIndex(name, ".") if n >= 0 { // format = name[n+1:] name = name[:n] name = strings.R...
identifier_body
ser.rs
} impl<'a> Drop for Serializer<'a> { fn drop(&mut self) { // Drop layers in reverse order. while !self.stack.is_empty() { self.stack.pop(); } } } #[allow(nonstandard_style)] struct write_u64 { major: u8, v: u64, } impl write_u64 { fn into(self, out: &'_ mut (dy...
enum Layer<'a> { Seq(Box<dyn Seq<'a> + 'a>), Map(Box<dyn Map<'a> + 'a>),
random_line_split
ser.rs
(self, out: &'_ mut (dyn io::Write)) -> io::Result<()> { let Self { major, v: value } = self; let mask = major << 5; macro_rules! with_uNs {( $($uN:ident)<* ) => ({ mod c { $( pub mod $uN { pub const MAX: u64 = ::core::$uN::MAX as _; } )* ...
into
identifier_name
ser.rs
, 32, 246, 129, 33, 246, 130, 0, 0, 246, 130, 0, 32, 246 ], vec ); let test_object = from_slice(&vec[..]).unwrap(); assert_eq!(object, test_object); } #[test] fn test_object_object_keys() { use :...
let vec = to_vec(&42.5f32).unwrap(); assert_eq_hex!(vec, b"\xF9\x51\x50"); assert_eq!(from_slice::<f32>(&vec[..]).unwrap(), 42.5f32); } } }
identifier_body
result-info-plot-scatter-exec-time.py
default=" execution time (s)", dest="axis_label_suffix", ) parser.add_argument("--axis-label-colour", type=str, default="black", dest="axis_label_colour", ) parser.add_argument("--annotate", default=False, action='store_true', ) parser.add_argumen...
# Event must be sat or timeout _logger.info('index {} is {}'.format(index, event_tag)) if event_tag not in { 'sat', 'timeout', 'soft_timeout'}: # Skip this. We can't do a meaningful comparison here continue indices_to_use.append(index) ...
assert isinstance(ri['event_tag'], list) event_tag, _ = event_analysis.merge_aggregate_events( ri['event_tag'])
conditional_block
result-info-plot-scatter-exec-time.py
def main(args): global _logger global _fail_count parser = argparse.ArgumentParser(description=__doc__) DriverUtil.parserAddLoggerArg(parser) parser.add_argument('first_result_info', type=argparse.FileType('r')) parser.add_argument('second_result_info', type=argparse.FileType(...
if prefix == "": return path if path.startswith(prefix): return path[len(prefix):]
identifier_body
result-info-plot-scatter-exec-time.py
default=False, action='store_true', ) parser.add_argument("--output", default=None, type=argparse.FileType('wb'), ) parser.add_argument("--error-bars", default=False, action='store_true', ) parser.add_argument("--annotate-timeout-point", de...
print("# incomparable: {}".format(len(bounds_incomparable_keys))) print("# of x = y and is timeout: {}".format(len(x_eq_y_and_is_timeout_keys))) # Now plot extend = 100
random_line_split
result-info-plot-scatter-exec-time.py
(prefix, path): if prefix == "": return path if path.startswith(prefix): return path[len(prefix):] def main(args): global _logger global _fail_count parser = argparse.ArgumentParser(description=__doc__) DriverUtil.parserAddLoggerArg(parser) parser.add_argument('first_result...
strip
identifier_name
api.js
Descrizione" + SPACE + "unità" + SPACE + "di" + SPACE + "stima", jsonId:"Descrizione_unita_di_stima", skip:1}, {text:"Valore" + SPACE + "di" + SPACE + "mercato" + SPACE + "del" + SPACE + "lotto", jsonId:"Valore_di_mercato_del_lotto", skip:2, number:true}, {text:"Foglio" + SPACE + "di" + SPACE + "mappa", jsonI...
var indirizzo2 = jsonMongo.Indirizzo + " " + jsonMongo.N_civico + ", " + jsonMongo.Comune + ", " + jsonMongo.Provincia; console.log(indirizzo2); nominatim.search({q: indirizzo2}, function (err2, res2, data2) { if (err2) { ...
conditional_block
api.js
:"Provincia", skip:1}, {text:"CAP", jsonId:"CAP", skip:1}, {text:"Indirizzo", jsonId:"Indirizzo", skip:1}, {text:"N." + SPACE + "civico", jsonId:"N_civico", skip:1}, {text:"Interno", jsonId:"Interno", skip:1}, {text:"Scala", jsonId:"Scala", skip:1}, {text:"Piano", jsonId:"Piano", skip:1} ...
console.log('La perizia CRIF ' + json.Nome_File + ' è stata salvata in mongo'); } }); } router.post('/upload', function(req, res){ upload(req, res, function(err){ if (err){ res.json({error_code:1, err_desc:err}); return; } res.json({error_code:0, err_desc:null}); var pdfParser = new PDFP...
} else { console.log(err); } } else {
random_line_split
apply.rs
/// * `values` - Vec with paths fn random(values: Vec<path::PathBuf>) -> Result<path::PathBuf> { let chosen = values.choose(&mut rand::thread_rng()).ok_or_else(|| { anyhow!( "Scheme not found. Check if it exists, or run update schemes if you didn't already." ) })?; Ok(chosen.to_...
else { process::Command::new(&command_vec[0]) .args(&command_vec[1..]) .stdout(process::Stdio::null()) .stderr(process::Stdio::null()) .status() .with_context(|| format!("Couldn't run hook '{}'", full_command))?; } ...
{ process::Command::new(&command_vec[0]) .stdout(process::Stdio::null()) .stderr(process::Stdio::null()) .status() .with_context(|| format!("Couldn't run hook '{}'", full_command))?; }
conditional_block
apply.rs
/// * `values` - Vec with paths fn random(values: Vec<path::PathBuf>) -> Result<path::PathBuf> { let chosen = values.choose(&mut rand::thread_rng()).ok_or_else(|| { anyhow!( "Scheme not found. Check if it exists, or run update schemes if you didn't already." ) })?; Ok(chosen.to_...
( file_content: &str, start: &str, end: &str, built_template: &str, ) -> Result<String> { let mut changed_content = String::new(); let mut found_start = false; let mut found_end = false; let mut appended = false; for line in file_content.lines() { if found_start && !found_...
replace_delimiter
identifier_name
apply.rs
/// * `values` - Vec with paths fn random(values: Vec<path::PathBuf>) -> Result<path::PathBuf> { let chosen = values.choose(&mut rand::thread_rng()).ok_or_else(|| { anyhow!( "Scheme not found. Check if it exists, or run update schemes if you didn't already." ) })?; Ok(chosen.to_...
//Check if config file exists if !config_path.exists() { eprintln!("Config {:?} doesn't exist, creating", config_path); let default_content = match fs::read_to_string(path::Path::new("/etc/flavours.conf")) { Ok(content) => content, Err(_) => String::from(""), }; ...
println!(); }
random_line_split
apply.rs
/// * `values` - Vec with paths fn random(values: Vec<path::PathBuf>) -> Result<path::PathBuf> { let chosen = values.choose(&mut rand::thread_rng()).ok_or_else(|| { anyhow!( "Scheme not found. Check if it exists, or run update schemes if you didn't already." ) })?; Ok(chosen.to_...
.with_context(|| format!("Couldn't run hook '{}'", full_command))?; } } Ok(()) } /// Replace with delimiter lines /// /// In a string, removes everything from one line to another, and puts the built template in place /// /// * `file_content` - String with lines to be replaced /// * `s...
{ if let Some(command) = command { let full_command = shell.replace("{}", &command); if verbose { println!("running {}", full_command); } let command_vec = shell_words::split(&full_command)?; if command_vec.len() == 1 { process::Command::new(&command_...
identifier_body
constrained_attack.py
as DataFrame Autoencoder output vector Returns -------- recontrution vector sorted descending and dropped """ # print(temp) temp = temp.sort_values(by=row_index, axis=1, ascending=False) i = 0 for col in temp.columns: if temp.loc[row_index, col] < theta: brea...
(row_index, prev_col_name, changed_variables, max_concealable_variables): """ select the sensor value to be manipulated depending on the constrints Parameters ---------- row_index : int prev_col_name : string changed_variables : list variables that can be manipulated max_conc...
choose_column
identifier_name
constrained_attack.py
as DataFrame Autoencoder output vector Returns -------- recontrution vector sorted descending and dropped """ # print(temp) temp = temp.sort_values(by=row_index, axis=1, ascending=False) i = 0 for col in temp.columns: if temp.loc[row_index, col] < theta: brea...
previous_best_error = error newBest = att_data.copy() last_optimization = changes num_changes_without_optimizations = 0 optimized = True try: if not(col_name) in changed_variables[row_index]: changed_variables[r...
print(error, previous_best_error)
conditional_block
constrained_attack.py
X : pandas DataFrame Dataframe Containing one row of sensor readings Returns -------- bool detection outcome float average recontrution error pandas dataframe reconstruction error vector for the considered sensor readings """ X_transformed = pd.DataFrame( ...
prov = pd.DataFrame(index=[row_index], columns=xset, data=att_data[xset]) Yhat, original_error, temp = scale_input_and_detect_single( row_index, prov)
random_line_split
constrained_attack.py
as DataFrame Autoencoder output vector Returns -------- recontrution vector sorted descending and dropped """ # print(temp) temp = temp.sort_values(by=row_index, axis=1, ascending=False) i = 0 for col in temp.columns: if temp.loc[row_index, col] < theta: brea...
original_vector = att_data.copy() changes = 0 found_solution = 0 _, error, temp = scale_input_and_detect_single(row_index, att_data) previous_best_error = error[row_index] temp = sort_temp_and_drop(row_index, temp) prev_col_name = None num_changes_without_optimizations = 0 last_opti...
""" this is the main algorithm, it actually transforms the input row trying to change its predicted label. updates after 5 changes on the same variable the ranking and optimizes the new ranked 1 variable Parameters ---------- row_index : int att_data : pandas DataFrame original data to...
identifier_body
watchman-diag
(buf) == 0: break blob.append(buf) os.close(fd) if len(blob) == 0: return None return "".join(blob) def parsefdinfo(self, blob): watches = 0 for line in blob.split("\n"): if line.find("inotify wd") != -1: wa...
) #
random_line_split
SurfstoreClientUtils.go
) if err == nil { *localFileMeta = remoteFileMeta } } } else { err := downloadFile(client, nil, &remoteFileMeta) if err == nil { localFileMeta := remoteFileMeta fileMetaMap[remoteFilename] = &localFileMeta } } } // working on files only on local -> upload for local...
(client RPCClient) map[string][]string { // open directory localFileInfos, err := ioutil.ReadDir(client.BaseDir) if err != nil { panic(err) } localFileMap := make(map[string][]string) // iterate over all the local files for _, fileInfo := range localFileInfos { if fileInfo.Name() == "index.txt" { continu...
getLocalFileHashBlockListMap
identifier_name
SurfstoreClientUtils.go
) if err == nil { *localFileMeta = remoteFileMeta } } } else { err := downloadFile(client, nil, &remoteFileMeta) if err == nil { localFileMeta := remoteFileMeta fileMetaMap[remoteFilename] = &localFileMeta } } } // working on files only on local -> upload for local...
} else { for i := int64(0); i < numBlocks; i++ { currentBlockOffset := i * int64(blockSize) var currentBlockSize int if blockSize < int(fileSize-currentBlockOffset) { currentBlockSize = blockSize } else { currentBlockSize = int(fileSize - currentBlockOffset) } block := NewBlock(currentBlo...
{ log.Println("uploadFile: Failed to put empty block to the server") return false }
conditional_block
SurfstoreClientUtils.go
4(blockSize) if fileSize%int64(blockSize) != 0 { numBlocks++ } if numBlocks == 0 { // for empty file blockBuffer := make([]byte, 0) block := Block{BlockData: blockBuffer, BlockSize: 0} succ := false err := client.PutBlock(block, &succ) if !succ || err != nil { log.Println("uploadFile: Failed to pu...
random_line_split
SurfstoreClientUtils.go
) if err == nil { *localFileMeta = remoteFileMeta } } } else { err := downloadFile(client, nil, &remoteFileMeta) if err == nil { localFileMeta := remoteFileMeta fileMetaMap[remoteFilename] = &localFileMeta } } } // working on files only on local -> upload for local...
line, err := reader.ReadString('\n') isReaderEnded = err == io.EOF if err != nil && err != io.EOF { panic(err) } if line == "" { break } text := strings.TrimSuffix(line, "\n") lineParts := strings.Split(text, ",") if len(lineParts) == 3 { filename := lineParts[0] version, _ := strconv.Ato...
{ // For read access. indexFilename := filepath.Join(client.BaseDir, "index.txt") indexFile, err := os.Open(indexFilename) if err != nil { // index.txt does not exit indexFile, err = os.Create(indexFilename) if err != nil { panic(err) } } defer indexFile.Close() fileMetaMap := make(map[string]*FileM...
identifier_body
player.rs
, visible_game: &VisibleGame, discard_pile: &mut Vec<Card>) -> bool { // Removes and returns the given card from the player's hand. fn remove_from_hand(hand: &mut Vec<Card>, card: &Card) -> Card { let index = hand.iter().position(|c| c == card).unwrap(); hand.swap_remove(index) ...
{ // TODO implement }
identifier_body
player.rs
<Card>) -> bool { // Removes and returns the given card from the player's hand. fn remove_from_hand(hand: &mut Vec<Card>, card: &Card) -> Card { let index = hand.iter().position(|c| c == card).unwrap(); hand.swap_remove(index) } if self.can_play(action, visible_g...
do_action_returns_false_if_action_not_playable
identifier_name
player.rs
} pub fn coins(&self) -> u32 { self.coins } pub fn hand(&self) -> &Vec<Card> { &self.hand } /// Performs the given [`Action`] on the current player, for example moving a card from the player's hand into the /// player's built structures. Returns `true` if the action is legal,...
// "choice" cards. At the same time, make a vector of resources choices available to us. let mut choices = Vec::new(); for card in &self.built_structures { match card.power() { // TODO: can we write these four options more succinctly? Power::Purchasabl...
// Initialise a Resources struct with the number of coins we have. let mut available_resources = Resources::coins(self.coins); // Add all the other resources we always have access to (ie. those that are not resource
random_line_split
runtime.rs
or threads, you /// will be able to access the runtime from those tasks or threads. /// /// The difference between <code>[Arc]\<Runtime></code> and [`Handle`] is that /// an <code>[Arc]\<Runtime></code> will prevent the runtime from shutting down, /// whereas a [`Handle`] does not prevent that. This is because shutdow...
/// [runtime builder]: crate::runtime::Builder #[cfg(feature = "rt-multi-thread")] #[cfg_attr(docsrs, doc(cfg(feature = "rt-multi-thread")))] pub fn new() -> std::io::Result<Runtime> { Builder::new_multi_thread().enable_all().build() } } /// Returns a handle ...
/// /// [mod]: index.html /// [main]: ../attr.main.html /// [threaded scheduler]: index.html#threaded-scheduler
random_line_split
runtime.rs
threads, you /// will be able to access the runtime from those tasks or threads. /// /// The difference between <code>[Arc]\<Runtime></code> and [`Handle`] is that /// an <code>[Arc]\<Runtime></code> will prevent the runtime from shutting down, /// whereas a [`Handle`] does not prevent that. This is because shutdown o...
( scheduler: Scheduler, handle: Handle, blocking_pool: BlockingPool, ) -> Runtime { Runtime { scheduler, handle, blocking_pool, } } cfg_not_wasi! { /// Creates a new runtime instance with default configuration values. ...
from_parts
identifier_name
runtime.rs
/// // Spawn a future onto the runtime /// rt.spawn(async { /// println!("now running on a worker thread"); /// }); /// # } /// ``` #[track_caller] pub fn spawn<F>(&self, future: F) -> JoinHandle<F::Output> where F: Future + Send + 'static, F::Output: Send + 'stat...
{ match &mut self.scheduler { Scheduler::CurrentThread(current_thread) => { // This ensures that tasks spawned on the current-thread // runtime are dropped inside the runtime's context. let _guard = context::try_set_current(&self.handle.inner); ...
identifier_body
multiuser.go
MultiDB) systemDBFile() string { return filepath.Join(m.BaseDir(), "system.sqlite") } func validUserName(name string) bool { var validUser = regexp.MustCompile(`^\p{L}+[_0-9\p{L}]*$`) return validUser.MatchString(name) } func validDir(dir string) bool { if _, err := os.Stat(dir); os.IsNotExist(err) { return fal...
(username string) Item { q, err := ParseQuery(fmt.Sprintf("User Username=%s", username)) if err != nil { return 0 } results, err := m.system.Find(q, 1) if err != nil || len(results) != 1 { return 0 } return results[0] } // ExistingUser returns true if a user with the given user name exists, false otherwise....
userID
identifier_name
multiuser.go
ErrDBFail, err } if err := tx.Set("User", user.id, "Modified", []Value{now}); err != nil { return nil, ErrDBFail, err } if err := tx.Commit(); err != nil { return nil, ErrDBFail, Fail(`multiuser database error: %s`, err) } dirpath := m.UserDir(&user) err = CreateDirIfNotExist(dirpath) if err != nil { ret...
{ err = os.RemoveAll(filepath.Join(dir, name)) if err != nil { return err } }
conditional_block
multiuser.go
// BaseDir returns the base directory of the multiuser database. This directory contains databases // for all users. func (m *MultiDB) BaseDir() string { return m.basepath } func (m *MultiDB) userFile(user *User, file string) string { return filepath.Join(m.UserDir(user), file) } func (m *MultiDB) userDBFile(user...
{ return filepath.Join(m.basepath, user.name) }
identifier_body
multiuser.go
) } now := NewDate(time.Now()) if err := tx.Set("User", user.id, "Created", []Value{now}); err != nil { return nil, ErrDBFail, err } if err := tx.Set("User", user.id, "Modified", []Value{now}); err != nil { return nil, ErrDBFail, err } if err := tx.Commit(); err != nil { return nil, ErrDBFail, Fail(`multiu...
if err != nil { return err
random_line_split
B-Server.go
.Println("| Broadcast Program |") fmt.Println("|_____________________________|\n") } func main() { // 0. Inicializando servicos adicionais; raven.SetDSN("https://277886f557384520a086cfedea9930cf@sentry.io/1831452") // 0.1. blabla2 raven.SetDefaultLoggerName("saulopinedo") raven.SetDebug(true) raven....
PanicOnError(err) defer jsonFile.Close() byteValueJSON, _ := ioutil.ReadAll(jsonFile) config := Properties{} json.Unmarshal(byteValueJSON, &config) channelCount := config.IDchanBegin nameChannels[0] = "Global" // 3. Preparando o cabecalho; cmd := exec.Command("cmd", "/c", "cls") cmd.Stdout = os.Stdout cmd...
serverAddresses := make(map[string]string) // 2. Lendo configuracoes; jsonFile, err := os.Open(`b-properties.json`)
random_line_split
B-Server.go
else { message = strings.TrimLeft(message, "/") sub := strings.Split(message, " ") // ID nos comandos nao possuem um significado. commandQueue <- Command{0, socket, sub[0], sub[1:]} } } // Se o loop quebrar, significa que o cliente se desconectou; deadConnection <- socket } func PanicOnError(err err...
{ // ID 0 significa um tipo de mensagem. messageQueue <- Chat{0, nil, chanClients[socket], message, nameClients[socket]} }
conditional_block
B-Server.go
(writer http.ResponseWriter, request *http.Request) { socket, err := upgrader.Upgrade(writer, request, nil) if err != nil { fmt.Println(err) } _, msg, err := socket.ReadMessage() nameClients[socket] = string(msg) // msg contem o nome do usuario. newConnection <- socket for { // Recebendo mensagens desse cl...
handler
identifier_name
B-Server.go
func PrintOnError(err error) { if err != nil { raven.CaptureError(err, nil) log.Println(err) } } func serialize(message Chat) ([]byte, error) { var b bytes.Buffer encoder := gob.NewEncoder(&b) err := encoder.Encode(message) return b.Bytes(), err } func deserialize(b []byte) (Chat, error) { var msg Chat ...
{ if err != nil { raven.CaptureErrorAndWait(err, nil) log.Panic(err) } }
identifier_body
train_fineall.py
1)') parser.add_argument('--epochs', type=int, default=600, metavar='N', help='number of epochs to train (default: 300)') parser.add_argument('--batchsize', type=int, default=128, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--lr', type=f...
#dataiter = iter(train_loader) #print(len(train_loader)) #print(len(val_loader)) #images,labels= dataiter.next() #print(images) #print(labels) # print images #imshow(torchvision.utils.make_grid(images)) # define loss function (criterion) and pptimizer criterion = nn.CrossEntropyLoss().cuda() optimizer = optim.SGD...
img = img / 2 + 0.5 # unnormalize npimg = img.numpy() plt.imshow(np.transpose(npimg, (1,2,0))) plt.show()
identifier_body
train_fineall.py
1)') parser.add_argument('--epochs', type=int, default=600, metavar='N', help='number of epochs to train (default: 300)') parser.add_argument('--batchsize', type=int, default=128, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--lr', type=f...
(model, name): print('saving the model ...') if not os.path.exists(PATH_TO_MODEL): os.mkdir(PATH_TO_MODEL) torch.save(model,PATH_TO_MODEL+'/'+str(historyMax)+'.t7') print('done.') def visualize(data): for i in range(0,24): print('color '+str(i)+ '!') for j in range(0,24): ...
save_model
identifier_name
train_fineall.py
net18(pretrained=True)#at least 224*224 model=torch.load(args.modelpos) model.fc=nn.Linear(512,24) for param in model.parameters(): param.requires_grads=False model.fc.requires_grads=True model.layer4.requires_grads=True model.layer3.requires_grads=True model.layer2.requires_grads=True model.layer1.requires_grads...
haha=0 if(epoch>10): for i in range(epoch-10+1,epoch+1): if(Hloss[i]==lossMin): haha=1 if haha==0: break
conditional_block
train_fineall.py
: 1)') parser.add_argument('--epochs', type=int, default=600, metavar='N', help='number of epochs to train (default: 300)') parser.add_argument('--batchsize', type=int, default=128, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--lr', type=...
traindir = os.path.join(args.data, 'train') valdir = os.path.join(args.data, 'val') normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) traindir='data/train' valdir='data/val' #print(os.listdir(traindir)) train_loader1= torch.utils.data.DataLoader( ...
print(colored('initializing done.',"blue")) # Data loading code
random_line_split
lines.py
visible(lines[0:mid]) struct2 = visible(lines[mid:]) struct = combine(struct1, struct2) # print("visibleD ", struct) return struct def combine(struct1, struct2): # print("combining''''''''''''''''''''''''''''''''''''''") # print(struct1) # print(struct2) # IDEA : We assume that struc...
def higher(region, cand): point1 = [region[0], gety(region[0], region[2])] point2 = [region[1], gety(region[1], region[2])] high1 = high(point1, cand) high2 = high(point2, cand) if high1 and high2: return 1 elif not (high1 or high2): return -1 else: return 0 de...
return 1 + binary_flip_search(struct[1:mid], cand)
conditional_block
lines.py
10 and x20, we are done. Similarly for x > x1n and x2n. infx = intersection(struct1[0][2], struct2[0][2])[0] # print("infx", infx) inf2x = intersection(struct1[-1][2], struct2[-1][2])[0] # print("inf2x", inf2x) if infx <= min(struct1[0][1], struct2[0][1]): final = [[float("-inf"), infx, stru...
mylines = [] for i in range(1, n + 1): m = float(random.uniform(-100000, 100000)) c = float(random.uniform(-100000, 100000)) mylines += [[m, c, i]] f = open('input.txt', 'w') f.write(str(n) + '\n') for line in mylines: f.write(str(line[0]) + ':' + str(line[1]) + '\n') ...
identifier_body
lines.py
visible(lines[0:mid]) struct2 = visible(lines[mid:]) struct = combine(struct1, struct2) # print("visibleD ", struct) return struct def combine(struct1, struct2): # print("combining''''''''''''''''''''''''''''''''''''''") # print(struct1) # print(struct2) # IDEA : We assume that struc...
return mid if higher1 == higher_mid: # print("in call case0|||||||||||||||||||||||") return mid + 1 + binary_flip_search(struct[mid + 1:-1], cand) else: # print("in call case1||||||||||||||||||||||||||") return 1 + binary_flip_search(struct[1:mid], cand) def higher(reg...
if higher_mid is 0:
random_line_split
lines.py
must be lower, # and as we approach +infinity, struct2 must be higer. # The point of intersection is where this flip happens. This is also a reasonable approach, # but the corner casses etc. need to be considered. # Unsaid here is the assumption that there is one and only one point of intersection. ...
generate
identifier_name
tower-of-power.py
?:[\w-]+(?:\s*,\s*[\w-]+)*)?\s*)\)' clss_re = r'(?:\.([\w-]+))?' text_re = r':\s*(.*)?' line_re = re.compile( wsop_re + name_re + wsop_re + deps_re + wsop_re + clss_re + wsop_re + text_re ) match = line_re.match(line) if ma...
x0 = model.eval(svs[node][0][0]) y0 = model.eval(svs[node][0][1]) x1 = model.eval(svs[node][1][0]) y1 = model.eval(svs[node][1][1]) import random x0 = int(str(x0)) * 160 + 10 + random.choice(range(10)) ...
conditional_block
tower-of-power.py
some algorithms below self.insert(dag.ROOT, []) # The following incomprehensible regular expressions define the BOX file format # which I invented to make it easier to specify DAGs for this project. def load_line(self, line): import re wsop_re = r'\s*' name_re = r'([\w-]+)' ...
def is_direct_dependency(self, node, dep): return self.is_dependency(node, dep) and\ not self.is_transitive_dependency(node, dep) # Okay, okay, fine, I'll start talking about the solver now. def solve(self): # The way it works is, each box is represented by four symbolic integers, # rep...
for sd in self.get_dependencies(node): if self.is_dependency(sd, dep): return True return False
identifier_body
tower-of-power.py
some algorithms below self.insert(dag.ROOT, []) # The following incomprehensible regular expressions define the BOX file format # which I invented to make it easier to specify DAGs for this project. def load_line(self, line): import re wsop_re = r'\s*' name_re = r'([\w-]+)' ...
(x0min, x0max, x1min, x1max): return z3.Or(x0min >= x1max, x0max <= x1min) for node1 in self.get_nodes(): for node2 in self.get_nodes(): if node1 != node2: solver.add( z3.Or( ranges_disjoint( ...
ranges_disjoint
identifier_name
tower-of-power.py
some algorithms below self.insert(dag.ROOT, []) # The following incomprehensible regular expressions define the BOX file format # which I invented to make it easier to specify DAGs for this project. def load_line(self, line): import re wsop_re = r'\s*' name_re = r'([\w-]+)' ...
svs = {} solver = z3.Solver() for node in self.get_nodes(): svs[node] = ( (z3.Int(node+'_x0'), z3.Int(node+'_y0')), (z3.Int(node+'_x1'), z3.Int(node+'_y1')) ) # Almost immediately, we need to make some sanity assertions. We want the # top...
# upside-down stalactite-towers.)
random_line_split
pool.rs
a usize /// which will the be stored for display. pub fn custom_subgraph<OP, R, START, END, S>(tag: &'static str, start: START, end: END, op: OP) -> R where OP: FnOnce() -> R, START: FnOnce() -> S, END: FnOnce(S) -> usize, { let s = start(); start_subgraph(tag); let r = op(); let measured_v...
/// After running, we post-process the logs and return a `RunLog` together with the closure's /// result. pub fn logging_install<OP, R>(&self, op: OP) -> (R, RunLog)
random_line_split
pool.rs
/// /// <div> /// <img /// src="http://www-id.imag.fr/Laboratoire/Membres/Wagner_Frederic/images/downgraded_manual_max.svg"/> /// </div> /// /// Using it we obtain the graph below. /// On the real file you can hover but javascript and toggle the display of the different tags but /// it is disabled with rustdoc so I dow...
/// Identical to `join`, except that the closures have a parameter /// that provides context for the way the closure has been called, /// especially indicating whether they're executing on a different /// thread than where `join_context` was called. This will occur if /// the second job is stolen by a different thre...
{ let continuation_task_id = next_task_id(); logs!( RayonEvent::SubgraphEnd(tag, measured_value), RayonEvent::Child(continuation_task_id), RayonEvent::TaskEnd(now()), // start continuation task RayonEvent::TaskStart(continuation_task_id, now()) ); }
identifier_body
pool.rs
/// The end function will be called just after running the graph on this S and produce a usize /// which will the be stored for display. pub fn custom_subgraph<OP, R, START, END, S>(tag: &'static str, start: START, end: END, op: OP) -> R where OP: FnOnce() -> R, START: FnOnce() -> S, END: FnOnce(S) -> usize...
logging_install
identifier_name
slide-load.js
farCoords: {}, closeCoords: {}, transiton: {}, defaults: { transition: "bottom", ajax: { url: "/", dataType: 'html', type: 'POST', data: {}, }, }, /** * Initializes the creation of the loader and sets its options. * @param {Object} config A configuration object ...
/** * Gets the far coordinates of the element. * * The far coordinates are the distances from each side of the document * to the opposite side of the element. So distance from the left side * of the document to the right side of the element. * * @param {jQuery} coords The jQuery object to ge...
coords.left = this.offsets.left; // $.extend(coords, this.offsets); return coords; },
random_line_split
slide-load.js
four cooridantes. */ _get_close_coords: function() { var coords = {}; coords.bottom = $(".faux-body").outerHeight() - this.farCoords.bottom; coords.right = $(".faux-body").outerWidth() - this.farCoords.right; coords.top = this.offsets.top; coords.left = this.offsets.left; // $.extend(coord...
{ $.error( 'pushLoad has no method '+arguments[0] ); }
conditional_block
main.rs
older // variable is still usable after assignment. Rust won’t let us annotate a type with the Copy trait if the // type, or any of its parts, has implemented the Drop trait. If the type needs something special to happen // when the value goes out of scope and we add the Copy annotation to that type, we...
ction will erro
identifier_body
main.rs
this //is kinda of a pain. The people at Rust feel the same. let s1 = gives_ownership(); //Rust also let's return variables as tuples so which we can then can deconstruct this when //we get the returned values. //Now it's time to go over references and borrowing! let s1 = String::from("hel...
.i]; } } &s[..] }
conditional_block
main.rs
To learn about how to add the Copy annotation to your type, see Appendix C on Derivable Traits. // So what types are Copy? You can check the documentation for the given type to be sure, but as a general rule, // any group of simple scalar values can be Copy, and nothing that requires allocation or is some fo...
tring)
identifier_name
main.rs
//Note: In C++, this pattern of deallocating resources at the end of an item’s lifetime is sometimes //called Resource Acquisition Is Initialization (RAII). The drop function in Rust will be familiar //to you if you’ve used RAII patterns. let x = 5; let y = x;// y is just a copy of x since they ...
println!("{}", s);
random_line_split
mod.rs
// Parity Ethereum is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License ...
// (at your option) any later version.
random_line_split
mod.rs
64>, _nonce: U256, _password: SignWith) -> Result<WithToken<SignedTransaction>> { Err(errors::account("Signing unsupported", "See #9997")) } fn sign_message(&self, _address: Address, _password: SignWith, _hash: SignMessage) -> Result<WithToken<Signature>> { Err(errors::account("Signing unsupported", "See #99...
(&self) -> &Self::Target { match *self { WithToken::No(ref v) => v, WithToken::Yes(ref v, _) => v, } } } impl<T: Debug> WithToken<T> { /// Map the value with the given closure, preserving the token. pub fn map<S, F>(self, f: F) -> WithToken<S> where S: Debug, F: FnOnce(T) -> S, { match self { Wi...
deref
identifier_name
environment.py
logger.info("Note: {e} environment variable is specified, but tests are " "still run locally\n" "Check other values required to run tests against existing " "deployent".format(e=env_var_name)) def _missing_api_token_warning(env_var_name): if os.environ....
context.client.tag(actual, desired, force=True)
conditional_block
environment.py
output def _get_k8s_volumes_to_delete(): # universal_newlines decodes output on Python 3.x out = subprocess.check_output(['kubectl', 'get', 'pods', '-o', 'json'], universal_newlines=True) j = json.loads(out) volumes = [] for pod in j['items']: pod_vols = pod['spec'].get('volumes', []) ...
def _is_3scale_preview_running(context, accepted_codes={200, 403, 401}): try: res = requests.post(context.threescale_preview_url) if res.status_code in accepted_codes: return True except requests.exceptions.ConnectionError: pass return False def _is_backbone_api_runn...
try: res = requests.post(threescale_url) if res.status_code in accepted_codes: return True except requests.exceptions.ConnectionError: pass return False
identifier_body