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 |
|---|---|---|---|---|
watch_zeromq.py | #!/usr/bin/env python
# | # in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice an... | # Copyright (c) 2017 DevicePilot Ltd.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal | random_line_split |
loader.rs | id and hash criteria that this
// search is being performed for.
let mut libraries = Vec::new();
for (_hash, (rlibs, dylibs)) in candidates.move_iter() {
let mut metadata = None;
let rlib = self.extract_one(rlibs, "rlib", &mut metadata);
let dylib = self.extr... | // Just a small wrapper to time how long reading metadata takes.
fn get_metadata_section(os: Os, filename: &Path) -> Result<MetadataBlob, StrBuf> { | random_line_split | |
loader.rs | let slot = candidates.find_or_insert_with(hash, |_| {
(HashSet::new(), HashSet::new())
});
let (ref mut rlibs, _) = *slot;
rlibs.insert(fs::realpath(path).unwrap());
FileMatches
... | {
diag.handler().note(format!("crate_id: {}", crateid.to_str()));
} | identifier_body | |
loader.rs | .len() > 0 {
format!("found incorrect triple for crate `{}`", self.ident)
} else {
format!("can't find crate for `{}`", self.ident)
};
let message = match self.root {
&None => message,
&Some(ref r) => format!("{} which `{}` depends on",
... | else {
FileDoesntMatch
}
});
// We have now collected all known libraries into a set of candidates
// keyed of the filename hash listed. For each filename, we also have a
// list of rlibs/dylibs that apply. Here, we map each of these lists
// (per ha... | {
info!("dylib candidate: {}", path.display());
match self.try_match(file, dylib_prefix, dysuffix) {
Some(hash) => {
info!("dylib accepted, hash: {}", hash);
let slot = candidates.find_or_insert_with(hash, |_| {
... | conditional_block |
loader.rs | // errors are emitted).
fn extract_one(&mut self, m: HashSet<Path>, flavor: &str,
slot: &mut Option<MetadataBlob>) -> Option<Path> {
let mut ret = None::<Path>;
let mut error = 0;
if slot.is_some() {
// FIXME(#10786): for an optimization, we only read one of ... | meta_section_name | identifier_name | |
LocalStorageServiceSpec.js | // Copyright 2017 The TIE Authors. 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
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by appl... | return true;
}
});
}));
beforeEach(inject(function($injector) {
LocalStorageService = $injector.get('LocalStorageService');
localStorage.clear();
}));
it('should be unavailable', function() {
expect(LocalStorageService.isAvailable()).toBe(f... | doesServerExist: function() { | random_line_split |
pisa_same_entity.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
check same interface phos_binding patterns
"""
import os
import sys
import urllib
import urllib2
import cPickle as pickle
from multiprocessing import Pool
def get_entityid(p):
pdbid,interface_id,chain1,chain2 = p
url = 'http://www.rcsb.org/pdb/rest/customRepo... |
phos_res = set(phos_res)
if len(phos_res) == 1:
one_phos_interfaces.append(interface)
elif len(phos_res) > 1:
more_phos_interfaces.append(interface)
else:
zero_phos_interfaces.append(interface)
print 'after filter non_one_phos_interfaces',len(one... | phos_res.append('_'.join(res2.split('_')[:3])) | conditional_block |
pisa_same_entity.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
check same interface phos_binding patterns
"""
import os
import sys
import urllib
import urllib2
import cPickle as pickle
from multiprocessing import Pool
def get_entityid(p):
pdbid,interface_id,chain1,chain2 = p
url = 'http://www.rcsb.org/pdb/rest/customRepo... | for bondi in bond_info:
res1,res2,dist = bondi
if [p for p in PHOS if res1[-8:] == p]:
res1 = '_'.join(res1.split('_')[:3])
if not res1 in phos_interacting_residues.keys():
... | phos_interacting_residues = {}
PHOS = ['TPO_ O1P','TPO_ O2P','TPO_ O3P','TPO_ OG1','SEP_ O1P','SEP_ O2P','SEP_ O3P','SEP_ OG ','PTR_ O1P','PTR_ O2P','PTR _O3P','PTR OH ']
for bond in bonds:
bond_type,bond_info = bond | random_line_split |
pisa_same_entity.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
check same interface phos_binding patterns
"""
import os
import sys
import urllib
import urllib2
import cPickle as pickle
from multiprocessing import Pool
def get_entityid(p):
pdbid,interface_id,chain1,chain2 = p
url = 'http://www.rcsb.org/pdb/rest/customRepo... | cluster_patterns = []
for c in cluster:
bonds = c[6]
phos_interacting_residues = {}
PHOS = ['TPO_ O1P','TPO_ O2P','TPO_ O3P','TPO_ OG1','SEP_ O1P','SEP_ O2P','SEP_ O3P','SEP_ OG ','PTR_ O1P','PTR_ O2P','PTR _O3P','PTR OH ']
... | pdbid_chain = [(p[0],p[1],p[-1][0][0],p[-1][1][0]) for p in pdb_interfaces]
p = Pool(4)
result = p.map(get_entityid,pdbid_chain)
p.close()
pdb_chain_entity = {}
for r in result:
if not (r[0],r[2],r[3]) in pdb_chain_entity.keys():
pdb_chain_entity[(r[0],r[2],r[3])] = [r]
... | identifier_body |
pisa_same_entity.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
check same interface phos_binding patterns
"""
import os
import sys
import urllib
import urllib2
import cPickle as pickle
from multiprocessing import Pool
def get_entityid(p):
pdbid,interface_id,chain1,chain2 = p
url = 'http://www.rcsb.org/pdb/rest/customRepo... | (pdb_interfaces):
zero_phos_interfaces = []
one_phos_interfaces = []
more_phos_interfaces = []
for interface in pdb_interfaces:
pdbid,p1,interface_area,p2,p3,p4,bonds = interface[:7]
phos_res = []
for bond in bonds:
bond_type,bond_info = bond
for bondi in ... | filter_non_one_phos | identifier_name |
AlfFilmStripViewDocument.js | /**
* Copyright (C) 2005-2015 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at ... | * requested if asked for by the [Film Strip View]{@link module:alfresco/documentlibrary/views/AlfFilmStripView})
* and if the current item is a container then the standard thumbnail is rendered
*
* @instance
*/
postCreate: function alfresco_documentlibrary_views_layouts_AlfFilmS... | random_line_split | |
mixins.py |
import warnings
from xigt.consts import (
ID,
TYPE,
ALIGNMENT,
CONTENT,
SEGMENTATION
)
from xigt.errors import (
XigtError,
XigtStructureError
)
from xigt.ref import id_re
# list.clear() doesn't exist in Python2, but del list[:] has other problems
try:
[].clear
except AttributeError:
... |
def __eq__(self, other):
try:
return (
# quick check for comparing, e.g., XigtCorpus and Igt
self._contained_type == other._contained_type
and len(self) == len(other)
and all(a == b for a, b in zip(self, other))
)
... | self._dict = {}
self._contained_type = contained_type
self._container = container if container is not None else self | identifier_body |
mixins.py | import warnings
from xigt.consts import (
ID,
TYPE,
ALIGNMENT,
CONTENT,
SEGMENTATION
)
from xigt.errors import (
XigtError,
XigtStructureError
)
from xigt.ref import id_re
# list.clear() doesn't exist in Python2, but del list[:] has other problems
try:
[].clear
except AttributeError:
... | # NOTE: this method is destructive. check for broken refs here?
if obj.id is not None:
del self._dict[obj.id]
list.remove(self, obj)
def clear(self):
self._dict.clear()
# list.clear doesn't exist in Python2
# list.clear(self)
listclear(self)
... | def extend(self, objs):
for obj in objs:
self.append(obj)
def remove(self, obj): | random_line_split |
mixins.py |
import warnings
from xigt.consts import (
ID,
TYPE,
ALIGNMENT,
CONTENT,
SEGMENTATION
)
from xigt.errors import (
XigtError,
XigtStructureError
)
from xigt.ref import id_re
# list.clear() doesn't exist in Python2, but del list[:] has other problems
try:
[].clear
except AttributeError:
... |
self._create_id_mapping(obj)
list.__setitem__(self, idx, obj)
def __delitem__(self, obj_id):
# NOTE: this method is destructive. check for broken refs here?
obj = self[obj_id]
self.remove(obj)
def get(self, obj_id, default=None):
try:
return self[ob... | del self._dict[cur_obj.id] | conditional_block |
mixins.py |
import warnings
from xigt.consts import (
ID,
TYPE,
ALIGNMENT,
CONTENT,
SEGMENTATION
)
from xigt.errors import (
XigtError,
XigtStructureError
)
from xigt.ref import id_re
# list.clear() doesn't exist in Python2, but del list[:] has other problems
try:
[].clear
except AttributeError:
... | (object):
def __init__(self, alignment=None, content=None, segmentation=None):
if segmentation and (content or alignment):
raise XigtError(
'The "segmentation" reference attribute cannot co-occur with '
'the "content" or "alignment" reference attributes.'
... | XigtReferenceAttributeMixin | identifier_name |
SignalWifi2BarLockTwoTone.js | , 'SignalWifi2BarLockTwoTone'); | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path fillOpacity=".3" d="M15.5 14.5c0-2.8 2.2-5 5-5 .36 0 .71.04 1.05.11L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7L12 21.5l3.5-4.36V14.5z"... | random_line_split | |
objects.py | # -*- coding: utf-8 -*-
def get_instance_children(obj, depth=0, sig=0):
"""
Récupèration récursive des relations enfants d'un objet
@depth: integer limitant le niveau de recherche des enfants, 0=illimité
"""
children = []
# Pour toute les relations enfants de l'objet
for child in obj._m... | children.append( (verbose_name, unicode(elem), followed) )
return children
| = get_instance_children(elem, depth=depth, sig=sig+1)
| conditional_block |
objects.py | # -*- coding: utf-8 -*-
def get_instance_children(obj, depth=0, sig=0):
| """
Récupèration récursive des relations enfants d'un objet
@depth: integer limitant le niveau de recherche des enfants, 0=illimité
"""
children = []
# Pour toute les relations enfants de l'objet
for child in obj._meta.get_all_related_objects():
# Nom de l'attribut d'accès
c... | identifier_body | |
objects.py | # -*- coding: utf-8 -*-
def | (obj, depth=0, sig=0):
"""
Récupèration récursive des relations enfants d'un objet
@depth: integer limitant le niveau de recherche des enfants, 0=illimité
"""
children = []
# Pour toute les relations enfants de l'objet
for child in obj._meta.get_all_related_objects():
# Nom de l... | get_instance_children | identifier_name |
objects.py | # -*- coding: utf-8 -*-
def get_instance_children(obj, depth=0, sig=0): | children = []
# Pour toute les relations enfants de l'objet
for child in obj._meta.get_all_related_objects():
# Nom de l'attribut d'accès
cname = child.get_accessor_name()
verbose_name = child.model._meta.verbose_name
# Récupère tout les objets des relations
for elem ... | """
Récupèration récursive des relations enfants d'un objet
@depth: integer limitant le niveau de recherche des enfants, 0=illimité
""" | random_line_split |
docextract_webinterface.py | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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 2 ... |
def extract_from_pdf_string(pdf):
"""Extract references from a pdf stored in a string
Given a string representing a pdf, this function writes the string to
disk and passes it to refextract.
We need to create a temoporary file because we need to run pdf2text on it"""
# Save new record to file
... | """Check that the url we received is not gibberish"""
return url.startswith('http://') or \
url.startswith('https://') or \
url.startswith('ftp://') | identifier_body |
docextract_webinterface.py | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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 2 of t... | """
def extract_references(self, req, form):
"""Refrences extraction page
This page can be used for authors to test their pdfs against our
refrences extraction process"""
user_info = collect_user_info(req)
# Handle the 3 POST parameters
if 'pdf' in form and... | <p>URL: <input type="text" name="url" style="width: 600px;"/></p>
<textarea name="txt" style="width: 500px; height: 500px;"></textarea>
<p><input type="submit" /></p>
</form> | random_line_split |
docextract_webinterface.py | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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 2 ... |
return extract_from_pdf_string(form['pdf'].stream.read())
def extract_references_pdf_url(self, req, form):
"""Extract references from the pdf pointed by the passed url"""
check_login(req)
if 'url' not in form:
return 'No URL specified'
url = form['url']
... | return 'No PDF file uploaded' | conditional_block |
docextract_webinterface.py | # -*- coding: utf-8 -*-
##
## This file is part of Invenio.
## Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CERN.
##
## Invenio 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 2 ... | (url):
"""Check that the url we received is not gibberish"""
return url.startswith('http://') or \
url.startswith('https://') or \
url.startswith('ftp://')
def extract_from_pdf_string(pdf):
"""Extract references from a pdf stored in a string
Given a string representing a pdf, th... | check_url | identifier_name |
Batch_Service_operations_should_patch_pool_parameters_successfully.nock.js | // This file has been autogenerated.
exports.setEnvironment = function() {
process.env['AZURE_BATCH_ACCOUNT'] = 'batchtestnodesdk';
process.env['AZURE_BATCH_ENDPOINT'] = 'https://batchtestnodesdk.japaneast.batch.azure.com/';
process.env['AZURE_SUBSCRIPTION_ID'] = '603663e9-700c-46de-9d41-e080ff1d461e';
};
expor... | 'request-id': '14d2a531-7415-4a05-a1ba-07026787bfed',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
dataserviceversion: '3.0',
dataserviceid: 'https://batchtestnodesdk.japaneast.batch.azure.com/pools/nodesdktestpool1',
date: 'Fri, 01 Apr 2016 05:47:01 GMT',
connection: 'close' });
ret... | server: 'Microsoft-HTTPAPI/2.0', | random_line_split |
conf.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Schema for configuration files, exact encoding json/xml to be worked out.
use crate::io::gpio::{PinMode, PullMode};
use serde::Deserialize;
/// Configuration of a... | {
/// Optional specification of transport backend, for which this
/// configuration applies (to be implemented).
pub interface: Option<String>,
/// List of names of other configuration files to include recursively.
#[serde(default)]
pub includes: Vec<String>,
/// List of GPIO pin configurat... | ConfigurationFile | identifier_name |
conf.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
//! Schema for configuration files, exact encoding json/xml to be worked out.
use crate::io::gpio::{PinMode, PullMode};
use serde::Deserialize;
/// Configuration of a... | pub struct StrappingConfiguration {
/// The user-visible name of the strapping combination.
pub name: String,
/// List of GPIO pin configurations (the alias_of) field should not be used in these.
#[serde(default)]
pub pins: Vec<PinConfiguration>,
}
/// Parity configuration for UART communication.
#... |
/// Configuration of a particular GPIO pin.
#[derive(Deserialize, Clone, Debug)] | random_line_split |
event_analysis.py | from tf_idf import *
class EventAnalysis:
"""
Class that contains all the necessary operation to process to a text analysis
"""
@staticmethod
def get_id_website(id_doc, is_website):
"""
Apply the processing to have a website id
"""
return id_doc if not... |
def set_corpus_complete(self):
"""
Define the corpus as complete to proceed to the next step with tf-idf
"""
self.is_corpus_complete = True
self.tf_idf = TfIdf(self.corpus)
def compute_tf_idf(self, term, id_doc):
"""
The id is as follow :
... | """
The id is as follow :
- A description : Event's id
- A website : Event's id + "_"
"""
self.corpus.add_document(Document(text, id_doc)) | identifier_body |
event_analysis.py | from tf_idf import *
class EventAnalysis:
"""
Class that contains all the necessary operation to process to a text analysis
"""
@staticmethod
def get_id_website(id_doc, is_website):
"""
Apply the processing to have a website id
"""
return id_doc if not... | - A description : Event's id
- A website : Event's id + "_"
"""
return self.tf_idf.get_tf_idf(term, id_doc)
def get_tf_idf_the_k_most_important(self, k, id_doc):
"""
Return a OrderedDict that contains the k most important term (sorted by frequences). If there ... |
def compute_tf_idf(self, term, id_doc):
"""
The id is as follow :
| random_line_split |
event_analysis.py | from tf_idf import *
class EventAnalysis:
"""
Class that contains all the necessary operation to process to a text analysis
"""
@staticmethod
def get_id_website(id_doc, is_website):
"""
Apply the processing to have a website id
"""
return id_doc if not... |
if k <= 0:
raise Exception("The k is <= 0 !")
from itertools import islice
from collections import OrderedDict
#Transform OrderedDict(key, tuple(double1, double2)) in OrderedDict(key, double2)
return OrderedDict((x[0], (x[1][0], x[1][1], x[1][2])) for x i... | raise Exception("The corpus is not complete ! Please call set_corpus_complete when you've filled it.") | conditional_block |
event_analysis.py | from tf_idf import *
class EventAnalysis:
"""
Class that contains all the necessary operation to process to a text analysis
"""
@staticmethod
def get_id_website(id_doc, is_website):
"""
Apply the processing to have a website id
"""
return id_doc if not... | (self):
self.corpus = Corpus()
self.is_corpus_complete = False
self.tf_idf = None
def add_document_in_corpus(self, text, id_doc):
"""
The id is as follow :
- A description : Event's id
- A website : Event's id + "_"
"""
self.corpus.... | __init__ | identifier_name |
lista02_exercicio01_questao05.py | # ----------------------------------------------------------
# Introdução a Programação de Computadores - IPC
# Universidade do Estado do Amazonas - UEA
# Prof. Jucimar Jr
# Edson de Lima Barros 1715310043
# Gabriel Nascimento de Oliveira 1715310052
# Luiz Daniel Raposo Nunes de Mello ... |
length_in_meters = int(input('Digite a medida (em metros): '))
length_in_centimeters = length_in_meters * 100
print ('%d metros são %d centímetros' % (length_in_meters, length_in_centimeters)) | #
# 1.5. Faça um Programa que converta metros para centímetros.
# ---------------------------------------------------------- | random_line_split |
test_definition.py | from microscopes.mixture.definition import model_definition
from microscopes.models import bb, niw
from nose.tools import (
assert_equals,
assert_is_not,
)
import pickle
import copy
def test_model_definition_pickle():
defn = model_definition(10, [bb, niw(3)])
bstr = pickle.dumps(defn)
defn1 = pic... | defn = model_definition(10, [bb, niw(3)])
defn_shallow = copy.copy(defn)
defn_deep = copy.deepcopy(defn)
assert_is_not(defn, defn_shallow)
assert_is_not(defn, defn_deep)
assert_is_not(defn._models, defn_deep._models)
assert_equals(defn.n(), defn_shallow.n())
assert_equals(defn.n(), defn_deep... | identifier_body | |
test_definition.py | from microscopes.mixture.definition import model_definition
from microscopes.models import bb, niw
from nose.tools import (
assert_equals,
assert_is_not,
)
import pickle
import copy
def | ():
defn = model_definition(10, [bb, niw(3)])
bstr = pickle.dumps(defn)
defn1 = pickle.loads(bstr)
assert_equals(defn.n(), defn1.n())
assert_equals(len(defn.models()), len(defn1.models()))
for a, b in zip(defn.models(), defn1.models()):
assert_equals(a.name(), b.name())
def test_model_d... | test_model_definition_pickle | identifier_name |
test_definition.py | from microscopes.mixture.definition import model_definition
from microscopes.models import bb, niw
from nose.tools import (
assert_equals,
assert_is_not,
)
import pickle
import copy
def test_model_definition_pickle():
defn = model_definition(10, [bb, niw(3)])
bstr = pickle.dumps(defn)
defn1 = pic... |
def test_model_definition_copy():
defn = model_definition(10, [bb, niw(3)])
defn_shallow = copy.copy(defn)
defn_deep = copy.deepcopy(defn)
assert_is_not(defn, defn_shallow)
assert_is_not(defn, defn_deep)
assert_is_not(defn._models, defn_deep._models)
assert_equals(defn.n(), defn_shallow.n(... | assert_equals(a.name(), b.name()) | conditional_block |
test_definition.py | from microscopes.mixture.definition import model_definition
from microscopes.models import bb, niw
from nose.tools import ( | import copy
def test_model_definition_pickle():
defn = model_definition(10, [bb, niw(3)])
bstr = pickle.dumps(defn)
defn1 = pickle.loads(bstr)
assert_equals(defn.n(), defn1.n())
assert_equals(len(defn.models()), len(defn1.models()))
for a, b in zip(defn.models(), defn1.models()):
asser... | assert_equals,
assert_is_not,
)
import pickle | random_line_split |
angular-locale_en-mt.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_pr... | "DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
],
"ERANAMES": [
"Before Christ",
"Anno Domini"
],
"ERAS": [
"BC",
"AD"
],
... | random_line_split | |
angular-locale_en-mt.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_pr... | var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
... | v = Math.min(getDecimals(n), 3);
}
| conditional_block |
angular-locale_en-mt.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function ge | ) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.va... | tDecimals(n | identifier_name |
angular-locale_en-mt.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
| function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
... | n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
| identifier_body |
EvalForBotnetDetection.py | #!/usr/bin/env python
""" Evaluate the performance of detector
get the statistical quantify for the hypotheis test
like False Alarm Rate.
"""
from __future__ import print_function, division, absolute_import
import copy, os
import collections
from ..Detector import MEM_FS
from ..Detector import BotDetector
from ..util i... | precision=precision,
f1_score=f1_score)
return data_recorder.to_pandas_dataframe()
def run(self):
timeframe_rg = self.desc['timeframe_rg']
thresholds = self.desc['roc_thresholds']
assert len(timeframe_rg) == 2, "unknown fo... | f1_score = 2 * precision * TPR / (precision + TPR)
data_recorder.add(threshold=threshold,
FPR=FPR,
TPR=TPR, | random_line_split |
EvalForBotnetDetection.py | #!/usr/bin/env python
""" Evaluate the performance of detector
get the statistical quantify for the hypotheis test
like False Alarm Rate.
"""
from __future__ import print_function, division, absolute_import
import copy, os
import collections
from ..Detector import MEM_FS
from ..Detector import BotDetector
from ..util i... |
data_frame = data_recorder.to_pandas_dataframe()
data_frame.set_index(['threshold'], drop=False)
return {
'metric': data_frame,
'ground_truth_bot_ips': ground_truth['ground_truth_bot_ips'],
'all_ips': ground_truth['all_ips'],
}
def run(self):
... | bot_detector.desc['threshold'] = threshold
self.logger.info('Start to detect with threshold %s ' % (threshold))
result = bot_detector.detect(None, anomaly_detect=False)
tp, fn, tn, fp, sensitivity, specificity = \
get_detect_metric(ground_truth['ground_truth_bot_ips']... | conditional_block |
EvalForBotnetDetection.py | #!/usr/bin/env python
""" Evaluate the performance of detector
get the statistical quantify for the hypotheis test
like False Alarm Rate.
"""
from __future__ import print_function, division, absolute_import
import copy, os
import collections
from ..Detector import MEM_FS
from ..Detector import BotDetector
from ..util i... | 'all_ips': all_ips,
}
@staticmethod
def get_detected_ips(label_info, detection):
ips = set()
for i, d in enumerate(detection):
if not d:
continue
ips |= set(label_info['win_ips'][i])
return ips
def eval(self):
th... | label_col_name = self.desc['label_col_name']
ip_col_names = self.desc['ip_col_names']
detect_rg = self.desc.get('detect_rg')
rg_type = self.desc['win_type']
assert len(ip_col_names) <= 2, "at most two IP columns are allowed."
fetch_columns = [label_col_name] + ip_col_names
... | identifier_body |
EvalForBotnetDetection.py | #!/usr/bin/env python
""" Evaluate the performance of detector
get the statistical quantify for the hypotheis test
like False Alarm Rate.
"""
from __future__ import print_function, division, absolute_import
import copy, os
import collections
from ..Detector import MEM_FS
from ..Detector import BotDetector
from ..util i... | (self):
thresholds = self.desc['roc_thresholds']
ground_truth = self.get_ground_truth()
self.logger.debug('# of ips in this time frame: %d.' %
(len(ground_truth['all_ips'])))
self.logger.debug('# of bot ips in this time frame: %d.' %
... | eval | identifier_name |
app-init.ts |
function style() {
const NAME = CUSTOMIZE.site_name || "CoCalc";
HELP_EMAIL = CUSTOMIZE.help_email || "help@cocalc.com";
const SITE_DESCR = CUSTOMIZE.site_description || "";
document.title = `${NAME} – ${SITE_DESCR}`;
const msg = document.getElementById("cc-message");
if (msg == null) {
// happens whe... | clearTimeout(lastFn);
lastFn = setTimeout(() => {
if (Date.now() - lastRan >= limit) {
fn(...args);
lastRan = Date.now();
}
}, limit - (Date.now() - lastRan));
}
};
} | conditional_block | |
app-init.ts | CUSTOMIZE.help_email || "help@cocalc.com";
const SITE_DESCR = CUSTOMIZE.site_description || "";
document.title = `${NAME} – ${SITE_DESCR}`;
const msg = document.getElementById("cc-message");
if (msg == null) {
// happens when loading is very quick and message is already removed
return;
}
msg.innerH... | span.style.width = "0%"; | random_line_split | |
app-init.ts | lastRan));
}
};
}
function style() {
const NAME = CUSTOMIZE.site_name || "CoCalc";
HELP_EMAIL = CUSTOMIZE.help_email || "help@cocalc.com";
const SITE_DESCR = CUSTOMIZE.site_description || "";
document.title = `${NAME} – ${SITE_DESCR}`;
const msg = document.getElementById("cc-message");
if (msg == nu... | errorbox.innerHTML = error_msg({
msg,
lineNo,
columnNo,
url,
stack,
show_explanation,
});
}
window.
onerror = handle_window_error;
// magic code to load all webpack assets
// order matters!
const asset_names = ["fill", "css", "pdf.worker", "vendor", "smc"];
const asset_width = Math.max(..... | rror == null) {
// Sometimes this window.onerror gets called with error null.
// We ignore that here. E.g., this happens when you open
// a project sometimes with this input:
// {msg: "ResizeObserver loop limit exceeded", url: "https://cocalc.com/45f...44a1-b842-6eaf5ee07f8f/files/?session=default", li... | identifier_body |
app-init.ts | - lastRan));
}
};
}
function style() {
const NAME = CUSTOMIZE.site_name || "CoCalc";
HELP_EMAIL = CUSTOMIZE.help_email || "help@cocalc.com";
const SITE_DESCR = CUSTOMIZE.site_description || "";
document.title = `${NAME} – ${SITE_DESCR}`;
const msg = document.getElementById("cc-message");
if (msg == ... | ading.err != null) return;
for (const name of asset_names) {
const size = loading.size[name];
const info = DEFLATE_FACTOR * loading.loaded[name];
let msg = `${pad(name, asset_width + 1)} `;
let pct = 0;
if (size != null && size != 0 && info != null && !isNaN(info)) {
if (loading.done[name] !... | ) {
if (lo | identifier_name |
partition_helper_mrbpr.py | # =======================================================================
# This file is part of MCLRE.
#
# MCLRE 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 your ... | # Bi-directional edges
relation_tsv.writerow([relation_id, user1, user2, 1])
relation_tsv.writerow([relation_id, user2, user1, 1])
if __name__ == "__main__":
PARSER = argparse.ArgumentParser()
PARSER.add_argument("-d", "--data_dir", type=str, requir... | """ Generate the weight files """
dict_network_users = defaultdict(set)
# Read the Data and store its grouping variables in GROUP -> USERS and USER -> GROUPs
with open(os.path.join(data_dir, input_filename), "r") as data_file:
data_reader = csv.reader(data_file, delimiter="\t")
for row in ... | identifier_body |
partition_helper_mrbpr.py | # =======================================================================
# This file is part of MCLRE.
#
# MCLRE 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 your ... | (data_dir, input_filename, output_filename, relation_id, max_members):
""" Generate the weight files """
dict_network_users = defaultdict(set)
# Read the Data and store its grouping variables in GROUP -> USERS and USER -> GROUPs
with open(os.path.join(data_dir, input_filename), "r") as data_file:
... | generate_relation | identifier_name |
partition_helper_mrbpr.py | # =======================================================================
# This file is part of MCLRE.
#
# MCLRE 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 your ... |
for user1, user2 in itertools.combinations(dict_network_users[group_id], 2):
# Bi-directional edges
relation_tsv.writerow([relation_id, user1, user2, 1])
relation_tsv.writerow([relation_id, user2, user1, 1])
if __name__ == "__main__":
PA... | dict_network_users[group_id] = random.sample(dict_network_users[group_id], max_members) | conditional_block |
partition_helper_mrbpr.py | # =======================================================================
# This file is part of MCLRE.
#
# MCLRE 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 your ... | help="Input Filename (TSV format)")
PARSER.add_argument("-o", "--output_filename", type=str, required=True,
help="Output Filename")
PARSER.add_argument("-r", "--relation_id", type=int, required=True,
help="MRBPR Relation Id")
PARSER.add... | PARSER = argparse.ArgumentParser()
PARSER.add_argument("-d", "--data_dir", type=str, required=True,
help="Data Directory")
PARSER.add_argument("-i", "--input_filename", type=str, required=True, | random_line_split |
django.js.uncompressed.js | //>>built
define("dojox/highlight/languages/django", ["dojox/main", "../_base", "./xml", "./html"], function(dojox){
var dh = dojox.highlight, dhc = dh.constants, dhl = dh.languages, x = dhl.xml, h = dhl.html;
dhl.django = {
defaultMode: {
contains: ['tag', 'comment', 'doctype', 'template_comment', 'template_ta... | },
{
className: 'argument',
begin: '"', end: '"'
}
]
};
return dhl.django;
}); | 'length': 1, 'phone2numeric': 1, 'wordwrap': 1, 'time': 1,
'addslashes': 1, 'slugify': 1, 'first': 1
},
contains: ['argument'] | random_line_split |
import_whisper.py | #!/usr/bin/env python
# Copyright 2016 Criteo
#
# 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 agree... |
opts = _parse_opts(args)
pool_factory = multiprocessing.Pool
if opts.process == 1:
pool_factory = multiprocessing_dummy.Pool
pool = pool_factory(opts.process, initializer=_setup_process, initargs=(opts,))
out_fd = sys.stderr
if opts.quiet:
out_fd = _DEV_NULL
if "__pypy__"... | args = sys.argv[1:] | conditional_block |
import_whisper.py | #!/usr/bin/env python
# Copyright 2016 Criteo
#
# 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 agree... | total_points += n_points
pbar.update(n_path)
except KeyboardInterrupt:
pool.terminate()
pool.close()
pool.join()
print(
"Uploaded",
walker.count,
"metrics containing",
total_points,
"points",
file=out_fd,
... | ) as pbar:
try:
res = pool.imap_unordered(_import_whisper, paths)
for n_path, n_points in enumerate(res): | random_line_split |
import_whisper.py | #!/usr/bin/env python
# Copyright 2016 Criteo
#
# 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 agree... | return ret
def _setup_process(opts):
global _WORKER
_WORKER = _Worker(opts)
def _import_whisper(*args, **kwargs):
assert _WORKER is not None, "_setup_process was never called"
try:
return _WORKER.import_whisper(*args, **kwargs)
except Exception as e:
log.exception(e)
... | if not self._accessor.is_connected:
self._accessor.connect()
name = metric_name_from_wsp(self._opts.root_directory, self._opts.prefix, path)
metadata = self._read_metadata(name, path)
log.debug("%s: %s" % (name, metadata.as_string_dict()))
if not metadata:
retur... | identifier_body |
import_whisper.py | #!/usr/bin/env python
# Copyright 2016 Criteo
#
# 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 agree... | (self, root_directory, regexp):
self.count = 0
self.root_directory = root_directory
self.regexp = re.compile(regexp)
def paths(self, root=None):
root = root or self.root_directory
for entry in scandir.scandir(root):
if entry.is_dir():
for filename... | __init__ | identifier_name |
util.rs | use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use std::process::{Command, Stdio};
pub trait SplitEOL {
fn split_eol(&self) -> Vec<String>;
}
impl SplitEOL for String {
fn split_eol(&self) -> Vec<String> {
if self.trim() == "" {
Vec::new()
} else {
self.split("\n").map(ToOw... | .stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()?;
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stdout).into_owned();
let status = output.status
.code()
.ok_or(io::Error::new(io::ErrorKind::Other,
... | let output = Command::new(name).args(args)
.stdin(Stdio::null()) | random_line_split |
util.rs | use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use std::process::{Command, Stdio};
pub trait SplitEOL {
fn split_eol(&self) -> Vec<String>;
}
impl SplitEOL for String {
fn split_eol(&self) -> Vec<String> {
if self.trim() == "" {
Vec::new()
} else {
self.split("\n").map(ToOw... | (name: &str, args: &[&str]) -> Result<(String, String, i32), io::Error> {
use std::process::*;
let output = Command::new(name).args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()?;
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stde... | communicate | identifier_name |
util.rs | use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use std::process::{Command, Stdio};
pub trait SplitEOL {
fn split_eol(&self) -> Vec<String>;
}
impl SplitEOL for String {
fn split_eol(&self) -> Vec<String> {
if self.trim() == "" {
Vec::new()
} else {
self.split("\n").map(ToOw... |
pub fn get_lines(name: &str, args: &[&str]) -> Result<Vec<String>, io::Error> {
communicate(name, args).map(|(stdout, _, _)| stdout.split_eol())
}
pub fn read_content<P: AsRef<Path>>(path: P) -> io::Result<String> {
let mut buf = String::new();
File::open(path)
.and_then(|mut f| f.read_to_string(&mut buf))... | {
use std::process::*;
let output = Command::new(name).args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()?;
let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr = String::from_utf8_lossy(&output.stdout).into_owned();
let status ... | identifier_body |
util.rs | use std::fs::File;
use std::io::{self, Read};
use std::path::Path;
use std::process::{Command, Stdio};
pub trait SplitEOL {
fn split_eol(&self) -> Vec<String>;
}
impl SplitEOL for String {
fn split_eol(&self) -> Vec<String> {
if self.trim() == "" | else {
self.split("\n").map(ToOwned::to_owned).collect()
}
}
}
pub fn communicate(name: &str, args: &[&str]) -> Result<(String, String, i32), io::Error> {
use std::process::*;
let output = Command::new(name).args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
... | {
Vec::new()
} | conditional_block |
asteroid-weather.vi.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="vi">
<context>
<name></name>
<message id="id-today">
<location filename="../src/main.qml" line="49"/>
<source>Today</source>
<translation>Hôm nay</translation>
</message>
<message id="id-tomorrow">
... | <location filename="../src/main.qml" line="89"/>
<source><h3>No data</h3>Sync AsteroidOS with your phone.</source>
<translation><h3>Không có dữ liệu</h3>Hãy đồng bộ AsteroidOS với điện thoại của bạn.</translation>
</message>
<message id="id-min">
<location... | <source>Unknown</source>
<translation>Không xác định</translation>
</message>
<message id="id-no-data-sync"> | random_line_split |
packed-struct-with-destructor.rs | idy-linelength
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:set print pretty off
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print packed
// check:$1 = {x = 123, y = 234, z = 345}
// debugger:print packedInPacked
// check:$2 = {a = 1111, b = {x = 2222, y = 3333, z = 4444... | {
x: i64,
y: i32,
z: i16
}
impl Drop for Unpacked {
fn drop(&mut self) {}
}
#[packed]
struct UnpackedInPacked {
a: i16,
b: Unpacked,
c: Unpacked,
d: i64
}
#[packed]
struct PackedInPackedWithDrop {
a: i32,
b: Packed,
c: i64,
d: Packed
}
impl Drop for PackedInPackedWit... | Unpacked | identifier_name |
packed-struct-with-destructor.rs |
// ignore-tidy-linelength
// ignore-android: FIXME(#10381)
// compile-flags:-g
// debugger:set print pretty off
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print packed
// check:$1 = {x = 123, y = 234, z = 345}
// debugger:print packedInPacked
// check:$2 = {a = 1111, b = {x = 2222, y = 33... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split | |
JohnTravoltageModel.js | new Vector2( 309.4189406099519, 448.5906902086678 ),
new Vector2( 322.362760834671, 473.86195826645275 ),
new Vector2( 284.14767255216697, 461.5345104333869 ),
new Vector2( 327.9101123595506, 341.95826645264856 ),
new Vector2( 281.6821829855538, 296.34670947030503 ),
new Vector2( 286... | //this sim are constrained to this shape
this.bodyVertices = [ new Vector2( 422.21508828250404, 455.370786516854 ),
new Vector2( 403.10754414125205, 424.5521669341895 ),
new Vector2( 379.68539325842704, 328.3980738362762 ),
new Vector2( 357.4959871589086, 335.17817014446234 ), | random_line_split | |
JohnTravoltageModel.js | new Electron( point.x, point.y, this, { tandem: tandem } );
}, [], {
tandem: tandem.createTandem( 'electronGroup' ),
phetioType: PhetioGroup.PhetioGroupIO( Electron.ElectronIO )
} );
this.arm = new Arm( tandem.createTandem( 'arm' ) );
this.leg = new Leg( tandem.createTandem( 'leg' ) );
... | {
this.electronGroup.getElement( i ).step( dt );
} | conditional_block | |
JohnTravoltageModel.js | //--------------------------------------------------------------------------
// The following Properties are being used to explore haptic feedback, they
// are to be used in prototypes and view representations are hidden behind
// query parameters
//--------------------------------------------------... | createObjectShape | identifier_name | |
JohnTravoltageModel.js | chargeStartedEmitter.addListener( () => {
numberOfElectronsOnDischargeStart = this.electronGroup.count;
} );
this.dischargeEndedEmitter.addListener( () => {
this.numberOfElectronsDischarged = numberOfElectronsOnDischargeStart - this.electronGroup.count;
} );
//------------------------------... | {
return this.bodyShape.containsPoint( point );
} | identifier_body | |
main.py | import os
import pandas as pd
import sys
import plotter
from PyQt4 import QtGui, QtCore
# The main window inherits from QWidget (an empty window).
class MainLayout(QtGui.QWidget):
def __init__(self):
# Initialize the object as a QWidget
QtGui.QWidget.__init__(self)
self.setWindowTitle("M... |
if __name__ == '__main__':
main()
| os.makedirs('./stocks') | conditional_block |
main.py | import os
import pandas as pd
import sys
import plotter
from PyQt4 import QtGui, QtCore
# The main window inherits from QWidget (an empty window).
class MainLayout(QtGui.QWidget):
def __init__(self):
# Initialize the object as a QWidget
QtGui.QWidget.__init__(self) | self.setWindowTitle("Multiple Stocks Plotter")
self.setMinimumWidth(400)
# Create the vertical box that lays out the whole form
self.layout = QtGui.QVBoxLayout()
# A label of instructions.
self.label = QtGui.QLabel(self)
self.label.setText("Enter the names of th... | random_line_split | |
main.py | import os
import pandas as pd
import sys
import plotter
from PyQt4 import QtGui, QtCore
# The main window inherits from QWidget (an empty window).
class MainLayout(QtGui.QWidget):
def __init__(self):
# Initialize the object as a QWidget
QtGui.QWidget.__init__(self)
self.setWindowTitle("M... |
def main():
# Create the Qt Application
qt_app = QtGui.QApplication(sys.argv)
# Create the layout and show it.
app = MainLayout()
app.run()
qt_app.exec_()
# Create the folder where the stock data (CSV files) will be downloaded.
if not os.path.exists('./stocks'):
os.makedirs('... | self.setFocus()
self.show() # Show the layout. | identifier_body |
main.py | import os
import pandas as pd
import sys
import plotter
from PyQt4 import QtGui, QtCore
# The main window inherits from QWidget (an empty window).
class MainLayout(QtGui.QWidget):
def __init__(self):
# Initialize the object as a QWidget
QtGui.QWidget.__init__(self)
self.setWindowTitle("M... | (self):
# Parse the text in the input box and call the plotter function. Show a
# message box with errors if anything is wrong.
# Get the text from the input field, and create the dataframe.
stock_ids = self.stocks_input.text()
stocks = pd.DataFrame()
# If there's no te... | parse_and_plot | identifier_name |
AppcastReplaceItem.py | #!/usr/bin/env python
"""
Usage:
AppcastReplaceItem <path-to-appcast> <old-version> <new-version> <path-to-dmg>
Example: AppcastReplaceItem appcast-release.xml 1.1.4 1.2 Release/build/Adium_1.2.dmg
"""
# Configurable variables.
app_name = 'Adium'
changelog_fmt = 'http://www.adium.im/changelogs/%(version)s.html'
encl... |
else:
if '</item>' in line:
is_in_item = False
is_correct_item = False
elif '<title>' in line:
if '>%(app_name)s %(old_version)s<' % args in line:
line = line.replace(old_version, version)
is_correct_item = found_correct_item = True
elif is_correct_item:
if'<pubDate>' in line:
line = ' ... | is_in_item = True | conditional_block |
AppcastReplaceItem.py | #!/usr/bin/env python
"""
Usage:
AppcastReplaceItem <path-to-appcast> <old-version> <new-version> <path-to-dmg>
Example: AppcastReplaceItem appcast-release.xml 1.1.4 1.2 Release/build/Adium_1.2.dmg
"""
# Configurable variables.
app_name = 'Adium'
changelog_fmt = 'http://www.adium.im/changelogs/%(version)s.html'
encl... |
# Because XML parsing with the standard library is a PITA, we're going to do it the hackish way.
xmlfile = file(appcast_path)
lines = []
is_in_item = False
is_correct_item = False
found_correct_item = False
for line in xmlfile:
if not is_in_item:
if '<item>' in line:
is_in_item = True
else:
if '</item>' in li... | dmg_filename = os.path.split(dmg_pathname)[1]
url = args['url'] = 'http://adiumx.cachefly.net/' + dmg_filename | random_line_split |
estimate_pi.rs | // A very inefficient way to approximate PI using random number.
//
// with const N: u64 = 100_000_000_000;
// ~14mn
// pi ~= 3.14159183515999985
// error ~= 0.00000081842979327
extern crate pcgrng;
use std::f64;
fn main() | {
let mut rng = pcgrng::PCG32::seed(0, 0);
const N: u64 = 1_000_000;
let mut nb_inside = 0;
for _ in 0..N+1 {
let (x,y) = (rng.next_f64(), rng.next_f64());
let d = x*x + y*y; // check if randomly select point is inside the circle
nb_inside += (d < 1.0) as u64;
};
let pi_... | identifier_body | |
estimate_pi.rs | // A very inefficient way to approximate PI using random number.
//
// with const N: u64 = 100_000_000_000;
// ~14mn
// pi ~= 3.14159183515999985
// error ~= 0.00000081842979327
extern crate pcgrng;
use std::f64;
fn main() {
let mut rng = pcgrng::PCG32::seed(0, 0);
| let (x,y) = (rng.next_f64(), rng.next_f64());
let d = x*x + y*y; // check if randomly select point is inside the circle
nb_inside += (d < 1.0) as u64;
};
let pi_estimate = (4 * nb_inside) as f64 / (N as f64);
println!("pi ~= {:.17}", pi_estimate);
let error = (f64::consts::PI ... | const N: u64 = 1_000_000;
let mut nb_inside = 0;
for _ in 0..N+1 { | random_line_split |
estimate_pi.rs | // A very inefficient way to approximate PI using random number.
//
// with const N: u64 = 100_000_000_000;
// ~14mn
// pi ~= 3.14159183515999985
// error ~= 0.00000081842979327
extern crate pcgrng;
use std::f64;
fn | () {
let mut rng = pcgrng::PCG32::seed(0, 0);
const N: u64 = 1_000_000;
let mut nb_inside = 0;
for _ in 0..N+1 {
let (x,y) = (rng.next_f64(), rng.next_f64());
let d = x*x + y*y; // check if randomly select point is inside the circle
nb_inside += (d < 1.0) as u64;
};
let ... | main | identifier_name |
stack.rs | //! A lock-free stack which supports concurrent pushes and a concurrent call to
//! drain the entire stack all at once.
use std::prelude::v1::*;
use std::sync::atomic::AtomicUsize;
use std::mem;
use std::marker;
use std::sync::atomic::Ordering::SeqCst;
use task::EventSet;
pub struct Stack<T> {
head: AtomicUsize... | fn drop(&mut self) {
for item in self.by_ref() {
drop(item);
}
}
}
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
use std::rc::Rc;
use std::cell::Cell;
use super::Stack;
struct Set(Rc<Cell<usize>>, usize);
impl Drop for Set {
fn drop(&mut self) ... | impl<T> Drop for Drain<T> { | random_line_split |
stack.rs | //! A lock-free stack which supports concurrent pushes and a concurrent call to
//! drain the entire stack all at once.
use std::prelude::v1::*;
use std::sync::atomic::AtomicUsize;
use std::mem;
use std::marker;
use std::sync::atomic::Ordering::SeqCst;
use task::EventSet;
pub struct Stack<T> {
head: AtomicUsize... |
unsafe {
let node = Box::from_raw(self.head);
self.head = node.next;
return Some(node.data)
}
}
}
impl<T> Drop for Drain<T> {
fn drop(&mut self) {
for item in self.by_ref() {
drop(item);
}
}
}
#[cfg(test)]
mod tests {
use... | {
return None
} | conditional_block |
stack.rs | //! A lock-free stack which supports concurrent pushes and a concurrent call to
//! drain the entire stack all at once.
use std::prelude::v1::*;
use std::sync::atomic::AtomicUsize;
use std::mem;
use std::marker;
use std::sync::atomic::Ordering::SeqCst;
use task::EventSet;
pub struct Stack<T> {
head: AtomicUsize... | <T> {
head: *mut Node<T>,
}
impl<T> Stack<T> {
pub fn new() -> Stack<T> {
Stack {
head: AtomicUsize::new(0),
_marker: marker::PhantomData,
}
}
pub fn push(&self, data: T) {
let mut node = Box::new(Node { data: data, next: 0 as *mut _ });
let mut ... | Drain | identifier_name |
stack.rs | //! A lock-free stack which supports concurrent pushes and a concurrent call to
//! drain the entire stack all at once.
use std::prelude::v1::*;
use std::sync::atomic::AtomicUsize;
use std::mem;
use std::marker;
use std::sync::atomic::Ordering::SeqCst;
use task::EventSet;
pub struct Stack<T> {
head: AtomicUsize... |
}
impl<T> Iterator for Drain<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.head.is_null() {
return None
}
unsafe {
let node = Box::from_raw(self.head);
self.head = node.next;
return Some(node.data)
}
}
}
impl... | {
self.drain();
} | identifier_body |
remove_files.py | #!/usr/bin/env python
data = {
"default_prefix": "OSVC_COMP_REMOVE_FILES_",
"example_value": """
[
"/tmp/foo",
"/bar/to/delete"
]
""",
"description": """* Verify files and file trees are uninstalled
""",
"form_definition": """
Desc: |
A rule defining a set of files to remove, fed to the 'remove_files' co... | (CompObject):
def __init__(self, prefix=None):
CompObject.__init__(self, prefix=prefix, data=data)
def init(self):
patterns = self.get_rules()
patterns = sorted(list(set(patterns)))
self.files = self.expand_patterns(patterns)
if len(self.files) == 0:
pinfo(... | CompRemoveFiles | identifier_name |
remove_files.py | #!/usr/bin/env python
data = {
"default_prefix": "OSVC_COMP_REMOVE_FILES_",
"example_value": """
[
"/tmp/foo",
"/bar/to/delete"
]
""",
"description": """* Verify files and file trees are uninstalled
""",
"form_definition": """
Desc: |
A rule defining a set of files to remove, fed to the 'remove_files' co... |
def fix(self):
r = 0
for _file in self.files:
r |= self.fix_file(_file)
return r
if __name__ == "__main__":
main(CompRemoveFiles)
| r = 0
for _file in self.files:
r |= self.check_file(_file)
return r | identifier_body |
remove_files.py | #!/usr/bin/env python
data = {
"default_prefix": "OSVC_COMP_REMOVE_FILES_",
"example_value": """
[
"/tmp/foo",
"/bar/to/delete"
]
""",
"description": """* Verify files and file trees are uninstalled
""",
"form_definition": """
Desc: |
A rule defining a set of files to remove, fed to the 'remove_files' co... | main(CompRemoveFiles) | conditional_block | |
remove_files.py | #!/usr/bin/env python
data = {
"default_prefix": "OSVC_COMP_REMOVE_FILES_",
"example_value": """
[
"/tmp/foo",
"/bar/to/delete"
]
""",
"description": """* Verify files and file trees are uninstalled
""",
"form_definition": """
Desc: | | A rule defining a set of files to remove, fed to the 'remove_files' compliance object.
Css: comp48
Outputs:
-
Dest: compliance variable
Class: remove_files
Type: json
Format: list
Inputs:
-
Id: path
Label: File path
DisplayModeLabel: ""
LabelCss: edit16
Mandatory: Yes
Hel... | random_line_split | |
grpc_connection.d.ts | /**
* @license
* Copyright 2017 Google 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 applica... | implements Connection {
private databaseInfo;
private firestore;
private cachedStub;
constructor(protos: grpc.GrpcObject, databaseInfo: DatabaseInfo);
private sameToken(tokenA, tokenB);
private ensureActiveStub(token);
private getRpcCallable<Req, Resp>(rpcName, token);
invokeRPC... | GrpcConnection | identifier_name |
grpc_connection.d.ts | /**
* @license
* Copyright 2017 Google 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 applica... | import { DatabaseInfo } from '../core/database_info';
import { Connection, Stream } from '../remote/connection';
/**
* A Connection implemented by GRPC-Node.
*/
export declare class GrpcConnection implements Connection {
private databaseInfo;
private firestore;
private cachedStub;
constructor... | * See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as grpc from 'grpc';
import { Token } from '../api/credentials';
| random_line_split |
index.ts | import { AsyncLocalStorage } from 'async_hooks';
import { proxify, proxifyWithWait } from './lib/proxify';
import { IAuthorization } from './types/IAuthorization';
import { IServiceContext } from './types/ServiceClass';
import { IPresence } from './types/IPresence';
import { IAccount } from './types/IAccount';
import ... | export const EnterpriseSettings = proxify<IEnterpriseSettings>('ee-settings');
export const asyncLocalStorage = new AsyncLocalStorage<IServiceContext>(); | random_line_split | |
buildProtocol.ts | /// <reference types="node"/>
import * as ts from "../lib/typescript";
import * as path from "path";
function endsWith(s: string, suffix: string) {
return s.lastIndexOf(suffix, s.length - suffix.length) !== -1;
}
function isStringEnum(declaration: ts.EnumDeclaration) {
return declaration.members.le... |
this.visitedTypes.push(type);
const s = type.aliasSymbol || type.getSymbol();
if (!s) {
return;
}
if (s.name === "Array" || s.name === "ReadOnlyArray") {
// we should process type argument instead
return this.processType((type as any).... | {
return;
} | conditional_block |
buildProtocol.ts | /// <reference types="node"/>
import * as ts from "../lib/typescript";
import * as path from "path";
function endsWith(s: string, suffix: string) {
return s.lastIndexOf(suffix, s.length - suffix.length) !== -1;
}
function isStringEnum(declaration: ts.EnumDeclaration) {
return declaration.members.le... | () { return "\r\n"; }
};
const diags = emitResult.diagnostics.map(d => ts.formatDiagnostic(d, diagHost)).join("\r\n");
throw new Error(`Declaration file for protocol.ts is not generated:\r\n${diags}`);
}
return protocolDts;
}
const protocolFileName = ... | getNewLine | identifier_name |
buildProtocol.ts | /// <reference types="node"/>
import * as ts from "../lib/typescript";
import * as path from "path";
function endsWith(s: string, suffix: string) {
return s.lastIndexOf(suffix, s.length - suffix.length) !== -1;
}
function isStringEnum(declaration: ts.EnumDeclaration) {
return declaration.members.le... |
}
function writeProtocolFile(outputFile: string, protocolTs: string, typeScriptServicesDts: string) {
const options = { target: ts.ScriptTarget.ES5, declaration: true, noResolve: false, types: [] as string[], stripInternal: true };
/**
* 1st pass - generate a program from protocol.ts and typescri... | {
if (node.kind === ts.SyntaxKind.UnionType) {
for (const t of (node as ts.UnionTypeNode).types) {
this.processTypeOfNode(t);
}
}
else {
const type = this.typeChecker.getTypeAtLocation(node);
if (type && !(type.flags & (ts.T... | identifier_body |
buildProtocol.ts | /// <reference types="node"/>
import * as ts from "../lib/typescript";
import * as path from "path";
function endsWith(s: string, suffix: string) {
return s.lastIndexOf(suffix, s.length - suffix.length) !== -1;
}
function isStringEnum(declaration: ts.EnumDeclaration) {
return declaration.members.le... | });
if (protocolDts === undefined) {
const diagHost: ts.FormatDiagnosticsHost = {
getCanonicalFileName(f) { return f; },
getCurrentDirectory() { return "."; },
getNewLine() { return "\r\n"; }
};
const diags = em... | let protocolDts: string | undefined;
const emitResult = program.emit(program.getSourceFile(protocolTs), (file, content) => {
if (endsWith(file, ".d.ts")) {
protocolDts = content;
}
| random_line_split |
ListRemoveWithIndexCodec.ts | /* tslint:disable */
import ClientMessage = require('../ClientMessage');
import {BitsUtil} from '../BitsUtil';
import {Data} from '../serialization/Data';
import {ListMessageType} from './ListMessageType';
import Address = require('../Address');
import DistributedObjectInfoCodec = require('./DistributedObjectInfoCodec'... | parameters['response'] = toObjectFunction(clientMessage.readData());
}
return parameters;
}
} | if (clientMessage.readBoolean() !== true) { | random_line_split |
ListRemoveWithIndexCodec.ts | /* tslint:disable */
import ClientMessage = require('../ClientMessage');
import {BitsUtil} from '../BitsUtil';
import {Data} from '../serialization/Data';
import {ListMessageType} from './ListMessageType';
import Address = require('../Address');
import DistributedObjectInfoCodec = require('./DistributedObjectInfoCodec'... |
return parameters;
}
}
| {
parameters['response'] = toObjectFunction(clientMessage.readData());
} | conditional_block |
ListRemoveWithIndexCodec.ts | /* tslint:disable */
import ClientMessage = require('../ClientMessage');
import {BitsUtil} from '../BitsUtil';
import {Data} from '../serialization/Data';
import {ListMessageType} from './ListMessageType';
import Address = require('../Address');
import DistributedObjectInfoCodec = require('./DistributedObjectInfoCodec'... | (name: string, index: number) {
// Encode request into clientMessage
var clientMessage = ClientMessage.newClientMessage(this.calculateSize(name, index));
clientMessage.setMessageType(REQUEST_TYPE);
clientMessage.setRetryable(RETRYABLE);
clientMessage.appendString(name);
clientMes... | encodeRequest | identifier_name |
ListRemoveWithIndexCodec.ts | /* tslint:disable */
import ClientMessage = require('../ClientMessage');
import {BitsUtil} from '../BitsUtil';
import {Data} from '../serialization/Data';
import {ListMessageType} from './ListMessageType';
import Address = require('../Address');
import DistributedObjectInfoCodec = require('./DistributedObjectInfoCodec'... |
static decodeResponse(clientMessage: ClientMessage, toObjectFunction: (data: Data) => any = null) {
// Decode response from client message
var parameters: any = {'response': null};
if (clientMessage.readBoolean() !== true) {
parameters['response'] = toObjectFunction(clientMessage.read... | {
// Encode request into clientMessage
var clientMessage = ClientMessage.newClientMessage(this.calculateSize(name, index));
clientMessage.setMessageType(REQUEST_TYPE);
clientMessage.setRetryable(RETRYABLE);
clientMessage.appendString(name);
clientMessage.appendInt32(index);
... | identifier_body |
windowing.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Abstract windowing methods. The concrete implementations of these can be found in `platform/`.
use compositor... | {
Forward,
Back,
}
/// Events that the windowing system sends to Servo.
#[derive(Clone)]
pub enum WindowEvent {
/// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps
/// by another Servo subsystem).
///
/// FIXME(pcwalton): This is kind of ugly and may no... | WindowNavigateMsg | identifier_name |
windowing.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Abstract windowing methods. The concrete implementations of these can be found in `platform/`.
use compositor... | /// Sets the load data for the current page.
fn set_page_url(&self, url: ServoUrl);
/// Called when the browser chrome should display a status message.
fn status(&self, Option<String>);
/// Called when the browser has started loading a frame.
fn load_start(&self, back: bool, forward: bool);
... | fn set_page_title(&self, title: Option<String>); | random_line_split |
select_handler.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
///
/// Implementation of the callbacks that the CSS selector engine uses to query the DOM.
///
use dom::node::Ab... |
pub struct NodeSelectHandler {
node: AbstractNode
}
fn with_node_name<R>(node: AbstractNode, f: &fn(&str) -> R) -> R {
if !node.is_element() {
fail!(~"attempting to style non-element node");
}
do node.with_imm_element |element_n| {
f(element_n.tag_name)
}
}
impl SelectHandler<Abst... | use core::str::eq_slice; | random_line_split |
select_handler.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
///
/// Implementation of the callbacks that the CSS selector engine uses to query the DOM.
///
use dom::node::Ab... | (&self, node: &AbstractNode, name: &str) -> Option<AbstractNode> {
match node.parent_node() {
Some(parent) => {
do with_node_name(parent) |node_name| {
if eq_slice(name, node_name) {
Some(parent)
} else {
... | named_parent_node | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.