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 |
|---|---|---|---|---|
ClipboardScreen.tsx | import * as Clipboard from 'expo-clipboard';
import * as React from 'react';
import { Button, Text, TextInput } from 'react-native';
import { Page, Section } from '../components/Page';
export default function | () {
return (
<Page>
<Section title="Set String">
<SetStringExample />
</Section>
<Section title="Get String">
<GetStringExample />
</Section>
<Section title="Clipboard listener">
<ListenerExample />
</Section>
</Page>
);
}
ClipboardScreen.navigat... | ClipboardScreen | identifier_name |
ClipboardScreen.tsx | import * as Clipboard from 'expo-clipboard';
import * as React from 'react';
import { Button, Text, TextInput } from 'react-native';
import { Page, Section } from '../components/Page';
export default function ClipboardScreen() |
ClipboardScreen.navigationOptions = {
title: 'Clipboard',
};
function GetStringExample() {
const [value, setValue] = React.useState('');
return (
<>
<Text>On the clipboard: {value || 'nothing'}</Text>
<Button
onPress={async () => {
const value = await Clipboard.getStringAsyn... | {
return (
<Page>
<Section title="Set String">
<SetStringExample />
</Section>
<Section title="Get String">
<GetStringExample />
</Section>
<Section title="Clipboard listener">
<ListenerExample />
</Section>
</Page>
);
} | identifier_body |
ClipboardScreen.tsx | import * as Clipboard from 'expo-clipboard';
import * as React from 'react';
import { Button, Text, TextInput } from 'react-native';
import { Page, Section } from '../components/Page';
export default function ClipboardScreen() {
return (
<Page>
<Section title="Set String">
<SetStringExample />
... |
};
}, []);
return (
<>
<Text style={{ padding: 8, height: 48, margin: 8, borderBottomWidth: 1 }}>
Clipboard value changed to: {value}
</Text>
</>
);
}
| {
Clipboard.removeClipboardListener(clipboardListener.current);
} | conditional_block |
translation.py | import json
from pprint import pprint
import requests
from telegram import Update, Bot
from telegram.ext import CommandHandler
from tg_bot import dispatcher
# Open API key
API_KEY = "6ae0c3a0-afdc-4532-a810-82ded0054236"
URL = "http://services.gingersoftware.com/Ginger/correct/json/GingerTheText"
def | (bot: Bot, update: Update):
if update.effective_message.reply_to_message:
msg = update.effective_message.reply_to_message
params = dict(
lang="US",
clientVersion="2.0",
apiKey=API_KEY,
text=msg.text
)
res = requests.get(URL, params=pa... | translate | identifier_name |
translation.py | import json
from pprint import pprint
import requests
from telegram import Update, Bot
from telegram.ext import CommandHandler
from tg_bot import dispatcher
# Open API key
API_KEY = "6ae0c3a0-afdc-4532-a810-82ded0054236"
URL = "http://services.gingersoftware.com/Ginger/correct/json/GingerTheText"
def translate(bot... | clientVersion="2.0",
apiKey=API_KEY,
text=msg.text
)
res = requests.get(URL, params=params)
# print(res)
# print(res.text)
pprint(json.loads(res.text))
changes = json.loads(res.text).get('LightGingerTheTextResult')
curr_string ... |
params = dict(
lang="US", | random_line_split |
translation.py | import json
from pprint import pprint
import requests
from telegram import Update, Bot
from telegram.ext import CommandHandler
from tg_bot import dispatcher
# Open API key
API_KEY = "6ae0c3a0-afdc-4532-a810-82ded0054236"
URL = "http://services.gingersoftware.com/Ginger/correct/json/GingerTheText"
def translate(bot... | start = change.get('From')
end = change.get('To') + 1
suggestions = change.get('Suggestions')
if suggestions:
sugg_str = suggestions[0].get('Text') # should look at this list more
curr_string += msg.text[prev_end:start] + sugg_str
... | if update.effective_message.reply_to_message:
msg = update.effective_message.reply_to_message
params = dict(
lang="US",
clientVersion="2.0",
apiKey=API_KEY,
text=msg.text
)
res = requests.get(URL, params=params)
# print(res)
... | identifier_body |
translation.py | import json
from pprint import pprint
import requests
from telegram import Update, Bot
from telegram.ext import CommandHandler
from tg_bot import dispatcher
# Open API key
API_KEY = "6ae0c3a0-afdc-4532-a810-82ded0054236"
URL = "http://services.gingersoftware.com/Ginger/correct/json/GingerTheText"
def translate(bot... | end = change.get('To') + 1
suggestions = change.get('Suggestions')
if suggestions:
sugg_str = suggestions[0].get('Text') # should look at this list more
curr_string += msg.text[prev_end:start] + sugg_str
prev_end = end
curr_s... | msg = update.effective_message.reply_to_message
params = dict(
lang="US",
clientVersion="2.0",
apiKey=API_KEY,
text=msg.text
)
res = requests.get(URL, params=params)
# print(res)
# print(res.text)
pprint(json.loads(res.tex... | conditional_block |
config.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use serde::{Deserialize, Serialize};
use tikv_util::config::ReadableDuration;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
#[serde(rename_all = "kebab-case")]
pub struct Config {
pub max_batch_size: Option<usize>,
... | () -> Config {
Config {
max_batch_size: None,
pool_size: 2,
reschedule_duration: ReadableDuration::secs(5),
low_priority_pool_size: 1,
}
}
}
| default | identifier_name |
config.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use serde::{Deserialize, Serialize};
use tikv_util::config::ReadableDuration;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
#[serde(rename_all = "kebab-case")]
pub struct Config {
pub max_batch_size: Option<usize>,
... | } | random_line_split | |
blackLionStatuette.js | import { getWikiHtml } from './helpers.js'
import execAll from 'execall'
// Get the current claim ticket offers
export default async function blackLionStatuette () | {
let page = await getWikiHtml('Black_Lion_Statuette')
// Find all items sold for Black Lion Statuette with their costs
let regex = /<tr[\s\S]*?<a href="[^"]*" title="([^"]*)">[\s\S]*?class="inline-icon">(\d*)( | )*<a [^>]* title="Black Lion Statuette"[\s\S]*?<\/tr>/gi
let matches = execAll(regex, pa... | identifier_body | |
blackLionStatuette.js | import { getWikiHtml } from './helpers.js'
import execAll from 'execall'
// Get the current claim ticket offers
export default async function blackLionStatuette () {
let page = await getWikiHtml('Black_Lion_Statuette')
// Find all items sold for Black Lion Statuette with their costs
let regex = /<tr[\s\S]*?<a h... | } | })
return map | random_line_split |
blackLionStatuette.js | import { getWikiHtml } from './helpers.js'
import execAll from 'execall'
// Get the current claim ticket offers
export default async function | () {
let page = await getWikiHtml('Black_Lion_Statuette')
// Find all items sold for Black Lion Statuette with their costs
let regex = /<tr[\s\S]*?<a href="[^"]*" title="([^"]*)">[\s\S]*?class="inline-icon">(\d*)( | )*<a [^>]* title="Black Lion Statuette"[\s\S]*?<\/tr>/gi
let matches = execAll(regex... | blackLionStatuette | identifier_name |
operator-overloading.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 ... |
}
impl ops::Index<bool,int> for Point {
fn index(&self, +x: &bool) -> int {
if *x { self.x } else { self.y }
}
}
impl cmp::Eq for Point {
fn eq(&self, other: &Point) -> bool {
(*self).x == (*other).x && (*self).y == (*other).y
}
fn ne(&self, other: &Point) -> bool { !(*self).eq(ot... | {
Point {x: !self.x, y: !self.y }
} | identifier_body |
operator-overloading.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 ... | else { self.y }
}
}
impl cmp::Eq for Point {
fn eq(&self, other: &Point) -> bool {
(*self).x == (*other).x && (*self).y == (*other).y
}
fn ne(&self, other: &Point) -> bool { !(*self).eq(other) }
}
pub fn main() {
let mut p = Point {x: 10, y: 20};
p += Point {x: 101, y: 102};
p = p... | { self.x } | conditional_block |
operator-overloading.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 ... | (&self) -> Point {
Point {x: !self.x, y: !self.y }
}
}
impl ops::Index<bool,int> for Point {
fn index(&self, +x: &bool) -> int {
if *x { self.x } else { self.y }
}
}
impl cmp::Eq for Point {
fn eq(&self, other: &Point) -> bool {
(*self).x == (*other).x && (*self).y == (*other).... | not | identifier_name |
operator-overloading.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 ... |
let q = !p;
assert!(q.x == !(p.x));
assert!(q.y == !(p.y));
// Issue #1733
let result: ~fn(int) = |_|();
result(p[true]);
} | p = p - Point {x: 100, y: 100};
assert!(p + Point {x: 5, y: 5} == Point {x: 16, y: 27});
assert!(-p == Point {x: -11, y: -22});
assert!(p[true] == 11);
assert!(p[false] == 22); | random_line_split |
add-userid.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals
# Copyright (C) 2018 Ben McGinnes <ben@gnupg.org>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free S... | key = c.get_key(fpr, secret=True)
c.key_add_uid(key, userid) | else:
userid = "{0} <{2}>".format(uid_name, uid_email)
| random_line_split |
add-userid.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, unicode_literals
# Copyright (C) 2018 Ben McGinnes <ben@gnupg.org>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free S... |
elif os.path.exists(homedir) is True:
c.home_dir = homedir
else:
pass
fpr = "".join(fpr0.split())
if uid_cmnt:
userid = "{0} ({1}) <{2}>".format(uid_name, uid_cmnt, uid_email)
else:
userid = "{0} <{2}>".format(uid_name, uid_email)
key = c.get_key(fpr, secret=True)
c.key_add_uid(key, userid)
| if os.path.exists(os.path.expanduser(homedir)) is True:
c.home_dir = os.path.expanduser(homedir)
else:
pass | conditional_block |
zipup.py | #!/usr/bin/env python3
import sys
import os
import argparse
import zipfile
import tarfile
def make_zipfile(outname, filenames, prefix):
with zipfile.ZipFile(outname, "w", zipfile.ZIP_DEFLATED) as z:
for filename in filenames:
z.write(filename, prefix+filename)
def make_tarfile(outname, filenam... | Supported output formats: """+", ".join(x[0] for x in formathandlers)
def parse_argv(argv):
p = argparse.ArgumentParser(
description=tophelptext, epilog=bottomhelptext
)
p.add_argument("filelist",
help="name of file containing newline-separated relative "
"path... | random_line_split | |
zipup.py | #!/usr/bin/env python3
import sys
import os
import argparse
import zipfile
import tarfile
def make_zipfile(outname, filenames, prefix):
with zipfile.ZipFile(outname, "w", zipfile.ZIP_DEFLATED) as z:
for filename in filenames:
z.write(filename, prefix+filename)
def make_tarfile(outname, filenam... |
raise KeyError(os.path.splitext(outbaselower)[1])
def main(argv=None):
args = parse_argv(argv or sys.argv)
if args.filelist == '-':
filenames = set(sys.stdin)
else:
with open(args.filelist, "r") as infp:
filenames = set(infp)
filenames = set(x.strip() for x in filenames... | return writerfunc | conditional_block |
zipup.py | #!/usr/bin/env python3
import sys
import os
import argparse
import zipfile
import tarfile
def make_zipfile(outname, filenames, prefix):
with zipfile.ZipFile(outname, "w", zipfile.ZIP_DEFLATED) as z:
for filename in filenames:
z.write(filename, prefix+filename)
def make_tarfile(outname, filenam... |
if __name__=='__main__':
main()
| args = parse_argv(argv or sys.argv)
if args.filelist == '-':
filenames = set(sys.stdin)
else:
with open(args.filelist, "r") as infp:
filenames = set(infp)
filenames = set(x.strip() for x in filenames)
filenames = sorted(x for x in filenames if x)
outname = args.output or... | identifier_body |
zipup.py | #!/usr/bin/env python3
import sys
import os
import argparse
import zipfile
import tarfile
def make_zipfile(outname, filenames, prefix):
with zipfile.ZipFile(outname, "w", zipfile.ZIP_DEFLATED) as z:
for filename in filenames:
z.write(filename, prefix+filename)
def make_tarfile(outname, filenam... | (argv):
p = argparse.ArgumentParser(
description=tophelptext, epilog=bottomhelptext
)
p.add_argument("filelist",
help="name of file containing newline-separated relative "
"paths to files to include, or - for standard input")
p.add_argument("foldername",
... | parse_argv | identifier_name |
materialbox.d.ts | /// <reference path="./common.d.ts" />
declare namespace M {
class Materialbox extends Component<MaterialboxOptions> {
/**
* Get Instance
*/
static getInstance(elem: Element): Materialbox;
/**
* Init Materialbox
*/
static init(els: Element, optio... | */
originalHeight: number;
/**
* Open materialbox
*/
open(): void;
/**
* Close materialbox
*/
close(): void;
}
interface MaterialboxOptions {
/**
* Transition in duration in milliseconds
* @default ... | random_line_split | |
materialbox.d.ts | /// <reference path="./common.d.ts" />
declare namespace M {
class | extends Component<MaterialboxOptions> {
/**
* Get Instance
*/
static getInstance(elem: Element): Materialbox;
/**
* Init Materialbox
*/
static init(els: Element, options?: Partial<MaterialboxOptions>): Materialbox;
/**
* Init Materi... | Materialbox | identifier_name |
timepicker-section.ts | /// <reference path="../../tsd.d.ts" />
import {
Component, View,
} from 'angular2/core';
import { CORE_DIRECTIVES } from 'angular2/common';
import {tabs} from '../../ng2-bootstrap';
import {TimepickerDemo} from './timepicker/timepicker-demo';
let name = 'Timepicker';
let src = 'https://github.com/valor-software/ng... | {
}
| TimepickerSection | identifier_name |
timepicker-section.ts | /// <reference path="../../tsd.d.ts" />
import {
Component, View,
} from 'angular2/core';
import { CORE_DIRECTIVES } from 'angular2/common';
import {tabs} from '../../ng2-bootstrap';
import {TimepickerDemo} from './timepicker/timepicker-demo';
let name = 'Timepicker';
let src = 'https://github.com/valor-software/ng... | <div class="card card-block panel panel-default panel-body">
<pre class="language-typescript"><code class="language-typescript" ng-non-bindable>${ts}</code></pre>
</div>
</tab>
</tabset>
</div>
<br>
<div class="row">
<h2>API</h2>
<div class="card c... | <pre class="language-html"><code class="language-html" ng-non-bindable>${html}</code></pre>
</div>
</tab>
<tab heading="TypeScript"> | random_line_split |
realtimeController.ts | window.controllers = window.controllers || {};
window.controllers.realtimeController = (function (angular, config) {
'use strict';
//realtimeController.$inject = ['$scope', '$interval', 'yahooService', 'chartService'];
return ['$scope', '$interval', 'yahooService', 'chartService', realtimeController]... | tock) {
yahooService.getPrice(stock.symbol)
.then(function (result) {
var price = result.price;
if (angular.isUndefined(stock.quotes)) {
stock.quotes = [];
}
stock.quotes.push(price... | freshStock(s | identifier_name |
realtimeController.ts | window.controllers = window.controllers || {};
window.controllers.realtimeController = (function (angular, config) {
'use strict';
//realtimeController.$inject = ['$scope', '$interval', 'yahooService', 'chartService'];
return ['$scope', '$interval', 'yahooService', 'chartService', realtimeController]... | chartService.refresh(stock.chart, stock.quotes);
}
});
}
}
})(window.angular, window.config); |
yahooService.getPrice(stock.symbol)
.then(function (result) {
var price = result.price;
if (angular.isUndefined(stock.quotes)) {
stock.quotes = [];
}
stock.quotes.push(price);
... | identifier_body |
realtimeController.ts | window.controllers = window.controllers || {};
window.controllers.realtimeController = (function (angular, config) {
'use strict';
//realtimeController.$inject = ['$scope', '$interval', 'yahooService', 'chartService'];
return ['$scope', '$interval', 'yahooService', 'chartService', realtimeController]... | lse {
stock.direction = 'down';
}
if (stock.quotes.length > 10) {
stock.quotes.splice(0, 1);
}
if (angular.isUndefined(stock.chart)) {
stock.chart = chartService... |
stock.direction = 'up';
} e | conditional_block |
realtimeController.ts | return ['$scope', '$interval', 'yahooService', 'chartService', realtimeController];
function realtimeController($scope, $interval, yahooService, chartService) {
var refresh = config.priceRefresh;
var stocks = [
createStock('MSFT'),
createStock('AAPL'),
... | window.controllers = window.controllers || {};
window.controllers.realtimeController = (function (angular, config) {
'use strict';
//realtimeController.$inject = ['$scope', '$interval', 'yahooService', 'chartService'];
| random_line_split | |
alias.py | import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter transla... |
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.... | def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value) | identifier_body |
alias.py | import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter transla... |
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1... | return np.logical_not(self._mapped_eq(other)) | conditional_block |
alias.py | import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter transla... | (self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(ot... | __eq__ | identifier_name |
alias.py | import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter transla... |
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=... | def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj | random_line_split |
processlock.py | # Copyright (c) 2012 Hesky Fisher
# See LICENSE.txt for details.
#
# processlock.py - Cross platform global lock to ensure plover only runs once.
"""Global lock to ensure plover only runs once."""
import sys
class LockNotAcquiredException(Exception):
pass
if sys.platform.startswith('win32'):
from ctypes ... |
lock_file_name = os.path.expanduser(
'~/.plover-lock-%s-%s' % (hostname, display))
self.fd = open(lock_file_name, 'w')
def acquire(self):
try:
fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as e:
... | import socket
hostname = socket.gethostname() | conditional_block |
processlock.py | # Copyright (c) 2012 Hesky Fisher
# See LICENSE.txt for details.
#
# processlock.py - Cross platform global lock to ensure plover only runs once.
"""Global lock to ensure plover only runs once."""
import sys
class LockNotAcquiredException(Exception):
pass
if sys.platform.startswith('win32'):
from ctypes ... | (self):
self.mutex = windll.kernel32.CreateMutexA(None, False, self.guid)
if windll.kernel32.GetLastError() == 0xB7: # ERROR_ALREADY_EXISTS
raise LockNotAcquiredException()
def release(self):
if hasattr(self, 'mutex'):
windll.kernel32.CloseHan... | acquire | identifier_name |
processlock.py | # Copyright (c) 2012 Hesky Fisher
# See LICENSE.txt for details.
#
# processlock.py - Cross platform global lock to ensure plover only runs once.
"""Global lock to ensure plover only runs once."""
import sys
class LockNotAcquiredException(Exception):
pass
if sys.platform.startswith('win32'):
from ctypes ... | hostname = socket.gethostname()
lock_file_name = os.path.expanduser(
'~/.plover-lock-%s-%s' % (hostname, display))
self.fd = open(lock_file_name, 'w')
def acquire(self):
try:
fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)... | import socket | random_line_split |
processlock.py | # Copyright (c) 2012 Hesky Fisher
# See LICENSE.txt for details.
#
# processlock.py - Cross platform global lock to ensure plover only runs once.
"""Global lock to ensure plover only runs once."""
import sys
class LockNotAcquiredException(Exception):
pass
if sys.platform.startswith('win32'):
from ctypes ... | self.release() | identifier_body | |
tac_code.rs | use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result;
use super::{
function_attributes::FunctionAttribute,
types::Type,
node_info::{ DeclarationInfo, FunctionInfo },
};
use std::rc::Rc;
#[derive(Clone, Debug, PartialEq)]
pub enum Statement {
Assignment{ operator: Optio... | (&self, formatter: &mut Formatter) -> Result {
write!(formatter, "{}", match *self {
Operator::Plus => "+".to_string(),
Operator::Minus => "-".to_string(),
Operator::Multiply => "*".to_string(),
Operator::Divide => "/".to_string(),
Operator::Modu... | fmt | identifier_name |
tac_code.rs | use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result;
use super::{
function_attributes::FunctionAttribute,
types::Type,
node_info::{ DeclarationInfo, FunctionInfo },
};
use std::rc::Rc;
#[derive(Clone, Debug, PartialEq)]
pub enum Statement {
Assignment{ operator: Optio... | fn fmt(&self, formatter: &mut Formatter) -> Result {
write!(formatter, "{}", match *self {
Statement::Assignment{ref operator, ref destination, ref left_operand, ref right_operand} =>
format!("{}= {}{}{}",
opt_to_str(destination),
... | }
impl Display for Statement {
| random_line_split |
tac_code.rs | use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result;
use super::{
function_attributes::FunctionAttribute,
types::Type,
node_info::{ DeclarationInfo, FunctionInfo },
};
use std::rc::Rc;
#[derive(Clone, Debug, PartialEq)]
pub enum Statement {
Assignment{ operator: Optio... | "<initialized {} value>", t),
})
}
}
impl Display for Operator {
fn fmt(&self, formatter: &mut Formatter) -> Result {
write!(formatter, "{}", match *self {
Operator::Plus => "+".to_string(),
Operator::Minus => "-".to_string(),
Opera... | {
write!(formatter, "{}", match *self {
Operand::ArrayIndex { id, ref index_operand, ref variable_info} => {
format!("{}_{}[{}]", variable_info.name, id, index_operand)
},
Operand::ArraySlice{ id, ref start_operand, ref end_operand, ref variable_info} => ... | identifier_body |
Main_TopBarView.js | /* RequireJS Module Dependency Definitions */
define([
'app',
'jquery',
'marionette',
'handlebars',
'collections/TopBarMessagesCollection',
'text!templates/main_topbar.html',
'foundation-reveal',
'foundation-topbar'
], function (App, $, Marionette, Handlebars, TopBarMessagesCollection, template){
"use strict"... | }
App.session.logout({
},{
success: function(){
console.log("Logged out");
Backbone.history.navigate('home', {trigger: true});
},
error: function() {
console.log("Logged out failed");
}
});
}
});
}); | event.stopPropagation();
event.preventDefault(); | random_line_split |
Plugins.py | #
#
# (C) Copyright 2001 The Internet (Aust) Pty Ltd
# ACN: 082 081 472 ABN: 83 082 081 472
# All Rights Reserved
# | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT... | # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE | random_line_split |
Plugins.py | #
#
# (C) Copyright 2001 The Internet (Aust) Pty Ltd
# ACN: 082 081 472 ABN: 83 082 081 472
# All Rights Reserved
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ... | (self, name, description, pluginClass,
pluginStartForm, pluginStartMethod,
pluginEditForm=None, pluginEditMethod=None):
self.name=name #No Spaces please...
self.description=description
self.plugin=pluginClass
self.manage_addForm=pluginStartForm
self.manage_addMethod=pluginStartMethod
self.manage_e... | __init__ | identifier_name |
Plugins.py | #
#
# (C) Copyright 2001 The Internet (Aust) Pty Ltd
# ACN: 082 081 472 ABN: 83 082 081 472
# All Rights Reserved
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A ... | self.name = name #No Spaces please...
self.cryptoMethod = crypto
self.description = description
self.plugin = pluginMethod | identifier_body | |
mmca_et.py | (self, D, H, Hprime, gamma, to_learn=['W', 'pi', 'sigma'], comm=MPI.COMM_WORLD):
""" MMCA-ET init method.
Takes data dimension *D*, number of hidden causes *H*,
and ET approximation parameters *Hprime* and *gamma*. Optional
list of parameters *to_learn* and MPI *comm* object.
... | __init__ | identifier_name | |
mmca_et.py | 'W' : ( -np.inf, +np.inf, False ),
'pi' : ( tol, 1-tol, False ),
'sigma': ( tol, +np.inf, False )
}
# XXX debugging XXX
#self.tbl = AutoTable("mmca-debug/mmca-debug-%04d.h5" % comm.rank)
#self.last_ca... | def __init__(self, D, H, Hprime, gamma, to_learn=['W', 'pi', 'sigma'], comm=MPI.COMM_WORLD):
""" MMCA-ET init method.
Takes data dimension *D*, number of hidden causes *H*,
and ET approximation parameters *Hprime* and *gamma*. Optional
list of parameters *to_learn* and MPI *comm* objec... | identifier_body | |
mmca_et.py | ound), self.rho_lbound)
beta = 1./T
pre1 = -1./2./sigma/sigma
pil_bar = np.log( pies/(1.-pies) )
Wl = accel.log(np.abs(W))
Wrho = accel.exp(rho * Wl)
Wrhos = np.sign(W) * Wrho
Wsquared = W*W
# Some asserts
assert np.isfinite(... | tracing.tracepoint("M_step:update sigma")
assert np.isfinite(my_sigma).all()
sigma_new = np.sqrt(comm.allreduce(my_sigma) / D / N_use) | conditional_block | |
mmca_et.py | (no_states, Hprime)
state_abs = self.state_abs # shape: (no_states,)
no_states = len(state_abs)
# Disable some warnings
old_seterr = np.seterr(divide='ignore', under='ignore')
# To compute et_loglike:
my_ldenom_sum = 0.0
ldenom_sum = 0.0
# Pr... | else: | random_line_split | |
SelectGroup.tsx | ///
/// softvis3d-frontend
/// Copyright (C) 2020 Stefan Rinderle and Yvo Niedrich
/// stefan@rinderle.info / yvo.niedrich@gmail.com
///
/// This program is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Lesser General Public
/// License as published by the Free Software Foundati... |
return child;
}
);
}
}
| {
return React.cloneElement(child, {
selected: child.props.value === this.props.selectedValue,
disabled: this.props.disabled || child.props.disabled,
ref: this.props.optionRef,
});
} | conditional_block |
SelectGroup.tsx | ///
/// softvis3d-frontend
/// Copyright (C) 2020 Stefan Rinderle and Yvo Niedrich
/// stefan@rinderle.info / yvo.niedrich@gmail.com
///
/// This program is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Lesser General Public
/// License as published by the Free Software Foundati... |
private renderChildren(): Array<React.Component<any, any>> {
return React.Children.map<React.ReactChild, any>(
this.props.children as SelectOption[],
(child: React.ReactChild) => {
if (typeof child === "object" && child.type === SelectOption) {
r... | {
return (
<optgroup disabled={this.props.disabled} label={this.props.label}>
{this.renderChildren()}
</optgroup>
);
} | identifier_body |
SelectGroup.tsx | ///
/// softvis3d-frontend
/// Copyright (C) 2020 Stefan Rinderle and Yvo Niedrich
/// stefan@rinderle.info / yvo.niedrich@gmail.com
///
/// This program is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Lesser General Public
/// License as published by the Free Software Foundati... |
return child;
}
);
}
} | selected: child.props.value === this.props.selectedValue,
disabled: this.props.disabled || child.props.disabled,
ref: this.props.optionRef,
});
} | random_line_split |
SelectGroup.tsx | ///
/// softvis3d-frontend
/// Copyright (C) 2020 Stefan Rinderle and Yvo Niedrich
/// stefan@rinderle.info / yvo.niedrich@gmail.com
///
/// This program is free software; you can redistribute it and/or
/// modify it under the terms of the GNU Lesser General Public
/// License as published by the Free Software Foundati... | () {
return (
<optgroup disabled={this.props.disabled} label={this.props.label}>
{this.renderChildren()}
</optgroup>
);
}
private renderChildren(): Array<React.Component<any, any>> {
return React.Children.map<React.ReactChild, any>(
th... | render | identifier_name |
lib.rs | });
info!("Starting servo");
simpleservo::init(opts, gl.gl_wrapper, wakeup, callbacks).expect("error initializing Servo");
let result = Box::new(ServoInstance {
scroll_state: ScrollState::TriggerUp,
scroll_scale: Scale::new(SCROLL_SCALE / hidpi),
shut_down_complete,
});
Box... | set_clipboard_contents | identifier_name | |
lib.rs | _update,
keyboard,
});
info!("Starting servo");
simpleservo::init(opts, gl.gl_wrapper, wakeup, callbacks).expect("error initializing Servo");
let result = Box::new(ServoInstance {
scroll_state: ScrollState::TriggerUp,
scroll_scale: Scale::new(SCROLL_SCALE / hidpi),
shut_... | {
None
} | identifier_body | |
lib.rs | => Err("Servo is not available in this thread"),
})
}
#[no_mangle]
pub unsafe extern "C" fn init_servo(
ctxt: EGLContext,
surf: EGLSurface,
disp: EGLDisplay,
landscape: bool,
app: MLApp,
logger: MLLogger,
history_update: MLHistoryUpdate,
url_update: MLURLUpdate,
keyboard: MLKey... | let service = Box::new(service);
let heartbeat = Box::new(heartbeat);
VRInitOptions::VRService(service, heartbeat)
} else {
VRInitOptions::None
};
let xr_discovery: Option<Box<dyn webxr_api::Discovery>> = if !landscape {
let discovery = MagicLeapDiscovery::new(ctxt, ... | let vr_init = if !landscape {
let name = String::from("Magic Leap VR Display");
let (service, heartbeat) = MagicLeapVRService::new(name, ctxt, gl.gl_wrapper.clone())
.expect("Failed to create VR service"); | random_line_split |
featured.js | EasyBlog.module( "featured" , function($) {
var module = this;
// require: start
EasyBlog.require()
.done(function(){
// controller: start
EasyBlog.Controller(
"Featured.Scroller",
{
defaultOptions: {
elements: null,
itemWidth: null,
// Auto rotate option
autorotate: {
enabled : false,
... | }
},
function(self) {return {
/**
* Featured scroller object initialization happens here.
*
*/
init: function() {
// Set the current holder width to a temporary location.
self.options.itemWidth = self.placeHolder().width() + 1;
// Calculate the total width of the whole parent container as ... | "{slider}" : ".featured-entries",
"{sliderItems}" : ".slider-holder ul li",
"{sliderNavigation}" : ".featured-navi .featured-a a" | random_line_split |
featured.js | EasyBlog.module( "featured" , function($) {
var module = this;
// require: start
EasyBlog.require()
.done(function(){
// controller: start
EasyBlog.Controller(
"Featured.Scroller",
{
defaultOptions: {
elements: null,
itemWidth: null,
// Auto rotate option
autorotate: {
enabled : false,
... |
},
nextItem : function( element )
{
var index = $( element ).data( 'slider' );
var left = 0;
// If the current index is 1, we can just leave left as 0
if( index != 1 )
{
left = self.options.itemWidth * parseInt( index - 1 );
}
// Since any items after the first item is hidden by ... | {
setTimeout( function(){
self.initAutoRotate();
}, parseInt( self.options.autorotate.interval ) * 1000 );
} | conditional_block |
admin.py | from django.contrib import admin
from django import forms
from django.contrib.auth.models import User
from sample.models import (Doctor, Worker, Patient, SpecialtyType, TimeSlot, Case, Comment, CommentGroup,
Scan)
class searchDoctor(admin.ModelAdmin):
list_display = ['user_first_name', 'user_last_name', '... |
class searchCase(admin.ModelAdmin):
search_fields = ['id']
list_display = ['id']
class searchComment(admin.ModelAdmin):
search_fields = ['text']
list_display = ['text']
class searchScan(admin.ModelAdmin):
search_fields = ['patient', 'comments']
admin.site.register(Doctor, searchDoctor)
admin.si... | search_fields = ['start_time', 'end_time'] | identifier_body |
admin.py | from django.contrib import admin
from django import forms |
from sample.models import (Doctor, Worker, Patient, SpecialtyType, TimeSlot, Case, Comment, CommentGroup,
Scan)
class searchDoctor(admin.ModelAdmin):
list_display = ['user_first_name', 'user_last_name', 'get_some_value']
search_fields = ['user__first_name', 'user__last_name',
'sp... | from django.contrib.auth.models import User | random_line_split |
admin.py | from django.contrib import admin
from django import forms
from django.contrib.auth.models import User
from sample.models import (Doctor, Worker, Patient, SpecialtyType, TimeSlot, Case, Comment, CommentGroup,
Scan)
class searchDoctor(admin.ModelAdmin):
list_display = ['user_first_name', 'user_last_name', '... | (admin.ModelAdmin):
list_display = ['user_first_name', 'user_last_name']
search_fields = ['user__first_name', 'user__last_name']
class searchPatient(admin.ModelAdmin):
list_display = ['first_name', 'last_name']
search_fields = ['first_name', 'last_name']
class searchSpeciality(admin.ModelAdmin):
s... | searchWorker | identifier_name |
toggleEnabled.js | /* Updates fields based on checkbox changes
*/
var PRFtoggleEnabled = function(cbox, id, type) {
oldval = cbox.checked ? 0 : 1;
var dataS = {
"action" : "toggleEnabled",
"id": id,
"type": type,
"oldval": oldval,
};
data = $.param(dataS);
$.ajax({
type: "POST"... | (d, fld, tm_type)
{
document.getElementById(fld + "_month").selectedIndex = d.getMonth() + 1;
document.getElementById(fld + "_day").selectedIndex = d.getDate();
document.getElementById(fld + "_year").value = d.getFullYear();
// Update the time, if time fields are present.
if (tm_type != 0) {
... | PRF_updateDate | identifier_name |
toggleEnabled.js | /* Updates fields based on checkbox changes
*/
var PRFtoggleEnabled = function(cbox, id, type) {
oldval = cbox.checked ? 0 : 1;
var dataS = {
"action" : "toggleEnabled",
"id": id,
"type": type,
"oldval": oldval,
};
data = $.param(dataS);
$.ajax({
type: "POST"... |
document.getElementById(fld + "_hour").selectedIndex = hour;
document.getElementById(fld + "_minute").selectedIndex = d.getMinutes();
}
}
| {
if (hour == 0) {
hour = 12;
} else if (hour > 12) {
hour -= 12;
ampm = 1;
}
document.getElementById(fld + "_ampm").selectedIndex = ampm;
} | conditional_block |
toggleEnabled.js | /* Updates fields based on checkbox changes
*/
var PRFtoggleEnabled = function(cbox, id, type) {
oldval = cbox.checked ? 0 : 1;
var dataS = {
"action" : "toggleEnabled",
"id": id,
"type": type,
"oldval": oldval,
};
data = $.param(dataS);
$.ajax({
type: "POST"... | }
}
| {
document.getElementById(fld + "_month").selectedIndex = d.getMonth() + 1;
document.getElementById(fld + "_day").selectedIndex = d.getDate();
document.getElementById(fld + "_year").value = d.getFullYear();
// Update the time, if time fields are present.
if (tm_type != 0) {
var hour = d.get... | identifier_body |
toggleEnabled.js | /* Updates fields based on checkbox changes
*/
var PRFtoggleEnabled = function(cbox, id, type) {
oldval = cbox.checked ? 0 : 1;
var dataS = {
"action" : "toggleEnabled",
"id": id,
"type": type,
"oldval": oldval,
};
data = $.param(dataS);
$.ajax({
type: "POST"... | }
} | }
document.getElementById(fld + "_ampm").selectedIndex = ampm;
}
document.getElementById(fld + "_hour").selectedIndex = hour;
document.getElementById(fld + "_minute").selectedIndex = d.getMinutes(); | random_line_split |
sbtview.py | import sublime
import sublime_plugin
try:
from .sbtsettings import SBTSettings
from .util import maybe, OnePerWindow
except(ValueError):
from sbtsettings import SBTSettings
from util import maybe, OnePerWindow
import re
class SbtView(OnePerWindow):
settings = {
"line_numbers": False,
... |
def delete_word_left(self):
if self.panel.sel()[0].begin() > self._output_size:
for r in self.panel.sel():
p = max(self.panel.word(r).begin(), self._output_size)
self.panel.sel().add(sublime.Region(p, r.end()))
self._erase_output(*self.panel.sel())
... | p = self.panel.sel()[-1].end()
self._erase_output(sublime.Region(self._output_size, p)) | conditional_block |
sbtview.py | import sublime
import sublime_plugin
try:
from .sbtsettings import SBTSettings
from .util import maybe, OnePerWindow
except(ValueError):
from sbtsettings import SBTSettings
from util import maybe, OnePerWindow
import re
class SbtView(OnePerWindow):
settings = {
"line_numbers": False,
... |
def start(self):
self.clear_output()
self.show()
self._set_running(True)
def finish(self):
self.show_output('\n -- Finished --\n')
self._set_running(False)
def show(self):
self._update_panel_colors()
self.window.run_command('show_panel', {'panel': ... | self.window = window
self.settings = SBTSettings(window)
self.panel = self.window.get_output_panel('sbt')
self.panel.set_syntax_file("Packages/SublimeSBT/SBTOutput.hidden-tmLanguage")
for name, setting in SbtView.settings.items():
self.panel.settings().set(name, setting)
... | identifier_body |
sbtview.py | import sublime
import sublime_plugin
try:
from .sbtsettings import SBTSettings
from .util import maybe, OnePerWindow
except(ValueError):
from sbtsettings import SBTSettings
from util import maybe, OnePerWindow
import re
class SbtView(OnePerWindow):
settings = {
"line_numbers": False,
... | (self):
self._update_panel_colors()
self.window.run_command('show_panel', {'panel': 'output.sbt'})
sublime.set_timeout(self._show_selection, 0)
def hide(self):
self.window.run_command('hide_panel', {'panel': 'output.sbt'})
def focus(self):
self.window.focus_view(self.pa... | show | identifier_name |
sbtview.py | import sublime
import sublime_plugin
try:
from .sbtsettings import SBTSettings
from .util import maybe, OnePerWindow
except(ValueError):
from sbtsettings import SBTSettings
from util import maybe, OnePerWindow
import re
class SbtView(OnePerWindow):
settings = {
"line_numbers": False,
... | self._update_panel_colors()
self.window.run_command('show_panel', {'panel': 'output.sbt'})
sublime.set_timeout(self._show_selection, 0)
def hide(self):
self.window.run_command('hide_panel', {'panel': 'output.sbt'})
def focus(self):
self.window.focus_view(self.panel)
... | random_line_split | |
low-priority.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _pure = require('recompose/pure');
var _pure2 = _interopRequireDefault(_pure);
var _SvgIcon = require('../../SvgIcon');
var _SvgIcon2 = _interopRequireDe... | (obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var ContentLowPriority = function ContentLowPriority(props) {
return _react2.default.createElement(
_SvgIcon2.default,
props,
_react2.default.createElement('path', { d: 'M14 5h8v2h-8zm0 5.5h8v2h-8zm0 5.5h8v2h-8zM2 11.5C2 15.08 4.92 18 8.5 1... | _interopRequireDefault | identifier_name |
low-priority.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _pure = require('recompose/pure');
var _pure2 = _interopRequireDefault(_pure);
var _SvgIcon = require('../../SvgIcon');
var _SvgIcon2 = _interopRequireDe... |
exports.default = ContentLowPriority; | ContentLowPriority.displayName = 'ContentLowPriority'; | random_line_split |
low-priority.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _pure = require('recompose/pure');
var _pure2 = _interopRequireDefault(_pure);
var _SvgIcon = require('../../SvgIcon');
var _SvgIcon2 = _interopRequireDe... |
var ContentLowPriority = function ContentLowPriority(props) {
return _react2.default.createElement(
_SvgIcon2.default,
props,
_react2.default.createElement('path', { d: 'M14 5h8v2h-8zm0 5.5h8v2h-8zm0 5.5h8v2h-8zM2 11.5C2 15.08 4.92 18 8.5 18H9v2l3-3-3-3v2h-.5C6.02 16 4 13.98 4 11.5S6.02 7 8.5 7H12V5H8.5... | { return obj && obj.__esModule ? obj : { default: obj }; } | identifier_body |
setup.py | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... | install_requires=[
'msrest>=0.6.21',
'azure-common~=1.1',
'azure-mgmt-core>=1.3.0,<2.0.0',
],
python_requires=">=3.6"
) | 'tests',
# Exclude packages that will be covered by PEP420 or nspkg
'azure',
'azure.mgmt',
]), | random_line_split |
setup.py | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------... |
with open('README.md', encoding='utf-8') as f:
readme = f.read()
with open('CHANGELOG.md', encoding='utf-8') as f:
changelog = f.read()
setup(
name=PACKAGE_NAME,
version=version,
description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME),
long_description=readme + ... | raise RuntimeError('Cannot find version information') | conditional_block |
error_page.js | import React from 'react';
import PropTypes from 'prop-types';
import Footer from './../../../components/footer/footer';
function ErrorPage({ env, componentInfo, err }) {
const isDevelopment = env === 'development';
if (isDevelopment) |
return (
<div className="error-page">
<h1>Error Occurred.</h1>
{isDevelopment ? (
<div>
<h2>Error Message: {err.message}</h2>
<h2>Error Stack: {JSON.stringify(err.stack, null, 2)}</h2>
<h2>Component Info: {JSON.stringify(componentInfo, null, 2)}</h2>
</di... | {
console.error(err); // eslint-disable-line no-console
console.error(err.stack); // eslint-disable-line no-console
} | conditional_block |
error_page.js | import React from 'react';
import PropTypes from 'prop-types';
import Footer from './../../../components/footer/footer';
function ErrorPage({ env, componentInfo, err }) | );
}
ErrorPage.propTypes = {
err: PropTypes.shape({}),
componentInfo: PropTypes.shape({}),
env: PropTypes.string.isRequired
};
ErrorPage.defaultProps = {
err: {},
componentInfo: {}
};
export default ErrorPage;
| {
const isDevelopment = env === 'development';
if (isDevelopment) {
console.error(err); // eslint-disable-line no-console
console.error(err.stack); // eslint-disable-line no-console
}
return (
<div className="error-page">
<h1>Error Occurred.</h1>
{isDevelopment ? (
<div>
... | identifier_body |
error_page.js | import React from 'react';
import PropTypes from 'prop-types';
import Footer from './../../../components/footer/footer';
function | ({ env, componentInfo, err }) {
const isDevelopment = env === 'development';
if (isDevelopment) {
console.error(err); // eslint-disable-line no-console
console.error(err.stack); // eslint-disable-line no-console
}
return (
<div className="error-page">
<h1>Error Occurred.</h1>
{isDevelopm... | ErrorPage | identifier_name |
error_page.js | import React from 'react';
import PropTypes from 'prop-types';
import Footer from './../../../components/footer/footer';
function ErrorPage({ env, componentInfo, err }) {
const isDevelopment = env === 'development';
if (isDevelopment) {
console.error(err); // eslint-disable-line no-console
console.error(e... | <h1>Error Occurred.</h1>
{isDevelopment ? (
<div>
<h2>Error Message: {err.message}</h2>
<h2>Error Stack: {JSON.stringify(err.stack, null, 2)}</h2>
<h2>Component Info: {JSON.stringify(componentInfo, null, 2)}</h2>
</div>
) : (
<p>We\'re sorry please... | return (
<div className="error-page"> | random_line_split |
currency_symbol.js | angular.module('app.filters').filter('currencySymbol', currencySymbol);
currencySymbol.$inject = ['$filter'];
function | ($filter) {
var currencySymbols = {
'EUR': '€ ',
'GBP': '£ ',
'USD': '$ ',
'ZAR': 'R ',
'NOR': 'kr ',
'DKK': 'kr ',
'SEK': 'kr ',
'CHF': 'CHF ',
};
return function(amount, currency, ... | currencySymbol | identifier_name |
currency_symbol.js | angular.module('app.filters').filter('currencySymbol', currencySymbol);
currencySymbol.$inject = ['$filter'];
function currencySymbol($filter) | return $filter('currency')(newAmount, currencySymbols[currency]);
};
}
| {
var currencySymbols = {
'EUR': '€ ',
'GBP': '£ ',
'USD': '$ ',
'ZAR': 'R ',
'NOR': 'kr ',
'DKK': 'kr ',
'SEK': 'kr ',
'CHF': 'CHF ',
};
return function(amount, currency, divide = f... | identifier_body |
currency_symbol.js | angular.module('app.filters').filter('currencySymbol', currencySymbol);
currencySymbol.$inject = ['$filter'];
function currencySymbol($filter) {
var currencySymbols = {
'EUR': '€ ',
'GBP': '£ ',
'USD': '$ ',
'ZAR': 'R ',
'NOR': 'kr ',
'DK... |
return $filter('currency')(newAmount, currencySymbols[currency]);
};
}
| {
// Divide the amount by 100 so we get the proper amount;
newAmount /= 100;
} | conditional_block |
currency_symbol.js | angular.module('app.filters').filter('currencySymbol', currencySymbol);
currencySymbol.$inject = ['$filter'];
function currencySymbol($filter) {
var currencySymbols = {
'EUR': '€ ',
'GBP': '£ ', | 'ZAR': 'R ',
'NOR': 'kr ',
'DKK': 'kr ',
'SEK': 'kr ',
'CHF': 'CHF ',
};
return function(amount, currency, divide = false) {
let newAmount = amount;
if (divide) {
// Divide the amount by 100 so we... | 'USD': '$ ', | random_line_split |
auth.service.ts | import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Injectable } from '@angular/core';
import { Account } from './models/account';
@Injectable()
export class AuthService {
constructor(private http : Http) {}
private user : boolean;
isLoggedIn() : boolean {
if (this.use... |
}).catch(res => {
console.log(res);
return Promise.reject(false);
});
}
} | {
return Promise.reject(false);
} | conditional_block |
auth.service.ts | import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Injectable } from '@angular/core';
import { Account } from './models/account';
@Injectable()
export class AuthService {
constructor(private http : Http) {}
private user : boolean;
| () : boolean {
if (this.user) {
return true;
} else {
return false;
}
}
getUserStatus() : Promise<void> {
return this.http.get('api/status').toPromise()
.then(res => {
if (res.json().status) {
this.user = true;
} else {
this.user = false;
}
}).catch(res => {
console.log(res);
... | isLoggedIn | identifier_name |
auth.service.ts | import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise'; |
import { Injectable } from '@angular/core';
import { Account } from './models/account';
@Injectable()
export class AuthService {
constructor(private http : Http) {}
private user : boolean;
isLoggedIn() : boolean {
if (this.user) {
return true;
} else {
return false;
}
}
getUserStatus() : Promise<... | random_line_split | |
auth.service.ts | import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Injectable } from '@angular/core';
import { Account } from './models/account';
@Injectable()
export class AuthService {
constructor(private http : Http) {}
private user : boolean;
isLoggedIn() : boolean {
if (this.use... |
register(username : string, password : string) : Promise<boolean> {
return this.http.post('api/register', { username : username, password : password }).toPromise()
.then(res => {
if (res.status && res.status == 200) {
return Promise.resolve(true);
} else {
return Promise.reject(false);
}
}).ca... | {
return this.http.get('api/logout').toPromise()
.then(res => {
this.user = false;
return Promise.resolve(true);
}).catch(res => {
this.user = false;
console.log(res);
return Promise.reject(false);
});
} | identifier_body |
tips.rs | /// Utilties for loading remote FROG tips.
use futures::{Future, Stream};
use errors::*;
use hyper::{self, Method, Request};
use hyper::header::ContentType;
use hyper_tls;
use tokio_core::reactor::Core; |
/// A tip, as received from the server. These are the public API fields.
#[allow(dead_code)]
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Tip {
pub number: TipNum,
pub tip: String,
}
/// A croak is normally precisely 50 tips, but serde_json can't handle encoding and decoding
/// fixed-sized arra... | use serde_json;
use std::io;
/// A tip number, as received from the server. I doubt we'll overflow.
type TipNum = u64; | random_line_split |
tips.rs | /// Utilties for loading remote FROG tips.
use futures::{Future, Stream};
use errors::*;
use hyper::{self, Method, Request};
use hyper::header::ContentType;
use hyper_tls;
use tokio_core::reactor::Core;
use serde_json;
use std::io;
/// A tip number, as received from the server. I doubt we'll overflow.
type TipNum = u... | {
pub number: TipNum,
pub tip: String,
}
/// A croak is normally precisely 50 tips, but serde_json can't handle encoding and decoding
/// fixed-sized arrays, so this contains a vector of tips.
#[derive(Serialize, Deserialize, Debug)]
pub struct Croak {
pub tips: Vec<Tip>,
}
/// Return a `Result` with a `... | Tip | identifier_name |
score_student.js | // JavaScript Document
var datable_result;
var _url_path = baseurl+'enrolment/new_enrolment/';
var _url_edit = baseurl+'enrolment/new_enrolment/';
var _url_del = baseurl+'enrolment/delete/';
$(document).ready(function() {
datable_result = $('#datable_score_student').DataTable( { | "filter" : true,
"info" : true,
"paging" : true,
"ordering" : true,
"processing" : true,
"serverSide" : true ,
dom : "<'row'<'col-sm-4'l><'col-sm-4 text-center'B><'col-sm-4'f>>tp",
buttons: [
{extend: 'copy',className: 'btn-sm... | // fixedColumns : true, | random_line_split |
score_student.js | // JavaScript Document
var datable_result;
var _url_path = baseurl+'enrolment/new_enrolment/';
var _url_edit = baseurl+'enrolment/new_enrolment/';
var _url_del = baseurl+'enrolment/delete/';
$(document).ready(function() {
datable_result = $('#datable_score_student').DataTable( {
// fixedColumns : true,... | {
$.ajax({
type: "POST",
url: url,
success: function(data){
datable_result.draw();
}
});
} | identifier_body | |
score_student.js | // JavaScript Document
var datable_result;
var _url_path = baseurl+'enrolment/new_enrolment/';
var _url_edit = baseurl+'enrolment/new_enrolment/';
var _url_del = baseurl+'enrolment/delete/';
$(document).ready(function() {
datable_result = $('#datable_score_student').DataTable( {
// fixedColumns : true,... | (url){
delete_data(url,remove_row);
}
//
function remove_row(url){
$.ajax({
type: "POST",
url: url,
success: function(data){
datable_result.draw();
}
});
}
| on_delete_data | identifier_name |
block_sync.rs | s: bool, start_hash: &H256, start_number: BlockNumber) -> Self {
BlockDownloader {
state: State::Idle,
highest_block: None,
last_imported_block: start_number,
last_imported_hash: start_hash.clone(),
last_round_start: start_number,
last_round_start_hash: start_hash.clone(),
blocks: BlockCollection... |
self.blocks.insert_headers(headers);
trace!(target: "sync", "Inserted {} headers", count);
},
_ => trace!(target: "sync", "Unexpected headers({})", headers.len()),
}
Ok(DownloadAction::None)
}
/// Called by peer once it has new block bodies
pub fn import_bodies(&mut self, _io: &mut SyncIo, r: &U... | {
trace!(target: "sync", "No useful headers");
return Err(BlockDownloaderImportError::Useless);
} | conditional_block |
block_sync.rs | BlockStatus::Unknown => {
headers.push(hdr.as_raw().to_vec());
hashes.push(hash);
}
}
}
// Disable the peer for this syncing round if it gives invalid chain
if !valid_response {
trace!(target: "sync", "Invalid headers response");
return Err(BlockDownloaderImportError::Invalid);
}
mat... | let block = block_and_receipts.block;
let receipts = block_and_receipts.receipts;
let (h, number, parent) = {
let header = BlockView::new(&block).header_view();
(header.sha3(), header.number(), header.parent_hash()) | random_line_split | |
block_sync.rs | (hash.clone());
}
/// Unmark header as being downloaded.
pub fn clear_header_download(&mut self, hash: &H256) {
self.blocks.clear_header_download(hash)
}
/// Unmark block body as being downloaded.
pub fn clear_body_download(&mut self, hashes: &[H256]) {
self.blocks.clear_body_download(hashes)
}
/// Unmar... | {
self.state = State::ChainHead;
trace!(target: "sync", "Starting round (last imported count = {:?}, last started = {}, block = {:?}", self.imported_this_round, self.last_round_start, self.last_imported_block);
// Check if need to retract to find the common block. The problem is that the peers still return header... | identifier_body | |
block_sync.rs | {
/// No active downloads.
Idle,
/// Downloading subchain heads
ChainHead,
/// Downloading blocks
Blocks,
/// Download is complete
Complete,
}
/// Data that needs to be requested from a peer.
pub enum BlockRequest {
Headers {
start: H256,
count: u64,
skip: u64,
},
Bodies {
hashes: Vec<H256>,
},
R... | State | identifier_name | |
index.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import RcSelect, { Option, OptGroup } from 'rc-select';
import classNames from 'classnames';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
export interface AbstractSelectProps {... | {
multiple: mode === 'multiple',
tags: mode === 'tags',
combobox: isCombobox,
};
const notFoundContentLocale = isCombobox ?
null : notFoundContent || locale.notFoundContent;
return (
<RcSelect
{...restProps}
{...modeConfig}
prefixCls={prefixCls}
... | {
// children 带 dom 结构时,无法填入输入框
optionLabelProp = optionLabelProp || 'value';
}
const modeConfig = | conditional_block |
index.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import RcSelect, { Option, OptGroup } from 'rc-select';
import classNames from 'classnames';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
export interface AbstractSelectProps {... |
saveSelect = (node: any) => {
this.rcSelect = node;
}
renderSelect = (locale: SelectLocale) => {
const {
prefixCls,
className = '',
size,
mode,
...restProps,
} = this.props;
const cls = classNames({
[`${prefixCls}-lg`]: size === 'large',
[`${prefixCls}-... | {
this.rcSelect.blur();
} | identifier_body |
index.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import RcSelect, { Option, OptGroup } from 'rc-select';
import classNames from 'classnames';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
export interface AbstractSelectProps {... | () {
this.rcSelect.focus();
}
blur() {
this.rcSelect.blur();
}
saveSelect = (node: any) => {
this.rcSelect = node;
}
renderSelect = (locale: SelectLocale) => {
const {
prefixCls,
className = '',
size,
mode,
...restProps,
} = this.props;
const cls = cl... | focus | identifier_name |
index.tsx | import * as React from 'react';
import PropTypes from 'prop-types';
import RcSelect, { Option, OptGroup } from 'rc-select';
import classNames from 'classnames';
import LocaleReceiver from '../locale-provider/LocaleReceiver';
import defaultLocale from '../locale-provider/default';
export interface AbstractSelectProps {... | allowClear?: boolean;
disabled?: boolean;
style?: React.CSSProperties;
placeholder?: string;
dropdownClassName?: string;
dropdownStyle?: React.CSSProperties;
dropdownMenuStyle?: React.CSSProperties;
onSearch?: (value: string) => any;
filterOption?: boolean | ((inputValue: string, option: React.ReactEl... | showSearch?: boolean; | random_line_split |
char_class.rs | // Copyright 2014 Strahinja Val Markovic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... |
let chars = toU32Vector( &contents );
let mut char_class = CharClass { single_chars: Vec::new(),
ranges: Vec::new() };
let mut index = 0;
loop {
match rangeAtIndex( index, &chars ) {
Some( range ) => {
char_class.ranges.push( range );
... | {
match ( chars.get( index ),
chars.get( index + 1 ),
chars.get( index + 2 ) ) {
( Some( char1 ), Some( char2 ), Some( char3 ) )
if *char2 == '-' as u32 => Some( ( *char1, *char3 ) ),
_ => None
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.