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 |
|---|---|---|---|---|
buffer-builder.js | // Copyright 2015-present runtime.js project 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
//
// Unless required by applicab... | (u8) {
for (const item of u8) {
this.uint8(item & 0xff);
}
this._repeatFirst = this._p.length - u8.length;
this._repeatLast = this._p.length;
return this;
}
repeat(times = 0) {
for (let t = 0; t < times; ++t) {
for (let i = this._repeatFirst; i < this._repeatLast; ++i) {
... | array | identifier_name |
buffer-builder.js | // Copyright 2015-present runtime.js project 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
//
// Unless required by applicab... |
checksum(fn) {
this._checksumOffset = this._p.length;
this._ck = fn;
return this.uint16(0);
}
uint32(valueOpt) {
const value = valueOpt >>> 0;
this.uint8((value >>> 24) & 0xff);
this.uint8((value >>> 16) & 0xff);
this.uint8((value >>> 8) & 0xff);
this.uint8(value & 0xff);
th... | {
this._checksumLast = this._p.length;
return this;
} | identifier_body |
userscripts.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 dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::Node... | (head: &HTMLHeadElement) {
if let Some(ref path_str) = opts::get().userscripts {
let node = head.upcast::<Node>();
let first_child = node.GetFirstChild();
let doc = node.owner_doc();
let doc = doc.r();
let path = if &**path_str == "" {
let mut p = resources_dir_p... | load_script | identifier_name |
userscripts.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 dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::Node... | for file in files {
let name = match file.into_os_string().into_string() {
Ok(ref s) if s.ends_with(".js") => "file://".to_owned() + &s[..],
_ => continue
};
let new_script = doc.CreateElement(DOMString::from("script")).unwrap();
le... | {
let node = head.upcast::<Node>();
let first_child = node.GetFirstChild();
let doc = node.owner_doc();
let doc = doc.r();
let path = if &**path_str == "" {
let mut p = resources_dir_path();
p.push("user-agent-js");
p
} else {
... | conditional_block |
userscripts.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 dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::Node... |
for file in files {
let name = match file.into_os_string().into_string() {
Ok(ref s) if s.ends_with(".js") => "file://".to_owned() + &s[..],
_ => continue
};
let new_script = doc.CreateElement(DOMString::from("script")).unwrap();
l... | {
if let Some(ref path_str) = opts::get().userscripts {
let node = head.upcast::<Node>();
let first_child = node.GetFirstChild();
let doc = node.owner_doc();
let doc = doc.r();
let path = if &**path_str == "" {
let mut p = resources_dir_path();
p.push... | identifier_body |
userscripts.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 dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::codegen::Bindings::Node... | for file in files {
let name = match file.into_os_string().into_string() {
Ok(ref s) if s.ends_with(".js") => "file://".to_owned() + &s[..],
_ => continue
};
let new_script = doc.CreateElement(DOMString::from("script")).unwrap();
le... | files.sort();
| random_line_split |
location.py | from util.enums import Color
class Location:
"""
Location on a chessboard
"""
ROWS = [1, 2, 3, 4, 5, 6, 7, 8] # RANKS
COLS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] # FILES
def __init__(self, row, col):
""" initializer
:param row: integer
:param col: str
:r... | (cls, l1, l2, inclusive=False):
""" Create locations between two locations
:param l1: start Location
:param l2: stop Location
:param inclusive: include l1 and l2
:return: Location generator
"""
if l1.row == l2.row:
low_idx = min(cls.COLS.index(l1.col)... | from_between | identifier_name |
location.py | from util.enums import Color
class Location:
"""
Location on a chessboard
"""
ROWS = [1, 2, 3, 4, 5, 6, 7, 8] # RANKS
COLS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] # FILES
def __init__(self, row, col):
""" initializer
:param row: integer
:param col: str
:r... |
else:
raise ValueError('locations must be on the same row or column')
@classmethod
def all(cls):
for row in cls.ROWS:
for col in cls.COLS:
yield cls(row, col) | yield cls(i, l1.col) | conditional_block |
location.py | from util.enums import Color
class Location:
"""
Location on a chessboard
"""
ROWS = [1, 2, 3, 4, 5, 6, 7, 8] # RANKS
COLS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] # FILES
def __init__(self, row, col):
""" initializer |
:param row: integer
:param col: str
:return:
"""
# validate the input
if row not in self.ROWS:
raise ValueError("'{}' is not a valid location")
elif col not in self.COLS:
raise ValueError("'{}' is not a valid location")
self.row, ... | random_line_split | |
location.py | from util.enums import Color
class Location:
"""
Location on a chessboard
"""
ROWS = [1, 2, 3, 4, 5, 6, 7, 8] # RANKS
COLS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] # FILES
def __init__(self, row, col):
""" initializer
:param row: integer
:param col: str
:r... | high_idx -= 1
for i in cls.ROWS[low_idx:high_idx]:
yield cls(i, l1.col)
else:
raise ValueError('locations must be on the same row or column')
@classmethod
def all(cls):
for row in cls.ROWS:
for col in cls.COLS:
... | """ Create locations between two locations
:param l1: start Location
:param l2: stop Location
:param inclusive: include l1 and l2
:return: Location generator
"""
if l1.row == l2.row:
low_idx = min(cls.COLS.index(l1.col), cls.COLS.index(l2.col))
hi... | identifier_body |
products.ts | const product = [
{
name: 'Bananas',
description: 'Yummy yellow fruit',
id: 'sku_GBJ2Ep8246qeeT',
price: 400,
image:
'https://images.unsplash.com/photo-1574226516831-e1dff420e562?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=225&q=80',
attribution: 'Photo by Priscilla D... | id: 'sku_GBJ2WWfMaGNC2Z',
price: 100,
image:
'https://images.unsplash.com/photo-1482012792084-a0c3725f289f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=225&q=80',
attribution: 'Photo by Jonathan Pielmayer on Unsplash',
currency: 'USD',
},
]
export default product | name: 'Tangerines', | random_line_split |
fine_friend.js | var name = "Fine Friend";
var collection_type = 0;
var is_secret = 0;
var desc = "Made 7 friends";
var status_text = "You're getting pretty popular! You've earned a Fine Friend badge.";
var last_published = 1316379385;
var is_shareworthy = 0;
var url = "fine-friend";
var category = "social";
var url_swf = "\/c2.... | "giant" : "friendly",
"points" : 10
}
};
// generated ok (NO DATE) | }
var rewards = {
"favor" : { | random_line_split |
fine_friend.js | var name = "Fine Friend";
var collection_type = 0;
var is_secret = 0;
var desc = "Made 7 friends";
var status_text = "You're getting pretty popular! You've earned a Fine Friend badge.";
var last_published = 1316379385;
var is_shareworthy = 0;
var url = "fine-friend";
var category = "social";
var url_swf = "\/c2.... |
var rewards = {
"favor" : {
"giant" : "friendly",
"points" : 10
}
};
// generated ok (NO DATE)
| { // generated from rewards
var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
multiplier += pc.imagination_get_achievement_modifier();
if (/completist/i.exec(this.name)) {
var level = pc.stats_get_level();
if (level > 4) {
multiplier *= (pc.stats_get_level(... | identifier_body |
fine_friend.js | var name = "Fine Friend";
var collection_type = 0;
var is_secret = 0;
var desc = "Made 7 friends";
var status_text = "You're getting pretty popular! You've earned a Fine Friend badge.";
var last_published = 1316379385;
var is_shareworthy = 0;
var url = "fine-friend";
var category = "social";
var url_swf = "\/c2.... | (pc){
}
var conditions = {
211 : {
type : "counter",
group : "player",
label : "buddies_count",
value : "7"
},
};
function onComplete(pc){ // generated from rewards
var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
multiplier += pc.imagination_get_achievement_... | on_apply | identifier_name |
strings.js | define({
"settingsHeader": "지오룩업 위젯에 대한 세부정보 설정", | "layerTable": {
"colEnrich": "보강",
"colLabel": "레이어",
"colFieldSelector": "필드"
},
"fieldTable": {
"colAppend": "추가",
"colName": "이름",
"colAlias": "별칭",
"colOrder": "작업",
"label": "추가할 필드를 선택합니다. 별칭과 순서를 업데이트할 필드를 선택하세요."
},
"symbolArea": {
"symbolLabelWithin": "다음 내에서 위치에 대... | "settingsDesc": "맵의 폴리곤 레이어에 대해 CSV 파일에서 위치 목록을 보강합니다. 폴리곤 레이어에서 선택한 필드가 위치에 추가됩니다.",
"settingsLoadingLayers": "레이어를 불러오는 동안 기다려 주세요.",
"settingsConfigureTitle": "레이어 필드 구성", | random_line_split |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Wgsim(Package):
"""Wgsim is a small tool for simulating sequence reads from a reference
... | (self, spec, prefix):
cc = Executable(spack_cc)
cc('-g', '-O2', '-Wall', '-o', 'wgsim', 'wgsim.c', '-lz', '-lm')
install_tree(self.stage.source_path, prefix.bin)
| install | identifier_name |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Wgsim(Package):
"""Wgsim is a small tool for simulating sequence reads from a reference
... | cc = Executable(spack_cc)
cc('-g', '-O2', '-Wall', '-o', 'wgsim', 'wgsim.c', '-lz', '-lm')
install_tree(self.stage.source_path, prefix.bin) | random_line_split | |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Wgsim(Package):
"""Wgsim is a small tool for simulating sequence reads from a reference
... | cc = Executable(spack_cc)
cc('-g', '-O2', '-Wall', '-o', 'wgsim', 'wgsim.c', '-lz', '-lm')
install_tree(self.stage.source_path, prefix.bin) | identifier_body | |
javax.management.remote.JMXConnectorServer.d.ts | declare namespace javax {
namespace management {
namespace remote {
abstract class JMXConnectorServer extends javax.management.NotificationBroadcasterSupport implements javax.management.remote.JMXConnectorServerMBean, javax.management.MBeanRegistration, javax.management.remote.JMXAddressable {
publ... | public constructor(arg0: javax.management.MBeanServer)
public getMBeanServer(): javax.management.MBeanServer
public setMBeanServerForwarder(arg0: javax.management.remote.MBeanServerForwarder): void
public getConnectionIds(): java.lang.String[]
public toJMXConnector(arg0: java.uti... | public constructor() | random_line_split |
DistributedPartyJukeboxActivityBase.py | OTPBase import OTPBase
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from toontown.parties.DistributedPartyActivity import DistributedPartyActivity
from toontown.parties.PartyGlobals import ActivityIds, ActivityTypes, JUKEBOX_TIMEOUT
from toontown.parties.PartyGlobals import ge... |
def __handleGuiClose(self):
self.__deactivateGui()
self.d_toonExitDemand()
def __handleQueueSong(self, name, values):
self.d_setNextSong(values[0], values[1])
def d_setNextSong(self, phase, filename):
self.sendUpdate('setNextSong', [(phase, filename)])
def setSongInQ... | if self.gui.isLoaded():
for i in range(len(songInfoList)):
songInfo = songInfoList[i]
self.__addSongToQueue(songInfo, isLocalQueue=index >= 0 and i == index)
self.gui.enableAddSongButton() | identifier_body |
DistributedPartyJukeboxActivityBase.py | OTPBase import OTPBase
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from toontown.parties.DistributedPartyActivity import DistributedPartyActivity
from toontown.parties.PartyGlobals import ActivityIds, ActivityTypes, JUKEBOX_TIMEOUT
from toontown.parties.PartyGlobals import ge... |
def getMusicData(self, phase, filename):
data = []
phase = sanitizePhase(phase)
phase = self.phaseTo | self.gui.pushQueuedItemToTop(self.localQueuedSongListItem) | conditional_block |
DistributedPartyJukeboxActivityBase.py | OTPBase import OTPBase
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from toontown.parties.DistributedPartyActivity import DistributedPartyActivity
from toontown.parties.PartyGlobals import ActivityIds, ActivityTypes, JUKEBOX_TIMEOUT
from toontown.parties.PartyGlobals import ge... | (self):
self.localQueuedSongInfo = None
self.localQueuedSongListItem = None
return
def __play(self, phase, filename, length):
self.music = base.loadMusic((MUSIC_PATH + '%s') % (phase, filename))
if self.music:
if self.__checkPartyValidity() and hasattr(base.cr.pl... | __localClearQueuedSong | identifier_name |
DistributedPartyJukeboxActivityBase.py | .OTPBase import OTPBase
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from toontown.parties.DistributedPartyActivity import DistributedPartyActivity
from toontown.parties.PartyGlobals import ActivityIds, ActivityTypes, JUKEBOX_TIMEOUT
from toontown.parties.PartyGlobals import g... | class DistributedPartyJukeboxActivityBase(DistributedPartyActivity):
notify = directNotify.newCategory('DistributedPartyJukeboxActivityBase')
def __init__(self, cr, actId, phaseToMusicData):
DistributedPartyActivity.__init__(self, cr, actId, ActivityTypes.Continuous)
self.phaseToMusicData = pha... | random_line_split | |
type_constructor.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/// <amd-module name="@angular/compiler-cli/src/ngtsc/typecheck/src/type_constructor" />
import * as ts from 'typescr... | * @param meta additional metadata required to generate the type constructor.
* @returns a `ts.MethodDeclaration` for the type constructor.
*/
export declare function generateInlineTypeCtor(node: ClassDeclaration<ts.ClassDeclaration>, meta: TypeCtorMetadata, config: TypeCheckingConfig): ts.MethodDeclaration;
export d... | * impossible.
*
* @param node the `ClassDeclaration<ts.ClassDeclaration>` for which a type constructor will be
* generated. | random_line_split |
styles.js | import styled from 'styled-components';
export const Container = styled.div`
width: 100%;
height: 100%;
`;
export const EditorContainer = styled.div`
${''/* padding: 30px 30px; */}
width: 100%;
box-sizing: border-box;
position: relative;
font-family: 'Proxima-Nova', 'helvetica', 'arial';
... | color: #131517;
}
& h2 {
font-size: 28px;
font-weight: normal;
letter-spacing: -.008em;
line-height: 1.24;
margin-bottom: 20px;
color: #797C80;
}
& ul {
padding-left: 24px;
${''/* list-style: none; */}
}
& ol {
padd... | margin-bottom: 20px; | random_line_split |
datepicker.ts | DetectionStrategy,
Component,
ComponentRef,
EventEmitter,
Input,
OnDestroy,
Optional,
Output,
ViewChild,
ViewContainerRef,
ViewEncapsulation
} from '@angular/core';
import { Overlay } from '../core/overlay/overlay';
import { OverlayRef } from '../core/overlay/overlay-ref';
import { ComponentPortal }... |
ngOnDestroy() {
this.close();
if (this._popupRef) {
this._popupRef.dispose();
}
if (this._inputSubscription) {
this._inputSubscription.unsubscribe();
}
}
/** Selects the given date and closes the currently open popup or dialog. */
_selectAndClose(date: D): void {
let oldVa... | {
if (!this._dateAdapter) {
throw createMissingDateImplError('DateAdapter');
}
} | identifier_body |
datepicker.ts | ChangeDetectionStrategy,
Component,
ComponentRef,
EventEmitter,
Input,
OnDestroy,
Optional,
Output,
ViewChild,
ViewContainerRef,
ViewEncapsulation
} from '@angular/core';
import { Overlay } from '../core/overlay/overlay';
import { OverlayRef } from '../core/overlay/overlay-ref';
import { ComponentP... | if (this.opened) {
return;
}
if (!this._datepickerInput) {
throw new MdError('Attempted to open an MdDatepicker with no associated input.');
}
//this.touchUi ? this._openAsDialog() :
this._openAsPopup();
this.opened = true;
}
/** Close the calendar. */
close(): void {
... | /** Open the calendar. */
open(): void { | random_line_split |
datepicker.ts | DetectionStrategy,
Component,
ComponentRef,
EventEmitter,
Input,
OnDestroy,
Optional,
Output,
ViewChild,
ViewContainerRef,
ViewEncapsulation
} from '@angular/core';
import { Overlay } from '../core/overlay/overlay';
import { OverlayRef } from '../core/overlay/overlay-ref';
import { ComponentPortal }... |
this._datepickerInput = input;
this._inputSubscription =
this._datepickerInput._valueChange.subscribe((value: D) => this._selected = value);
}
/** Open the calendar. */
open(): void {
if (this.opened) {
return;
}
if (!this._datepickerInput) {
throw new MdError('Attempted to... | {
throw new MdError('An MdDatepicker can only be associated with a single input.');
} | conditional_block |
datepicker.ts | ChangeDetectionStrategy,
Component,
ComponentRef,
EventEmitter,
Input,
OnDestroy,
Optional,
Output,
ViewChild,
ViewContainerRef,
ViewEncapsulation
} from '@angular/core';
import { Overlay } from '../core/overlay/overlay';
import { OverlayRef } from '../core/overlay/overlay-ref';
import { ComponentP... | (): D {
return this._datepickerInput && this._datepickerInput.min;
}
/** The maximum selectable date. */
get _maxDate(): D {
return this._datepickerInput && this._datepickerInput.max;
}
get _dateFilter(): (date: D | null) => boolean {
return this._datepickerInput && this._datepickerInput._dateFi... | _minDate | identifier_name |
color-picker.tsx | import * as React from "react";
import { Collapse, Button, Intent, Card } from '@blueprintjs/core';
import { tr } from "../api/i18n";
import { NBSP } from '../constants';
import { DEFAULT_COLOR } from '../api/ol-style-contracts';
import { HexColorPicker } from "react-colorful";
/**
* Color picker props
*
* @since ... | <HexColorPicker style={{ width: "100%" }} color={props.value ?? DEFAULT_COLOR} onChange={(c: any) => props.onChange(c)} />
<Button icon="chevron-up" intent={Intent.PRIMARY} onClick={() => setIsPickerOpen(false)}>{tr("ACTION_CLOSE", props.locale)}</Button>
</Card>
</Co... | };
return <div>
<button disabled={props.disabled} style={{ width: 80, borderRadius: 3, backgroundColor: props.value ?? DEFAULT_COLOR }} onClick={onPickerToggle}>{NBSP}{NBSP}{NBSP}</button>
<Collapse isOpen={isPickerOpen}>
<Card> | random_line_split |
disposable.js | Rights Reserved.
//
// 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 agreed to in writing, so... |
delete goog.Disposable.instances_[uid];
}
}
};
/**
* Associates a disposable object with this object so that they will be disposed
* together.
* @param {goog.disposable.IDisposable} disposable that will be disposed when
* this object is disposed.
*/
goog.Disposable.prototype.registerDisposable =... | {
throw Error(this + ' did not call the goog.Disposable base ' +
'constructor or was disposed of after a clearUndisposedObjects ' +
'call');
} | conditional_block |
disposable.js | Rights Reserved.
//
// 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 agreed to in writing, so... | * For example:
* <pre>
* mypackage.MyClass = function() {
* mypackage.MyClass.base(this, 'constructor');
* // Constructor logic specific to MyClass.
* ...
* };
* goog.inherits(mypackage.MyClass, goog.Disposable);
*
* mypackage.MyClass.prototype.disposeInternal = function() {
* // Disp... | * Not reentrant. To avoid calling it twice, it must only be called from the
* subclass' {@code disposeInternal} method. Everywhere else the public
* {@code dispose} method must be used. | random_line_split |
journey.module.ts | import { NgModule } from '@angular/core';
import {
MdInputModule,
MdButtonModule,
MdCardModule,
MdListModule,
MdMenuModule,
MdTooltipModule,
MdDialogModule,
MdSnackBarModule,
} from '@angular/material';
import {
SharedModule,
SafeStylePipe,
} from '../shared';
import { CastModule } from '../parts/c... | { }
| JourneyModule | identifier_name |
journey.module.ts | import { NgModule } from '@angular/core';
import {
MdInputModule,
MdButtonModule,
MdCardModule,
MdListModule,
MdMenuModule,
MdTooltipModule,
MdDialogModule,
MdSnackBarModule,
} from '@angular/material';
import {
SharedModule,
SafeStylePipe,
} from '../shared';
import { CastModule } from '../parts/c... | ConfirmComponent,
],
providers: [
JourneyResolver,
SafeStylePipe,
],
})
export class JourneyModule { } | JourneyDetailCastComponent,
],
entryComponents: [ | random_line_split |
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
*
* Unless required by ap... | * var bool = isSameValue( 3.14, 3.14 );
* // returns true
*
* @example
* var bool = isSameValue( {}, {} );
* // returns false
*
* @example
* var bool = isSameValue( -0.0, -0.0 );
* // returns true
*
* @example
* var bool = isSameValue( -0.0, 0.0 );
* // returns false
*
* @example
* var bool = isSameValue( NaN, NaN );
*... | * @example | random_line_split |
ScatterView.js | define(function (require) {
var SymbolDraw = require('../helper/SymbolDraw');
var LargeSymbolDraw = require('../helper/LargeSymbolDraw');
require('../../echarts').extendChartView({
type: 'scatter',
init: function () {
this._normalSymbolDraw = new SymbolDraw();
... | });
}); | this._symbolDraw && this._symbolDraw.remove(api, true);
}
| random_line_split |
auth.js | //----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
"use strict";
var crypto = require("crypto"); | } else if (documentClient.resourceTokens) {
return this.getAuthorizationTokenUsingResourceTokens(documentClient.resourceTokens, path, resourceId);
}
},
getAuthorizationTokenUsingMasterKey: function (verb, resourceId, resourceType, headers, masterKey) {
var key = new Buffer(m... |
var AuthHandler = {
getAuthorizationHeader: function (documentClient, verb, path, resourceId, resourceType, headers) {
if (documentClient.masterKey) {
return this.getAuthorizationTokenUsingMasterKey(verb, resourceId, resourceType, headers, documentClient.masterKey); | random_line_split |
auth.js | //----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
"use strict";
var crypto = require("crypto");
var AuthHandler = {
getAuthorizationHeader: fun... |
},
getAuthorizationTokenUsingMasterKey: function (verb, resourceId, resourceType, headers, masterKey) {
var key = new Buffer(masterKey, "base64");
var text = (verb || "").toLowerCase() + "\n" +
(resourceType || "").toLowerCase() + "\n" +
(resourceId || ""... | {
return this.getAuthorizationTokenUsingResourceTokens(documentClient.resourceTokens, path, resourceId);
} | conditional_block |
flavormanage.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... |
req.cache_db_flavor(flavor)
except (exception.InstanceTypeExists,
exception.InstanceTypeIdExists) as err:
raise webob.exc.HTTPConflict(explanation=err.format_message())
except exception.InvalidInput as exc:
raise webob.exc.HTTPBadRequest(explanation=e... | flavors.add_flavor_access(flavor['flavorid'],
context.project_id, context) | conditional_block |
flavormanage.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... |
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")
except exception.NotFound as e:
raise web... | super(FlavorManageController, self).__init__() | identifier_body |
flavormanage.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | if not self.is_valid_body(body, 'flavor'):
msg = _("Invalid request body")
raise webob.exc.HTTPBadRequest(explanation=msg)
vals = body['flavor']
name = vals.get('name')
flavorid = vals.get('id')
memory = vals.get('ram')
vcpus = vals.get('vcpus')
... | authorize(context) | random_line_split |
flavormanage.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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... | (self):
super(FlavorManageController, self).__init__()
@wsgi.action("delete")
def _delete(self, req, id):
context = req.environ['nova.context']
authorize(context)
try:
flavor = flavors.get_flavor_by_flavor_id(
id, ctxt=context, read_deleted="no")... | __init__ | identifier_name |
mail.py | #!/usr/bin/python3
import sys, getpass, urllib.request, urllib.error, json
def mgmt(cmd, data=None, is_json=False):
# The base URL for the management daemon. (Listens on IPv4 only.)
mgmt_uri = 'http://127.0.0.1:10222'
setup_key_auth(mgmt_uri)
req = urllib.request.Request(mgmt_uri + cmd, urllib.parse.urlencode(d... |
else:
print("Invalid command-line arguments.")
sys.exit(1)
| print(mgmt("/mail/aliases/remove", { "source": sys.argv[3] })) | conditional_block |
mail.py | #!/usr/bin/python3
import sys, getpass, urllib.request, urllib.error, json
def mgmt(cmd, data=None, is_json=False):
# The base URL for the management daemon. (Listens on IPv4 only.)
mgmt_uri = 'http://127.0.0.1:10222'
setup_key_auth(mgmt_uri)
req = urllib.request.Request(mgmt_uri + cmd, urllib.parse.urlencode(d... | print("*", end='')
print()
elif sys.argv[1] == "user" and sys.argv[2] in ("add", "password"):
if len(sys.argv) < 5:
if len(sys.argv) < 4:
email = input("email: ")
else:
email = sys.argv[3]
pw = read_password()
else:
email, pw = sys.argv[3:5]
if sys.argv[2] == "add":
print(mgmt("/mail/users/a... | if "admin" in user['privileges']: | random_line_split |
mail.py | #!/usr/bin/python3
import sys, getpass, urllib.request, urllib.error, json
def mgmt(cmd, data=None, is_json=False):
# The base URL for the management daemon. (Listens on IPv4 only.)
mgmt_uri = 'http://127.0.0.1:10222'
setup_key_auth(mgmt_uri)
req = urllib.request.Request(mgmt_uri + cmd, urllib.parse.urlencode(d... | ():
first = getpass.getpass('password: ')
second = getpass.getpass(' (again): ')
while first != second:
print('Passwords not the same. Try again.')
first = getpass.getpass('password: ')
second = getpass.getpass(' (again): ')
return first
def setup_key_auth(mgmt_uri):
key = open('/var/lib/mailinabox/api.ke... | read_password | identifier_name |
mail.py | #!/usr/bin/python3
import sys, getpass, urllib.request, urllib.error, json
def mgmt(cmd, data=None, is_json=False):
# The base URL for the management daemon. (Listens on IPv4 only.)
mgmt_uri = 'http://127.0.0.1:10222'
setup_key_auth(mgmt_uri)
req = urllib.request.Request(mgmt_uri + cmd, urllib.parse.urlencode(d... |
def setup_key_auth(mgmt_uri):
key = open('/var/lib/mailinabox/api.key').read().strip()
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(
realm='Mail-in-a-Box Management Server',
uri=mgmt_uri,
user=key,
passwd='')
opener = urllib.request.build_opener(auth_handler)
urllib.req... | first = getpass.getpass('password: ')
second = getpass.getpass(' (again): ')
while first != second:
print('Passwords not the same. Try again.')
first = getpass.getpass('password: ')
second = getpass.getpass(' (again): ')
return first | identifier_body |
assign-user-renderer.js | /**
* @fileoverview Simple group component renderer.
*
*/
goog.provide('ydn.crm.su.ui.group.AssignUserRenderer');
goog.require('ydn.crm.su.ui.group.SimpleGroupRenderer');
/**
* Simple group component renderer.
* @constructor | };
goog.inherits(ydn.crm.su.ui.group.AssignUserRenderer,
ydn.crm.su.ui.group.SimpleGroupRenderer);
goog.addSingletonGetter(ydn.crm.su.ui.group.AssignUserRenderer);
/**
* @inheritDoc
*/
ydn.crm.su.ui.group.AssignUserRenderer.prototype.decorate = function(x) {
goog.base(this, 'decorate', x);
var ctrl = /** @t... | * @struct
* @extends {ydn.crm.su.ui.group.SimpleGroupRenderer}
*/
ydn.crm.su.ui.group.AssignUserRenderer = function() {
goog.base(this); | random_line_split |
urls.py |
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an impor... | """dryorm URL Configuration | random_line_split | |
15.2.3.3-4-200.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright an... |
runTestCase(testcase);
| {
var desc = Object.getOwnPropertyDescriptor(Number, "POSITIVE_INFINITY");
if (desc.writable === false &&
desc.enumerable === false &&
desc.configurable === false &&
desc.hasOwnProperty('get') === false &&
desc.hasOwnProperty('set') === false) {
return true;
}
} | identifier_body |
15.2.3.3-4-200.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright an... | function testcase() {
var desc = Object.getOwnPropertyDescriptor(Number, "POSITIVE_INFINITY");
if (desc.writable === false &&
desc.enumerable === false &&
desc.configurable === false &&
desc.hasOwnProperty('get') === false &&
desc.hasOwnProperty('set') === false) {
return true;
}
}
r... | random_line_split | |
15.2.3.3-4-200.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright an... | () {
var desc = Object.getOwnPropertyDescriptor(Number, "POSITIVE_INFINITY");
if (desc.writable === false &&
desc.enumerable === false &&
desc.configurable === false &&
desc.hasOwnProperty('get') === false &&
desc.hasOwnProperty('set') === false) {
return true;
}
}
runTestCase(testca... | testcase | identifier_name |
15.2.3.3-4-200.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright an... |
}
runTestCase(testcase);
| {
return true;
} | conditional_block |
http_server.ts | import * as http from "http";
import * as path from "path";
import * as fs from "fs";
import * as logger from "./logger";
import * as mime_map from "./http_server_mime_map";
///////////////////////////////////////////////////////////////////////////
// Bare minimum REST server
export interface IRequestWithBody extend... | public mime: string;
}
export class MinimalHttpServer {
// registered handlers
private handlers: Map<string, IProcessingHandler>;
// registered static content
private routes: Map<string, RouteRec>;
// prefix for logging messages
private log_prefix: string;
constructor(log_prefix?: str... | (data: any, callback: IProcessingHandlerCallback);
}
class RouteRec {
public local_path: string; | random_line_split |
http_server.ts | import * as http from "http";
import * as path from "path";
import * as fs from "fs";
import * as logger from "./logger";
import * as mime_map from "./http_server_mime_map";
///////////////////////////////////////////////////////////////////////////
// Bare minimum REST server
export interface IRequestWithBody extend... | (method: string, addr: string, body: any, resp: http.ServerResponse) {
logger.logger().debug(this.log_prefix + `Handling ${method} ${addr}`);
if (this.routes.has(addr)) {
const rec = this.routes.get(addr);
const stat = fs.statSync(rec.local_path);
resp.writeHead(200, ... | handle | identifier_name |
http_server.ts | import * as http from "http";
import * as path from "path";
import * as fs from "fs";
import * as logger from "./logger";
import * as mime_map from "./http_server_mime_map";
///////////////////////////////////////////////////////////////////////////
// Bare minimum REST server
export interface IRequestWithBody extend... | return;
}
logger.logger().debug(this.log_prefix + "Handling " + req.body);
try {
this.handlers.get(addr)(data, (err, data_inner) => {
if (err) {
return this.handleError(err, resp);... | {
const server = http.createServer(this.withBody((req, resp) => {
// get the HTTP method, path and body of the request
// let method = req.method;
const addr = req.url;
logger.logger().debug(this.log_prefix + `Handling ${req.method} ${addr}`);
if (th... | identifier_body |
http_server.ts | import * as http from "http";
import * as path from "path";
import * as fs from "fs";
import * as logger from "./logger";
import * as mime_map from "./http_server_mime_map";
///////////////////////////////////////////////////////////////////////////
// Bare minimum REST server
export interface IRequestWithBody extend... |
const rec = new RouteRec();
rec.local_path = path.resolve(local_path);
const ext = path.extname(local_path);
rec.mime = mime_map.getMImeType(ext);
this.routes.set(addr, rec);
}
/** For registering all files from certain directory as simple static paths */
public addD... | {
addr = "/" + addr;
} | conditional_block |
match-vec-rvalue.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
match vec!(1, 2, 3) {
x => {
assert_eq!(x.len(), 3);
assert_eq!(*x.get(0), 1);
assert_eq!(*x.get(1), 2);
assert_eq!(*x.get(2), 3);
}
}
} | identifier_body | |
match-vec-rvalue.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
match vec!(1, 2, 3) {
x => {
assert_eq!(x.len(), 3);
assert_eq!(*x.get(0), 1);
assert_eq!(*x.get(1), 2);
assert_eq!(*x.get(2), 3);
}
}
}
| main | identifier_name |
match-vec-rvalue.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | x => {
assert_eq!(x.len(), 3);
assert_eq!(*x.get(0), 1);
assert_eq!(*x.get(1), 2);
assert_eq!(*x.get(2), 3);
}
}
} |
pub fn main() {
match vec!(1, 2, 3) { | random_line_split |
donut-display.js | /* globals d3 */
/* Inspired a lot from: https://github.com/vicapow/angular-d3-talk/blob/master/slides/demos/lets-make-a-donut-chart-directive */
'use strict';
/**
* @ngdoc directive
* @name couchD3App.directive:donutDisplay
* @description
* # donutDisplay
*/
angular.module('couchD3App').directive('donutDisplay'... |
});
});
function arcTween(a) {
// see: http://bl.ocks.org/mbostock/1346410
var i = d3.interpolate(scope._current, a);
scope._current = i(0);
return function(t) {
return arc(i(t));
};
}
// add the <path>s for each arc slice
// All modification in the arc actually modify the item inside... | {
scope.onClick();
} | conditional_block |
donut-display.js | /* globals d3 */
/* Inspired a lot from: https://github.com/vicapow/angular-d3-talk/blob/master/slides/demos/lets-make-a-donut-chart-directive */
'use strict';
/**
* @ngdoc directive
* @name couchD3App.directive:donutDisplay
* @description
* # donutDisplay
*/
angular.module('couchD3App').directive('donutDisplay'... | scope: {
'data': '=',
'onClick': '&'
},
templateUrl: 'views/graphInfo.html'
};
}); |
return {
restrict: 'E',
link: link, | random_line_split |
donut-display.js | /* globals d3 */
/* Inspired a lot from: https://github.com/vicapow/angular-d3-talk/blob/master/slides/demos/lets-make-a-donut-chart-directive */
'use strict';
/**
* @ngdoc directive
* @name couchD3App.directive:donutDisplay
* @description
* # donutDisplay
*/
angular.module('couchD3App').directive('donutDisplay'... | (a) {
// see: http://bl.ocks.org/mbostock/1346410
var i = d3.interpolate(scope._current, a);
scope._current = i(0);
return function(t) {
return arc(i(t));
};
}
// add the <path>s for each arc slice
// All modification in the arc actually modify the item inside "svg"
var arcs = svg.selectAll(... | arcTween | identifier_name |
donut-display.js | /* globals d3 */
/* Inspired a lot from: https://github.com/vicapow/angular-d3-talk/blob/master/slides/demos/lets-make-a-donut-chart-directive */
'use strict';
/**
* @ngdoc directive
* @name couchD3App.directive:donutDisplay
* @description
* # donutDisplay
*/
angular.module('couchD3App').directive('donutDisplay'... |
// add the <path>s for each arc slice
// All modification in the arc actually modify the item inside "svg"
var arcs = svg.selectAll('path.arc').data(pie(scope.data))
.enter().append('path')
.attr('class', 'arc')
.style('stroke', 'white')
.attr('fill', function(d, i) {
return color(i);
})
/... | {
// see: http://bl.ocks.org/mbostock/1346410
var i = d3.interpolate(scope._current, a);
scope._current = i(0);
return function(t) {
return arc(i(t));
};
} | identifier_body |
curly.ts | , boolean] = AttributeBinding.parse(binding);
let attribute = parsed[1];
if (seen.indexOf(attribute) === -1) {
seen.push(attribute);
AttributeBinding.install(element, component, parsed, operations);
}
i--;
}
if (seen.indexOf('id') === -1) {
let id = component.elementId ? component... |
getCapabilities(state: DefinitionState) {
return state.capabilities;
}
prepareArgs(state: DefinitionState, args: Arguments): Option<PreparedArguments> {
if (args.named.has('__ARGS__')) {
let __args__ = args.named.get('__ARGS__').value() as Dict<VersionedPathReference>;
let prepared = {
... | }
return (component && component.tagName) || 'div';
} | random_line_split |
curly.ts | , boolean] = AttributeBinding.parse(binding);
let attribute = parsed[1];
if (seen.indexOf(attribute) === -1) {
seen.push(attribute);
AttributeBinding.install(element, component, parsed, operations);
}
i--;
}
if (seen.indexOf('id') === -1) {
let id = component.elementId ? component... |
return (component && component.tagName) || 'div';
}
getCapabilities(state: DefinitionState) {
return state.capabilities;
}
prepareArgs(state: DefinitionState, args: Arguments): Option<PreparedArguments> {
if (args.named.has('__ARGS__')) {
let __args__ = args.named.get('__ARGS__').value() a... | {
return null;
} | conditional_block |
curly.ts | , boolean] = AttributeBinding.parse(binding);
let attribute = parsed[1];
if (seen.indexOf(attribute) === -1) {
seen.push(attribute);
AttributeBinding.install(element, component, parsed, operations);
}
i--;
}
if (seen.indexOf('id') === -1) {
let id = component.elementId ? component... |
getCapabilities(state: DefinitionState) {
return state.capabilities;
}
prepareArgs(state: DefinitionState, args: Arguments): Option<PreparedArguments> {
if (args.named.has('__ARGS__')) {
let __args__ = args.named.get('__ARGS__').value() as Dict<VersionedPathReference>;
let prepared = {
... | {
let { component, hasWrappedElement } = state;
if (!hasWrappedElement) {
return null;
}
return (component && component.tagName) || 'div';
} | identifier_body |
curly.ts | , boolean] = AttributeBinding.parse(binding);
let attribute = parsed[1];
if (seen.indexOf(attribute) === -1) {
seen.push(attribute);
AttributeBinding.install(element, component, parsed, operations);
}
i--;
}
if (seen.indexOf('id') === -1) {
let id = component.elementId ? component... | (state: DefinitionState) {
return state.capabilities;
}
prepareArgs(state: DefinitionState, args: Arguments): Option<PreparedArguments> {
if (args.named.has('__ARGS__')) {
let __args__ = args.named.get('__ARGS__').value() as Dict<VersionedPathReference>;
let prepared = {
positional: EM... | getCapabilities | identifier_name |
step5_tco.rs | use std::rc::Rc;
//use std::collections::HashMap;
use fnv::FnvHashMap;
use itertools::Itertools;
#[macro_use]
extern crate lazy_static;
extern crate regex;
extern crate itertools;
extern crate fnv;
extern crate rustyline;
use rustyline::error::ReadlineError;
use rustyline::Editor;
#[macro_use]
mod types;
use types::... | (ast: &MalVal, env: &Env) -> MalRet {
match ast {
Sym(_) => Ok(env_get(&env, &ast)?),
List(v,_) => {
let mut lst: MalArgs = vec![];
for a in v.iter() { lst.push(eval(a.clone(), env.clone())?) }
Ok(list!(lst))
},
Vector(v,_) => {
let mut lst: MalArgs = vec![];
for a in v.... | eval_ast | identifier_name |
step5_tco.rs | use std::rc::Rc;
//use std::collections::HashMap;
use fnv::FnvHashMap;
use itertools::Itertools;
#[macro_use]
extern crate lazy_static;
extern crate regex;
extern crate itertools;
extern crate fnv;
extern crate rustyline;
use rustyline::error::ReadlineError;
use rustyline::Editor;
#[macro_use]
mod types;
use types::... | _ => Ok(ast.clone()),
}
}
fn eval(mut ast: MalVal, mut env: Env) -> MalRet {
let ret: MalRet;
'tco: loop {
ret = match ast.clone() {
List(l,_) => {
if l.len() == 0 { return Ok(ast); }
let a0 = &l[0];
match a0 {
Sym(ref a0sym) if a0sym == "def!" => {
env_set(&env, ... | {
match ast {
Sym(_) => Ok(env_get(&env, &ast)?),
List(v,_) => {
let mut lst: MalArgs = vec![];
for a in v.iter() { lst.push(eval(a.clone(), env.clone())?) }
Ok(list!(lst))
},
Vector(v,_) => {
let mut lst: MalArgs = vec![];
for a in v.iter() { lst.push(eval(a.clone(), en... | identifier_body |
step5_tco.rs | use std::rc::Rc;
//use std::collections::HashMap;
use fnv::FnvHashMap;
use itertools::Itertools;
#[macro_use]
extern crate lazy_static;
extern crate regex;
extern crate itertools;
extern crate fnv;
extern crate rustyline;
use rustyline::error::ReadlineError;
use rustyline::Editor;
#[macro_use]
mod types;
use types::... | }
}
}
// vim: ts=2:sw=2:expandtab | random_line_split | |
models.py | import json
import django
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.core.serializers.json import DjangoJSONEncoder
from django.d... |
def get_value(self):
value = json.loads(self.value)
value['id'] = self.id
value['type'] = self.widget_type
return value
def set_value(self, obj):
self.value = json.dumps(obj, cls=JSONEncoder, ensure_ascii=False)
def save(self, *args, **kwargs):
created = se... | user = models.ForeignKey(AUTH_USER_MODEL, verbose_name=_(u"user"))
page_id = models.CharField(_(u"Page"), max_length=256)
widget_type = models.CharField(_(u"Widget Type"), max_length=50)
value = models.TextField(_(u"Widget Params")) | random_line_split |
models.py | import json
import django
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.core.serializers.json import DjangoJSONEncoder
from django.d... |
def add_view_permissions(sender, **kwargs):
"""
This syncdb hooks takes care of adding a view permission too all our
content types.
"""
argv = sys.argv
permissions_with_tests = getattr(settings, "XADMIN_TEST_VIEW_PERMISSIONS", True)
if not permissions_with_tests and len(argv) > 1 \
... | AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') | conditional_block |
models.py | import json
import django
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.core.serializers.json import DjangoJSONEncoder
from django.d... | name="Can view %s" % content_type.name)
#print "Added view permission for %s" % content_type.name
# check for all our view permissions after a syncdb
post_syncdb.connect(add_view_permissions)
class Bookmark(models.Model):
title = models.CharField(_(u'Title'), ma... | """
This syncdb hooks takes care of adding a view permission too all our
content types.
"""
argv = sys.argv
permissions_with_tests = getattr(settings, "XADMIN_TEST_VIEW_PERMISSIONS", True)
if not permissions_with_tests and len(argv) > 1 \
and (argv[1] == "test" or argv[1] == "jenkins... | identifier_body |
models.py | import json
import django
from django.db import models
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from django.core.serializers.json import DjangoJSONEncoder
from django.d... | (sender, **kwargs):
"""
This syncdb hooks takes care of adding a view permission too all our
content types.
"""
argv = sys.argv
permissions_with_tests = getattr(settings, "XADMIN_TEST_VIEW_PERMISSIONS", True)
if not permissions_with_tests and len(argv) > 1 \
and (argv[1] == "test... | add_view_permissions | identifier_name |
chain_api.rs | {
match get_output_v2(
&self.chain,
&commit,
include_proof.unwrap_or(false),
include_merkle_proof.unwrap_or(false),
) {
Ok(Some((output, _))) => outputs.push(output),
Ok(None) => {
// Ignore outputs that are not found
}
Err(e) => {
error!(
"Failure to ... | {
let excess = req
.uri()
.path()
.trim_end_matches('/')
.rsplit('/')
.next()
.ok_or_else(|| ErrorKind::RequestError("missing excess".into()))?;
let excess = util::from_hex(excess)
.map_err(|_| ErrorKind::RequestError("invalid excess hex".into()))?;
if excess.len() != 33 {
return Err(Error... | identifier_body | |
chain_api.rs | (StatusCode::OK, "{}"),
Err(e) => response(
StatusCode::INTERNAL_SERVER_ERROR,
format!("validate failed: {}", e),
),
}
}
}
pub struct ChainResetHandler {
pub chain: Weak<chain::Chain>,
pub sync_state: Weak<chain::SyncState>,
}
impl ChainResetHandler {
pub fn reset_chain_head(&self, hash: Hash) -> ... | if let Ok(x) = util::from_hex(id) {
commitments.push(Commitment::from_vec(x));
}
});
let start_height = parse_param!(params, "start_height", 1);
let end_height = parse_param!(params, "end_height", 1);
let include_rp = params.get("include_rp").is_some();
debug!(
"outputs_block_batch: {}-{}, {:?},... |
let query = must_get_query!(req);
let params = QueryParams::from(query);
params.process_multival_param("id", |id| { | random_line_split |
chain_api.rs | (StatusCode::OK, "{}"),
Err(e) => response(
StatusCode::INTERNAL_SERVER_ERROR,
format!("validate failed: {}", e),
),
}
}
}
pub struct ChainResetHandler {
pub chain: Weak<chain::Chain>,
pub sync_state: Weak<chain::SyncState>,
}
impl ChainResetHandler {
pub fn reset_chain_head(&self, hash: Hash) -> ... | {
pub chain: Weak<chain::Chain>,
}
impl OutputHandler {
pub fn get_outputs_v2(
&self,
commits: Option<Vec<String>>,
start_height: Option<u64>,
end_height: Option<u64>,
include_proof: Option<bool>,
include_merkle_proof: Option<bool>,
) -> Result<Vec<OutputPrintable>, Error> {
let mut outputs: Vec<Outp... | OutputHandler | identifier_name |
chain_api.rs | pub chain: Weak<chain::Chain>,
pub sync_state: Weak<chain::SyncState>,
}
impl ChainResetHandler {
pub fn reset_chain_head(&self, hash: Hash) -> Result<(), Error> {
let chain = w(&self.chain)?;
let header = chain.get_block_header(&hash)?;
chain.reset_chain_head(&header)?;
// Reset the sync status and clear ... | {
return_vec.push(res);
} | conditional_block | |
scripts.js | function | () {
//tool tips
jQuery('.tooltips').tooltip();
//popovers
jQuery('.popovers').popover();
//custom scrollbar
//for html
jQuery("html").niceScroll({styler:"fb",cursorcolor:"#007AFF", cursorwidth: '6', cursorborderradius: '10px', background: '#F7F7F7', cursorborder: '', zindex... | initializeJS | identifier_name |
scripts.js | function initializeJS() {
//tool tips
jQuery('.tooltips').tooltip();
//popovers
jQuery('.popovers').popover();
//custom scrollbar
//for html
jQuery("html").niceScroll({styler:"fb",cursorcolor:"#007AFF", cursorwidth: '6', cursorborderradius: '10px', background: '#F7F7F7', cur... | var mode = state ? "on" : "off";
$.cookie("edit_mode", mode, { path : '/' });
//if we're on the roster page, we should refresh the page
//but give it some time to complete the animation
setTimeout(function(){ location.reload(true);}, 1000);
});
... |
//the following methods are called when the swich is changed
//going to use this to send a message to update the tables
$('input[name="edit_switch"]').on('switchChange.bootstrapSwitch', function(event, state) {
//change the cookie value depending on the state
| random_line_split |
scripts.js | function initializeJS() | jQuery('.sub', last).slideUp(200);
var sub = jQuery(this).next();
if (sub.is(":visible")) {
jQuery('.menu-arrow').addClass('arrow_carrot-right');
sub.slideUp(200);
} else {
jQuery('.menu-arrow').addClass('arrow_carrot-down'); ... | {
//tool tips
jQuery('.tooltips').tooltip();
//popovers
jQuery('.popovers').popover();
//custom scrollbar
//for html
jQuery("html").niceScroll({styler:"fb",cursorcolor:"#007AFF", cursorwidth: '6', cursorborderradius: '10px', background: '#F7F7F7', cursorborder: '', zindex: '... | identifier_body |
scripts.js | function initializeJS() {
//tool tips
jQuery('.tooltips').tooltip();
//popovers
jQuery('.popovers').popover();
//custom scrollbar
//for html
jQuery("html").niceScroll({styler:"fb",cursorcolor:"#007AFF", cursorwidth: '6', cursorborderradius: '10px', background: '#F7F7F7', cur... |
//Bootstrap switch functions, this makes my layout and edit mode
//selection look so snazzy
// --Devan
$('input[name="edit_switch"]').bootstrapSwitch();
$('input[name="layout_switch"]').bootstrapSwitch();
var mode = $.cookie("edit_mode");
//if the cookie is not set... | {
$("#lastname-btn").addClass("active");
} | conditional_block |
lib.rs | _all_pixels(*red, *green, *blue);
//! blinkt.show()?;
//!
//! thread::sleep(Duration::from_millis(250));
//!
//! mem::swap(red, green);
//! mem::swap(red, blue);
//! }
//! }
//! ```
//!
//! ### APA102 or SK9822 LED strip
//!
//! The recommended way to control an LED strip is to use t... |
}
impl SerialOutput for BlinktSpi {
fn write(&mut self, data: &[u8]) -> Result<()> {
self.0.write(data)?;
Ok(())
}
}
/// Interface for the Pimoroni Blinkt!, and any similar APA102 or SK9822 LED
/// strips or boards.
///
/// By default, Blinkt is set up to communicate with an 8-pixel board th... | {
Self(
spi::Spi::new(
spi::Bus::Spi0,
spi::SlaveSelect::Ss0,
1_000_000,
spi::Mode::Mode0,
)
.expect("Can't create spi bus"),
)
} | identifier_body |
lib.rs | _all_pixels(*red, *green, *blue);
//! blinkt.show()?;
//!
//! thread::sleep(Duration::from_millis(250));
//!
//! mem::swap(red, green);
//! mem::swap(red, blue);
//! }
//! }
//! ```
//!
//! ### APA102 or SK9822 LED strip
//!
//! The recommended way to control an LED strip is to use t... | //! #
//! # fn main() -> Result<(), Box<dyn Error>> {
//! # let mut blinkt = Blinkt::new()?;
//! #
//! blinkt.iter_mut().for_each(|pixel| {
//! pixel.set_rgb(255, 0, 255);
//! });
//! # Ok(())
//! # }
//! ```
//!
//! For more idiomatic `for` loops, you can access the same iterator
//! through a mutable refer... | //! # use std::error::Error;
//! #
//! # use blinkt::Blinkt; | random_line_split |
lib.rs | _all_pixels(*red, *green, *blue);
//! blinkt.show()?;
//!
//! thread::sleep(Duration::from_millis(250));
//!
//! mem::swap(red, green);
//! mem::swap(red, blue);
//! }
//! }
//! ```
//!
//! ### APA102 or SK9822 LED strip
//!
//! The recommended way to control an LED strip is to use t... | (&mut self, data: &[u8]) -> Result<()> {
for byte in data {
for n in 0..8 {
if (byte & (1 << (7 - n))) > 0 {
self.pin_data.set_high();
} else {
self.pin_data.set_low();
}
self.pin_clock.set_high(... | write | identifier_name |
options.py | # -*- coding: utf-8 -*-
# * Copyright (C) 2012-2014 Croissance Commune
# * Authors:
# * Arezki Feth <f.a@majerti.fr>;
# * Miotte Julien <j.m@majerti.fr>;
# * TJEBBES Gaston <g.t@majerti.fr>
#
# This file is part of Autonomie : Progiciel de gestion de CAE.
#
# Autonomie is free software: you can red... |
def move_down(self):
"""
Move the current instance down in the category's order
"""
order = self.order
new_order = order + 1
self.__class__.insert(self, new_order)
@classmethod
def get_next_order(cls):
"""
:returns: The next available order
... | ""
Move the current instance up in the category's order
"""
order = self.order
if order > 0:
new_order = order - 1
self.__class__.insert(self, new_order)
| identifier_body |
options.py | # -*- coding: utf-8 -*-
# * Copyright (C) 2012-2014 Croissance Commune
# * Authors:
# * Arezki Feth <f.a@majerti.fr>;
# * Miotte Julien <j.m@majerti.fr>;
# * TJEBBES Gaston <g.t@majerti.fr>
#
# This file is part of Autonomie : Progiciel de gestion de CAE.
#
# Autonomie is free software: you can red... |
def move_down(self):
"""
Move the current instance down in the category's order
"""
order = self.order
new_order = order + 1
self.__class__.insert(self, new_order)
@classmethod
def get_next_order(cls):
"""
:returns: The next available order
... | ew_order = order - 1
self.__class__.insert(self, new_order)
| conditional_block |
options.py | # -*- coding: utf-8 -*-
# * Copyright (C) 2012-2014 Croissance Commune
# * Authors:
# * Arezki Feth <f.a@majerti.fr>;
# * Miotte Julien <j.m@majerti.fr>;
# * TJEBBES Gaston <g.t@majerti.fr>
#
# This file is part of Autonomie : Progiciel de gestion de CAE.
#
# Autonomie is free software: you can red... | cls):
"""
Regenerate order attributes
"""
items = cls._query_active_items().order_by(cls.order).all()
for index, item in enumerate(items):
item.order = index
DBSESSION().merge(item)
def get_id_foreignkey_col(foreignkey_str):
"""
Return an id col... | eorder( | identifier_name |
options.py | # -*- coding: utf-8 -*-
# * Copyright (C) 2012-2014 Croissance Commune
# * Authors:
# * Arezki Feth <f.a@majerti.fr>;
# * Miotte Julien <j.m@majerti.fr>;
# * TJEBBES Gaston <g.t@majerti.fr>
#
# This file is part of Autonomie : Progiciel de gestion de CAE.
#
# Autonomie is free software: you can red... | info={'colanderalchemy': get_hidden_field_conf()},
)
return column | ForeignKey(foreignkey_str),
primary_key=True, | random_line_split |
ruby.js | /*
Language: Ruby
Author: Anton Kovalyov <anton@kovalyov.net>
Contributors: Peter Leonov <gojpeg@yandex.ru>, Vasily Polovnyov <vast@whiteants.net>, Loren Segal <lsegal@soen.ca>
*/
function(hljs) {
var RUBY_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]\\@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?';
var RUBY_KE... | relevance: 0
},
{
className: 'symbol',
begin: hljs.UNDERSCORE_IDENT_RE + '(\\!|\\?)?:',
relevance: 0
},
{
className: 'number',
begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b',
relevance: 0
},
{
className: 'variabl... | className: 'symbol',
begin: ':',
contains: [STRING, {begin: RUBY_METHOD_RE}], | random_line_split |
follow.js | mess around a lot with the zIndex which
* lets some hints in the background.
* TODO: Some positions are not calculated correctly (mostly
* because of uber-fancy-designed-webpages. Basic HTML and CSS
* works good
* TODO: Still some links can't be followed/unexpected things
* happen. Blame some freaky webdesigners... |
//Put it all together
function followLinks(follow) {
// if(follow.charAt(0) == 'l') {
// follow = follow.substr(1);
// charset = 'thsnlrcgfdbmwvz-/';
// }
var s = follow.split('');
var linknr = labelToInt(follow);
if (document.body) document.body.setAttribute('onkeyup', 'keyPressHan... | {
var n = 0;
var i;
for(i = 0; i < label.length; ++i) {
n *= charset.length;
n += charset.indexOf(label[i]);
}
return n;
} | identifier_body |
follow.js | mess around a lot with the zIndex which
* lets some hints in the background.
* TODO: Some positions are not calculated correctly (mostly
* because of uber-fancy-designed-webpages. Basic HTML and CSS
* works good
* TODO: Still some links can't be followed/unexpected things
* happen. Blame some freaky webdesigners... |
n -= 1; // our highest key will be n-1
while(n) {
keylen += 1;
n = Math.floor(n / charset.length);
}
return keylen;
}
// pass: number
// returns: label
function intToLabel(n) {
var label = '';
do {
label = charset.charAt(n % charset.length) + label;
n = Math.floor(n / charset.length);
} while(n);
retur... | {
return 1;
} | conditional_block |
follow.js | pages mess around a lot with the zIndex which
* lets some hints in the background.
* TODO: Some positions are not calculated correctly (mostly
* because of uber-fancy-designed-webpages. Basic HTML and CSS
* works good
* TODO: Still some links can't be followed/unexpected things
* happen. Blame some freaky webdes... | item.click();
}
} else if (name == 'TEXTAREA' || name == 'SELECT') {
item.focus();
item.select();
} else {
item.click();
window.location = item.href;
}
}
}
//Returns a list of all links (in this version
//just the el... | random_line_split | |
follow.js | pages mess around a lot with the zIndex which
* lets some hints in the background.
* TODO: Some positions are not calculated correctly (mostly
* because of uber-fancy-designed-webpages. Basic HTML and CSS
* works good
* TODO: Still some links can't be followed/unexpected things
* happen. Blame some freaky webdes... | (n) {
var label = '';
do {
label = charset.charAt(n % charset.length) + label;
n = Math.floor(n / charset.length);
} while(n);
return label;
}
// pass: label
// returns: number
function labelToInt(label) {
var n = 0;
var i;
for(i = 0; i < label.length; ++i) {
n *= charset.length;
n += charset.indexOf(lab... | intToLabel | identifier_name |
c-style-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | {
TheOnlyVariant
}
static SINGLE_VARIANT: SingleVariant = TheOnlyVariant;
static mut AUTO_ONE: AutoDiscriminant = One;
static mut AUTO_TWO: AutoDiscriminant = One;
static mut AUTO_THREE: AutoDiscriminant = One;
static mut MANUAL_ONE: ManualDiscriminant = OneHundred;
static mut MANUAL_TWO: ManualDiscriminant = O... | SingleVariant | identifier_name |
c-style-enum.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | }
static SINGLE_VARIANT: SingleVariant = TheOnlyVariant;
static mut AUTO_ONE: AutoDiscriminant = One;
static mut AUTO_TWO: AutoDiscriminant = One;
static mut AUTO_THREE: AutoDiscriminant = One;
static mut MANUAL_ONE: ManualDiscriminant = OneHundred;
static mut MANUAL_TWO: ManualDiscriminant = OneHundred;
static mut ... |
enum SingleVariant {
TheOnlyVariant | random_line_split |
index.d.ts | // Type definitions for multer-s3 2.7
// Project: https://github.com/badunk/multer-s3
// Definitions by: KIM Jaesuck a.k.a. gim tcaesvk <https://github.com/tcaesvk>
// Gal Talmor <https://github.com/galtalmor>
// Matt Terski <https://github.com/terski>
// Definitions: https://github.com/... | contentType?(req: Express.Request, file: Express.Multer.File, callback: (error: any, mime?: string, stream?: NodeJS.ReadableStream) => void): void;
contentDisposition?: ((req: Express.Request, file: Express.Multer.File, callback: (error: any, contentDisposition?: string) => void) => void) | string | undefined;
... | interface Options {
s3: AWS.S3;
bucket: ((req: Express.Request, file: Express.Multer.File, callback: (error: any, bucket?: string) => void) => void) | string;
key?(req: Express.Request, file: Express.Multer.File, callback: (error: any, key?: string) => void): void;
acl?: ((req: Express.Request, file: Ex... | random_line_split |
DateBlock.js | import React, { PropTypes } from 'react';
import { dateTimeUtils } from '../../utils';
| const isMultiDayEvent = endDate ? dateTimeUtils.dateTimeNoOffset(startDate, 'DDD') !== dateTimeUtils.dateTimeNoOffset(endDate, 'DDD') : false;
// get start date values
const [startDayName, startMonth, startDayNum] = dateTimeUtils.dateTimeNoOffset(startDate, 'ddd MMM D').split(' ');
// get end date values
... | import styles from './DateBlock.sass';
const DateBlock = ({ startDate, endDate }) => { | random_line_split |
parser2.py | # parser2.py
# parses sentences from the CSV files
# J. Hassler Thurston
# RocHack Hackathon December 7, 2013
# Modified December 11, 2013
import nltk
from random import choice
cfg_file = 'upenn_grammar.cfg'
tbank_productions = []
nonterminals = []
rightside = []
def get_initial_rules():
global tbank_productions, n... |
else:
frags.append(items[0])
else:
print items[:2]
# This is where we need to make our changes
chosen_expansion = choice(items)
#print type(chosen_expansion)
frags.append(generate_sample(grammar, [chosen_expansion]))
return frags
| frags.append(generate_sample(grammar, grammar.productions(lhs=items[0]))) | conditional_block |
parser2.py | # parser2.py
# parses sentences from the CSV files
# J. Hassler Thurston
# RocHack Hackathon December 7, 2013
# Modified December 11, 2013
import nltk
from random import choice
cfg_file = 'upenn_grammar.cfg'
tbank_productions = []
nonterminals = []
rightside = []
def get_initial_rules():
global tbank_productions, n... | frags = []
if len(items) == 1:
print items
if isinstance(items[0], nltk.grammar.Nonterminal):
frags.append(generate_sample(grammar, grammar.productions(lhs=items[0])))
else:
frags.append(items[0])
else:
print items[:2]
# This is where we need to make our changes
chosen_expansion = choice(items)
#p... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.