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 |
|---|---|---|---|---|
test_msg_types.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Daniel Zhang (張道博)'
__copyright__ = 'Copyright (c) 2014, University of Hawaii Smart Energy Project'
__license__ = 'https://raw.github' \
'.com/Hawaii-Smart-Energy-Project/Maui-Smart-Grid/master/BSD' \
'-LICENSE.txt'
import unittes... | def tearDown(self):
pass
if __name__ == '__main__':
RUN_SELECTED_TESTS = True
if RUN_SELECTED_TESTS:
selected_tests = ['test_aggregation_types']
mySuite = unittest.TestSuite()
for t in selected_tests:
mySuite.addTest(MSGTypesTester(t))
unittest.TextTestRu... | ssertTrue(MSGAggregationTypes.weather in MSGAggregationTypes)
self.assertTrue(MSGAggregationTypes.egauge in MSGAggregationTypes)
self.assertTrue(MSGAggregationTypes.circuit in MSGAggregationTypes)
self.assertTrue(MSGAggregationTypes.irradiance in MSGAggregationTypes)
| identifier_body |
test_msg_types.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Daniel Zhang (張道博)'
__copyright__ = 'Copyright (c) 2014, University of Hawaii Smart Energy Project'
__license__ = 'https://raw.github' \
'.com/Hawaii-Smart-Energy-Project/Maui-Smart-Grid/master/BSD' \
'-LICENSE.txt'
import unittes... | unittest.TextTestRunner().run(mySuite)
else:
unittest.main()
| e.addTest(MSGTypesTester(t))
| conditional_block |
test_msg_types.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Daniel Zhang (張道博)'
__copyright__ = 'Copyright (c) 2014, University of Hawaii Smart Energy Project'
__license__ = 'https://raw.github' \
'.com/Hawaii-Smart-Energy-Project/Maui-Smart-Grid/master/BSD' \
'-LICENSE.txt'
import unittes... | """
def setUp(self):
self.logger = SEKLogger(__name__, 'DEBUG')
def test_aggregation_types(self):
self.assertTrue(MSGAggregationTypes.weather in MSGAggregationTypes)
self.assertTrue(MSGAggregationTypes.egauge in MSGAggregationTypes)
self.assertTrue(MSGAggregationTypes.circu... | class MSGTypesTester(unittest.TestCase):
"""
Unit tests for MSG Aggregation Types. | random_line_split |
get_keyword_feature.py | #-------------------------------------------------------------------------------
# coding=utf8
# Name: 模块1
# Purpose:
#
# Author: zhx
#
# Created: 10/05/2016
# Copyright: (c) zhx 2016
# Licence: <your licence>
#-------------------------------------------------------------------------------
import ... | f len(tmplist)!=0:
tmplist.sort()
mean = tmplist[int(len(tmplist)/2)]
for w in tmpdic:
if tmpdic[w]==mean:
mean_word =w
if min_word!='':
new_sheet.cell(row=r,column=1).value = words[min_word][0]
new_sheet.cell(row=r... | as_key(w):
tmpdic[w] =int(words[w][2])
tmplist.append(int(words[w][2]))
likes = int(words[w][2])
if likes<minlike:
minlike = likes
min_word = w
if likes>maxlike:
maxlike = likes
... | conditional_block |
get_keyword_feature.py | #-------------------------------------------------------------------------------
# coding=utf8
# Name: 模块1
# Purpose:
#
# Author: zhx
#
# Created: 10/05/2016
# Copyright: (c) zhx 2016
# Licence: <your licence>
#-------------------------------------------------------------------------------
import ... | new_sheet = cctv_new.active
#print cctv_data.get_sheet_names()
sheet1 = cctv_keywords["Sheet"]
sheet2 = cctv_data["Sheet"]
words = {}
for r in xrange(1,36003):
word = sheet1.cell(row=r,column=1).value
word_min = sheet1.cell(row=r,column=2).value
word_max = sheet1.cell(row... | def main():
cctv_data = openpyxl.load_workbook("cctv.xlsx")
cctv_keywords = openpyxl.load_workbook("cctv_keywords.xlsx")
cctv_new = openpyxl.Workbook() | random_line_split |
get_keyword_feature.py | #-------------------------------------------------------------------------------
# coding=utf8
# Name: 模块1
# Purpose:
#
# Author: zhx
#
# Created: 10/05/2016
# Copyright: (c) zhx 2016
# Licence: <your licence>
#-------------------------------------------------------------------------------
import ... | cctv_data = openpyxl.load_workbook("cctv.xlsx")
cctv_keywords = openpyxl.load_workbook("cctv_keywords.xlsx")
cctv_new = openpyxl.Workbook()
new_sheet = cctv_new.active
#print cctv_data.get_sheet_names()
sheet1 = cctv_keywords["Sheet"]
sheet2 = cctv_data["Sheet"]
words = {}
for r in x... | ():
| identifier_name |
get_keyword_feature.py | #-------------------------------------------------------------------------------
# coding=utf8
# Name: 模块1
# Purpose:
#
# Author: zhx
#
# Created: 10/05/2016
# Copyright: (c) zhx 2016
# Licence: <your licence>
#-------------------------------------------------------------------------------
import ... | if like == '赞':
like = '0'
if repost =='转发':
repost = '0'
like_repost = int(like)+int(repost)
if like_repost>threshold:
popular =1
else:
popular =0
hour = int(time[1:3])
minute =int (time[4:])
time = hour*60 ... | _data = openpyxl.load_workbook("cctv.xlsx")
cctv_keywords = openpyxl.load_workbook("cctv_keywords.xlsx")
cctv_new = openpyxl.Workbook()
new_sheet = cctv_new.active
#print cctv_data.get_sheet_names()
sheet1 = cctv_keywords["Sheet"]
sheet2 = cctv_data["Sheet"]
words = {}
for r in xrange(1,... | identifier_body |
media_operations.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
i... |
file_type, ext = content_type.split('/')
try:
metadata = process_file(content, file_type)
except OSError: # error from PIL when image is supposed to be an image but is not.
raise SuperdeskApiError.internalError('Failed to process file')
file_name = get_file_name(content)
content.se... | content_type = magic.from_buffer(content.getvalue(), mime=True).decode('UTF-8')
content.seek(0) | conditional_block |
media_operations.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
i... | (metadata):
return dict((k.lower(), json.dumps(v)) for k, v in metadata.items())
def decode_metadata(metadata):
return dict((k.lower(), decode_val(v)) for k, v in metadata.items())
def decode_val(string_val):
"""Format dates that elastic will try to convert automatically."""
val = json.loads(string_... | encode_metadata | identifier_name |
media_operations.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
i... | if rv.status_code not in (200, 201):
raise SuperdeskApiError.internalError('Failed to retrieve file from URL: %s' % url)
mime = magic.from_buffer(rv.content, mime=True).decode('UTF-8')
ext = mime.split('/')[1]
name = 'stub.' + ext
return BytesIO(rv.content), name, mime
def download_file_f... |
def download_file_from_url(url):
rv = requests.get(url, timeout=15) | random_line_split |
media_operations.py | # -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
i... |
def decode_val(string_val):
"""Format dates that elastic will try to convert automatically."""
val = json.loads(string_val)
try:
arrow.get(val, 'YYYY-MM-DD') # test if it will get matched by elastic
return str(arrow.get(val))
except (Exception):
return val
def process_file(... | return dict((k.lower(), decode_val(v)) for k, v in metadata.items()) | identifier_body |
profile_customization_app.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/cr_components/customize_themes/customize_themes.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import '... | (profileInfo: ProfileInfo) {
this.style.setProperty(
'--header-background-color', profileInfo.backgroundColor);
this.pictureUrl_ = profileInfo.pictureUrl;
this.isManaged_ = profileInfo.isManaged;
this.welcomeTitle_ = profileInfo.welcomeTitle;
}
}
customElements.define(
ProfileCustomizatio... | setProfileInfo_ | identifier_name |
profile_customization_app.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/cr_components/customize_themes/customize_themes.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import '... |
private isDoneButtonDisabled_(): boolean {
return !this.profileName_ || !this.$.nameInput.validate();
}
private setProfileInfo_(profileInfo: ProfileInfo) {
this.style.setProperty(
'--header-background-color', profileInfo.backgroundColor);
this.pictureUrl_ = profileInfo.pictureUrl;
this.... | {
this.profileCustomizationBrowserProxy_.done(this.profileName_);
} | identifier_body |
profile_customization_app.ts | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/cr_components/customize_themes/customize_themes.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import '... | * Called when the Done button is clicked. Sends the profile name back to
* native.
*/
private onDoneCustomizationClicked_() {
this.profileCustomizationBrowserProxy_.done(this.profileName_);
}
private isDoneButtonDisabled_(): boolean {
return !this.profileName_ || !this.$.nameInput.validate();
... | info => this.setProfileInfo_(info));
}
/** | random_line_split |
SpectrumBarGraphVisualizer.ts | /*
Feathers
Copyright 2012-2015 Joshua Tynjala. All Rights Reserved.
This program is free software. You can redistribute and/or modify it in
accordance with the terms of the accompanying license agreement.
*/
module feathers.media
{
import FeathersControl = feathers.core.FeathersControl;
import SoundChannel = flash... |
this.invalidate(this.INVALIDATION_FLAG_DATA);
}
/*override*/ public dispose():void
{
this.mediaPlayer = null;
super.dispose();
}
/*override*/ protected initialize():void
{
this._bars = new QuadBatch();
this.addChild(this._bars);
}
/*override*/ protected draw():void
{
this.autoS... | {
this.handlePlaybackStateChange();
this._mediaPlayer.addEventListener(this.MediaPlayerEventType.PLAYBACK_STATE_CHANGE, this.mediaPlayer_playbackStateChange);
} | conditional_block |
SpectrumBarGraphVisualizer.ts | /*
Feathers
Copyright 2012-2015 Joshua Tynjala. All Rights Reserved.
This program is free software. You can redistribute and/or modify it in
accordance with the terms of the accompanying license agreement.
*/
module feathers.media
{
import FeathersControl = feathers.core.FeathersControl;
import SoundChannel = flash... | if(this._mediaPlayer == value)
{
return;
}
if(this._mediaPlayer)
{
this._mediaPlayer.removeEventListener(this.MediaPlayerEventType.PLAYBACK_STATE_CHANGE, this.mediaPlayer_playbackStateChange);
}
this._mediaPlayer = <ITimedMediaPlayer>value ;
if(this._mediaPlayer)
{
this.handlePlay... | { | random_line_split |
SpectrumBarGraphVisualizer.ts | /*
Feathers
Copyright 2012-2015 Joshua Tynjala. All Rights Reserved.
This program is free software. You can redistribute and/or modify it in
accordance with the terms of the accompanying license agreement.
*/
module feathers.media
{
import FeathersControl = feathers.core.FeathersControl;
import SoundChannel = flash... | (value:IMediaPlayer)
{
if(this._mediaPlayer == value)
{
return;
}
if(this._mediaPlayer)
{
this._mediaPlayer.removeEventListener(this.MediaPlayerEventType.PLAYBACK_STATE_CHANGE, this.mediaPlayer_playbackStateChange);
}
this._mediaPlayer = <ITimedMediaPlayer>value ;
if(this._mediaPlayer)... | mediaPlayer | identifier_name |
SpectrumBarGraphVisualizer.ts | /*
Feathers
Copyright 2012-2015 Joshua Tynjala. All Rights Reserved.
This program is free software. You can redistribute and/or modify it in
accordance with the terms of the accompanying license agreement.
*/
module feathers.media
{
import FeathersControl = feathers.core.FeathersControl;
import SoundChannel = flash... |
/**
* @private
*/
protected _color:number = 0x000000;
public get color():number
{
return this._color;
}
/**
* @private
*/
public set color(value:number)
{
if(this._color == value)
{
return;
}
this._color = value;
this.invalidate(this.INVALIDATION_FLAG_STYLES);
}
... | {
if(this._gap == value)
{
return;
}
this._gap = value;
this.invalidate(this.INVALIDATION_FLAG_STYLES);
} | identifier_body |
test_cp_mgmt_service_icmp.py | # Ansible module to manage CheckPoint Firewall (c) 2019
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is dist... | (self, mocker, connection_mock):
mock_function = mocker.patch(function_path)
mock_function.return_value = {'changed': True, api_call_object: OBJECT_AFTER_UPDATE}
result = self._run_module(UPDATE_PAYLOAD)
assert result['changed']
assert OBJECT_AFTER_UPDATE.items() == result[api_c... | test_update | identifier_name |
test_cp_mgmt_service_icmp.py | # Ansible module to manage CheckPoint Firewall (c) 2019
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is dist... |
@pytest.fixture
def connection_mock(self, mocker):
connection_class_mock = mocker.patch('ansible.module_utils.network.checkpoint.checkpoint.Connection')
return connection_class_mock.return_value
def test_create(self, mocker, connection_mock):
mock_function = mocker.patch(function_... | return mocker.patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json) | identifier_body |
test_cp_mgmt_service_icmp.py | # Ansible module to manage CheckPoint Firewall (c) 2019
# | # Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with ... | # Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# | random_line_split |
pubsub-macros.rs | use jsonrpc_core;
use jsonrpc_pubsub;
use serde_json;
#[macro_use]
extern crate jsonrpc_derive;
use jsonrpc_core::futures::channel::mpsc;
use jsonrpc_pubsub::typed::Subscriber;
use jsonrpc_pubsub::{PubSubHandler, PubSubMetadata, Session, SubscriptionId};
use std::sync::Arc;
pub enum MyError {}
impl From<MyError> for ... |
}
type Result<T> = ::std::result::Result<T, MyError>;
#[rpc]
pub trait Rpc {
type Metadata;
/// Hello subscription.
#[pubsub(subscription = "hello", subscribe, name = "hello_subscribe", alias("hello_alias"))]
fn subscribe(&self, a: Self::Metadata, b: Subscriber<String>, c: u32, d: Option<u64>);
/// Hello subs... | {
unreachable!()
} | identifier_body |
pubsub-macros.rs | use jsonrpc_core;
use jsonrpc_pubsub;
use serde_json;
#[macro_use]
extern crate jsonrpc_derive;
use jsonrpc_core::futures::channel::mpsc;
use jsonrpc_pubsub::typed::Subscriber;
use jsonrpc_pubsub::{PubSubHandler, PubSubMetadata, Session, SubscriptionId};
use std::sync::Arc;
pub enum MyError {}
impl From<MyError> for ... | let mut io = PubSubHandler::default();
let rpc = RpcImpl::default();
io.extend_with(rpc.to_delegate());
// when
let meta = Metadata;
let req = r#"{"jsonrpc":"2.0","id":1,"method":"hello_alias","params":[1]}"#;
let res = io.handle_request_sync(req, meta);
let expected = r#"{
"jsonrpc": "2.0",
"result": 5,
... | #[test]
fn test_subscribe_with_alias() { | random_line_split |
pubsub-macros.rs | use jsonrpc_core;
use jsonrpc_pubsub;
use serde_json;
#[macro_use]
extern crate jsonrpc_derive;
use jsonrpc_core::futures::channel::mpsc;
use jsonrpc_pubsub::typed::Subscriber;
use jsonrpc_pubsub::{PubSubHandler, PubSubMetadata, Session, SubscriptionId};
use std::sync::Arc;
pub enum MyError {}
impl From<MyError> for ... | (&self, a: u64, b: u64) -> Result<u64> {
Ok(a + b)
}
fn notify(&self, a: u64) {
println!("Received `notify` with value: {}", a);
}
}
#[derive(Clone, Default)]
struct Metadata;
impl jsonrpc_core::Metadata for Metadata {}
impl PubSubMetadata for Metadata {
fn session(&self) -> Option<Arc<Session>> {
let (tx, ... | add | identifier_name |
TrustBoundary.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | # Unless required by applicable law or agreed to in writing,
# software distributed under 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 Lice... | # http://www.apache.org/licenses/LICENSE-2.0
# | random_line_split |
TrustBoundary.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | (self): return self.theComponents
def privilegeLevels(self): return self.thePrivilegeLevels
def tags(self): return self.theTags
| components | identifier_name |
TrustBoundary.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... |
def description(self): return self.theDescription
def components(self): return self.theComponents
def privilegeLevels(self): return self.thePrivilegeLevels
def tags(self): return self.theTags
| return self.theType | identifier_body |
middleware.py | import time
import re
from django.http import HttpResponseRedirect
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.conf import settings
# In-memory caches are used since different processes do not necessarily
# exhibit the same response times, even though they may share a ... |
def redirect_percentage_slowest_from_cache():
return cache.get('django_scaler_percentage_slowest')
def redirect_regexes_dummy():
return []
def redirect_regexes_from_cache():
return cache.get('django_scaler_regexes')
class ScalerMiddleware:
"""Add as the first middleware in your settings file"""... | return 0 | identifier_body |
middleware.py | import time
import re
from django.http import HttpResponseRedirect
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.conf import settings
# In-memory caches are used since different processes do not necessarily
# exhibit the same response times, even though they may share a ... | return HttpResponseRedirect(SERVER_BUSY_URL)
# On to automatic redirection
now = time.time()
# Marker for process_response
setattr(request, '_django_scaler_stamp', now)
# Cache key uses path info
prefix = request.META['PATH_INFO'] + '-scaler-'
... | if n_slowest or percentage_slowest:
# Sort by slowest reversed
paths = sorted(
_request_response_times,
key=_request_response_times.__getitem__,
reverse=True
)
if n_slowest:
li = paths... | conditional_block |
middleware.py | import time
import re
from django.http import HttpResponseRedirect
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.conf import settings
# In-memory caches are used since different processes do not necessarily
# exhibit the same response times, even though they may share a ... | now = time.time()
# Marker for process_response
setattr(request, '_django_scaler_stamp', now)
# Cache key uses path info
prefix = request.META['PATH_INFO'] + '-scaler-'
# Fetch values
key_stamp = prefix + 'stamp'
key_hits = prefix + 'hits'
key_t... | random_line_split | |
middleware.py | import time
import re
from django.http import HttpResponseRedirect
from django.core.cache import cache
from django.core.urlresolvers import reverse
from django.conf import settings
# In-memory caches are used since different processes do not necessarily
# exhibit the same response times, even though they may share a ... | :
"""Add as the first middleware in your settings file"""
def process_request(self, request):
# Ajax requests are not subject to scaling. Busy page is exempt from
# scaling.
if request.is_ajax() or request.META['PATH_INFO'] == SERVER_BUSY_URL:
return
# If a n_slowe... | ScalerMiddleware | identifier_name |
rec-extend.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 origin: Point = Point {x: 0, y: 0};
let right: Point = Point {x: origin.x + 10,.. origin};
let up: Point = Point {y: origin.y + 10,.. origin};
assert_eq!(origin.x, 0);
assert_eq!(origin.y, 0);
assert_eq!(right.x, 10);
assert_eq!(right.y, 0);
assert_eq!(up.x, 0);
assert_eq!(up.y... | identifier_body | |
rec-extend.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 ... | assert_eq!(origin.x, 0);
assert_eq!(origin.y, 0);
assert_eq!(right.x, 10);
assert_eq!(right.y, 0);
assert_eq!(up.x, 0);
assert_eq!(up.y, 10);
} |
pub fn main() {
let origin: Point = Point {x: 0, y: 0};
let right: Point = Point {x: origin.x + 10,.. origin};
let up: Point = Point {y: origin.y + 10,.. origin}; | random_line_split |
rec-extend.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 origin: Point = Point {x: 0, y: 0};
let right: Point = Point {x: origin.x + 10,.. origin};
let up: Point = Point {y: origin.y + 10,.. origin};
assert_eq!(origin.x, 0);
assert_eq!(origin.y, 0);
assert_eq!(right.x, 10);
assert_eq!(right.y, 0);
assert_eq!(up.x, 0);
assert_eq!(u... | main | identifier_name |
expense_claim.py | appe
from frappe import _
from frappe.utils import get_fullname, flt, cstr
from frappe.model.document import Document
from erpnext.hr.utils import set_employee_name
from erpnext.accounts.party import get_party_account
from erpnext.accounts.general_ledger import make_gl_entries
from erpnext.accounts.doctype.sales_invoic... |
elif self.total_sanctioned_amount > 0 and self.docstatus == 1 and self.approval_status == 'Approved':
self.status = "Unpaid"
elif self.docstatus == 1 and self.approval_status == 'Rejected':
self.status = 'Rejected'
def set_payable_account(self):
if not self.payable_account and not self.is_paid:
self.p... | self.status = "Paid" | conditional_block |
expense_claim.py | import Document
from erpnext.hr.utils import set_employee_name
from erpnext.accounts.party import get_party_account
from erpnext.accounts.general_ledger import make_gl_entries
from erpnext.accounts.doctype.sales_invoice.sales_invoice import get_bank_cash_account
from erpnext.controllers.accounts_controller import Acco... | get_expense_claim_account | identifier_name | |
expense_claim.py | appe
from frappe import _
from frappe.utils import get_fullname, flt, cstr
from frappe.model.document import Document
from erpnext.hr.utils import set_employee_name
from erpnext.accounts.party import get_party_account
from erpnext.accounts.general_ledger import make_gl_entries
from erpnext.accounts.doctype.sales_invoic... | if self.is_paid:
update_reimbursed_amount(self)
self.set_status()
def on_cancel(self):
self.update_task_and_project()
if self.payable_account:
self.make_gl_entries(cancel=True)
if self.is_paid:
update_reimbursed_amount(self)
self.set_status()
def update_task_and_project(self):
if self.task... | self.update_task_and_project()
self.make_gl_entries()
| random_line_split |
expense_claim.py | appe
from frappe import _
from frappe.utils import get_fullname, flt, cstr
from frappe.model.document import Document
from erpnext.hr.utils import set_employee_name
from erpnext.accounts.party import get_party_account
from erpnext.accounts.general_ledger import make_gl_entries
from erpnext.accounts.doctype.sales_invoic... |
def validate_sanctioned_amount(self):
for d in self.get('expenses'):
if flt(d.sanctioned_amount) > flt(d.claim_amount):
frappe.throw(_("Sanctioned Amount cannot be greater than Claim Amount in Row {0}.").format(d.idx))
def set_expense_account(self):
for expense in self.expenses:
if not expense.defaul... | task = frappe.get_doc("Task", self.task)
task.update_total_expense_claim()
task.save() | identifier_body |
binary_frame_reader.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use bincode::deserialize;
use byteorder::{LittleEndian, ReadBytesExt};
use clap;
use std::any::TypeId;
use std::fs... | // (a) SetRootPipeline
// (b) SetDisplayList
// (c) GenerateFrame that occurs *after* (a) and (b)
match msg {
ApiMsg::UpdateDocument(_, ref txn) => {
if txn.generate_frame {
... | // need to find: | random_line_split |
binary_frame_reader.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use bincode::deserialize;
use byteorder::{LittleEndian, ReadBytesExt};
use clap;
use std::any::TypeId;
use std::fs... | else if self.play_through {
if !self.frame_exists(self.frame_num + 1) {
process::exit(0);
}
self.next_frame();
self.do_frame(wrench);
} else {
wrench.refresh();
}
self.frame_num
}
// note that we don't loop he... | {
wrench.begin_frame();
let frame_items = self.frame_data.clone();
for item in frame_items {
match item {
Item::Message(msg) => if !self.should_skip_upload_msg(&msg) {
wrench.api.send_message(msg);
},
... | conditional_block |
binary_frame_reader.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use bincode::deserialize;
use byteorder::{LittleEndian, ReadBytesExt};
use clap;
use std::any::TypeId;
use std::fs... | (&self, frame: u32) -> bool {
!self.eof || (frame as usize) < self.frame_offsets.len()
}
}
impl WrenchThing for BinaryFrameReader {
fn do_frame(&mut self, wrench: &mut Wrench) -> u32 {
// save where the frame begins as we read through the file
if self.frame_num as usize >= self.frame_of... | frame_exists | identifier_name |
binary_frame_reader.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use bincode::deserialize;
use byteorder::{LittleEndian, ReadBytesExt};
use clap;
use std::any::TypeId;
use std::fs... |
// a frame exists if we either haven't hit eof yet, or if
// we have, then if we've seen its offset.
fn frame_exists(&self, frame: u32) -> bool {
!self.eof || (frame as usize) < self.frame_offsets.len()
}
}
impl WrenchThing for BinaryFrameReader {
fn do_frame(&mut self, wrench: &mut Wrenc... | {
if !self.skip_uploads {
return false;
}
match *msg {
ApiMsg::UpdateResources(..) => true,
_ => false,
}
} | identifier_body |
gulp-typescript.d.ts | // Compiled using typings@0.6.10
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/960fd659b456e2fb5d23c52794ffdc56b09796cf/gulp-typescript/gulp-typescript.d.ts
// Type definitions for gulp-typescript
// Project: https://github.com/ivogabe/gulp-typescript
// Definitions by: Asana <https://asa... | emitDecoratorMetadata?: boolean;
experimentalDecorators?: boolean;
experimentalAsyncFunctions?: boolean;
moduleResolution?: string;
noEmitHelpers?: boolean;
preserveConstEnums?: boolean;
isolatedModules?: boolean;
}
int... | suppressImplicitAnyIndexErrors?: boolean;
jsx?: string;
declaration?: boolean; | random_line_split |
fulfill.rs | can't generally check these things right away because we have
// to wait until types are resolved.)
//
// These are stored in a map keyed to the id of the innermost
// enclosing fn body / static initializer expression. This is
// because the location where the obligation was incurred can be
// ... | only_new_obligations);
let mut errors = Vec::new();
| random_line_split | |
fulfill.rs | _type(&mut selcx, projection_ty, cause, 0);
for obligation in normalized.obligations {
self.register_predicate_obligation(infcx, obligation);
}
debug!("normalize_associated_type: result={}", normalized.value.repr(infcx.tcx));
normalized.value
}
pub fn register_bui... | { } | conditional_block | |
fulfill.rs | in some expression `let x = Foo { ... }` it will
// instantiate the type parameter `T` with a fresh type `$0`. At
// the same time, it will record a region obligation of
// `$0:'static`. This will get checked later by regionck. (We
// can't generally check these things right away because we have
//... | <'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
let mut selcx = SelectionContext::new(infcx, typer);
self.select(&mut... | select_where_possible | identifier_name |
game.py | #!/usr/bin/env python
# game.py
#
# Copyright (C) 2013, 2014 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
import stage
import gameloop
import math
import random
import config
import gamestate as gs
direction = (0, 0)
lastPos = (0, 0)
snake = []
speed = 1
ap... |
for part in snake:
if part[0] == x and part[1] == y:
position_free = False
if position_free and not isOutOfBoundaries(x, y):
apples.append((x, y))
else:
spawnApple()
def isOutOfBoundaries(x, y):
if x < stage.boundaries['left'] or x > stage.boundaries['right'] - 1... | position_free = False | conditional_block |
game.py | #!/usr/bin/env python
# game.py
#
# Copyright (C) 2013, 2014 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
import stage
import gameloop
import math
import random
import config
import gamestate as gs
direction = (0, 0)
lastPos = (0, 0)
snake = []
speed = 1
ap... | elif y < stage.boundaries['top'] or y > stage.boundaries['bottom'] - 1:
return True
return False
def checkPositionAllowed():
global lives
collides_with_body = False
x = snake[0][0]
y = snake[0][1]
for i in range(1, len(snake) - 1):
if x == snake[i][0] and y == snake[i][1... | random_line_split | |
game.py | #!/usr/bin/env python
# game.py
#
# Copyright (C) 2013, 2014 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
import stage
import gameloop
import math
import random
import config
import gamestate as gs
direction = (0, 0)
lastPos = (0, 0)
snake = []
speed = 1
ap... | ():
global grow, lastPos
last_unchanged = None
lastPos = (snake[len(snake) - 1][0], snake[len(snake) - 1][1])
for i, part in enumerate(snake):
if i == 0:
x = part[0] + speed * direction[0]
y = part[1] + speed * direction[1]
else:
x = last_unchanged[0]... | moveSnake | identifier_name |
game.py | #!/usr/bin/env python
# game.py
#
# Copyright (C) 2013, 2014 Kano Computing Ltd.
# License: http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
#
import stage
import gameloop
import math
import random
import config
import gamestate as gs
direction = (0, 0)
lastPos = (0, 0)
snake = []
speed = 1
ap... |
def checkCatch():
if not len(snake) or not len(apples):
return
for i, apple in enumerate(apples):
if (snake[0][0]) == apple[0] and (snake[0][1]) == apple[1]:
eatApple(i)
def eatApple(i):
global grow, score
apples.pop(i)
spawnApple()
grow += config.food_values['... | moveSnake()
checkCatch()
checkPositionAllowed() | identifier_body |
cache.ts | import { prepareEmpty } from '@pnpm/prepare'
import { addDependenciesToPackage, install } from '@pnpm/core'
import {
addDistTag,
testDefaults,
} from './utils'
test('should fail to update when requests are cached', async () => {
const project = prepareEmpty()
const opts = await testDefaults()
await addDist... | await project.storeHas('dep-of-pkg-with-1-dep', '100.0.0')
await addDistTag('dep-of-pkg-with-1-dep', '100.1.0', 'latest')
await install(manifest, { ...opts, depth: 1, update: true })
await project.storeHas('dep-of-pkg-with-1-dep', '100.0.0')
})
test('should not cache when cache is not used', async () => {
... | random_line_split | |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
} | identifier_body | |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | #[allow(non_camel_case_types)]
pub mod values;
pub mod viewport;
pub mod workqueue;
use std::sync::Arc;
/// The CSS properties supported by the style system.
// Generated from the properties.mako.rs template by build.rs
#[macro_use]
#[allow(unsafe_code)]
pub mod properties {
include!(concat!(env!("OUT_DIR"), "/pr... | pub mod timer;
pub mod traversal;
#[macro_use] | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of sty... | <T: 'static>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
| arc_ptr_eq | identifier_name |
trends-chart.js | import template from './trends-chart.html';
import Chart from 'chart.js';
export default {
template,
bindings: {
array: '<',
count: '<',
},
controller: ['$scope', controllerFunc],
};
function controllerFunc($scope) | data: {
labels: ['Feb', 'March', 'April', 'May', 'June', 'July'],
datasets,
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
},
}],
},
tooltips: {
enabled: true,
mode: 'si... | {
this.chartType = 'line';
$scope.$watch('$ctrl.count', () => {
const params = (this.array[0] && this.array[0].sequence) ? this.array[0].sequence : null;
if (params) this.createChart();
});
$scope.$watch('$ctrl.chartType', () => {
if ($scope.myTrendsChart) this.createChart();
});
this.createC... | identifier_body |
trends-chart.js | import template from './trends-chart.html';
import Chart from 'chart.js';
export default {
template,
bindings: {
array: '<',
count: '<',
},
controller: ['$scope', controllerFunc],
};
function | ($scope) {
this.chartType = 'line';
$scope.$watch('$ctrl.count', () => {
const params = (this.array[0] && this.array[0].sequence) ? this.array[0].sequence : null;
if (params) this.createChart();
});
$scope.$watch('$ctrl.chartType', () => {
if ($scope.myTrendsChart) this.createChart();
});
thi... | controllerFunc | identifier_name |
trends-chart.js | import template from './trends-chart.html';
import Chart from 'chart.js';
export default {
template,
bindings: {
array: '<',
count: '<',
},
controller: ['$scope', controllerFunc],
};
function controllerFunc($scope) {
this.chartType = 'line';
$scope.$watch('$ctrl.count', () => {
const params ... | ],
// backgroundColor: [
// `rgba(${255 - index * 30}, 159, ${100 + index * 30}, 0.5)`,
// `rgba(${255 - index * 30}, 159, ${100 + index * 30}, 0.5)`,
// `rgba(${255 - index * 30}, 159, ${100 + index * 30}, 0.5)`,
// `rgba(${255 - index * 30}, 159, ${1... | e.sequence[3].avgAdm || 0,
e.sequence[4].avgAdm || 0,
e.sequence[5].avgAdm || 0,
e.sequence[6].avgAdm || 0, | random_line_split |
TagSortDropdown.test.js | import { shallowMount } from '@vue/test-utils'
import TagSortDropdown from '@/components/Dashboard/Sidebar/TagSortDropdown'
const $bus = {
$emit: jest.fn((e, data) => data)
}
| const wrapper = shallowMount(TagSortDropdown, {
propsData: {
visible: true
},
mocks: { $bus }
})
expect(wrapper.find('.tag-sort-dropdown').isVisible()).toBe(true)
})
it('is hidden if visibility is false', () => {
const wrapper = shallowMount(TagSortDropdown, {
propsD... | describe('Tag Sort Dropdown', () => {
it('shows if visibility is true', () => { | random_line_split |
format.ts | // moment.js
// version : 2.18.1
// authors : Tim Wood, Iskren Chernev, Moment.js contributors
// license : MIT
// momentjs.com
import './units/index';
import { formatFunctions, makeFormatFunction } from './format/format';
import { Locale } from './locale/locale.class';
import { getLocale } from './locale/locales';
im... |
export function expandFormat(_format: string, locale: Locale): string {
let format = _format;
let i = 5;
const localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
const replaceLongDateFormatTokens = (input: any) => {
return locale.formatLongDate(input) || input;
};
localFormattingTo... | const format = expandFormat(_format, locale);
formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
return formatFunctions[format](date, locale, isUTC, offset);
} | random_line_split |
format.ts | // moment.js
// version : 2.18.1
// authors : Tim Wood, Iskren Chernev, Moment.js contributors
// license : MIT
// momentjs.com
import './units/index';
import { formatFunctions, makeFormatFunction } from './format/format';
import { Locale } from './locale/locale.class';
import { getLocale } from './locale/locales';
im... |
// format date using native date object
export function formatMoment(date: Date, _format: string, locale: Locale, isUTC?: boolean, offset = 0): string {
if (!isDateValid(date)) {
return locale.invalidDate;
}
const format = expandFormat(_format, locale);
formatFunctions[format] = formatFunctions[format] |... | {
const _locale = getLocale(locale || 'en');
if (!_locale) {
throw new Error(
`Locale "${locale}" is not defined, please add it with "defineLocale(...)"`
);
}
const _format = format || (isUTC ? 'YYYY-MM-DDTHH:mm:ss[Z]' : 'YYYY-MM-DDTHH:mm:ssZ');
const output = formatMoment(date, _format, _loc... | identifier_body |
format.ts | // moment.js
// version : 2.18.1
// authors : Tim Wood, Iskren Chernev, Moment.js contributors
// license : MIT
// momentjs.com
import './units/index';
import { formatFunctions, makeFormatFunction } from './format/format';
import { Locale } from './locale/locale.class';
import { getLocale } from './locale/locales';
im... |
const format = expandFormat(_format, locale);
formatFunctions[format] = formatFunctions[format] || makeFormatFunction(format);
return formatFunctions[format](date, locale, isUTC, offset);
}
export function expandFormat(_format: string, locale: Locale): string {
let format = _format;
let i = 5;
const loc... | {
return locale.invalidDate;
} | conditional_block |
format.ts | // moment.js
// version : 2.18.1
// authors : Tim Wood, Iskren Chernev, Moment.js contributors
// license : MIT
// momentjs.com
import './units/index';
import { formatFunctions, makeFormatFunction } from './format/format';
import { Locale } from './locale/locale.class';
import { getLocale } from './locale/locales';
im... | (_format: string, locale: Locale): string {
let format = _format;
let i = 5;
const localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g;
const replaceLongDateFormatTokens = (input: any) => {
return locale.formatLongDate(input) || input;
};
localFormattingTokens.lastIndex = 0;
while (... | expandFormat | identifier_name |
main.rs | use std::cell::Cell;
use std::rt::io::{Reader, Writer, Listener};
use std::rt::io::net::tcp::*;
use std::rt::io::net::ip::*;
fn allocate_buffer(buffer_size: uint) -> ~[u8] {
let mut buffer: ~[u8] = std::vec::with_capacity(buffer_size);
unsafe { std::vec::raw::set_len(&mut buffer, buffer_size); }
return bu... | },
};
}
}
}
} | loop {
match stream.read(dest_buffer) {
Some(x) => stream.write(dest_buffer.slice_to(x)),
None => {
break | random_line_split |
main.rs | use std::cell::Cell;
use std::rt::io::{Reader, Writer, Listener};
use std::rt::io::net::tcp::*;
use std::rt::io::net::ip::*;
fn allocate_buffer(buffer_size: uint) -> ~[u8] {
let mut buffer: ~[u8] = std::vec::with_capacity(buffer_size);
unsafe { std::vec::raw::set_len(&mut buffer, buffer_size); }
return bu... | () {
let listen_address = Ipv4(127, 0, 0, 1, 8000);
let mut listener = match TcpListener::bind(listen_address) {
Some(x) => x,
None => {
fail!("Unable to bind to " + listen_address.to_str());
}
};
loop {
let stream = Cell::new(listener.accept().unwrap());... | main | identifier_name |
main.rs | use std::cell::Cell;
use std::rt::io::{Reader, Writer, Listener};
use std::rt::io::net::tcp::*;
use std::rt::io::net::ip::*;
fn allocate_buffer(buffer_size: uint) -> ~[u8] |
fn main() {
let listen_address = Ipv4(127, 0, 0, 1, 8000);
let mut listener = match TcpListener::bind(listen_address) {
Some(x) => x,
None => {
fail!("Unable to bind to " + listen_address.to_str());
}
};
loop {
let stream = Cell::new(listener.accept().... | {
let mut buffer: ~[u8] = std::vec::with_capacity(buffer_size);
unsafe { std::vec::raw::set_len(&mut buffer, buffer_size); }
return buffer
} | identifier_body |
main.rs | use std::cell::Cell;
use std::rt::io::{Reader, Writer, Listener};
use std::rt::io::net::tcp::*;
use std::rt::io::net::ip::*;
fn allocate_buffer(buffer_size: uint) -> ~[u8] {
let mut buffer: ~[u8] = std::vec::with_capacity(buffer_size);
unsafe { std::vec::raw::set_len(&mut buffer, buffer_size); }
return bu... |
};
loop {
let stream = Cell::new(listener.accept().unwrap());
do spawn {
let mut dest_buffer = allocate_buffer(512);
let mut stream = stream.take();
loop {
match stream.read(dest_buffer) {
Some(x) => stream.write(dest_bu... | {
fail!("Unable to bind to " + listen_address.to_str());
} | conditional_block |
weather.reducer.ts | SELECT_CITY
} from './weather.actions';
export interface IWeather {
data: string;
airQuality: string;
forecast: {};
selected: {};
isFetching: false;
}
export const weatherReducer: ActionReducer<IWeather> = (state: IWeather, action: Action): IWeather => {
switch (action.type) {
case WEATHER_GET:
... | import { Action, ActionReducer } from '@ngrx/store';
import {
AIR_QUALITY_GET_SUCCESS, WEATHER_GET_SUCCESS, WEATHER_DATA_GET_SUCCESS, WEATHER_GET, | random_line_split | |
index.d.ts | // Type definitions for AmplifyJs (using JQuery Deferred) 1.1
// Project: http://amplifyjs.com/
// Definitions by: Jonas Eriksson <https://github.com/joeriks/>, Laurentiu Stamate <https://github.com/laurentiustamate94>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <r... | * success (optional): Function to invoke on success.
* error (optional): Function to invoke on error.
*/
(settings: RequestSettings): JQueryPromise<any>;
}
} | * data (optional): Data associated with the request. | random_line_split |
lib.rs | } => {
//! println!("Command took {} nanoseconds.", duration);
//! }, | //! client.add_completion_hook(log_query_duration).unwrap();
//! ```
//!
//! ## Topology Monitoring
//!
//! Each server within a MongoDB server set is monitored asynchronously for changes in status, and
//! the driver's view of the current topology is updated in response to this. This allows the
//! driver to be aware ... | //! _ => println!("Failed to execute command."),
//! }
//! }
//!
//! let mut client = Client::connect("localhost", 27017).unwrap(); | random_line_split |
lib.rs | } => {
//! println!("Command took {} nanoseconds.", duration);
//! },
//! _ => println!("Failed to execute command."),
//! }
//! }
//!
//! let mut client = Client::connect("localhost", 27017).unwrap();
//! client.add_completion_hook(log_query_duration).unwrap();
//! ```
//!
//! ## Topol... | {
/// Indicates how a server should be selected for read operations.
pub read_preference: ReadPreference,
/// Describes the guarantees provided by MongoDB when reporting the success of a write
/// operation.
pub write_concern: WriteConcern,
req_id: Arc<AtomicIsize>,
topology: Topology,
... | ClientInner | identifier_name |
lib.rs | } => {
//! println!("Command took {} nanoseconds.", duration);
//! },
//! _ => println!("Failed to execute command."),
//! }
//! }
//!
//! let mut client = Client::connect("localhost", 27017).unwrap();
//! client.add_completion_hook(log_query_duration).unwrap();
//! ```
//!
//! ## Topol... |
#[cfg(feature = "ssl")]
/// Creates a new options struct with a specified SSL certificate
pub fn with_unauthenticated_ssl(ca_file: &str, verify_peer: bool) -> ClientOptions {
let mut options = ClientOptions::new();
options.stream_connector = StreamConnector::with_unauthenticated_ssl(ca_fil... | {
let mut options = ClientOptions::new();
options.stream_connector =
StreamConnector::with_ssl(ca_file, certificate_file, key_file, verify_peer);
options
} | identifier_body |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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 | * limitations under the License.
*/
// TypeScript Version: 2.0
/// <reference types="@stdlib/types"/>
/**
* If provided a value, returns an updated minimum value; otherwise, returns the current minimum value.
*
* ## Notes
*
* - If provided `NaN` or a value which, when used in computations, results in `NaN`, the ac... | *
* Unless required by applicable law or agreed to in writing, software
* distributed under 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 | random_line_split |
playlist.component.ts | import { StorageService } from './../../common/services/storage.service';
import { Store } from '@ngrx/store';
import { SpotifyService } from './../../common/services/spotify.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnInit, NgZone } from '@angular/core';
@Component({
... | implements OnInit {
constructor(
private route: ActivatedRoute,
private router: Router,
private spotify: SpotifyService,
private storage: StorageService,
private store: Store<any>,
private zone: NgZone
) { }
showPanel: boolean;
ngOnInit() {
this... | PlaylistComponent | identifier_name |
playlist.component.ts | import { Component, OnInit, NgZone } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'playlist',
templateUrl: 'playlist.component.html',
styleUrls: ['playlist.component.scss']
})
export class PlaylistComponent implements OnInit {
constructor(
private route: ActivatedRoute,... | import { StorageService } from './../../common/services/storage.service';
import { Store } from '@ngrx/store';
import { SpotifyService } from './../../common/services/spotify.service';
import { ActivatedRoute, Router } from '@angular/router'; | random_line_split | |
playlist.component.ts | import { StorageService } from './../../common/services/storage.service';
import { Store } from '@ngrx/store';
import { SpotifyService } from './../../common/services/spotify.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnInit, NgZone } from '@angular/core';
@Component({
... |
showPanel: boolean;
ngOnInit() {
this.route.params.subscribe(this.onParamsLoaded);
this.showPanel = false;
this.getState(this.store);
};
private onParamsLoaded = (params: any) => {
this.spotify.gettingPlaylist(params.id, params.owner, 20, 0);
};
private getSt... | { } | identifier_body |
test_word_cloud.py | # -*- coding: utf-8 -*-
"""Word cloud integration tests using mongo modulestore."""
import json
from operator import itemgetter
from xmodule.x_module import STUDENT_VIEW
from .helpers import BaseTestXmodule
class TestWordCloud(BaseTestXmodule):
"""Integration test for word cloud xmodule."""
CATEGORY = "wo... | (self):
"""Test word cloud data flow per single and collective users submits.
Make sures that:
1. Inital state of word cloud is correct. Those state that
is sended from server to frontend, when students load word
cloud page.
2. Students can submit d... | test_collective_users_submits | identifier_name |
test_word_cloud.py | # -*- coding: utf-8 -*-
"""Word cloud integration tests using mongo modulestore."""
import json
from operator import itemgetter
from xmodule.x_module import STUDENT_VIEW
from .helpers import BaseTestXmodule
class TestWordCloud(BaseTestXmodule):
"""Integration test for word cloud xmodule."""
CATEGORY = "wo... |
self._check_response(users_state, correct_state)
def test_collective_users_submits(self):
"""Test word cloud data flow per single and collective users submits.
Make sures that:
1. Inital state of word cloud is correct. Those state that
is sended from server to... | random_line_split | |
test_word_cloud.py | # -*- coding: utf-8 -*-
"""Word cloud integration tests using mongo modulestore."""
import json
from operator import itemgetter
from xmodule.x_module import STUDENT_VIEW
from .helpers import BaseTestXmodule
class TestWordCloud(BaseTestXmodule):
"""Integration test for word cloud xmodule."""
CATEGORY = "wo... |
return users_state
def _post_words(self, words):
"""Post `words` and return current state for each user:
{username: json_state}
"""
users_state = {}
for user in self.users:
response = self.clients[user.username].post(
self.get_url('sub... | response = self.clients[user.username].post(self.get_url('get_state'))
users_state[user.username] = json.loads(response.content.decode('utf-8')) | conditional_block |
test_word_cloud.py | # -*- coding: utf-8 -*-
"""Word cloud integration tests using mongo modulestore."""
import json
from operator import itemgetter
from xmodule.x_module import STUDENT_VIEW
from .helpers import BaseTestXmodule
class TestWordCloud(BaseTestXmodule):
"""Integration test for word cloud xmodule."""
CATEGORY = "wo... | u'display_student_percents': False
}
for _, response_content in users_state.items():
self.assertEqual(response_content, correct_initial_data)
def test_post_words(self):
"""Students can submit data succesfully.
Word cloud data properly updates after students... | """Inital state of word cloud is correct. Those state that
is sended from server to frontend, when students load word
cloud page.
"""
users_state = self._get_users_state()
self.assertEqual(
''.join(set([
content['status']
... | identifier_body |
Selector-dbg.js | /*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides class sap.ui.core.support.plugins.Selector (Selector support plugin)
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Pop... | var rm = sap.ui.getCore().createRenderManager();
rm.write("<div id='" + this._sPopupId + "' style='border: 2px solid rgb(0, 128, 0); background-color: rgba(0, 128, 0, .55);'></div>");
rm.flush(sap.ui.getCore().getStaticAreaRef(), false, true);
rm.destroy();
jPopupRef = jQuery.sap.byId(this._sPopupI... | if (!this._sPopupId) {
this._sPopupId = this.getId() + "-" + jQuery.sap.uid(); | random_line_split |
Selector-dbg.js | /*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides class sap.ui.core.support.plugins.Selector (Selector support plugin)
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Pop... | (oElement, oPlugin){
//TODO: to be extended
return {"id": oElement.getId()};
}
return Selector;
});
| getElementDetailsForEvent | identifier_name |
Selector-dbg.js | /*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides class sap.ui.core.support.plugins.Selector (Selector support plugin)
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Pop... | return false;
}
function getElementDetailsForEvent(oElement, oPlugin){
//TODO: to be extended
return {"id": oElement.getId()};
}
return Selector;
});
| {
if (sId) {
var oElem = sap.ui.getCore().byId(sId);
if (oElem) {
var jPopupRef = jQuery.sap.byId(oPlugin._sPopupId);
var jRef = oElem.$();
if (jRef.is(":visible")) {
jPopupRef.width(jRef.outerWidth());
jPopupRef.height(jRef.outerHeight());
oPlugin._oPopup.open(0, "BeginTop",... | identifier_body |
Selector-dbg.js | /*!
* UI development toolkit for HTML5 (OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides class sap.ui.core.support.plugins.Selector (Selector support plugin)
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Pop... |
}
}
return false;
}
function getElementDetailsForEvent(oElement, oPlugin){
//TODO: to be extended
return {"id": oElement.getId()};
}
return Selector;
});
| {
jPopupRef.width(jRef.outerWidth());
jPopupRef.height(jRef.outerHeight());
oPlugin._oPopup.open(0, "BeginTop", "BeginTop", jRef[0], "0 0", "none");
if (bSend) {
sap.ui.core.support.Support.getStub().sendEvent(oPlugin.getId() + "Select", getElementDetailsForEvent(oElem, oPlugin));
}... | conditional_block |
api-notes.js | var joi = require('joi');
var _ = require('lodash');
module.exports = function(router, db) {
// This is our "class" that accesses/modifies notes in the db
var NoteService = require('../lib/db-notes')
var noteService = new NoteService(db);
// Joi is a wonderful library that takes strings and converts them into th... |
res.json(200, null);
});
});
/**
* Deletes a note from the db
*/
router.delete('/api/notes/:id', function(req, res, next) {
noteService.remove(req.params.id, function(err, result) {
if(err) return next(err);
if(result === 0) {
return res.send(400, { error: 'Note `' + req.params.id + '` does ... | {
return res.send(400, { error: 'Note `' + req.params.id + '` does not exist' });
} | conditional_block |
api-notes.js | var joi = require('joi');
var _ = require('lodash');
module.exports = function(router, db) {
// This is our "class" that accesses/modifies notes in the db
var NoteService = require('../lib/db-notes')
var noteService = new NoteService(db);
// Joi is a wonderful library that takes strings and converts them into th... | });
/**
* Updates a note.
* TODO: Not yet used and tested
*/
router.put('/api/notes/:id', function(req, res, next) {
var id;
try{
id = ObjectID(req.params.id);
}catch(err) {
return res.send(400, {error: err.message});
}
noteService.updateNote(id, req.body, function(err, result) {
if(err) r... | if(req.accepts(['html', 'json']) === 'html') return res.redirect('/notes');
res.send(200, result);
}); | random_line_split |
CalloutGroupItem.js | import React from 'react';
import PropTypes from 'prop-types';
import Text from '../Text/Text';
import { Styled } from './CalloutGroupItem.styles';
const CalloutGroupItem = ({ text, imgSrc, imgAlt, emoji }) => {
return (
<>
{!imgSrc ? (
!emoji ? (
<Text>{text}</Text>
) : (
<Text>
<Styled.... |
CalloutGroupItem.propTypes = {
emoji: PropTypes.string,
text: PropTypes.oneOfType([PropTypes.node, PropTypes.string]).isRequired,
imgSrc: PropTypes.node,
imgAlt: PropTypes.string,
};
export default CalloutGroupItem; | random_line_split | |
events.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v12.0.2
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Events = (function () {
function | () {
}
/** Everything has changed with the columns. Either complete new set of columns set, or user called setState()*/
Events.EVENT_COLUMN_EVERYTHING_CHANGED = 'columnEverythingChanged';
/** User has set in new columns. */
Events.EVENT_NEW_COLUMNS_LOADED = 'newColumnsLoaded';
/** The pivot mode... | Events | identifier_name |
events.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v12.0.2
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Events = (function () {
function Events() {
}
... | Events.EVENT_COLUMN_MOVED = 'columnMoved';
/** One or more columns was shown / hidden */
Events.EVENT_COLUMN_VISIBLE = 'columnVisible';
/** One or more columns was pinned / unpinned*/
Events.EVENT_COLUMN_PINNED = 'columnPinned';
/** A column group was opened / closed */
Events.EVENT_COLUMN_G... | /** The list of grid columns has changed. */
Events.EVENT_GRID_COLUMNS_CHANGED = 'gridColumnsChanged';
/** A value column was added, removed or agg function was changed. */
Events.EVENT_COLUMN_VALUE_CHANGED = 'columnValueChanged';
/** A column was moved */ | random_line_split |
events.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v12.0.2
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Events = (function () {
function Events() |
/** Everything has changed with the columns. Either complete new set of columns set, or user called setState()*/
Events.EVENT_COLUMN_EVERYTHING_CHANGED = 'columnEverythingChanged';
/** User has set in new columns. */
Events.EVENT_NEW_COLUMNS_LOADED = 'newColumnsLoaded';
/** The pivot mode flag was ... | {
} | identifier_body |
pref_util.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;
use std::sync::{Arc, R... |
}
| {
*self.user_prefs.write().unwrap() = self.default_prefs.clone();
} | identifier_body |
pref_util.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;
use std::sync::{Arc, R... | Some(other.into())
}
}
}
)+
}
}
impl_pref_from! {
f64 => PrefValue::Float,
i64 => PrefValue::Int,
String => PrefValue::Str,
&str => PrefValue::Str,
bool => PrefValue::Bool,
}
impl_from_pref! {
PrefValue::Float ... | fn from(other: PrefValue) -> Self {
if let PrefValue::Missing = other {
None
} else { | random_line_split |
pref_util.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;
use std::str::FromStr;
use std::sync::{Arc, R... | <V>(&self, key: &str, val: V) -> Result<(), PrefError>
where
V: Into<PrefValue>,
{
let mut prefs = self.user_prefs.write().unwrap();
self.set_inner(key, &mut prefs, val)
}
pub fn set_all<M>(&self, values: M) -> Result<(), PrefError>
where
M: IntoIterator<Item = (Stri... | set | identifier_name |
base58.js | module.exports = (app) => {
let Base58 = {};
Base58.alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
Base58.alphabetMap = {};
for(let i = 0; i < Base58.alphabet.length; i++) {
Base58.alphabetMap[Base58.alphabet.charAt(i)] = i
}
Base58.encode = function(buffer) {
if (buffe... |
while (carry) {
digits.unshift(carry);
carry = (digits[0] / 58) | 0;
digits[0] %= 58
}
}
// deal with leading zeros
for (i = 0; i < buffer.length - 1 && buffer[i] == 0; i++) digits.unshift(0)
return digits.map(function(digit) { return Base58.alphabet[digit] }).join... | random_line_split | |
text_plots.py | import numpy as np
import pandas as pd
import seaborn as sns
import wordcloud
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.manifold import TSNE
from sklearn.preprocessing import Normalizer
from sklearn.pipeline import make_pipeline
def sample... | X = TSNE(n_components=2,
init='pca',
perplexity=perplexity,
n_iter=n_iter,
random_state=123).fit_transform(X)
proj = pd.DataFrame({'component_1': X[:, 0], 'component_2': X[:, 1]})
proj['text'] = text_list
if labels is not None:
proj['labels'] ... | # project down to two dimensions with t-SNE | random_line_split |
text_plots.py | import numpy as np
import pandas as pd
import seaborn as sns
import wordcloud
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.manifold import TSNE
from sklearn.preprocessing import Normalizer
from sklearn.pipeline import make_pipeline
def sample... | # fit text features
vectorizer = TfidfVectorizer(ngram_range=(1,2),
stop_words='english',
sublinear_tf=False,
use_idf=True,
max_df=0.95,
min_df=5,
... | """Generate a horizontal bar chart of words ranked by their global
tf-idf weights in the corpus.
Parameters
----------
text_list : array-like of shape [n_samples,]
The list of documents to generate the word cloud.
ngram_range : tuple (default=(1,2))
The ngrams to use. Defaults to un... | identifier_body |
text_plots.py | import numpy as np
import pandas as pd
import seaborn as sns
import wordcloud
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.manifold import TSNE
from sklearn.preprocessing import Normalizer
from sklearn.pipeline import make_pipeline
def sample... |
return proj
| proj['labels'] = labels | conditional_block |
text_plots.py | import numpy as np
import pandas as pd
import seaborn as sns
import wordcloud
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.manifold import TSNE
from sklearn.preprocessing import Normalizer
from sklearn.pipeline import make_pipeline
def | (seq, n_samples, seed=123):
random_state = np.random.RandomState(seed)
return random_state.choice(seq, size=n_samples, replace=False)
def frequency_plot(text_list,
ngram_range=(1,2),
max_words=500,
plot_n_words=10,
yaxis_label='word',... | sample_array | identifier_name |
mod.rs | //-------------------------------------------------------------------------------
// URL:
//-------------------------------------------------------------------------------
use std::path::Path;
use time;
use reader;
pub const ID: i32 = 8;
pub const DIR: &str = "array/dutchflag";
//--------------------------------... |
if element == 0 {
elements[mid] = elements[low];
elements[low] = element;
low += 1;
mid += 1;
} else if element == 1 {
mid += 1;
} else {
elements[mid] = elements[high];
elements[high] = element;
high -= 1;
}
}
} | let mut mid = 0;
let mut high = elements.len() - 1;
while mid <= high {
let element = elements[mid]; | random_line_split |
mod.rs | //-------------------------------------------------------------------------------
// URL:
//-------------------------------------------------------------------------------
use std::path::Path;
use time;
use reader;
pub const ID: i32 = 8;
pub const DIR: &str = "array/dutchflag";
//--------------------------------... | high -= 1;
}
}
}
| {
let mut low = 0;
let mut mid = 0;
let mut high = elements.len() - 1;
while mid <= high {
let element = elements[mid];
if element == 0 {
elements[mid] = elements[low];
elements[low] = element;
low += 1;
mid += 1;
} else if element == 1 {
mid += 1;
} else {
... | identifier_body |
mod.rs | //-------------------------------------------------------------------------------
// URL:
//-------------------------------------------------------------------------------
use std::path::Path;
use time;
use reader;
pub const ID: i32 = 8;
pub const DIR: &str = "array/dutchflag";
//--------------------------------... | (elements: &mut Vec<i64>) {
let mut low = 0;
let mut mid = 0;
let mut high = elements.len() - 1;
while mid <= high {
let element = elements[mid];
if element == 0 {
elements[mid] = elements[low];
elements[low] = element;
low += 1;
mid += 1;
} else if element == 1 {
... | first_algorithm | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.