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 |
|---|---|---|---|---|
ButtonBase.js | ::-moz-focus-inner': {
borderStyle: 'none' // Remove Firefox dotted outline.
},
'&$disabled': {
pointerEvents: 'none',
// Disable link interactions
cursor: 'default'
},
'@media print': {
colorAdjust: 'exact'
}
},
/* Pseudo-class applied to the root element if `dis... |
const handleMouseDown = useRippleHandler('start', onMouseDown);
const handleDragLeave = useRippleHandler('stop', onDragLeave);
const handleMouseUp = useRippleHandler('stop', onMouseUp);
const handleMouseLeave = useRippleHandler('stop', event => {
if (focusVisible) {
event.preventDefault();
}
... | {
return useEventCallback(event => {
if (eventCallback) {
eventCallback(event);
}
const ignore = skipRippleAction;
if (!ignore && rippleRef.current) {
rippleRef.current[rippleAction](event);
}
return true;
});
} | identifier_body |
ButtonBase.js | } = props,
other = _objectWithoutPropertiesLoose(props, ["action", "buttonRef", "centerRipple", "children", "classes", "className", "component", "disabled", "disableRipple", "disableTouchRipple", "focusRipple", "focusVisibleClassName", "onBlur", "onClick", "onFocus", "onFocusVisible", "onKeyDown", "onKeyUp", ... | random_line_split | ||
ButtonBase.js | ::-moz-focus-inner': {
borderStyle: 'none' // Remove Firefox dotted outline.
},
'&$disabled': {
pointerEvents: 'none',
// Disable link interactions
cursor: 'default'
},
'@media print': {
colorAdjust: 'exact'
}
},
/* Pseudo-class applied to the root element if `dis... |
});
const isNonNativeButton = () => {
const button = getButtonNode();
return component && component !== 'button' && !(button.tagName === 'A' && button.href);
};
/**
* IE 11 shim for https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/repeat
*/
const keydownRef = React.useRef(false... | {
onFocus(event);
} | conditional_block |
ButtonBase.js | '&::-moz-focus-inner': {
borderStyle: 'none' // Remove Firefox dotted outline.
},
'&$disabled': {
pointerEvents: 'none',
// Disable link interactions
cursor: 'default'
},
'@media print': {
colorAdjust: 'exact'
}
},
/* Pseudo-class applied to the root element if `... | () {
// #StrictMode ready
return ReactDOM.findDOMNode(buttonRef.current);
}
const rippleRef = React.useRef(null);
const [focusVisible, setFocusVisible] = React.useState(false);
if (disabled && focusVisible) {
setFocusVisible(false);
}
const {
isFocusVisible,
onBlurVisible,
ref: fo... | getButtonNode | identifier_name |
urls.py | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from views import HomeView, SimpleChainView, MultipleChainView, ModelChainView, EditCarView, DeleteCarView, \
AjaxChainedNames, AjaxChainedCountries, AjaxCh... | url(r'^multiple-chain/$', MultipleChainView.as_view(), name='multiple_chain'),
url(r'^model-chain/$', ModelChainView.as_view(), name='model_chain'),
url(r'^edit-car/(?P<pk>[-\d]+)/$', EditCarView.as_view(), name='edit_car'),
url(r'^delete-car/(?P<pk>[-\d]+)/$', DeleteCarView.as_view(), name='delete_car'... | url(r'^ajax/chained-cities/$', AjaxChainedCities.as_view(), name='ajax_chained_cities'),
url(r'^ajax/chained-brand-models/$', AjaxChainedModels.as_view(), name='ajax_chained_models'),
url(r'^ajax/chained-colors/$', AjaxChainedColors.as_view(), name='ajax_chained_colors'),
url(r'^simple-chain/$', Simple... | random_line_split |
ingest_file_browser.js | // remove selected entry
explorer.selectedEntryId = undefined;
} else {
// remove highlighting of existing entries
$('#' + explorerId).find('.backbone-file-explorer-entry').css('border', '');
// highlight selected entry
$(entryEl).css('border', borderCssSpec);
... | (arrange) {
var selectedType = arrange.getTypeForCssId(arrange.selectedEntryId);
// enable/disable delete button
if (typeof arrange.selectedEntryId !== 'undefined') {
enableElements(['#arrange_delete_button']);
} else {
disableElements(['#arrange_delete_button']);
}
// enable/disab... | enableOrDisableArrangePanelActionButtons | identifier_name |
ingest_file_browser.js | // remove selected entry
explorer.selectedEntryId = undefined;
} else {
// remove highlighting of existing entries
$('#' + explorerId).find('.backbone-file-explorer-entry').css('border', '');
// highlight selected entry
$(entryEl).css('border', borderCssSpec);
... | } else {
disableElements(['#arrange_edit_metadata_button']);
}
// enable/disable create directory button
// (if nothing is selected, it'll create in top level)
if (typeof arrange.selectedEntryId === 'undefined' || selectedType == 'directory') {
enableElements(['#arrange_create_director... | {
var selectedType = arrange.getTypeForCssId(arrange.selectedEntryId);
// enable/disable delete button
if (typeof arrange.selectedEntryId !== 'undefined') {
enableElements(['#arrange_delete_button']);
} else {
disableElements(['#arrange_delete_button']);
}
// enable/disable create ... | identifier_body |
ingest_file_browser.js | // remove selected entry
explorer.selectedEntryId = undefined;
} else {
// remove highlighting of existing entries
$('#' + explorerId).find('.backbone-file-explorer-entry').css('border', '');
// highlight selected entry
$(entryEl).css('border', borderCssSpec);
... |
if (typeof destination == 'undefined') {
// Moving into the parent directory arrange/
// Error if source is a file
if (source.type() != 'directory') {
move.self.alert('Error', "Files must go in a SIP, not the parent directory.");
}
move.containerPath = arrangeDir+'/'
} els... | {
move.droppedPath+='/'
} | conditional_block |
ingest_file_browser.js | */
var enableElements = function(cssSelectors) {
for (var index in cssSelectors) {
$(cssSelectors[index]).removeAttr('disabled');
}
};
var disableElements = function(cssSelectors) {
for (var index in cssSelectors) {
$(cssSelectors[index]).attr('disabled', 'disabled');
}
};
function setupBacklogBrowse... | 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 Archivematica. If not, see <http://www.gnu.org/licenses/>. | random_line_split | |
raml-snippets.js | 'use strict';
angular.module('raml')
.value('snippets', {
options: ['options:', ' description: <<insert text or markdown here>>'],
head: ['head:', ' description: <<insert text or markdown here>>'],
get: ['get:', ' description: <<insert text or markdown here>>'],
post: ['post:', ' description: <<i... |
return [
key + ':'
];
};
return service;
});
| {
//For text elements that are part of an array
//we do not add an empty line break:
return suggestion.isList ? [key] : [key, ''];
} | conditional_block |
raml-snippets.js | 'use strict';
angular.module('raml')
.value('snippets', {
options: ['options:', ' description: <<insert text or markdown here>>'],
head: ['head:', ' description: <<insert text or markdown here>>'],
get: ['get:', ' description: <<insert text or markdown here>>'],
post: ['post:', ' description: <<i... | }
return [
key + ':'
];
};
return service;
}); | if (metadata.isText) {
//For text elements that are part of an array
//we do not add an empty line break:
return suggestion.isList ? [key] : [key, '']; | random_line_split |
generate.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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 r... |
use common::ui::UI;
use hcore::crypto::SymKey;
use error::Result;
pub fn start(ui: &mut UI, ring: &str, cache: &Path) -> Result<()> {
ui.begin(format!("Generating ring key for {}", &ring))?;
let pair = SymKey::generate_pair_for_ring(ring)?;
pair.to_pair_files(cache)?;
ui.end(format!(
"Generat... | use std::path::Path; | random_line_split |
generate.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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 r... | {
ui.begin(format!("Generating ring key for {}", &ring))?;
let pair = SymKey::generate_pair_for_ring(ring)?;
pair.to_pair_files(cache)?;
ui.end(format!(
"Generated ring key pair {}.",
&pair.name_with_rev()
))?;
Ok(())
} | identifier_body | |
generate.rs | // Copyright (c) 2016 Chef Software Inc. and/or applicable contributors
//
// 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 r... | (ui: &mut UI, ring: &str, cache: &Path) -> Result<()> {
ui.begin(format!("Generating ring key for {}", &ring))?;
let pair = SymKey::generate_pair_for_ring(ring)?;
pair.to_pair_files(cache)?;
ui.end(format!(
"Generated ring key pair {}.",
&pair.name_with_rev()
))?;
Ok(())
}
| start | identifier_name |
game.js | canvas to draw the trajectory on the screen
this.bitmap = this.game.add.bitmapData(this.game.width, this.game.height);
this.bitmap.context.fillStyle = 'rgb(255, 255, 255)';
this.bitmap.context.strokeStyle = 'rgb(255, 255, 255)';
this.game.add.image(0, 0, this.bitmap);
// Simulate a pointer click/t... |
explosion = this.game.add.sprite(0, 0, 'blast');
explosion.anchor.setTo(0.5, 0.5);
// Add an animation for the explosion that kills the sprite when the
// animation is complete
var animation = explosion.animations.add('boom', [0,1,2,3], 60, false);
animation.killOnCompl... | conditional_block | |
game.js | ('shot');
explosionSound = this.game.add.audio('explosion');
enemySound = this.game.add.audio('enemyexplosion');
explosionSound.volume == 0.01;
//Background
this.game.add.tileSprite(0,0,6400,6400,'background');
// Create an object representing our gun
this.gun = this.game.add.sprite(50, th... |
// The update() method is called every frame
GameState.prototype.update = function() {
if (this.game.time.fps !== 0) {
this.debugText.setText(
this.game.time.fps + ' FPS\n' +
'Bullet Shot Speed = ' + this.BULLET_SPEED+'\n'+
'World Gravity = ' + this.GRAVITY+'\n'+
'Ma... | }; | random_line_split |
script_runtime.rs | .rt(), JSGCParamKey::JSGC_SLICE_TIME_BUDGET, val as u32);
}
}
if let Some(val) = PREFS.get("js.mem.gc.compacting.enabled").as_boolean() {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_COMPACTING_ENABLED, val as u32);
}
if let Some(val) = PREFS.get("js.mem.gc.high_frequency_time_limi... | {
use js::jsapi::{JS_DEFAULT_ZEAL_FREQ, JS_SetGCZeal};
let level = match PREFS.get("js.mem.gc.zeal.level").as_i64() {
Some(level @ 0...14) => level as u8,
_ => return,
};
let frequency = match PREFS.get("js.mem.gc.zeal.frequency").as_i64() {
Some(frequency) if frequency >= 0 => ... | identifier_body | |
script_runtime.rs | >;
/// Clone this handle.
fn clone(&self) -> Box<ScriptChan + Send>;
}
#[derive(Clone, Copy, Debug, Eq, Hash, JSTraceable, PartialEq)]
pub enum ScriptThreadEventCategory {
AttachLayout,
ConstellationMsg,
DevtoolsMsg,
DocumentEvent,
DomEvent,
FileRead,
FormPlannedNavigation,
Imag... | fn deref(&self) -> &RustRuntime {
&self.0
}
}
#[allow(unsafe_code)]
pub unsafe fn new_rt_and_cx() -> Runtime {
LiveDOMReferences::initialize();
let runtime = RustRuntime::new().unwrap();
JS_AddExtraGCRootsTracer(runtime.rt(), Some(trace_rust_roots), ptr::null_mut());
// Needed for deb... | type Target = RustRuntime; | random_line_split |
script_runtime.rs | .get("js.mem.high_water_mark").as_i64() {
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MAX_MALLOC_BYTES, val as u32 * 1024 * 1024);
}
if let Some(val) = PREFS.get("js.mem.max").as_i64() {
let max = if val <= 0 || val >= 0x1000 {
-1
} else {
val * 1024 * 1024... | debug_gc_callback | identifier_name | |
script_runtime.rs | /// Clone this handle.
fn clone(&self) -> Box<ScriptChan + Send>;
}
#[derive(Clone, Copy, Debug, Eq, Hash, JSTraceable, PartialEq)]
pub enum ScriptThreadEventCategory {
AttachLayout,
ConstellationMsg,
DevtoolsMsg,
DocumentEvent,
DomEvent,
FileRead,
FormPlannedNavigation,
ImageCa... | ;
let mode = if val {
JSGCMode::JSGC_MODE_INCREMENTAL
} else if compartment {
JSGCMode::JSGC_MODE_COMPARTMENT
} else {
JSGCMode::JSGC_MODE_GLOBAL
};
JS_SetGCParameter(runtime.rt(), JSGCParamKey::JSGC_MODE, mode as u32);
}
if let Some(va... | {
false
} | conditional_block |
test_gpmae.py | # Copyright 2013 Mario Graff Guerrero
# 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 wri... | ():
x = np.linspace(-10, 10, 100)
pol = np.array([0.2, -0.3, 0.2])
X = np.vstack((x**2, x, np.ones(x.shape[0])))
y = (X.T * pol).sum(axis=1)
x = x[:, np.newaxis]
gp = GPMAE.init_cl(verbose=True,
generations=30, seed=0,
max_length=1000).train(x, y)
... | test_gpmae | identifier_name |
test_gpmae.py | # Copyright 2013 Mario Graff Guerrero
# 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 wri... | x = np.linspace(-10, 10, 100)
pol = np.array([0.2, -0.3, 0.2])
X = np.vstack((x**2, x, np.ones(x.shape[0])))
y = (X.T * pol).sum(axis=1)
x = x[:, np.newaxis]
gp = GPMAE.init_cl(verbose=True,
generations=30, seed=0,
max_length=1000).train(x, y)
gp.run... | identifier_body | |
test_gpmae.py | # Copyright 2013 Mario Graff Guerrero
# 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 wri... |
def test_gpmae():
x = np.linspace(-10, 10, 100)
pol = np.array([0.2, -0.3, 0.2])
X = np.vstack((x**2, x, np.ones(x.shape[0])))
y = (X.T * pol).sum(axis=1)
x = x[:, np.newaxis]
gp = GPMAE.init_cl(verbose=True,
generations=30, seed=0,
max_length=1000... | random_line_split | |
views.py | from django.shortcuts import get_object_or_404, Http404, redirect
from django.urls import reverse
from django.views.generic import DetailView, UpdateView
from django.http import HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.http import urlencode
from froide.helper.utils impor... | foirequest = self.message.request
ctx = {
"foirequest": foirequest,
"user": foirequest.user,
"message": self.message,
}
context["post_instructions"] = self.object.get_post_instructions(ctx)
context["message"] = self.message
atts = [a fo... | random_line_split | |
views.py | from django.shortcuts import get_object_or_404, Http404, redirect
from django.urls import reverse
from django.views.generic import DetailView, UpdateView
from django.http import HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.http import urlencode
from froide.helper.utils impor... | (LoginRequiredMixin):
pk_url_kwarg = "letter_id"
form_class = LetterForm
model = LetterTemplate
def handle_no_permission(self):
return render_403(self.request)
def get_queryset(self):
qs = super().get_queryset()
if not self.request.user.is_staff:
qs = qs.filter(... | LetterMixin | identifier_name |
views.py | from django.shortcuts import get_object_or_404, Http404, redirect
from django.urls import reverse
from django.views.generic import DetailView, UpdateView
from django.http import HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.http import urlencode
from froide.helper.utils impor... |
def get_object(self, queryset=None):
obj = super().get_object(queryset=None)
self.message = get_object_or_404(FoiMessage, id=self.kwargs["message_id"])
self.message_user = self.message.request.user
if not can_write_foirequest(self.message.request, self.request):
raise H... | qs = super().get_queryset()
if not self.request.user.is_staff:
qs = qs.filter(active=True)
return qs | identifier_body |
views.py | from django.shortcuts import get_object_or_404, Http404, redirect
from django.urls import reverse
from django.views.generic import DetailView, UpdateView
from django.http import HttpResponse
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.http import urlencode
from froide.helper.utils impor... |
context["description"] = self.object.get_description(
{
"message": self.message,
"foirequest": self.message.request,
}
)
return context
def send_letter(self, form_data):
sender = MessageSender(self.object, self.message, form_d... | context["ready"] = form.is_valid() and not self.request.POST.get("edit")
context["preview_qs"] = urlencode(form.cleaned_data) | conditional_block |
navModel.ts | import { AnyAction, createAction } from '@reduxjs/toolkit';
import { NavIndex, NavModel, NavModelItem } from '@savantly/sprout-api';
import { defaultNavTree } from './defaultNavTree';
//import config from '../../core/config';
export function buildInitialState(): NavIndex {
const navIndex: NavIndex = {};
const roo... | (text: string, subTitle?: string): NavModel {
const node = {
text,
subTitle,
icon: 'exclamation-triangle',
};
return {
breadcrumbs: [node],
node: node,
main: node,
};
}
export const initialState: NavIndex = {};
export const updateNavIndex = createAction<NavModelItem>('navIndex/updateNa... | buildWarningNav | identifier_name |
navModel.ts | import { AnyAction, createAction } from '@reduxjs/toolkit';
import { NavIndex, NavModel, NavModelItem } from '@savantly/sprout-api';
import { defaultNavTree } from './defaultNavTree';
//import config from '../../core/config';
export function buildInitialState(): NavIndex {
const navIndex: NavIndex = {};
const roo... |
}
navIndex['not-found'] = { ...buildWarningNav('Page not found', '404 Error').node };
}
function buildWarningNav(text: string, subTitle?: string): NavModel {
const node = {
text,
subTitle,
icon: 'exclamation-triangle',
};
return {
breadcrumbs: [node],
node: node,
main: node,
};
}
... | {
buildNavIndex(navIndex, node.children, node);
} | conditional_block |
navModel.ts | import { AnyAction, createAction } from '@reduxjs/toolkit';
import { NavIndex, NavModel, NavModelItem } from '@savantly/sprout-api';
import { defaultNavTree } from './defaultNavTree';
//import config from '../../core/config';
export function buildInitialState(): NavIndex {
const navIndex: NavIndex = {};
const roo... | return {
breadcrumbs: [node],
node: node,
main: node,
};
}
export const initialState: NavIndex = {};
export const updateNavIndex = createAction<NavModelItem>('navIndex/updateNavIndex');
// Since the configuration subtitle includes the organization name, we include this action to update the org name if... | text,
subTitle,
icon: 'exclamation-triangle',
}; | random_line_split |
navModel.ts | import { AnyAction, createAction } from '@reduxjs/toolkit';
import { NavIndex, NavModel, NavModelItem } from '@savantly/sprout-api';
import { defaultNavTree } from './defaultNavTree';
//import config from '../../core/config';
export function buildInitialState(): NavIndex {
const navIndex: NavIndex = {};
const roo... |
export const initialState: NavIndex = {};
export const updateNavIndex = createAction<NavModelItem>('navIndex/updateNavIndex');
// Since the configuration subtitle includes the organization name, we include this action to update the org name if it changes.
export const updateConfigurationSubtitle = createAction<strin... | {
const node = {
text,
subTitle,
icon: 'exclamation-triangle',
};
return {
breadcrumbs: [node],
node: node,
main: node,
};
} | identifier_body |
__init__.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 not use ... |
if test_index is not None:
results_dir = os.path.join(results_dir, str(test_index))
return results_dir
TestContext.test_name = property(patched_test_name)
TestContext.results_dir = staticmethod(patched_results_dir)
| results_dir = os.path.join(results_dir, decorate_args(test_context.injected_args_name, True)) | conditional_block |
__init__.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 not use ... |
TestContext.test_name = property(patched_test_name)
TestContext.results_dir = staticmethod(patched_results_dir)
| """
Monkey patch results_dir.
"""
results_dir = test_context.session_context.results_dir
if test_context.cls is not None:
results_dir = os.path.join(results_dir, test_context.cls.__name__)
if test_context.function is not None:
results_dir = os.path.join(results_dir, test_context.fun... | identifier_body |
__init__.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 not use ... | (self):
"""
Monkey patched test_name property function.
"""
name_components = [self.module_name,
self.cls_name,
self.function_name,
self.injected_args_name]
name = ".".join(filter(lambda x: x is not None and len(x) > 0, name_compo... | patched_test_name | identifier_name |
__init__.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 not use ... |
return results_dir
TestContext.test_name = property(patched_test_name)
TestContext.results_dir = staticmethod(patched_results_dir) | results_dir = os.path.join(results_dir, decorate_args(test_context.injected_args_name, True))
if test_index is not None:
results_dir = os.path.join(results_dir, str(test_index)) | random_line_split |
admin.py | from django.contrib import admin
from django.contrib.contenttypes import generic
from models import Attribute, BaseModel
from django.utils.translation import ugettext_lazy as _
class MetaInline(generic.GenericTabularInline):
|
class BaseAdmin(admin.ModelAdmin):
"""
def get_readonly_fields(self, request, obj=None):
fs = super(BaseAdmin, self).get_readonly_fields(request, obj)
fs += ('created_by', 'last_updated_by',)
return fs
def get_fieldsets(self, request, obj=None):
fs = super(BaseAdmin, self)... | model = Attribute
extra = 0 | identifier_body |
admin.py | from django.contrib import admin
from django.contrib.contenttypes import generic
from models import Attribute, BaseModel
from django.utils.translation import ugettext_lazy as _
class MetaInline(generic.GenericTabularInline):
model = Attribute
extra = 0
class BaseAdmin(admin.ModelAdmin):
"""
def get_re... | instance.save() | if isinstance(instance, BaseModel): #Check if it is the correct type of inline
if not instance.created_by_id:
instance.created_by = request.user
instance.last_updated_by = request.user | random_line_split |
admin.py | from django.contrib import admin
from django.contrib.contenttypes import generic
from models import Attribute, BaseModel
from django.utils.translation import ugettext_lazy as _
class MetaInline(generic.GenericTabularInline):
model = Attribute
extra = 0
class BaseAdmin(admin.ModelAdmin):
"""
def get_re... |
obj.last_updated_by = request.user
obj.save()
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
for instance in instances:
if isinstance(instance, BaseModel): #Check if it is the correct type of inline
if no... | obj.created_by = request.user | conditional_block |
admin.py | from django.contrib import admin
from django.contrib.contenttypes import generic
from models import Attribute, BaseModel
from django.utils.translation import ugettext_lazy as _
class | (generic.GenericTabularInline):
model = Attribute
extra = 0
class BaseAdmin(admin.ModelAdmin):
"""
def get_readonly_fields(self, request, obj=None):
fs = super(BaseAdmin, self).get_readonly_fields(request, obj)
fs += ('created_by', 'last_updated_by',)
return fs
def get_fiel... | MetaInline | identifier_name |
nodemailer-mailgun-transport-tests.ts | import mailgunTransport = require('nodemailer-mailgun-transport');
import nodemailer = require('nodemailer');
const opts: mailgunTransport.Options = {
auth: {
api_key: "harry"
}
};
const optsWithDomain: mailgunTransport.Options = {
auth: {
api_key: "harry",
domain: "http://www.foo.... | transport.sendMail(mailOptions, (error: Error, info: nodemailer.SentMessageInfo): void => {
// nothing
}); | random_line_split | |
setup.py | import io
import os
import re
import sys
from setuptools import setup
def restify():
if os.path.isfile('README.md'):
if os.system('pandoc -s README.md -o README.rst') != 0:
print('----------------------------------------------------------')
print('WARNING: pandoc command failed, could not restify R... | 'Development Status :: 5 - Production/Stable',
'Environment :: Other Environment', 'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :... | random_line_split | |
setup.py | import io
import os
import re
import sys
from setuptools import setup
def | ():
if os.path.isfile('README.md'):
if os.system('pandoc -s README.md -o README.rst') != 0:
print('----------------------------------------------------------')
print('WARNING: pandoc command failed, could not restify README.md')
print('----------------------------------------------------------')... | restify | identifier_name |
setup.py | import io
import os
import re
import sys
from setuptools import setup
def restify():
|
setup(
name="localimport",
version="1.7.3",
description="Isolated import of Python Modules",
long_description=restify(),
author="Niklas Rosenstein",
author_email="rosensteinniklas@gmail.com",
url='https://github.com/NiklasRosenstein/localimport',
py_modules=["localimport"],
keywords=["import", "emb... | if os.path.isfile('README.md'):
if os.system('pandoc -s README.md -o README.rst') != 0:
print('----------------------------------------------------------')
print('WARNING: pandoc command failed, could not restify README.md')
print('----------------------------------------------------------')
... | identifier_body |
setup.py | import io
import os
import re
import sys
from setuptools import setup
def restify():
if os.path.isfile('README.md'):
if os.system('pandoc -s README.md -o README.rst') != 0:
|
else:
with io.open('README.rst', encoding='utf8') as fp:
text = fp.read()
# Remove ".. raw:: html\n\n ....\n" stuff, it results from using
# raw HTML in Markdown but can not be properly rendered in PyPI.
text = re.sub('..\s*raw::\s*html\s*\n\s*\n\s+[^\n]+\n', '', text, re.M)
... | print('----------------------------------------------------------')
print('WARNING: pandoc command failed, could not restify README.md')
print('----------------------------------------------------------')
if sys.stdout.isatty():
if sys.version_info[0] >= 3:
input("Enter to continue..... | conditional_block |
cross-borrow-trait.rs | // Copyright 2012-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
// <LICEN... | let x: Box<Trait> = box Foo;
let _y: &Trait = x; //~ ERROR mismatched types: expected `&Trait`, found `Box<Trait>`
} |
pub fn main() { | random_line_split |
cross-borrow-trait.rs | // Copyright 2012-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
// <LICEN... | () {
let x: Box<Trait> = box Foo;
let _y: &Trait = x; //~ ERROR mismatched types: expected `&Trait`, found `Box<Trait>`
}
| main | identifier_name |
cross-borrow-trait.rs | // Copyright 2012-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
// <LICEN... | {
let x: Box<Trait> = box Foo;
let _y: &Trait = x; //~ ERROR mismatched types: expected `&Trait`, found `Box<Trait>`
} | identifier_body | |
io.py | """
* Copyright (C) Caleb Marshall and others... - All Rights Reserved
* Written by Caleb Marshall <anythingtechpro@gmail.com>, May 27th, 2017
* Licensing information can found in 'LICENSE', which is part of this source code package.
"""
import struct
class Endianness(object):
"""
A enum that stores networ... | def read_ushort(self):
return self.read_from('H')[0]
def write_ushort(self, value):
self.write_to('H', value)
def read_int(self):
return self.read_from('i')[0]
def write_int(self, value):
self.write_to('i', value)
def read_uint(self):
return self.read_from... |
def write_short(self, value):
self.write_to('h', value)
| random_line_split |
io.py | """
* Copyright (C) Caleb Marshall and others... - All Rights Reserved
* Written by Caleb Marshall <anythingtechpro@gmail.com>, May 27th, 2017
* Licensing information can found in 'LICENSE', which is part of this source code package.
"""
import struct
class | (object):
"""
A enum that stores network endianess formats
"""
NATIVE = '='
LITTLE_ENDIAN = '<'
BIG_ENDIAN = '>'
NETWORK = '!'
class DataBufferError(IOError):
"""
A data buffer specific io error
"""
class DataBufferIO(object):
"""
A class for manipulating (reading and/... | Endianness | identifier_name |
io.py | """
* Copyright (C) Caleb Marshall and others... - All Rights Reserved
* Written by Caleb Marshall <anythingtechpro@gmail.com>, May 27th, 2017
* Licensing information can found in 'LICENSE', which is part of this source code package.
"""
import struct
class Endianness(object):
"""
A enum that stores networ... |
def read_from(self, fmt):
data = struct.unpack_from(self.byte_order + fmt, self.data, self.offset)
self.offset += struct.calcsize(fmt)
return data
def write_to(self, fmt, *args):
self.write(struct.pack(self.byte_order + fmt, *args))
def read_byte(self):
return sel... | self.data = bytes()
self.offset = 0 | identifier_body |
io.py | """
* Copyright (C) Caleb Marshall and others... - All Rights Reserved
* Written by Caleb Marshall <anythingtechpro@gmail.com>, May 27th, 2017
* Licensing information can found in 'LICENSE', which is part of this source code package.
"""
import struct
class Endianness(object):
"""
A enum that stores networ... |
self.data += data
def clear(self):
self.data = bytes()
self.offset = 0
def read_from(self, fmt):
data = struct.unpack_from(self.byte_order + fmt, self.data, self.offset)
self.offset += struct.calcsize(fmt)
return data
def write_to(self, fmt, *args):
... | return | conditional_block |
qb_zcycode.py | from Control_functions import *
from servoctl import *
#from enum import Enum
from Compass_HMC5883L import Compass
#from pypurss_test import *
'''
class NavState(Enum):
GO_TO_GOAL=0
PRE_WALL_FOLLOW=1
WALL_FOLLOW=2
HALT=3
# AVOID_OBSTACLES=4
'''
class Navigation:
def __init__(self):
self.control_func= ControlFu... |
nav.run()
time.sleep(0.01)
except KeyboardInterrupt:
print 'keyboard interrupt received.. stopping the quickbot'
nav.stop() |
try:
while 1: | random_line_split |
qb_zcycode.py | from Control_functions import *
from servoctl import *
#from enum import Enum
from Compass_HMC5883L import Compass
#from pypurss_test import *
'''
class NavState(Enum):
GO_TO_GOAL=0
PRE_WALL_FOLLOW=1
WALL_FOLLOW=2
HALT=3
# AVOID_OBSTACLES=4
'''
class Navigation:
def __init__(self):
self.control_func= ControlFu... | self.control_func.servo.set_pwm(0.1,30)
time.sleep(0.1)
self.navState='WALL_FOLLOW'
else:
self.navState='GO_TO_GOAL'
return
nav=Navigation()
try:
while 1:
nav.run()
time.sleep(0.01)
except KeyboardInterrupt:
print 'keyboard interrupt received.. stopping the quickbot'
nav.stop... | self.control_func.servo.set_pwm(0,0)
hc_dist=self.control_func.pypruss.get_distances()
ob_detect=self.obstacle_detect(hc_dist)
print 'ob_detect in WALL_FOLLOW', ob_detect
if len(ob_detect)>1:
wf_turn = self.control_func.ao_heading(hc_dist,ob_detect)
time.sleep(1)
self.control_fun... | conditional_block |
qb_zcycode.py | from Control_functions import *
from servoctl import *
#from enum import Enum
from Compass_HMC5883L import Compass
#from pypurss_test import *
'''
class NavState(Enum):
GO_TO_GOAL=0
PRE_WALL_FOLLOW=1
WALL_FOLLOW=2
HALT=3
# AVOID_OBSTACLES=4
'''
class Navigation:
def __init__(self):
|
def go_to_goal(self,angle):
# print 'gtg function start'
currentHeading=self.control_func.compass.get_heading()
print 'currentHeading is', currentHeading
Headingerror=currentHeading-angle
print 'error is', Headingerror
if Headingerror>180:
Headingerror=Headingerror-360
elif Headingerror<-180:
... | self.control_func= ControlFunctions()
self.navState='GO_TO_GOAL'
self.currentHeading=0
self.Headingerror=0
self.goalHeading=270
self.hc_dist=[]
# self.servo=Servo()
# self.compass=Compass()
# self.pypruss = self.control_func.pypruss
self.wf_heading=0 | identifier_body |
qb_zcycode.py | from Control_functions import *
from servoctl import *
#from enum import Enum
from Compass_HMC5883L import Compass
#from pypurss_test import *
'''
class NavState(Enum):
GO_TO_GOAL=0
PRE_WALL_FOLLOW=1
WALL_FOLLOW=2
HALT=3
# AVOID_OBSTACLES=4
'''
class Navigation:
def __init__(self):
self.control_func= ControlFu... | (self):
self.control_func.servo.set_pwm(0,0)
nav.control_func.pypruss.stop_pru()
def run(self):
currentHeading=self.control_func.compass.get_heading()
if self.navState=='GO_TO_GOAL':
hc_dist=self.control_func.pypruss.get_distances()
print 'hc_dists=',hc_dist
ob_detect=self.obstacle_det... | stop | identifier_name |
secure.js | 'use strict';
module.exports = {
port: 443,
db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/myapp4',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.min.css',
],
js: [
'public/lib/angular... | google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'https://localhost:443/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '... | }, | random_line_split |
organise.py | import os
import shutil
from hashlib import md5
from io import StringIO
from PIL import Image
from photonix.photos.models import LibraryPath
from photonix.photos.utils.db import record_photo
from photonix.photos.utils.fs import (determine_destination,
find_new_file_name, mkdir_p)... | (self):
self.file_hash_cache = {}
def get_file_hash(self, fn, hash_type):
if fn in self.file_hash_cache and hash_type in self.file_hash_cache[fn]:
return self.file_hash_cache[fn][hash_type]
return None
def set_file_hash(self, fn, hash_type, hash_val):
if fn not in s... | reset | identifier_name |
organise.py | import os
import shutil
from hashlib import md5
from io import StringIO
from PIL import Image
from photonix.photos.models import LibraryPath
from photonix.photos.utils.db import record_photo
from photonix.photos.utils.fs import (determine_destination,
find_new_file_name, mkdir_p)... | were_duplicates = 0
were_bad = 0
for r, d, f in os.walk(orig):
if SYNOLOGY_THUMBNAILS_DIR_NAME in r:
continue
for fn in sorted(f):
filepath = os.path.join(r, fn)
dest = determine_destination(filepath)
if blacklisted_type(fn):
#... | random_line_split | |
organise.py | import os
import shutil
from hashlib import md5
from io import StringIO
from PIL import Image
from photonix.photos.models import LibraryPath
from photonix.photos.utils.db import record_photo
from photonix.photos.utils.fs import (determine_destination,
find_new_file_name, mkdir_p)... | library_paths = LibraryPath.objects.filter(type='St', backend_type='Lo')
if paths:
library_paths = library_paths.filter(path__in=paths)
for library_path in library_paths:
print(f'Searching path for changes {library_path.path}')
library_path.rescan() | identifier_body | |
organise.py | import os
import shutil
from hashlib import md5
from io import StringIO
from PIL import Image
from photonix.photos.models import LibraryPath
from photonix.photos.utils.db import record_photo
from photonix.photos.utils.fs import (determine_destination,
find_new_file_name, mkdir_p)... |
if orig_hash == dest_hash:
return True
# Try matching on image data (ignoring EXIF)
if os.path.splitext(origpath)[1][1:].lower() in ['jpg', 'jpeg', 'png', ]:
orig_hash = fhc.get_file_hash(origpath, 'image')
if not orig_hash:
orig_hash = md5(Image.open(StringIO(fhc.get_... | dest_hash = md5(fhc.get_file(destpath, 'dest')).hexdigest()
fhc.set_file_hash(destpath, 'file', dest_hash) | conditional_block |
hud.py | ## INFO ########################################################################
## ##
## plastey ##
## ======= ... |
# If deque just become empty
elif not self._still_empty:
# Switch state flag and update display
self._still_empty = True
self._update()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def write(self, message):
# Add new ... | self._messages.pop()
# Update display
self._update() | conditional_block |
hud.py | ## INFO ########################################################################
## ##
## plastey ##
## ======= ... |
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def clear(self):
self._messages = deque()
self._update()
#- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
def update(self):
# If there are any messages left
if len... | messages = iter(self._messages)
try:
self._text_first.text = next(messages)
self._text_other.text = '\n'.join(messages)
except StopIteration:
self._text_first.text = self._text_other.text = ''
# Update timer
self._last_time = self._get_time() | identifier_body |
hud.py | ## INFO ########################################################################
## ##
## plastey ##
## ======= ... | (self, text_first_object,
text_other_object,
time_getter,
interval):
self._text_first = text_first_object
self._text_other = text_other_object
self._get_time = time_getter
self._interval = interval
self.... | __init__ | identifier_name |
hud.py | ## INFO ########################################################################
## ##
## plastey ##
## ======= ... | ## called 'LICENSE'. If not, see <http://www.gnu.org/licenses>. ##
## ##
######################################################################## INFO ##
# Import python modules
from collections import deque
#--------------------... | ## See the GNU General Public License for more details. ##
## ##
## You should have received a copy of the GNU General Public License ##
## along with this program, most likely a file in the root directory, ... | random_line_split |
snakeCase.test.ts | import { result, TestInput } from './assets/result';
import { surround } from './assets/surround';
import snakeCase, { SnakeCaseSettings } from '../snakeCase';
const emptyObj = {};
const surround42 = surround('42', '_');
const phrases: TestInput<SnakeCaseSettings>[] = [
['', ''],
['Multiple spaces in p... |
describe('Passing a config object', () => {
describe.each([
emptyObj,
{ numbers: true },
{ numbers: false }
] as SnakeCaseSettings[])('%s', (conf) => {
it.each(phrases)('"%s"', (input, output) => {
expect(snakeCase(input, conf)).toBe(result(output, conf));
});
});
... | random_line_split | |
main.rs | /// serde_eg
/// Example of serializing a rust struct into various formats
///
///
extern crate bincode;
extern crate serde;
extern crate serde_cbor;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
/// struct to describe some properties of a city
#[derive(Serialize, Deserialize)]
struct City {
nam... | () {
let calabar = City {
name: String::from("Calabar"),
population: 470_000,
latitude: 4.95,
longitude: 8.33,
};
let as_json = serde_json::to_string(&calabar).unwrap();
let as_cbor = serde_cbor::to_vec(&calabar).unwrap();
let as_bincode = bincode::serialize(&calabar... | main | identifier_name |
main.rs | /// serde_eg
/// Example of serializing a rust struct into various formats
///
///
extern crate bincode;
extern crate serde;
extern crate serde_cbor;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
/// struct to describe some properties of a city
#[derive(Serialize, Deserialize)]
struct City {
nam... | }
fn main() {
let calabar = City {
name: String::from("Calabar"),
population: 470_000,
latitude: 4.95,
longitude: 8.33,
};
let as_json = serde_json::to_string(&calabar).unwrap();
let as_cbor = serde_cbor::to_vec(&calabar).unwrap();
let as_bincode = bincode::serializ... | latitude: f64,
longitude: f64, | random_line_split |
api.py | # Copyright © 2019 José Alberto Orejuela García (josealberto4444)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | lf, pagesource):
re_explanation = re.compile("Explanation: </b>(.*?)<p>", flags=re.DOTALL) # Compile regex for extracting explanation.
explanation = re_explanation.search(pagesource).groups()[0] # Extract explanation.
explanation = explanation.replace('/\n', '/') # Fix split URLs along several l... | ap_explanation(se | identifier_name |
api.py | # Copyright © 2019 José Alberto Orejuela García (josealberto4444)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | TO-DO: Check if already downloaded first
# def download_media():
# if self.media_type == 'image':
# link = self.api_response['hdurl']
# r = requests.get(link)
# extension = os.path.splitext(link)[1]
# filename = self.filename + extension
# with open(file... | :
userpage = self.get_userpage()
explanation = self.scrap_explanation(userpage)
except:
explanation = self.api_response['explanation']
self.html = False
else:
self.save_explanation(explanation)
self.h... | conditional_block |
api.py | # Copyright © 2019 José Alberto Orejuela García (josealberto4444)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | def explanation(self):
filename = self.filename + '.html'
if os.path.exists(filename):
with open(filename, 'rt') as f:
self.explanation = f.read()
self.html = True
else:
try:
userpage = self.get_userpage()
exp... | h open(self.filename + '.html', 'wt') as f:
f.write(explanation)
| identifier_body |
api.py | # Copyright © 2019 José Alberto Orejuela García (josealberto4444)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | return r.text
def scrap_explanation(self, pagesource):
re_explanation = re.compile("Explanation: </b>(.*?)<p>", flags=re.DOTALL) # Compile regex for extracting explanation.
explanation = re_explanation.search(pagesource).groups()[0] # Extract explanation.
explanation = explanation.r... | r = requests.get(url, params=payload) | random_line_split |
entries.py | # Copyright 2016 Google Inc.
#
# 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, ... | (self, payload, logger, insert_id=None, timestamp=None,
labels=None, severity=None, http_request=None, resource=None):
super(ProtobufEntry, self).__init__(
payload, logger, insert_id=insert_id, timestamp=timestamp,
labels=labels, severity=severity, http_request=http_requ... | __init__ | identifier_name |
entries.py | # Copyright 2016 Google Inc.
#
# 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, ... |
def parse_message(self, message):
"""Parse payload into a protobuf message.
Mutates the passed-in ``message`` in place.
:type message: Protobuf message
:param message: the message to be logged
"""
# NOTE: This assumes that ``payload`` is already a deserialized
... | super(ProtobufEntry, self).__init__(
payload, logger, insert_id=insert_id, timestamp=timestamp,
labels=labels, severity=severity, http_request=http_request,
resource=resource)
if isinstance(self.payload, any_pb2.Any):
self.payload_pb = self.payload
sel... | identifier_body |
entries.py | # Copyright 2016 Google Inc.
#
# 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, ... | """
_PAYLOAD_KEY = 'jsonPayload'
class ProtobufEntry(_BaseEntry):
"""Entry created with ``protoPayload``.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry
:type payload: str, dict or any_pb2.Any
:param payload: The payload passed as ``textPayload``, ``jsonPayload``... | class StructEntry(_BaseEntry):
"""Entry created with ``jsonPayload``.
See
https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry | random_line_split |
entries.py | # Copyright 2016 Google Inc.
#
# 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, ... |
def parse_message(self, message):
"""Parse payload into a protobuf message.
Mutates the passed-in ``message`` in place.
:type message: Protobuf message
:param message: the message to be logged
"""
# NOTE: This assumes that ``payload`` is already a deserialized
... | self.payload_pb = None | conditional_block |
utils.py | import hashlib
import logging
import requests
from builds.models import Version
from projects.utils import slugify_uniquely
from search.indexes import PageIndex, ProjectIndex, SectionIndex
from betterversion.better import version_windows, BetterVersion
log = logging.getLogger(__name__)
def sync_versions(project, ... |
if to_delete_qs.count():
ret_val = {obj.slug for obj in to_delete_qs}
log.info("(Sync Versions) Deleted Versions: [%s]" % ' '.join(ret_val))
to_delete_qs.delete()
return ret_val
else:
return set()
def index_search_request(version, page_list, commit):
log_msg = ' '.... | to_delete_qs = project.versions.exclude(
identifier__in=current_versions).exclude(
uploaded=True).exclude(
active=True).exclude(
slug='latest') | random_line_split |
utils.py | import hashlib
import logging
import requests
from builds.models import Version
from projects.utils import slugify_uniquely
from search.indexes import PageIndex, ProjectIndex, SectionIndex
from betterversion.better import version_windows, BetterVersion
log = logging.getLogger(__name__)
def | (project, versions, type):
"""
Update the database with the current versions from the repository.
"""
# Bookkeeping for keeping tag/branch identifies correct
verbose_names = [v['verbose_name'] for v in versions]
project.versions.filter(verbose_name__in=verbose_names).update(type=type)
old_v... | sync_versions | identifier_name |
utils.py | import hashlib
import logging
import requests
from builds.models import Version
from projects.utils import slugify_uniquely
from search.indexes import PageIndex, ProjectIndex, SectionIndex
from betterversion.better import version_windows, BetterVersion
log = logging.getLogger(__name__)
def sync_versions(project, ... |
if added:
log.info("(Sync Versions) Added Versions: [%s] " % ' '.join(added))
return added
def delete_versions(project, version_data):
"""
Delete all versions not in the current repo.
"""
current_versions = []
if 'tags' in version_data:
for version in version_data['tags']:... | slug = slugify_uniquely(Version, version['verbose_name'], 'slug', 255, project=project)
Version.objects.create(
project=project,
slug=slug,
type=type,
identifier=version['identifier'],
verbose_name=version['verbose_name'],
... | conditional_block |
utils.py | import hashlib
import logging
import requests
from builds.models import Version
from projects.utils import slugify_uniquely
from search.indexes import PageIndex, ProjectIndex, SectionIndex
from betterversion.better import version_windows, BetterVersion
log = logging.getLogger(__name__)
def sync_versions(project, ... | continue
else:
# Update slug with new identifier
Version.objects.filter(
project=project, verbose_name=version_name
).update(
identifier=version_id,
type=type,
mach... | """
Update the database with the current versions from the repository.
"""
# Bookkeeping for keeping tag/branch identifies correct
verbose_names = [v['verbose_name'] for v in versions]
project.versions.filter(verbose_name__in=verbose_names).update(type=type)
old_versions = {}
old_version_va... | identifier_body |
configParse.py | #
# configparse.py
#
# an example of using the parsing module to be able to process a .INI configuration file
#
# Copyright (c) 2003, Paul McGuire
#
from pyparsing import \
Literal, Word, ZeroOrMore, Group, Dict, Optional, \
printables, ParseException, restOfLine
import pprint
inibnf = ... |
if not inibnf:
# punctuation
lbrack = Literal("[").suppress()
rbrack = Literal("]").suppress()
equals = Literal("=").suppress()
semi = Literal(";")
comment = semi + Optional( restOfLine )
nonrbrack = "".join( [ c for c in p... | global inibnf
| random_line_split |
configParse.py | #
# configparse.py
#
# an example of using the parsing module to be able to process a .INI configuration file
#
# Copyright (c) 2003, Paul McGuire
#
from pyparsing import \
Literal, Word, ZeroOrMore, Group, Dict, Optional, \
printables, ParseException, restOfLine
import pprint
inibnf = ... |
inibnf.ignore( comment )
return inibnf
pp = pprint.PrettyPrinter(2)
def test( strng ):
print strng
try:
iniFile = file(strng)
iniData = "".join( iniFile.readlines() )
bnf = inifile_BNF()
tokens = bnf.parseString( iniData )
... | global inibnf
if not inibnf:
# punctuation
lbrack = Literal("[").suppress()
rbrack = Literal("]").suppress()
equals = Literal("=").suppress()
semi = Literal(";")
comment = semi + Optional( restOfLine )
nonrbrack = "".join(... | identifier_body |
configParse.py | #
# configparse.py
#
# an example of using the parsing module to be able to process a .INI configuration file
#
# Copyright (c) 2003, Paul McGuire
#
from pyparsing import \
Literal, Word, ZeroOrMore, Group, Dict, Optional, \
printables, ParseException, restOfLine
import pprint
inibnf = ... |
return inibnf
pp = pprint.PrettyPrinter(2)
def test( strng ):
print strng
try:
iniFile = file(strng)
iniData = "".join( iniFile.readlines() )
bnf = inifile_BNF()
tokens = bnf.parseString( iniData )
pp.pprint( tokens.asList() )
except ... | lbrack = Literal("[").suppress()
rbrack = Literal("]").suppress()
equals = Literal("=").suppress()
semi = Literal(";")
comment = semi + Optional( restOfLine )
nonrbrack = "".join( [ c for c in printables if c != "]" ] ) + " \t"
nonequals = "".j... | conditional_block |
configParse.py | #
# configparse.py
#
# an example of using the parsing module to be able to process a .INI configuration file
#
# Copyright (c) 2003, Paul McGuire
#
from pyparsing import \
Literal, Word, ZeroOrMore, Group, Dict, Optional, \
printables, ParseException, restOfLine
import pprint
inibnf = ... | ():
global inibnf
if not inibnf:
# punctuation
lbrack = Literal("[").suppress()
rbrack = Literal("]").suppress()
equals = Literal("=").suppress()
semi = Literal(";")
comment = semi + Optional( restOfLine )
nonrbrack =... | inifile_BNF | identifier_name |
intro.js |
import prefix from '../prefix'
import translate from '../translate'
export default {
deck: function (deck) {
deck.intro = deck.queued(intro)
function | (next) {
var cards = deck.cards
cards.forEach(function (card, i) {
card.intro(i, function (i) {
if (i === cards.length - 1) {
next()
}
})
})
}
},
card: function (card) {
var transform = prefix('transform')
var transition = prefix('trans... | intro | identifier_name |
intro.js |
import prefix from '../prefix'
import translate from '../translate'
export default {
deck: function (deck) {
deck.intro = deck.queued(intro)
function intro (next) |
},
card: function (card) {
var transform = prefix('transform')
var transition = prefix('transition')
var transitionDelay = prefix('transition-delay')
var $el = card.$el
card.intro = function (i, cb) {
var delay = i * 10 + 250
var z = i / 4
$el.style[transform] = translate(-... | {
var cards = deck.cards
cards.forEach(function (card, i) {
card.intro(i, function (i) {
if (i === cards.length - 1) {
next()
}
})
})
} | identifier_body |
intro.js |
import prefix from '../prefix'
import translate from '../translate'
export default {
deck: function (deck) {
deck.intro = deck.queued(intro)
function intro (next) {
var cards = deck.cards
cards.forEach(function (card, i) {
card.intro(i, function (i) {
if (i === cards.length -... |
})
})
}
},
card: function (card) {
var transform = prefix('transform')
var transition = prefix('transition')
var transitionDelay = prefix('transition-delay')
var $el = card.$el
card.intro = function (i, cb) {
var delay = i * 10 + 250
var z = i / 4
$el.styl... | {
next()
} | conditional_block |
intro.js | import prefix from '../prefix'
import translate from '../translate'
export default {
deck: function (deck) {
deck.intro = deck.queued(intro)
function intro (next) {
var cards = deck.cards
cards.forEach(function (card, i) {
card.intro(i, function (i) {
if (i === cards.length - ... |
cb && cb(i)
}, 1250 + delay)
}, 500)
}
}
} | $el.style[transition] = '' | random_line_split |
actor.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/. */
/// General actor system infrastructure.
use std::any::{Any, AnyRefExt, AnyMutRefExt};
use std::collections::Hash... | (&self, prefix: &str) -> String {
let suffix = self.next.get();
self.next.set(suffix + 1);
format!("{:s}{:u}", prefix, suffix)
}
/// Add an actor to the registry of known actors that can receive messages.
pub fn register(&mut self, actor: Box<Actor+Send+Sized>) {
self.actors... | new_name | identifier_name |
actor.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/. */
/// General actor system infrastructure.
use std::any::{Any, AnyRefExt, AnyMutRefExt};
use std::collections::Hash... |
/// Create a unique name based on a monotonically increasing suffix
pub fn new_name(&self, prefix: &str) -> String {
let suffix = self.next.get();
self.next.set(suffix + 1);
format!("{:s}{:u}", prefix, suffix)
}
/// Add an actor to the registry of known actors that can receive ... | return key.to_string();
}
}
panic!("couldn't find actor named {:s}", actor)
} | random_line_split |
memory.py | # -*- coding: utf-8 -*-
"""
Retrieve information on system memory (RAM).
"""
import psutil
import orchard.extensions
def free() -> int:
"""
Get the amount of memory available for usage.
:return: The memory in Bytes that can be used.
"""
memory = psutil.virtual_memory()
return m... |
@orchard.extensions.cache.memoize()
def swap_total() -> int:
"""
Get the total amount of swap memory.
:return: The total amount of swap memory in Bytes.
"""
swap = psutil.swap_memory()
return swap.total
def swap_used() -> int:
"""
Get the amount of swap memory used.
... | """
Get the amount of swap memory available for usage.
:return: The amount of swap memory in Bytes that can be used.
"""
swap = psutil.swap_memory()
return swap.free | identifier_body |
memory.py | # -*- coding: utf-8 -*-
"""
Retrieve information on system memory (RAM).
"""
import psutil
import orchard.extensions
def free() -> int:
"""
Get the amount of memory available for usage.
:return: The memory in Bytes that can be used.
"""
memory = psutil.virtual_memory()
return m... | () -> int:
"""
Get the total amount of swap memory.
:return: The total amount of swap memory in Bytes.
"""
swap = psutil.swap_memory()
return swap.total
def swap_used() -> int:
"""
Get the amount of swap memory used.
:return: The amount of swap memory in Bytes tha... | swap_total | identifier_name |
memory.py | # -*- coding: utf-8 -*-
""" | Retrieve information on system memory (RAM).
"""
import psutil
import orchard.extensions
def free() -> int:
"""
Get the amount of memory available for usage.
:return: The memory in Bytes that can be used.
"""
memory = psutil.virtual_memory()
return memory.free
@orchard.extensi... | random_line_split | |
instr_vextracti128.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test] | }
#[test]
fn vextracti128_2() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI128, operand1: Some(IndirectScaledIndexedDisplaced(EAX, EBX, Eight, 1167941305, Some(OperandSize::Xmmword), None)), operand2: Some(Direct(YMM0)), operand3: Some(Literal8(96)), operand4: None, lock: false, rounding_mode: None, merg... | fn vextracti128_1() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI128, operand1: Some(Direct(XMM5)), operand2: Some(Direct(YMM4)), operand3: Some(Literal8(67)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 125, 57, 229, 67], Oper... | random_line_split |
instr_vextracti128.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn vextracti128_1() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI128, operand1: So... | () {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI128, operand1: Some(IndirectDisplaced(RDX, 545176606, Some(OperandSize::Xmmword), None)), operand2: Some(Direct(YMM0)), operand3: Some(Literal8(81)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None ... | vextracti128_4 | identifier_name |
instr_vextracti128.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn vextracti128_1() {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI128, operand1: So... | {
run_test(&Instruction { mnemonic: Mnemonic::VEXTRACTI128, operand1: Some(IndirectDisplaced(RDX, 545176606, Some(OperandSize::Xmmword), None)), operand2: Some(Direct(YMM0)), operand3: Some(Literal8(81)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, ... | identifier_body | |
plot_msg_minus_cosmo.py | Dir)
# check if input data is complete
if in_msg.verbose:
print("*** check input data for ", in_msg.sat_str()) | RGBs = check_input(in_msg, in_msg.sat_str(layout="%(sat)s")+in_msg.sat_nr_str(), in_msg.datetime)
# in_msg.sat_nr might be changed to backup satellite
if in_msg.verbose:
print('*** Create plots for ')
print(' Satellite/Sensor: ' + in_msg.sat_str())
print(' Satellite number: ' + in_m... | random_line_split | |
plot_msg_minus_cosmo.py | Dir)
# check if input data is complete
if in_msg.verbose:
print("*** check input data for ", in_msg.sat_str())
RGBs = check_input(in_msg, in_msg.sat_str(layout="%(sat)s")+in_msg.sat_nr_str(), in_msg.datetime)
# in_msg.sat_nr might be changed to backup satellite
if in_msg.verbose:
print('... |
f1 = open(statisticFile,'a') # mode append
i_rgb=0
for rgb in RGBs:
if rgb in products.MSG_color:
mean_array[i_rgb]=data[rgb.replace("c","")].data.mean()
i_rgb=i_rgb+1
# create string to write
str2write = ... | print("*** write statistics (average values) to "+statisticFile) | conditional_block |
plot_msg_minus_cosmo.py | (in_msg):
# do statistics for the last full hour (minutes=0, seconds=0)
in_msg.datetime = datetime(in_msg.datetime.year, in_msg.datetime.month, in_msg.datetime.day, in_msg.datetime.hour, 0, 0)
area_loaded = choose_area_loaded_msg(in_msg.sat, in_msg.sat_nr, in_msg.datetime)
# define contour writ... | plot_msg_minus_cosmo | identifier_name | |
plot_msg_minus_cosmo.py | print(' Area: ', in_msg.areas)
print(' reader level: ', in_msg.reader_level)
# define satellite data object
#global_data = GeostationaryFactory.create_scene(in_msg.sat, in_msg.sat_nr_str(), "seviri", in_msg.datetime)
global_data = GeostationaryFactory.create_scene(in_msg.sat_st... | in_msg.datetime = datetime(in_msg.datetime.year, in_msg.datetime.month, in_msg.datetime.day, in_msg.datetime.hour, 0, 0)
area_loaded = choose_area_loaded_msg(in_msg.sat, in_msg.sat_nr, in_msg.datetime)
# define contour write for coasts, borders, rivers
cw = ContourWriterAGG(in_msg.mapDir)
# check... | identifier_body | |
tag.rs | // Copyright 2016 Jeremy Letang.
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to ... |
pub fn list_for_user_id(db: &mut PgConnection, list_user_id: &str) -> Result<Vec<Tag>, DieselError> {
use diesel::{LoadDsl, FilterDsl, ExpressionMethods};
use db::schemas::tags::dsl::{tags, user_id};
tags.filter(user_id.eq(list_user_id)).load::<Tag>(db)
}
pub fn delete(db: &mut PgConnection, delete_id: &... | {
use diesel::LoadDsl;
use db::schemas::tags::dsl::tags;
tags.load::<Tag>(db)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.