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
utils.py
: bool = False): logger = logging.getLogger() if debug: log_level = logging.DEBUG else: log_level = logging.INFO logger.setLevel(log_level) if not any(type(i) == logging.StreamHandler for i in logger.handlers): sh = logging.StreamHandler() sh.setLevel(log_level) ...
return cum_edit_distance / len(data_loader) pred = [] true = [] for i in tqdm(range(0, math.ceil(len(dataset) / n_batch))): data = dataset[n_batch * i:n_batch * (i + 1)] graph, label = model.batchify(data, ctx) output = model(graph) predictions = nd.argmax(output, axis=...
predictions_labels = model.unbatchify(batch, output) for prediction, label in predictions_labels: if not logged_example: logger.info('Some example predictions:\n{}'.format(pprint.pformat(predictions_labels[:10]))) logged_example = True ...
conditional_block
utils.py
: bool = False): logger = logging.getLogger() if debug: log_level = logging.DEBUG else: log_level = logging.INFO logger.setLevel(log_level) if not any(type(i) == logging.StreamHandler for i in logger.handlers): sh = logging.StreamHandler() sh.setLevel(log_level) ...
Converts a tuple of tuples into a PaddedArray (i.e. glorified pair of nd.Arrays for working with SequenceMask) Pads to the length of the longest tuple in the outer tuple, unless pad_amount is specified. ''' value_lengths = nd.array([len(i) for i in tup_of_tups], dtype='float32', ...
def tuple_of_tuples_to_padded_array(tup_of_tups: Tuple[Tuple[int, ...], ...], ctx, pad_amount=None): '''
random_line_split
utils.py
_level) if not any(type(i) == logging.StreamHandler for i in logger.handlers): sh = logging.StreamHandler() sh.setLevel(log_level) logger.addHandler(sh) file_handlers = [i for i in logger.handlers if type(i) == logging.FileHandler] for h in file_handlers: logger.removeHandle...
VarNamingGraphVocabLoss
identifier_name
main.rs
passport is interesting; the only missing field is cid, so it looks like data from North Pole Credentials, not a passport at all! Surely, nobody would mind if you made the system temporarily ignore missing cid fields. Treat this "passport" as valid. The fourth passport is missing two fields, cid and byr. Missing cid ...
; } valid_passports_total } fn validate_passport(passport: &HashMap<String, String>) -> bool { let mut result = true; // Birth year if let Some(byr) = passport.get("byr") { result = result && validate_byr(byr); } else { result = false; } // Issue Year if let Some(...
{ 0 }
conditional_block
main.rs
third passport is interesting; the only missing field is cid, so it looks like data from North Pole Credentials, not a passport at all! Surely, nobody would mind if you made the system temporarily ignore missing cid fields. Treat this "passport" as valid. The fourth passport is missing two fields, cid and byr. Missin...
(passport: &HashMap<String, String>) -> bool { let mut result = true; // Birth year if let Some(byr) = passport.get("byr") { result = result && validate_byr(byr); } else { result = false; } // Issue Year if let Some(iyr) = passport.get("iyr") { result = result && va...
validate_passport
identifier_name
main.rs
third passport is interesting; the only missing field is cid, so it looks like data from North Pole Credentials, not a passport at all! Surely, nobody would mind if you made the system temporarily ignore missing cid fields. Treat this "passport" as valid. The fourth passport is missing two fields, cid and byr. Missin...
ecl valid: brn ecl invalid: wat pid valid: 000000001 pid invalid: 0123456789 Here are some invalid passports: eyr:1972 cid:100 hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 iyr:2019 hcl:#602927 eyr:1967 hgt:170cm ecl:grn pid:012533040 byr:1946 hcl:dab227 iyr:2012 ecl:brn hgt:182cm pid:021572410 eyr:...
hcl valid: #123abc hcl invalid: #123abz hcl invalid: 123abc
random_line_split
main.rs
third passport is interesting; the only missing field is cid, so it looks like data from North Pole Credentials, not a passport at all! Surely, nobody would mind if you made the system temporarily ignore missing cid fields. Treat this "passport" as valid. The fourth passport is missing two fields, cid and byr. Missin...
for item in lin.split_whitespace() { let mut pair = item.split(':'); let key = String::from(pair.next().unwrap()); let value = String::from(pair.next().unwrap()); entry.insert(key, value); } line = lines.next(); ...
{ let mut passports: Vec< HashMap<String, String> > = Vec::new(); let file = File::open(filename).unwrap(); let reader = BufReader::new(file); let mut lines = reader.lines(); // iterate over lines until end of file loop { let mut line = lines.next(); if line.is_none() { ...
identifier_body
deck.go
) != len(order) && len(order) != 1 { return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1") } } else { if len(order) != 0 { return nil, errors.New("Error: unused 'order' fields") } } var l []Deck qs = qs.OrderBy(sortFields...) if _, err = qs.Limit(limit, offset).All...
= ankiCar
identifier_name
deck.go
if hasShow[pop.Id] == 1{ return true, nil }else{ hasShow[pop.Id] = 1 } newChilds := GetSons(pop, o) childs = append(childs, newChilds...) } return false, nil } func GetSons(this *Deck, o orm.Ormer)[]*Deck{ sons := []*Deck{} qs := o.QueryTable("deck") qs.Filter("parent_id", this.Id).All(&sons) ret...
il } o.LoadRelated(rel
conditional_block
deck.go
1 { // 2) there is exactly one order, all the sorted fields will be sorted by this order for _, v := range sortby { orderby := "" if order[0] == "desc" { orderby = "-" + v } else if order[0] == "asc" { orderby = v } else { return nil, errors.New("Error: Invalid order. Must be eithe...
ser)([]*Card, error){ //先获取所有子目录的id subDirs, err := GetSubDirs(this, true) if err != nil{ return nil, err } //获取所有task, 并且ready_time > now的 cards := []*Card{} o := orm.NewOrm() qs := o.QueryTable("card") sub_dir_ids := []int{} for _, sd := range(subDirs){ sub_dir_ids = append(sub_dir_ids, sd.Id) } qs.F...
rm() qs := o.QueryTable("card") qs.Filter("did", this.Id).All(&cards) return cards } func GetCards(this *Deck, user *U
identifier_body
deck.go
== 1 { // 2) there is exactly one order, all the sorted fields will be sorted by this order for _, v := range sortby { orderby := "" if order[0] == "desc" { orderby = "-" + v } else if order[0] == "asc" { orderby = v } else { return nil, errors.New("Error: Invalid order. Must be ei...
//2 将map中一样的部分消除 //3 将nid表多出来的,插入card //4 将card表多出来的,删除 nidMap := map[int]int{} cidMap := map[int]*Card{} o := orm.NewOrm() qs1 := o.QueryTable("note") notes := []*Note{} qs1.Filter("did", this.Id).All(&notes) for i:=0; i<len(notes); i++{ n := notes[i] nidMap[n.Id] = 1 } qs2 := o.QueryTable("card") ...
func syncCards(this *Deck, user *User)(error) { //1 生成左右两份 map
random_line_split
queryRedEnvelopesGrantCtrl.js
$scope.statusRecoveryStr=angular.toJson($scope.statusRecoverySelect); $scope.statusAccountSelect=[{text:"全部",value:''},{text:"待入账",value:'0'},{text:"已记账",value:'1'}, {text:"记账失败",value:'2'}]; $scope.statusAccountStr=angular.toJson($scope.statusAccountSelect); $scope.recoveryTypeSelect=[{text:"...
'<a ng-show="row.entity.busType==0&&row.entity.statusRisk==0&&grid.appScope.hasPermit(\'redEnvelopesGrant.updateStatusRisk\')" ng-click="grid.appScope.modifyStatusRisk(row.entity)" > | 风控关闭</a>' + '</div>' } ], onRegisterApi: function(gridApi) {
random_line_split
queryRedEnvelopesGrantCtrl.js
.page.totalCount; $scope.gridOptions.totalItems = data.page.totalCount; if(data.sunOrder!=null){ $scope.sunOrder=data.sunOrder; } }else{ $scope.notice(data.msg); } $sco...
conditional_block
index.d.ts
{ constructor(); /** * ## Callbacks */ onCallTransfer: (alias: string) => void; onChatMessage: (message: PexRTC.ChatMessage) => void; onConnect: (stream: PexRTC.PexMediaStream | null) => void; onConferenceUpdate: (properties: { guest_muted: boolean; locked: boolean; ...
PexRTC
identifier_name
index.d.ts
: (participant: PexRTC.AnyParticipant) => void; onPresentation: ( setting: boolean, presenter: string | null, uuid?: string ) => void; onPresentationConnected: (stream: PexRTC.PexMediaStream) => void; onPresentationDisconnected: (reason: string) => void; onPresentationReload:...
readonly dialOut: ( destination: string, protocol?: 'sip' | 'h323' | 'rtmp' | 'mssip' | 'auto', role?: PexRTC.Role, cb?: (res: { result: string[] }) => void, params?: { presentation_uri?: string; streaming?: boolean; dtmf_sequence?: string;...
/** * ## Conference control functions */
random_line_split
store.go
), }, { Keys: bson.D{{Key: "_userId", Value: 1}, {Key: "time", Value: -1}, {Key: "type", Value: 1}}, Options: options.Index(). SetName("UserIdTimeWeighted_v2"). SetBackground(true). SetPartialFilterExpression( bson.D{ {Key: "_active", Value: true}, }, ), }, } if _, err :=...
} return err == nil, err }
random_line_split
store.go
any data with time stored as an ISO string. // See https://github.com/golang/go/issues/19635 if !p.Date.Start.IsZero() && !p.Date.End.IsZero() { groupDataQuery["time"] = bson.M{"$gte": p.Date.Start, "$lte": p.Date.End} } else if !p.Date.Start.IsZero() { groupDataQuery["time"] = bson.M{"$gte": p.Date.Start} } e...
GetDeviceData
identifier_name
store.go
medtronic, err = strconv.ParseBool(values[len(values)-1]) if err != nil { return nil, errors.New("medtronic parameter not valid") } } p := &Params{ UserID: q.Get(":userID"), DeviceID: q.Get("deviceId"), UploadID: q.Get("uploadId"), //the query params for type and subtype can contain multiple valu...
{ return nil, errors.New("medtronic parameter not valid") }
conditional_block
store.go
).FindOne(c.context, query).Err() if err != nil && err != mongo.ErrNoDocuments { return false, err } if err == mongo.ErrNoDocuments { return false, nil } return err == nil, err } // GetDexcomDataSource - get func (c *MongoStoreClient) GetDexcomDataSource(userID string) (bson.M, error) { if userID == "" { ...
{ for _, x := range haystack { if needle == x { return true } } return false }
identifier_body
commonAPI.js
.get("24kPrice", function(err, replayData){ if(replayData){ res.json(JSON.parse(replayData)); }else{ request(config.web24kPriceUrl,function(error, response, data){ if (!error && response.statusCode == 200 && common.isValid(data)) { var pa...
as error:"+error); res.json(null); }else{ try { res.json(data ? JSON.parse(data) : null); }catch(e){ logger.error("getNewsInfoList has error:"+e); res.json(null); } ...
f(error){ logger.error("getNewsInfoList h
conditional_block
commonAPI.js
Client.get("24kPrice", function(err, replayData){ if(replayData){ res.json(JSON.parse(replayData)); }else{ request(config.web24kPriceUrl,function(error, response, data){ if (!error && response.statusCode == 200 && common.isValid(data)) { ...
SyllabusService.getCourse(loc_params.groupType, loc_params.groupId, new Date(), loc_params.flag, function(apiResult){ res.json(apiResult); }); }); /** * 获取指定分析师的下次课程安排 */ router.get("/getNextCourses", function(req, res) { var loc_params = { type : req.query["type"], p...
random_line_split
keyrebels_new.py
", "Ireland", "Denmark", "Greece", "Spain", "Portugal", "Austria", "Sweden", "Finland"]} def outputToCsv(outputName, df): fileName = "output/" + outputName + ".csv" df.to_csv(fileName, index=False, encoding="utf-8-sig") # function from https://matplotlib.org/ def survey(results, categ...
def filterGender(df, group): return df[df.Gender == group] def filterAge(df, criteria, threshold): if criteria == "above": return df[df.Age >= threshold] elif criteria == "below": return df[df.Age <= threshold] def combineVotes(dict): ordered = OrderedDict([('FOR', ...
return df[df['Country'].isin(group)]
identifier_body
keyrebels_new.py
", "Ireland", "Denmark", "Greece", "Spain", "Portugal", "Austria", "Sweden", "Finland"]} def outputToCsv(outputName, df): fileName = "output/" + outputName + ".csv" df.to_csv(fileName, index=False, encoding="utf-8-sig") # function from https://matplotlib.org/ def survey(results, categ...
ax.legend(ncol=len(category_names), bbox_to_anchor=(0, 1), loc='lower left', fontsize='small') # ax.set_title("Proportion of MEPs' votes by political group") # plt.subplots_adjust(left=0.1, bottom=0.1, right=0.1, top=0.8) # plt.tight_layout() plt.savefig(str(name) + "out.png...
ax.text(x, y, str(float(c)), ha='center', va='center', color=text_color)
conditional_block
keyrebels_new.py
", "Ireland", "Denmark", "Greece", "Spain", "Portugal", "Austria", "Sweden", "Finland"]} def outputToCsv(outputName, df): fileName = "output/" + outputName + ".csv" df.to_csv(fileName, index=False, encoding="utf-8-sig") # function from https://matplotlib.org/ def survey(results, categ...
(df, group): return df[df.Gender == group] def filterAge(df, criteria, threshold): if criteria == "above": return df[df.Age >= threshold] elif criteria == "below": return df[df.Age <= threshold] def combineVotes(dict): ordered = OrderedDict([('FOR', 0), ('ABSTAINED', 0), ...
filterGender
identifier_name
keyrebels_new.py
"Ireland", "Denmark", "Greece", "Spain", "Portugal", "Austria", "Sweden", "Finland"]} def outputToCsv(outputName, df): fileName = "output/" + outputName + ".csv" df.to_csv(fileName, index=False, encoding="utf-8-sig") # function from https://matplotlib.org/ def survey(results, categor...
def filterAge(df, criteria, threshold): if criteria == "above": return df[df.Age >= threshold] elif criteria == "below": return df[df.Age <= threshold] def combineVotes(dict): ordered = OrderedDict([('FOR', 0), ('ABSTAINED', 0), ('NOT PRESENT', 0), ('AGAINST', 0)]) for i i...
return df[df.Gender == group]
random_line_split
COCDataCrawler.py
.vpWorth = '' self.defaultMove = '' self.cardList = [] self.pngName = '' self.bGetAllInfo = False class CGetWebData: def __init__(self): self.figureHeaders = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,applic...
ml(indent='\t')) def ReadMonsterBuildFromXML(self): self.monsterList.clear(); dom = xml.dom.minidom.parse(self.monsterXMLPath) root = dom.documentElement monsters = root.getElementsByTagName("Monster") # 获取Monster节点 # print(len(monsters)) for eachMonster in monsters:...
Attribute("Count", str(eachCard.count)) monsterNode.appendChild(cardNode) root.appendChild(monsterNode) with open(self.monsterXMLPath, 'w') as f: f.write(doc.toprettyx
conditional_block
COCDataCrawler.py
__(self,name=''): self.name = name self.inGameNames = [] self.hp = '' self.draw = '' self.vpWorth = '' self.defaultMove = '' self.cardList = [] self.pngName = '' self.bGetAllInfo = False class CGetWebData: def __init__(self): self.figu...
def __init__(self,figure_name): funLog = CFunTrace('CFigure:__init__') self.cardlist = [] self.name = figure_name log = CLog('添加人物:{nameStr}'.format(nameStr = figure_name)) def addCard(self,name,count): funLog = CFunTrace('CFigure:addCard()') card = CCard(name,count) ...
identifier_body
COCDataCrawler.py
class CLog: def __init__(self,funName): self.__funName = funName if CURR_LOG_LEVEL.value <= LOG_LEVEL.Log.value: print(self.__funName) class CCard: def __init__(self,name,count): self.name = name self.count = count class CFigure: def __init__(self,figure_name): ...
random_line_split
COCDataCrawler.py
.vpWorth = '' self.defaultMove = '' self.cardList = [] self.pngName = '' self.bGetAllInfo = False class CGetWebData: def __init__(self): self.figureHeaders = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,applic...
创建根节点 root.setAttribute("URL", self.fugureURLs[0]) doc.appendChild(root) for eachFigure in self.figureList: figureNode = doc.createElement("Figure") figureNode.setAttribute("name", eachFigure.name) for eachCard in eachFigure.cardlist: cardNode ...
ent("FigureBuild") #
identifier_name
error.ts
id is needed to identify the post.'; export const POST_ID_TOO_LONG = -40354; es[POST_ID_TOO_LONG] = 'post id is too long. Must be less than 128 characters.'; export const POST_ID_CANNOT_CONTAIN_SLASH = -40355; es[POST_ID_CANNOT_CONTAIN_SLASH] = 'post id cannot contain slashes.'; // export const POST_ID_CANNOT_SOLELY_C...
{ let code = 0; let message = ''; // console.log("convert; ", FireStoreErrorObject); switch (FireStoreErrorObject['code']) { case 5: /// convert firebase error message into backend error message with information. code = DOCUMENT_ID_DOES_NOT_EXISTS_FOR_UPDATE; message =...
identifier_body
error.ts
. Or maybe the has a wrong(expired) ID token.'; export const NO_USER_DOCUMENT_ID = -400220; es[NO_USER_DOCUMENT_ID] = 'Empty document path for user collection.'; export const FAILED_TO_VERIFY_USER = -400230; es[FAILED_TO_VERIFY_USER] = 'Failed to verify who you are.'; export const FAILED_TO_CREATE_ANONYMOUS = -40023...
patchWithMarker
identifier_name
error.ts
given route is not exists. It is a wrong route.'; export const EMPTY_ROUTE = -40063; es[EMPTY_ROUTE] = 'Empty route.'; export const WRONG_METHOD = -40064; es[WRONG_METHOD] = 'Wrong method.'; export const ANONYMOUS_CANNOT_EDIT_PROFILE = -40070; es[ANONYMOUS_CANNOT_EDIT_PROFILE] = 'Anonymous cannot set/update profile.';...
// documnets export const DOCUMENT_ID_DOES_NOT_EXISTS_FOR_GET = -40004; es[DOCUMENT_ID_DOES_NOT_EXISTS_FOR_GET] = 'Document ID to get a data does not exist in database. collection: #collectionName, documentID: #documentID'; export const DOCUMENT_ID_DOES_NOT_EXISTS_FOR_GET_IN_TRANSACTION = -40006; es[DOCUMENT_ID_DOES_N...
random_line_split
reader.rs
(b: &'a [u8]) -> Result<RtpReader<'_>, RtpReaderError> { if b.len() < Self::MIN_HEADER_LEN { return Err(RtpReaderError::BufferTooShort(b.len())); } let r = RtpReader { buf: b }; if r.version() != 2 { return Err(RtpReaderError::UnsupportedVersion(r.version())); ...
new
identifier_name
reader.rs
8, 0xa1u8, 0x04u8, 0x72u8, 0x53u8, 0xa0u8, 0xb4u8, 0xffu8, 0x79u8, 0x1fu8, 0x07u8, 0xe2u8, 0x5du8, 0x01u8, 0x7du8, 0x63u8, 0xc1u8, 0x16u8, 0x89u8, 0x23u8, 0x4au8, 0x17u8, 0xbbu8, 0x6du8, 0x0du8, 0x81u8, 0x1au8, 0xbbu8, 0x94u8, 0x5bu8, 0xcbu8, 0x2du8, 0xdeu8, 0x98u8, 0x40u8, 0x22u8, 0x62u8, 0x41u...
{ let reader = RtpReader::new(&TEST_RTP_PACKET_WITH_EXTENSION).unwrap(); assert_eq!(2, reader.version()); assert!(reader.padding().is_none()); assert!(reader.extension().is_some()); assert_eq!(0, reader.csrc_count()); assert_eq!(111, reader.payload_type()); }
identifier_body
reader.rs
as u32) << 24 | (self.buf[5] as u32) << 16 | (self.buf[6] as u32) << 8 | (self.buf[7] as u32) } /// The _synchronisation source_ for this packet. Many applications of RTP do not use this /// field. pub fn ssrc(&self) -> u32 { (self.buf[8] as u32) << 24 ...
else { None } } /// Create a `RtpPacketBuilder` from this packet. **Note** that padding from the original /// packet will not be used by default, and must be defined on the resulting `RtpPacketBuilder` /// if required. /// /// The padding is not copied from the original si...
{ let offset = self.csrc_end(); let id = (self.buf[offset] as u16) << 8 | (self.buf[offset + 1] as u16); let start = offset + 4; Some((id, &self.buf[start..start + self.extension_len()])) }
conditional_block
reader.rs
xb3u8, 0xa1u8, 0x04u8, 0x72u8, 0x53u8, 0xa0u8, 0xb4u8, 0xffu8, 0x79u8, 0x1fu8, 0x07u8, 0xe2u8, 0x5du8, 0x01u8, 0x7du8, 0x63u8, 0xc1u8, 0x16u8, 0x89u8, 0x23u8, 0x4au8, 0x17u8, 0xbbu8, 0x6du8, 0x0du8, 0x81u8, 0x1au8, 0xbbu8, 0x94u8, 0x5bu8, 0xcbu8, 0x2du8, 0xdeu8, 0x98u8, 0x40u8, 0x22u8, 0x62u8, 0...
assert!(reader.padding().is_none()); assert!(reader.extension().is_some()); assert_eq!(0, reader.csrc_count()); assert_eq!(111, reader.payload_type());
random_line_split
lib.rs
//! (5.0, 5.0)]; //! //! assert_eq!(Ok((0.6, 2.2)), linear_regression_of(&tuples)); //! //! //! // Example 3: directly operating on integer (converted to float as required) //! let xs: Vec<u8> = vec![1, 2, 3, 4, 5]; //! let ys: Vec<u8> = vec![2, 4, 5, 4, 5]; //! //! ...
let x_sum: F = xs.iter().cloned().map(Into::into).sum(); let n = F::from(xs.len()).ok_or(Error::Mean)?; let x_mean = x_sum / n; let y_sum: F = ys.iter().cloned().map(Into::into).sum(); let y_mean = y_sum / n; lin_reg( xs.iter() .map(|i| i.clone().into()) .zip(ys...
{ return Err(Error::Mean); }
conditional_block
lib.rs
//! (5.0, 5.0)]; //! //! assert_eq!(Ok((0.6, 2.2)), linear_regression_of(&tuples)); //! //! //! // Example 3: directly operating on integer (converted to float as required) //! let xs: Vec<u8> = vec![1, 2, 3, 4, 5]; //! let ys: Vec<u8> = vec![2, 4, 5, 4, 5]; //! //! ...
pub fn parts(mut self) -> Result<(F, F, F, F), Error> { self.normalize()?; let Self { x_mean, y_mean, x_mul_y_mean, x_squared_mean, .. } = self; Ok((x_mean, y_mean, x_mul_y_mean, x_s...
{ match self.n { 1 => return Ok(()), 0 => return Err(Error::NoElements), _ => {} } let n = F::from(self.n).ok_or(Error::Mean)?; self.n = 1; self.x_mean = self.x_mean / n; self.y_mean = self.y_mean / n...
identifier_body
lib.rs
//! (5.0, 5.0)]; //! //! assert_eq!(Ok((0.6, 2.2)), linear_regression_of(&tuples)); //! //! //! // Example 3: directly operating on integer (converted to float as required) //! let xs: Vec<u8> = vec![1, 2, 3, 4, 5]; //! let ys: Vec<u8> = vec![2, 4, 5, 4, 5]; //! //! ...
<F: FloatCore> { x_mean: F, y_mean: F, x_mul_y_mean: F, x_squared_mean: F, n: usize, } impl<F: FloatCore> Default for Accumulator<F> { fn default() -> Self { Self::new() } } impl<F: FloatCore> Accumulator<F> { pub fn new() -> ...
Accumulator
identifier_name
lib.rs
), //! (5.0, 5.0)]; //! //! assert_eq!(Ok((0.6, 2.2)), linear_regression_of(&tuples)); //! //! //! // Example 3: directly operating on integer (converted to float as required) //! let xs: Vec<u8> = vec![1, 2, 3, 4, 5]; //! let ys: Vec<u8> = vec![2, 4, 5, 4, 5]; //! //! ...
.
// If we ran the generic impl on each tuple field, that would be very cache inefficient let n = F::from(xys.len()).ok_or(Error::Mean)?; let (x_sum, y_sum) = xys .iter() .cloned()
random_line_split
rro_test.go
theme: "faza", overrides: ["foo"], } android_library { name: "bar", resource_dirs: ["bar/res"], } android_app { name: "baz", sdk_version: "current", resource_dirs: ["baz/res"], } ` result := android.GroupFixturePreparers( PrepareForTestWithJavaDefaultModules, PrepareForTestWithOv...
{ fs := android.MockFS{ "baz/res/res/values/strings.xml": nil, "bar/res/res/values/strings.xml": nil, } bp := ` runtime_resource_overlay { name: "foo", certificate: "platform", lineage: "lineage.bin", product_specific: true, static_libs: ["bar"], resource_libs: ["baz"], aaptflags: ["--keep...
identifier_body
rro_test.go
_resource_overlay { name: "foo_themed", certificate: "platform", product_specific: true, theme: "faza", overrides: ["foo"], } android_library { name: "bar", resource_dirs: ["bar/res"], } android_app { name: "baz", sdk_version: "current", resource_dirs: ["baz/res"], } ` resul...
(t *testing.T) { ctx, _ := testJava(t, ` runtime_resource_overlay { name: "foo_overlay", certificate: "platform", product_specific: true, sdk_version: "current", } override_runtime_resource_overlay { name: "bar_overlay", base: "foo_overlay", package_name: "com.android.bar.overlay", targe...
TestOverrideRuntimeResourceOverlay
identifier_name
rro_test.go
untime_resource_overlay { name: "foo_themed", certificate: "platform", product_specific: true, theme: "faza", overrides: ["foo"],
} android_app { name: "baz", sdk_version: "current", resource_dirs: ["baz/res"], } ` result := android.GroupFixturePreparers( PrepareForTestWithJavaDefaultModules, PrepareForTestWithOverlayBuildComponents, fs.AddToFixture(), ).RunTestWithBp(t, bp) m := result.ModuleForTests("foo", "android_c...
} android_library { name: "bar", resource_dirs: ["bar/res"],
random_line_split
rro_test.go
_resource_overlay { name: "foo_themed", certificate: "platform", product_specific: true, theme: "faza", overrides: ["foo"], } android_library { name: "bar", resource_dirs: ["bar/res"], } android_app { name: "baz", sdk_version: "current", resource_dirs: ["baz/res"], } ` resul...
// Check device location. path = androidMkEntries.EntryMap["LOCAL_MODULE_PATH"] expectedPath = []string{shared.JoinPath("out/target/product/test_device/product/overlay")} android.AssertStringPathsRelativeToTopEquals(t, "LOCAL_MODULE_PATH", result.Config, expectedPath, path) // A themed module has a different de...
{ t.Errorf("Unexpected LOCAL_CERTIFICATE value: %v, expected: %v", path, expectedPath) }
conditional_block
youtubeService.go
attempt to get the video is u, err := url.Parse(mapping.StrToV(videoURL)) if err != nil { return nil, err } var videoID *string values := u.Query()["id"] if len(values) == 0 { videoID, err = c.gateway.GetYoutubeVideoID(videoURL) if err != nil { return nil, errors.New("could not get video ID") } } re...
(youtubeURL *string) (*string, error) { if youtubeURL == nil { return nil, errors.New("Need url") } _, err := c.gateway.GetYoutubeVideoID(youtubeURL) if err != nil { return nil, err } return nil, err // baseURL := "https://www.googleapis.com/youtube/v3/search?" // url := fmt.Sprintf("%spart=%s&maxResults=1&...
GetYoutubeVideoID
identifier_name
youtubeService.go
attempt to get the video is u, err := url.Parse(mapping.StrToV(videoURL)) if err != nil { return nil, err }
videoID, err = c.gateway.GetYoutubeVideoID(videoURL) if err != nil { return nil, errors.New("could not get video ID") } } response, err := c.gateway.GetYoutubeVideoDetails(videoID) if err != nil { return nil, err } // baseURL := "https://www.googleapis.com/youtube/v3/videos?" // url := fmt.Sprintf("%s...
var videoID *string values := u.Query()["id"] if len(values) == 0 {
random_line_split
youtubeService.go
{} // resp, err := client.Do(req) // if err != nil { // return nil, err // } // err = json.NewDecoder(resp.Body).Decode(&response) // if err != nil { // return nil, err // } // if response == nil { // return nil, errors.New("response is nil") // } return response, nil } // GetYoutubeVideoID - func (c *Y...
VideoCategoryMap[userCategoryID] == nil || VideoCategoryMap[candidateCategoryID] == nil { return 0 } containsCandidateCategory := false containsUserCategory := false for _, category := range VideoCategoryMap[userCategoryID] { if category == candidateCategoryID { containsCandidateCategory = true } } for...
identifier_body
youtubeService.go
attempt to get the video is u, err := url.Parse(mapping.StrToV(videoURL)) if err != nil { return nil, err } var videoID *string values := u.Query()["id"] if len(values) == 0 { videoID, err = c.gateway.GetYoutubeVideoID(videoURL) if err != nil { return nil, errors.New("could not get video ID") } } re...
// cursor, err := c.Find(context.Background(), filters, options) // users := []*types.User{} // if err = cursor.All(context.Background(), &users); err != nil { // return nil, err // } return users, nil } // TODO – add in title words to tags // RankAndMatchYoutubeVideos - func (c *YoutubeController) RankAndMa...
{ return nil, err }
conditional_block
mod.rs
"), (libc::SIG_ERR, _) => DEFAULT_ERROR_HANDLER .expect("Default handlers should be set before registering actions"), (default_action, None) => default_action, } }; SigActionPair { guest_facing_action: original, int...
/// Register the given sigaction as the default. Optionally an override function /// can be passed in that will us to change the default handler for an action fn insert_action( sigaction: libc::sigaction, override_default_handler: Option<libc::sighandler_t>, ) -> SlotKey { HANDLER_SLOT_MAP.insert(Some(Sig...
{ if action.sa_flags & libc::SA_SIGINFO > 0 { let to_run: extern "C" fn(libc::c_int, *const libc::siginfo_t, *const libc::c_void) = transmute(action.sa_sigaction as *const libc::c_void); to_run( signal_val, &sig_info as *const libc::siginfo_t, ptr::nul...
identifier_body
mod.rs
"), (libc::SIG_ERR, _) => DEFAULT_ERROR_HANDLER .expect("Default handlers should be set before registering actions"), (default_action, None) => default_action, } }; SigActionPair { guest_facing_action: original, int...
/// treatment of function pointers in signal handlers (instead of checking for) ///specific values of sighandler_t before calling pub extern "C" fn default_ignore_handler<T: ToolGlobal>( _signal_value: libc::c_int, _siginfo: *const libc::siginfo_t, _ctx: *const libc::c_void, ) { } /// This is our replaceme...
/// This is our replacement for default handlers where /// `libc::sighandler_t = libc::SIG_IGN` which is the default handler /// value for lots of signals. This function does nothing, but allows uniform
random_line_split
mod.rs
(original: libc::sigaction, override_handler: Option<libc::sighandler_t>) -> Self { let mut internal_action = original.clone(); // This is safe because it is only reading from a mut static that is // guaranteed to have been completely set before this function // is called intern...
new
identifier_name
featureExtractors.py
Int[k] /= len(intervals) vec['interval_probs'] = couInt vec['pitch_mean'] = np.mean(noteNums) vec['interval_mean'] = np.mean(np.abs(intervals)) vec['interval_signs'] = sum(np.sign(intervals)) / len(intervals) vec['interval_prop_small'] = sum([abs(intervals[n]) <= 2 for n in range(0, len(intervals))...
sumIntProbs *= songVec['interval_probs'][i]
conditional_block
featureExtractors.py
temp[0] for x in xtemp] # print(str(xCoords) + " vs " + str(yCoords)) polyFit1 = np.polyfit(xCoords, yCoords, 1, full=True) vec['polyfit_1'] = polyFit1[0][0] vec['polyfit_residual_1'] = 0 if polyFit1[1].size > 0: vec['polyfit_residual_1'] = np.sqrt(polyFit1[1][0]) vec['polyfit_2'] = 0 ...
ret = [] for tn in tableNames: item = table[tn] ret.append(item[featsType][featureName]) return ret
identifier_body
featureExtractors.py
the notes of the associated pattern occurrence useTies is a boolean determining whether or not tied notes count as two notes or one for the purpose of indexing (true for 1, false for 2) necessary bc MTC-ANN indexing doesn't count """ # inStart = int(annEntry[6]) # numNotes = int(annEntry[8]) ...
mel = cur_class.score # for now just remove rests noteNums = [x.pitch.midi for x in mel] intervals = [noteNums[n] - noteNums[n-1] for n in range(1, len(noteNums))] highest = max(noteNums) lowest = min(noteNums) vec['numNotes'] = len(noteNums) vec['pitch_highest'] = highest vec['...
random_line_split
featureExtractors.py
range(12): num = len([x for x in noteNums if abs(x) % 12 == n]) vec['pitch_class_count_' + str(n)] = num / len(noteNums) for n in range(-3, 3): num = len([x for x in noteDurs if 2**(n) <= x < 2**(n+1)]) vec['rhythm_duration_count_' + str(n)] = num / len(noteDurs) return vec #...
getFeaturesForClasses
identifier_name
single_train.py
visdial.decoders import Decoder from visdial.model import EncoderDecoderModel from visdial.utils.checkpointing import CheckpointManager, load_checkpoint from single_evaluation import Evaluation class MVAN(object): def __init__(self, hparams): self.hparams = hparams self._logger = logging.getLogger(__name__...
print(""" # ------------------------------------------------------------------------- # DATALOADER FINISHED # ------------------------------------------------------------------------- """) def _build_model(self): # =================================================================...
old_split = "train" if self.hparams.dataset_version == "0.9" else None self.train_dataset = VisDialDataset( self.hparams, overfit=self.hparams.overfit, split="train", old_split = old_split ) collate_fn = None if "dan" in self.hparams.img_feature_type: collate_fn = self.tra...
identifier_body
single_train.py
_seed[0])) # def _build_data_process(self): def _build_dataloader(self): # ============================================================================= # SETUP DATASET, DATALOADER # ============================================================================= old_split = "train" if self.hparams....
if epoch < self.hparams.num_epochs - 1 and self.hparams.dataset_version == '0.9': continue torch.cuda.empty_cache()
random_line_split
single_train.py
visdial.decoders import Decoder from visdial.model import EncoderDecoderModel from visdial.utils.checkpointing import CheckpointManager, load_checkpoint from single_evaluation import Evaluation class MVAN(object): def __init__(self, hparams): self.hparams = hparams self._logger = logging.getLogger(__name__...
# Total Iterations -> for learning rate scheduler if self.hparams.training_splits == "trainval": self.iterations = (len(self.train_dataset) + len(self.valid_dataset)) // self.hparams.virtual_batch_size else: self.iterations = len(self.train_dataset) // self.hparams.virtual_batch_size # ==...
self.criterion = nn.CrossEntropyLoss(ignore_index=self.train_dataset.vocabulary.PAD_INDEX)
conditional_block
single_train.py
visdial.decoders import Decoder from visdial.model import EncoderDecoderModel from visdial.utils.checkpointing import CheckpointManager, load_checkpoint from single_evaluation import Evaluation class MVAN(object): def __init__(self, hparams): self.hparams = hparams self._logger = logging.getLogger(__name__...
(current_iteration: int) -> float: """Returns a learning rate multiplier. Till `warmup_epochs`, learning rate linearly increases to `initial_lr`, and then gets multiplied by `lr_gamma` every time a milestone is crossed. """ current_epoch = float(current_iteration) / self.iterations ...
lr_lambda_fun
identifier_name
settings.py
= 30 # user agents # USER_AGENTS = [ \ # "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1" \ # "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11", \ # "Mozilla/5.0 (Windows NT 6.1; WOW...
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20", "Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Versio...
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6",
random_line_split
set1.rs
bb) => aa ^ bb, }) .collect::<Vec<u8>>(); return Ok(result); } pub fn xor_in_place(data: &mut [u8], other: &[u8]) -> Result<usize, &'static str> { if data.len() != other.len() { return Err("buffer size mismatch"); } let xor_count = data.iter_mut() .zip(other) ....
(plaintext: &[u8], key: &[u8]) -> Vec<u8> { let result = plaintext .iter() .zip(key.iter().cycle()) .map(|pair| match pair { (&aa, &bb) => aa ^ bb, }) .collect::<Vec<u8>>(); return result; } use std::collections::BTreeMap; pub fn char_freq_score(text: &[u8]...
xor_repeat
identifier_name
set1.rs
) .sum() }) .sum(); return Ok(result); } pub fn find_best_single_byte_xor(ciphertext: &[u8]) -> u8 { let mut decoded: Vec<(f64, u8, Vec<u8>)> = Vec::with_capacity(256); for i in 0..=256 { let key: Vec<u8> = vec![i as u8; ciphertext.len()]; if let Ok(decoded_...
{ let plaintext = "Burning 'em, if you ain't quick and nimble\n\ I go crazy when I hear a cymbal"; let key = "ICE"; let plaintext = plaintext.as_bytes(); let key = key.as_bytes(); let ciphertext = set1::xor_repeat(&plaintext, &key); let ciphert...
identifier_body
set1.rs
&bb) => aa ^ bb, }) .collect::<Vec<u8>>(); return Ok(result); } pub fn xor_in_place(data: &mut [u8], other: &[u8]) -> Result<usize, &'static str> { if data.len() != other.len() { return Err("buffer size mismatch"); } let xor_count = data.iter_mut() .zip(other) ...
#[test] fn xor() { let a = "1c0111001f01010006
} }
random_line_split
alerts.go
token for bearer token or JWT auth, alternatively set CORTEX_AUTH_TOKEN.").Default("").Envar("CORTEX_AUTH_TOKEN").StringVar(&a.ClientConfig.AuthToken) alertCmd.Flag("user", "API user to use when contacting cortex, alternatively set CORTEX_API_USER. If empty, CORTEX_TENANT_ID will be used instead.").Default("").Envar(...
{ log.WithFields(log.Fields{ "alertname": m.Metric["alertname"], "state": m.Metric, }).Infof("alert found that was not in both sources") }
conditional_block
alerts.go
auge( prometheus.GaugeOpts{ Name: "cortextool_alerts_single_source", Help: "Alerts found by the alerts verify command that are coming from a single source rather than multiple sources..", }, ) ) // AlertmanagerCommand configures and executes rule related cortex api operations type AlertmanagerCommand struct...
(k *kingpin.ParseContext) error { var empty interface{} if a.IgnoreString != "" { a.IgnoreAlerts = make(map[string]interface{}) chunks := strings.Split(a.IgnoreString, ",") for _, name := range chunks { a.IgnoreAlerts[name] = empty log.Info("Ignoring alerts with name: ", name) } } lhs := fmt.Sprintf(...
verifyConfig
identifier_name
alerts.go
rule related cortex api operations type AlertmanagerCommand struct { ClientConfig client.Config AlertmanagerURL url.URL AlertmanagerConfigFile string TemplateFiles []string DisableColor bool cli *client.CortexClient } // AlertCommand configures and executes rule related Prom...
var lastErr error var n int
random_line_split
alerts.go
auge( prometheus.GaugeOpts{ Name: "cortextool_alerts_single_source", Help: "Alerts found by the alerts verify command that are coming from a single source rather than multiple sources..", }, ) ) // AlertmanagerCommand configures and executes rule related cortex api operations type AlertmanagerCommand struct...
func (a *AlertmanagerCommand) getConfig(k *kingpin.ParseContext) error { cfg, templates, err := a.cli.GetAlertmanagerConfig(context.Background()) if err != nil { if err == client.ErrResourceNotFound { log.Infof("no alertmanager config currently exist for this user") return nil } return err } p := pri...
{ cli, err := client.New(a.ClientConfig) if err != nil { return err } a.cli = cli return nil }
identifier_body
blog_details_min.js
-sub')['click'](function () { var _0x19ea25 = { 'WMqVz': function (_0x568012, _0x2af04b) { return _0x568012(_0x2af04b); }, 'NAaLP': '.ui.form', 'hMYzs': 'validate\x20form', 'Tffrz': function (_0x142248) { return _0x142248(); } }; var _0x26e47e = _0x19ea25['WMq...
VGcy': '3|1|0|4|5|2', 'HeFaY': function (_0x1b0cd0, _0x2a80fc) { return _0x1b0cd0(_0x2a80fc); }, 'spJaG': 'comment-nickname', 'ncEqy': '#comment-form', 'bmUZw': function (_0x409e74, _0x533775) { return _0x409e74(_0x533775); }, 'GosxG': 'com...
'i
identifier_name
blog_details_min.js
else { _0x2a7476['CEXJj']($, _0x2a7476['eyVUT'])['hide'](0x1f4); } } }); $('.ui.form')['form']({ 'fields': { 'nickName': { 'identifier': 'nickName', 'rules': [{'type': 'empty', 'prompt': '评论昵称不能为空'}] }, 'content': {'identifier': 'content', 'rules': [{...
{ _0x2a7476['BqmBe']($, _0x2a7476['eyVUT'])['show'](0x64); }
conditional_block
blog_details_min.js
-btn-sub')['click'](function () { var _0x19ea25 = { 'WMqVz': function (_0x568012, _0x2af04b) { return _0x568012(_0x2af04b); }, 'NAaLP': '.ui.form', 'hMYzs': 'validate\x20form', 'Tffrz': function (_0x142248) { return _0x142248(); } }; var _0x26e47e = _0x19ea25[...
8 = { 'iVGcy': '3|1|0|4|5|2', 'HeFaY': function (_0x1b0cd0, _0x2a80fc) { return _0x1b0cd0(_0x2a80fc); }, 'spJaG': 'comment-nickname', 'ncEqy': '#comment-form', 'bmUZw': function (_0x409e74, _0x533775) { return _0x409e74(_0x533775); }, ...
'uqJae': function (_0x2b03ce, _0xb22fbb) { return _0x2b03ce(_0xb22fbb); }, 'giuBZ': '[name=\x27content\x27]', 'Xjmxp': function (_0x731754, _0x30f655) { return _0x731754(_0x30f655); }, 'STElQ': '[name=\x27parentComment.id\x27]', 'jJieZ': function (_0x46bac3, _0xd2eff0) { ...
identifier_body
blog_details_min.js
-btn-sub')['click'](function () { var _0x19ea25 = { 'WMqVz': function (_0x568012, _0x2af04b) { return _0x568012(_0x2af04b); }, 'NAaLP': '.ui.form', 'hMYzs': 'validate\x20form', 'Tffrz': function (_0x142248) { return _0x142248(); } }; var _0x26e47e = _0x19ea25[...
if (_0x547753['Ln
}, 'pRMne': '.views', 'MQdBm': 'viewId', 'ElsTJ': '获取数据出错!', 'LnJlb': function (_0x5694d3, _0x2622b8) { return _0x5694d3 != _0x2622b8; }, 'UGZdK': 'POST', 'nFSAq': '/addView', 'FNhau': 'json' };
random_line_split
ACL2011_v2.py
debug", action="store_true", help="debug output") parser.add_argument("--featuremap", metavar="FILE", default="featuremap", help="location of feature map") parser.add_argument("--nfolds", metavar="N", type=int, default=5, help="number of fo...
DocumentCollection
identifier_name
ACL2011_v2.py
for filename in filenames: if filename.endswith(".txt"): # example filename: t_hilton_1.txt, meaning truthful review of the Hilton hotel (label, hotel, i) = filename.split("_") # get review text with codecs.open(path.join(dirpath, file...
return doc[self.text_key]
identifier_body
ACL2011_v2.py
subprocess.call(program) # extract features, unknown from stdout. features = {} unknown = {} location = 0 for line in stdout.splitlines(): if line.startswith("Total number of words:"): wc = int(line[line.find(":")+1:]) if wc == 0: wc = 0.0000001 ...
# get training features and labels logging.getLogger("fold_{0}".format(i)).debug("getting training features and labels") train_features = get_features(train, featuremap, is_train=True) (train_labels, _) = train.flatten() # choose parameters using nested cross-validation on train...
CV_ids, CV_hotels, CV_labels, CV_preds, CV_binary_preds = [], [], [], [], [] # CV output for (i, (train, test)) in enumerate(DocumentCollection.get_train_test(folds)):
random_line_split
ACL2011_v2.py
subprocess.call(program) # extract features, unknown from stdout. features = {} unknown = {} location = 0 for line in stdout.splitlines(): if line.startswith("Total number of words:"): wc = int(line[line.find(":")+1:]) if wc == 0: wc = 0.0000001 ...
# load featuremap featuremap = WordMap(args.featuremap) # load documents, ignoring the folds if not path.isdir(args.data): raise IOError("Data directory not found: {0}".format(args.data)) docs = {} for (dirpath, dirnames, filenames) in os.walk(args.data): for filename in filen...
logging.basicConfig(level=logging.INFO)
conditional_block
Reber, Kotovsky (1997).py
lineWidth=3, lineColor=[-1,-1,-1], fillColor=[1,1,1], opacity=0, interpolate=True, autoDraw=True, ) def box_factory(name, position, size): return visual.Rect( win=win, name=name, widt...
if event.getKeys(keyList=["escape"]): sound_gen.stop() exp.nextEntry() core.quit() t = trial.getTime() instruction_text.draw() if sound_gen.status == NOT_STARTED: time = trial.getTime() if sound_to_play != BEEP_SOU...
conditional_block
Reber, Kotovsky (1997).py
m_1 = choice(possible_conditions_1.items()) expInfo[u'group'] = condition_mapping_1.index(condition_wm_1[0]) #group == WM_CONDITION expInfo[u'Experiment part'] = u'1' # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc filename = os.path.join(_thisDir, u'data\\{}_{}_{}'.format(expInfo['p...
(name, position, size): return visual.Rect( win=win, name=name, width=size, height=3, pos=position, lineWidth=1, lineColor=[1,1,1], fillColor=[1,1,1], opacity=0, interpolate=True, autoDraw=True, ...
box_open_factory
identifier_name
Reber, Kotovsky (1997).py
m_1 = choice(possible_conditions_1.items()) expInfo[u'group'] = condition_mapping_1.index(condition_wm_1[0]) #group == WM_CONDITION expInfo[u'Experiment part'] = u'1' # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc filename = os.path.join(_thisDir, u'data\\{}_{}_{}'.format(expInfo['p...
def can_move(obj, condition): if not isinstance(obj, visual.Circle): return False index = obj.name if (condition[index] == True) and all(condition[index+1:5] == False): return True return False lst = ['A', 'C', 'D', 'W', 'F'] if expInfo[u'group']in (u'1', u'2', u'3'): number = in...
state = [] for box, circle in zip(boxes, circles): state.append(box.overlaps(circle)) state += [True] return np.array(state)
identifier_body
Reber, Kotovsky (1997).py
ания - вынуть все пять шаров из коробок. Шар можно вынуть или положить обратно в коробку, нажав на него компьютерной мышью. Шар можно вынуть или положить обратно в коробку только в том случае, если верхняя часть коробки открыта. Например, прямо сейчас два шара справа можно вынуть, а три слева – нельзя. В процессе в...
random_line_split
renderer.go
the URL comes after the link text. if !entering { r.outs(w, "\n\\[la]") r.out(w, link.Destination) r.outs(w, "\\[ra]") } } func (r *Renderer) image(w io.Writer, node *ast.Image, entering bool) { // only works with `ascii-art` images if !bytes.HasSuffix(node.Destination, []byte(".ascii-art")) { // remove f...
otnotes(w
identifier_name
renderer.go
.SH ") default: r.outs(w, "\n.SS ") } } } func (r *Renderer) citation(w io.Writer, node *ast.Citation, entering bool) { r.outs(w, "[") for i, dest := range node.Destination { if i > 0 { r.outs(w, ", ") } r.out(w, dest) } r.outs(w, "]") } func (r *Renderer) paragraph(w io.Writer, para *ast.Paragr...
if entering { r.outs(w, "\n.RS\n.TS\nallbox;\n") cells := rows(tab) for r1 := 0; r1 < len(cells); r1++ { align := "" for c := 0; c < len(cells[r1]); c++ { x := cells[r1][c] switch x.Align { case ast.TableAlignmentLeft: align += "l " case ast.TableAlignmentRight: align += "r " ...
func (r *Renderer) table(w io.Writer, tab *ast.Table, entering bool) { // The tbl renderer want to see the entire table's columns, rows first
random_line_split
renderer.go
'url=array-vs-slice.svg' // Text 'Array versus Slice svg' // Text '\n' // Image 'url=array-vs-slice.ascii-art' // Text 'Array versus Slice ascii-art' // // The image with svg will be removed as child and then we continue to walk the AST. for _, child := range figure.GetChildren() { // for ...
if s == "" { return } io.WriteString(w, s) io.WriteString(w, "\n") }
identifier_body
renderer.go
") default: r.outs(w, "\n.SS ") } } } func (r *Renderer) citation(w io.Writer, node *ast.Citation, entering bool) { r.outs(w, "[") for i, dest := range node.Destination { if i > 0 { r.outs(w, ", ") } r.out(w, dest) } r.outs(w, "]") } func (r *Renderer) paragraph(w io.Writer, para *ast.Paragraph...
return } } r.outs(w, "\n.PP\n") return } r.outs(w, "\n") } func (r *Renderer) list(w io.Writer, list *ast.List, entering bool) { if list.IsFootnotesList { return } // normal list if entering { r.allListLevel++ if list.ListFlags&ast.ListTypeOrdered == 0 && list.ListFlags&ast.ListTypeTerm == ...
{ _, ok := c[i].(*ast.Paragraph) if ok { par++ } if c[i] == para { if par > 1 { // No .PP because that messes up formatting. r.outs(w, "\n\n") } } }
conditional_block
main.rs
x)).unwrap_or(format!("")); format!("{}{}{}", name, suffix, ext) } enum CompilationResult { Success { ir_path: PathBuf, llvm_ir: String, cc_output: String, }, Failure { cc_output: String, }, } /// returns the result of compilation with clang (for reference) fn refe...
fn print_output(retval: Option<i32>, output: &str) { colored_print!{ colorize(); Reset, "{}", output; } if let Some(code) = retval { colored_println!{ colorize(); Cyan, "return code"; Reset, ": {}", code; } } } fn print_stderr(stderr...
{ colored_println!{ colorize(); color, "{} ", heading; } }
identifier_body
main.rs
{}", x)).unwrap_or(format!("")); format!("{}{}{}", name, suffix, ext) } enum CompilationResult { Success { ir_path: PathBuf, llvm_ir: String, cc_output: String, }, Failure { cc_output: String, }, } /// returns the result of compilation with clang (for reference) fn ...
.arg("-emit-llvm") .arg("-o") .arg(ir_path.display().to_string()) .arg(src_path.display().to_string()) .output()?; let cc_output = String::from_utf8_lossy(&output.stderr).into_owned(); if !ir_path.exists() { return Ok(CompilationResult::Failure { cc_output }); ...
let output = Command::new("clang") .arg("-O0") .arg("-S")
random_line_split
main.rs
{}", x)).unwrap_or(format!("")); format!("{}{}{}", name, suffix, ext) } enum CompilationResult { Success { ir_path: PathBuf, llvm_ir: String, cc_output: String, }, Failure { cc_output: String, }, } /// returns the result of compilation with clang (for reference) fn ...
{ compilation: CompilationResult, assembly: AssemblyResult, execution: ExecutionResult, } fn do_for(version: Version, path: &Path) -> io::Result<Results> { let (compilation, assembly, execution); // explicitly denote borrowing region { compilation = (version.get_compiler_func())(&path...
Results
identifier_name
wasm3.go
(_signature)) lock.Lock() slot := C.attachFunction(r.Ptr().modules, _moduleName, _functionName, _signature) slotsToCallbacks[int(slot)] = callback lock.Unlock() } // LoadModule wraps m3_LoadModule and returns a module object func (r *Runtime) LoadModule(module *Module) (*Module, error) { if module.Ptr().memoryIm...
{ return (C.IM3Function)(f.ptr) }
identifier_body
wasm3.go
an alias for IM3Environment type EnvironmentT C.IM3Environment // ModuleT is an alias for IM3Module type ModuleT C.IM3Module // FunctionT is an alias for IM3Function type FunctionT C.IM3Function // FuncTypeT is an alias for IM3FuncType type FuncTypeT C.IM3FuncType // ResultT is an alias for M3Result type ResultT C...
var slotsToCallbacks = make(map[int]CallbackFunction) // GetBuf return the internal buffer index func (w *WasiIoVec) GetBuf() uint32 { return uint32(w.buf) } // GetBufLen return the buffer len func (w *WasiIoVec) GetBufLen() int { return int(w.buf_len) } //export dynamicFunctionWrapper func dynamicFunctionWrapper...
// CallbackFunction is the signature for callbacks type CallbackFunction func(runtime RuntimeT, sp unsafe.Pointer, mem unsafe.Pointer) int
random_line_split
wasm3.go
an alias for IM3Environment type EnvironmentT C.IM3Environment // ModuleT is an alias for IM3Module type ModuleT C.IM3Module // FunctionT is an alias for IM3Function type FunctionT C.IM3Function // FuncTypeT is an alias for IM3FuncType type FuncTypeT C.IM3FuncType // ResultT is an alias for M3Result type ResultT C...
if r.cfg.EnableSpecTest { C.m3_LinkSpecTest(r.Ptr().modules) } // if r.cfg.EnableWASI { // C.m3_LinkWASI(r.Ptr().modules) // } return module, nil } // FindFunction calls m3_FindFunction and returns a call function func (r *Runtime) FindFunction(funcName string) (FunctionWrapper, error) { result := C.m3Err_n...
{ return nil, errLoadModule }
conditional_block
wasm3.go
an alias for IM3Environment type EnvironmentT C.IM3Environment // ModuleT is an alias for IM3Module type ModuleT C.IM3Module // FunctionT is an alias for IM3Function type FunctionT C.IM3Function // FuncTypeT is an alias for IM3FuncType type FuncTypeT C.IM3FuncType // ResultT is an alias for M3Result type ResultT C...
(lookupName string) (*Function, error) { var fn *Function for i := 0; i < m.NumFunctions(); i++ { ptr := C
GetFunctionByName
identifier_name
preview_panel.js
Text_ = element.querySelector('.preview-text'); /** * FileSelection to be displayed. * @type {FileSelection} * @private */ this.selection_ = {entries: [], computeBytes: function() {}}; /** * Sequence value that is incremented by every selection update and is used to * check if the callback is ...
}; /** * Update the text in the preview panel. * @private */ PreviewPanel.prototype.updatePreviewArea_ = function() { // If the preview panel is hiding, does not update the current view. if (!this.visible) return; var selection = this.selection_; // If no item is selected, no information is displayed ...
{ this.element_.setAttribute('visibility', PreviewPanel.Visibility_.HIDING); }
conditional_block
preview_panel.js
* Current entry to be displayed. * @type {Entry} * @private */ this.currentEntry_ = null; /** * Dom element of the preview panel. * @type {HTMLElement} * @private */ this.element_ = element; /** * @type {PreviewPanel.Thumbnails} */ this.thumbnails = new PreviewPanel.Thumbnails(...
this.visibilityType_ = visibilityType; /**
random_line_split
preview_panel.js
update and is used to * check if the callback is up to date or not. * @type {number} * @private */ this.sequence_ = 0; /** * @type {VolumeManagerWrapper} * @private */ this.volumeManager_ = volumeManager; cr.EventTarget.call(this); }; /** * Name of PreviewPanels's event. * @enum {stri...
selection
identifier_name
preview_panel.js
Text_ = element.querySelector('.preview-text'); /** * FileSelection to be displayed. * @type {FileSelection} * @private */ this.selection_ = {entries: [], computeBytes: function() {}}; /** * Sequence value that is incremented by every selection update and is used to * check if the callback is ...
}; /** * Initializes the element. */ PreviewPanel.prototype.initialize = function() { this.element_.addEventListener('webkitTransitionEnd', this.onTransitionEnd_.bind(this)); this.updateVisibility_(); // Also update the preview area contents, because the update is suppressed ...
{ this.height_ = this.height_ || this.element_.clientHeight; return this.height_; }
identifier_body
cylinder.rs
derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)] /// Cylinders can be capped in either or both ends. pub enum CylinderCap { Top, Bottom, Both, } impl Display for CylinderCap { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { CylinderCap::Top => write!(f,...
} #[cfg(test)] mod tests { use super::*; use surface::LatticeType::*; fn setup_cylinder(radius: f64, height: f64, lattice: &LatticeType) -> Cylinder { Cylinder { name: None, residue: None, lattice: lattice.clone(), alignment: Direction::Z, ...
fn describe_short(&self) -> String { format!("{} (Cylinder)", unwrap_name(&self.name)) }
random_line_split
cylinder.rs
derive(Clone, Copy, Debug, PartialEq, Deserialize, Serialize)] /// Cylinders can be capped in either or both ends. pub enum CylinderCap { Top, Bottom, Both, } impl Display for CylinderCap { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match *self { CylinderCap::Top => write!(f,...
() { let lattice = PoissonDisc { density: 10.0 }; assert!(setup_cylinder(-1.0, 1.0, &lattice).construct().is_err()); assert!(setup_cylinder(1.0, -1.0, &lattice).construct().is_err()); assert!(setup_cylinder(1.0, 1.0, &lattice).construct().is_ok()); } #[test] fn add_caps_to_...
constructing_cylinder_with_negative_radius_or_height_returns_error
identifier_name
writeAllSln.py
olution1 = [] self.global_presolution2 = [] self.global_postsolution_header = "" # By default include all projects. self.pkgname = "" # Define pattern for first line of Project definition, picking out name (e.g. CalibSvcLib) and # unique id, which appears to be of for...
fp.write(ln)
conditional_block
writeAllSln.py
SolutionDict = {} self.header = [] self.global_presolution1 = [] self.global_presolution2 = [] self.global_postsolution_header = "" # By default include all projects. self.pkgname = "" # Define pattern for first line of Project definition, picking out name (e...
def writeAllSln(self, path): #print "Writing ", path try: fp = open(path, 'w') except: print "Cannot open ", path, " for write" exit(1) try: fp.write(self.header[0]) fp.write(self.header[1]) # Write o...
h1 = fp.readline() h2 = fp.readline() if self.header == []: self.header = [h1, h2] next = fp.readline() while next[:8] == "Project(": next = self.readProject(fp, next, base) # Next should be Global if next[:6] == "Global": return self....
identifier_body
writeAllSln.py
SolutionDict = {} self.header = [] self.global_presolution1 = [] self.global_presolution2 = [] self.global_postsolution_header = "" # By default include all projects. self.pkgname = "" # Define pattern for first line of Project definition, picking out name (e...
(self, path): #print "Writing ", path try: fp = open(path, 'w') except: print "Cannot open ", path, " for write" exit(1) try: fp.write(self.header[0]) fp.write(self.header[1]) # Write out all the projects ...
writeAllSln
identifier_name
writeAllSln.py
SolutionDict = {} self.header = [] self.global_presolution1 = [] self.global_presolution2 = [] self.global_postsolution_header = "" # By default include all projects. self.pkgname = "" # Define pattern for first line of Project definition, picking out name (e...
except: print "failed read past preSolution1" sys.stdout.flush() exit(1) sys.stdout.flush() if next.rfind("postSolution") != -1: if self.global_postsolution_header == "": self.global...
try: next = fp.readline()
random_line_split