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
job.py
64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36" } self.session.headers.update(headers) response = self.session.get(base64.b64decode(result['id']).decode()) if response.text.find('callbackFunction') >= 0: ...
t_token = token.groups()[0] self.ticket_info_for_passenger_form = json.loads(form.groups()[0].replace("'", '"')) self.order_request_dto = json.loads(order.groups()[0].replace("'", '"')) except: return False, False, html # TODO Error slide_val = re.search(r"var if_ch...
identifier_body
job.py
.get_name(), Config().USER_HEARTBEAT_INTERVAL) UserLog.add_quick_log(message).flush() def get_last_heartbeat(self): if Config().is_cluster_enabled(): return int(self.cluster.session.get(Cluster.KEY_USER_LAST_HEARTBEAT, 0)) return self.last_heartbeat def set_last_heartbeat(...
有用,01-10 看来应该是没用 01-22 有时拿到的状态 是已失效的再加上试试 return is_login def auth_uamtk(self): response = self.session.post(API_AUTH_UAMTK.get('url'), {'appid': 'otn'}, headers={ 'Referer': 'https://kyfw.12306.cn/otn/passport?redirect=/otn/login/userLogin', 'Origin': 'https://kyfw.12306....
会维持状态,这里再请求下个人中心看有没
identifier_name
jac.py
F: R^m -> R^n # i.e. # [ F_1(x_1, ..., x_m) ] # F(x) = [ : : : ] # [ F_n(x_1, ..., x_m) ]. # Then Dij = dFi/dxj, i=1..n, j=1..m (an n x m matrix). # This is numerically approximated (forward-difference approximation) by # (F(x1,...,xj+h,...,xn) - F(x1,...,xj,...,xn)) / h # or (cent...
# ---------------------------------------------------------------- def gt_something(): thetalo = 0 thetahi = 2*math.pi philo = 0 phihi = math.pi nphi = 12 ntheta = 12 if (len(sys.argv) == 3): nphi = int(sys.argv[1]) ntheta = int(sys.argv[2]) dtheta = (thetahi-thetalo)/ntheta dphi = (phihi-philo)/...
[x, y, z] = q return [x**2 + y**2 + z**2]
identifier_body
jac.py
F: R^m -> R^n # i.e. # [ F_1(x_1, ..., x_m) ] # F(x) = [ : : : ] # [ F_n(x_1, ..., x_m) ]. # Then Dij = dFi/dxj, i=1..n, j=1..m (an n x m matrix). # This is numerically approximated (forward-difference approximation) by # (F(x1,...,xj+h,...,xn) - F(x1,...,xj,...,xn)) / h # or (cent...
a = 0.2 b = 0.3 c = sqrt(1 - a**2 - b**2) do_point_with_det(F, [a,b,c]) a = 0.8 b = 0.2 c = sqrt(1 - a**2 - b**2) do_point_with_det(F, [a,b,c]) print # ---------------------------------------------------------------- def F(q): [x, y, z] = q #f1 = x**2 #f2 = y**2 #f3 = z**2 #f1 = x**2 * y**2 #f2 = y...
a=0.1 do_point_with_det(F, [cos(a),sin(a),0])
random_line_split
jac.py
F: R^m -> R^n # i.e. # [ F_1(x_1, ..., x_m) ] # F(x) = [ : : : ] # [ F_n(x_1, ..., x_m) ]. # Then Dij = dFi/dxj, i=1..n, j=1..m (an n x m matrix). # This is numerically approximated (forward-difference approximation) by # (F(x1,...,xj+h,...,xn) - F(x1,...,xj,...,xn)) / h # or (cent...
DF = jac(F, q) # * Form an orthonormal basis # * Compute DF of the basis # * Row-reduce that to get the rank of DF on TM|q #print "q = ", q, #print "det(DF) = ", d #print "%7.4f %7.4f %7.4f %7.4f %7.4f,%7.4f %7.4f,%7.4f %7.4f,%7.4f" % ( # x,y,z, d, DG[0][0], -DG[0][0]*x, DG[0][1], -DG[0][1...
x = sin(phi) * cos(theta) y = sin(phi) * sin(theta) z = cos(phi) q = [x,y,z] DF = jac(F, q) d = DF.det() # Let G(x,y,z) = x^2 + y^2 + z^2. The unit sphere is the level set # for G(x,y,z) = 1. # Tangent plane at (u,v,w): # dG/dx(x-u) + dG/dy(y-v) + dG/dz(z-w) # where (u,v,w) are the co...
conditional_block
jac.py
F: R^m -> R^n # i.e. # [ F_1(x_1, ..., x_m) ] # F(x) = [ : : : ] # [ F_n(x_1, ..., x_m) ]. # Then Dij = dFi/dxj, i=1..n, j=1..m (an n x m matrix). # This is numerically approximated (forward-difference approximation) by # (F(x1,...,xj+h,...,xn) - F(x1,...,xj,...,xn)) / h # or (cent...
(): F = F1 do_point_with_det(F, [0,0,0]) print do_point_with_det(F, [0,0,1]) do_point_with_det(F, [0,1,0]) do_point_with_det(F, [1,0,0]) print do_point_with_det(F, [1,1,0]) do_point_with_det(F, [1,0,1]) do_point_with_det(F, [0,1,1]) print do_point_with_det(F, [1,1,1]) do_point_with_det(F, [1,2,3]) do_p...
frufru
identifier_name
person.py
__author__="vvladych" __date__ ="$09.10.2014 23:01:15$" from forecastmgmt.dao.db_connection import get_db_connection import psycopg2.extras from MDO import MDO from person_name import PersonName class Person(MDO): sql_dict={"get_all":"SELECT sid, common_name, birth_date, birth_place, person_uuid FROM fc_...
(self, other): cur=get_db_connection().cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) data=(other.common_name, other.birth_date, other.birth_place, self.sid) cur.execute(Person.sql_dict["update_person"],data) cur.close() # update person_names # delete ou...
update
identifier_name
person.py
__author__="vvladych" __date__ ="$09.10.2014 23:01:15$" from forecastmgmt.dao.db_connection import get_db_connection import psycopg2.extras from MDO import MDO from person_name import PersonName class Person(MDO): sql_dict={"get_all":"SELECT sid, common_name, birth_date, birth_place, person_uuid FROM fc_...
else: self.names=[] def load_object_from_db(self,rec): self.common_name=rec.common_name self.birth_date=rec.birth_date self.birth_place=rec.birth_place self.uuid=rec.person_uuid self.names=PersonName().get_all_for_foreign_key(self.sid) ...
self.names=PersonName().get_all_for_foreign_key(self.sid)
conditional_block
person.py
__author__="vvladych" __date__ ="$09.10.2014 23:01:15$" from forecastmgmt.dao.db_connection import get_db_connection import psycopg2.extras from MDO import MDO from person_name import PersonName class Person(MDO): sql_dict={"get_all":"SELECT sid, common_name, birth_date, birth_place, person_uuid FROM fc_p...
data=(other.common_name, other.birth_date, other.birth_place, self.sid) cur.execute(Person.sql_dict["update_person"],data) cur.close() # update person_names # delete outdated person_names for person_name in self.names: if person_name not in other.name...
return Person(rec.sid, rec.common_name, rec.birth_date, rec.birth_place, rec.person_uuid) def update(self, other): cur=get_db_connection().cursor(cursor_factory=psycopg2.extras.NamedTupleCursor)
random_line_split
person.py
__author__="vvladych" __date__ ="$09.10.2014 23:01:15$" from forecastmgmt.dao.db_connection import get_db_connection import psycopg2.extras from MDO import MDO from person_name import PersonName class Person(MDO): sql_dict={"get_all":"SELECT sid, common_name, birth_date, birth_place, person_uuid FROM fc_...
def update(self, other): cur=get_db_connection().cursor(cursor_factory=psycopg2.extras.NamedTupleCursor) data=(other.common_name, other.birth_date, other.birth_place, self.sid) cur.execute(Person.sql_dict["update_person"],data) cur.close() ...
return Person(rec.sid, rec.common_name, rec.birth_date, rec.birth_place, rec.person_uuid)
identifier_body
expr-block.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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(dead_code)] // Tests for standalone blocks as expressions fn test_basic() { let rs: bool = { true }; assert!((rs)); } struct RS { v1: isize...
random_line_split
expr-block.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 ...
struct RS { v1: isize, v2: isize } fn test_rec() { let rs = { RS {v1: 10, v2: 20} }; assert_eq!(rs.v2, 20); } fn test_filled_with_stuff() { let rs = { let mut a = 0; while a < 10 { a += 1; } a }; assert_eq!(rs, 10); } pub fn main() { test_basic(); test_rec(); test_filled_with_stuff(); }
{ let rs: bool = { true }; assert!((rs)); }
identifier_body
expr-block.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 ...
() { test_basic(); test_rec(); test_filled_with_stuff(); }
main
identifier_name
cfg.py
= [] # TODO(alexbw): generalize to break, return, continue, yield, etc. # A stack of lists, tracking continue statements self.continue_ = [] # A stack of lists tracking break nodes self.break_ = [] def set_current_leaves(self, cfg_node): """Link this cfg_node to the current leaves. This...
(self, node): self.break_[-1].extend(self.current_leaves) self.current_leaves[:] = [] def visit_Continue(self, node): self.continue_[-1].extend(self.current_leaves) self.current_leaves[:] = [] def visit_Try(self, node): self.visit_statements(node.body) body = self.current_leaves handle...
visit_Break
identifier_name
cfg.py
is the central function for building the CFG. It links the current head cfg_nodes to the passed cfg_node. It then resets the head to the passed cfg_node. Args: cfg_node: A CfgNode instance. """ for head in self.current_leaves: head.next.add(cfg_node) # While we're linking the CFG...
"""Depth-first walking the CFG, applying dataflow info propagation.""" # node.value is None only for the exit CfgNode. if not node.value: return if anno.hasanno(node.value, self.out_label): before = hash(anno.getanno(node.value, self.out_label)) else: before = None preds = [ ...
identifier_body
cfg.py
= [] # TODO(alexbw): generalize to break, return, continue, yield, etc. # A stack of lists, tracking continue statements self.continue_ = [] # A stack of lists tracking break nodes self.break_ = [] def set_current_leaves(self, cfg_node): """Link this cfg_node to the current leaves. This...
self.current_leaves = body self.visit_statements(node.orelse) self.current_leaves = handlers + self.current_leaves self.visit_statements(node.finalbody) def visit_With(self, node): for item in node.items: self.set_current_leaves(CfgNode(item)) self.visit_statements(node.body) # TODO(...
self.current_leaves = body[:] self.visit_statements(handler.body) handlers.extend(self.current_leaves)
conditional_block
cfg.py
= [] # TODO(alexbw): generalize to break, return, continue, yield, etc. # A stack of lists, tracking continue statements self.continue_ = [] # A stack of lists tracking break nodes self.break_ = [] def set_current_leaves(self, cfg_node): """Link this cfg_node to the current leaves. This...
def __init__(self, analysis): self.transfer_fn = analysis.transfer_fn self.in_label = analysis.in_label self.out_label = analysis.out_label super(PropagateAnalysis, self).__init__() def visit_If(self, node): # Depth-first. self.generic_visit(node) incoming = anno.getanno(node.body[0], s...
"""Port analysis annotations from statements to their enclosing blocks."""
random_line_split
exp_entries.py
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module defines Entry classes for containing experimental data. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Pi...
def as_dict(self): """ :return: MSONable dict """ return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "thermodata": [td.as_dict() for td in self._thermodata], "composition": self.composition.as_dict(), ...
""" :param d: Dict representation. :return: ExpEntry """ thermodata = [ThermoData.from_dict(td) for td in d["thermodata"]] return cls(d["composition"], thermodata, d["temperature"])
identifier_body
exp_entries.py
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module defines Entry classes for containing experimental data. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Pi...
(cls, d): """ :param d: Dict representation. :return: ExpEntry """ thermodata = [ThermoData.from_dict(td) for td in d["thermodata"]] return cls(d["composition"], thermodata, d["temperature"]) def as_dict(self): """ :return: MSONable dict """ ...
from_dict
identifier_name
exp_entries.py
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module defines Entry classes for containing experimental data. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Pi...
self.temperature = temperature super().__init__(comp, enthalpy) def __repr__(self): return "ExpEntry {}, Energy = {:.4f}".format(self.composition.formula, self.energy) def __str__(self): return self.__repr__() @classmet...
raise ValueError("List of Thermodata does not contain enthalpy " "values.")
conditional_block
exp_entries.py
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ This module defines Entry classes for containing experimental data. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Pi...
thermodata: A sequence of ThermoData associated with the entry. temperature: A temperature for the entry in Kelvin. Defaults to 298K. """ comp = Composition(composition) self._thermodata = thermodata found = False enthalpy = float("inf") for data i...
Args: composition: Composition of the entry. For flexibility, this can take the form of all the typical input taken by a Composition, including a {symbol: amt} dict, a string formula, and others.
random_line_split
test_hashes.py
#!/usr/bin/env python3 # Copyright (C) 2017-2021 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except...
# def test_fingerprint() -> None: # # seed = "bfc4cbaad0ff131aa97fa30a48d09ae7df914bcc083af1e07793cd0a7c61a03f65d622848209ad3366a419f4718a80ec9037df107d8d12c19b83202de00a40ad" # xprv = rootxprv_from_seed(seed) # pf = fingerprint(xprv) # xprv is automatically converted to xpub # child_key = derive(xp...
test_vectors = ( plain_prv_keys + net_unaware_compressed_pub_keys + net_unaware_uncompressed_pub_keys ) for hexstring in test_vectors: hash160(hexstring) hash256(hexstring)
identifier_body
test_hashes.py
#!/usr/bin/env python3
# This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except according to the terms contained in the LICENSE file. "Tests for the `bt...
# Copyright (C) 2017-2021 The btclib developers #
random_line_split
test_hashes.py
#!/usr/bin/env python3 # Copyright (C) 2017-2021 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except...
# def test_fingerprint() -> None: # # seed = "bfc4cbaad0ff131aa97fa30a48d09ae7df914bcc083af1e07793cd0a7c61a03f65d622848209ad3366a419f4718a80ec9037df107d8d12c19b83202de00a40ad" # xprv = rootxprv_from_seed(seed) # pf = fingerprint(xprv) # xprv is automatically converted to xpub # child_key = derive(xp...
hash160(hexstring) hash256(hexstring)
conditional_block
test_hashes.py
#!/usr/bin/env python3 # Copyright (C) 2017-2021 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except...
() -> None: test_vectors = ( plain_prv_keys + net_unaware_compressed_pub_keys + net_unaware_uncompressed_pub_keys ) for hexstring in test_vectors: hash160(hexstring) hash256(hexstring) # def test_fingerprint() -> None: # # seed = "bfc4cbaad0ff131aa97fa30a48d09ae...
test_hash160_hash256
identifier_name
crypter.rs
EncryptionMethod::Aes192Ctr => EncryptionMethod::Aes192Ctr, DBEncryptionMethod::Aes256Ctr => EncryptionMethod::Aes256Ctr, DBEncryptionMethod::Unknown => EncryptionMethod::Unknown, } } #[cfg(not(feature = "prost-codec"))] pub fn compat(method: EncryptionMethod) -> EncryptionMethod { method } #[...
(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("PlainKey") .field(&"REDACTED".to_string()) .finish() } } // Don't expose the key in a display print impl_display_as_debug!(PlainKey); #[cfg(test)] mod tests { use hex::FromHex; use super::*; ...
fmt
identifier_name
crypter.rs
EncryptionMethod::Aes192Ctr => EncryptionMethod::Aes192Ctr, DBEncryptionMethod::Aes256Ctr => EncryptionMethod::Aes256Ctr, DBEncryptionMethod::Unknown => EncryptionMethod::Unknown, } } #[cfg(not(feature = "prost-codec"))] pub fn compat(method: EncryptionMethod) -> EncryptionMethod { method } #[...
&mut tag.0, )?; Ok((ciphertext, tag)) } pub fn decrypt(&self, ct: &[u8], tag: AesGcmTag) -> Result<Vec<u8>> { let cipher = OCipher::aes_256_gcm(); let plaintext = symm::decrypt_aead( cipher, &self.key.0, Some(self.iv.as_slice()), ...
Some(self.iv.as_slice()), &[], /* AAD */ pt,
random_line_split
07f975f81f03_remove_team_domain.py
# -*- coding: utf-8 -*- """Remove team domain Revision ID: 07f975f81f03 Revises: 4e206c5ddabd Create Date: 2017-08-04 15:12:11.992856 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '07f975f81f03' down_revision = '4e206c5ddabd' branch_labels = None depends_on = ...
op.add_column( 'team', sa.Column('domain', sa.VARCHAR(length=253), autoincrement=False, nullable=True), ) op.create_index('ix_team_domain', 'team', ['domain'], unique=False)
identifier_body
07f975f81f03_remove_team_domain.py
# -*- coding: utf-8 -*- """Remove team domain Revision ID: 07f975f81f03 Revises: 4e206c5ddabd Create Date: 2017-08-04 15:12:11.992856 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '07f975f81f03' down_revision = '4e206c5ddabd' branch_labels = None depends_on = ...
(): op.add_column( 'team', sa.Column('domain', sa.VARCHAR(length=253), autoincrement=False, nullable=True), ) op.create_index('ix_team_domain', 'team', ['domain'], unique=False)
downgrade
identifier_name
07f975f81f03_remove_team_domain.py
# -*- coding: utf-8 -*- """Remove team domain Revision ID: 07f975f81f03 Revises: 4e206c5ddabd Create Date: 2017-08-04 15:12:11.992856 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '07f975f81f03' down_revision = '4e206c5ddabd' branch_labels = None depends_on = ...
op.add_column( 'team', sa.Column('domain', sa.VARCHAR(length=253), autoincrement=False, nullable=True), ) op.create_index('ix_team_domain', 'team', ['domain'], unique=False)
random_line_split
ext.js
var appName = csInterface.hostEnvironment.appName; if(appName != "FLPR"){ loadJSX(); } var appNames = ["PHXS"]; for (var i = 0; i < appNames.length; i++) { var name = appNames[i]; if (appName.indexOf(name) >= 0) { var btn = document.ge...
function onLoaded() { var csInterface = new CSInterface();
random_line_split
ext.js
function onLoaded() { var csInterface = new CSInterface(); var appName = csInterface.hostEnvironment.appName; if(appName != "FLPR"){ loadJSX(); } var appNames = ["PHXS"]; for (var i = 0; i < appNames.length; i++) { var name = appNames[i]; ...
(value, delta) { var computedValue = !isNaN(delta) ? value + delta : value; if (computedValue < 0) { computedValue = 0; } else if (computedValue > 255) { computedValue = 255; } computedValue = computedValue.toString(16); return computedVa...
computeValue
identifier_name
ext.js
function onLoaded() { var csInterface = new CSInterface(); var appName = csInterface.hostEnvironment.appName; if(appName != "FLPR")
var appNames = ["PHXS"]; for (var i = 0; i < appNames.length; i++) { var name = appNames[i]; if (appName.indexOf(name) >= 0) { var btn = document.getElementById("btn_" + name); if (btn) btn.disabled = false; } } u...
{ loadJSX(); }
conditional_block
ext.js
function onLoaded() { var csInterface = new CSInterface(); var appName = csInterface.hostEnvironment.appName; if(appName != "FLPR"){ loadJSX(); } var appNames = ["PHXS"]; for (var i = 0; i < appNames.length; i++) { var name = appNames[i]; ...
} function onAppThemeColorChanged(event) { // Should get a latest HostEnvironment object from application. var skinInfo = JSON.parse(window.__adobe_cep__.getHostEnvironment()).appSkinInfo; // Gets the style information such as color info from the skinInfo, // and redraw all UI controls of your ...
{ function computeValue(value, delta) { var computedValue = !isNaN(delta) ? value + delta : value; if (computedValue < 0) { computedValue = 0; } else if (computedValue > 255) { computedValue = 255; } computedValue = computedValue.toString(16)...
identifier_body
regions-fn-subtyping.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 ...
(f: Box<FnMut(&usize)>) { // Here, g is a function that can accept a usize pointer with // lifetime r, and f is a function that can accept a usize pointer // with any lifetime. The assignment g = f should be OK (i.e., // f's type should be a subtype of g's type), because f can be // used in any con...
ok
identifier_name
regions-fn-subtyping.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 ...
{ }
identifier_body
regions-fn-subtyping.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 ...
}
pub fn main() {
random_line_split
lib.rs
//! Asynchronous channels. //! //! This crate provides channels that can be used to communicate between //! asynchronous tasks. //! //! All items of this library are only available when the `std` or `alloc` feature of this //! library is activated, and it is activated by default. #![cfg_attr(feature = "cfg-target-has-...
($($item:item)*) => {$( #[cfg_attr(feature = "cfg-target-has-atomic", cfg(target_has_atomic = "ptr"))] $item )*}; } cfg_target_has_atomic! { #[cfg(feature = "alloc")] extern crate alloc; #[cfg(feature = "alloc")] mod lock; #[cfg(feature = "std")] pub mod mpsc; #[cfg...
macro_rules! cfg_target_has_atomic {
random_line_split
process-spawn-with-unicode-params.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
my_env.push(env); // run child let p = Command::new(&child_path) .arg(arg) .cwd(&cwd) .env_set_all(&my_env) .spawn().unwrap().wait_with_output().unwrap(); // display the output asser...
assert!(fs::copy(&my_path, &child_path).is_ok()); let mut my_env = my_env;
random_line_split
process-spawn-with-unicode-params.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert!(old_io::stdout().write(&p.output).is_ok()); assert!(old_io::stderr().write(&p.error).is_ok()); // make sure the child succeeded assert!(p.status.success()); } else { // child // check working directory (don't try to compare with `cwd` he...
{ // parent let child_filestem = Path::new(child_name); let child_filename = child_filestem.with_extension(my_ext); let child_path = cwd.join(child_filename); // make a separate directory for the child drop(fs::mkdir(&cwd, old_io::USER_RWX).is_ok()); ass...
conditional_block
process-spawn-with-unicode-params.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let my_args = os::args(); let my_cwd = os::getcwd().unwrap(); let my_env = os::env(); let my_path = Path::new(os::self_exe_name().unwrap()); let my_dir = my_path.dir_path(); let my_ext = my_path.extension_str().unwrap_or(""); // some non-ASCII characters let blah = "\u03c...
main
identifier_name
process-spawn-with-unicode-params.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
if my_args.len() == 1 { // parent let child_filestem = Path::new(child_name); let child_filename = child_filestem.with_extension(my_ext); let child_path = cwd.join(child_filename); // make a separate directory for the child drop(fs::mkdir(&cwd, old_io::USER_...
{ let my_args = os::args(); let my_cwd = os::getcwd().unwrap(); let my_env = os::env(); let my_path = Path::new(os::self_exe_name().unwrap()); let my_dir = my_path.dir_path(); let my_ext = my_path.extension_str().unwrap_or(""); // some non-ASCII characters let blah = "\u03c0\u...
identifier_body
modules.js
var modules = { "success" : [ {id: 1, name:"控制台", code:"console", protocol:"http", domain:"console.ecc.com", port:"18333", created:'2017-03-08 00:00:00', creator:'1', modified:'2017-03-08 00:00:00', modifier:'1'}, {id: 2, name:"服务中心", code:"service-center", protocol:"http", domain:"sc.ecc.com", port:"18222", creat...
}
"modules": modules
random_line_split
app.js
var App = angular.module("App", ["ionic"]); App.service("ChileBitBook", ["$http","$log", ChileBitBook]); App.controller("AppCtrl", ["$scope", "ChileBitBook", "$log", AppCtrl]); function
($scope, ChileBitBook, $log){ $scope.Bids = []; $scope.Asks = []; $scope.updateBook = function(){ ChileBitBook.getBook($scope); }; } function ChileBitBook($http, $log){ this.getBook = function($scope) { $http.jsonp("https://api.blinktrade.com/api/v1/CLP/orderbook?callback=JSON_CALLB...
AppCtrl
identifier_name
app.js
var App = angular.module("App", ["ionic"]); App.service("ChileBitBook", ["$http","$log", ChileBitBook]); App.controller("AppCtrl", ["$scope", "ChileBitBook", "$log", AppCtrl]); function AppCtrl($scope, ChileBitBook, $log)
function ChileBitBook($http, $log){ this.getBook = function($scope) { $http.jsonp("https://api.blinktrade.com/api/v1/CLP/orderbook?callback=JSON_CALLBACK") .success(function(result){ var Bid; $.each(result.bids, function(index, stringBid){ Bid = { ...
{ $scope.Bids = []; $scope.Asks = []; $scope.updateBook = function(){ ChileBitBook.getBook($scope); }; }
identifier_body
app.js
var App = angular.module("App", ["ionic"]); App.service("ChileBitBook", ["$http","$log", ChileBitBook]); App.controller("AppCtrl", ["$scope", "ChileBitBook", "$log", AppCtrl]); function AppCtrl($scope, ChileBitBook, $log){ $scope.Bids = []; $scope.Asks = []; $scope.updateBook = function(){ ChileB...
Volume: stringAsk[1], Id: stringAsk[2], }; $scope.Asks.push(Ask); }); }); }; }
Ask = { Price: stringAsk[0],
random_line_split
main.py
# -*- coding: utf-8 -*- # This file is part of the Rocket Web Server # Copyright (c) 2010 Timothy Farrell # Import System Modules import sys import time import socket import logging import traceback from threading import Lock try: from queue import Queue except ImportError: from Queue import Queue # Import P...
(self, interfaces = ('127.0.0.1', 8000), method = 'wsgi', app_info = None, min_threads = None, max_threads = None, queue_size = None, timeout = 600, handle_signals = True): se...
__init__
identifier_name
main.py
# -*- coding: utf-8 -*- # This file is part of the Rocket Web Server # Copyright (c) 2010 Timothy Farrell # Import System Modules import sys import time import socket import logging import traceback from threading import Lock try: from queue import Queue except ImportError: from Queue import Queue # Import P...
finally: self.startstop_lock.release() if background: return while self._monitor.isAlive(): try: time.sleep(THREAD_STOP_CHECK_INTERVAL) except KeyboardInterrupt: # Capture a keyboard interrupt when running from a...
l.start()
conditional_block
main.py
# -*- coding: utf-8 -*- # This file is part of the Rocket Web Server # Copyright (c) 2010 Timothy Farrell # Import System Modules import sys import time import socket import logging import traceback from threading import Lock try: from queue import Queue except ImportError: from Queue import Queue # Import P...
self.timeout, self._threadpool) self._monitor.setDaemon(True) self._monitor.start() # I know that EXPR and A or B is bad but I'm keeping it for Py2.4 # compatibility. str_extract = lambda...
log.info('Starting %s' % SERVER_SOFTWARE) self.startstop_lock.acquire() try: # Set up our shutdown signals if self.handle_signals: try: import signal signal.signal(signal.SIGTERM, self._sigterm) signal....
identifier_body
main.py
# -*- coding: utf-8 -*- # This file is part of the Rocket Web Server # Copyright (c) 2010 Timothy Farrell # Import System Modules import sys import time import socket import logging import traceback from threading import Lock try: from queue import Queue except ImportError: from Queue import Queue # Import P...
# Start our worker threads self._threadpool.start() # Start our monitor thread self._monitor = Monitor(self.monitor_queue, self.active_queue, self.timeout, self._...
signal.signal(signal.SIGTERM, self._sigterm) signal.signal(signal.SIGUSR1, self._sighup) except: log.debug('This platform does not support signals.')
random_line_split
slotNameValidator.ts
import { FunctionAppService } from 'app/shared/services/function-app.service'; import { PortalResources } from './../models/portal-resources'; import { Validations, Regex } from './../models/constants'; import { Injector } from '@angular/core/src/core'; import { ArmObj } from './../models/arm/arm-obj'; import { Transla...
} const siteNamePlusHypenLength = this._getSiteNameLength() + 1; if (control.value.length < Validations.websiteNameMinLength) { return Promise.resolve({ invalidSiteName: this._ts.instant(PortalResources.validation_siteNameMinChars) }); } else if (control.value.length + siteNamePlusHypenLength > V...
validate(control: FormControl) { if (!control.value) { return Promise.resolve(null);
random_line_split
slotNameValidator.ts
import { FunctionAppService } from 'app/shared/services/function-app.service'; import { PortalResources } from './../models/portal-resources'; import { Validations, Regex } from './../models/constants'; import { Injector } from '@angular/core/src/core'; import { ArmObj } from './../models/arm/arm-obj'; import { Transla...
implements Validator { private _ts: TranslateService; private _functionAppService: FunctionAppService; constructor(injector: Injector, private _siteId: string) { this._ts = injector.get(TranslateService); this._functionAppService = injector.get(FunctionAppService); } validate(control: FormControl) ...
SlotNameValidator
identifier_name
section_table.rs
} else if idx as u64 <= 0xfff_fff_fff { // 64^6 - 1 self.name[0] = b'/'; self.name[1] = b'/'; for i in 0..6 { let rem = (idx % 64) as u8; idx /= 64; let c = match rem { 0..=25 => b'A' + rem, ...
{ let mut section = SectionTable::default(); for &(offset, name) in [ (0usize, b"/0\0\0\0\0\0\0"), (1, b"/1\0\0\0\0\0\0"), (9_999_999, b"/9999999"), (10_000_000, b"//AAmJaA"), #[cfg(target_pointer_width = "64")] (0xfff_fff_fff, b"//...
identifier_body
section_table.rs
26..=51 c - b'a' + 26 } else if b'0' <= c && c <= b'9' { // 52..=61 c - b'0' + 52 } else if c == b'+' { // 62 62 } else if c == b'/' { // 63 63 } else { return Err(()); }; val ...
Ok(()) } else if idx as u64 <= 0xfff_fff_fff { // 64^6 - 1 self.name[0] = b'/'; self.name[1] = b'/'; for i in 0..6 { let rem = (idx % 64) as u8; idx /= 64; let c = match rem { 0..=25 ...
{ // 10^7 - 1 // write!(&mut self.name[1..], "{}", idx) without using io::Write. // We write into a temporary since we calculate digits starting at the right. let mut name = [0; 7]; let mut len = 0; if idx == 0 { name[6] = b'0'; ...
conditional_block
section_table.rs
26..=51 c - b'a' + 26 } else if b'0' <= c && c <= b'9' { // 52..=61 c - b'0' + 52 } else if c == b'+' { // 62
} else if c == b'/' { // 63 63 } else { return Err(()); }; val = val * 64 + v as usize; } Ok(val) } impl SectionTable { pub fn parse( bytes: &[u8], offset: &mut usize, string_table_offset: usize, ) -> error::Res...
62
random_line_split
section_table.rs
26..=51 c - b'a' + 26 } else if b'0' <= c && c <= b'9' { // 52..=61 c - b'0' + 52 } else if c == b'+' { // 62 62 } else if c == b'/' { // 63 63 } else { return Err(()); }; val ...
(_ctx: &scroll::Endian) -> usize { SIZEOF_SECTION_TABLE } } impl ctx::TryIntoCtx<scroll::Endian> for SectionTable { type Error = error::Error; fn try_into_ctx(self, bytes: &mut [u8], ctx: scroll::Endian) -> Result<usize, Self::Error> { let offset = &mut 0; bytes.gwrite(&self.name[.....
size_with
identifier_name
mod.rs
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CNDTR2 { #[doc = r" Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R...
#[doc = r" Value of the field"] pub struct NDTR { bits: u16, } impl NDTR { #[doc = r" Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u16 { self.bits } } #[doc = r" Proxy"] pub struct _NDTW<'a> { w: &'a mut W, } impl<'a> _NDTW<'a> { #[doc = r" Writes raw bits...
random_line_split
mod.rs
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CNDTR2 { #[doc = r" Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R...
<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Val...
write
identifier_name
mod.rs
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::CNDTR2 { #[doc = r" Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R...
#[doc = r" Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { ...
{ let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); }
identifier_body
__init__.py
lightweight class library designed to support the following tasks: - Data interchange and preprocessing between pathway databases and analysis software. - Quick prototyping of pathway analysis algorithms The basic object in the Bio.Pathway model is Interaction, which represents an arbitrary interaction between any...
def reverse(self): """Returns a new Reaction that is the reverse of self.""" reactants = {} for r in self.reactants: reactants[r] = - self.reactants[r] return Reaction(reactants, self.catalysts, self.reversible, self.data) def species(self):...
return substrates + " --> " + products
conditional_block
__init__.py
lightweight class library designed to support the following tasks: - Data interchange and preprocessing between pathway databases and analysis software. - Quick prototyping of pathway analysis algorithms The basic object in the Bio.Pathway model is Interaction, which represents an arbitrary interaction between any...
(self, reactants={}, catalysts=[], reversible=0, data=None): """Initializes a new Reaction object.""" # enforce invariants on reactants: self.reactants = reactants.copy() # loop over original, edit the copy for r, value in reactants.items(): if value ...
__init__
identifier_name
__init__.py
lightweight class library designed to support the following tasks: - Data interchange and preprocessing between pathway databases and analysis software. - Quick prototyping of pathway analysis algorithms The basic object in the Bio.Pathway model is Interaction, which represents an arbitrary interaction between any...
def __str__(self): """Returns a string representation of self.""" substrates = "" products = "" all_species = sorted(self.reactants) for species in all_species: stoch = self.reactants[species] if stoch < 0: # species is a substrate: ...
",".join(map(repr, [self.reactants, self.catalysts, self.data, self.reversible])) + ")"
random_line_split
__init__.py
lightweight class library designed to support the following tasks: - Data interchange and preprocessing between pathway databases and analysis software. - Quick prototyping of pathway analysis algorithms The basic object in the Bio.Pathway model is Interaction, which represents an arbitrary interaction between any...
def remove_reaction(self, reaction): """Removes reaction from self.""" self.__reactions.remove(reaction) def reactions(self): """Returns a list of the reactions in this system. Note the order is arbitrary! """ # TODO - Define __lt__ so that Reactions can be so...
"""Adds reaction to self.""" self.__reactions.add(reaction)
identifier_body
ReactBrowserEventEmitter.js
of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work th...
/** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * ReactBrowserEventEmitter.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = merge(ReactE...
{ // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[moun...
identifier_body
ReactBrowserEventEmitter.js
of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work th...
topKeyPress: 'keypress', topKeyUp: 'keyup', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topScroll: 'scroll', topSelectionChange: 'selectionchange', topTextInput: 'textInput', topTouchCancel: '...
random_line_split
ReactBrowserEventEmitter.js
of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work th...
(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListen...
getListeningForDocument
identifier_name
lint-ctypes.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 ...
() { }
main
identifier_name
lint-ctypes.rs
// 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 http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![deny(ctypes)] e...
// 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. //
random_line_split
lint-ctypes.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 ...
{ }
identifier_body
utils.js
++) { if (i===8 || i===13 || i===18 || i===23) { uuid[i] = '-'; } else if (i===14) { uuid[i] = '4'; } else { if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; r = rnd & 0xf; rnd = rnd >> 4; uuid...
return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+'T' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds())+'Z' ; }; var _daynames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; var _monnames = ['Jan', 'Feb', 'Mar', ...
{ return n<10 ? '0'+n : n; }
identifier_body
utils.js
++) { if (i===8 || i===13 || i===18 || i===23) { uuid[i] = '-'; } else if (i===14) { uuid[i] = '4'; } else { if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; r = rnd & 0xf; rnd = rnd >> 4; uuid...
var rv = {}; for (var i = 0; i < array.length; i++) { if (array[i] === undefined) { continue; } rv[array[i]] = true; } return rv; }; exports.sort_keys = function (obj) { return Object.keys(obj).sort(); }; exports.uniq = function (arr) { var out = []; var o = 0; for (va...
{ throw "arguments to to_object must be a string or array"; }
conditional_block
utils.js
i++) { if (i===8 || i===13 || i===18 || i===23) { uuid[i] = '-'; } else if (i===14) { uuid[i] = '4'; } else { if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; r = rnd & 0xf; rnd = rnd >> 4; uu...
out += '=\n' + str[i]; cur_length = 1; } } } return out; }; exports.node_min = function (min, cur) { var wants = min.split('.'); var has = (cur || process.version.substring(1)).split('.'); for (var i=0; i<=3; i++) { // note use of unary ...
if ((i === (str.length - 1)) || (str[i+1] === '\n')) { out += str[i]; } else {
random_line_split
utils.js
++) { if (i===8 || i===13 || i===18 || i===23) { uuid[i] = '-'; } else if (i===14) { uuid[i] = '4'; } else { if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0; r = rnd & 0xf; rnd = rnd >> 4; uuid...
(n) { return n<10 ? '0'+n : n; } return d.getUTCFullYear()+'-' + pad(d.getUTCMonth()+1)+'-' + pad(d.getUTCDate())+'T' + pad(d.getUTCHours())+':' + pad(d.getUTCMinutes())+':' + pad(d.getUTCSeconds())+'Z' ; }; var _daynames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; var _m...
pad
identifier_name
assets.py
""" Asset compilation and collection. """ from __future__ import print_function import argparse from paver.easy import sh, path, task, cmdopts, needs, consume_args, call_task from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler import glob import traceback from .utils.envs imp...
def on_modified(self, event): print('\tCHANGED:', event.src_path) try: process_xmodule_assets() except Exception: # pylint: disable=W0703 traceback.print_exc() def theme_sass_paths(): """ Return the a list of paths to the theme's sass assets, or an em...
""" register files with observer """ observer.schedule(self, 'common/lib/xmodule/', recursive=True)
identifier_body
assets.py
""" Asset compilation and collection. """ from __future__ import print_function import argparse from paver.easy import sh, path, task, cmdopts, needs, consume_args, call_task from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler import glob import traceback from .utils.envs imp...
(args): """ Compile CoffeeScript and Sass, then collect static assets. """ parser = argparse.ArgumentParser(prog='paver update_assets') parser.add_argument( 'system', type=str, nargs='*', default=['lms', 'studio'], help="lms or studio", ) parser.add_argument( '--setti...
update_assets
identifier_name
assets.py
""" Asset compilation and collection. """ from __future__ import print_function import argparse from paver.easy import sh, path, task, cmdopts, needs, consume_args, call_task from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler import glob import traceback from .utils.envs imp...
if args.watch: call_task('watch_assets', options={'background': not args.debug})
compile_sass(args.debug) if args.collect: collect_assets(args.system, args.settings)
random_line_split
assets.py
""" Asset compilation and collection. """ from __future__ import print_function import argparse from paver.easy import sh, path, task, cmdopts, needs, consume_args, call_task from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler import glob import traceback from .utils.envs imp...
def on_modified(self, event): print('\tCHANGED:', event.src_path) try: compile_sass() except Exception: # pylint: disable=W0703 traceback.print_exc() class XModuleSassWatcher(SassWatcher): """ Watches for sass file changes """ ignore_directories =...
observer.schedule(self, dirname, recursive=True)
conditional_block
IconButton.tsx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
interface IconButtonProps { icon: JSX.Element; label?: string; onClick: MouseEventHandler<HTMLDivElement>; } const StyledDiv = styled.div` display: flex; align-items: center; color: ${({ theme }) => theme.colors.grayscale.base}; &:hover { color: ${({ theme }) => theme.colors.primary.base}; } `; c...
import React, { MouseEventHandler } from 'react'; import { styled } from '@superset-ui/core';
random_line_split
oauth_app.py
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any la...
@transaction.atomic def post(self, request): with self._handle_exception(request): name = request.data['name'] username = request.user.username if (OauthApp.objects.filter(name=name).exists()): e_msg = ('application with name: %s already exists.' % n...
if ('name' in self.kwargs): self.paginate_by = 0 try: return OauthApp.objects.get(name=self.kwargs['name']) except: return [] return OauthApp.objects.all()
identifier_body
oauth_app.py
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any la...
return OauthApp.objects.all() @transaction.atomic def post(self, request): with self._handle_exception(request): name = request.data['name'] username = request.user.username if (OauthApp.objects.filter(name=name).exists()): e_msg = ('applicat...
self.paginate_by = 0 try: return OauthApp.objects.get(name=self.kwargs['name']) except: return []
conditional_block
oauth_app.py
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any la...
from storageadmin.exceptions import RockStorAPIException from storageadmin.util import handle_exception class OauthAppView(rfc.GenericView): serializer_class = OauthAppSerializer def get_queryset(self, *args, **kwargs): if ('name' in self.kwargs): self.paginate_by = 0 try: ...
from django.db import transaction from oauth2_provider.models import Application as OauthApplication from storageadmin.models import (OauthApp, User) from storageadmin.serializers import OauthAppSerializer import rest_framework_custom as rfc
random_line_split
oauth_app.py
""" Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com> This file is part of RockStor. RockStor is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any la...
(rfc.GenericView): serializer_class = OauthAppSerializer def get_queryset(self, *args, **kwargs): if ('name' in self.kwargs): self.paginate_by = 0 try: return OauthApp.objects.get(name=self.kwargs['name']) except: return [] ret...
OauthAppView
identifier_name
api.ts
(req, file, cb) { const userId = _.get(req, 'params.userId') || 'anonymous' const ext = path.extname(file.originalname) cb(undefined, `${userId}_${new Date().getTime()}${ext}`) } }) let upload = multer({ storage: diskStorage }) if (globalConfig.uploadsUseS3) { /* You can overrid...
filename
identifier_name
api.ts
const USER_ID_MAX_LENGTH = 40 const MAX_MESSAGE_HISTORY = 100 const SUPPORTED_MESSAGES = [ 'text', 'quick_reply', 'form', 'login_prompt', 'visit', 'request_start_conversation', 'postback', 'voice' ] const WEBCHAT_CUSTOM_ID_KEY = 'webchatCustomId' type ChatRequest = BPRequest & { visitorId: string ...
const ERR_MSG_TYPE = '`type` is required and must be valid' const ERR_CONV_ID_REQ = '`conversationId` is required and must be valid' const ERR_BAD_LANGUAGE = '`language` is required and must be valid' const ERR_BAD_CONV_ID = "The conversation ID doesn't belong to that user" const ERR_BAD_USER_SESSION_ID = 'session id i...
random_line_split
api.ts
} = req.params const { conversationId, webSessionId } = req.body || {} req.visitorId = await bp.realtime.getVisitorIdFromGuestSocketId(webSessionId) if (!req.visitorId) { return next(ERR_BAD_USER_SESSION_ID) } if (!userIdIsValid(req.visitorId)) { return next(ERR_USER_ID_INVALID) }...
{ const config = await bp.config.getModuleConfigForBot('channel-web', req.botId) if (payload.type === 'voice') { if (_.isEmpty(payload.audio)) { throw new Error('Voices messages must contain an audio buffer') } } else if ( (!payload.text || !_.isString(payload.text) || payload.tex...
identifier_body
api.ts
= (options: { convoIdRequired?: boolean } = {}) => async ( req: ChatRequest, _res: Response, next: NextFunction ) => { const { botId } = req.params const { conversationId, webSessionId } = req.body || {} req.visitorId = await bp.realtime.getVisitorIdFromGuestSocketId(webSessionId) if (!r...
if (options.convoIdRequired && req.conversationId === undefined) { return next(ERR_CONV_ID_REQ) } req.botId = botId req.userId = userId next() } const getRecent = async (messaging: MessagingClient, userId: string) => { const convs = await messaging.listConversations(userId, 1) ...
{ let conversation: Conversation try { conversation = await req.messaging.getConversation(conversationId) } catch {} if (!conversation || !userId || conversation.userId !== userId) { return next(ERR_BAD_CONV_ID) } req.conversationId = conversationId }
conditional_block
4_traitsbounds_mistake1.rs
/* Writing a function which adds 2 to every element of vector and a function to multiply 2 to every element of the vector */ /* NOTES: OWNERSHIP AND BORROW RULES 1. Only one owner at a time 2. Only 1 active mutable borrow at a time 3. Every other borrow after a shared borrow should be a shared borrow...
} fn vec_add<T: Arith>(vec: &mut Vec<T>){ for e in vec.iter_mut(){ /* e is of type &mut i32. But you can give it to print() which expects i32 because rust derefs it implicitly */ e.print(); e.add(5); } } fn main(){ println!("Hello World"); let mut vec: Vec<i32> = vec...
random_line_split
4_traitsbounds_mistake1.rs
/* Writing a function which adds 2 to every element of vector and a function to multiply 2 to every element of the vector */ /* NOTES: OWNERSHIP AND BORROW RULES 1. Only one owner at a time 2. Only 1 active mutable borrow at a time 3. Every other borrow after a shared borrow should be a shared borrow...
(self, b: i32) -> i32{ self + b } fn mult(self, b: Self) -> Self{ self * b } fn print(self) { println!("Val = {}", self); } } fn vec_add<T: Arith>(vec: &mut Vec<T>){ for e in vec.iter_mut(){ /* e is of type &mut i32. But you can give it to print() which...
add
identifier_name
4_traitsbounds_mistake1.rs
/* Writing a function which adds 2 to every element of vector and a function to multiply 2 to every element of the vector */ /* NOTES: OWNERSHIP AND BORROW RULES 1. Only one owner at a time 2. Only 1 active mutable borrow at a time 3. Every other borrow after a shared borrow should be a shared borrow...
fn main(){ println!("Hello World"); let mut vec: Vec<i32> = vec![1,2,3,4,5]; vec_add(&mut vec); } /* What's the mistake with e.add(5) which is throwing below error. Isn't 'b:Self' of type i32 for the current example <anon>:35:15: 35:16 error: mismatched types: expected `T`, found `_` (expected ty...
{ for e in vec.iter_mut(){ /* e is of type &mut i32. But you can give it to print() which expects i32 because rust derefs it implicitly */ e.print(); e.add(5); } }
identifier_body
001.js
Allah, Tuhan semesta alam.", "japanese": "2. \u0026#19975;\u0026#26377;\u0026#12398;\u0026#20027;\u0026#65292;\u0026#12450;\u0026#12483;\u0026#12521;\u0026#12540;\u0026#12395;\u0026#12371;\u0026#12381;\u0026#20961;\u0026#12390;\u0026#12398;\u0026#31216;\u0026#35715;\u0026#12354;\u0026#12428;\u0026#65292;", ...
"korean": "4. 심판의 날을 주관하시도다", "chinese": "4. 報應日的主。", "tafsir": "٤. أي الجزاء وهو يوم القيامة ، وخص بالذكر لأنه لا ملك ظاهرًا فيه لأحد إلا الله تعالى بدليل {لمن الملك اليوم؟ لله} ومن قرأ مالك فمعناه الأمر كله في يوم القيامة أو هو موصوف بذلك دائمًا {كغافر الذنب} فصح وقوعه صفة لمعرفة.", "russia...
"japanese": "4. \u0026#26368;\u0026#24460;\u0026#12398;\u0026#23529;\u0026#12365;\u0026#12398;\u0026#26085;\u0026#12398;\u0026#20027;\u0026#23472;\u0026#32773;\u0026#12395;\u0026#12290;",
random_line_split
fn.rs
// Function that returns a boolean value fn is_divisible_by(lhs: uint, rhs: uint) -> bool { // Corner case, early return if rhs == 0 { return false;
// This is an expression, the `return` keyword is not necessary here lhs % rhs == 0 } // Functions that "don't" return a value, actually return the unit type `()` fn fizzbuzz(n: uint) -> () { if is_divisible_by(n, 15) { println!("fizzbuzz"); } else if is_divisible_by(n, 3) { println!("...
}
random_line_split
fn.rs
// Function that returns a boolean value fn is_divisible_by(lhs: uint, rhs: uint) -> bool { // Corner case, early return if rhs == 0 { return false; } // This is an expression, the `return` keyword is not necessary here lhs % rhs == 0 } // Functions that "don't" return a value, actually re...
(n: uint) { for n in range(1, n + 1) { fizzbuzz(n); } } fn main() { fizzbuzz_to(100); }
fizzbuzz_to
identifier_name
fn.rs
// Function that returns a boolean value fn is_divisible_by(lhs: uint, rhs: uint) -> bool { // Corner case, early return if rhs == 0 { return false; } // This is an expression, the `return` keyword is not necessary here lhs % rhs == 0 } // Functions that "don't" return a value, actually re...
} // When a function returns `()`, the return type can be omitted from the // signature fn fizzbuzz_to(n: uint) { for n in range(1, n + 1) { fizzbuzz(n); } } fn main() { fizzbuzz_to(100); }
{ println!("{}", n); }
conditional_block
fn.rs
// Function that returns a boolean value fn is_divisible_by(lhs: uint, rhs: uint) -> bool { // Corner case, early return if rhs == 0 { return false; } // This is an expression, the `return` keyword is not necessary here lhs % rhs == 0 } // Functions that "don't" return a value, actually re...
fn main() { fizzbuzz_to(100); }
{ for n in range(1, n + 1) { fizzbuzz(n); } }
identifier_body
thisInInnerFunctions.js
//// [thisInInnerFunctions.ts] class Foo { x = "hello"; bar() { function inner() { this.y = "hi"; // 'this' should be not type to 'Foo' either var f = () => this.y; // 'this' should be not type to 'Foo' either } } } function test() { var x = () => { (()...
}
var x = function () { (function () { return _this; })(); _this; };
random_line_split
thisInInnerFunctions.js
//// [thisInInnerFunctions.ts] class
{ x = "hello"; bar() { function inner() { this.y = "hi"; // 'this' should be not type to 'Foo' either var f = () => this.y; // 'this' should be not type to 'Foo' either } } } function test() { var x = () => { (() => this)(); this; }; } /...
Foo
identifier_name
thisInInnerFunctions.js
//// [thisInInnerFunctions.ts] class Foo { x = "hello"; bar() { function inner() { this.y = "hi"; // 'this' should be not type to 'Foo' either var f = () => this.y; // 'this' should be not type to 'Foo' either } } } function test() { var x = () => { (()...
Foo.prototype.bar = function () { function inner() { var _this = this; this.y = "hi"; // 'this' should be not type to 'Foo' either var f = function () { return _this.y; }; // 'this' should be not type to 'Foo' either } }; return Foo; }()); funct...
{ this.x = "hello"; }
identifier_body
routes.js
/** * Created by andyf on 4/14/2017. */ //------------------------------------------// //------------------ROUTES------------------// //------------------------------------------// var multer = require("multer"); var express = require("express"); var app = express(); var multer = require("multer"); var m...
(req, res, next) { if(req.isAuthenticated()){ return next(); } res.redirect('/login'); }
isLoggedIn
identifier_name
routes.js
/** * Created by andyf on 4/14/2017. */ //------------------------------------------// //------------------ROUTES------------------// //------------------------------------------// var multer = require("multer"); var express = require("express"); var app = express(); var multer = require("multer"); var m...
}); app.get('/admin', function(req,res) { res.sendfile('app/admin.html'); }); app.get('/users', function(req,res){ res.json(req.user); // Find some documents // User.find(function(err, docs) { // console.log("Found the following r...
{ res.sendfile('app/index.html'); }
conditional_block
routes.js
/** * Created by andyf on 4/14/2017. */ //------------------------------------------// //------------------ROUTES------------------// //------------------------------------------// var multer = require("multer"); var express = require("express"); var app = express(); var multer = require("multer"); var m...
{ if(req.isAuthenticated()){ return next(); } res.redirect('/login'); }
identifier_body