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 |
|---|---|---|---|---|
script.js | send too many ajax requests
*/
function addRowToTable(action, name, instructions) | 'src', 'picture.php?' + $.param({'medicineName': name})
);
newElement.children('td').eq(0).append(pictureElement);
pictureElement.ready(function () {
pictureElement.height(pictureElement.width());
});
} else if (action === "update") {
row = '... | {
'use strict';
var htmlName, newElement, pictureElement, medicineName, row;
htmlName = JSON.stringify("medicine_" + name);
console.log(name, instructions);
if (action === "insert") {
newElement = $("<tr name=" + htmlName + ">").append(
$('<td/>').text(name),
$('... | identifier_body |
script.js | send too many ajax requests
*/
function | (action, name, instructions) {
'use strict';
var htmlName, newElement, pictureElement, medicineName, row;
htmlName = JSON.stringify("medicine_" + name);
console.log(name, instructions);
if (action === "insert") {
newElement = $("<tr name=" + htmlName + ">").append(
$('<td/>'... | addRowToTable | identifier_name |
script.js | send too many ajax requests
*/
function addRowToTable(action, name, instructions) {
'use strict';
var htmlName, newElement, pictureElement, medicineName, row;
htmlName = JSON.stringify("medicine_" + name);
console.log(name, instructions);
if (action === "insert") {
newElement = $("<tr... |
});
/*
setTimeout(
function () {nameElement.trigger("input");},
0
);
*/
$('div#searchTable').height($('div#formDiv').height());
//Ajax call to getAll.php to get all medicine entries in database
request = $.ajax({
url: 'getAll.php',
type: 'p... | {
$("tr[name='google']").css("display", "none");
} | conditional_block |
script.js | 't send too many ajax requests
*/
function addRowToTable(action, name, instructions) {
'use strict';
var htmlName, newElement, pictureElement, medicineName, row;
htmlName = JSON.stringify("medicine_" + name);
console.log(name, instructions);
if (action === "insert") {
newElement = $("<... | // Serialize the data in the form
//serializedData = form.serialize();
console.log(inputs);
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be seria... |
inputs = form.find("input, select, button, textarea"); | random_line_split |
fourier.py | the paper
"Rethinking Attention with Performers" https://arxiv.org/pdf/2009.14794.pdf
and the traditional random Fourier features that approximate the RBF kernel.
"""
from math import sqrt, log
from typing import Optional
from einops import repeat
import torch
from .base import Kernel
def orthogonal_random_matrix... | else:
raise ValueError(f"Invalid scaling {scaling}")
return torch.diag(multiplier) @ final_matrix
def orthogonal_matrix_chunk(
cols: int,
device: torch.device = None
) -> torch.Tensor:
unstructured_block = torch.randn((cols, cols), device=device)
q, _ = torch.qr(unstructured_... | num_full_blocks = int(num_rows / num_columns)
block_list = []
for _ in range(num_full_blocks):
q = orthogonal_matrix_chunk(num_columns, device)
block_list.append(q)
remaining_rows = num_rows - (num_full_blocks * num_columns)
if remaining_rows > 0:
q = orthogonal_matrix_chunk(n... | identifier_body |
fourier.py | paper
"Rethinking Attention with Performers" https://arxiv.org/pdf/2009.14794.pdf
and the traditional random Fourier features that approximate the RBF kernel.
"""
from math import sqrt, log
from typing import Optional
from einops import repeat
import torch
from .base import Kernel
def orthogonal_random_matrix_(
... |
else:
raise ValueError(f"Invalid scaling {scaling}")
return torch.diag(multiplier) @ final_matrix
def orthogonal_matrix_chunk(
cols: int,
device: torch.device = None
) -> torch.Tensor:
unstructured_block = torch.randn((cols, cols), device=device)
q, _ = torch.qr(unstructured_... | multiplier = sqrt((float(num_columns))) * torch.ones((num_rows,), device=device) | conditional_block |
fourier.py | the paper
"Rethinking Attention with Performers" https://arxiv.org/pdf/2009.14794.pdf
and the traditional random Fourier features that approximate the RBF kernel.
"""
from math import sqrt, log
from typing import Optional
from einops import repeat
import torch
from .base import Kernel
def orthogonal_random_matrix... | query_dimensions: int, The input query dimensions in order to sample
the noise matrix
n_dims: int, The size of the feature map (default: query_dimensions)
softmax_temp: float, A normalizer for the dot products that is
multiplied to the input feature... | passed in `kernel_fn`.
Arguments
--------- | random_line_split |
fourier.py | paper
"Rethinking Attention with Performers" https://arxiv.org/pdf/2009.14794.pdf
and the traditional random Fourier features that approximate the RBF kernel.
"""
from math import sqrt, log
from typing import Optional
from einops import repeat
import torch
from .base import Kernel
def orthogonal_random_matrix_(
... | (
self,
device: Optional[torch.device] = "cpu"
):
return orthogonal_random_matrix_(
self.kernel_size,
self.head_size,
scaling=self.ortho_scaling,
device=device
)
def forward(
self,
x: torch.Tensor,... | new_kernel | identifier_name |
differentiation.go | 5. Traverse the graph from output towards input. On each visit, perform the symbolic differentiation
//
// For most cases, Grad() should be used instead of Backpropagate(), as Grad() performs several checks which would be the general use case, before calling Backpropagate()
func Backpropagate(outputs, gradOutputs, wrt ... | {
deriv.derivOf = append(deriv.derivOf, of)
of.deriv = deriv
} | identifier_body | |
differentiation.go | list of Nodes that are affected by differentiating output.
// Given a list of WRTs, we want to find a list of nodes that will be affected when backpropagating.
func backwardDiffAnalysis(wrt, sortedNodes Nodes) (retVal NodeSet, err error) {
symdiffLogf("Backwards analysis")
enterLogScope()
defer leaveLogScope()
if... |
symdiffLogf("reduced to... %x", n.ID())
// node.derives = append(node.derives, n)
n.derivOf = append(n.derivOf, node)
node.deriv = n
nodeGradMap[node] = Nodes{n}
// }
} else if len(nodeGradMap[node]) == 1 {
deriv := nodeGradMap[node][0]
deriv.deriv | {
leaveLogScope()
return nil, SymDiffError{
single: node,
nodes: nodeGradMap[node],
gradMap: nodeGradMap,
err: errors.Wrap(err, "ReduceAdd failed during differentiation"),
}
} | conditional_block |
differentiation.go | list of Nodes that are affected by differentiating output.
// Given a list of WRTs, we want to find a list of nodes that will be affected when backpropagating.
func backwardDiffAnalysis(wrt, sortedNodes Nodes) (retVal NodeSet, err error) {
symdiffLogf("Backwards analysis")
enterLogScope()
defer leaveLogScope()
if... | single: node,
nodes: nodeGradMap[node],
gradMap: nodeGradMap,
err: errors.Wrap(err, "ReduceAdd failed during differentiation"),
}
}
symdiffLogf("reduced to... %x", n.ID())
// node.derives = append(node.derives, n)
n.derivOf = append(n.derivOf, node)
node.deriv = n
nodeG... | leaveLogScope()
return nil, SymDiffError{ | random_line_split |
differentiation.go | (outputs, sortedNodes Nodes) (retVal NodeSet, err error) {
symdiffLogf("Forward analysis. Already sorted?")
enterLogScope()
defer leaveLogScope()
if !outputs.AllSameGraph() {
return nil, errors.New("The supplied output Nodes are not the same graph")
}
diffSet := outputs.mapSet()
symdiffLogf("Diff Set: %v", ... | forwardDiffAnalysis | identifier_name | |
TypedAction.ts | .g. to a Redux `Store.dispatch`.
*
* The true benefit of TypedActions come on the Reducer-side. See
* the TypedReducer class for more on creating a TypedAction-savvy Reducer for Redux.
*
* Conforms to Flux Standard Action recommendations.
*
* @see TypedActionDef#create
*/
export interface TypedAction<T, E exten... | * All Definitions for a Redux-enabled application MUST have unique strings.
*/
export interface NoPayloadDefinition<E extends string> {
/**
* Creates an Action of this type (and no payload).
* Functionally equivalent to the explicit NoPayloadDefinition.create().
*/
(): { type: E; payload:... | *
* - Definitions should be used to create Actions.
* - Definitions can be used to identify an Action, based on its own `type`.
* | random_line_split |
TypedAction.ts | **DEPRECATED**: As of Redoodle 2.5.0, consumers should prefer `defineAction()`
* over than `TypedAction.define()`. See https://github.com/palantir/redoodle/issues/35
*
* Options to TypedAction.define().
*
* @deprecated
*/
export interface DefineOptions<T> {
/**
* A function used to validat... | {
throw new Error(`'${type}' validation failed`);
} | conditional_block | |
TypedAction.ts | /**
* **DEPRECATED**: As of Redoodle 2.5.0, consumers should prefer `defineAction()`
* over than `TypedAction.define()`. See https://github.com/palantir/redoodle/issues/35
*
* One of the core functions of Redoodle, `TypedAction.define` creates a Definition
* to manage all Redux actions of a specific ty... | createNoPayloadDefinition | identifier_name | |
TypedAction.ts | . to a Redux `Store.dispatch`.
*
* The true benefit of TypedActions come on the Reducer-side. See
* the TypedReducer class for more on creating a TypedAction-savvy Reducer for Redux.
*
* Conforms to Flux Standard Action recommendations.
*
* @see TypedActionDef#create
*/
export interface TypedAction<T, E extends... |
/**
* **DEPRECATED**: As of Redoodle 2.5.0, consumers should prefer `defineAction()`
* over than `TypedAction.define()`. See https://github.com/palantir/redoodle/issues/35
*
* Similar to TypedAction.define, creates a NoPayloadDefinition for the given Action type
* string, like `"example::clear_foo"`.... | {
return <T>(options?: DefineOptions<T>) => {
if (
process.env.NODE_ENV !== "production" &&
options !== undefined &&
options.validate !== undefined
) {
return createDefinitionWithValidator<E, T>(type, options.validate);
} else {
return createDefinition<E, T>... | identifier_body |
time-sentiment.component.ts | renderedChart = false;
notDataWarn = false;
appliedFilter = false;
chartHeight = 300;
chartRange1;
chartRange2;
chartRangeFilter1;
chartRangeFilter2;
constructor(private chartService: ChartService, private _element: ElementRef) { }
ngOnInit() {
this.sentimentLineChart = dc.lineChart('#sentiment... | {
colorArray.push('#DDDDDD');
} | conditional_block | |
time-sentiment.component.ts | styleUrls: ['./time-sentiment.component.scss']
})
export class TimeSentimentComponent implements OnInit {
aggrView = true;
compView = false;
data: any[];
cfilter: CrossFilter.CrossFilter<{}>;
dimension: CrossFilter.Dimension<{}, Date>;
sentGroups: { group: CrossFilter.Group<{}, Date, any>, sent: string}[]... | random_line_split | ||
time-sentiment.component.ts | sentimentLineChart: dc.LineChart;
renderedChart = false;
notDataWarn = false;
appliedFilter = false;
chartHeight = 300;
chartRange1;
chartRange2;
chartRangeFilter1;
chartRangeFilter2;
constructor(private chartService: ChartService, private _element: ElementRef) { }
ngOnInit() | // Collapsible view
this.chartService.GetChartMode().subscribe(mode => {
if (this.data && this.data.length > 0) {
if (mode && mode === 'small') {
this.chartHeight = 85;
this.renderChart();
} else if (mode && mode === 'big') {
this.chartHeight = 300;
... | {
this.sentimentLineChart = dc.lineChart('#sentimentChartLine');
this.chartService.GetData().subscribe((data) => { this.data = data; });
// Crossfilter
this.chartService.getCrossfilter().subscribe((filter) => {
this.cfilter = filter;
this.setDimension();
if (this.data && this.data.len... | identifier_body |
time-sentiment.component.ts | implements OnInit {
aggrView = true;
compView = false;
data: any[];
cfilter: CrossFilter.CrossFilter<{}>;
dimension: CrossFilter.Dimension<{}, Date>;
sentGroups: { group: CrossFilter.Group<{}, Date, any>, sent: string}[];
sentimentLineChart: dc.LineChart;
renderedChart = false;
notDataWarn = false;
... | TimeSentimentComponent | identifier_name | |
text.rs | /// as """.
///
pub(crate) fn escape(input: &str) -> String {
let mut result = String::with_capacity(input.len());
for c in input.chars() {
match c {
XML_ESC_AMP_CHAR => result.push_str(&to_entity(XML_ESC_AMP_CHAR)),
XML_ESC_APOS_CHAR => result.push_str(&to_entity(XML_ESC_A... | || c == '_'
|| (c >= 'a' && c <= 'z')
|| (c >= '\u{C0}' && c <= '\u{D6}') | random_line_split | |
text.rs | else if let Some(a_match) = capture.name("char") {
let replacement = char_from_entity(a_match.as_str());
(a_match.start(), a_match.end(), replacement)
} else if let Some(a_match) = capture.name("char_hex") {
let replacement = char_from_entity(a_match.as_str())... |
//
// TODO: this does not yet deal with entity references.
//
let replacement = match resolver.resolve(a_match.as_str()) {
None => panic!("unknown entity reference {}", a_match.as_str()),
Some(replacement) => {
... | conditional_block | |
text.rs | xFFFFE-#xFFFFF],
/// [#x10FFFE-#x10FFFF].
/// ```
///
#[allow(dead_code)]
pub(crate) fn is_xml_10_char(c: char) -> bool {
c == '\u{0009}'
|| c == '\u{000A}'
|| c == '\u{000D}'
|| (c >= '\u{0020}' && c <= '\u{D7FF}')
|| (c >= '\u{E000}' && c <= '\u{FFFD}')
|| (c >= '\u{10000}'... | if s == XML_NS_ATTR_SPACE_DEFAULT {
Ok(SpaceHandling::Default)
} else if s == XML_NS_ATTR_SPACE_PRESERVE {
Ok(SpaceHandling::Preserve)
} else {
Err(())
}
}
}
// | identifier_body | |
text.rs | {
c == '\u{09}' || c == '\u{0A}' || c == '\u{0D}' || c == '\u{20}'
}
///
/// ```ebnf
/// NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] |
/// [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] |
/// [#x2C00-#x2FEF... | lize_avalue_entity_resolver() {
| identifier_name | |
ionic-native-map.ts | ");
let userID = localStorage.getItem("userID");
let URL = globalVars.UserAddress(userID);
// console.log(locationExists);
let data = {
alias: this.locationAlias,
address: this.address,
lat: this.lat,
long: this.lng
}
if(this.validate()){
// let loc... | };
this.addMarker(map, this.newLocation); | random_line_split | |
ionic-native-map.ts | available_locations: Array<Object> = [];
newLocation;
marker;
constructor(public navCtrl: NavController,
public navParams: NavParams,
private googleMaps: GoogleMaps,
private platform: Platform,
private geolocation: Geolocation,
private androi... | this.listenToSearchInput();
this.getMapLocation(location, this.latLng);
}
listenToSearchInput() {
this.hide = false;
let location: string;
console.log('location1:', location)
// let searchInput$ = Observable.fromEvent(this.button.nativeElement, 'keyup')
// .map(e => location = e['s... | {
console.log("ngAfterViewInit", this.newLocation);
// this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.ACCESS_FINE_LOCATION).then(
// success => console.log('Permission granted'),
// err => this.androidPermissions.requestPermissions(this.androidPermissions.PERMISSION.ACCES... | identifier_body |
ionic-native-map.ts | : GoogleMaps,
private platform: Platform,
private geolocation: Geolocation,
private androidPermissions: AndroidPermissions,
private alertCtrl: AlertController,
private popoverCtrl: PopoverController,
private mapService: MapService,
... | loadMap | identifier_name | |
ionic-native-map.ts | available_locations: Array<Object> = [];
newLocation;
marker;
constructor(public navCtrl: NavController,
public navParams: NavParams,
private googleMaps: GoogleMaps,
private platform: Platform,
private geolocation: Geolocation,
private androi... |
}
savedButtonClicked(myEvent) {
this.saved = this.saved ? false : true;
setTimeout(()=>{
this.saved = this.saved ? false : true;
}, 200);
let inputs;
this.addressResponse = inputs;
let URL = globalVars.getUsersAddress(this.userID);
this.authService.getCall(U... | {
// let location$ = this.mapService.getJSON(location, this.latLng);
// location$.subscribe(res => console.log)
} | conditional_block |
lib.rs | " BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Parts of this work are derived from the `protoc-rust-grpc` crate by
// Stepan Koltsov <stepan.koltsov@gmail.com>.
//
// Copyright 2016, Stepan Koltsov <stepan.koltsov@gmail.com>.
//
// Licensed under ... | <Input, Output>(input: Input, expected_outputs: Output)
where
Input: AsRef<Path>,
| assert_compile_grpc_protos | identifier_name |
lib.rs | " BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Parts of this work are derived from the `protoc-rust-grpc` crate by
// Stepan Koltsov <stepan.koltsov@gmail.com>.
//
// Copyright 2016, Stepan Koltsov <stepan.koltsov@gmail.com>.
//
// Licensed under ... |
fn normalize<Paths, Bases>(
paths: Paths,
bases: Bases,
) -> CompileResult<(Vec<PathBuf>, Vec<PathBuf>, Vec<PathBuf>)>
where
Paths: IntoIterator,
Paths::Item: AsRef<Path>,
Bases: IntoIterator,
Bases::Item: AsRef<Path>,
{
let absolutized_bases = bases
.into_iter()
.map(absol... | {
let p = path.as_ref();
if p.is_relative() {
match std::env::current_dir() {
Ok(cwd) => Ok(cwd.join(p)),
Err(err) => Err(format_err!(
"Failed to determine CWD needed to absolutize a relative path: {:?}",
err
)),
}
} else {
... | identifier_body |
lib.rs | IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Parts of this work are derived from the `protoc-rust-grpc` crate by
// Stepan Koltsov <stepan.koltsov@gmail.com>.
//
// Copyright 2016, Stepan Koltsov <stepan.koltsov@gmail.com>.
//
// Licensed und... | .as_slice(),
includes: stringified_includes
.iter()
.map(String::as_str)
.collect::<Vec<&str>>()
.as_slice(),
include_imports: true,
})
.context("failed to write descriptor set")?;
let mut serial... | .iter()
.map(String::as_str)
.collect::<Vec<&str>>() | random_line_split |
baselines_utils.py | class SetFromFlat(object):
def __init__(self, var_list, dtype=tf.float32):
assigns = []
shapes = list(map(var_shape, var_list))
total_size = np.sum([intprod(shape) for shape in shapes])
self.theta = theta = tf.placeholder(dtype, [total_size])
start = 0
assigns = []
... | super(SumSegmentTree, self).__init__(
capacity=capacity,
operation=operator.add,
neutral_element=0.0
) | identifier_body | |
baselines_utils.py | else:
feed_dict[inpt] = value
def __call__(self, *args):
assert len(args) <= len(self.inputs), "Too many arguments provided"
feed_dict = {}
# Update the args
for inpt, value in zip(self.inputs, args):
self._feed_input(feed_dict, inpt, value)
# Update... | )
def reduce(self, start=0, end=None): | random_line_split | |
baselines_utils.py | summary_tag=None):
with tf.variable_scope(name):
stride_shape = [1, stride[0], stride[1], 1]
filter_shape = [filter_size[0], filter_size[1], int(x.get_shape()[3]), num_filters]
# there are "num input feature maps * filter height * filter width"
# inputs to each hidden unit
... | (x):
out = x.get_shape().as_list()
assert all(isinstance(a, int) for a in out), \
"shape function assumes that shape is fully known"
return out
def numel(x):
return intprod(var_shape(x))
def intprod(x):
return int(np.prod(x))
def flatgrad(loss, var_list, clip_norm=None):
grads = tf.gr... | var_shape | identifier_name |
baselines_utils.py | summary_tag=None):
with tf.variable_scope(name):
stride_shape = [1, stride[0], stride[1], 1]
filter_shape = [filter_size[0], filter_size[1], int(x.get_shape()[3]), num_filters]
# there are "num input feature maps * filter height * filter width"
# inputs to each hidden unit
... |
self.op = tf.group(*assigns)
def __call__(self, theta):
tf.get_default_session().run(self.op, feed_dict={self.theta: theta})
class GetFlat(object):
def __init__(self, var_list):
self.op = tf.concat(axis=0, values=[tf.reshape(v, [numel(v)]) for v in var_list])
def __call__(self):
... | size = intprod(shape)
assigns.append(tf.assign(v, tf.reshape(theta[start:start + size], shape)))
start += size | conditional_block |
encoder.rs | ::Error> for EncodingError {
fn from(err: io::Error) -> EncodingError {
EncodingError::IoError(err)
}
}
impl From<EncodingError> for io::Error {
fn from(err: EncodingError) -> io::Error {
io::Error::new(io::ErrorKind::Other, (&err as &error::Error).description())
}
}
/// PNG Encoder
pub... | else {
Err(EncodingError::Format("invalid number of frames for an animated PNG".into()))
}
}
pub fn write_header(self) -> Result<Writer<W>> {
Writer::new(self.w, self.info).init()
}
}
impl<W: Write> HasParameters for Encoder<W> {}
impl<W: Write> Parameter<Encoder<W>> for Col... | {
let mut encoder = Encoder::new(w, width, height);
let animation_ctl = AnimationControl { num_frames: frames, num_plays: 0 };
let mut frame_ctl = FrameControl::default();
frame_ctl.width = width;
frame_ctl.height = height;
encoder.info.animation... | conditional_block |
encoder.rs | use self::EncodingError::*;
match *self {
IoError(ref err) => err.description(),
Format(ref desc) => &desc,
}
}
}
impl fmt::Display for EncodingError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
write!(fmt, "{}", (self as ... | fn description(&self) -> &str { | random_line_split | |
encoder.rs | >> {
if frames > 0 {
let mut encoder = Encoder::new(w, width, height);
let animation_ctl = AnimationControl { num_frames: frames, num_plays: 0 };
let mut frame_ctl = FrameControl::default();
frame_ctl.width = width;
frame_ctl.height = height;
... | drop | identifier_name | |
encoder.rs | ::Error> for EncodingError {
fn from(err: io::Error) -> EncodingError {
EncodingError::IoError(err)
}
}
impl From<EncodingError> for io::Error {
fn from(err: EncodingError) -> io::Error |
}
/// PNG Encoder
pub struct Encoder<W: Write> {
w: W,
info: Info,
}
impl<W: Write> Encoder<W> {
pub fn new(w: W, width: u32, height: u32) -> Encoder<W> {
let mut info = Info::default();
info.width = width;
info.height = height;
Encoder { w: w, info: info }
}
pub ... | {
io::Error::new(io::ErrorKind::Other, (&err as &error::Error).description())
} | identifier_body |
conn.rs | Ok(t) => t,
Err(e) => return Err(e)
};
Ok(Connection {
addr: addr,
host: host,
sock: Some(Plain(sock)),
name: name,
term: t
})
}
pub fn status(&mut self) {
self.send_handshake(false);
// Send the... | else if packet_id == 0x2 {
let json = packet.read_string();
debug!("Got chat message: {}", json);
// Let's wrap up the Json so that we can
// deal with it more easily
let j = json::from_str(json).unwrap();
let j = ExtraJSON::new(j);
... | {
let x = packet.read_be_i32().unwrap();
// Need to respond
let mut resp = Packet::new_out(0x0);
resp.write_be_i32(x);
self.write_packet(resp);
// Chat Message
} | conditional_block |
conn.rs | "].list_map(|x| x.string()).concat();
self.term.attr(term::attr::ForegroundColor(term::color::BRIGHT_YELLOW));
self.term.write(bytes!("[Server] "));
self.term.reset();
self.term.write(msg.as_bytes());
self.term.write(bytes!("\n"));
... | {
match *self {
Some(ref mut s) => s.flush(),
None => Err(io::standard_error(io::OtherIoError))
}
} | identifier_body | |
conn.rs | {
addr: SocketAddr,
host: ~str,
sock: Option<Sock>,
name: ~str,
term: term::Terminal<LineBufferedWriter<StdWriter>>
}
impl Connection {
pub fn new(name: ~str, host: ~str, port: u16) -> Result<Connection, ~str> {
// Resolve host
let addr = match addrinfo::get_host_addresses(hos... | Connection | identifier_name | |
conn.rs |
})
}
pub fn status(&mut self) {
self.send_handshake(false);
// Send the status request
self.write_packet(Packet::new_out(0x0));
// and read back the response
let (packet_id, mut packet) = self.read_packet();
// Make sure we got the right response
... |
// write json to stdin and close it
write!(p.stdin.get_mut_ref() as &mut Writer, r#"
\{
"accessToken": "{}", | random_line_split | |
prefix_code.rs | 0f0f) << 4;
v = (v & 0xcccc) >> 2 | (v & 0x3333) << 2;
v = (v & 0xaaaa) >> 1 | (v & 0x5555) << 1;
v
}
pub fn generate_codes(sizes: &[u8], codes: &mut [PrefixCode]) -> bool {
let mut num_codes: [u32, ..MAX_EXPECTED_CODE_SIZE + 1] = [0, ..MAX_EXPECTED_CODE_SIZE + 1];
let mut next_code: [u32, ..MAX_EXPECTED_CODE_SIZ... |
}
}
for p in decoder_table.mut_iter() {
*p = 0xffff;
}
for i in range(0, sizes.len()) {
let s = sizes[i] as uint;
let code = next_code[s];
next_code[s] += 1;
let offset = (code as u16 + dec_first_offset[s]) as uint;
dec_offset_to_sym[offset] = i as u16;
let rev_code = reverse_u16(code) >> (16 ... | {
//return false; // Error, sizes don't add up
fail!("Code sizes don't add up");
} | conditional_block |
prefix_code.rs | (self) -> u16 {
self.s
}
}
pub fn sort_symbols2<'a>(mut first: &'a mut [OrdFreq], mut second: &'a mut [OrdFreq]) -> &'a mut [OrdFreq] {
let mut hist = [0u32, ..256 * 2];
for &s in first.iter() {
let f = s.freq();
hist[ (f & 0xff) as uint] += 1;
hist[256 + ((f >> 8) & 0xff) as uint] += 1;
}
l... | sym | identifier_name | |
prefix_code.rs | 0f0f) << 4;
v = (v & 0xcccc) >> 2 | (v & 0x3333) << 2;
v = (v & 0xaaaa) >> 1 | (v & 0x5555) << 1;
v
}
pub fn generate_codes(sizes: &[u8], codes: &mut [PrefixCode]) -> bool {
let mut num_codes: [u32, ..MAX_EXPECTED_CODE_SIZE + 1] = [0, ..MAX_EXPECTED_CODE_SIZE + 1];
let mut next_code: [u32, ..MAX_EXPECTED_CODE_SIZ... |
let mut code = 0u32;
let mut offset = 0u32;
for i in range(1, MAX_EXPECTED_CODE_SIZE + 1) {
next_code[i] = code;
dec_first_offset[i] = offset as u16 - code as u16;
code += num_codes[i];
dec_max_code[i] = code << (16 - i);
code <<= 1;
offset += num_codes[i];
}
dec_max_code[17] = 0x10000;
if code != ... | let mut next_code: [u32, ..MAX_EXPECTED_CODE_SIZE + 1] = [0, ..MAX_EXPECTED_CODE_SIZE + 1];
for &s in sizes.iter() {
num_codes[s as uint] += 1;
} | random_line_split |
fma_utils.py | r.raise_for_status()
tracks = []
artists = []
date_created = []
for track in r.json()['aTracks']:
|
return tracks, artists, date_created
def _get_data(self, dataset, fma_id, fields=None):
url = self.BASE_URL + dataset + 's.json?'
url += dataset + '_id=' + str(fma_id) + '&api_key=' + self.api_key
# print(url)
r = requests.get(url)
r.raise_for_status()
if r.... | tracks.append(track['track_id'])
artists.append(track['artist_name'])
date_created.append(track['track_date_created']) | conditional_block |
fma_utils.py | r.raise_for_status()
tracks = []
artists = []
date_created = []
for track in r.json()['aTracks']:
tracks.append(track['track_id'])
artists.append(track['artist_name'])
date_created.append(track['track_date_created'])
return tracks, arti... | :
def load(self, filepath):
raise NotImplemented()
class RawAudioLoader(Loader):
def __init__(self, sampling_rate=SAMPLING_RATE):
self.sampling_rate = sampling_rate
self.shape = (NB_AUDIO_SAMPLES * sampling_rate // SAMPLING_RATE, )
def load(self, filepath):
return self._lo... | Loader | identifier_name |
fma_utils.py | )
r.raise_for_status()
tracks = []
artists = []
date_created = []
for track in r.json()['aTracks']:
tracks.append(track['track_id'])
artists.append(track['artist_name'])
date_created.append(track['track_date_created'])
return tracks, ar... | return data[fields]
def get_track(self, track_id, fields=None):
return self._get_data('track', track_id, fields)
def get_album(self, album_id, fields=None):
return self._get_data('album', album_id, fields)
def get_artist(self, artist_id, fields=None):
return self._get... | url = self.BASE_URL + dataset + 's.json?'
url += dataset + '_id=' + str(fma_id) + '&api_key=' + self.api_key
# print(url)
r = requests.get(url)
r.raise_for_status()
if r.json()['errors']:
raise Exception(r.json()['errors'])
data = r.json()['dataset'][0]
... | identifier_body |
fma_utils.py | )
r.raise_for_status()
tracks = []
artists = []
date_created = []
for track in r.json()['aTracks']:
tracks.append(track['track_id'])
artists.append(track['artist_name'])
date_created.append(track['track_date_created'])
return tracks, ar... | def create_tree(root_id, node_p, depth):
if depth == 0:
return
children = self.df[self.df['parent'] == root_id]
for child in children.iterrows():
genre_id = child[0]
node_c = create_node(genre_id)
graph.add_edge(... | #name = self.df.at[genre_id, 'title'] + '\n' + str(genre_id)
name = '"{}\n{} / {}"'.format(title, genre_id, ntracks)
return pydot.Node(name)
| random_line_split |
main.rs | .x = 5;
*r.y = 6;
}
assert_eq!(5, point.x);
assert_eq!(6, point.y);
point = Point { x: 0, ..point};
assert_eq!(6, point.y);
struct Color(i32, i32, i32);
let black = Color(17, 0, 0);
let Color(r, _, _) = black;
println!("{}", r);
enum Message {
Quit,
ChangeC... | impl Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * (self.radius * self.radius)
}
fn reference(&self) -> &Circle{
println!("taking self by reference!");
self
}
fn mutable_reference(&mut self) {
println!("taking self by mutable reference!");
}
... | random_line_split | |
main.rs | .x = 5;
*r.y = 6;
}
assert_eq!(5, point.x);
assert_eq!(6, point.y);
point = Point { x: 0, ..point};
assert_eq!(6, point.y);
struct Color(i32, i32, i32);
let black = Color(17, 0, 0);
let Color(r, _, _) = black;
println!("{}", r);
enum Message {
Quit,
ChangeC... | (&self) -> String { format!("string: {}", *self) }
}
fn do_something<T: FooBar>(x: T) {
x.method();
}
let x = 5u8;
let y = "Hello".to_string();
do_something(x);
do_something(y);
fn do_something2(x: &FooBar) {
x.method();
}
let x = 5u8;
//casting
do_something2(&x as &FooBar);
... | method | identifier_name |
main.rs | !("taking self by mutable reference!");
}
fn takes_ownership(self) {
println!("taking ownership of self!");
}
fn new(x: f64, y: f64, radius: f64) -> Circle {
Circle {
x: x,
y: y,
radius: radius,
}
}
}
struct CircleBuilder {
... | Vec::new()
}
}
| identifier_body | |
static.go | {
return err
}
return nil
}
// ValidateHeader validates Header.
// Returns the first error encountered.
func ValidateHeader(header *Header) error {
if header == nil {
return consts.ErrNilHeader
}
tokenType := header.TokenTyp
if tokenType < NoType || tokenType > Jet {
return consts.ErrUnknownTokenType
}
... |
if err := ValidateSecret(secret); err != nil {
return "", err
}
if body.Permission == Admin && header.Alg != Hs512 {
return "", consts.ErrInvalidPermission
}
// Currently supports JWT, JET
if header.TokenTyp != Jwt && header.TokenTyp != Jet {
return "", consts.ErrUnknownTokenType
}
tokenString, err := ge... | {
return "", err
} | conditional_block |
static.go | {
return err
}
return nil
}
// ValidateHeader validates Header.
// Returns the first error encountered.
func ValidateHeader(header *Header) error {
if header == nil {
return consts.ErrNilHeader
}
tokenType := header.TokenTyp
if tokenType < NoType || tokenType > Jet {
return consts.ErrUnknownTokenType
}
... | encodedSignature, err := hashSignature(alg, encodedHeaderBody, secret)
if err != nil {
return "", nil
}
// 5. Build Token Signature = <encoded header>.<encoded body>.<hashed(<encoded header>.<encoded body>)>
var bufferTokenSignature bytes.Buffer
bufferTokenSignature.WriteString(encodedHeaderBody)
bufferTokenSi... | encodedHeaderBody := bufferHeaderBody.String()
// 4. Build <hashed(<encoded header>.<encoded body>)> | random_line_split |
static.go | {
return err
}
return nil
}
// ValidateHeader validates Header.
// Returns the first error encountered.
func ValidateHeader(header *Header) error {
if header == nil {
return consts.ErrNilHeader
}
tokenType := header.TokenTyp
if tokenType < NoType || tokenType > Jet {
return consts.ErrUnknownTokenType
}
... |
func isExpired(timestamp int64) bool {
if timestamp <= 0 || time.Now().UTC().Unix() >= timestamp {
return true
}
return false
}
// NewToken generates token string using a header, body, and secret.
// Return error if an error exists during signing.
func NewToken(header *Header, body *Body, secret *pbauth.Secret)... | {
if secret == nil {
return consts.ErrNilSecret
}
if strings.TrimSpace(secret.Key) == "" {
return consts.ErrEmptySecret
}
createTime := secret.CreatedTimestamp
if createTime == 0 || createTime > time.Now().UTC().Unix() {
return consts.ErrInvalidSecretCreateTimestamp
}
if isExpired(secret.ExpirationTimesta... | identifier_body |
static.go | {
return err
}
return nil
}
// ValidateHeader validates Header.
// Returns the first error encountered.
func ValidateHeader(header *Header) error {
if header == nil {
return consts.ErrNilHeader
}
tokenType := header.TokenTyp
if tokenType < NoType || tokenType > Jet {
return consts.ErrUnknownTokenType
}
... | (header *Header, body *Body, secret *pbauth.Secret) (string, error) {
if err := ValidateHeader(header); err != nil {
return "", err
}
if err := ValidateBody(body); err != nil {
return "", err
}
if err := ValidateSecret(secret); err != nil {
return "", err
}
if body.Permission == Admin && header.Alg != Hs51... | getTokenSignature | identifier_name |
reader.rs | Context {
fn validate(&self) -> Result<()> {
if self.max_concurrency == 0 {
return Err(Error::msg("max concurrency must be at least 1."));
}
Ok(())
}
}
impl ReaderContext {
fn default_reader_threads() -> usize {
1
}
}
/// A given query payload that describe... |
#[derive(Debug, Serialize)]
pub struct QueryResults {
/// The retrieved documents.
pub(crate) hits: Vec<DocumentHit>,
/// The total amount of documents matching the search
count: usize,
/// The amount of time taken to search in seconds.
time_taken: f32,
}
impl QueryResults {
#[inline]
... | impl Default for Sort {
fn default() -> Self {
Self::Desc
}
} | random_line_split |
reader.rs | Context {
fn validate(&self) -> Result<()> {
if self.max_concurrency == 0 {
return Err(Error::msg("max concurrency must be at least 1."));
}
Ok(())
}
}
impl ReaderContext {
fn default_reader_threads() -> usize {
1
}
}
/// A given query payload that describe... | ,
_ => Err(Error::msg("field is not a fast field")),
};
}
let out = match field_type {
FieldType::I64(_) => {
let collector =
collector.custom_score(move |segment_reader: &SegmentReader| {
let reader = segment_reader
... | {
let out: (Vec<(DateTime, DocAddress)>, usize) =
order_and_search(&searcher, field, query, collector, executor)?;
Ok((process_search(&searcher, schema, out.0)?, out.1))
} | conditional_block |
reader.rs | Context {
fn | (&self) -> Result<()> {
if self.max_concurrency == 0 {
return Err(Error::msg("max concurrency must be at least 1."));
}
Ok(())
}
}
impl ReaderContext {
fn default_reader_threads() -> usize {
1
}
}
/// A given query payload that describes how the reader should
/... | validate | identifier_name |
reader.rs | pub(crate) hits: Vec<DocumentHit>,
/// The total amount of documents matching the search
count: usize,
/// The amount of time taken to search in seconds.
time_taken: f32,
}
impl QueryResults {
#[inline]
pub fn len(&self) -> usize {
self.hits.len()
}
}
/// Attaches an order by... | {
let id_field = self.query_handler.id_field();
let document = self
.pool
.spawn(move |searcher, executor| {
let qry = TermQuery::new(
Term::from_field_u64(id_field, id),
IndexRecordOption::Basic,
);
... | identifier_body | |
LibphysGRU.py | d)
self.identity = tf.eye(Sd)
return E, U, W, V, b, c, [None, None]
def GRUnn(self, out_prev, x_t):
E, U, W, V, b, c = self.E, self.U, self.W, self.V, self.b, self.c
Hd, Sd, Bd = self.signal2model.hidden_dim, self.signal2model.signal_dim, tf.shape(x_t)[0]
coversion_ones = t... | # [s, o, l] = tf.scan(self.GRUnn, x_batch, initializer=[initial_s, initial_out, initial_l], parallel_iterations=1,
# name="network_output")
[s, o] = tf.scan(self.GRUnn, x_batch, initializer=[initial_s, initial_out], parallel_iterations=1,
name="networ... | random_line_split | |
LibphysGRU.py | , U, W, V, b, c, [None, None]
def GRUnn(self, out_prev, x_t):
E, U, W, V, b, c = self.E, self.U, self.W, self.V, self.b, self.c
Hd, Sd, Bd = self.signal2model.hidden_dim, self.signal2model.signal_dim, tf.shape(x_t)[0]
coversion_ones = tf.ones((1, Bd), dtype=tf.float32, name="conversion_matr... | self.epoch += 1
# tic = time.time()
random_indexes = np.random.permutation(self.signal2model.batch_size)
groups = np.reshape(random_indexes,
(int(self.signal2model.batch_size/self.signal2model.mini_batch_size),
self.sig... | conditional_block | |
LibphysGRU.py | )
self.identity = tf.eye(Sd)
return E, U, W, V, b, c, [None, None]
def GRUnn(self, out_prev, x_t):
E, U, W, V, b, c = self.E, self.U, self.W, self.V, self.b, self.c
Hd, Sd, Bd = self.signal2model.hidden_dim, self.signal2model.signal_dim, tf.shape(x_t)[0]
coversion_ones = tf... |
@property
def optimize_op(self):
""" An Operation that takes one optimization step. """
return self._optimize_op
def train(self, X, Y, signal2model=None):
self.batch_size += np.shape(X)[0]
self.init_time = time.time()
plt.ion()
if signal2model is not None:
... | trainables = self.parameters
grads = tf.gradients(self.loss, trainables)
grad_var_pairs = zip(grads, trainables)
# grads, _ = tf.clip_by_global_norm(grads, clip_norm=1.0)
# self.learning_rate = tf.train.exponential_decay(
# self.signal2model.learning_rate_val, self.epoch, sel... | identifier_body |
LibphysGRU.py | )
self.identity = tf.eye(Sd)
return E, U, W, V, b, c, [None, None]
def GRUnn(self, out_prev, x_t):
E, U, W, V, b, c = self.E, self.U, self.W, self.V, self.b, self.c
Hd, Sd, Bd = self.signal2model.hidden_dim, self.signal2model.signal_dim, tf.shape(x_t)[0]
coversion_ones = tf... | (self, x_batch):
initial_s = tf.zeros((self.signal2model.n_grus, self.signal2model.hidden_dim, tf.shape(x_batch)[1]), dtype=np.float32)
initial_out = tf.zeros((self.signal2model.signal_dim, tf.shape(x_batch)[1]), dtype=np.float32)
# initial_l = tf.zeros((self.signal2model.signal_dim, tf.shape(x_... | feed_forward_predict | identifier_name |
search-table.controller.js | License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
(function () {
'use strict';
/**
* @ngdoc controller
* @name SearchTableContro... |
if ( searchlight_item ) {
searchlight_item.dirty = true;
searchlight_item.deleted = deleted;
cache.add(searchlight_item, searchlight_item._id, getSearchlightTimestamp(searchlight_item));
}
}
});
}
| {
ctrl.hitsSrc.splice(index,1);
} | conditional_block |
search-table.controller.js | the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
(function () {
'use strict';
/**
* @ngdoc controller
* @name SearchTableCo... | 'horizon.framework.conf.resource-type-registry.service',
'horizon.app.core.openstack-service-api.userSession',
'horizon.dashboard.project.search.searchlightFacetUtils',
'horizon.dashboard.project.search.searchlightSearchHelper',
'horizon.dashboard.project.search.settingsService',
'horizon.dashbo... | random_line_split | |
search-table.controller.js | description
* Controller for the search table.
* Serves as the focal point for table actions.
*/
angular
.module('horizon.dashboard.project.search')
.controller('searchTableController', SearchTableController);
SearchTableController.$inject = [
'$scope',
'$filter',
'$q',
'$timeout',... | {
if (type === undefined || item.type === type) {
accumulator.push(item.id);
}
return accumulator;
} | identifier_body | |
search-table.controller.js | the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
(function () {
'use strict';
/**
* @ngdoc controller
* @name SearchTableCo... | (searchlight_item) {
return cache.sync(searchlight_item, searchlight_item._id, getSearchlightTimestamp(searchlight_item));
}
function removeDeletedItems(searchlight_item) {
if ( searchlight_item.deleted ) {
return false;
} else {
return true;
}
}
function action... | syncWithCache | identifier_name |
modal-gallery.component.ts | this.description = description;
this.extUrl = extUrl;
this.selected = selected;
}
}
/**
* Enum `Keyboard` with keys and their relative key codes.
*/
export enum Keyboard {
ESC = 27,
LEFT_ARROW = 37,
RIGHT_ARROW = 39,
UP_ARROW = 38,
DOWN_ARROW = 40
}
/**
* Interface `Description` to change t... | this.width = width;
this.height = height;
this.thumb = thumb; | random_line_split | |
modal-gallery.component.ts | want to show enable button, this is not enough. You have to use also `buttonsConfig`.
*/
@Input() downloadable: boolean = false;
/**
* Description object with the configuration to show image descriptions.
*/
@Input() description: Description;
/**
* Object of type `ButtonsConfig` to show/hide button... |
const esc: number = this.keyboardConfig && this.keyboardConfig.esc ? this.keyboardConfig.esc : Keyboard.ESC;
const right: number = this.keyboardConfig && this.keyboardConfig.right ? this.keyboardConfig.right : Keyboard.RIGHT_ARROW;
const left: number = this.keyboardConfig && this.keyboardConfig.left ? this... | {
return;
} | conditional_block |
modal-gallery.component.ts | want to show enable button, this is not enough. You have to use also `buttonsConfig`.
*/
@Input() downloadable: boolean = false;
/**
* Description object with the configuration to show image descriptions.
*/
@Input() description: Description;
/**
* Object of type `ButtonsConfig` to show/hide button... | tImageCountsToDisplay(){
var selectedImages = this.images.filter(image=>{
return image.selected === true;
});
var selectedImageCount = selectedImages.length;
var tobeselected = this.selectionLimit - selectedImageCount;
this.canSelectImage = tobeselected <= 0 && !this.currentImage.selected;
... | // to prevent errors when you pass to this library
// the array of images inside a subscribe block, in this way: `...subscribe(val => { this.images = arrayOfImages })`
// As you can see, I'm providing examples in these situations in all official demos
if (this.modalImages) {
// I pass `false` as param... | identifier_body |
modal-gallery.component.ts | of `Image`s as `modalImages`, you have to subscribe to that
* Observable. So, to prevent memory leaks, you must store the subscription and call `unsubscribe` in
* OnDestroy.
*/
private subscription: Subscription;
/**
* Listener to catch keyboard's events and call the right method based on the key.
... | adImage() {
| identifier_name | |
lib.rs | (jit: bool) -> Box<dyn TargetIsa + 'static> {
let mut flags_builder = cranelift::codegen::settings::builder();
// `simplejit` requires non-PIC code
if !jit {
// allow creating shared libraries
flags_builder
.enable("is_pic")
.expect("is_pic should be a valid option");... | get_isa | identifier_name | |
lib.rs | : true,
strings: Default::default(),
error_handler: Default::default(),
debug,
}
}
// we have to consider the following cases:
// 1. declaration before definition
// 2. 2nd declaration before definition
// 3. definition
// 4. declaration after definiti... |
// TODO: this is grossly inefficient, ask Cranelift devs if
// there's an easier way to make parameters modifiable.
fn store_stack_params(
&mut self,
params: &[Symbol],
func_start: Block,
location: &Location,
builder: &mut FunctionBuilder,
) -> CompileResult<()> ... | {
match init {
Initializer::Scalar(expr) => {
let val = self.compile_expr(*expr, builder)?;
// TODO: replace with `builder.ins().stack_store(val.ir_val, stack_slot, 0);`
// when Cranelift implements stack_store for i8 and i16
let addr =... | identifier_body |
lib.rs | ());
}
let u64_size = match meta.ctype.sizeof() {
Ok(size) => size,
Err(err) => {
return Err(CompileError::semantic(Locatable {
data: err.into(),
location,
}))
}
};
let kind = Stac... | use std::io::{Error, ErrorKind};
use std::process::Command;
| random_line_split | |
cef.go |
func (d defaultLogger) Panicf(fmt string, args ... interface{}) {
log.Panicf("[cef] " + fmt, args...)
}
// Sandbox is disabled. Including the "cef_sandbox.lib"
// library results in lots of GCC warnings/errors. It is
// compatible only with VS 2010. It would be required to
// build it using GCC. Add -lcef_sandbo... | {
log.Printf("[cef] " + fmt, args...)
} | identifier_body | |
cef.go | LogSeverity int
LogFile string
ResourcesDirPath string
LocalesDirPath string
RemoteDebuggingPort int
PersistSessionCookies bool
IgnoreCertificateErrors int
}
type CefState int
var (
STATE_DEFAULT CefState = 0
STATE_ENABLED CefState ... | Logger.Infof("CreateBrowser, url=%s\n", url)
// Initialize cef_window_info_t structure.
var windowInfo *C.cef_window_info_t
windowInfo = (*C.cef_window_info_t)(
C.calloc(1, C.sizeof_cef_window_info_t))
FillWindowInfo(windowInfo, hwnd)
// url
var cefUrl *C.cef_string_t
cefU... | url string) bool { | random_line_split |
cef.go | (fmt string, args ... interface{}) {
log.Printf("[cef] " + fmt, args...)
}
func (d defaultLogger) Panicf(fmt string, args ... interface{}) {
log.Panicf("[cef] " + fmt, args...)
}
// Sandbox is disabled. Including the "cef_sandbox.lib"
// library results in lots of GCC warnings/errors. It is
// compatible only... | Errorf | identifier_name | |
cef.go | efState
JavascriptCloseWindows CefState
JavascriptAccessClipboard CefState
JavascriptDomPaste CefState
CaretBrowsing CefState
Java CefState
Plugins CefState
UniversalAccessFromFileUrls CefSta... | {
continue
} | conditional_block | |
romaO.py | 9, 0.76047],
[0.33253, 0.59151, 0.75704],
[0.32893, 0.58412, 0.75351],
[0.32559, 0.57671, 0.74987],
[0.32256, 0.56928, 0.74613],
[0.31978, 0.56186, 0.74228],
[0.31727, 0.55441, 0.7383],
[0.31505, 0.546... | import matplotlib.pyplot as plt
import numpy as np
try:
from viscm import viscm
viscm(romaO_map)
except ImportError:
print("viscm not found, falling back on simple display")
plt.imshow(np.linspace(0, 100, 256)[None, :], aspect=... | conditional_block | |
romaO.py | 2165],
[0.78242, 0.6759, 0.33066],
[0.78669, 0.68481, 0.33988],
[0.79087, 0.69365, 0.34929],
[0.79494, 0.7024, 0.35888],
[0.7989, 0.71106, 0.36867],
[0.80273, 0.71961, 0.37859],
[0.80642, 0.72803, 0.38... | [0.58965, 0.82137, 0.80743],
[0.58037, 0.81644, 0.80848],
[0.57108, 0.81135, 0.80935],
[0.56181, 0.80612, 0.81004],
[0.55255, 0.80074, 0.81055], | random_line_split | |
tags.rs | ;
}
None => unreachable!(),
}
}
let result = if tags.is_empty() {
ctx.psql().get_tags_mapset(mapset_id).await
} else {
let db_result = match action {
Action::Add => ctx.psql().add_tags_mapset(mapset_id, tags).await,
Action::Remove => c... | let builder = MessageBuilder::new().content("Exiting loop :wave:");
msg.create_message( | conditional_block | |
tags.rs | data: CommandData) -> Result<()> {
let (msg, mut args) = match data {
CommandData::Message { msg, args, .. } => (msg, args),
CommandData::Interaction { .. } => unreachable!(),
};
// Parse mapset id
let mapset_id = match args.next().map(u32::from_str) {
Some(Ok(num)) => num,
... | let mode = match args.next() {
Some(arg) => match arg.cow_to_ascii_lowercase().as_ref() {
"mna" | "mania" | "m" => GameMode::Mania,
"osu" | "std" | "standard" | "o" => GameMode::Osu,
_ => {
let content = "Could not parse first argument as mode. \
... | CommandData::Interaction { .. } => unreachable!(),
};
// Parse arguments as mode | random_line_split |
tags.rs | , tags).await,
Action::Remove => ctx.psql().remove_tags_mapset(mapset_id, tags).await,
};
match db_result {
Ok(_) => ctx.psql().get_tags_mapset(mapset_id).await,
Err(err) => Err(err),
}
};
// Then show the final tags
match result {
Ok(tag... | clone();
ma | identifier_name | |
tags.rs | : CommandData) -> Result<()> {
let (msg, mut args) = match data {
CommandData::Message { msg, args, .. } => (msg, args),
CommandData::Interaction { .. } => unreachable!(),
};
// Parse mapset id
let mapset_id = match args.next().map(u32::from_str) {
Some(Ok(num)) => num,
... | let mut untagged = match ctx.psql().get_all_tags_mapset(mode).await {
Ok(tags) => tags.iter().any(|tag| tag.untagged()),
Err(err) => {
let _ = msg.error(&ctx, GENERAL_ISSUE).await;
return Err(err);
}
};
if !untagged {
let content = "All backgrounds h... | let (msg, mut args) = match data {
CommandData::Message { msg, args, .. } => (msg, args),
CommandData::Interaction { .. } => unreachable!(),
};
// Parse arguments as mode
let mode = match args.next() {
Some(arg) => match arg.cow_to_ascii_lowercase().as_ref() {
"mna" | ... | identifier_body |
golem_renderer.rs | Float, Dimension::D4)
));
for matrix_counter in 1 ..= shader.description.num_float_matrices {
uniforms.push(Uniform::new(
MATRIX_VARIABLE_NAMES[matrix_counter as usize],
UniformType::Matrix(Dimension::D4)
... | );
}
for int_counter in 1 ..= shader.description.num_ints {
let _result = shader_program.set_uniform(
&format!("int{}", int_counter),
UniformValue::Int(parameters.ints[int_counter as usize - 1])
... | UniformValue::Float(parameters.floats[float_counter as usize - 1]) | random_line_split |
golem_renderer.rs | Float, Dimension::D4)
));
for matrix_counter in 1 ..= shader.description.num_float_matrices {
uniforms.push(Uniform::new(
MATRIX_VARIABLE_NAMES[matrix_counter as usize],
UniformType::Matrix(Dimension::D4)
... | (&self) -> &ElementBuffer {
&self.storage.quad_indices
}
/// Gets the number of indices in the `ElementBuffer` given by the `get_quad_indices`
/// method, in integers (which is just 6).
pub fn get_num_quad_indices(&self) -> usize {
6
}
/// Checks if the shader with the given *i... | get_quad_indices | identifier_name |
golem_renderer.rs | ].to_float_array())
);
}
for vector_counter in 1 ..= shader.description.num_float_vectors {
let _result = shader_program.set_uniform(
&format!("floatVector{}", vector_counter),
UniformValue::Vector4(p... | {
let mut last_used_times: Vec<u64> = self
.map
.values()
.map(|cached_shader| cached_shader.last_used)
.collect();
last_used_times.sort();
let median = last_used_times[last_used_times.len() / 2];
// Remove ... | conditional_block | |
TheGiver.py | usersSavedDataObj.keys():
for browserCount in usersSavedDataObj[userName]["previous_browser_counts"]:
if browserCount["name"] == browserName:
return browserCount
def usersBrowserCount(userName, browserName):
if userName in usersObj.keys():
for browserCount in usersObj[userName]["previous_browser_counts"]:... | currentLoser = users[0]
currentScore = usersPreviousScore(currentLoser["name"])
for user in users:
userScore = usersPreviousScore(user["name"])
if userScore > currentScore:
currentLoser = user
currentScore = userScore
return currentLoser
# Clean up object
for user in users:
user["score"] = 0.0
user["la... |
def previousRoundLoser(): | random_line_split |
TheGiver.py | currentLoser
# Clean up object
for user in users:
user["score"] = 0.0
user["last_score"] = 0.0
user["loses"] = 0
user["bails"] = 0
user["previous_browsers"] = []
user["previous_browser_counts"] = []
# Load saved user data into users
if user["name"] in usersSavedDataObj.keys():
user["score"] = usersSavedDat... | scoreThisRound = scoreThisRound + browser["score"]
usersBrowsersString = usersBrowsersString + '[' + browser["name"] + '] '
# update the number of times user has tested this browser
browserCount = usersBrowserCount(user["name"], browser["name"])
browserCount["count"] = browserCount["count"] + 1 | conditional_block | |
TheGiver.py | usersSavedDataObj.keys():
for browserCount in usersSavedDataObj[userName]["previous_browser_counts"]:
if browserCount["name"] == browserName:
return browserCount
def usersBrowserCount(userName, browserName):
if userName in usersObj.keys():
for browserCount in usersObj[userName]["previous_browser_counts"]:... | ():
currentLoser = users[0]
currentScore = usersPreviousScore(currentLoser["name"])
for user in users:
userScore = usersPreviousScore(user["name"])
if userScore > currentScore:
currentLoser = user
currentScore = userScore
return currentLoser
# Clean up object
for user in users:
user["score"] = 0.0
user... | previousRoundLoser | identifier_name |
TheGiver.py | usersSavedDataObj.keys():
for browserCount in usersSavedDataObj[userName]["previous_browser_counts"]:
if browserCount["name"] == browserName:
return browserCount
def usersBrowserCount(userName, browserName):
if userName in usersObj.keys():
for browserCount in usersObj[userName]["previous_browser_counts"]:... |
def previousRoundLoser():
currentLoser = users[0]
currentScore = usersPreviousScore(currentLoser["name"])
for user in users:
userScore = usersPreviousScore(user["name"])
if userScore > currentScore:
currentLoser = user
currentScore = userScore
return currentLoser
# Clean up object
for user in users:
u... | return sum(b["score"] for b in usersObj[userName]["previous_browsers"]) | identifier_body |
repr.rs | _profile(&profile);
if let Ok(static_credentials) = try_static {
break BaseProvider::AccessKey(static_credentials);
}
}
let next_profile = match chain_provider(&profile) {
// this provider wasn't a chain provider, reload it as a base provider
... | Provider | identifier_name | |
repr.rs | BaseProvider<'a> {
/// A profile that specifies a named credential source
/// Eg: `credential_source = Ec2InstanceMetadata`
///
/// The following profile produces two separate `ProfileProvider` rows:
/// 1. `BaseProvider::NamedSource("Ec2InstanceMetadata")`
/// 2. `RoleArn { role_arn: "...", ..... |
/// Load static credentials from a profile
///
/// Example:
/// ```ini
/// [profile B]
/// aws_access_key_id = abc123
/// aws_secret_access_key = def456
/// ```
fn static_creds_from_profile(profile: &Profile) -> Result<Credentials, ProfileFileError> {
use static_credentials::*;
let access_key = profile.get(AW... | {
let session_name = profile.get(role::SESSION_NAME);
match (
profile.get(role::ROLE_ARN),
profile.get(web_identity_token::TOKEN_FILE),
) {
(Some(role_arn), Some(token_file)) => Some(Ok(BaseProvider::WebIdentityTokenRole {
role_arn,
web_identity_token_file: to... | identifier_body |
repr.rs | }
pub fn chain(&self) -> &[RoleArn<'a>] {
&self.chain.as_slice()
}
}
/// A base member of the profile chain
///
/// Base providers do not require input credentials to provide their own credentials,
/// eg. IMDS, ECS, Environment variables
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum BaseProv... | random_line_split | ||
neural_network.py | hat = logistic(self.W @ Z).T
return Z, Yhat
def loss(self, X, V, W, Y):
Z, Yhat = self.forward(X, V, W)
log_Yhat = log(Yhat)
log_Yhat_inv = log(1 - Yhat)
log_Yhat[Y == 0] = 0
log_Yhat_inv[Y == 1] = 0
if not (np.isfinite(log_Yhat).all() and
np... | eps = EPSILON_FINITE_DIFFERENCE
def d(h):
eps_vec = np.zeros_like(z)
eps_vec[h] = eps
yhat_plus = logistic(W @ (z + eps_vec))
yhat_minus = logistic(W @ (z - eps_vec))
L_plus = self.loss(yhat_plus, y)
L_minus = self.loss(yhat_minus, y)
... | identifier_body | |
neural_network.py | x K). We use stochastic gradient
descent, i.e. compute and update gradients for a single input row at a
time, so in backpropagation we work with x (d x 1) and y (K x 1).
| Input | x | d x 1 |
| First weight matrix | V | H x d |
| Hidden layer | Z = t... | # grad__z_h__V_h = x * (1 - z[h] ** 2)
# grad__L__V_h = grad__L__z[h] * grad__z_h__V_h
# V[h, :] -= self.learning_rate * grad__L__V_h
xx = x.reshape((1, d + 1)).repeat(H + 1, 0)
grad__L__V = diag((1 - z ** 2) * grad__L__z) @ xx
return grad__L__V, grad__L__W
... | random_line_split | |
neural_network.py | y)
H = self.H
K = self.K
n, d = X.shape
# X has extra offset dimension containing all 1s
# The hidden layer z also has a unit whose value is always 1
d -= 1
if self.V is None:
self.V = random_normal(0, 0.1, (H + 1, d + 1))
if self.W is None:... | y_int = np.floor(y).astype(np.int)
assert (y_int == y).all()
y = y_int | conditional_block | |
neural_network.py | (self, yhat):
"""
Map values in output layer to classification predictions.
"""
raise NotImplementedError
class SingleLayerTanhLogisticNeuralNetwork(NeuralNetwork):
"""
A classification neural net with one hidden layer.
The hidden layer uses the tanh activation function.
... | prediction_fn | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.