file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
printing.py | # Copyright (C) 2010, 2012 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions an... |
else:
summary = "%s ran as expected%s, %d didn't%s%s:" % (grammar.pluralize('test', expected), expected_summary_str, unexpected, incomplete_str, timing_summary)
self._print_quiet(summary)
self._print_quiet("")
def _test_status_line(self, test_name, suffix):
format_stri... | if expected == total:
if expected > 1:
summary = "All %d tests ran as expected%s%s." % (expected, expected_summary_str, timing_summary)
else:
summary = "The test ran as expected%s%s." % (expected_summary_str, timing_summary)
else:
... | conditional_block |
printing.py | # Copyright (C) 2010, 2012 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions an... | (self, run_results):
# Reverse-sort by the time spent in the driver.
individual_test_timings = sorted(run_results.results_by_name.values(), key=lambda result: result.test_run_time, reverse=True)
num_printed = 0
slow_tests = []
timeout_or_crash_tests = []
unexpected_slow_... | _print_individual_test_times | identifier_name |
printing.py | # Copyright (C) 2010, 2012 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions an... |
if self._options.details:
self._print_test_trace(result, exp_str, got_str)
elif self._options.verbose or not expected:
self.writeln(self._test_status_line(test_name, result_message))
elif self.num_completed == self.num_tests:
self._meter.write_update('')
... | self._options.timing, result.test_run_time) | random_line_split |
epics.ts | import { Epic } from 'redux-observable';
import { from, of } from 'rxjs'; | import { RootAction, RootState, Services, isActionOf } from 'typesafe-actions';
import { loadTodosAsync, saveTodosAsync } from './actions';
import { getTodos } from './selectors';
export const loadTodosEpic: Epic<
RootAction,
RootAction,
RootState,
Services
> = (action$, state$, { api }) =>
action$.pipe(
... | import { filter, switchMap, map, catchError } from 'rxjs/operators'; | random_line_split |
resolveService.ts | /** @module ng1 */ /** */
import {State} from "../../state/stateObject";
import {PathNode} from "../../path/node";
import {ResolveContext} from "../../resolve/resolveContext";
import {Obj, mapObj} from "../../common/common"; | /**
* Implementation of the legacy `$resolve` service for angular 1.
*/
var $resolve = {
/**
* Asynchronously injects a resolve block.
*
* This emulates most of the behavior of the ui-router 0.2.x $resolve.resolve() service API.
*
* Given an object `invocables`, where keys are strings and values are ... | import {resolvablesBuilder} from "../../state/stateBuilder";
| random_line_split |
ip.rs | //! Handles parsing of Internet Protocol fields (shared between ipv4 and ipv6)
use nom::bits;
use nom::error::Error;
use nom::number;
use nom::sequence;
use nom::IResult;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IPProtocol {
... |
}
pub(crate) fn two_nibbles(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
bits::bits::<_, _, Error<_>, _, _>(sequence::pair(
bits::streaming::take(4u8),
bits::streaming::take(4u8),
))(input)
}
pub(crate) fn protocol(input: &[u8]) -> IResult<&[u8], IPProtocol> {
let (input, protocol) = numbe... | {
match raw {
0 => IPProtocol::HOPOPT,
1 => IPProtocol::ICMP,
2 => IPProtocol::IGMP,
3 => IPProtocol::GGP,
4 => IPProtocol::IPINIP,
5 => IPProtocol::ST,
6 => IPProtocol::TCP,
7 => IPProtocol::CBT,
8 => IP... | identifier_body |
ip.rs | //! Handles parsing of Internet Protocol fields (shared between ipv4 and ipv6)
use nom::bits;
use nom::error::Error;
use nom::number;
use nom::sequence;
use nom::IResult;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum IPProtocol {
... | other => IPProtocol::Other(other),
}
}
}
pub(crate) fn two_nibbles(input: &[u8]) -> IResult<&[u8], (u8, u8)> {
bits::bits::<_, _, Error<_>, _, _>(sequence::pair(
bits::streaming::take(4u8),
bits::streaming::take(4u8),
))(input)
}
pub(crate) fn protocol(input: &[u8]) -> ... | 16 => IPProtocol::CHAOS,
17 => IPProtocol::UDP,
41 => IPProtocol::IPV6,
58 => IPProtocol::ICMP6, | random_line_split |
ip.rs | //! Handles parsing of Internet Protocol fields (shared between ipv4 and ipv6)
use nom::bits;
use nom::error::Error;
use nom::number;
use nom::sequence;
use nom::IResult;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum | {
HOPOPT,
ICMP,
IGMP,
GGP,
IPINIP,
ST,
TCP,
CBT,
EGP,
IGP,
BBNRCCMON,
NVPII,
PUP,
ARGUS,
EMCON,
XNET,
CHAOS,
UDP,
IPV6,
ICMP6,
Other(u8),
}
impl From<u8> for IPProtocol {
fn from(raw: u8) -> Self {
match raw {
... | IPProtocol | identifier_name |
aboutController.spec.js | define(['lodash'], function (_) {
'use strict';
describe('Controller.About', function () {
beforeEach(angular.mock.module('app.controllers'));
describe('When Initialising', function () {
var scope, versionService;
beforeEach(angular.mock.inject(function ($q) {
... | scope = $rootScope.$new();
$controller('aboutController as about', { $scope: scope, versionService: versionService });
}));
it('should set current app version', angular.mock.inject(function () {
expect(scope.about.appVersion).toBe('111');
... | beforeEach(angular.mock.inject(function ($controller, $rootScope) { | random_line_split |
component.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// We are temporarily importing the existing viewEngine from core so we can be sure we are
// correctly implementing... |
/**
* Creates the root component view and the root component node.
*
* @param rNode Render host element.
* @param def ComponentDef
* @param rootView The parent view where the host node is stored
* @param renderer The current renderer
* @param sanitizer The sanitizer, if provided
*
* @returns Component view c... | {
NG_DEV_MODE && publishDefaultGlobalUtils();
NG_DEV_MODE && assertComponentType(componentType);
const rendererFactory = opts.rendererFactory || domRendererFactory3;
const sanitizer = opts.sanitizer || null;
const componentDef = getComponentDef<T>(componentType) !;
if (componentDef.type != componentType) c... | identifier_body |
component.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// We are temporarily importing the existing viewEngine from core so we can be sure we are
// correctly implementing... |
/** Options that control how the component should be bootstrapped. */
export interface CreateComponentOptions {
/** Which renderer factory to use. */
rendererFactory?: RendererFactory3;
/** A custom sanitizer instance */
sanitizer?: Sanitizer;
/** A custom animation player handler */
playerHandler?: Pla... | import {getRootContext} from './util/view_traversal_utils';
import {readPatchedLView} from './util/view_utils';
| random_line_split |
component.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// We are temporarily importing the existing viewEngine from core so we can be sure we are
// correctly implementing... | <T>(
componentType: ComponentType<T>|
Type<T>/* Type as workaround for: Microsoft/TypeScript/issues/4881 */
,
opts: CreateComponentOptions = {}): T {
NG_DEV_MODE && publishDefaultGlobalUtils();
NG_DEV_MODE && assertComponentType(componentType);
const rendererFactory = opts.rendererFactory || ... | renderComponent | identifier_name |
component.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// We are temporarily importing the existing viewEngine from core so we can be sure we are
// correctly implementing... |
const rootTNode = getPreviousOrParentTNode();
if (tView.firstCreatePass && componentDef.hostBindings) {
const elementIndex = rootTNode.index - HEADER_OFFSET;
setActiveHostElement(elementIndex);
incrementActiveDirectiveId();
const expando = tView.expandoInstructions !;
invokeHostBindingsInCrea... | {
componentDef.contentQueries(RenderFlags.Create, component, rootView.length - 1);
} | conditional_block |
docserver.py | from __future__ import print_function
import flask
import os
import threading
import time
import webbrowser
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
_basedir = os.path.join("..", os.path.dirname(__file__))
app = flask.Flask(__name__, static... | print("Asked Server to shut down.")
def ui():
time.sleep(0.5)
input("Press <ENTER> to exit...\n")
if __name__ == "__main__":
print("\nStarting Bokeh plot server on port %d..." % PORT)
print("Visit http://localhost:%d/en/latest/index.html to see plots\n" % PORT)
t_server = threading.Thread(t... | random_line_split | |
docserver.py | from __future__ import print_function
import flask
import os
import threading
import time
import webbrowser
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
_basedir = os.path.join("..", os.path.dirname(__file__))
app = flask.Flask(__name__, static... | ():
time.sleep(0.5)
input("Press <ENTER> to exit...\n")
if __name__ == "__main__":
print("\nStarting Bokeh plot server on port %d..." % PORT)
print("Visit http://localhost:%d/en/latest/index.html to see plots\n" % PORT)
t_server = threading.Thread(target=serve_http)
t_server.start()
t_br... | ui | identifier_name |
docserver.py | from __future__ import print_function
import flask
import os
import threading
import time
import webbrowser
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
_basedir = os.path.join("..", os.path.dirname(__file__))
app = flask.Flask(__name__, static... |
@app.route('/en/latest/<path:filename>')
def send_pic(filename):
return flask.send_from_directory(
os.path.join(_basedir,"sphinx/_build/html/"), filename)
def open_browser():
# Child process
time.sleep(0.5)
webbrowser.open("http://localhost:%d/en/latest/index.html" % PORT, new="tab")
def se... | return """
<h1>Welcome to the Bokeh documentation server</h1>
You probably want to go to <a href="/en/latest/index.html"> Index</a>
""" | identifier_body |
docserver.py | from __future__ import print_function
import flask
import os
import threading
import time
import webbrowser
from tornado.wsgi import WSGIContainer
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
_basedir = os.path.join("..", os.path.dirname(__file__))
app = flask.Flask(__name__, static... | print("\nStarting Bokeh plot server on port %d..." % PORT)
print("Visit http://localhost:%d/en/latest/index.html to see plots\n" % PORT)
t_server = threading.Thread(target=serve_http)
t_server.start()
t_browser = threading.Thread(target=open_browser)
t_browser.start()
ui()
shutdown_server... | conditional_block | |
utils.py | from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import object
from cgi import escape
from io import BytesIO as IO
import functools
import gzip
import dateutil.parser as dateparser
import json
import os
from flask import after_this_request, request, Response
... | (f):
'''
Decorator to notify owner of actions taken on their DAGs by others
'''
@functools.wraps(f)
def wrapper(*args, **kwargs):
if request.args.get('confirmed') == "true":
dag_id = request.args.get('dag_id')
task_id = request.args.get('task_id')
dag = da... | notify_owner | identifier_name |
utils.py | from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import object
from cgi import escape
from io import BytesIO as IO
import functools
import gzip
import dateutil.parser as dateparser
import json
import os
from flask import after_this_request, request, Response
... |
gzip_buffer = IO()
gzip_file = gzip.GzipFile(mode='wb',
fileobj=gzip_buffer)
gzip_file.write(response.data)
gzip_file.close()
response.data = gzip_buffer.getvalue()
response.headers['Content-Encoding'] = 'gzi... | return response | conditional_block |
utils.py | from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import object
from cgi import escape
from io import BytesIO as IO
import functools
import gzip
import dateutil.parser as dateparser
import json
import os
from flask import after_this_request, request, Response
... | if 'execution_date' in request.args:
log.execution_date = dateparser.parse(
request.args.get('execution_date'))
session.add(log)
session.commit()
return f(*args, **kwargs)
return wrapper
def notify_owner(f):
'''
Decorator to notify owner of ac... | random_line_split | |
utils.py | from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import object
from cgi import escape
from io import BytesIO as IO
import functools
import gzip
import dateutil.parser as dateparser
import json
import os
from flask import after_this_request, request, Response
... | kwargs.setdefault('id', field.id)
html = '''
<div id="{el_id}" style="height:100px;">{contents}</div>
<textarea
id="{el_id}_ace" name="{form_name}"
style="display:none;visibility:hidden;">
</textarea>
'''.format(
el_id=kwargs.get('id', field.id... | identifier_body | |
quantile-generator.py | #!/usr/bin/env python3
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import argparse
import itertools
import sys
from benchexec import... |
return extract_value
def main(args=None):
if args is None:
args = sys.argv
parser = argparse.ArgumentParser(
fromfile_prefix_chars="@",
description="""Create CSV tables for quantile plots with the results of a benchmark execution.
The CSV tables are similar to those p... | pos = None
for i, column in enumerate(run_result.columns):
if column.title == column_identifier:
pos = i
break
if pos is None:
sys.exit(f"CPU time missing for task {run_result.task_id}.")
return util.to_decimal(run_result.values[pos]) | identifier_body |
quantile-generator.py | #!/usr/bin/env python3
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import argparse
import itertools
import sys
from benchexec import... |
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
sys.exit("Script was interrupted by user.") | task_id for task_id, show in zip(run_result.id, relevant_id_columns) if show
)
result_values = (util.remove_unit(value or "") for value in run_result.values)
print(*itertools.chain([index], task_ids, result_values), sep="\t")
| random_line_split |
quantile-generator.py | #!/usr/bin/env python3
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import argparse
import itertools
import sys
from benchexec import... | (run_result):
pos = None
for i, column in enumerate(run_result.columns):
if column.title == column_identifier:
pos = i
break
if pos is None:
sys.exit(f"CPU time missing for task {run_result.task_id}.")
return util.to_decimal(run_res... | extract_value | identifier_name |
quantile-generator.py | #!/usr/bin/env python3
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import argparse
import itertools
import sys
from benchexec import... |
parser = argparse.ArgumentParser(
fromfile_prefix_chars="@",
description="""Create CSV tables for quantile plots with the results of a benchmark execution.
The CSV tables are similar to those produced with table-generator,
but have an additional first column with the index fo... | args = sys.argv | conditional_block |
Table.d.ts | /// <reference types="react" />
import React from 'react';
import { PaginationProps } from '../pagination';
import { Store } from './createStore';
import Column, { ColumnProps } from './Column';
import ColumnGroup from './ColumnGroup';
export interface TableRowSelection<T> {
type?: 'checkbox' | 'radio';
selecte... | <T> extends React.Component<TableProps<T>, any> {
static Column: typeof Column;
static ColumnGroup: typeof ColumnGroup;
static propTypes: {
dataSource: React.Requireable<any>;
columns: React.Requireable<any>;
prefixCls: React.Requireable<any>;
useFixedHeader: React.Requireabl... | Table | identifier_name |
Table.d.ts | /// <reference types="react" />
import React from 'react';
import { PaginationProps } from '../pagination';
import { Store } from './createStore';
import Column, { ColumnProps } from './Column';
import ColumnGroup from './ColumnGroup';
export interface TableRowSelection<T> {
type?: 'checkbox' | 'radio';
selecte... | sortOrder: any;
};
getSorterFn(): ((a: any, b: any) => any) | undefined;
toggleSortOrder(order: any, column: any): void;
handleFilter: (column: any, nextFilters: any) => void;
handleSelect: (record: any, rowIndex: any, e: any) => void;
handleRadioSelect: (record: any, rowIndex: any, e: a... | getFiltersFromColumns(columns?: any): {};
getSortStateFromColumns(columns?: any): {
sortColumn: any; | random_line_split |
action_mask_model.py | from gym.spaces import Dict
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC
from ray.rllib.utils.framework import try_... | (self, input_dict, state, seq_lens):
# Extract the available actions tensor from the observation.
action_mask = input_dict["obs"]["action_mask"]
# Compute the unmasked logits.
logits, _ = self.internal_model({"obs": input_dict["obs"]["observations"]})
# If action masking is dis... | forward | identifier_name |
action_mask_model.py | from gym.spaces import Dict
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC
from ray.rllib.utils.framework import try_... | return self.internal_model.value_function() | identifier_body | |
action_mask_model.py | from gym.spaces import Dict
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC
from ray.rllib.utils.framework import try_... |
# Convert action_mask into a [0.0 || -inf]-type mask.
inf_mask = tf.maximum(tf.math.log(action_mask), tf.float32.min)
masked_logits = logits + inf_mask
# Return masked logits.
return masked_logits, state
def value_function(self):
return self.internal_model.value_f... | return logits, state | conditional_block |
action_mask_model.py | from gym.spaces import Dict
from ray.rllib.models.tf.fcnet import FullyConnectedNetwork
from ray.rllib.models.tf.tf_modelv2 import TFModelV2
from ray.rllib.models.torch.torch_modelv2 import TorchModelV2
from ray.rllib.models.torch.fcnet import FullyConnectedNetwork as TorchFC
from ray.rllib.utils.framework import try_... | self.no_masking = model_config["custom_model_config"]["no_masking"]
def forward(self, input_dict, state, seq_lens):
# Extract the available actions tensor from the observation.
action_mask = input_dict["obs"]["action_mask"]
# Compute the unmasked logits.
logits, _ = sel... | if "no_masking" in model_config["custom_model_config"]: | random_line_split |
dynamic-material-select.component.ts | import { Component, EventEmitter, Inject, Input, Optional, Output, ViewChild } from "@angular/core";
import { FormGroup } from "@angular/forms";
import { ErrorStateMatcher, MAT_RIPPLE_GLOBAL_OPTIONS, RippleGlobalOptions } from "@angular/material/core";
import { MAT_FORM_FIELD_DEFAULT_OPTIONS, MatFormFieldDefaultOptions... | extends DynamicFormControlComponent {
@Input() formLayout?: DynamicFormLayout;
@Input() group!: FormGroup;
@Input() layout?: DynamicFormControlLayout;
@Input() model!: DynamicSelectModel<string>;
@Output() blur: EventEmitter<any> = new EventEmitter();
@Output() change: EventEmitter<any> = new ... | DynamicMaterialSelectComponent | identifier_name |
dynamic-material-select.component.ts | import { Component, EventEmitter, Inject, Input, Optional, Output, ViewChild } from "@angular/core";
import { FormGroup } from "@angular/forms";
import { ErrorStateMatcher, MAT_RIPPLE_GLOBAL_OPTIONS, RippleGlobalOptions } from "@angular/material/core";
import { MAT_FORM_FIELD_DEFAULT_OPTIONS, MatFormFieldDefaultOptions... | }
} | random_line_split | |
d1_sbl_recon.py | import re
import sqlite3
import csv
import ast
import os
import sys
import fnmatch
import datetime
import xlrd
import win32com.client
def question_marks(st):
question_marks = '?'
for i in range(0, len(st.split(','))-1):
question_marks = question_marks + ",?"
return question_marks
def xlsx_to_arr(xlsx_file, works... | ():
conn, cur = db_cur()
pb_dir = os.path.dirname(os.path.abspath(__file__))
# pb_dir = "\\\\p7fs0003\\nd\\3033-Horizon-FA-Share\\PB_DeltaOne\\Daily_Data"
sbl_dir = os.path.dirname(os.path.abspath(__file__))
# sbl_dir = "\\\\P7FS0001\\ED\\SBL\\Reports\\Daily SBL Report\\ReportData"
output_dir = "\\\\p7fs0003\\... | main | identifier_name |
d1_sbl_recon.py | import re
import sqlite3
import csv
import ast
import os
import sys
import fnmatch
import datetime
import xlrd
import win32com.client
def question_marks(st):
question_marks = '?'
for i in range(0, len(st.split(','))-1):
question_marks = question_marks + ",?"
return question_marks
def xlsx_to_arr(xlsx_file, works... |
wr.writerow(line)
csv_file.close()
return
def arrs_to_xlsx(filename, header=[], arr=[]):
i = 1
xl = win32com.client.Dispatch('Excel.Application')
wb = xl.Workbooks.Add()
for x in range(0, len(header)):
ws = wb.Worksheets(x+1)
for i, cell in enumerate(header[x].split(',')):
ws.Cells(1,i+1).Value = ... | line.append(str(ele)) | conditional_block |
d1_sbl_recon.py | import re
import sqlite3
import csv
import ast
import os
import sys
import fnmatch
import datetime
import xlrd
import win32com.client
def question_marks(st):
question_marks = '?'
for i in range(0, len(st.split(','))-1):
question_marks = question_marks + ",?"
return question_marks
def xlsx_to_arr(xlsx_file, works... |
def create_tbl(cur, tbl_name, header, arr = [], index_arr = []):
cur.execute("""select count(*) FROM sqlite_master WHERE type='table' AND name = '%s' """ % (tbl_name))
tbl_exists = cur.fetchone()
if tbl_exists[0] == 0:
cur.execute("CREATE TABLE " + tbl_name + " (" + header.replace("id,", "id PRIMARY KEY,") + " ... | conn = sqlite3.connect(source, detect_types=sqlite3.PARSE_DECLTYPES)
# conn.row_factory = sqlite3.Row
cur = conn.cursor()
return conn, cur | identifier_body |
d1_sbl_recon.py | import re
import sqlite3
import csv
import ast
import os
import sys
import fnmatch
import datetime
import xlrd
import win32com.client
def question_marks(st):
question_marks = '?'
for i in range(0, len(st.split(','))-1):
question_marks = question_marks + ",?"
return question_marks
def xlsx_to_arr(xlsx_file, works... | arrs_to_xlsx(inv_file, [sbl_header], [sbl_arr])
return
if __name__ == "__main__":
print ("D1 G1 SBL Recon")
try:
main()
except KeyboardInterrupt:
print ("Ctrl+C pressed. Stopping...") | random_line_split | |
filter.ts | import {
Selector,
TypeOrArray,
isFunction,
isString,
} from '@mdui/shared/helpers.js';
import $ from '../$.js';
import { JQ } from '../shared/core.js';
import './is.js';
import './map.js';
declare module '../shared/core.js' {
interface JQ<T = HTMLElement> {
/**
* 从当前对象中筛选出与指定表达式匹配的元素
* @param ... |
});
};
| conditional_block | |
filter.ts | import {
Selector,
TypeOrArray,
isFunction,
isString, |
declare module '../shared/core.js' {
interface JQ<T = HTMLElement> {
/**
* 从当前对象中筛选出与指定表达式匹配的元素
* @param selector
* 可以是 CSS 表达式、DOM 元素、DOM 元素数组、或回调函数
*
* 回调函数的第一个参数为元素的索引位置,第二个参数为当前元素,`this` 指向当前元素
*
* 回调函数返回 `true` 时,对应元素会被保留;返回 `false` 时,对应元素会被移除
* @example
```js
// 筛选出所... | } from '@mdui/shared/helpers.js';
import $ from '../$.js';
import { JQ } from '../shared/core.js';
import './is.js';
import './map.js'; | random_line_split |
fdt_test.py | # SPDX-License-Identifier: GPL-2.0+
# Copyright (c) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
# Test for the fdt modules
import os
import sys
import tempfile
import unittest
from dtoc import fdt
from dtoc import fdt_util
from dtoc.fdt import FdtScan
from patman import tools
class TestFdt(unittes... | def testFdtNormalProp(self):
fname = self.GetCompiled('045_prop_test.dts')
dt = FdtScan(fname)
node = dt.GetNode('/binman/intel-me')
self.assertEquals('intel-me', node.name)
val = fdt_util.GetString(node, 'filename')
self.assertEquals(str, type(val))
self.asse... | self._DeleteProp(dt)
| random_line_split |
fdt_test.py | # SPDX-License-Identifier: GPL-2.0+
# Copyright (c) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
# Test for the fdt modules
import os
import sys
import tempfile
import unittest
from dtoc import fdt
from dtoc import fdt_util
from dtoc.fdt import FdtScan
from patman import tools
class TestFdt(unittes... | (self, fname):
return fdt_util.EnsureCompiled(self.TestFile(fname))
def _DeleteProp(self, dt):
node = dt.GetNode('/microcode/update@0')
node.DeleteProp('data')
def testFdtNormal(self):
fname = self.GetCompiled('034_x86_ucode.dts')
dt = FdtScan(fname)
self._Delet... | GetCompiled | identifier_name |
fdt_test.py | # SPDX-License-Identifier: GPL-2.0+
# Copyright (c) 2016 Google, Inc
# Written by Simon Glass <sjg@chromium.org>
#
# Test for the fdt modules
import os
import sys
import tempfile
import unittest
from dtoc import fdt
from dtoc import fdt_util
from dtoc.fdt import FdtScan
from patman import tools
class TestFdt(unittes... |
@classmethod
def tearDownClass(self):
tools._FinaliseForTest()
def TestFile(self, fname):
return os.path.join(self._binman_dir, 'test', fname)
def GetCompiled(self, fname):
return fdt_util.EnsureCompiled(self.TestFile(fname))
def _DeleteProp(self, dt):
node = dt.... | self._binman_dir = os.path.dirname(os.path.realpath(sys.argv[0]))
self._indir = tempfile.mkdtemp(prefix='binmant.')
tools.PrepareOutputDir(self._indir, True) | identifier_body |
TimelineRecording.js | /*
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions a... |
addInstrument(instrument)
{
console.assert(instrument instanceof WebInspector.Instrument, instrument);
console.assert(!this._instruments.contains(instrument), this._instruments, instrument);
this._instruments.push(instrument);
this.dispatchEventToListeners(WebInspector.Timeli... | {
return this._timelines.get(recordType);
} | identifier_body |
TimelineRecording.js | /*
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions a... | this._startTime = timestamp;
this._endTime = timestamp;
this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.TimesUpdated);
}
}
// Private
_keyForRecord(record)
{
var key = record.type;
if (record instanceof WebInspector.Script... | random_line_split | |
TimelineRecording.js | /*
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions a... | ()
{
return this._endTime;
}
start()
{
console.assert(!this._capturing, "Attempted to start an already started session.");
console.assert(!this._readonly, "Attempted to start a readonly session.");
this._capturing = true;
for (let instrument of this._instrument... | endTime | identifier_name |
glb.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 ... |
fn regions(&mut self, a: ty::Region, b: ty::Region) -> RelateResult<'tcx, ty::Region> {
debug!("{}.regions({}, {})",
self.tag(),
a.repr(self.fields.infcx.tcx),
b.repr(self.fields.infcx.tcx));
let origin = Subtype(self.fields.trace.clone());
Ok(... | {
lattice::super_lattice_tys(self, a, b)
} | identifier_body |
glb.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 | use super::combine::CombineFields;
use super::higher_ranked::HigherRankedRelations;
use super::InferCtxt;
use super::lattice::{self, LatticeDir};
use super::Subtype;
use middle::ty::{self, Ty};
use middle::ty_relate::{Relate, RelateResult, TypeRelation};
use util::ppaux::Repr;
/// "Greatest lower bound" (common subty... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
glb.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 ... | (fields: CombineFields<'a, 'tcx>) -> Glb<'a, 'tcx> {
Glb { fields: fields }
}
}
impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Glb<'a, 'tcx> {
fn tag(&self) -> &'static str { "Glb" }
fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.fields.tcx() }
fn a_is_expected(&self) -> bool { self.fields.a_is_expect... | new | identifier_name |
client.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Typescript async/await rewrite of smc-util/client.coffee...
*/
import { webapp_client } from "../../webapp-client";
const schema = require("smc-util/schema");
const DEFAULT... | oject_id: string): Promise<void> {
try {
await webapp_client.project_client.touch(project_id);
} catch (err) {
console.warn(`unable to touch '${project_id}' -- ${err}`);
}
}
export async function start_project(
project_id: string,
timeout: number = 60
): Promise<void> {
const store = redux.getStore... | ch_project(pr | identifier_name |
client.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Typescript async/await rewrite of smc-util/client.coffee...
*/
import { webapp_client } from "../../webapp-client";
const schema = require("smc-util/schema");
const DEFAULT... | nterface QueryOpts {
query: object;
changes?: boolean;
options?: object[]; // e.g., [{limit:5}],
no_post?: boolean;
}
export async function query(opts: QueryOpts): Promise<any> {
return await webapp_client.query_client.query(opts);
}
export function get_default_font_size(): number {
const account: any = r... | if (opts.primary_keys.length <= 0) {
throw Error("primary_keys must be array of positive length");
}
const opts1: any = opts;
opts1.client = webapp_client;
return new SyncDB(opts1);
}
i | identifier_body |
client.ts | /*
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
* License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details
*/
/*
Typescript async/await rewrite of smc-util/client.coffee...
*/
import { webapp_client } from "../../webapp-client";
const schema = require("smc-util/schema");
const DEFAULT... | );
} else if (resp.error) {
throw Error(resp.error);
} else {
throw Error("Syntax error prevented formatting code.");
}
} else {
return resp.patch;
}
}
export function log_error(error: string | object): void {
webapp_client.tracking_client.log_error(error);
}
interface Syncstri... | `Syntax error prevented formatting code (possibly on line ${loc.start.line} column ${loc.start.column}) -- fix and run again.` | random_line_split |
top-track-tile.component.ts | import {
Component,
Input,
trigger,
state,
style,
transition,
animate,
OnInit,
OnDestroy
} from '@angular/core';
import { ChangeDetectionStrategy } from '@angular/core'
import { Store } from '@ngrx/store';
import { Action } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { Sub... | () {
this.isPlayingSubscription.unsubscribe();
this.favoritesSubscription.unsubscribe();
}
clickHandler() {
if (!this.playing) {
this.loadingNow();
}
this.store$.dispatch(this.trackActions.togglePlayPause(this.topTrack, this.tracksList));
}
goToDetail($event) {
// Only go to deta... | ngOnDestroy | identifier_name |
top-track-tile.component.ts | import {
Component,
Input,
trigger,
state,
style,
transition,
animate,
OnInit,
OnDestroy
} from '@angular/core';
import { ChangeDetectionStrategy } from '@angular/core'
import { Store } from '@ngrx/store';
import { Action } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { Sub... |
this.isFavorited = !this.isFavorited;
if (this.isFavorited) {
this.store$.dispatch(this.favoriteActions.addFavorite(this.topTrack));
this.showFavoritedMessage = true;
setTimeout(() => { this.showFavoritedMessage = false; }, 1000);
} else {
this.store$.dispatch(this.favoriteActions.r... | {
this.showLoginMessage = true;
setTimeout(() => { this.showLoginMessage = false; }, 1000);
return;
} | conditional_block |
top-track-tile.component.ts | import {
Component,
Input,
trigger,
state,
style,
transition,
animate,
OnInit,
OnDestroy
} from '@angular/core';
import { ChangeDetectionStrategy } from '@angular/core'
import { Store } from '@ngrx/store';
import { Action } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { Sub... |
clickHandler() {
if (!this.playing) {
this.loadingNow();
}
this.store$.dispatch(this.trackActions.togglePlayPause(this.topTrack, this.tracksList));
}
goToDetail($event) {
// Only go to detail page if we clicked outside of the play icon
if ($event.target.tagName !== 'I') {
this.r... | {
this.isPlayingSubscription.unsubscribe();
this.favoritesSubscription.unsubscribe();
} | identifier_body |
top-track-tile.component.ts | import {
Component,
Input,
trigger,
state,
style,
transition,
animate,
OnInit,
OnDestroy
} from '@angular/core';
import { ChangeDetectionStrategy } from '@angular/core'
import { Store } from '@ngrx/store';
import { Action } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { Sub... | ]),
trigger('fadeInOutFast', [
state('in', style({opacity: 1})),
transition('void => *', [
style({
opacity: 0,
}),
animate('0.02s ease-in')
]),
transition('* => void', [
animate('0.02s 10 ease-out', style({
opacity: 0,
}))
... | random_line_split | |
AssessmentRounded.js | import createSvgIcon from './utils/createSvgIcon'; | export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM8 17c-.55 0-1-.45-1-1v-5c0-.55.45-1 1-1s1 .45 1 1v5c0 .55-.45 1-1 1zm4 0c-.55 0-1-.45-1-1V8c0-.55.45-1 1-1s1 .45 1 1v8c0 .55-.45 1-1 1zm4 0c-.55 0-1-.45-1-1v-2c0-.55.45-1 1-1s1 .4... | import { jsx as _jsx } from "react/jsx-runtime"; | random_line_split |
PizzaShopMap.js | Ext.define('PF.view.PizzaShopMap', {
extend:'PF.view.EsriMap',
xtype:'pizzashopmap',
config:{
// Override some config which the base EsriMap will use...
basemapLayer:"http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",
mapHeight:"140px",
// And provide a bit of our own.
... | {
map.centerAndZoom(pizzaShop.geometry, 17);
}
}
}
}); | if (pizzaShop) | random_line_split |
PizzaShopMap.js | Ext.define('PF.view.PizzaShopMap', {
extend:'PF.view.EsriMap',
xtype:'pizzashopmap',
config:{
// Override some config which the base EsriMap will use...
basemapLayer:"http://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer",
mapHeight:"140px",
// And provide a bit of our own.
... |
}
}); | {
var pizzaShop = this.getPizzaShop();
if (pizzaShop)
{
map.centerAndZoom(pizzaShop.geometry, 17);
}
} | conditional_block |
TableCell.tsx | import {
forwardRef,
ReactNode,
TdHTMLAttributes,
ThHTMLAttributes,
} from "react";
import cn from "classnames";
import { useIcon } from "@react-md/icon";
import { bem } from "@react-md/utils";
import { TableCellConfig, useTableConfig } from "./config";
import { useTableFooter } from "./footer";
import { useSt... | (
block({
grow,
header,
sticky,
"sticky-header":
(header && sticky && propSticky !== "cell") ||
isStickyHeader ||
isStickyAbove,
"sticky-cell": isStickyCell || isStickyAbove || isStickyFooterCell,
... | cn | identifier_name |
TableCell.tsx | import {
forwardRef,
ReactNode,
TdHTMLAttributes,
ThHTMLAttributes,
} from "react";
import cn from "classnames";
import { useIcon } from "@react-md/icon";
import { bem } from "@react-md/utils";
import { TableCellConfig, useTableConfig } from "./config";
import { useTableFooter } from "./footer";
import { useSt... | * should change as well which will cause the sort icon to rotate. The default
* behavior is to have the icon facing upwards and not-rotated when
* `"ascending"`, otherwise it will rotate downwards when `"descending"`.
*
* If this prop is set to `"none"`, the cell will render the clickable button
* in ... | export interface TableCellProps extends TableCellAttributes, TableCellOptions {
/**
* If you want to apply a sort icon for a header cell, set this prop to either
* `"ascending"` or `"descending"`. When you change the sort order, this prop | random_line_split |
TableCell.tsx | import {
forwardRef,
ReactNode,
TdHTMLAttributes,
ThHTMLAttributes,
} from "react";
import cn from "classnames";
import { useIcon } from "@react-md/icon";
import { bem } from "@react-md/utils";
import { TableCellConfig, useTableConfig } from "./config";
import { useTableFooter } from "./footer";
import { useSt... |
>
<TableCellContent
id={id ? `${id}-sort` : undefined}
icon={sortIcon}
iconAfter={sortIconAfter}
sortOrder={sortOrder}
rotated={sortIconRotated}
hAlign={hAlign}
>
{children}
</TableCellContent>
</Component>
);... | {scope} | identifier_body |
TableCell.tsx | import {
forwardRef,
ReactNode,
TdHTMLAttributes,
ThHTMLAttributes,
} from "react";
import cn from "classnames";
import { useIcon } from "@react-md/icon";
import { bem } from "@react-md/utils";
import { TableCellConfig, useTableConfig } from "./config";
import { useTableFooter } from "./footer";
import { useSt... |
const Component = header ? "th" : "td";
return (
<Component
{...props}
ref={ref}
id={id}
aria-sort={sortOrder === "none" ? undefined : sortOrder}
colSpan={colSpan}
className={cn(
block({
grow,
header,
sticky,
... | {
scope = !inheritedHeader && propHeader ? "row" : "col";
} | conditional_block |
S15.4.4.7_A4_T2.js | // Copyright 2009 the Sputnik authors. All rights reserved.
/**
* Check ToUint32(length) for non Array objects
*
* @path ch15/15.4/15.4.4/15.4.4.7/S15.4.4.7_A4_T2.js
* @description length = 4294967295
*/
var obj = {};
obj.push = Array.prototype.push;
obj.length = 4294967295;
//CHECK#1
var push = obj.push("x", "... |
//CHECK#5
if (obj[4294967297] !== "z") {
$ERROR('#5: var obj = {}; obj.push = Array.prototype.push; obj.length = 4294967295; obj.push("x", "y", "z"); obj[4294967297] === "z". Actual: ' + (obj[4294967297]));
}
| {
$ERROR('#4: var obj = {}; obj.push = Array.prototype.push; obj.length = 4294967295; obj.push("x", "y", "z"); obj[4294967296] === "y". Actual: ' + (obj[4294967296]));
} | conditional_block |
S15.4.4.7_A4_T2.js | // Copyright 2009 the Sputnik authors. All rights reserved.
/** | *
* @path ch15/15.4/15.4.4/15.4.4.7/S15.4.4.7_A4_T2.js
* @description length = 4294967295
*/
var obj = {};
obj.push = Array.prototype.push;
obj.length = 4294967295;
//CHECK#1
var push = obj.push("x", "y", "z");
if (push !== 4294967298) {
$ERROR('#1: var obj = {}; obj.push = Array.prototype.push; obj.length = 42... | * Check ToUint32(length) for non Array objects | random_line_split |
level2_menu.js | var level2_menu = {
preload: function() {
},
create: function() {
game.input.onTap.add(this.start, this);
var style = { font: "30px Arial", fill: "#ffffff" };
// Adding a text centered on the screen
var text = this.game.add.text(game.world.centerX, game.world.centerY - ... | text1.anchor.setTo(0.5, 0.5);
var text2 = this.game.add.text(game.world.centerX, game.world.centerY + 50, "Badass..", style);
text2.anchor.setTo(0.5, 0.5);
},
start: function() {
this.game.state.start('level2');
}
}; | text.anchor.setTo(0.5, 0.5);
var text1 = this.game.add.text(game.world.centerX, game.world.centerY - 20, "approaches a room...", style); | random_line_split |
contactDetails.ts | /* Allow chai assertions which don't end in a function call, e.g. expect(thing).to.be.undefined */
/* tslint:disable:no-unused-expression */
import { expect } from 'chai' | import { ContactDetails } from 'claims/models/contactDetails'
describe('ContactDetails', () => {
describe('constructor', () => {
it('should set primitive type fields to undefined', () => {
let contactDetails = new ContactDetails()
expect(contactDetails.dxAddress).to.be.undefined
expect(contactD... | random_line_split | |
api.py | # -*- coding: utf-8 -*- pylint: disable-msg=R0801
#
# Copyright (c) 2013 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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 ver... | class Meta:
queryset = Journey.objects.all()
resource_name = 'journey'
throttle = BaseThrottle(throttle_at=100, timeframe=60)
class ConnectionResource(ModelResource):
"""
The connections
"""
station_from = fields.ForeignKey(StationResource, 'station_from')
station_to = ... | The journeys
"""
station_from = fields.ForeignKey(StationResource, 'station_from')
station_to = fields.ForeignKey(StationResource, 'station_to')
| random_line_split |
api.py | # -*- coding: utf-8 -*- pylint: disable-msg=R0801
#
# Copyright (c) 2013 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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 ver... |
class ConnectionResource(ModelResource):
"""
The connections
"""
station_from = fields.ForeignKey(StationResource, 'station_from')
station_to = fields.ForeignKey(StationResource, 'station_to')
class Meta:
queryset = Connection.objects.all()
resource_name = 'connection'
... | ""
The journeys
"""
station_from = fields.ForeignKey(StationResource, 'station_from')
station_to = fields.ForeignKey(StationResource, 'station_to')
class Meta:
queryset = Journey.objects.all()
resource_name = 'journey'
throttle = BaseThrottle(throttle_at=100, timeframe=60)
| identifier_body |
api.py | # -*- coding: utf-8 -*- pylint: disable-msg=R0801
#
# Copyright (c) 2013 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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 ver... |
queryset = Connection.objects.all()
resource_name = 'connection'
throttle = BaseThrottle(throttle_at=100, timeframe=60)
| eta: | identifier_name |
text.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/. */
//! Generic types for text properties.
use app_units::Au;
use cssparser::Parser;
use parser::ParserContext;
use p... | /// `<value>`
Value(Value),
}
impl<Value> Spacing<Value> {
/// Returns `normal`.
#[inline]
pub fn normal() -> Self {
Spacing::Normal
}
/// Parses.
#[inline]
pub fn parse_with<'i, 't, F>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
parse: F)
... | /// `normal`
Normal, | random_line_split |
text.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/. */
//! Generic types for text properties.
use app_units::Au;
use cssparser::Parser;
use parser::ParserContext;
use p... | <Value> {
/// `normal`
Normal,
/// `<value>`
Value(Value),
}
impl<Value> Spacing<Value> {
/// Returns `normal`.
#[inline]
pub fn normal() -> Self {
Spacing::Normal
}
/// Parses.
#[inline]
pub fn parse_with<'i, 't, F>(
context: &ParserContext,
input: ... | Spacing | identifier_name |
proctored_exam.py | """
Proctored Exams Transformer
"""
from django.conf import settings
from edx_proctoring.api import get_attempt_status_summary
from edx_proctoring.models import ProctoredExamStudentAttemptStatus
from openedx.core.lib.block_structure.transformer import BlockStructureTransformer, FilteringTransformerMixin
class Proct... |
return [block_structure.create_removal_filter(is_proctored_exam_for_user)]
| """
Test whether the block is a proctored exam for the user in
question.
"""
if (
block_key.block_type == 'sequential' and (
block_structure.get_xblock_field(block_key, 'is_proctored_enabled') or
block_st... | identifier_body |
proctored_exam.py | """
Proctored Exams Transformer
"""
from django.conf import settings
from edx_proctoring.api import get_attempt_status_summary
from edx_proctoring.models import ProctoredExamStudentAttemptStatus
from openedx.core.lib.block_structure.transformer import BlockStructureTransformer, FilteringTransformerMixin
class Proct... | """
Computes any information for each XBlock that's necessary to execute
this transformer's transform method.
Arguments:
block_structure (BlockStructureCollectedData)
"""
block_structure.request_xblock_fields('is_proctored_enabled')
block_structure.re... |
@classmethod
def collect(cls, block_structure): | random_line_split |
proctored_exam.py | """
Proctored Exams Transformer
"""
from django.conf import settings
from edx_proctoring.api import get_attempt_status_summary
from edx_proctoring.models import ProctoredExamStudentAttemptStatus
from openedx.core.lib.block_structure.transformer import BlockStructureTransformer, FilteringTransformerMixin
class | (FilteringTransformerMixin, BlockStructureTransformer):
"""
Exclude proctored exams unless the user is not a verified student or has
declined taking the exam.
"""
VERSION = 1
BLOCK_HAS_PROCTORED_EXAM = 'has_proctored_exam'
@classmethod
def name(cls):
return "proctored_exam"
... | ProctoredExamTransformer | identifier_name |
proctored_exam.py | """
Proctored Exams Transformer
"""
from django.conf import settings
from edx_proctoring.api import get_attempt_status_summary
from edx_proctoring.models import ProctoredExamStudentAttemptStatus
from openedx.core.lib.block_structure.transformer import BlockStructureTransformer, FilteringTransformerMixin
class Proct... |
def is_proctored_exam_for_user(block_key):
"""
Test whether the block is a proctored exam for the user in
question.
"""
if (
block_key.block_type == 'sequential' and (
block_structure.get_xblock_field(block... | return [block_structure.create_universal_filter()] | conditional_block |
instr_movntdqa.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn movntdqa_1() {
run_test(&Instruction { mnemonic: Mnemonic::MOVNTDQA, operand1: Some(Direc... | {
run_test(&Instruction { mnemonic: Mnemonic::MOVNTDQA, operand1: Some(Direct(XMM6)), operand2: Some(IndirectScaledIndexed(RBX, RSI, Two, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 56, ... | identifier_body | |
instr_movntdqa.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::MOVNTDQA, operand1: Some(Direct(XMM2)), operand2: Some(IndirectScaledIndexed(EBX, EDI, Four, Some(OperandSize::Xmmword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, ... | movntdqa_1 | identifier_name |
AboutApplyingWhatWeHaveLearnt.js | var _; //globals
describe("About Applying What We Have Learnt", function() {
var products;
beforeEach(function () {
products = [
{ name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
{ name: "Pizza Primavera", ingredients: ["roma", "sundried tom... | sum += i;
}
}
expect(sum).toBe(233168);
});
it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {
var sum = _.range(0,1000,1).filter(function(x){
if (x % 3 === 0 || x % 5 === 0)
return x;}.reduce... | it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () {
var sum = 0;
for(var i=1; i<1000; i+=1) {
if (i % 3 === 0 || i % 5 === 0) { | random_line_split |
AboutApplyingWhatWeHaveLearnt.js | var _; //globals
describe("About Applying What We Have Learnt", function() {
var products;
beforeEach(function () {
products = [
{ name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false },
{ name: "Pizza Primavera", ingredients: ["roma", "sundried tom... |
expect(productsICanEat.length).toBe(1);
});
it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {
var productsICanEat = [];
productsICanEat = _.filter(products, function(x){
return x.containsNuts === false;
... | { //go through all products
if (products[i].containsNuts === false) { //filter contains nuts
hasMushrooms = false;
for (j = 0; j < products[i].ingredients.length; j+=1) { //any ingredient with mushrooms is a no
... | conditional_block |
__main__.py | # -*- coding: utf-8 -*-
import cgitb
import fnmatch
import io
import logging
import click
import pyjsdoc
import pyjsparser
import sys
from .parser.parser import ModuleMatcher
from .parser.visitor import Visitor, SKIP
from . import jsdoc
class Printer(Visitor):
def __init__(self, level=0):
super(Printer,... | (files, visitor, ctx):
for name in files:
with io.open(name) as f:
ctx.logger.info("%s", name)
try:
yield visitor().visit(pyjsparser.parse(f.read()))
except Exception as e:
if ctx.logger.isEnabledFor(logging.DEBUG):
ctx.... | visit_files | identifier_name |
__main__.py | # -*- coding: utf-8 -*-
import cgitb
import fnmatch
import io
import logging
import click
import pyjsdoc
import pyjsparser
import sys
from .parser.parser import ModuleMatcher
from .parser.visitor import Visitor, SKIP
from . import jsdoc
class Printer(Visitor):
def __init__(self, level=0):
super(Printer,... |
print('}')
try:
autojsdoc.main(prog_name='autojsdoc')
except Exception:
print(cgitb.text(sys.exc_info()))
| node = todo.pop()
if node in done:
continue
done.add(node)
deps = byname[node]
todo.update(deps - done)
for dep in deps:
print(' "%s" -> "%s";' % (node, dep)) | conditional_block |
__main__.py | # -*- coding: utf-8 -*-
import cgitb
import fnmatch
import io
import logging
import click
import pyjsdoc
import pyjsparser
import sys
from .parser.parser import ModuleMatcher
from .parser.visitor import Visitor, SKIP
from . import jsdoc
class Printer(Visitor):
def __init__(self, level=0):
super(Printer,... |
def exit_generic(self, node):
self.level -= 1
def enter_Identifier(self, node):
self._print(node['name'])
return SKIP
def enter_Literal(self, node):
self._print(node['value'])
return SKIP
def enter_BinaryExpression(self, node):
self._print(node['opera... | self._print(node['type'])
self.level += 1 | identifier_body |
__main__.py | # -*- coding: utf-8 -*-
import cgitb
import fnmatch
import io
import logging
import click
import pyjsdoc
import pyjsparser
import sys
from .parser.parser import ModuleMatcher
from .parser.visitor import Visitor, SKIP
from . import jsdoc
class Printer(Visitor):
def __init__(self, level=0):
super(Printer,... | 'doc': 'maybe tourmanager instance?',
}),
}),
# OH FOR FUCK'S SAKE
jsdoc.ModuleDoc({
'module': 'summernote/summernote',
'exports': jsdoc.NSDoc({'doc': "totally real summernote"}),
})
]
@click.group(context_settings={'help_option_names': ['-h', '--help']})
@click.opti... | 'exports': jsdoc.NSDoc({
'name': 'Tour', | random_line_split |
curve.py | from org.jfree.data.xy import XYSeries, XYSeriesCollection
from org.jfree.chart.plot import PlotOrientation
from org.jfree.chart import ChartFactory
from geoscript.plot.chart import Chart
from org.jfree.chart.renderer.xy import XYSplineRenderer, XYLine3DRenderer
def | (data, name="", smooth=True, trid=True):
"""
Creates a curve based on a list of (x,y) tuples.
Setting *smooth* to ``True`` results in a spline renderer renderer is used.
Setting *trid* to ``True`` results in a 3D plot. In this case the ``smooth``
argument is ignored.
"""
dataset = XYSeriesColle... | curve | identifier_name |
curve.py | from org.jfree.data.xy import XYSeries, XYSeriesCollection
from org.jfree.chart.plot import PlotOrientation
from org.jfree.chart import ChartFactory
from geoscript.plot.chart import Chart
from org.jfree.chart.renderer.xy import XYSplineRenderer, XYLine3DRenderer
def curve(data, name="", smooth=True, trid=True):
| """
Creates a curve based on a list of (x,y) tuples.
Setting *smooth* to ``True`` results in a spline renderer renderer is used.
Setting *trid* to ``True`` results in a 3D plot. In this case the ``smooth``
argument is ignored.
"""
dataset = XYSeriesCollection()
xy = XYSeries(name);
fo... | identifier_body | |
curve.py | from org.jfree.data.xy import XYSeries, XYSeriesCollection
from org.jfree.chart.plot import PlotOrientation
from org.jfree.chart import ChartFactory
from geoscript.plot.chart import Chart
from org.jfree.chart.renderer.xy import XYSplineRenderer, XYLine3DRenderer
def curve(data, name="", smooth=True, trid=True):
"""
... |
dataset.addSeries(xy);
chart = ChartFactory.createXYLineChart(None, None, None, dataset,
PlotOrientation.VERTICAL, True, True, False)
if smooth:
chart.getXYPlot().setRenderer(XYSplineRenderer())
if trid:
chart.getXYPlot().setRenderer(XYLine3DRenderer())
return Chart(chart)
| xy.add(d[0], d[1]) | conditional_block |
curve.py | from org.jfree.data.xy import XYSeries, XYSeriesCollection
from org.jfree.chart.plot import PlotOrientation
from org.jfree.chart import ChartFactory
from geoscript.plot.chart import Chart
from org.jfree.chart.renderer.xy import XYSplineRenderer, XYLine3DRenderer
def curve(data, name="", smooth=True, trid=True):
"""
... | PlotOrientation.VERTICAL, True, True, False)
if smooth:
chart.getXYPlot().setRenderer(XYSplineRenderer())
if trid:
chart.getXYPlot().setRenderer(XYLine3DRenderer())
return Chart(chart) | dataset.addSeries(xy);
chart = ChartFactory.createXYLineChart(None, None, None, dataset, | random_line_split |
urls.py | # -*- coding: utf-8 -*-
# urls.py ---
#
# Created: Wed Dec 14 23:02:53 2011 (+0200)
# Author: Janne Kuuskeri
#
from django.conf.urls.defaults import patterns, url
import resources
dictresource = resources.MyDictResource()
textresource = resources.MyTextResource()
respresource = resources.MyRespResource()
authresou... |
acl_resources = (
dictresource,
textresource,
respresource,
authresource,
anonresource,
permresource,
)
urlpatterns = patterns('',
url(r'^perm', permresource),
url(r'^auth$', authresource),
url(r'^person', personresource),
url(r'^auth/anon', anonresource),
url(r'^valid... | factoryresource = resources.FactoryResource()
| random_line_split |
DebugSslClient.py | #!/usr/bin/python2.7
from nassl._nassl import SSL
from SslClient import SslClient
class DebugSslClient(SslClient):
"""
An SSL client with additional debug methods that no one should ever use (insecure renegotiation, etc.).
"""
def get_secure_renegotiation_support(self):
return self._ssl.get_... |
else :
d['GeneratorType'] = 'Unknown'
return d
@staticmethod
def _openssl_str_to_dic(s, param_tab=' ') :
"""EDH and ECDH parameters pretty-printing."""
d = {}
to_XML = lambda x : "_".join(m for m in x.replace('-', ' ').split(' '))
current... | d['Generator'] = d.pop(k)
d['GeneratorType'] = k.split('_')[1].strip('()')
break | conditional_block |
DebugSslClient.py | #!/usr/bin/python2.7
from nassl._nassl import SSL
from SslClient import SslClient
class DebugSslClient(SslClient):
"""
An SSL client with additional debug methods that no one should ever use (insecure renegotiation, etc.).
"""
def get_secure_renegotiation_support(self):
return self._ssl.get_... |
def get_ecdh_param(self):
"""Retrieve the negotiated Ephemeral EC Diffie Helmann parameters."""
d = self._openssl_str_to_dic(self._ssl.get_ecdh_param(), ' ')
d['GroupSize'] = d.pop('ECDSA_Parameters').strip('( bit)')
d['Type'] = "ECDH"
if 'Cofactor' in d :
... | """Retrieve the negotiated Ephemeral Diffie Helmann parameters."""
d = self._openssl_str_to_dic(self._ssl.get_dh_param())
d['GroupSize'] = d.pop('DH_Parameters').strip('( bit)')
d['Type'] = "DH"
d['Generator'] = d.pop('generator').split(' ')[0]
return d | identifier_body |
DebugSslClient.py | #!/usr/bin/python2.7
from nassl._nassl import SSL
from SslClient import SslClient
class DebugSslClient(SslClient):
"""
An SSL client with additional debug methods that no one should ever use (insecure renegotiation, etc.).
"""
def get_secure_renegotiation_support(self):
return self._ssl.get_... | """Get the SSL connection's Session object."""
return self._ssl.get_session()
def set_session(self, sslSession):
"""Set the SSL connection's Session object."""
return self._ssl.set_session(sslSession)
def set_options(self, options):
return self._ssl.set_options(option... | self._ssl.renegotiate()
return self.do_handshake()
def get_session(self): | random_line_split |
DebugSslClient.py | #!/usr/bin/python2.7
from nassl._nassl import SSL
from SslClient import SslClient
class DebugSslClient(SslClient):
"""
An SSL client with additional debug methods that no one should ever use (insecure renegotiation, etc.).
"""
def get_secure_renegotiation_support(self):
return self._ssl.get_... | (self):
return self._ssl.get_current_compression_method()
@staticmethod
def get_available_compression_methods():
"""
Returns the list of SSL compression methods supported by SslClient.
"""
return SSL.get_available_compression_methods()
def do_renegotiate(self):
... | get_current_compression_method | identifier_name |
identify.js | /* globals describe, beforeEach, $fixture, qq, assert, it, qqtest, helpme, purl */
if (qq.supportedFeatures.imagePreviews && qqtest.canDownloadFileAsBlob) | {
describe("identify.js", function() {
"use strict";
function testPreviewability(expectedToBePreviewable, key, expectedMime, done) {
qqtest.downloadFileAsBlob(key, expectedMime).then(function(blob) {
new qq.Identify(blob, function() {}).isPreviewable().then(function(mime... | conditional_block | |
identify.js | /* globals describe, beforeEach, $fixture, qq, assert, it, qqtest, helpme, purl */
if (qq.supportedFeatures.imagePreviews && qqtest.canDownloadFileAsBlob) {
describe("identify.js", function() {
"use strict";
function testPreviewability(expectedToBePreviewable, key, expectedMime, done) |
it("classifies gif as previewable", function(done) {
testPreviewability(true, "drop-background.gif", "image/gif", done);
});
it("classifies jpeg as previewable", function(done) {
testPreviewability(true, "fearless.jpeg", "image/jpeg", done);
});
it("cl... | {
qqtest.downloadFileAsBlob(key, expectedMime).then(function(blob) {
new qq.Identify(blob, function() {}).isPreviewable().then(function(mime) {
!expectedToBePreviewable && assert.fail();
assert.equal(mime, expectedMime);
done();
... | identifier_body |
identify.js | /* globals describe, beforeEach, $fixture, qq, assert, it, qqtest, helpme, purl */
if (qq.supportedFeatures.imagePreviews && qqtest.canDownloadFileAsBlob) {
describe("identify.js", function() {
"use strict";
function | (expectedToBePreviewable, key, expectedMime, done) {
qqtest.downloadFileAsBlob(key, expectedMime).then(function(blob) {
new qq.Identify(blob, function() {}).isPreviewable().then(function(mime) {
!expectedToBePreviewable && assert.fail();
assert.equal(m... | testPreviewability | identifier_name |
identify.js | /* globals describe, beforeEach, $fixture, qq, assert, it, qqtest, helpme, purl */
if (qq.supportedFeatures.imagePreviews && qqtest.canDownloadFileAsBlob) {
describe("identify.js", function() {
"use strict";
function testPreviewability(expectedToBePreviewable, key, expectedMime, done) {
... | });
it("marks a non-image as not previewable", function(done) {
testPreviewability(false, "simpletext.txt", null, done);
});
});
} |
it("classifies tiff as previewable", function(done) {
testPreviewability(qq.supportedFeatures.tiffPreviews, "sample.tif", "image/tiff", done); | random_line_split |
0008_auto_20190823_1324.py | # Generated by Django 2.1.11 on 2019-08-23 11:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| dependencies = [
('sliders', '0007_slide_name_sub'),
]
operations = [
migrations.AlterField(
model_name='link',
name='plugin',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='plugin_link', to='cms.... | identifier_body | |
0008_auto_20190823_1324.py | # Generated by Django 2.1.11 on 2019-08-23 11:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration): | dependencies = [
('sliders', '0007_slide_name_sub'),
]
operations = [
migrations.AlterField(
model_name='link',
name='plugin',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='plugin_link', to='... | random_line_split | |
0008_auto_20190823_1324.py | # Generated by Django 2.1.11 on 2019-08-23 11:24
from django.db import migrations, models
import django.db.models.deletion
class | (migrations.Migration):
dependencies = [
('sliders', '0007_slide_name_sub'),
]
operations = [
migrations.AlterField(
model_name='link',
name='plugin',
field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related... | Migration | identifier_name |
main.rs | extern crate term_mux;
extern crate termion;
extern crate chan_signal;
use std::io::{Read, Write, Result};
use std::fs::File;
use std::thread;
use std::time::Duration;
use termion::get_tty;
use termion::raw::IntoRawMode;
use chan_signal::{notify, Signal};
use term_mux::pty::Pty;
use term_mux::tui::{get_terminal_size, ... | () {
let signal = notify(&[Signal::WINCH]);
let mut tty_output = get_tty().unwrap().into_raw_mode().unwrap();
let mut tty_input = tty_output.try_clone().unwrap();
let pty_resize = Pty::spawn(&get_shell(), &get_terminal_size().unwrap()).unwrap();
let mut pty_output = pty_resize.try_cl... | main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.