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 |
|---|---|---|---|---|
make-draggable.ts | // // import { Subject } from 'rxjs/Subject';
// import * as React from 'react';
// import * as ReactDOM from 'react-dom';
// import { DragAndDrop, IDragActions } from '../logic/dragndrop';
// export function makeDraggable<T>(Component: React.ComponentClass<T>): React.ComponentClass<T & IDraggableProps> {
//... | // private get componentProps(): T {
// return this.props as any;
// }
// private onMouseDown = (evt: React.MouseEvent<any>) => {
// if (this.draggableProps.onDown) { this.draggableProps.onDown(evt); }
// this.mouseDown$.next(evt);
// }
// public componentDidMount() {
/... | // }
| random_line_split |
kmeans.py | import json
import math
import random
import os
class KMeans(object):
# TO-DO: Richard
def __init__(self, dataset=None):
file_path = os.path.dirname(os.path.realpath(__file__))
if dataset is None:
self.mega_dataset = json.loads(open(file_path + '/dataset.json', 'r').read... |
def _kmeans(self, k, iterations=100):
clusters = [set() for _ in xrange(k)]
centroids = random.sample(self.dataset, k)
# init data to clusters
for datum in self.dataset:
i = random.choice(range(k))
clusters[i].add(datum)
for _ in xrange(iter... | try:
datum_len = range(len(next(iter(data))))
result = [0 for x in datum_len]
for datum in data:
for i, value in enumerate(datum):
result[i] += value
for i in datum_len:
result[i] /= float(len(data))
... | identifier_body |
kmeans.py | import json
import math
import random
import os
class KMeans(object):
# TO-DO: Richard
def __init__(self, dataset=None):
file_path = os.path.dirname(os.path.realpath(__file__))
if dataset is None:
self.mega_dataset = json.loads(open(file_path + '/dataset.json', 'r').read... | f.close()
return champ2cluster
# Example: | random_line_split | |
kmeans.py | import json
import math
import random
import os
class KMeans(object):
# TO-DO: Richard
def __init__(self, dataset=None):
file_path = os.path.dirname(os.path.realpath(__file__))
if dataset is None:
|
else:
self.mega_dataset = json.loads(dataset)
def _ED(self, point1, point2):
result = 0
for i in xrange(len(point1)):
result += pow(point2[i] - point1[i], 2)
return math.sqrt(result)
def _closest(self, datum, centroids):
closest_ind... | self.mega_dataset = json.loads(open(file_path + '/dataset.json', 'r').read()) | conditional_block |
kmeans.py | import json
import math
import random
import os
class KMeans(object):
# TO-DO: Richard
def __init__(self, dataset=None):
file_path = os.path.dirname(os.path.realpath(__file__))
if dataset is None:
self.mega_dataset = json.loads(open(file_path + '/dataset.json', 'r').read... | (self, point1, point2):
result = 0
for i in xrange(len(point1)):
result += pow(point2[i] - point1[i], 2)
return math.sqrt(result)
def _closest(self, datum, centroids):
closest_index = None
closest_distance = None
for i, point in enumerate(centr... | _ED | identifier_name |
main.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Julien Chaumont"
__copyright__ = "Copyright 2014, Julien Chaumont"
__licence__ = "MIT"
__version__ = "1.0.2"
__contact__ = "julienc91 [at] outlook.fr"
import flickrapi
import os, sys
import re
from config import *
class ShFlickr:
##
# Connexion to F... |
##
# Get the list of pictures to synchronize within an album.
# @param subfolder Complete path to the subfolder to synchronize
# @param photoset_id Id of the album on Flickr, or None of the album does not exist yet
# @return The list of the pictures to synchronize.
#
def ... | photos_to_sync[subfolder] = self.synclist_subfolder(os.path.join(folder, subfolder), photoset_id)
return photos_to_sync, photoset_ids | random_line_split |
main.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Julien Chaumont"
__copyright__ = "Copyright 2014, Julien Chaumont"
__licence__ = "MIT"
__version__ = "1.0.2"
__contact__ = "julienc91 [at] outlook.fr"
import flickrapi
import os, sys
import re
from config import *
class ShFlickr:
##
# Connexion to F... |
else:
photo_id = response.find('photoid').text
done = True
count += 1
consecutive_errors = 0
if photoset_ids[subfolder] is None:
print "Creating the re... | print "Error, retrying upload (%s/%s)" % (nb_errors, MAX_RETRIES) | conditional_block |
main.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Julien Chaumont"
__copyright__ = "Copyright 2014, Julien Chaumont"
__licence__ = "MIT"
__version__ = "1.0.2"
__contact__ = "julienc91 [at] outlook.fr"
import flickrapi
import os, sys
import re
from config import *
class ShFlickr:
##
# Connexion to F... | is_friend=VISIBLE_FRIEND)
except KeyboardInterrupt:
print "Exit by user request"
return
except:
nb_errors += 1
consecutive_errors ... | for subfolder in sorted(photos_to_sync):
count = 1
total = len(photos_to_sync[subfolder])
len_count = len(str(total))
consecutive_errors = 0
print "Album %s: %s photos to synchronize" % (subfolder, total)
for photo in sorte... | identifier_body |
main.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Julien Chaumont"
__copyright__ = "Copyright 2014, Julien Chaumont"
__licence__ = "MIT"
__version__ = "1.0.2"
__contact__ = "julienc91 [at] outlook.fr"
import flickrapi
import os, sys
import re
from config import *
class ShFlickr:
##
# Connexion to F... | (self):
self.flickr = flickrapi.FlickrAPI(API_KEY, API_SECRET)
(token, frob) = self.flickr.get_token_part_one(perms='delete')
if not token:
raw_input("Press ENTER after you authorized this program")
self.flickr.get_token_part_two((token, frob))
##
# Get the list of ... | __init__ | identifier_name |
DOMTestCase.js | case "text/html":
return ".html";
case "text/xml":
return ".xml";
case "application/xhtml+xml":
return ".xhtml";
case "image/svg+xml":
return ".svg";
case "text/mathml":
return ".mml";
}
return ".html";
}
function equalsAutoCase(conte... | setAsynchronous | identifier_name | |
DOMTestCase.js | must appear once and only once in the actual list
var expectedLen = expected.length;
var expectedValue;
var actualLen = actual.length;
var i;
var j;
var matches;
for(i = 0; i < expectedLen; i++) {
matches = 0;
expectedValue = expected[i];
for(j = 0; j < actualLen; j+... |
function getSuffix(contentType) {
switch(contentType) {
case "text/html":
return ".html";
case "text/xml":
return ".xml";
case "application/xhtml+xml":
return ".xhtml";
case "image/svg+xml":
return ".svg";
case "text/mathml":
retu... | {
return expected === actual;
} | identifier_body |
DOMTestCase.js | must appear once and only once in the actual list
var expectedLen = expected.length;
var expectedValue;
var actualLen = actual.length;
var i;
var j;
var matches;
for(i = 0; i < expectedLen; i++) {
matches = 0;
expectedValue = expected[i];
for(j = 0; j < actualLen; j+... | if(lastPound != -1) {
//
// substring before pound
//
uri = actual.substring(0,lastPound);
actualFragment = actual.substring(lastPound+1);
}
if(fragment != null) is(actualFragment, fragment, assertID);
var lastQuestion = uri.lastIndexOf("?");
var actualQuer... |
var uri = actual;
var lastPound = actual.lastIndexOf("#");
var actualFragment = ""; | random_line_split |
DOMTestCase.js | must appear once and only once in the actual list
var expectedLen = expected.length;
var expectedValue;
var actualLen = actual.length;
var i;
var j;
var matches;
for(i = 0; i < expectedLen; i++) {
matches = 0;
expectedValue = expected[i];
for(j = 0; j < actualLen; j+... |
}
}
return null;
}
function createTempURI(scheme) {
if (scheme == "http") {
return "http://localhost:8080/webdav/tmp" + Math.floor(Math.random() * 100000) + ".xml";
}
return "file:///tmp/domts" + Math.floor(Math.random() * 100000) + ".xml";
}
function EventMonitor() {
this.atEvents =... | {
//
// might be recoverable, warn but continue the test
// XXX warn
warn(testname + ": " + blder.initializationError);
} | conditional_block |
index.js | 'use strict';
var getSubplotCalcData = require('../get_data').getSubplotCalcData;
var counterRegex = require('../../lib').counterRegex;
var createPolar = require('../polar/polar');
var constants = require('./constants');
var attr = constants.attr;
var name = constants.name;
var counter = counterRegex(name);
var att... |
function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldIds = oldFullLayout._subplots[name] || [];
for(var i = 0; i < oldIds.length; i++) {
var id = oldIds[i];
var oldSubplot = oldFullLayout[id]._subplot;
if(!newFullLayout[id] && !!oldSubplot) {
old... | {
var fullLayout = gd._fullLayout;
var calcData = gd.calcdata;
var subplotIds = fullLayout._subplots[name];
for(var i = 0; i < subplotIds.length; i++) {
var id = subplotIds[i];
var subplotCalcData = getSubplotCalcData(calcData, name, id);
var subplot = fullLayout[id]._subplot;
... | identifier_body |
index.js | 'use strict';
var getSubplotCalcData = require('../get_data').getSubplotCalcData;
var counterRegex = require('../../lib').counterRegex;
var createPolar = require('../polar/polar');
var constants = require('./constants');
var attr = constants.attr;
var name = constants.name;
var counter = counterRegex(name);
var att... | layoutAttributes: require('./layout_attributes'),
supplyLayoutDefaults: require('./layout_defaults'),
plot: plot,
clean: clean,
toSVG: require('../cartesian').toSVG
}; | name: name,
idRoot: name,
idRegex: counter,
attrRegex: counter,
attributes: attributes, | random_line_split |
index.js | 'use strict';
var getSubplotCalcData = require('../get_data').getSubplotCalcData;
var counterRegex = require('../../lib').counterRegex;
var createPolar = require('../polar/polar');
var constants = require('./constants');
var attr = constants.attr;
var name = constants.name;
var counter = counterRegex(name);
var att... |
}
function clean(newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldIds = oldFullLayout._subplots[name] || [];
for(var i = 0; i < oldIds.length; i++) {
var id = oldIds[i];
var oldSubplot = oldFullLayout[id]._subplot;
if(!newFullLayout[id] && !!oldSubplot) {
o... | {
var id = subplotIds[i];
var subplotCalcData = getSubplotCalcData(calcData, name, id);
var subplot = fullLayout[id]._subplot;
if(!subplot) {
subplot = createPolar(gd, id, true);
fullLayout[id]._subplot = subplot;
}
subplot.plot(subplotCalcData, ... | conditional_block |
index.js | 'use strict';
var getSubplotCalcData = require('../get_data').getSubplotCalcData;
var counterRegex = require('../../lib').counterRegex;
var createPolar = require('../polar/polar');
var constants = require('./constants');
var attr = constants.attr;
var name = constants.name;
var counter = counterRegex(name);
var att... | (newFullData, newFullLayout, oldFullData, oldFullLayout) {
var oldIds = oldFullLayout._subplots[name] || [];
for(var i = 0; i < oldIds.length; i++) {
var id = oldIds[i];
var oldSubplot = oldFullLayout[id]._subplot;
if(!newFullLayout[id] && !!oldSubplot) {
oldSubplot.framewor... | clean | identifier_name |
TreeMap.ts | import Interfaces = require("../../Interfaces");
import Error = require("../../Error");
import MapHelpers = require("./MapHelpers");
import RedBlackTree = require("../trees/RedBlackTree");
import IterableHelpers = require("../IterableHelpers");
class TreeMap<K extends Interfaces.IComparableBaseObject, V extends Interf... | (key: K): V {
return this.tree.remove(key);
}
set(key: K, value: V): V {
this.tree.insert(key, value);
return null; //TODO!
}
size(): number {
return this.tree.size();
}
values(): Interfaces.IIterator<V> {
return this.tree.values();
}
// not to be used directly
__iterator__(): ... | remove | identifier_name |
TreeMap.ts | import Interfaces = require("../../Interfaces");
import Error = require("../../Error");
import MapHelpers = require("./MapHelpers");
import RedBlackTree = require("../trees/RedBlackTree"); |
class TreeMap<K extends Interfaces.IComparableBaseObject, V extends Interfaces.IBaseObject> implements Interfaces.ISortedMap<K, V> {
private tree: Interfaces.ITree<K, V>;
constructor() {
this.tree = new RedBlackTree<K, V>();
}
clear(): void {
this.tree.clear();
}
containsKey(key: K): boolean {
... | import IterableHelpers = require("../IterableHelpers"); | random_line_split |
TreeMap.ts | import Interfaces = require("../../Interfaces");
import Error = require("../../Error");
import MapHelpers = require("./MapHelpers");
import RedBlackTree = require("../trees/RedBlackTree");
import IterableHelpers = require("../IterableHelpers");
class TreeMap<K extends Interfaces.IComparableBaseObject, V extends Interf... |
}
export = TreeMap; | {
return this.keys();
} | identifier_body |
inject_repos.py | #!/usr/bin/env python3
"""inject_repos.py - CI secret repos injection.
"""
import yaml
from lxml import etree
from lxml.etree import ElementTree as ET
import argparse
from six import iteritems
def main():
repos_file, beaker_file = parse_args()
repos = load_secret_data(repos_file)
inject_repos(repos, beaker... | (repos, beaker_file):
parser = etree.XMLParser(strip_cdata=False)
tree = etree.parse(beaker_file, parser)
root = tree.getroot()
for repo_name, url in iteritems(repos):
etree.SubElement(root[1][0][4], "repo",
attrib={"name": repo_name, "url": url})
tree.write(
beaker_file,... | inject_repos | identifier_name |
inject_repos.py | #!/usr/bin/env python3
"""inject_repos.py - CI secret repos injection.
"""
import yaml
from lxml import etree
from lxml.etree import ElementTree as ET
import argparse
from six import iteritems
def main(): | def parse_args():
description_msg = 'Resolve and filter secret data'
parser = argparse.ArgumentParser(description=description_msg)
parser.add_argument(
"-f", "--secret-file", type=str,
help=("Path to secret file.")
)
parser.add_argument(
"-b", "--beaker-file", type=str,
... | repos_file, beaker_file = parse_args()
repos = load_secret_data(repos_file)
inject_repos(repos, beaker_file)
| random_line_split |
inject_repos.py | #!/usr/bin/env python3
"""inject_repos.py - CI secret repos injection.
"""
import yaml
from lxml import etree
from lxml.etree import ElementTree as ET
import argparse
from six import iteritems
def main():
repos_file, beaker_file = parse_args()
repos = load_secret_data(repos_file)
inject_repos(repos, beaker... | main() | conditional_block | |
inject_repos.py | #!/usr/bin/env python3
"""inject_repos.py - CI secret repos injection.
"""
import yaml
from lxml import etree
from lxml.etree import ElementTree as ET
import argparse
from six import iteritems
def main():
|
def parse_args():
description_msg = 'Resolve and filter secret data'
parser = argparse.ArgumentParser(description=description_msg)
parser.add_argument(
"-f", "--secret-file", type=str,
help=("Path to secret file.")
)
parser.add_argument(
"-b", "--beaker-file", type=str,
... | repos_file, beaker_file = parse_args()
repos = load_secret_data(repos_file)
inject_repos(repos, beaker_file) | identifier_body |
selectors.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/. */
use cssparser::Parser;
use selectors::parser::{Selector, ParserContext, parse_selector_list};
use style::selector_... | } | random_line_split | |
selectors.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/. */
use cssparser::Parser;
use selectors::parser::{Selector, ParserContext, parse_selector_list};
use style::selector_... |
#[test]
fn test_selectors() {
assert_roundtrip!(parse, "div");
assert_roundtrip!(parse, "svg|circle");
assert_roundtrip!(parse, "p:before", "p::before");
assert_roundtrip!(parse, "[border = \"0\"]:-servo-nonzero-border ~ ::-servo-details-summary");
}
| {
let mut context = ParserContext::new();
context.in_user_agent_stylesheet = true;
context.namespace_prefixes.insert("svg".into(), ns!(svg));
parse_selector_list(&context, input).map(|mut vec| vec.pop().unwrap())
} | identifier_body |
selectors.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/. */
use cssparser::Parser;
use selectors::parser::{Selector, ParserContext, parse_selector_list};
use style::selector_... | () {
assert_roundtrip!(parse, "div");
assert_roundtrip!(parse, "svg|circle");
assert_roundtrip!(parse, "p:before", "p::before");
assert_roundtrip!(parse, "[border = \"0\"]:-servo-nonzero-border ~ ::-servo-details-summary");
}
| test_selectors | identifier_name |
classification_test.py | import numpy as np
import pytoolkit as tk
def test_print_classification_multi():
y_true = np.array([0, 1, 1, 1, 2])
prob_pred = np.array(
[
[0.75, 0.00, 0.25],
[0.25, 0.75, 0.00],
[0.25, 0.75, 0.00],
[0.25, 0.00, 0.75],
[0.25, 0.75, 0.00],
... | ():
y_true = np.array([0, 1, 1, 0])
prob_pred = np.array([0.25, 0.25, 0.75, 0.25])
tk.evaluations.print_classification(y_true, prob_pred)
def test_print_classification_binary_multi():
y_true = np.array([0, 1, 1, 0])
prob_pred = np.array([[0.25, 0.75], [0.25, 0.75], [0.75, 0.25], [0.25, 0.75]])
... | test_print_classification_binary | identifier_name |
classification_test.py | import numpy as np
import pytoolkit as tk
def test_print_classification_multi():
y_true = np.array([0, 1, 1, 1, 2])
prob_pred = np.array(
[
[0.75, 0.00, 0.25],
[0.25, 0.75, 0.00],
[0.25, 0.75, 0.00],
[0.25, 0.00, 0.75],
[0.25, 0.75, 0.00],
... | y_true = np.array([0, 1, 1, 0])
prob_pred = np.array([[0.25, 0.75], [0.25, 0.75], [0.75, 0.25], [0.25, 0.75]])
tk.evaluations.print_classification(y_true, prob_pred) | identifier_body | |
classification_test.py | import numpy as np
import pytoolkit as tk
def test_print_classification_multi():
y_true = np.array([0, 1, 1, 1, 2])
prob_pred = np.array(
[
[0.75, 0.00, 0.25],
[0.25, 0.75, 0.00],
[0.25, 0.75, 0.00],
[0.25, 0.00, 0.75],
[0.25, 0.75, 0.00],
... | tk.evaluations.print_classification(y_true, prob_pred) | def test_print_classification_binary_multi():
y_true = np.array([0, 1, 1, 0])
prob_pred = np.array([[0.25, 0.75], [0.25, 0.75], [0.75, 0.25], [0.25, 0.75]]) | random_line_split |
webdriver_msg.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/. */
use constellation_msg::PipelineId; | use rustc_serialize::json::{Json, ToJson};
use url::Url;
#[derive(Deserialize, Serialize)]
pub enum WebDriverScriptCommand {
ExecuteScript(String, IpcSender<WebDriverJSResult>),
ExecuteAsyncScript(String, IpcSender<WebDriverJSResult>),
FindElementCSS(String, IpcSender<Result<Option<String>, ()>>),
Find... | use ipc_channel::ipc::IpcSender; | random_line_split |
webdriver_msg.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/. */
use constellation_msg::PipelineId;
use ipc_channel::ipc::IpcSender;
use rustc_serialize::json::{Json, ToJson};
use... | {
ExecuteScript(String, IpcSender<WebDriverJSResult>),
ExecuteAsyncScript(String, IpcSender<WebDriverJSResult>),
FindElementCSS(String, IpcSender<Result<Option<String>, ()>>),
FindElementsCSS(String, IpcSender<Result<Vec<String>, ()>>),
FocusElement(String, IpcSender<Result<(), ()>>),
GetActive... | WebDriverScriptCommand | identifier_name |
parser.py |
def parser(lien,nb) :
if lien == 1:
lien = "http://www.lesbonsnumeros.com/euromillions/rss.xml"
elif lien == 2:
lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=784&lang=ro"
elif lien == 3:
lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=313&lang=ro"
elif lien == 4:
lien = "http:... |
else :
nb = len(d['entries'])
while i < nb :
texte = d['entries'][i]['title'] + ". " + d['entries'][i]['description']
texte = re.sub('<[A-Za-z\/][^>]*>', '', texte)
for x in texte.split("\n"):
print x;
mouth.speakBlocking(x)
i += 1
| nb = nb | conditional_block |
parser.py |
def parser(lien,nb) :
|
elif lien == 2:
lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=784&lang=ro"
elif lien == 3:
lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=313&lang=ro"
elif lien == 4:
lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=526&lang=ro"
else :
lien = "http://www.20min.ch/rss/rss.tmpl?t... | if lien == 1:
lien = "http://www.lesbonsnumeros.com/euromillions/rss.xml" | identifier_body |
parser.py | def parser(lien,nb) :
if lien == 1:
lien = "http://www.lesbonsnumeros.com/euromillions/rss.xml"
elif lien == 2:
lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=784&lang=ro"
elif lien == 3:
lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=313&lang=ro" | elif lien == 4:
lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=526&lang=ro"
else :
lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=784&lang=ro"
d = feedparser.parse(lien)
i = 0
if nb == "de" :
nb = 2
if nb <= len(d['entries']) and nb != 0 :
nb = nb
else :
nb = len(d['entries'... | random_line_split | |
parser.py |
def | (lien,nb) :
if lien == 1:
lien = "http://www.lesbonsnumeros.com/euromillions/rss.xml"
elif lien == 2:
lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=784&lang=ro"
elif lien == 3:
lien = "http://www.20min.ch/rss/rss.tmpl?type=rubrik&get=313&lang=ro"
elif lien == 4:
lien = "http://www.20min... | parser | identifier_name |
routes.js | /*
* The MIT License (MIT)
*
* Copyright (c) 2018 Karl STEIN
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, c... |
let userIsConnected = false;
Router.autoRun = true;
Router.on("route", function () {
console.log("go to " + this.path);
});
Router.on("beforeRender", function () {
console.log("before " + this.path);
});
Router.on("afterRender", function () {
console.log("after " + this.path);
});
// Declare not foun... | {
let tpl = $("template[name=\"" + name + "\"]");
if (tpl.length) {
return tpl.eq(0).html();
}
} | identifier_body |
routes.js | /*
* The MIT License (MIT)
*
* Copyright (c) 2018 Karl STEIN
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, c... | (name) {
let tpl = $("template[name=\"" + name + "\"]");
if (tpl.length) {
return tpl.eq(0).html();
}
}
let userIsConnected = false;
Router.autoRun = true;
Router.on("route", function () {
console.log("go to " + this.path);
});
Router.on("beforeRender", function () {
console.log("before... | getTemplate | identifier_name |
routes.js | /*
* The MIT License (MIT)
*
* Copyright (c) 2018 Karl STEIN
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, c... |
Router.on("route", function () {
console.log("go to " + this.path);
});
Router.on("beforeRender", function () {
console.log("before " + this.path);
});
Router.on("afterRender", function () {
console.log("after " + this.path);
});
// Declare not found route
Router.notFound = function () {
this.render... | let userIsConnected = false;
Router.autoRun = true; | random_line_split |
routes.js | /*
* The MIT License (MIT)
*
* Copyright (c) 2018 Karl STEIN
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, c... |
});
}
});
Router.route("/forbidden", {
action: function () {
this.render(getTemplate("forbidden"));
}
});
Router.route("/form", {
action: function () {
this.render(getTemplate("form"));
}
});
Router.route("/login", {
action: function () {
userIsConnected = tru... | {
return confirm("Are you sure you want to quit this page ?");
} | conditional_block |
profile-status.js | Vue.http.options.emulateJSON = true;
var profile_status = new Vue({
el: '#profile-status',
data: {
isSuggestShow: 0,
suggest: [
{text: 'Предложение оплаты услуг, вирт за деньги, проституция, мошенничество, шантаж, спам', style: 'bg_ored'},
{text: 'Фото из интернета, паре... | };
}
}
}); | if (this.text == this.suggest[3].text) {
this.style = this.suggest[2].style;
};
if (this.text == this.suggest[4].text) {
this.style = this.suggest[4].style; | random_line_split |
profile-status.js |
Vue.http.options.emulateJSON = true;
var profile_status = new Vue({
el: '#profile-status',
data: {
isSuggestShow: 0,
suggest: [
{text: 'Предложение оплаты услуг, вирт за деньги, проституция, мошенничество, шантаж, спам', style: 'bg_ored'},
{text: 'Фото из интернета, пар... | conditional_block | ||
labelFilterUtils.ts | import { reduce } from 'lodash';
import type { IServerGroup } from '../../domain/IServerGroup';
export interface ILabelsMap {
[key: string]: string[];
}
export interface ILabelFilter {
key: string;
value: string;
}
export function buildLabelsMap(serverGroups: IServerGroup[]): ILabelsMap {
return reduce(
... | {
if (!trueKeyObject) {
return [];
}
return reduce(
trueKeyObject,
(labelFilters, _val, composedKey) => {
let [key, value] = composedKey.split(':');
if (key === 'null') {
key = null;
}
if (value === 'null') {
value = null;
}
return labelFilters.conca... | identifier_body | |
labelFilterUtils.ts | import { reduce } from 'lodash';
import type { IServerGroup } from '../../domain/IServerGroup';
export interface ILabelsMap {
[key: string]: string[];
}
export interface ILabelFilter {
key: string;
value: string;
}
export function buildLabelsMap(serverGroups: IServerGroup[]): ILabelsMap {
return reduce(
... |
return reduce(
labelFilters,
(trueKeyObj: { [key: string]: boolean }, labelFilter) => {
const key = `${labelFilter.key}:${labelFilter.value}`;
trueKeyObj[key] = true;
return trueKeyObj;
},
{},
);
}
export function trueKeyObjectToLabelFilters(trueKeyObject: { [key: string]: boolea... | {
return {};
} | conditional_block |
labelFilterUtils.ts | import { reduce } from 'lodash';
import type { IServerGroup } from '../../domain/IServerGroup';
export interface ILabelsMap {
[key: string]: string[];
}
export interface ILabelFilter {
key: string;
value: string;
}
export function buildLabelsMap(serverGroups: IServerGroup[]): ILabelsMap {
return reduce(
... | (labelFilters: ILabelFilter[]): { [key: string]: boolean } {
if (!labelFilters) {
return {};
}
return reduce(
labelFilters,
(trueKeyObj: { [key: string]: boolean }, labelFilter) => {
const key = `${labelFilter.key}:${labelFilter.value}`;
trueKeyObj[key] = true;
return trueKeyObj;
... | labelFiltersToTrueKeyObject | identifier_name |
labelFilterUtils.ts | import { reduce } from 'lodash';
import type { IServerGroup } from '../../domain/IServerGroup';
export interface ILabelsMap {
[key: string]: string[];
}
export interface ILabelFilter {
key: string;
value: string;
}
export function buildLabelsMap(serverGroups: IServerGroup[]): ILabelsMap {
return reduce(
... | }
if (value === 'null') {
value = null;
}
return labelFilters.concat([{ key, value }]);
},
[],
);
} | random_line_split | |
crateresolve4b-2.rs | // Copyright 2012 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 ... | { crateresolve4a::f() } | identifier_body | |
crateresolve4b-2.rs | // Copyright 2012 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 ... | () -> int { crateresolve4a::f() }
| g | identifier_name |
test_shared_group_details.py | from __future__ import absolute_import, print_function
from sentry.testutils import APITestCase
class SharedGroupDetailsTest(APITestCase):
def | (self):
self.login_as(user=self.user)
group = self.create_group()
event = self.create_event(group=group)
url = '/api/0/shared/issues/{}/'.format(group.get_share_id())
response = self.client.get(url, format='json')
assert response.status_code == 200, response.content
... | test_simple | identifier_name |
test_shared_group_details.py | from __future__ import absolute_import, print_function
from sentry.testutils import APITestCase
class SharedGroupDetailsTest(APITestCase):
def test_simple(self):
self.login_as(user=self.user)
group = self.create_group()
event = self.create_event(group=group)
url = '/api/0/shared... |
def test_feature_disabled(self):
self.login_as(user=self.user)
group = self.create_group()
org = group.organization
org.flags.disable_shared_issues = True
org.save()
url = '/api/0/shared/issues/{}/'.format(group.get_share_id())
response = self.client.get(ur... | random_line_split | |
test_shared_group_details.py | from __future__ import absolute_import, print_function
from sentry.testutils import APITestCase
class SharedGroupDetailsTest(APITestCase):
def test_simple(self):
|
def test_feature_disabled(self):
self.login_as(user=self.user)
group = self.create_group()
org = group.organization
org.flags.disable_shared_issues = True
org.save()
url = '/api/0/shared/issues/{}/'.format(group.get_share_id())
response = self.client.get(u... | self.login_as(user=self.user)
group = self.create_group()
event = self.create_event(group=group)
url = '/api/0/shared/issues/{}/'.format(group.get_share_id())
response = self.client.get(url, format='json')
assert response.status_code == 200, response.content
assert res... | identifier_body |
gregorian.js | define(
"dojo/cldr/nls/en-ie/gregorian", //begin v1.x content
{ | "timeFormat-medium": "HH:mm:ss",
"dateFormatItem-yyyyMMMM": "MMMM y",
"dateFormatItem-MEd": "E, d/M",
"dateFormat-medium": "d MMM y",
"dateFormatItem-MMdd": "dd/MM",
"dateFormatItem-yyyyMM": "MM/yyyy",
"dateFormat-full": "EEEE d MMMM y",
"timeFormat-long": "HH:mm:ss z",
"dayPeriods-format-wide-am": "a.m.",
"t... | "dateFormatItem-Md": "d/M",
"dateFormatItem-yMEd": "EEE, d/M/yyyy",
"timeFormat-full": "HH:mm:ss zzzz", | random_line_split |
mod.rs | //! The compiler code necessary to implement the `#[derive]` extensions.
use rustc_ast as ast;
use rustc_ast::ptr::P;
use rustc_ast::{Impl, ItemKind, MetaItem};
use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, MultiItemModifier};
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_span::Span;
macro pa... |
_ => {
(self.0)(ecx, span, meta_item, &item, &mut |a| items.push(a));
}
}
ExpandResult::Ready(items)
}
}
/// Constructs an expression that calls an intrinsic
fn call_intrinsic(
cx: &ExtCtxt<'_>,
span: Span,
intrinsic: Symbol,
args: Vec<P<ast:... | {
if let ast::StmtKind::Item(item) = stmt.into_inner().kind {
(self.0)(ecx, span, meta_item, &Annotatable::Item(item), &mut |a| {
// Cannot use 'ecx.stmt_item' here, because we need to pass 'ecx'
// to the function
... | conditional_block |
mod.rs | //! The compiler code necessary to implement the `#[derive]` extensions.
use rustc_ast as ast;
use rustc_ast::ptr::P;
use rustc_ast::{Impl, ItemKind, MetaItem};
use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, MultiItemModifier};
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_span::Span;
macro pa... |
macro pathvec_std($($rest:ident)::+) {{
vec![ $( sym::$rest ),+ ]
}}
macro path_std($($x:tt)*) {
generic::ty::Path::new( pathvec_std!( $($x)* ) )
}
pub mod bounds;
pub mod clone;
pub mod debug;
pub mod decodable;
pub mod default;
pub mod encodable;
pub mod hash;
#[path = "cmp/eq.rs"]
pub mod eq;
#[path = "c... | random_line_split | |
structinfo.rs | // GObject Introspection Rust bindings.
// Copyright (C) 2014 Luis Araujo <araujoc.luisf@gmail.com>
// This library 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 2.1 of the Licen... | unsafe { g_struct_info_get_field(info, n as c_int) }
}
/// Obtain the number of methods this structure has.
pub fn get_n_methods(info: *GIStructInfo) -> int {
unsafe { g_struct_info_get_n_methods(info) as int }
}
/// Obtain the type information for method with specified index.
pub fn get_method(info: *GIStruc... | pub fn get_field(info: *GIStructInfo, n: int) -> *GIFieldInfo { | random_line_split |
structinfo.rs | // GObject Introspection Rust bindings.
// Copyright (C) 2014 Luis Araujo <araujoc.luisf@gmail.com>
// This library 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 2.1 of the Licen... |
/// Obtain the required alignment of the structure.
pub fn get_alignment(info: *GIStructInfo) -> size_t {
unsafe { g_struct_info_get_alignment(info) }
}
/// Return true if this structure represents the "class structure" for some
/// GObject or GInterface.
pub fn is_gtype_struct(info: *GIStructInfo) -> GBoolean... | {
unsafe { g_struct_info_get_size(info) }
} | identifier_body |
structinfo.rs | // GObject Introspection Rust bindings.
// Copyright (C) 2014 Luis Araujo <araujoc.luisf@gmail.com>
// This library 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 2.1 of the Licen... | (info: *GIStructInfo) -> GBoolean {
unsafe { g_struct_info_is_foreign(info) }
}
/// Convert GIBaseInfo to GIStructInfo.
pub fn to_gi_struct_info<T>(object: *T) -> *GIStructInfo {
unsafe { transmute(object) }
}
| is_foreign | identifier_name |
logdata.py | import RPi.GPIO as GPIO
import os
import time
import datetime
import glob
import MySQLdb
from time import strftime
import serial
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
counter = ... | f=x.split()
moisture = f[1]
humidity = f[4]
temp = f[7]
print("Moisture: ")
print moisture
print("Humidity: ")
print humidity
print("Temperature: ")
print temp
datetimeWrite = (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S"))
sql = ("""INSERT INTO tempLog (datetime... | db = MySQLdb.connect(host="localhost", user="root",passwd="deb280794", db="temp_database")
cur = db.cursor()
while True:
x = ser.readline() | random_line_split |
logdata.py | import RPi.GPIO as GPIO
import os
import time
import datetime
import glob
import MySQLdb
from time import strftime
import serial
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
counter = ... | except:
# Rollback in case there is any error
db.rollback()
print "Failed writing to database"
time.sleep(0.5)
| x = ser.readline()
f=x.split()
moisture = f[1]
humidity = f[4]
temp = f[7]
print("Moisture: ")
print moisture
print("Humidity: ")
print humidity
print("Temperature: ")
print temp
datetimeWrite = (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S"))
sql = ("""INSERT INT... | conditional_block |
app.js | /**
*
* app.js
*
* This is the entry file for the application, mostly just setup and boilerplate
* code. Routes are configured at the end of this file!
*
*/
// Load the ServiceWorker, the Cache polyfill, the manifest.json file and the .htaccess file
import 'file?name=[name].[ext]!../serviceworker.js';
import 'f... |
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route } from 'react-router';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import FontFaceObserver from 'fontfaceobserver';... | {
// No ServiceWorker Support
} | conditional_block |
app.js | /**
*
* app.js
*
* This is the entry file for the application, mostly just setup and boilerplate
* code. Routes are configured at the end of this file!
*
*/
// Load the ServiceWorker, the Cache polyfill, the manifest.json file and the .htaccess file
import 'file?name=[name].[ext]!../serviceworker.js';
import 'f... |
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
// Observer loading of Open Sans (to remove open sans, remove the <link> tag in the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Open Sans', {});
// When Open Sans is loaded, add the js... |
import injectTapEventPlugin from 'react-tap-event-plugin'; | random_line_split |
runtimeCache.py | # -*- coding: utf-8 -*-
"""
Stores metadata about images which are built to encorporate changes to subuser images which are required in order to implement various permissions.
"""
#external imports
import os
import json
#internal imports
from subuserlib.classes.userOwnedObject import UserOwnedObject
from subuserlib.c... | (self):
if not self.getSubuser().getImageId():
raise NoRuntimeCacheForSubusersWhichDontHaveExistantImagesException("No runnable image for subuser found. Use\n\n $ subuser repair\n\nTo repair your instalation.")
runtimeCacheFilePath = self.getRuntimeCacheFilePath()
if os.path.exists(runtimeCacheFilePat... | load | identifier_name |
runtimeCache.py | # -*- coding: utf-8 -*-
"""
Stores metadata about images which are built to encorporate changes to subuser images which are required in order to implement various permissions.
"""
#external imports
import os
import json
#internal imports
from subuserlib.classes.userOwnedObject import UserOwnedObject
from subuserlib.c... | json.dump(self,runtimeCacheFileHandle,indent=1,separators=(',',': '))
def reload(self):
self.save()
self.load()
def load(self):
if not self.getSubuser().getImageId():
raise NoRuntimeCacheForSubusersWhichDontHaveExistantImagesException("No runnable image for subuser found. Use\n\n $ subuser... | def __init__(self,user,subuser):
self.__subuser = subuser
UserOwnedObject.__init__(self,user)
self.load()
def getPathToCurrentImagesRuntimeCacheDir(self):
return os.path.join(self.getUser().getConfig()["runtime-cache"],self.getSubuser().getImageId())
def getRuntimeCacheFilePath(self):
return o... | identifier_body |
runtimeCache.py | # -*- coding: utf-8 -*-
"""
Stores metadata about images which are built to encorporate changes to subuser images which are required in order to implement various permissions.
"""
#external imports
import os
import json
#internal imports
from subuserlib.classes.userOwnedObject import UserOwnedObject
from subuserlib.c... |
runtimeCacheFilePath = self.getRuntimeCacheFilePath()
if os.path.exists(runtimeCacheFilePath):
with open(runtimeCacheFilePath,mode="r") as runtimeCacheFileHandle:
runtimeCacheInfo = json.load(runtimeCacheFileHandle)
self.update(runtimeCacheInfo)
class NoRuntimeCacheForSubusersWhichDontHa... | raise NoRuntimeCacheForSubusersWhichDontHaveExistantImagesException("No runnable image for subuser found. Use\n\n $ subuser repair\n\nTo repair your instalation.") | conditional_block |
runtimeCache.py | # -*- coding: utf-8 -*-
"""
Stores metadata about images which are built to encorporate changes to subuser images which are required in order to implement various permissions.
"""
#external imports
import os
import json
#internal imports
from subuserlib.classes.userOwnedObject import UserOwnedObject
from subuserlib.c... |
def load(self):
if not self.getSubuser().getImageId():
raise NoRuntimeCacheForSubusersWhichDontHaveExistantImagesException("No runnable image for subuser found. Use\n\n $ subuser repair\n\nTo repair your instalation.")
runtimeCacheFilePath = self.getRuntimeCacheFilePath()
if os.path.exists(runtimeC... | random_line_split | |
interactive.js | 'use strict';
// virtual-dom
var h = require('virtual-dom/h');
// lodash
var difference = require('lodash/difference');
// bpmn-questionnaire
var BpmnQuestionnaire = require('../../../../lib/BpmnQuestionnaire');
var interactive = BpmnQuestionnaire.createType({
renderQuestion: fu... | var html;
if (this.state.rightAnswer) {
html =
h('div.panel.panel-success', [
h('div.panel-heading',
h('h3.panel-title', 'Glückwunsch!')
),
h('div.panel-body', 'Sie haben diese Frage richtig beantwortet!')
]);
} else {
... | renderResult: function() {
| random_line_split |
interactive.js | 'use strict';
// virtual-dom
var h = require('virtual-dom/h');
// lodash
var difference = require('lodash/difference');
// bpmn-questionnaire
var BpmnQuestionnaire = require('../../../../lib/BpmnQuestionnaire');
var interactive = BpmnQuestionnaire.createType({
renderQuestion: fu... |
return html;
},
checkIfValidAnswer: function() {
return this.diagram.state.selected.length > 0;
},
checkIfRightAnswer: function() {
return difference(this.options.diagram.rightAnswers, this.diagram.state.selected).length < 1;
}
});
module.exports = interactive; |
html = [
h('div.panel.panel-danger', [
h('div.panel-heading',
h('h3.panel-title', 'Oh nein!')
),
h('div.panel-body', 'Ihre Antwort war leider falsch! Die richtige Antwort lautet:')
]),
this.diagram.render(this.state)
]
... | conditional_block |
english.js | export default {
navigator: {
doc: 'Docs',
demo: 'Demo',
started: 'Get Started'
},
features: {
userExperience: {
title: 'Optimize Experience',
desc: 'To make scroll more smoothly, We support flexible configurations about inertial scrolling, rebound, fade scrollbar, etc. which could o... |
normalScrollListPage: {
desc: 'Nomal scroll list based on BetterScroll',
scrollbar: 'Scrollbar',
pullDownRefresh: 'Pull Down Refresh',
pullUpLoad: 'Pull Up Load',
previousTxt: 'I am the No.',
followingTxt: ' line',
newDataTxt: 'I am new data: '
},
scrollComponent: {
defaultLoadTx... | startGuidanceImg: 'full-page-slide.jpeg',
freeScrollImg: 'free-scroll.jpeg',
formListImg: 'form-list-en.jpeg'
}, | random_line_split |
pyunit_DEPRECATED_link_functions_binomialGLM.py | import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
import pandas as pd
import zipfile
import statsmodels.api as sm
def | ():
print("Read in prostate data.")
h2o_data = h2o.import_file(path=pyunit_utils.locate("smalldata/prostate/prostate_complete.csv.zip"))
h2o_data.head()
sm_data = pd.read_csv(zipfile.ZipFile(pyunit_utils.locate("smalldata/prostate/prostate_complete.csv.zip")).open("prostate_complete.csv")).as_matrix()
... | link_functions_binomial | identifier_name |
pyunit_DEPRECATED_link_functions_binomialGLM.py | import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
import pandas as pd
import zipfile
import statsmodels.api as sm
def link_functions_binomial():
| assert h2o_deviance - sm_deviance < 0.01, "expected h2o to have an equivalent or better deviance measures"
if __name__ == "__main__":
pyunit_utils.standalone_test(link_functions_binomial)
else:
link_functions_binomial()
| print("Read in prostate data.")
h2o_data = h2o.import_file(path=pyunit_utils.locate("smalldata/prostate/prostate_complete.csv.zip"))
h2o_data.head()
sm_data = pd.read_csv(zipfile.ZipFile(pyunit_utils.locate("smalldata/prostate/prostate_complete.csv.zip")).open("prostate_complete.csv")).as_matrix()
sm_data_resp... | identifier_body |
pyunit_DEPRECATED_link_functions_binomialGLM.py | import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
import pandas as pd
import zipfile
import statsmodels.api as sm
def link_functions_binomial():
print("Read in prostate data.")
h2o_data = h2o.import_file(path=pyunit_utils.locate("smalldata/prostate/prostate_complete.csv... |
else:
link_functions_binomial()
| pyunit_utils.standalone_test(link_functions_binomial) | conditional_block |
pyunit_DEPRECATED_link_functions_binomialGLM.py | import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
import pandas as pd
import zipfile
import statsmodels.api as sm
def link_functions_binomial():
print("Read in prostate data.")
h2o_data = h2o.import_file(path=pyunit_utils.locate("smalldata/prostate/prostate_complete.csv... | print("Testing for family: BINOMIAL")
print("Set variables for h2o.")
myY = "CAPSULE"
myX = ["ID","AGE","RACE","GLEASON","DCAPS","PSA","VOL","DPROS"]
print("Create models with canonical link: LOGIT")
h2o_model = h2o.glm(x=h2o_data[myX], y=h2o_data[myY].asfactor(), family="binomial", link="logit",alpha=[0.5... | sm_data_features = sm_data[:,[1,3,4,5,6,7,8,9]]
| random_line_split |
mod.rs | remacs_sys::{extract_data_from_object, make_uninit_string},
remacs_sys::{Qmd5, Qnil, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512},
symbols::{symbol_name, LispSymbolRef},
threads::ThreadState,
};
#[derive(Clone, Copy)]
enum HashAlg {
MD5,
SHA1,
SHA224,
SHA256,
SHA384,
SHA512,
}
st... |
fn sha512_buffer(buffer: &[u8], dest_buf: &mut [u8]) {
sha2_hash_buffer(Sha512::new(), buffer, dest_buf);
}
/// Return a hash of the contents of BUFFER-OR-NAME.
/// This hash is performed on the raw internal format of the buffer,
/// disregarding any coding systems. If nil, use the current buffer.
#[l | {
sha2_hash_buffer(Sha384::new(), buffer, dest_buf);
} | identifier_body |
mod.rs | remacs_sys::{extract_data_from_object, make_uninit_string},
remacs_sys::{Qmd5, Qnil, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512},
symbols::{symbol_name, LispSymbolRef},
threads::ThreadState,
};
#[derive(Clone, Copy)]
enum HashAlg {
MD5,
SHA1,
SHA224,
SHA256,
SHA384,
SHA512,
}
st... | sha2_hash_buffer(Sha224::new(), buffer, dest_buf);
}
fn sha256_buffer(buffer: &[u8], dest_buf: &mut [u8]) {
sha2_hash_buffer(Sha256::new(), buffer, dest_buf);
}
fn sha384_buffer(buffer: &[u8], dest_buf: &mut [u8]) {
sha2_hash_buffer(Sha384::new(), buffer, dest_buf);
}
fn sha512_buffer(buffer: &[u8], dest... |
fn sha224_buffer(buffer: &[u8], dest_buf: &mut [u8]) { | random_line_split |
mod.rs | ,
remacs_sys::{extract_data_from_object, make_uninit_string},
remacs_sys::{Qmd5, Qnil, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512},
symbols::{symbol_name, LispSymbolRef},
threads::ThreadState,
};
#[derive(Clone, Copy)]
enum HashAlg {
MD5,
SHA1,
SHA224,
SHA256,
SHA384,
SHA512,
}
... | (
algorithm: HashAlg,
object: LispObject,
start: LispObject,
end: LispObject,
coding_system: LispObject,
noerror: LispObject,
binary: LispObject,
) -> LispObject {
type HashFn = fn(&[u8], &mut [u8]);
let spec = list!(object, start, end, coding_system, noerror);
let mut start_byt... | _secure_hash | identifier_name |
mod.rs | remacs_sys::{extract_data_from_object, make_uninit_string},
remacs_sys::{Qmd5, Qnil, Qsha1, Qsha224, Qsha256, Qsha384, Qsha512},
symbols::{symbol_name, LispSymbolRef},
threads::ThreadState,
};
#[derive(Clone, Copy)]
enum HashAlg {
MD5,
SHA1,
SHA224,
SHA256,
SHA384,
SHA512,
}
st... |
digest
}
/// To avoid a copy, buffer is both the source and the destination of
/// this transformation. Buffer must contain len bytes of data and
/// 2*len bytes of space for the final hex string.
fn hexify_digest_string(buffer: &mut [u8], len: usize) {
static hexdigit: [u8; 16] = *b"0123456789abcdef";
de... | {
hexify_digest_string(digest_str.as_mut_slice(), digest_size);
} | conditional_block |
main.js | const electron = require('electron');
const app = electron.app; // Module to control application life. |
// Report crashes to our server.
// electron.crashReporter.start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;
const APP_NAME = app.getName();
const DARWIN_ALL_CLOSED_MENU = [
{
... | const BrowserWindow = electron.BrowserWindow; // Module to create native browser window.
const Menu = electron.Menu;
const autoUpdater = electron.autoUpdater;
const dialog = electron.dialog; | random_line_split |
main.js | const electron = require('electron');
const app = electron.app; // Module to control application life.
const BrowserWindow = electron.BrowserWindow; // Module to create native browser window.
const Menu = electron.Menu;
const autoUpdater = electron.autoUpdater;
const dialog = electron.dialog;
// Report crashes to o... |
mainWindow = new BrowserWindow(conf);
// Set ApplicationMenu bar
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/index.html');
// Open the DevTools.
// mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function()... | {
conf['icon'] = __dirname + '/icon.png';
} | conditional_block |
main.js | const electron = require('electron');
const app = electron.app; // Module to control application life.
const BrowserWindow = electron.BrowserWindow; // Module to create native browser window.
const Menu = electron.Menu;
const autoUpdater = electron.autoUpdater;
const dialog = electron.dialog;
// Report crashes to o... | // Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
function ... | {
// Create the browser window.
var conf = {
width: 1024, height: 768,
minWidth: 270, minHeight: 437,
titleBarStyle: 'hidden'
};
if (process.platform == 'linux') {
conf['icon'] = __dirname + '/icon.png';
}
mainWindow = new BrowserWindow(conf);
// Set ApplicationMenu bar
// and load the... | identifier_body |
main.js | const electron = require('electron');
const app = electron.app; // Module to control application life.
const BrowserWindow = electron.BrowserWindow; // Module to create native browser window.
const Menu = electron.Menu;
const autoUpdater = electron.autoUpdater;
const dialog = electron.dialog;
// Report crashes to o... | () {
var feedUrl = 'https://zwkuawed8b.execute-api.ap-northeast-1.amazonaws.com/prod?version=' + app.getVersion();
autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
var index = dialog.showMessageBox(mainWindow, {
type: 'info',
... | applyUpdater | identifier_name |
models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import (
force_text, python_2_unicode_compatible)
from django.utils.translation import ugettext_lazy as _
from select_multiple_field.models import Se... | choices=FLAVOUR_CHOICES
)
RANCH = 'r'
HONEY_MUSTARD = 'h'
BBQ = 'b'
DIP_CHOICES = (
(RANCH, _('Ranch')),
(HONEY_MUSTARD, _('Honey mustard')),
(BBQ, _('BBQ')),
)
dips = SelectMultipleField(
blank=True,
default='',
include_blank=False,
... | include_blank=False,
max_length=5,
max_choices=2, | random_line_split |
models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import (
force_text, python_2_unicode_compatible)
from django.utils.translation import ugettext_lazy as _
from select_multiple_field.models import Se... | (models.Model):
"""ChickenBalls is used for South migration testing"""
SUICIDE = 's'
HOT = 'h'
HOME_STYLE = 'H'
CAJUN = 'c'
JERK = 'j'
GATOR = 'g'
FLAVOUR_CHOICES = (
(_('Hot & Spicy'), (
(SUICIDE, _('Suicide hot')),
(HOT, _('Hot hot sauce')),
... | ChickenBalls | identifier_name |
models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
from django.utils.encoding import (
force_text, python_2_unicode_compatible)
from django.utils.translation import ugettext_lazy as _
from select_multiple_field.models import Se... | return reverse('ftw:detail', args=[self.pk]) | identifier_body | |
Todo.test.tsx | import React from 'react'
import { mount } from 'enzyme'
import renderer from 'react-test-renderer'
import Todo, { Props } from '../Todo'
describe('Todo component', () => {
const props: Props = {
completed: false,
onClick: jest.fn(),
text: 'todo text',
}
it('should render correctly when not comple... | })
}) | random_line_split | |
OcpLoginByTempAdmin.ts | /*********************************************************************
* Copyright (c) 2019 Red Hat, Inc.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifi... |
await this.ocpLogin.enterUserNameOpenShift(TestConstants.TS_SELENIUM_OCP_USERNAME);
await this.ocpLogin.enterPasswordOpenShift(TestConstants.TS_SELENIUM_OCP_PASSWORD);
await this.ocpLogin.clickOnLoginButton();
await this.ocpLogin.waitDisappearanceLoginPageOpenShift();
}
} | Logger.debug('OcpLoginByTempAdmin.login');
if (TestConstants.TS_OCP_LOGIN_PAGE_HTPASW) {
await this.ocpLogin.clickOnLoginWitnKubeAdmin();
} | random_line_split |
OcpLoginByTempAdmin.ts | /*********************************************************************
* Copyright (c) 2019 Red Hat, Inc.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifi... |
await this.ocpLogin.enterUserNameOpenShift(TestConstants.TS_SELENIUM_OCP_USERNAME);
await this.ocpLogin.enterPasswordOpenShift(TestConstants.TS_SELENIUM_OCP_PASSWORD);
await this.ocpLogin.clickOnLoginButton();
await this.ocpLogin.waitDisappearanceLoginPageOpenShift();
}
}
| {
await this.ocpLogin.clickOnLoginWitnKubeAdmin();
} | conditional_block |
OcpLoginByTempAdmin.ts | /*********************************************************************
* Copyright (c) 2019 Red Hat, Inc.
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifi... | (
@inject(CLASSES.OcpLoginPage) private readonly ocpLogin: OcpLoginPage) { }
async login() {
Logger.debug('OcpLoginByTempAdmin.login');
if (TestConstants.TS_OCP_LOGIN_PAGE_HTPASW) {
await this.ocpLogin.clickOnLoginWitnKubeAdmin();
}
await this.ocpLogin.enterUse... | constructor | identifier_name |
index.ts |
if (process.env.APP_DATA_PATH) {
process.APP_DATA_PATH = process.env.APP_DATA_PATH
} else {
process.APP_DATA_PATH = getAppDataPath()
}
process.IS_FAILSAFE = yn(process.env.BP_FAILSAFE)
process.BOTPRESS_EVENTS = new EventEmitter()
process.BOTPRESS_EVENTS.setMaxListeners(1000)
global.BOTPRESS_CORE_EVENT = (event, ... | {
if (typeof arguments[0] === 'string' && shouldDiscardError(arguments[0])) {
return (arguments[2] || arguments[1])()
}
return originalWrite.apply(this, (arguments as never) as [string])
} | identifier_body | |
index.ts | 'string' && shouldDiscardError(arguments[0])) {
return (arguments[2] || arguments[1])()
}
return originalWrite.apply(this, (arguments as never) as [string])
}
if (process.env.APP_DATA_PATH) {
process.APP_DATA_PATH = process.env.APP_DATA_PATH
} else {
process.APP_DATA_PATH = getAppDataPath()
}
process.IS... | type: 'string'
},
authToken: {
alias: 'token',
description: 'Authorization token on the remote botpress server',
type: 'string'
},
sourceDir: {
alias: 'dir',
description: 'The local directory containing the data you want to push... | random_line_split | |
index.ts | (this: Function): boolean {
if (typeof arguments[0] === 'string' && shouldDiscardError(arguments[0])) {
return (arguments[2] || arguments[1])()
}
return originalWrite.apply(this, (arguments as never) as [string])
}
if (process.env.APP_DATA_PATH) {
process.APP_DATA_PATH = process.env.APP_DATA_PATH
} else {... | stripDeprecationWrite | identifier_name | |
index.ts | string' && shouldDiscardError(arguments[0])) |
return originalWrite.apply(this, (arguments as never) as [string])
}
if (process.env.APP_DATA_PATH) {
process.APP_DATA_PATH = process.env.APP_DATA_PATH
} else {
process.APP_DATA_PATH = getAppDataPath()
}
process.IS_FAILSAFE = yn(process.env.BP_FAILSAFE)
process.BOTPRESS_EVENTS = new EventEmitter()
process.BOT... | {
return (arguments[2] || arguments[1])()
} | conditional_block |
a.rs | use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::error::Error;
static KEYPAD_MAP: [[u8; 3]; 3] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
struct Turtle {
x: i8,
y: i8,
code: String,
}
impl Turtle {
fn new() -> Turtle {
Turtle {
x: 1,
... | }
fn set_x(&mut self, x: i8) {
if self.x + x <= 2 && self.x + x >= 0 {
self.x = self.x + x;
}
}
fn set_y(&mut self, y: i8) {
if self.y + y <= 2 && self.y + y >= 0{
self.y = self.y + y;
}
}
fn move_turtle(&mut self, direction: &char) ... | random_line_split | |
a.rs | use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::error::Error;
static KEYPAD_MAP: [[u8; 3]; 3] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
struct Turtle {
x: i8,
y: i8,
code: String,
}
impl Turtle {
fn new() -> Turtle {
Turtle {
x: 1,
... |
fn press_button(&mut self) {
self.code.push_str(KEYPAD_MAP[self.y as usize][self.x as usize].to_string().as_str());
}
}
fn main() {
let mut turtle = Turtle::new();
let f = match File::open("input.txt") {
Err(e) => panic!("open failed: {}", e.description()),
Ok(file) => file,
... | {
match direction.to_lowercase().collect::<String>().as_str() {
"r" => self.set_x(1),
"l" => self.set_x(-1),
"u" => self.set_y(-1),
"d" => self.set_y(1),
_ => panic!("not a valid direction!"),
};
} | identifier_body |
a.rs | use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::error::Error;
static KEYPAD_MAP: [[u8; 3]; 3] = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]];
struct Turtle {
x: i8,
y: i8,
code: String,
}
impl Turtle {
fn new() -> Turtle {
Turtle {
x: 1,
... | (&mut self, direction: &char) {
match direction.to_lowercase().collect::<String>().as_str() {
"r" => self.set_x(1),
"l" => self.set_x(-1),
"u" => self.set_y(-1),
"d" => self.set_y(1),
_ => panic!("not a valid direction!"),
};
}
fn pr... | move_turtle | identifier_name |
test_maxout_op.py | # Copyright (c) 2018 PaddlePaddle 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 app... | unittest.main() | conditional_block | |
test_maxout_op.py | # Copyright (c) 2018 PaddlePaddle 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 app... |
def test_check_grad(self):
self.check_grad(['X'], 'Out')
class TestMaxOutOpAxis0(TestMaxOutOp):
def set_attrs(self):
self.axis = -1
class TestMaxOutOpAxis1(TestMaxOutOp):
def set_attrs(self):
self.axis = 3
class TestMaxOutOpFP32(TestMaxOutOp):
def set_attrs(self):
... | def setUp(self):
self.op_type = "maxout"
self.dtype = 'float64'
self.shape = [3, 6, 2, 4]
self.groups = 2
self.axis = 1
self.set_attrs()
x = np.random.uniform(-1, 1, self.shape).astype(self.dtype)
out = maxout_forward_naive(x, self.groups, self.axis)
... | identifier_body |
test_maxout_op.py | # Copyright (c) 2018 PaddlePaddle 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 app... | (self):
self.check_output()
def test_check_grad(self):
self.check_grad(['X'], 'Out')
class TestMaxOutOpAxis0(TestMaxOutOp):
def set_attrs(self):
self.axis = -1
class TestMaxOutOpAxis1(TestMaxOutOp):
def set_attrs(self):
self.axis = 3
class TestMaxOutOpFP32(TestMaxOutOp... | test_check_output | identifier_name |
test_maxout_op.py | # Copyright (c) 2018 PaddlePaddle 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 app... | out = fluid.layers.maxout(x, groups=self.groups, axis=self.axis)
exe = fluid.Executor(self.place)
res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
out_ref = maxout_forward_naive(self.x_np, self.groups, self.axis)
self.assertTrue(np.allclose(out_ref, res[0]))
... | paddle.enable_static()
def test_fluid_api(self):
with fluid.program_guard(fluid.Program()):
x = fluid.data('X', self.x_np.shape, self.x_np.dtype) | random_line_split |
webkittab.py | ypes.KeyMode.caret:
return
self.selection_enabled = self._widget.hasSelection()
self.selection_toggled.emit(self.selection_enabled)
settings = self._widget.settings()
settings.setAttribute(QWebSettings.CaretBrowsingEnabled, True)
if self._widget.isVisible():
... | selected_element = xml.etree.ElementTree.fromstring(
'<html>{}</html>'.format(selection)).find('a')
except xml.etree.ElementTree.ParseError:
raise browsertab.WebTabError('Could not parse selected '
'element!')
... | random_line_split | |
webkittab.py |
def check_printer_support(self):
pass
def check_preview_support(self):
pass
def to_pdf(self, filename):
printer = QPrinter()
printer.setOutputFileName(filename)
self.to_printer(printer)
def to_printer(self, printer, callback=None):
self._widget.print(... | pass | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.