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
command.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
logger.debug(f"Executing `{invocation}`") return subprocess.run(invocation, **kwargs) def __call__(self, *argv, **kwargs): self.run(*argv, **kwargs)
kwargs["check"] = True
conditional_block
command.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(executable): exec_exists = os.path.exists(executable) return executable if exec_exists else shutil.which(executable) # Decorator running a command and returning stdout class capture_stdout: def __init__(self, strip=False): self.strip = strip def __call__(self, f): def strip_it(x): ...
find_exec
identifier_name
bool.js
/** * This file is part of the Unit.js testing framework. * * (c) Nicolas Tallefourtane <dev@nicolab.net> * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code * or visit {@link http://unitjs.com|Unit.js}. * * @author Nicolas Tallefourt...
} // assert the type assertions.isBool(this.actual); // provides the assertions to the current asserter var useAssertions = ['isTrue', 'isNotTrue', 'isFalse', 'isNotFalse']; var asserterAssertions = _.pick(assertions, useAssertions); for (var method in asserterAssertions) { this[method] = asserte...
for (var method in commonApi) { this[method] = commonApi[method];
random_line_split
parse_shear.py
#!/usr/bin/env python # Usage parse_shear sequences.fna a2t.txt emb_output.b6 import sys import csv from collections import Counter, defaultdict sequences = sys.argv[1] accession2taxonomy = sys.argv[2] alignment = sys.argv[3] with open(accession2taxonomy) as inf: next(inf) csv_inf = csv.reader(inf...
reads_counter = Counter() with open(sequences) as inf: for i, line in enumerate(inf): if i % 100000 == 0: print("Processed %d lines" % i) print(line) if line.startswith('>'): name = '_'.join(line.split()[0][1:].split('_')[:-1]).split('.')[0] if...
random_line_split
parse_shear.py
#!/usr/bin/env python # Usage parse_shear sequences.fna a2t.txt emb_output.b6 import sys import csv from collections import Counter, defaultdict sequences = sys.argv[1] accession2taxonomy = sys.argv[2] alignment = sys.argv[3] with open(accession2taxonomy) as inf: next(inf) csv_inf = csv.reader(inf...
print("Loaded read counter") counts_dict = defaultdict(Counter) with open(alignment) as inf: csv_inf = csv.reader(inf, delimiter="\t") for i, row in enumerate(csv_inf): if i % 100000 == 0: print("Processed %d records" % i) print(row) if row[-1].startswith('k...
species = a2t[name] reads_counter.update([species])
conditional_block
markdown.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
Some(out.into_owned()) } /// Render `input` (e.g. "foo.md") into an HTML file in `output` /// (e.g. output = "bar" => "bar/foo.html"). pub fn render(input: &str, mut output: Path, matches: &getopts::Matches) -> int { let input_p = Path::new(input); output.push(input_p.filestem().unwrap()); output.set_e...
random_line_split
markdown.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(Some(a), Some(b), Some(c)) => (a,b,c), _ => return 3 }; let mut out = match io::File::create(&output) { Err(e) => { let _ = writeln!(&mut io::stderr(), "error opening `{}` for writing: {}", output.display(), e); ...
{ let input_p = Path::new(input); output.push(input_p.filestem().unwrap()); output.set_extension("html"); let mut css = StrBuf::new(); for name in matches.opt_strs("markdown-css").iter() { let s = format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{}\">\n", name); css.push_s...
identifier_body
markdown.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'a>(s: &'a str) -> (Vec<&'a str>, &'a str) { let mut metadata = Vec::new(); for line in s.lines() { if line.starts_with("%") { // remove %<whitespace> metadata.push(line.slice_from(1).trim_left()) } else { let line_start_byte = s.subslice_offset(line); ...
extract_leading_metadata
identifier_name
DbRepeaterList.js
//* @protected enyo.kind({ name: "enyo.DbRepeaterList", kind: enyo.VFlexBox, published: { pageSize: 50, stripSize: 20 }, events: { onQuery: "", onSetupRow: "" }, chrome: [ {kind: "Scroller", flex: 1, accelerated: false, components: [ {name: "client", kind: enyo.VirtualRepeater, accelerated: true, on...
return record; }, rendered: function() { this.inherited(arguments); if (this.bottomUp) { this.scrollToBottom(); } }, scrollToBottom: function() { this.$.scroller.scrollToBottom(); }, build: function() { // destroy previous request to make sure to cancel any watches if (this.request) { this.re...
{ this.doSetupRow(record, inIndex); return true; }
conditional_block
DbRepeaterList.js
//* @protected enyo.kind({ name: "enyo.DbRepeaterList", kind: enyo.VFlexBox, published: { pageSize: 50, stripSize: 20 }, events: { onQuery: "", onSetupRow: "" }, chrome: [ {kind: "Scroller", flex: 1, accelerated: false, components: [ {name: "client", kind: enyo.VirtualRepeater, accelerated: true, on...
}, queryResponse: function(inResponse, inRequest) { // cache request object so it's possible to destroy. this.request = inRequest; this.data = inResponse.results; if (this.bottomUp) { this.data.reverse(); } this.render(); }, updateRow: function(inIndex) { this.$.client.renderRow(inIndex); }, refr...
return this.doQuery(query);
random_line_split
export_all_courses.py
""" Script for exporting all courseware from Mongo to a directory and listing the courses which failed to export """ from django.core.management.base import BaseCommand from six import text_type from xmodule.contentstore.django import contentstore from xmodule.modulestore.django import modulestore from xmodule.modul...
return courses, failed_export_courses
print("-" * 80) print(u"Exporting course id = {0} to {1}".format(course_id, output_path)) try: course_dir = text_type(course_id).replace('/', '...') export_course_to_xml(module_store, content_store, course_id, root_dir, course_dir) except Exception as err: # pylint: disa...
conditional_block
export_all_courses.py
""" Script for exporting all courseware from Mongo to a directory and listing the courses which failed to export """ from django.core.management.base import BaseCommand from six import text_type from xmodule.contentstore.django import contentstore from xmodule.modulestore.django import modulestore from xmodule.modul...
help = 'Export all courses from mongo to the specified data directory and list the courses which failed to export' def add_arguments(self, parser): parser.add_argument('output_path') def handle(self, *args, **options): """ Execute the command """ courses, failed_exp...
class Command(BaseCommand): """ Export all courses from mongo to the specified data directory and list the courses which failed to export """
random_line_split
export_all_courses.py
""" Script for exporting all courseware from Mongo to a directory and listing the courses which failed to export """ from django.core.management.base import BaseCommand from six import text_type from xmodule.contentstore.django import contentstore from xmodule.modulestore.django import modulestore from xmodule.modul...
def export_courses_to_output_path(output_path): """ Export all courses to target directory and return the list of courses which failed to export """ content_store = contentstore() module_store = modulestore() root_dir = output_path courses = module_store.get_courses() course_ids = [x...
""" Execute the command """ courses, failed_export_courses = export_courses_to_output_path(options['output_path']) print("=" * 80) print("=" * 30 + "> Export summary") print(u"Total number of courses to export: {0}".format(len(courses))) print(u"Total number of c...
identifier_body
export_all_courses.py
""" Script for exporting all courseware from Mongo to a directory and listing the courses which failed to export """ from django.core.management.base import BaseCommand from six import text_type from xmodule.contentstore.django import contentstore from xmodule.modulestore.django import modulestore from xmodule.modul...
(self, *args, **options): """ Execute the command """ courses, failed_export_courses = export_courses_to_output_path(options['output_path']) print("=" * 80) print("=" * 30 + "> Export summary") print(u"Total number of courses to export: {0}".format(len(courses)))...
handle
identifier_name
testMovies.py
from __future__ import division import numpy as np from Tkinter import * import json import io import unicodecsv as csv #import csv #file = open("moviesTest-1970.txt",'r') act = open("invertedIndexActorsWeightedAll.txt",'r') dir = open("invertedIndexDirectorsWeightedAll.txt", 'r') wri = open("invertedIndexWritersWeig...
#line = file.readline() lact = act.readline() ldir = dir.readline() lwri = wri.readline() #gson = json.loads(line) jact = json.loads(lact) jdir = json.loads(ldir) jwri = json.loads(lwri) #file.close() act.close() dir.close() wri.close() class Test: def calcolaMedie(self,actors,directors,writers): me...
random_line_split
testMovies.py
from __future__ import division import numpy as np from Tkinter import * import json import io import unicodecsv as csv #import csv #file = open("moviesTest-1970.txt",'r') act = open("invertedIndexActorsWeightedAll.txt",'r') dir = open("invertedIndexDirectorsWeightedAll.txt", 'r') wri = open("invertedIndexWritersWeig...
line = file.readline() print line gson = json.loads(line) file.close() vector = [] input = [] labels = [] titles = [] #indice = 0 for elem in gson: #titles.append(gson.get(elem).get("title")) actors = gson.get(elem)....
def calcolaMedie(self,actors,directors,writers): mediaAct = 0 mediaDir = 0 mediaWri = 0 for elem in actors: print elem mediaAct += float(jact.get(elem).get("rating")) for elem in directors: mediaDir += float(jdir.get(elem).get("rating")) ...
identifier_body
testMovies.py
from __future__ import division import numpy as np from Tkinter import * import json import io import unicodecsv as csv #import csv #file = open("moviesTest-1970.txt",'r') act = open("invertedIndexActorsWeightedAll.txt",'r') dir = open("invertedIndexDirectorsWeightedAll.txt", 'r') wri = open("invertedIndexWritersWeig...
(self,data,theta): max = 0 ind = 0 p = self.hypothesis(data,theta) for k, x in enumerate(p): if x > max: max = x ind = k pred_lab = ind+1 return pred_lab #### reads the theta from file #### def getTheta(self): filen...
singleTest
identifier_name
testMovies.py
from __future__ import division import numpy as np from Tkinter import * import json import io import unicodecsv as csv #import csv #file = open("moviesTest-1970.txt",'r') act = open("invertedIndexActorsWeightedAll.txt",'r') dir = open("invertedIndexDirectorsWeightedAll.txt", 'r') wri = open("invertedIndexWritersWeig...
mediaAct = float(mediaAct/len(actors)) mediaDir = float(mediaDir/len(directors)) mediaWri = float(mediaWri/len(writers)) return mediaAct,mediaDir,mediaWri #### extract data from the json files #### def readData(self,filename): file = open(filename, 'r') line = ...
mediaWri += float(jwri.get(elem).get("rating"))
conditional_block
dhcpwn.py
#!/usr/bin/env python3 import argparse import logging import string # Quiet scapy logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy import volatile # noqa: E402 from scapy import sendrecv # noqa: E402 from scapy import config # noqa: E402 from scapy.layers import l2 # noqa: E402 from scapy.la...
def print_dhcp_response(response): print("Source: {}".format(response[l2.Ether].src)) print("Destination: {}".format(response[l2.Ether].dst)) for option in response[dhcp.DHCP].options: if isinstance(option, tuple): option, *values = option else: # For some reason ...
iface = kwargs["interface"] count = kwargs["count"] unique_hexdigits = str.encode("".join(set(string.hexdigits.lower()))) packet = ( l2.Ether(dst="ff:ff:ff:ff:ff:ff") / inet.IP(src="0.0.0.0", dst="255.255.255.255") / inet.UDP(sport=68, dport=67) / dhcp.BOOTP(chaddr=volatile....
identifier_body
dhcpwn.py
#!/usr/bin/env python3 import argparse import logging import string # Quiet scapy logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy import volatile # noqa: E402 from scapy import sendrecv # noqa: E402 from scapy import config # noqa: E402 from scapy.layers import l2 # noqa: E402 from scapy.la...
type=int, help='number of addresses to consume' ) subparsers.add_parser('sniff') args = p.parse_args() return args def main(): args = parse_args() dispatch = { "flood": dhcp_flood, "sniff": dhcp_sniff, } dispatch[args.command](**vars(args)) if __na...
action='store', default=10,
random_line_split
dhcpwn.py
#!/usr/bin/env python3 import argparse import logging import string # Quiet scapy logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy import volatile # noqa: E402 from scapy import sendrecv # noqa: E402 from scapy import config # noqa: E402 from scapy.layers import l2 # noqa: E402 from scapy.la...
print(output) def dhcp_sniff(**kwargs): sendrecv.sniff(filter="udp and (port 67 or 68)", prn=print_dhcp_response) def parse_args(): p = argparse.ArgumentParser(description=''' All your IPs are belong to us. ''', formatter_class=argparse.RawTextHelpFormatter) p.add_argument( ...
dhcp_type = dhcp.DHCPTypes.get(values[0], "unknown") output = "{} ({})".format(output, dhcp_type)
conditional_block
dhcpwn.py
#!/usr/bin/env python3 import argparse import logging import string # Quiet scapy logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy import volatile # noqa: E402 from scapy import sendrecv # noqa: E402 from scapy import config # noqa: E402 from scapy.layers import l2 # noqa: E402 from scapy.la...
(**kwargs): sendrecv.sniff(filter="udp and (port 67 or 68)", prn=print_dhcp_response) def parse_args(): p = argparse.ArgumentParser(description=''' All your IPs are belong to us. ''', formatter_class=argparse.RawTextHelpFormatter) p.add_argument( '-i', '--interface', ...
dhcp_sniff
identifier_name
bit_map.ts
import { word } from 'js/types'; import { ProDOSVolume } from '.'; import type { VDH } from './vdh'; const BLOCK_ENTRIES = 4096; export class BitMap { private vdh: VDH; private blocks: Uint8Array[]; constructor(volume: ProDOSVolume) { this.vdh = volume.vdh(); this.blocks = volume.blocks()...
throw new Error('Disk full'); } freeBlock(block: word) { if (block >= this.vdh.totalBlocks) { throw new Error('Block out of range'); } const blockOffset = this.vdh.bitMapPointer + Math.floor(block / BLOCK_ENTRIES); const byteOffset = (block - blockOffset * B...
{ const blockOffset = this.vdh.bitMapPointer + Math.floor(idx / BLOCK_ENTRIES); const bitMapBlock = this.blocks[blockOffset]; const byteOffset = (idx - blockOffset * BLOCK_ENTRIES) >> 8; const bits = bitMapBlock[byteOffset]; if (bits !== 0xff) { ...
conditional_block
bit_map.ts
import { word } from 'js/types'; import { ProDOSVolume } from '.'; import type { VDH } from './vdh'; const BLOCK_ENTRIES = 4096; export class BitMap { private vdh: VDH; private blocks: Uint8Array[]; constructor(volume: ProDOSVolume) { this.vdh = volume.vdh(); this.blocks = volume.blocks()...
(block: word) { if (block >= this.vdh.totalBlocks) { throw new Error('Block out of range'); } const blockOffset = this.vdh.bitMapPointer + Math.floor(block / BLOCK_ENTRIES); const byteOffset = (block - blockOffset * BLOCK_ENTRIES) >> 8; const bitOffset = block & 0x7; ...
freeBlock
identifier_name
bit_map.ts
import { word } from 'js/types'; import { ProDOSVolume } from '.'; import type { VDH } from './vdh'; const BLOCK_ENTRIES = 4096; export class BitMap { private vdh: VDH; private blocks: Uint8Array[]; constructor(volume: ProDOSVolume) { this.vdh = volume.vdh(); this.blocks = volume.blocks()...
throw new Error('Disk full'); } freeBlock(block: word) { if (block >= this.vdh.totalBlocks) { throw new Error('Block out of range'); } const blockOffset = this.vdh.bitMapPointer + Math.floor(block / BLOCK_ENTRIES); const byteOffset = (block - blockOffset * BL...
random_line_split
bit_map.ts
import { word } from 'js/types'; import { ProDOSVolume } from '.'; import type { VDH } from './vdh'; const BLOCK_ENTRIES = 4096; export class BitMap { private vdh: VDH; private blocks: Uint8Array[]; constructor(volume: ProDOSVolume) { this.vdh = volume.vdh(); this.blocks = volume.blocks()...
freeBlock(block: word) { if (block >= this.vdh.totalBlocks) { throw new Error('Block out of range'); } const blockOffset = this.vdh.bitMapPointer + Math.floor(block / BLOCK_ENTRIES); const byteOffset = (block - blockOffset * BLOCK_ENTRIES) >> 8; const bitOffset ...
{ for (let idx = 0; idx < this.vdh.totalBlocks; idx++) { const blockOffset = this.vdh.bitMapPointer + Math.floor(idx / BLOCK_ENTRIES); const bitMapBlock = this.blocks[blockOffset]; const byteOffset = (idx - blockOffset * BLOCK_ENTRIES) >> 8; const bits = bitMapBlo...
identifier_body
events.rs
use std::collections::{HashMap}; ///All user events pass through and/or are recorded in this structure. pub struct Events { ///Central Dispatch pub messages: Vec<Vec<String>>, /// Component State pub state: String, /// Global Key-Val State pub keyval: HashMap<String,String>, /// Time elapsed si...
///Send a method to central dispatch pub fn message(&mut self, msg: Vec<String>) { self.messages.push( msg ) } ///Set a state variable pub fn set(&mut self, key: &str, val: &str) { self.keyval.insert(key.to_string(), val.to_string()); } ///Get a state variable pub fn get(&mut self, ...
{ Events { messages: Vec::new(), state: "".to_owned(), keyval: HashMap::new(), time_elapsed: 0.0, } }
identifier_body
events.rs
use std::collections::{HashMap}; ///All user events pass through and/or are recorded in this structure. pub struct Events { ///Central Dispatch pub messages: Vec<Vec<String>>, /// Component State pub state: String, /// Global Key-Val State pub keyval: HashMap<String,String>, /// Time elapsed si...
impl Events { ///Creates a new Events object. Used in Window rendering and is not meant for general use. pub fn new() -> Events { Events { messages: Vec::new(), state: "".to_owned(), keyval: HashMap::new(), time_elapsed: 0.0, } } ///Send a method to central di...
random_line_split
events.rs
use std::collections::{HashMap}; ///All user events pass through and/or are recorded in this structure. pub struct Events { ///Central Dispatch pub messages: Vec<Vec<String>>, /// Component State pub state: String, /// Global Key-Val State pub keyval: HashMap<String,String>, /// Time elapsed si...
(&mut self, key: &str, val: &str) { self.keyval.insert(key.to_string(), val.to_string()); } ///Get a state variable pub fn get(&mut self, key: &str) -> String { self.keyval.get(&key.to_string()).unwrap_or(&"".to_string()).clone() } }
set
identifier_name
fake_server.py
import asyncio class FakeProtocol(asyncio.Protocol): def __init__(self, name): self.name = name self.connections_made = 0 self.data = [] self.connection_errors = [] self.expected_received = 0 self.expected = 0 self.connected = asyncio.Future() self.c...
self.transport = transport self.connections_made += 1 self.connected.set_result(None) def data_received(self, data): print("%s: data received" % self.name) self.data.append(data) if self.expectation and not self.expectation.done(): self.expected_received ...
def connection_made(self, transport): print("%s: connection made" % self.name)
random_line_split
fake_server.py
import asyncio class FakeProtocol(asyncio.Protocol): def __init__(self, name): self.name = name self.connections_made = 0 self.data = [] self.connection_errors = [] self.expected_received = 0 self.expected = 0 self.connected = asyncio.Future() self.c...
def connection_lost(self, exc): print("%s: connection lost" % self.name) self.closed.set_result(None) self.connected = asyncio.Future() self.connection_errors.append(exc) def expect(self, count): self.expected_received = 0 self.expected = count self.exp...
print("%s: data received" % self.name) self.data.append(data) if self.expectation and not self.expectation.done(): self.expected_received += len(data) if self.expected_received >= self.expected: self.expectation.set_result(None)
identifier_body
fake_server.py
import asyncio class FakeProtocol(asyncio.Protocol): def __init__(self, name): self.name = name self.connections_made = 0 self.data = [] self.connection_errors = [] self.expected_received = 0 self.expected = 0 self.connected = asyncio.Future() self.c...
def connection_lost(self, exc): print("%s: connection lost" % self.name) self.closed.set_result(None) self.connected = asyncio.Future() self.connection_errors.append(exc) def expect(self, count): self.expected_received = 0 self.expected = count self.exp...
self.expected_received += len(data) if self.expected_received >= self.expected: self.expectation.set_result(None)
conditional_block
fake_server.py
import asyncio class FakeProtocol(asyncio.Protocol): def __init__(self, name): self.name = name self.connections_made = 0 self.data = [] self.connection_errors = [] self.expected_received = 0 self.expected = 0 self.connected = asyncio.Future() self.c...
(self, count): self.expected_received = 0 self.expected = count self.expectation = asyncio.Future() return self.expectation def write(self, msg): self.transport.write(msg)
expect
identifier_name
ngModuleData.js
// Regex adapted from https://github.com/ceymard/gulp-ngcompile
module.exports = function processContent(fileContent, materialOnly) { var NG_MODULE_REGEX = materialOnly ? /\.module\(('material\.[^']*'|"material\.[^"]*")\s*,(?:\s*\[([^\]]+)\])?/g : /\.module\(('[^']*'|"[^"]*")\s*,(?:\s*\[([^\]]+)\])?/g; var match = NG_MODULE_REGEX.exec(fileContent || ''); var module = match &&...
random_line_split
ngModuleData.js
// Regex adapted from https://github.com/ceymard/gulp-ngcompile module.exports = function processContent(fileContent, materialOnly) { var NG_MODULE_REGEX = materialOnly ? /\.module\(('material\.[^']*'|"material\.[^"]*")\s*,(?:\s*\[([^\]]+)\])?/g : /\.module\(('[^']*'|"[^"]*")\s*,(?:\s*\[([^\]]+)\])?/g; var match =...
return { module: module || '', dependencies: dependencies }; };
{ dependencies = depsMatch.split(/\s*,\s*/).map(function(dep) { dep = dep.slice(1, -1); //remove quotes return dep; }); }
conditional_block
parser.py
from __future__ import print_function, absolute_import import re class CNFParser(object): """Stream parser for DIMACS format""" def __init__(self, file_object): self.file_object = file_object self.var_count = 0 self.clauses = [] self.remove_doubles = re.compile(r'\s\s+') ...
def _parse_line(self, line_number, line): line = line.strip() if len(line) == 0: return # Be flexible with comments (since some benchmarks use either) if line[0] in '#c': return line = self.remove_doubles.sub(r' ', line) elms = line.split(...
for line_number, line in enumerate(self.file_object): line = line.strip() if line[0] == 'p': return line_number, line elif line[0] == 'c' or line == '': continue else: raise Exception('Unexpected header on line {}: "{}"' ...
identifier_body
parser.py
from __future__ import print_function, absolute_import import re class CNFParser(object): """Stream parser for DIMACS format""" def __init__(self, file_object): self.file_object = file_object self.var_count = 0 self.clauses = [] self.remove_doubles = re.compile(r'\s\s+') ...
if literal == 0: break clause.append(literal) if len(clause) > 0: self.clauses.append(clause) class CNFFileParser(CNFParser): """Parse DIMACS files""" def __init__(self, filename): self.filename = filename with open(filename, 'r') a...
self._warn('Error in line #{} -- could not parse "{}"'.format( line_number, clause_str)) continue
random_line_split
parser.py
from __future__ import print_function, absolute_import import re class CNFParser(object): """Stream parser for DIMACS format""" def __init__(self, file_object): self.file_object = file_object self.var_count = 0 self.clauses = [] self.remove_doubles = re.compile(r'\s\s+') ...
class CNFFileParser(CNFParser): """Parse DIMACS files""" def __init__(self, filename): self.filename = filename with open(filename, 'r') as f: super(CNFFileParser, self).__init__(f)
self.clauses.append(clause)
conditional_block
parser.py
from __future__ import print_function, absolute_import import re class CNFParser(object): """Stream parser for DIMACS format""" def
(self, file_object): self.file_object = file_object self.var_count = 0 self.clauses = [] self.remove_doubles = re.compile(r'\s\s+') self._parse() def _parse(self): # find the header line_number, header = self._find_header() elms = header.split() ...
__init__
identifier_name
gen_user_followers.py
from datetime import * from Tweetstream import * from UserAnalyser import * from TimeAnalyser import * import math import sys import pickle #Frequency over the common def load_list(filein): d = dict() for l in filein: l = eval(l) d[l[0]] = l[1] return d if __name__ == "__main__": follow = load_list(open(sys....
ua.load_usersVectors() ua.load_idf() ua.load_usersScore() rank = dict() # normalizar pelo numero de kw no topic vector c = 0 for t in userstream: rank[t['id']] = 0 n = 0 if t['user_id'] in follow: c += 1 for fuser in follow[t['user_id']]: if fuser in ua.usersScore: rank[t['id']] += ua.users...
random_line_split
gen_user_followers.py
from datetime import * from Tweetstream import * from UserAnalyser import * from TimeAnalyser import * import math import sys import pickle #Frequency over the common def load_list(filein): d = dict() for l in filein: l = eval(l) d[l[0]] = l[1] return d if __name__ == "__main__": follow = load_list(open(sys....
if n > 0: rank[t['id']] /= n print c #prinit score, nwindow pickle.dump(rank, open(sys.argv[4]+"_rank_USER_followers.pick", 'w'), pickle.HIGHEST_PROTOCOL)
rank[t['id']] += ua.usersScore[fuser] n += 1
conditional_block
gen_user_followers.py
from datetime import * from Tweetstream import * from UserAnalyser import * from TimeAnalyser import * import math import sys import pickle #Frequency over the common def load_list(filein):
if __name__ == "__main__": follow = load_list(open(sys.argv[5], 'r')) keywords = open(sys.argv[2], 'r').readline().strip("\n").split(",") userstream = Tweetstream(jsonfilee=sys.argv[3], jsonformat=False, keywords=keywords) topicstream = Tweetstream(jsonfilee=sys.argv[1], jsonformat=False, keywords=keywords) ua ...
d = dict() for l in filein: l = eval(l) d[l[0]] = l[1] return d
identifier_body
gen_user_followers.py
from datetime import * from Tweetstream import * from UserAnalyser import * from TimeAnalyser import * import math import sys import pickle #Frequency over the common def
(filein): d = dict() for l in filein: l = eval(l) d[l[0]] = l[1] return d if __name__ == "__main__": follow = load_list(open(sys.argv[5], 'r')) keywords = open(sys.argv[2], 'r').readline().strip("\n").split(",") userstream = Tweetstream(jsonfilee=sys.argv[3], jsonformat=False, keywords=keywords) topicstrea...
load_list
identifier_name
x-tag-no-polyfills.js
event) { var match, target = event.target, root = event.currentTarget; while (!match && target && target != root) { if (target.tagName && matchSelector.call(target, pseudo.value)) match = target; target = target.parentNode; } if (!match && root.tagName && matchSelect...
modAttr(this, attr, name, value, method); accessor[z].call(this, value, old); syncAttr(this, attr, name, value, method); } : accessor[z] ? function(value){ accessor[z].call(this, value); } : null, tag.pseudos, accessor[z]); if (attr) attr.setter = accessor[z]; ...
}
random_line_split
x-tag-no-polyfills.js
event) { var match, target = event.target, root = event.currentTarget; while (!match && target && target != root)
if (!match && root.tagName && matchSelector.call(root, pseudo.value)) match = root; return match ? pseudo.listener = pseudo.listener.bind(match) : null; } function touchFilter(event){ return event.button === 0; } function writeProperty(key, event, base, desc){ if (desc) event[key] =...
{ if (target.tagName && matchSelector.call(target, pseudo.value)) match = target; target = target.parentNode; }
conditional_block
x-tag-no-polyfills.js
function resolveMixins(mixins, output){ var index = mixins.length; while (index--){ output.unshift(mixins[index]); if (xtag.mixins[mixins[index]].mixins) resolveMixins(xtag.mixins[mixins[index]].mixins, output); } return output; } function applyMixins(tag) { resolveM...
{ for (var z in mixin){ original[z + ':__mixin__(' + (uniqueMixinCount++) + ')'] = xtag.applyPseudos(z, mixin[z], tag.pseudos); } }
identifier_body
x-tag-no-polyfills.js
(element, selector){ return (selector || str).length ? toArray(element.querySelectorAll(selector)) : []; } // Pseudos function parsePseudo(fn){fn();} // Mixins function mergeOne(source, key, current){ var type = typeOf(current); if (type == 'object' && typeOf(source[key]) == 'object') ...
query
identifier_name
transform.rs
// Copyright 2019 Yin Guanhao <sopium@mysterious.site> // This file is part of TiTun. // TiTun 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 option) any la...
} // No `"` or `[`, not toml. true } fn transform_value(value: &str) -> String { let value = value.trim(); if value.contains(',') { // Array of strings. let a: toml::value::Array = value .split(',') .map(|v| toml::Value::String(v.trim().into())) ....
random_line_split
transform.rs
// Copyright 2019 Yin Guanhao <sopium@mysterious.site> // This file is part of TiTun. // TiTun 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 option) any la...
), r##" [General] log = "info" # Some comment [Interface] ListenPort = 7777 PrivateKey = "INZz5evbJBekyvtjRLHdnigrKeJ7HxOXR7lLm6yqMW4=" # Some more comment. [[Peer]] PublicKey = "NGnPOc0pxlnOjQz5DDSBJsSM6rf2T1MjBduxmvKBLiU=" # Some more comment. AllowedIPs = ["192.168.77.2/32", "192.168.77.4...
{ assert_eq!( super::maybe_transform( r##" [General] log = info # Some comment [Interface] ListenPort = 7777 PrivateKey = INZz5evbJBekyvtjRLHdnigrKeJ7HxOXR7lLm6yqMW4= # Some more comment. [Peer] PublicKey = NGnPOc0pxlnOjQz5DDSBJsSM6rf2T1MjBduxmvKBLiU= # Some more comment. Allowed...
identifier_body
transform.rs
// Copyright 2019 Yin Guanhao <sopium@mysterious.site> // This file is part of TiTun. // TiTun 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 option) any la...
(input: &str) -> bool { for l in input.lines() { let l = l.trim(); if l == "[Peer]" { // Not toml. return true; } if l.starts_with('#') || l.starts_with('[') { continue; } if l.contains('"') || l.contains('[') { // Is to...
need_transform
identifier_name
transform.rs
// Copyright 2019 Yin Guanhao <sopium@mysterious.site> // This file is part of TiTun. // TiTun 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 option) any la...
} } output } #[cfg(test)] mod tests { #[test] fn test_transform() { assert_eq!( super::maybe_transform( r##" [General] log = info # Some comment [Interface] ListenPort = 7777 PrivateKey = INZz5evbJBekyvtjRLHdnigrKeJ7HxOXR7lLm6yqMW4= # Some more comment. ...
{ output.push_str(l); output.push('\n'); }
conditional_block
prophy.py
from collections import namedtuple from prophyc.generators import base, word_wrap INDENT_STR = u" " MAX_LINE_WIDTH = 100 DocStr = namedtuple("DocStr", "block, inline") def _form_doc(model_node, max_inl_docstring_len, indent_level): block_doc, inline_doc = "", "" if model_node.docstring: if len(m...
elif model_node.docstring: block_doc = u"\n" + "".join( _gen_multi_line_doc(model_node.docstring, indent_level=indent_level, block_header=model_node.name)) return DocStr(block_doc, inline_doc) schema_line_breaker = word_wrap.BreakLinesByWidth(MAX_LINE_WIDTH, " ", "/* ", "...
inline_doc = u" // {}".format(model_node.docstring)
conditional_block
prophy.py
from collections import namedtuple from prophyc.generators import base, word_wrap INDENT_STR = u" " MAX_LINE_WIDTH = 100 DocStr = namedtuple("DocStr", "block, inline") def _form_doc(model_node, max_inl_docstring_len, indent_level): block_doc, inline_doc = "", "" if model_node.docstring: if len(m...
(member): value = u" = {};".format(member.value) return member.name, value return generate_schema_container(enumerator, "enum", column_selector) @staticmethod def translate_struct(struct): def column_selector(member): type_ = member.value if memb...
column_selector
identifier_name
prophy.py
from collections import namedtuple from prophyc.generators import base, word_wrap INDENT_STR = u" "
def _form_doc(model_node, max_inl_docstring_len, indent_level): block_doc, inline_doc = "", "" if model_node.docstring: if len(model_node.docstring) <= max_inl_docstring_len and "\n" not in model_node.docstring: inline_doc = u" // {}".format(model_node.docstring) elif model_node....
MAX_LINE_WIDTH = 100 DocStr = namedtuple("DocStr", "block, inline")
random_line_split
prophy.py
from collections import namedtuple from prophyc.generators import base, word_wrap INDENT_STR = u" " MAX_LINE_WIDTH = 100 DocStr = namedtuple("DocStr", "block, inline") def _form_doc(model_node, max_inl_docstring_len, indent_level): block_doc, inline_doc = "", "" if model_node.docstring: if len(m...
def _columnizer(model_node, column_splitter, max_line_width=100): members_table = [column_splitter(m) for m in model_node.members] widths = [max(len(str(r)) for r in g) for g in zip(*members_table)] max_inline_comment_width = max_line_width - sum(widths) for member, columns in zip(model_node.members...
assert "\n" not in block_header, "Will not work with line breaks in header bar." if block_header: if len(block_comment_text) >= 250: schema_line_breaker.make_a_bar("-" if indent_level else "=", block_header) yield block_header for paragraph in block_comment_text.split("\n"): ...
identifier_body
WaterfallSeries.js
.type !== 'waterfall' || HighchartsAdapter.inArray(series.stackKey) !== -1) { return; } // reset previously found dataMin and dataMax, do it only once if (resetMinMax) { axis.dataMin = axis.dataMax = null; resetMinMax = false; } var yData = series.processedYData, yDataLength = yData.length, ...
// 1 - set default options defaultPlotOptions.waterfall = merge(defaultPlotOptions.column, { lineWidth: 1, lineColor: '#333', dashStyle: 'dot', borderColor: '#333' }); // 2 - Create the series object seriesTypes.waterfall = extendClass(seriesTypes.column, { type: 'waterfall', upColorProp: 'fill', pointArra...
} } }); });
random_line_split
WaterfallSeries.js
!== 'waterfall' || HighchartsAdapter.inArray(series.stackKey) !== -1) { return; } // reset previously found dataMin and dataMax, do it only once if (resetMinMax) { axis.dataMin = axis.dataMax = null; resetMinMax = false; } var yData = series.processedYData, yDataLength = yData.length, serie...
prev = yData[i]; } } }, /** * Return [y, low] array, if low is not defined, it's replaced with null for further calculations */ toYData: function (pt) { if (pt.isSum) { return "sum"; } else if (pt.isIntermediateSum) { return "intermediateSum"; } return [pt.y]; }, /** * Postprocess...
{ yData[i] = curr[0];// + prev; }
conditional_block
example_grid_time.py
#!/usr/bin/env python """ Grid time ============= """ from datetime import timedelta import numpy as np from opendrift.readers import reader_global_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.oceandrift import OceanDrift # Seeding at a grid at regular interval o = OceanDrift(...
#%% # Running model for 60 hours o.run(steps=60*4, time_step=900, time_step_output=3600) #%% # Print and plot results print(o) o.animation(fast=True) #%% # .. image:: /gallery/animations/example_grid_time_0.gif
o.seed_elements(lons, lats, radius=0, number=100, time=start_time + i*time_step)
conditional_block
example_grid_time.py
#!/usr/bin/env python """ Grid time ============= """ from datetime import timedelta import numpy as np from opendrift.readers import reader_global_landmask from opendrift.readers import reader_netCDF_CF_generic from opendrift.models.oceandrift import OceanDrift # Seeding at a grid at regular interval o = OceanDrift(...
#%% # Print and plot results print(o) o.animation(fast=True) #%% # .. image:: /gallery/animations/example_grid_time_0.gif
o.run(steps=60*4, time_step=900, time_step_output=3600)
random_line_split
test_passthrough.py
# #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2018> Gabriel Falcão <gabriel@nacaolivre.org> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to ...
): url = 'http://httpbin.org/status/200' response1 = requests.get(url) response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.e...
est_http_passthrough(
identifier_name
test_passthrough.py
# #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2018> Gabriel Falcão <gabriel@nacaolivre.org> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation
# Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITE...
# files (the "Software"), to deal 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
random_line_split
test_passthrough.py
# #!/usr/bin/env python # -*- coding: utf-8 -*- # <HTTPretty - HTTP client mock for Python> # Copyright (C) <2011-2018> Gabriel Falcão <gabriel@nacaolivre.org> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to ...
@skip def test_https_passthrough(): url = 'https://raw.githubusercontent.com/gabrielfalcao/HTTPretty/master/COPYING' response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'https://google.com/', body="Not Google") response2 = requests.get('https://go...
rl = 'http://httpbin.org/status/200' response1 = requests.get(url) response1 = requests.get(url, stream=True) HTTPretty.enable() HTTPretty.register_uri(HTTPretty.GET, 'http://google.com/', body="Not Google") response2 = requests.get('http://google.com/') expect(response2.content).to.equal(b'N...
identifier_body
simple_treeview.rs
//! # TreeView Sample //! //! This sample demonstrates how to create a TreeView with a ListStore. extern crate gio; extern crate gtk; use gio::prelude::*; use gtk::prelude::*; use gtk::{ ApplicationWindow, CellRendererText, Label, ListStore, Orientation, TreeView, TreeViewColumn, WindowPosition, }; use std::...
(application: &gtk::Application) { let window = ApplicationWindow::new(application); window.set_title("Simple TreeView example"); window.set_position(WindowPosition::Center); // Creating a vertical layout to place both tree view and label in the window. let vertical_layout = gtk::Box::new(Orientat...
build_ui
identifier_name
simple_treeview.rs
//! # TreeView Sample //! //! This sample demonstrates how to create a TreeView with a ListStore. extern crate gio; extern crate gtk; use gio::prelude::*; use gtk::prelude::*; use gtk::{ ApplicationWindow, CellRendererText, Label, ListStore, Orientation, TreeView, TreeViewColumn, WindowPosition, }; use std::...
application.connect_activate(|app| { build_ui(app); }); application.run(&args().collect::<Vec<_>>()); }
) .expect("Initialization failed...");
random_line_split
simple_treeview.rs
//! # TreeView Sample //! //! This sample demonstrates how to create a TreeView with a ListStore. extern crate gio; extern crate gtk; use gio::prelude::*; use gtk::prelude::*; use gtk::{ ApplicationWindow, CellRendererText, Label, ListStore, Orientation, TreeView, TreeViewColumn, WindowPosition, }; use std::...
}); // Adding the layout to the window. window.add(&vertical_layout); window.show_all(); } fn main() { let application = gtk::Application::new( Some("com.github.gtk-rs.examples.simple_treeview"), Default::default(), ) .expect("Initialization failed..."); application....
{ // Now getting back the values from the row corresponding to the // iterator `iter`. // // The `get_value` method do the conversion between the gtk type and Rust. label.set_text(&format!( "Hello '{}' from row {}", model ...
conditional_block
simple_treeview.rs
//! # TreeView Sample //! //! This sample demonstrates how to create a TreeView with a ListStore. extern crate gio; extern crate gtk; use gio::prelude::*; use gtk::prelude::*; use gtk::{ ApplicationWindow, CellRendererText, Label, ListStore, Orientation, TreeView, TreeViewColumn, WindowPosition, }; use std::...
fn append_column(tree: &TreeView, id: i32) { let column = TreeViewColumn::new(); let cell = CellRendererText::new(); column.pack_start(&cell, true); // Association of the view's column with the model's `id` column. column.add_attribute(&cell, "text", id); tree.append_column(&column); } fn cr...
{ // Creation of a model with two rows. let model = ListStore::new(&[u32::static_type(), String::static_type()]); // Filling up the tree view. let entries = &["Michel", "Sara", "Liam", "Zelda", "Neo", "Octopus master"]; for (i, entry) in entries.iter().enumerate() { model.insert_with_values...
identifier_body
generatedLocale.d.ts
import Uppy = require('@uppy/core'); type DashboardLocale = Uppy.Locale< | 'closeModal' | 'importFrom' | 'addingMoreFiles' | 'addMoreFiles' | 'dashboardWindowTitle' | 'dashboardTitle' | 'copyLinkToClipboardSuccess' | 'copyLinkToClipboardFallback' | 'copyLink' | 'fileSource' | 'done' | 'back' ...
| 'uploadingXFiles' | 'processingXFiles' | 'poweredBy2' | 'poweredBy' | 'validating' | 'validateAndRetry' | 'rejectAll' | 'acceptAll' | 'clear' | 'cancelPending' | 'clearCompleted' | 'renamingFromTo' | 'minimize' | 'close' >; export = DashboardLocale;
| 'retryUpload' | 'cancelUpload' | 'xFilesSelected'
random_line_split
main.rs
#[allow(dead_code)] struct Nil; #[allow(dead_code)] struct Pair(i32, f32); #[allow(dead_code)] struct Point { x: i32, y: i32, } #[allow(dead_code)] struct Rectangle { p1: Point, p2: Point, } #[allow(unused_variables)] fn main() { let point1: Point = Point { x: 4, y: 5 }; println!("point coo...
}
random_line_split
main.rs
#[allow(dead_code)] struct
; #[allow(dead_code)] struct Pair(i32, f32); #[allow(dead_code)] struct Point { x: i32, y: i32, } #[allow(dead_code)] struct Rectangle { p1: Point, p2: Point, } #[allow(unused_variables)] fn main() { let point1: Point = Point { x: 4, y: 5 }; println!("point coordinates: ({}, {})", point1.x,...
Nil
identifier_name
GuardingTheRealm.js
const DrawCard = require('../../drawcard.js'); class GuardingTheRealm extends DrawCard {
(ability) { this.action({ title: 'Take control of character in discard pile', phase: 'marshal', target: { cardCondition: card => card.controller !== this.controller && card.location === 'discard pile' && card.getType() ==...
setupCardAbilities
identifier_name
GuardingTheRealm.js
const DrawCard = require('../../drawcard.js'); class GuardingTheRealm extends DrawCard { setupCardAbilities(ability)
ignoreEventCosts: true, cost: ability.costs.payGold(1), handler: () => { this.game.addMessage('{0} pays 1 gold to move {1} back to their hand', this.controller, this); this.controller.moveCard(this, 'hand'); } }); } } Guarding...
{ this.action({ title: 'Take control of character in discard pile', phase: 'marshal', target: { cardCondition: card => card.controller !== this.controller && card.location === 'discard pile' && card.getType() === 'charact...
identifier_body
GuardingTheRealm.js
class GuardingTheRealm extends DrawCard { setupCardAbilities(ability) { this.action({ title: 'Take control of character in discard pile', phase: 'marshal', target: { cardCondition: card => card.controller !== this.controller && card.location === 'discard ...
const DrawCard = require('../../drawcard.js');
random_line_split
_tarantula.py
# Copyright 2018-2020 by Christopher C. Little. # This file is part of Abydos. # # Abydos 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 option) any later versio...
self._tokenize(src, tar) a = self._intersection_card() b = self._src_only_card() c = self._tar_only_card() d = self._total_complement_card() num = a * (c + d) if num: return num / (a * (2 * c + d) + b * c) return 0.0 if __name__ == '__mai...
return 1.0
conditional_block
_tarantula.py
# Copyright 2018-2020 by Christopher C. Little. # This file is part of Abydos. # # Abydos 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 option) any later versio...
# You should have received a copy of the GNU General Public License # along with Abydos. If not, see <http://www.gnu.org/licenses/>. """abydos.distance._tarantula. Tarantula similarity """ from typing import Any, Counter as TCounter, Optional, Sequence, Set, Union from ._token_distance import _TokenDistance from .....
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. #
random_line_split
_tarantula.py
# Copyright 2018-2020 by Christopher C. Little. # This file is part of Abydos. # # Abydos 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 option) any later versio...
The length of each q-gram. Using this parameter and tokenizer=None will cause the instance to use the QGram tokenizer with this q value. metric : _Distance A string distance measure class for use in the ``soft`` and ``fuzzy`` variants. threshol...
"""Initialize Tarantula instance. Parameters ---------- alphabet : Counter, collection, int, or None This represents the alphabet of possible tokens. See :ref:`alphabet <alphabet>` description in :py:class:`_TokenDistance` for details. tokenizer : _To...
identifier_body
_tarantula.py
# Copyright 2018-2020 by Christopher C. Little. # This file is part of Abydos. # # Abydos 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 option) any later versio...
(_TokenDistance): r"""Tarantula similarity. For two sets X and Y and a population N, Tarantula similarity :cite:`Jones:2005` is .. math:: sim_{Tarantula}(X, Y) = \frac{\frac{|X \cap Y|}{|X \cap Y| + |X \setminus Y|}} {\frac{|X \cap Y|}{|X \cap Y| + |X \setminus...
Tarantula
identifier_name
hy-AM.js
(function (global, factory) { if (typeof define === "function" && define.amd) { define('element/locale/hy-AM', ['module', 'exports'], factory); } else if (typeof exports !== "undefined") { factory(module, exports); } else { var mod = { exports: {} }; factory(mod, mod.exports); global...
}, months: { jan: 'Յունվ', feb: 'Փետ', mar: 'Մար', apr: 'Ապր', may: 'Մայ', jun: 'Յուն', jul: 'Յուլ', aug: 'Օգ', sep: 'Սեպտ', oct: 'Յոկ', nov: 'Նոյ', dec: 'Դեկ' } }, ...
sat: 'Շաբ'
random_line_split
hy-AM.js
(function (global, factory) { if (typeof define === "function" && define.amd) { define('element/locale/hy-AM', ['module', 'exports'], factory); } else if (typeof exports !== "undefined") { factory(module, exports); } else
})(this, function (module, exports) { 'use strict'; exports.__esModule = true; exports.default = { el: { colorpicker: { confirm: 'Լաւ', clear: 'Մաքրել' }, datepicker: { now: 'Հիմա', today: 'Այսօր', cancel: 'Չեղարկել', clear: 'Մաքրել', ...
{ var mod = { exports: {} }; factory(mod, mod.exports); global.ELEMENT.lang = global.ELEMENT.lang || {}; global.ELEMENT.lang.hyAM = mod.exports; }
conditional_block
TimerPage.js
var React = require('react'); var Animation = require('react-addons-css-transition-group'); var NBButton = require('./NBItems').NBButton; var NBTitle = require('./NBItems').NBTitle; var NBEmpty = require('./NBItems').NBEmpty; var Navbar = React.createClass({ render: function() { return ( <div c...
render: function() { return ( <div className="page"> <div className="page-content"> <Navbar/> <Animation transitionName={{ appear: "slideLeft-enter", leave: "slideLeft-leave" ...
},
random_line_split
main.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2010-2011, Volkan Esgel # # This program 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 option) # any l...
def __createMainLayout(self): self.mainLayout = QGraphicsLinearLayout(Qt.Vertical, self.applet) noteview = Plasma.TreeView(self.applet) noteview.setStyleSheet("QTreeView { background: Transparent }") nmodel = NoteModel(self.package().path(), noteview) noteview.setModel(nmod...
def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) def init(self): self.setHasConfigurationInterface(True) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) """ self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background"...
identifier_body
main.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2010-2011, Volkan Esgel # # This program 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 option) # any l...
self.setBackgroundHints(Plasma.Applet.NoBackground) self.__createMainLayout() width = self.viewerSize.width() + 20 height = self.viewerSize.height() - 20 self.resize(width, height) def __createMainLayout(self): self.mainLayout = QGraphicsLinearLayout(Qt.Vertical, s...
self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) """
random_line_split
main.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2010-2011, Volkan Esgel # # This program 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 option) # any l...
(self): self.mainLayout = QGraphicsLinearLayout(Qt.Vertical, self.applet) noteview = Plasma.TreeView(self.applet) noteview.setStyleSheet("QTreeView { background: Transparent }") nmodel = NoteModel(self.package().path(), noteview) noteview.setModel(nmodel) noteview.native...
__createMainLayout
identifier_name
generator.py
import datetime import sys from decimal import Decimal if sys.version_info[0] == 2: integer_types = int, long text_type = unicode binary_type = str else: integer_types = int, text_type = str binary_type = bytes class Generator(object): def __init__(self, dict): self.dict = dict ...
elif isinstance(value, type(None)): return open_tag + close_tag elif isinstance(value, datetime.datetime) or isinstance(value, datetime.date): open_tag = "<" + key + " type=\"datetime\">" return open_tag + self.__generate_datetime(value) + close_tag else: ...
open_tag = "<" + self.__escape(key) + ">" close_tag = "</" + self.__escape(key) + ">" if isinstance(value, text_type): return open_tag + self.__escape(value).encode('ascii', 'xmlcharrefreplace').decode('utf-8') + close_tag elif isinstance(value, binary_type): return open...
identifier_body
generator.py
import datetime import sys from decimal import Decimal if sys.version_info[0] == 2: integer_types = int, long text_type = unicode binary_type = str else: integer_types = int, text_type = str binary_type = bytes class Generator(object): def __init__(self, dict): self.dict = dict ...
xml = "" for item in list: xml += self.__generate_node("item", item) return xml def __generate_node(self, key, value): open_tag = "<" + self.__escape(key) + ">" close_tag = "</" + self.__escape(key) + ">" if isinstance(value, text_type): retu...
for key, val in dictionary.items(): xml += self.__generate_node(key, val) return xml def __generate_list(self, list):
random_line_split
generator.py
import datetime import sys from decimal import Decimal if sys.version_info[0] == 2: integer_types = int, long text_type = unicode binary_type = str else: integer_types = int, text_type = str binary_type = bytes class Generator(object): def __init__(self, dict): self.dict = dict ...
else: raise RuntimeError("Unexpected XML node type: " + str(type(value)))
open_tag = "<" + key + " type=\"datetime\">" return open_tag + self.__generate_datetime(value) + close_tag
conditional_block
generator.py
import datetime import sys from decimal import Decimal if sys.version_info[0] == 2: integer_types = int, long text_type = unicode binary_type = str else: integer_types = int, text_type = str binary_type = bytes class Generator(object): def __init__(self, dict): self.dict = dict ...
(self, list): xml = "" for item in list: xml += self.__generate_node("item", item) return xml def __generate_node(self, key, value): open_tag = "<" + self.__escape(key) + ">" close_tag = "</" + self.__escape(key) + ">" if isinstance(value, text_type): ...
__generate_list
identifier_name
ru.js
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'toolbar', 'ru', { toolbarCollapse: 'Свернуть панель инструментов', toolbarExpand: 'Развернуть панель инструментов',
forms: 'Формы', basicstyles: 'Простые стили', paragraph: 'Абзац', links: 'Ссылки', insert: 'Вставка', styles: 'Стили', colors: 'Цвета', tools: 'Инструменты' }, toolbars: 'Панели инструментов редактора' } );
toolbarGroups: { document: 'Документ', clipboard: 'Буфер обмена / Отмена действий', editing: 'Корректировка',
random_line_split
scssScanner.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
// operators <, <= if (this.stream.advanceIfChar(_LAN)) { if (this.stream.advanceIfChar(_EQS)) { return this.finishToken(offset, SmallerEqualsOperator); } return this.finishToken(offset, TokenType.Delim); } // ooperators >, >= if (this.stream.advanceIfChar(_RAN)) { if (this.stream.advanceIf...
{ return this.finishToken(offset, NotEqualsOperator); }
conditional_block
scssScanner.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): IToken { // processes all whitespaces and comments const triviaToken = this.trivia(); if (triviaToken !== null) { return triviaToken; } const offset = this.stream.pos(); // scss variable if (this.stream.advanceIfChar(_DLR)) { const content = ['$']; if (this.ident(content)) { return thi...
scan
identifier_name
scssScanner.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}
{ if (super.comment()) { return true; } if (this.stream.advanceIfChars([_FSL, _FSL])) { this.stream.advanceWhileChar((ch: number) => { switch (ch) { case _NWL: case _CAR: case _LFD: return false; default: return true; } }); return true; } else { return fals...
identifier_body
scssScanner.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
// operators <, <= if (this.stream.advanceIfChar(_LAN)) { if (this.stream.advanceIfChar(_EQS)) { return this.finishToken(offset, SmallerEqualsOperator); } return this.finishToken(offset, TokenType.Delim); } // ooperators >, >= if (this.stream.advanceIfChar(_RAN)) { if (this.stream.advanceIfC...
// operator != if (this.stream.advanceIfChars([_BNG, _EQS])) { return this.finishToken(offset, NotEqualsOperator); }
random_line_split
gh_post_style_patch.py
#!/usr/bin/env python3 # # Copyright (C) 2018-2019 The ESPResSo project # # This file is part of ESPResSo. # # ESPResSo 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...
assert TOKEN_ESPRESSO_CI in comment gh_post.post_message(comment)
conditional_block
gh_post_style_patch.py
#!/usr/bin/env python3 # # Copyright (C) 2018-2019 The ESPResSo project # # This file is part of ESPResSo. # # ESPResSo 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...
# along with this program. If not, see <http://www.gnu.org/licenses/>. import os if not os.environ.get('CI_COMMIT_REF_NAME', '').startswith('PR-'): print("Not a pull request. Exiting now.") exit(0) import subprocess import gh_post SIZELIMIT = 10000 TOKEN_ESPRESSO_CI = 'style.patch' # Delete obsolete posts...
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License
random_line_split
mod.rs
// Copyright 2017 The Grin Developers // // 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...
mod delegator; pub mod miner;
random_line_split
url.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 https://mozilla.org/MPL/2.0/. */ //! Generic types for url properties. /// An image url or none, used for example in list-style-image /// /// cbi...
/// Returns whether the value is `none`. pub fn is_none(&self) -> bool { match *self { UrlOrNone::None => true, UrlOrNone::Url(..) => false, } } }
{ UrlOrNone::None }
identifier_body
url.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 https://mozilla.org/MPL/2.0/. */
//! Generic types for url properties. /// An image url or none, used for example in list-style-image /// /// cbindgen:derive-tagged-enum-copy-constructor=true #[derive( Animate, Clone, ComputeSquaredDistance, Debug, MallocSizeOf, PartialEq, Parse, SpecifiedValueInfo, ToAnimatedValue...
random_line_split
url.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 https://mozilla.org/MPL/2.0/. */ //! Generic types for url properties. /// An image url or none, used for example in list-style-image /// /// cbi...
() -> Self { UrlOrNone::None } /// Returns whether the value is `none`. pub fn is_none(&self) -> bool { match *self { UrlOrNone::None => true, UrlOrNone::Url(..) => false, } } }
none
identifier_name
features.rs
`Manifest::feature_gate` function, but otherwise you may wish to //! place the feature gate elsewhere in Cargo. //! //! 3. To actually perform the feature gate, you'll want to have code that looks //! like: //! //! ```rust,ignore //! use core::{Feature, Features}; //! //! let feature = Feature::launch_into_space...
//! unintended damage to your codebase, use with caution" //! })?; //! ``` //! //! Notably you'll notice the `require` function called with your `Feature`, and //! then you use `chain_err` to tack on more context for why the feature was //! required when the feature isn't activated. //! //! 4. Update the unstable ...
//! package.manifest().features().require(feature).chain_err(|| { //! "launching Cargo into space right now is unstable and may result in \
random_line_split
features.rs
`Manifest::feature_gate` function, but otherwise you may wish to //! place the feature gate elsewhere in Cargo. //! //! 3. To actually perform the feature gate, you'll want to have code that looks //! like: //! //! ```rust,ignore //! use core::{Feature, Features}; //! //! let feature = Feature::launch_into_space...
(&self, feature: &Feature) -> CargoResult<()> { if feature.is_enabled(self) { Ok(()) } else { let feature = feature.name.replace("_", "-"); let mut msg = format!("feature `{}` is required", feature); if nightly_features_allowed() { let s =...
require
identifier_name
features.rs
`Manifest::feature_gate` function, but otherwise you may wish to //! place the feature gate elsewhere in Cargo. //! //! 3. To actually perform the feature gate, you'll want to have code that looks //! like: //! //! ```rust,ignore //! use core::{Feature, Features}; //! //! let feature = Feature::launch_into_space...
} enum Status { Stable, Unstable, } macro_rules! features { ( pub struct Features { $([$stab:ident] $feature:ident: bool,)* } ) => ( #[derive(Default, Clone, Debug)] pub struct Features { $($feature: bool,)* activated: Vec<String>, ...
{ match s { "2015" => Ok(Edition::Edition2015), "2018" => Ok(Edition::Edition2018), s => { bail!("supported edition values are `2015` or `2018`, but `{}` \ is unknown", s) } } }
identifier_body