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 |
|---|---|---|---|---|
impl_encryption.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use openssl::hash::{self, MessageDigest};
use tidb_query_codegen::rpn_fn;
use tidb_query_datatype::expr::{Error, EvalContext};
use tidb_query_common::Result;
use tidb_query_datatype::codec::data_type::*;
use tidb_query_shared_expr::rand::{gen_random_... | "pingcap", 0, "2871823be240f8ecd1d72f24c99eaa2e58af18b4b8ba99a4fc2823ba5c43930a"),
("pingcap", 224, "cd036dc9bec69e758401379c522454ea24a6327b48724b449b40c6b7"),
("pingcap", 256, "2871823be240f8ecd1d72f24c99eaa2e58af18b4b8ba99a4fc2823ba5c43930a"),
("pingcap", 384, "c50955b6b0c7b991974... | ( | identifier_name |
tae-ui.js | // Text Adaptation Engine User Interface (tae-ui.js)
//-----------------------------------------------------------------------------
// This JavaScript contains the functionality related to the User Interface
// which enriches the Interactive Front-End component with the features of
// the Text Adaptation Engine compo... |
}
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 | // Text Adaptation Engine User Interface (tae-ui.js)
//-----------------------------------------------------------------------------
// This JavaScript contains the functionality related to the User Interface
// which enriches the Interactive Front-End component with the features of
// the Text Adaptation Engine compo... |
// 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 | // Text Adaptation Engine User Interface (tae-ui.js)
//-----------------------------------------------------------------------------
// This JavaScript contains the functionality related to the User Interface
// which enriches the Interactive Front-End component with the features of
// the Text Adaptation Engine compo... | (paragraphID, originalText, response) {
// Create the Simplification Box div
var questionsBox = document.createElement('div');
questionsBox.id = paragraphID + simplifyBoxIdSuffix;
questionsBox.className = simplifyBoxClassName;
// 1. The title is attached
var questionsHtml = '... | showSimplificationBox | identifier_name |
tae-ui.js | // Text Adaptation Engine User Interface (tae-ui.js)
//-----------------------------------------------------------------------------
// This JavaScript contains the functionality related to the User Interface
// which enriches the Interactive Front-End component with the features of
// the Text Adaptation Engine compo... |
function disableComponentFeatures() {
if (!featureEnabled) return;
featureEnabled = false;
// Remove Question Boxes
var questionsBoxes = document.getElementsByClassName(simplifyBoxClassName);
for (var i = questionsBoxes.length - 1; i >= 0; i--) {
questionsBoxes[i].parentNo... | {
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 | from torch.utils.data import TensorDataset
import torch
import numpy as np
import random
from torch.utils.data.sampler import RandomSampler, SubsetRandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data import DataLoader
import os
class InputFeatures(object):... | (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 | from torch.utils.data import TensorDataset
import torch
import numpy as np
import random
from torch.utils.data.sampler import RandomSampler, SubsetRandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data import DataLoader
import os
class InputFeatures(object):... | 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 | from torch.utils.data import TensorDataset
import torch
import numpy as np
import random
from torch.utils.data.sampler import RandomSampler, SubsetRandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data import DataLoader
import os
class InputFeatures(object):... |
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 | from torch.utils.data import TensorDataset
import torch
import numpy as np
import random
from torch.utils.data.sampler import RandomSampler, SubsetRandomSampler, SequentialSampler
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data import DataLoader
import os
class InputFeatures(object):... |
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 | // maybe like Problem D. Descending in the Dark round 2 2012
/*
Bipartite matching
Grid
BFS
Cycles
Hard
*/
use crate::algo::graph::flow::*;
use crate::algo::graph::*;
use crate::util::grid::constants::*;
use crate::util::grid::{Grid, GridCoord, GridRowColVec};
use crate::util::input::*;
//use std::thread;
use bimap::B... | 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 | // maybe like Problem D. Descending in the Dark round 2 2012
/*
Bipartite matching
Grid
BFS
Cycles
Hard
*/
use crate::algo::graph::flow::*;
use crate::algo::graph::*;
use crate::util::grid::constants::*;
use crate::util::grid::{Grid, GridCoord, GridRowColVec};
use crate::util::input::*;
//use std::thread;
use bimap::B... |
/*
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<'a>(case_no: u32, grid: &mut Grid<Tile>, M_soldier_limit: usi... | {
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 | // maybe like Problem D. Descending in the Dark round 2 2012
/*
Bipartite matching
Grid
BFS
Cycles
Hard
*/
use crate::algo::graph::flow::*;
use crate::algo::graph::*;
use crate::util::grid::constants::*;
use crate::util::grid::{Grid, GridCoord, GridRowColVec};
use crate::util::input::*;
//use std::thread;
use bimap::B... |
}
if let Err(err) = writeln!(f, "") {
return Err(err);
}
}
write!(f, "")
}
}
| {
return Err(err);
} | conditional_block |
d.rs | // maybe like Problem D. Descending in the Dark round 2 2012
/*
Bipartite matching
Grid
BFS
Cycles
Hard
*/
use crate::algo::graph::flow::*;
use crate::algo::graph::*;
use crate::util::grid::constants::*;
use crate::util::grid::{Grid, GridCoord, GridRowColVec};
use crate::util::input::*;
//use std::thread;
use bimap::B... | <'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 | /*
Copyright 2021, Pure Storage Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, s... | () *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 | /*
Copyright 2021, Pure Storage Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, s... |
returnedDiags = setAzureJitAccessPolicy(¶meters, 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 | /*
Copyright 2021, Pure Storage Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, s... |
func resourceFusionSECAzureCreate(ctx context.Context, d *schema.ResourceData, m interface{}) (returnedDiags diag.Diagnostics) {
tflog.Trace(ctx, "resourceFusionSECAzurereate")
azureClient, diags := m.(*CbsService).azureClientService(ctx)
if diags.HasError() {
return diags
}
name := d.Get("fusion_sec_name").(... | {
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 | /*
Copyright 2021, Pure Storage Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, s... | 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 | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package norm
import (
"fmt"
"unicode/utf8"
)
// MaxSegmentSize is the maximum size of a byte buffer needed to consider any
// sequence of starter and non-st... | else if inCopyStart < i.p {
i.rb.src.copySlice(i.buf[outCopyStart:], inCopyStart, i.p)
}
return i.buf[:outp]
doNorm:
// Insert what we have decomposed so far in the reorderBuffer.
// As we will only reorder, there will always be enough room.
i.rb.src.copySlice(i.buf[outCopyStart:], inCopyStart, i.p)
i.rb.inser... | {
return i.returnSlice(inCopyStart, i.p)
} | conditional_block |
iter.go | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package norm
import (
"fmt"
"unicode/utf8"
)
// MaxSegmentSize is the maximum size of a byte buffer needed to consider any
// sequence of starter and non-st... | () {
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 | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package norm
import (
"fmt"
"unicode/utf8"
)
// MaxSegmentSize is the maximum size of a byte buffer needed to consider any
// sequence of starter and non-st... | 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 | // Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package norm
import (
"fmt"
"unicode/utf8"
)
// MaxSegmentSize is the maximum size of a byte buffer needed to consider any
// sequence of starter and non-st... |
// 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 | import { Component, OnInit } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { JsonData } from 'src/app/services/actividades/model/json-data.model';
import { AlertController, NavController } from '@ionic/angular';
import { DocumentosService } from 'src/app/services/document... | 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 | import { Component, OnInit } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { JsonData } from 'src/app/services/actividades/model/json-data.model';
import { AlertController, NavController } from '@ionic/angular';
import { DocumentosService } from 'src/app/services/document... | /* 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 | import { Component, OnInit } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { JsonData } from 'src/app/services/actividades/model/json-data.model';
import { AlertController, NavController } from '@ionic/angular';
import { DocumentosService } from 'src/app/services/document... |
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 | import { Component, OnInit } from '@angular/core';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { JsonData } from 'src/app/services/actividades/model/json-data.model';
import { AlertController, NavController } from '@ionic/angular';
import { DocumentosService } from 'src/app/services/document... | 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 | // SPDX-License-Identifier: CC0-1.0
//! This module implements a minimal and non standard conforming HTTP 1.0
//! round-tripper that works with the bitcoind RPC server. This can be used
//! if minimal dependencies are a goal and synchronous communication is ok.
#[cfg(feature = "proxy")]
use socks::Socks5Stream;
use s... |
}
impl From<io::Error> for Error {
fn from(e: io::Error) -> Self {
Error::SocketError(e)
}
}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Self {
Error::Json(e)
}
}
impl From<Error> for crate::Error {
fn from(e: Error) -> crate::Error {
match e... | {
use self::Error::*;
match *self {
InvalidUrl {
..
}
| HttpResponseTooShort {
..
}
| HttpResponseNonAsciiHello(..)
| HttpResponseBadHello {
..
}
| HttpRespons... | identifier_body |
simple_http.rs | // SPDX-License-Identifier: CC0-1.0
//! This module implements a minimal and non standard conforming HTTP 1.0
//! round-tripper that works with the bitcoind RPC server. This can be used
//! if minimal dependencies are a goal and synchronous communication is ok.
#[cfg(feature = "proxy")]
use socks::Socks5Stream;
use s... | (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: &str,
user: Option<String>,
... | build | identifier_name |
simple_http.rs | // SPDX-License-Identifier: CC0-1.0
//! This module implements a minimal and non standard conforming HTTP 1.0
//! round-tripper that works with the bitcoind RPC server. This can be used
//! if minimal dependencies are a goal and synchronous communication is ok.
#[cfg(feature = "proxy")]
use socks::Socks5Stream;
use s... | // NB somehow, Rust's IpAddr accepts "127.0.0" and adds the extra 0..
];
for u in &invalid_urls {
if let Ok(b) = Builder::new().url(u) {
let tp = b.build();
panic!("expected error for url {}, got {:?}", u, tp);
}
}
}
#[... | random_line_split | |
DataManager.py | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 30 16:14:04 2018
@author: truthless
"""
import random
from stop import STOP_WORDS
import numpy as np
import torch
import torch.utils.data as data
import re
import json
import networkx as nx
import scipy.sparse as sp
PAD = 0
UNK = 1 #OOV
GO = 2
EOS = 3
device = torch.d... |
def pad_packed_collate(batch_data):
def merge(sequences):
lengths = [len(seq) for seq in sequences]
padded_seqs = torch.zeros(len(sequences), max(lengths)).long()
for i, seq in enumerate(sequences):
end = lengths[i]
padded_seqs[i, :end] = seq
return ... | 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 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 30 16:14:04 2018
@author: truthless
"""
import random
from stop import STOP_WORDS
import numpy as np
import torch
import torch.utils.data as data
import re
import json
import networkx as nx
import scipy.sparse as sp
PAD = 0
UNK = 1 #OOV
GO = 2
EOS = 3
device = torch.d... | 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 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 30 16:14:04 2018
@author: truthless
"""
import random
from stop import STOP_WORDS
import numpy as np
import torch
import torch.utils.data as data
import re
import json
import networkx as nx
import scipy.sparse as sp
PAD = 0
UNK = 1 #OOV
GO = 2
EOS = 3
device = torch.d... |
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 | # -*- coding: utf-8 -*-
"""
Created on Sun Dec 30 16:14:04 2018
@author: truthless
"""
import random
from stop import STOP_WORDS
import numpy as np
import torch
import torch.utils.data as data
import re
import json
import networkx as nx
import scipy.sparse as sp
PAD = 0
UNK = 1 #OOV
GO = 2
EOS = 3
device = torch.d... | (sequences, sequence_lengths):
lengths = torch.stack(sequence_lengths)
utterance_length = lengths.shape[1]
padded_seqs = torch.zeros(len(sequences), utterance_length, lengths.max().item()).long()
for i, seq in enumerate(sequences):
word_end = max(lengths[i]).item()
... | hierarchical_merge | identifier_name |
compression_utils.py | # Copyright 2021, Google LLC. All rights reserved.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | (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 | # Copyright 2021, Google LLC. All rights reserved.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | def _fwht(x, dim, log2):
x = tf.reshape(x, [-1, 2, dim // 2])
# The fast Walsh-Hadamard transform.
i = tf.constant(0)
c = lambda i, x: tf.less(i, log2)
b = lambda i, x: [i + 1, _hadamard_step(x, dim)]
i, x = tf.while_loop(c, b, [i, x])
return x
x = tf.cond(
tf... | x.set_shape(x_shape) # Failed shape inference in tf.while_loop.
return x
| random_line_split |
compression_utils.py | # Copyright 2021, Google LLC. All rights reserved.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
def inverse_randomized_hadamard_transform(x, original_dim, seed_pair, repeat=1):
"""Applies inverse of `randomized_hadamard_transform` with the given seed.
Args:
x: The transformed vector.
original_dim: The dimension of the original vector.
seed_pair: The same seed pair used in the forward transform... | """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 | # Copyright 2021, Google LLC. All rights reserved.
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
original_x_shape = x.shape.as_list()
dim = x.shape.as_list()[-1]
if dim is None: # dim is not statically known.
dim = tf.shape(x)[-1]
log2 = tf.cast(
tf.math.round(
tf.math.log(tf.cast(dim, tf.float32)) / tf.math.log(2.)),
tf.int32)
with tf.control_dep... | raise ValueError('Number of dimensions of x must be 2. Shape of x: %s' %
x.shape) | conditional_block |
import_openapi.go | package openapi
import (
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/boynton/sadl"
"github.com/ghodss/yaml"
)
var EnumTypes bool = true
func IsValidFile(path string) bool {
_, err := Load(path)
return err == nil
}
func Load(path string) (*Model, error) {
d... |
//expected: if 200 is in the list, use that
//else: if 201 is in the list, use that
//else: ? find a likely candidate.
var expectedStatus string = "default"
for status, _ := range op.Responses {
if strings.HasPrefix(status, "2") || strings.HasPrefix(status, "3") {
expectedStatus = status
break
}
}
// ... | {
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 | package openapi
import (
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/boynton/sadl"
"github.com/ghodss/yaml"
)
var EnumTypes bool = true
func IsValidFile(path string) bool {
_, err := Load(path)
return err == nil
}
func Load(path string) (*Model, error) {
d... | }
return nil
}
func guessDefaultResponseCode(op *Operation) string {
for status, _ := range op.Responses {
if strings.HasPrefix(status, "2") || strings.HasPrefix(status, "3") {
//kind of an arbitrary choice: the first one we encounter, and this is random order, too.
return status
}
}
return "200" //!
}
... | } | random_line_split |
import_openapi.go | package openapi
import (
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/boynton/sadl"
"github.com/ghodss/yaml"
)
var EnumTypes bool = true
func IsValidFile(path string) bool {
_, err := Load(path)
return err == nil
}
func Load(path string) (*Model, error) {
d... | (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 | package openapi
import (
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/boynton/sadl"
"github.com/ghodss/yaml"
)
var EnumTypes bool = true
func IsValidFile(path string) bool {
_, err := Load(path)
return err == nil
}
func Load(path string) (*Model, error) {
d... |
/*
func DetermineVersion(data []byte, format string) (string, error) {
var raw map[string]interface{}
var err error
switch format {
case "json":
err = json.Unmarshal(data, &raw)
case "yaml":
err = yaml.Unmarshal(data, &raw)
default:
err = fmt.Errorf("Unsupported file format: %q. Only \"json\" and \"yaml\"... | {
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 | #![allow(unused)]
#![warn(unused_must_use)]
use crate::{
ser::{Map, Seq, Serialize, ValueView},
Result,
};
use ::std::io::{self, Write as _};
/// Serialize any serializable type into a CBOR byte sequence.
///
/// ```rust
/// use miniserde_ditto::{cbor, Serialize};
///
/// #[derive(Serialize, Debug)]
/// struc... | }
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 | #![allow(unused)]
#![warn(unused_must_use)]
use crate::{
ser::{Map, Seq, Serialize, ValueView},
Result,
};
use ::std::io::{self, Write as _};
/// Serialize any serializable type into a CBOR byte sequence.
///
/// ```rust
/// use miniserde_ditto::{cbor, Serialize};
///
/// #[derive(Serialize, Debug)]
/// struc... | (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 | #![allow(unused)]
#![warn(unused_must_use)]
use crate::{
ser::{Map, Seq, Serialize, ValueView},
Result,
};
use ::std::io::{self, Write as _};
/// Serialize any serializable type into a CBOR byte sequence.
///
/// ```rust
/// use miniserde_ditto::{cbor, Serialize};
///
/// #[derive(Serialize, Debug)]
/// struc... | 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 | #!/usr/bin/env python
# Copyright (c) 2017, Daniel Liew
# This file is covered by the license in LICENSE.txt
# vim: set sw=4 ts=4 softtabstop=4 expandtab:
"""
Read two result info files and generate a scatter plot of execution time
"""
from load_smtrunner import add_smtrunner_to_module_search_path
add_smtrunner_to_modu... |
# 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 | #!/usr/bin/env python
# Copyright (c) 2017, Daniel Liew
# This file is covered by the license in LICENSE.txt
# vim: set sw=4 ts=4 softtabstop=4 expandtab:
"""
Read two result info files and generate a scatter plot of execution time
"""
from load_smtrunner import add_smtrunner_to_module_search_path
add_smtrunner_to_modu... |
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 | #!/usr/bin/env python
# Copyright (c) 2017, Daniel Liew
# This file is covered by the license in LICENSE.txt
# vim: set sw=4 ts=4 softtabstop=4 expandtab:
"""
Read two result info files and generate a scatter plot of execution time
"""
from load_smtrunner import add_smtrunner_to_module_search_path
add_smtrunner_to_modu... | tickFreq = 100
assert len(x_scatter_points) == len(y_scatter_points)
fig, ax = plt.subplots()
fig.patch.set_alpha(0.0) # Transparent
if pargs.error_bars:
splot = ax.errorbar(
x_scatter_points,
y_scatter_points,
xerr=x_scatter_errors,
yerr=y_sca... | 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 | #!/usr/bin/env python
# Copyright (c) 2017, Daniel Liew
# This file is covered by the license in LICENSE.txt
# vim: set sw=4 ts=4 softtabstop=4 expandtab:
"""
Read two result info files and generate a scatter plot of execution time
"""
from load_smtrunner import add_smtrunner_to_module_search_path
add_smtrunner_to_modu... | (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 | var express = require('express');
var router = express.Router();
var multer = require('multer');
var path = require('path');
var fs = require('fs');
var PDFParser = require('pdf2json');
var moment = require('moment');
const util = require('util');
var Nominatim = require('node-nominatim2');
var Perizia = require('../... | });
});
pdfParser.loadPDF(uploadDestination + path.sep + req.file.filename);
})
});
router.get('/id/:_id', function (req, res) {
Perizia.findOne({ CRIF: req.params._id }, function (err, perizia) {
if (err || !perizia) {
res.render('error', {});
} else {
res.json(perizia);//get... | 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 | var express = require('express');
var router = express.Router();
var multer = require('multer');
var path = require('path');
var fs = require('fs');
var PDFParser = require('pdf2json');
var moment = require('moment');
const util = require('util');
var Nominatim = require('node-nominatim2');
var Perizia = require('../... | 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 | use anyhow::{anyhow, Context, Result};
use rand::seq::SliceRandom;
use std::fs;
use std::io::{self, Read};
use std::path;
use std::process;
use std::str;
use std::thread;
use crate::config::Config;
use crate::find::find;
use crate::operations::build::build_template;
use crate::scheme::Scheme;
/// Picks a random path,... | 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 | use anyhow::{anyhow, Context, Result};
use rand::seq::SliceRandom;
use std::fs;
use std::io::{self, Read};
use std::path;
use std::process;
use std::str;
use std::thread;
use crate::config::Config;
use crate::find::find;
use crate::operations::build::build_template;
use crate::scheme::Scheme;
/// Picks a random path,... | (
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 | use anyhow::{anyhow, Context, Result};
use rand::seq::SliceRandom;
use std::fs;
use std::io::{self, Read};
use std::path;
use std::process;
use std::str;
use std::thread;
use crate::config::Config;
use crate::find::find;
use crate::operations::build::build_template;
use crate::scheme::Scheme;
/// Picks a random path,... | //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 | use anyhow::{anyhow, Context, Result};
use rand::seq::SliceRandom;
use std::fs;
use std::io::{self, Read};
use std::path;
use std::process;
use std::str;
use std::thread;
use crate::config::Config;
use crate::find::find;
use crate::operations::build::build_template;
use crate::scheme::Scheme;
/// Picks a random path,... |
/// 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
/// * `start` - Where to start replacing
/// * `end` - Where to stop replacing
/// * `built_template` - Built template to ... | {
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 | import sys
sys.path.append('../../../')
import keras
from keras.layers import Input, Dense, Activation
from keras.layers.merge import Maximum, Concatenate
from keras.models import Model
from keras.optimizers import Adam
from keras.utils import plot_model
# import required to load the attacked model
from autoencoder_BA... | (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 | import sys
sys.path.append('../../../')
import keras
from keras.layers import Input, Dense, Activation
from keras.layers.merge import Maximum, Concatenate
from keras.models import Model
from keras.optimizers import Adam
from keras.utils import plot_model
# import required to load the attacked model
from autoencoder_BA... |
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 | import sys
sys.path.append('../../../')
import keras
from keras.layers import Input, Dense, Activation
from keras.layers.merge import Maximum, Concatenate
from keras.models import Model
from keras.optimizers import Adam
from keras.utils import plot_model
# import required to load the attacked model
from autoencoder_BA... | if Yhat[row_index]:
start_time = time.time()
modified_row, solutions_found = change_vector_label(
row_index, prov, solutions_found, changed_variables, variables)
spent_time = time.time() - start_time
print("--- %s seconds --... | 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 | import sys
sys.path.append('../../../')
import keras
from keras.layers import Input, Dense, Activation
from keras.layers.merge import Maximum, Concatenate
from keras.models import Model
from keras.optimizers import Adam
from keras.utils import plot_model
# import required to load the attacked model
from autoencoder_BA... |
"""
Select wich dataset are you considering
(we are not allowed to publish WADI data, please request them itrust Singapore website)
"""
dataset = 'BATADAL' #'WADI'
data_folder = '../../Data/'+dataset
if dataset == 'BATADAL':
attack_ids = range(1,15)
att_data = pd.read_csv(data_folder+'/attack_1_from_test_dat... | """
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 | #!/usr/bin/env python3
# Collect some FB specific watchman diagnostics
import glob
import json
import os
import re
import stat
import subprocess
import sys
import time
import pywatchman
def print_table(table):
col_width = [max(len(x) for x in col) for col in zip(*table)]
for line in table:
print(
... | )
# Print the basic system info
print("Platform: %s" % sys.platform)
if os.name == "posix":
uname = os.uname()
print_table([uname])
print("Running watchman-diag as uid %d" % os.getuid())
print
if os.name == "posix":
print("RPM version: (rpm -q fb-watchman)")
passthru(["rpm", "-q", "fb-watchma... | random_line_split | |
SurfstoreClientUtils.go | package surfstore
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
)
/*
Implement the logic for a client syncing with the server here.
*/
func ClientSync(client RPCClient) {
// ================================== create a map for old index.txt============================... | (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 | package surfstore
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
)
/*
Implement the logic for a client syncing with the server here.
*/
func ClientSync(client RPCClient) {
// ================================== create a map for old index.txt============================... |
} 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 | package surfstore
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
)
/*
Implement the logic for a client syncing with the server here.
*/
func ClientSync(client RPCClient) {
// ================================== create a map for old index.txt============================... | block, found := blockMap[localBlockHash]
if found && block == nil {
currentBlockOffset := int64(i) * int64(blockSize)
var currentBlockSize int
if blockSize < int(fileSize-currentBlockOffset) {
currentBlockSize = blockSize
} else {
currentBlockSize = int(fileSize - current... | random_line_split | |
SurfstoreClientUtils.go | package surfstore
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strconv"
"strings"
)
/*
Implement the logic for a client syncing with the server here.
*/
func ClientSync(client RPCClient) {
// ================================== create a map for old index.txt============================... |
func updateFileMetaMapWithLocalFiles(client RPCClient, fileMetaMap map[string]*FileMetaData) map[string]*FileMetaData {
localFileMap := getLocalFileHashBlockListMap(client)
// iterate over the file meta map and see if old file exists
for filename, fileMeta := range fileMetaMap {
if localBlockHashList, ok := loc... | {
// 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 | use std::collections::HashMap;
use crate::card::{Card, Colour};
use crate::game::{Action, VisibleGame};
use crate::power::Power;
use crate::power::ScienceItem;
use crate::resources::{ProducedResources, Resources};
use crate::wonder::{WonderBoard, WonderSide, WonderType};
use std::fmt::Debug;
use crate::algorithms::Pla... |
#[test]
fn do_action_returns_false_if_action_not_playable() {
let mut player = new_player(vec![LumberYard]);
assert_eq!(false, player.do_action(&Action::Build(StonePit), &visible_game(), &mut vec![]));
}
#[test]
fn do_action_transfers_built_card_from_hand_to_built_structures() {
... | {
// TODO implement
} | identifier_body |
player.rs | use std::collections::HashMap;
use crate::card::{Card, Colour};
use crate::game::{Action, VisibleGame};
use crate::power::Power;
use crate::power::ScienceItem;
use crate::resources::{ProducedResources, Resources};
use crate::wonder::{WonderBoard, WonderSide, WonderType};
use std::fmt::Debug;
use crate::algorithms::Pla... | () {
let mut player = new_player(vec![LumberYard]);
assert_eq!(false, player.do_action(&Action::Build(StonePit), &visible_game(), &mut vec![]));
}
#[test]
fn do_action_transfers_built_card_from_hand_to_built_structures() {
let mut player = new_player(vec![LumberYard]);
asser... | do_action_returns_false_if_action_not_playable | identifier_name |
player.rs | use std::collections::HashMap;
use crate::card::{Card, Colour};
use crate::game::{Action, VisibleGame};
use crate::power::Power;
use crate::power::ScienceItem;
use crate::resources::{ProducedResources, Resources};
use crate::wonder::{WonderBoard, WonderSide, WonderType};
use std::fmt::Debug;
use crate::algorithms::Pla... | // "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 | use crate::runtime::blocking::BlockingPool;
use crate::runtime::scheduler::CurrentThread;
use crate::runtime::{context, EnterGuard, Handle};
use crate::task::JoinHandle;
use std::future::Future;
use std::time::Duration;
cfg_rt_multi_thread! {
use crate::runtime::Builder;
use crate::runtime::scheduler::MultiTh... | /// [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 | use crate::runtime::blocking::BlockingPool;
use crate::runtime::scheduler::CurrentThread;
use crate::runtime::{context, EnterGuard, Handle};
use crate::task::JoinHandle;
use std::future::Future;
use std::time::Duration;
cfg_rt_multi_thread! {
use crate::runtime::Builder;
use crate::runtime::scheduler::MultiTh... | (
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 | use crate::runtime::blocking::BlockingPool;
use crate::runtime::scheduler::CurrentThread;
use crate::runtime::{context, EnterGuard, Handle};
use crate::task::JoinHandle;
use std::future::Future;
use std::time::Duration;
cfg_rt_multi_thread! {
use crate::runtime::Builder;
use crate::runtime::scheduler::MultiTh... |
}
cfg_metrics! {
impl Runtime {
/// TODO
pub fn metrics(&self) -> crate::runtime::RuntimeMetrics {
self.handle.metrics()
}
}
}
| {
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 | package minidb
import (
"bytes"
"crypto/rand"
"fmt"
"os"
"path/filepath"
"regexp"
"time"
"github.com/rasteric/packdir"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/blake2b"
)
// Params contain all the parameters that are used by a multiuser database.
type Params struct {
Argon2Memory uint32
Ar... | (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 | package minidb
import (
"bytes"
"crypto/rand"
"fmt"
"os"
"path/filepath"
"regexp"
"time"
"github.com/rasteric/packdir"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/blake2b"
)
// Params contain all the parameters that are used by a multiuser database.
type Params struct {
Argon2Memory uint32
Ar... |
return nil
}
// Delete deletes the whole multiuser db including all housekeeping information and directories.
// This action cannot be undone.
func (m *MultiDB) Delete() (ErrCode, error) {
m.Close()
m.system.Close()
if err := removeContents(m.BaseDir()); err != nil {
return ErrFileSystem, err
}
return OK, nil... | {
err = os.RemoveAll(filepath.Join(dir, name))
if err != nil {
return err
}
} | conditional_block |
multiuser.go | package minidb
import (
"bytes"
"crypto/rand"
"fmt"
"os"
"path/filepath"
"regexp"
"time"
"github.com/rasteric/packdir"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/blake2b"
)
// Params contain all the parameters that are used by a multiuser database.
type Params struct {
Argon2Memory uint32
Ar... |
// 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 | package minidb
import (
"bytes"
"crypto/rand"
"fmt"
"os"
"path/filepath"
"regexp"
"time"
"github.com/rasteric/packdir"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/blake2b"
)
// Params contain all the parameters that are used by a multiuser database.
type Params struct {
Argon2Memory uint32
Ar... | }
for _, name := range names {
err = os.RemoveAll(filepath.Join(dir, name))
if err != nil {
return err
}
}
return nil
}
// Delete deletes the whole multiuser db including all housekeeping information and directories.
// This action cannot be undone.
func (m *MultiDB) Delete() (ErrCode, error) {
m.Close()... | if err != nil {
return err | random_line_split |
B-Server.go | package main
import (
"bufio"
"bytes"
"encoding/gob"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"strings"
"sync"
"time"
"github.com/getsentry/raven-go"
"github.com/gorilla/websocket"
"github.com/streadway/amqp"
)
// Associacoes entre clientes e atributos;
var nameC... | 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 | package main
import (
"bufio"
"bytes"
"encoding/gob"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"strings"
"sync"
"time"
"github.com/getsentry/raven-go"
"github.com/gorilla/websocket"
"github.com/streadway/amqp"
)
// Associacoes entre clientes e atributos;
var nameC... | 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 | package main
import (
"bufio"
"bytes"
"encoding/gob"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"strings"
"sync"
"time"
"github.com/getsentry/raven-go"
"github.com/gorilla/websocket"
"github.com/streadway/amqp"
)
// Associacoes entre clientes e atributos;
var nameC... | (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 | package main
import (
"bufio"
"bytes"
"encoding/gob"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/exec"
"strings"
"sync"
"time"
"github.com/getsentry/raven-go"
"github.com/gorilla/websocket"
"github.com/streadway/amqp"
)
// Associacoes entre clientes e atributos;
var nameC... |
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 | # -*- coding: utf-8 -*-
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pickle
from PIL import Image
from sklearn.neural_network import MLPClassifier
import argparse
import torch
import torch.optim as optim
from tqdm import *
from termcolor import *
from torch.autograd import Var... |
#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 | # -*- coding: utf-8 -*-
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pickle
from PIL import Image
from sklearn.neural_network import MLPClassifier
import argparse
import torch
import torch.optim as optim
from tqdm import *
from termcolor import *
from torch.autograd import Var... | (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 | # -*- coding: utf-8 -*-
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pickle
from PIL import Image
from sklearn.neural_network import MLPClassifier
import argparse
import torch
import torch.optim as optim
from tqdm import *
from termcolor import *
from torch.autograd import Var... | 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 | # -*- coding: utf-8 -*-
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import pickle
from PIL import Image
from sklearn.neural_network import MLPClassifier
import argparse
import torch
import torch.optim as optim
from tqdm import *
from termcolor import *
from torch.autograd import Var... |
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 | __author__ = 'hooda'
def intersection(line1, line2):
[line1, line2] = sorted([line1, line2])
if line1[0] == line2[0]:
print("INVALID")
m1, c1, m2, c2 = line1[0], line1[1], line2[0], line2[1]
x = (c2 - c1) / (m1 - m2)
y = (m2 * c1 - m1 * c2) / (m2 - m1)
print('interstection', line1, li... |
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 | __author__ = 'hooda'
def intersection(line1, line2):
[line1, line2] = sorted([line1, line2])
if line1[0] == line2[0]:
print("INVALID")
m1, c1, m2, c2 = line1[0], line1[1], line2[0], line2[1]
x = (c2 - c1) / (m1 - m2)
y = (m2 * c1 - m1 * c2) / (m2 - m1)
print('interstection', line1, li... |
def supertest(n):
# lines = generate(n)
# lines.sort()
# lines = clean(lines)
# for line in lines:
# print(line)
# print("Doing Brute Forces")
# sure = superbrute(lines)
print("doing ninja speed mode")
maybe = visible(lines)
writer(outfile, maybe)
surelines = []
for l... | 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 | __author__ = 'hooda'
def intersection(line1, line2):
[line1, line2] = sorted([line1, line2])
if line1[0] == line2[0]:
print("INVALID")
m1, c1, m2, c2 = line1[0], line1[1], line2[0], line2[1]
x = (c2 - c1) / (m1 - m2)
y = (m2 * c1 - m1 * c2) / (m2 - m1)
print('interstection', line1, li... | 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 | __author__ = 'hooda'
def intersection(line1, line2):
[line1, line2] = sorted([line1, line2])
if line1[0] == line2[0]:
print("INVALID")
m1, c1, m2, c2 = line1[0], line1[1], line2[0], line2[1]
x = (c2 - c1) / (m1 - m2)
y = (m2 * c1 - m1 * c2) / (m2 - m1)
print('interstection', line1, li... | (n):
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]) + ... | generate | identifier_name |
tower-of-power.py | # This is a bit of an experiment, really: a way to generate "box tower"
# dependency diagrams in the style of the inside cover of Matt Parker's book,
# "Things to Make and Do in the Fourth Dimension." Parker's blocks represent
# prerequisite-knowledge dependencies between his book chapters, but surely the
# same idea c... |
# This is the "solver gives up" case
else:
return rects
# This is perhaps the least exciting bit of the whole program: just some silly
# SVG generation routines. There's some logic to get the text wrapping to work,
# but other than that, it's pretty simple (and by "simple" I mean
# "exte... | 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 | # This is a bit of an experiment, really: a way to generate "box tower"
# dependency diagrams in the style of the inside cover of Matt Parker's book,
# "Things to Make and Do in the Fourth Dimension." Parker's blocks represent
# prerequisite-knowledge dependencies between his book chapters, but surely the
# same idea c... |
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 | # This is a bit of an experiment, really: a way to generate "box tower"
# dependency diagrams in the style of the inside cover of Matt Parker's book,
# "Things to Make and Do in the Fourth Dimension." Parker's blocks represent
# prerequisite-knowledge dependencies between his book chapters, but surely the
# same idea c... | (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 | # This is a bit of an experiment, really: a way to generate "box tower"
# dependency diagrams in the style of the inside cover of Matt Parker's book,
# "Things to Make and Do in the Fourth Dimension." Parker's blocks represent
# prerequisite-knowledge dependencies between his book chapters, but surely the
# same idea c... |
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 | //! `LoggedPool` structure for logging raw tasks events.
#![macro_use]
// we can now use performance counters to tag subgraphs
#[cfg(feature = "perf")]
use perfcnt::linux::PerfCounterBuilderLinux;
#[cfg(feature = "perf")]
use perfcnt::linux::{CacheId, CacheOpId, CacheOpResultId, HardwareEventType, SoftwareEventType};
... | where
OP: FnOnce() -> R + Send,
R: Send,
{
self.reset();
let id = next_task_id();
let c = || {
log(RayonEvent::TaskStart(id, now()));
let result = op();
log(RayonEvent::TaskEnd(now()));
result
};
let start = ... | /// 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 | //! `LoggedPool` structure for logging raw tasks events.
#![macro_use]
// we can now use performance counters to tag subgraphs
#[cfg(feature = "perf")]
use perfcnt::linux::PerfCounterBuilderLinux;
#[cfg(feature = "perf")]
use perfcnt::linux::{CacheId, CacheOpId, CacheOpResultId, HardwareEventType, SoftwareEventType};
... |
/// 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 | //! `LoggedPool` structure for logging raw tasks events.
#![macro_use]
// we can now use performance counters to tag subgraphs
#[cfg(feature = "perf")]
use perfcnt::linux::PerfCounterBuilderLinux;
#[cfg(feature = "perf")]
use perfcnt::linux::{CacheId, CacheOpId, CacheOpResultId, HardwareEventType, SoftwareEventType};
... | <OP, R>(&self, op: OP) -> (R, RunLog)
where
OP: FnOnce() -> R + Send,
R: Send,
{
self.reset();
let id = next_task_id();
let c = || {
log(RayonEvent::TaskStart(id, now()));
let result = op();
log(RayonEvent::TaskEnd(now()));
... | logging_install | identifier_name |
slide-load.js | (function($){
/**
* The pushLoad object creates and manages the AJAX transitions between
* all the pages and subpages on the site.
*
* This object is in charge of loading the new content as well as the
* animated transition between the old content and the new content. It also
* contains logic to determi... |
/**
* 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 | (function($){
/**
* The pushLoad object creates and manages the AJAX transitions between
* all the pages and subpages on the site.
*
* This object is in charge of loading the new content as well as the
* animated transition between the old content and the new content. It also
* contains logic to determi... |
return this;
};
})( jQuery ); | {
$.error( 'pushLoad has no method '+arguments[0] );
} | conditional_block |
main.rs | fn main() {
//Rust deals with stack and heaps for memory managment no gc or direct memory management
//The stack memory is a first in last off type queue
//Stack data must take up a known and fixed size
//In rust the heap is used for when we don't know the size of the vector at compile time
//or if ... | r on us since we are trying to
//modify a borrowed variable. We will always get an
//error for this function even if we never call it.
// fn change(some_string: &String) {
// some_string.push_str(", world");
// }
//This fixes the above code by making a mutable reference that we can now modify.
fn change(some_stri... | ction will erro | identifier_body |
main.rs | fn main() {
//Rust deals with stack and heaps for memory managment no gc or direct memory management
//The stack memory is a first in last off type queue
//Stack data must take up a known and fixed size
//In rust the heap is used for when we don't know the size of the vector at compile time
//or if ... | .i];
}
}
&s[..]
} | conditional_block | |
main.rs | fn main() {
//Rust deals with stack and heaps for memory managment no gc or direct memory management
//The stack memory is a first in last off type queue
//Stack data must take up a known and fixed size
//In rust the heap is used for when we don't know the size of the vector at compile time
//or if ... | {
some_string.push_str(", world");
}
//The below code creates a dangling pointer/reference.
//So when the data goes out of scope at the end of the function
//our reference now points to memory that has been freed.
//The compiler catches this and errors out on us.
// fn dangle() -> &String {
// let s = String:... | tring) | identifier_name |
main.rs | fn main() {
//Rust deals with stack and heaps for memory managment no gc or direct memory management
//The stack memory is a first in last off type queue
//Stack data must take up a known and fixed size
//In rust the heap is used for when we don't know the size of the vector at compile time
//or if ... |
//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 | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or |
// 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 | // Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at yo... | (&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 | """Module with code to be run before and after certain events during the testing."""
import json
import datetime
import subprocess
import os.path
import contextlib
from behave.log_capture import capture
import docker
import requests
import time
from src.s3interface import S3Interface
import logging
logging.getLogge... |
# Specify the analyses checked for when looking for "complete" results
def _get_expected_component_analyses(ecosystem):
common = context.EXPECTED_COMPONENT_ANALYSES
specific = context.ECOSYSTEM_DEPENDENT_ANALYSES.get(ecosystem, set())
return common | specific
context.get_expected_c... | context.client.tag(actual, desired, force=True) | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.