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 |
|---|---|---|---|---|
nw_threat_2_file_attachment.py | #!/usr/bin/env python
# Copyright (C) 2012 nwmaltego Developer.
# This file is part of nwmaltego - https://github.com/bostonlink/nwmaltego
# See the file 'LICENSE' for copying permission.
# Netwitness Threat to Filename Maltego transform
# Author: David Bressler (@bostonlink)
import sys
import urllib2, urllib, json
f... | # NW REST API Query amd results
risk_name = sys.argv[1]
fields = sys.argv[2].split('#')
date_t = datetime.today()
tdelta = timedelta(days=1)
diff = date_t - tdelta
diff = "'" + diff.strftime('%Y-%b-%d %H:%M:%S') + "'-'" + date_t.strftime('%Y-%b-%d %H:%M:%S') + "'"
for i in fields:
if 'ip' in i:
parse... |
nwmodule.nw_http_auth()
| random_line_split |
buff-manager.ts | import { Singleton, AutoWired, Inject } from 'typescript-ioc';
import { Channel, IBuff } from '../../../shared/interfaces';
import { SubscriptionManager } from './subscription-manager';
import { PlayerManager } from './player-manager';
import { Player } from '../../../shared/models';
@Singleton
@AutoWired
export clas... | (player: Player, buff: IBuff): void {
if(!player.$party) return;
this.subscriptionManager.emitToChannel(Channel.PlayerBuff, {
memberNames: player.$party.members.filter(x => x !== player.name),
buff
});
}
public cureInjury(player: Player): void {
if(!player.$party) return;
this.sub... | shareBuff | identifier_name |
buff-manager.ts | import { Singleton, AutoWired, Inject } from 'typescript-ioc';
import { Channel, IBuff } from '../../../shared/interfaces';
import { SubscriptionManager } from './subscription-manager';
import { PlayerManager } from './player-manager';
import { Player } from '../../../shared/models';
@Singleton
@AutoWired
export clas... | }
if(cure) {
player.cureInjury();
}
});
});
}
public shareBuff(player: Player, buff: IBuff): void {
if(!player.$party) return;
this.subscriptionManager.emitToChannel(Channel.PlayerBuff, {
memberNames: player.$party.members.filter(x => x !== player.name),
... | const player = this.playerManager.getPlayer(memberName);
if(!player) return;
if(buff) {
player.addBuff(buff); | random_line_split |
index.js | // Generated by CoffeeScript 1.8.0
var ConnectApp, connect, es, fs, http, https, liveReload, lr, opt, path, server, tiny_lr, util;
path = require("path");
es = require("event-stream");
util = require("gulp-util");
http = require("http");
https = require("https");
fs = require("fs");
connect = require("connect");... | else {
server = http.createServer(app);
}
app.use(connect.directory(typeof opt.root === "object" ? opt.root[0] : opt.root));
return server.listen(opt.port, (function(_this) {
return function(err) {
var sockets, stopServer, stoped;
if (err) {
return _this.log("Error on ... | {
server = https.createServer({
key: opt.https.key || fs.readFileSync(__dirname + '/certs/server.key'),
cert: opt.https.cert || fs.readFileSync(__dirname + '/certs/server.crt'),
ca: opt.https.ca || fs.readFileSync(__dirname + '/certs/ca.crt'),
passphrase: opt.https.passphrase || 'g... | conditional_block |
index.js | // Generated by CoffeeScript 1.8.0
var ConnectApp, connect, es, fs, http, https, liveReload, lr, opt, path, server, tiny_lr, util;
path = require("path");
es = require("event-stream");
util = require("gulp-util");
http = require("http");
https = require("https");
fs = require("fs");
connect = require("connect");... | })(this));
};
ConnectApp.prototype.middleware = function() {
var middleware;
middleware = opt.middleware ? opt.middleware.call(this, connect, opt) : [];
if (opt.livereload) {
if (typeof opt.livereload === "boolean") {
opt.livereload = {};
}
if (!opt.livereload.port) {
... | return _this.log("LiveReload started on port " + opt.livereload.port);
}
}
}; | random_line_split |
index.js | // Generated by CoffeeScript 1.8.0
var ConnectApp, connect, es, fs, http, https, liveReload, lr, opt, path, server, tiny_lr, util;
path = require("path");
es = require("event-stream");
util = require("gulp-util");
http = require("http");
https = require("https");
fs = require("fs");
connect = require("connect");... |
ConnectApp.prototype.server = function() {
var app;
app = connect();
this.middleware().forEach(function(middleware) {
return app.use(middleware);
});
if (opt.https != null) {
server = https.createServer({
key: opt.https.key || fs.readFileSync(__dirname + '/certs/server.key'),... | {
opt = options;
opt.port = opt.port || "8080";
opt.root = opt.root || path.dirname(module.parent.id);
opt.host = opt.host || "localhost";
if (opt.open) {
this.oldMethod("open");
}
this.server();
} | identifier_body |
index.js | // Generated by CoffeeScript 1.8.0
var ConnectApp, connect, es, fs, http, https, liveReload, lr, opt, path, server, tiny_lr, util;
path = require("path");
es = require("event-stream");
util = require("gulp-util");
http = require("http");
https = require("https");
fs = require("fs");
connect = require("connect");... | (options) {
opt = options;
opt.port = opt.port || "8080";
opt.root = opt.root || path.dirname(module.parent.id);
opt.host = opt.host || "localhost";
if (opt.open) {
this.oldMethod("open");
}
this.server();
}
ConnectApp.prototype.server = function() {
var app;
app = connect... | ConnectApp | identifier_name |
word.rs | use std::fmt;
use std::ops::Index;
//---
#[derive(Debug)]
pub struct Word {
pub raw: String // TODO keep it only visible inside the crate
}
impl Word {
pub fn new(s: &'static str) -> Word {
Word { raw: s.to_string() }
}
}
impl fmt::Display for Word {
fn fmt(&self, f: &mut fmt::Formatter) -> ... | }
} | random_line_split | |
word.rs |
use std::fmt;
use std::ops::Index;
//---
#[derive(Debug)]
pub struct Word {
pub raw: String // TODO keep it only visible inside the crate
}
impl Word {
pub fn | (s: &'static str) -> Word {
Word { raw: s.to_string() }
}
}
impl fmt::Display for Word {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.raw)
}
}
//---
#[derive(Debug)]
pub struct Bucket {
pub words: Vec<Word> // TODO keep it only visible inside the crate
... | new | identifier_name |
home.ts | import { Component, ChangeDetectionStrategy } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Store } from "@ngrx/store";
import { Observable } from "rxjs/Observable";
import { AppState } from '../../services/app-state';
| selector: 'page-home',
templateUrl: 'home.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class HomePage {
counter: Observable<number>;
constructor(public navCtrl: NavController, private store: Store<AppState>) {
}
ionViewDidLoad() {
this.counter = this.store.select('counter');... | @Component({ | random_line_split |
home.ts | import { Component, ChangeDetectionStrategy } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Store } from "@ngrx/store";
import { Observable } from "rxjs/Observable";
import { AppState } from '../../services/app-state';
@Component({
selector: 'page-home',
templateUrl: 'home.html',... | (){
setTimeout(() => {
this.store.dispatch({type: 'DECREMENT'});
}, 1000);
}
}
| decrementAsync | identifier_name |
home.ts | import { Component, ChangeDetectionStrategy } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Store } from "@ngrx/store";
import { Observable } from "rxjs/Observable";
import { AppState } from '../../services/app-state';
@Component({
selector: 'page-home',
templateUrl: 'home.html',... |
decrement(){
this.store.dispatch({type: 'DECREMENT'});
}
incrementAsync(){
setTimeout(() => {
this.store.dispatch({type: 'INCREMENT'});
}, 1000);
}
decrementAsync(){
setTimeout(() => {
this.store.dispatch({type: 'DECREMENT'});
}, 10... | {
this.store.dispatch({type: 'INCREMENT'});
} | identifier_body |
logcat.js | /*
* Guerilla
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the MIT License.
*
* Retrieves the Logcat from an Android device.
*/
var path = require('path');
var fs = require('fs-extra');
function Logcat (context, exec) |
Logcat.prototype.start = function (callback) {
var self = this;
var cmd = 'adb';
var args = [];
args.push('-s');
args.push(self.context.device.identifier);
args.push('logcat');
args.push('-v');
args.push('time');
var options = { log: [true, false, false, false], file: this.file };
self.process = self.ex... | {
this.context = context;
this.exec = exec;
this.file = path.join(context.output_dir, 'logcat.txt');
} | identifier_body |
logcat.js | /*
* Guerilla
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the MIT License.
*
* Retrieves the Logcat from an Android device.
*/
var path = require('path');
var fs = require('fs-extra');
function Logcat (context, exec) {
this.context = context;
this.exec = exec;
this.file = path.join(context.outpu... | module.exports = Logcat; | random_line_split | |
logcat.js | /*
* Guerilla
* Copyright 2015, Yahoo Inc.
* Copyrights licensed under the MIT License.
*
* Retrieves the Logcat from an Android device.
*/
var path = require('path');
var fs = require('fs-extra');
function | (context, exec) {
this.context = context;
this.exec = exec;
this.file = path.join(context.output_dir, 'logcat.txt');
}
Logcat.prototype.start = function (callback) {
var self = this;
var cmd = 'adb';
var args = [];
args.push('-s');
args.push(self.context.device.identifier);
args.push('logcat');
args.push(... | Logcat | identifier_name |
views.py | from media_tree.contrib.cms_plugins.media_tree_image.models import MediaTreeImage
from media_tree.contrib.cms_plugins.helpers import PluginLink
from media_tree.models import FileNode
from media_tree.contrib.views.detail.image import ImageNodeDetailView
from django.utils.translation import ugettext_lazy as _
from cms.ut... |
def get(self, request, *args, **kwargs):
self.return_url = request.GET.get('return_url', None)
return super(ImagePluginDetailView, self).get(request, *args, **kwargs) | context_data = super(ImagePluginDetailView, self).get_context_data(
*args, **kwargs)
if self.return_url:
page = get_page_from_path(self.return_url.strip('/'))
if page:
context_data.update({
'link': PluginLink(url=page.get_absolute_url(),
... | identifier_body |
views.py | from media_tree.contrib.cms_plugins.media_tree_image.models import MediaTreeImage
from media_tree.contrib.cms_plugins.helpers import PluginLink
from media_tree.models import FileNode
from media_tree.contrib.views.detail.image import ImageNodeDetailView
from django.utils.translation import ugettext_lazy as _
from cms.ut... |
if not allowed:
raise Http404
return obj
def get_context_data(self, *args, **kwargs):
context_data = super(ImagePluginDetailView, self).get_context_data(
*args, **kwargs)
if self.return_url:
page = get_page_from_path(self.return_url.stri... | page = get_page_from_path(plugin.page.get_path())
if page:
allowed = True
break | conditional_block |
views.py | from media_tree.contrib.cms_plugins.media_tree_image.models import MediaTreeImage
from media_tree.contrib.cms_plugins.helpers import PluginLink
from media_tree.models import FileNode
from media_tree.contrib.views.detail.image import ImageNodeDetailView
from django.utils.translation import ugettext_lazy as _
from cms.ut... | (self, request, *args, **kwargs):
self.return_url = request.GET.get('return_url', None)
return super(ImagePluginDetailView, self).get(request, *args, **kwargs) | get | identifier_name |
views.py | from media_tree.contrib.cms_plugins.media_tree_image.models import MediaTreeImage | from cms.utils.page_resolver import get_page_from_path
from django.http import Http404
class ImagePluginDetailView(ImageNodeDetailView):
return_url = None
def get_object(self, *args, **kwargs):
obj = super(ImagePluginDetailView, self).get_object(*args, **kwargs)
if obj:
allowed =... | from media_tree.contrib.cms_plugins.helpers import PluginLink
from media_tree.models import FileNode
from media_tree.contrib.views.detail.image import ImageNodeDetailView
from django.utils.translation import ugettext_lazy as _ | random_line_split |
Solution.py | class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
l, r = 0, len(height) - 1
s = 0
while l < r:
s = max(s, self.get_s(l, r, height))
if height[l] < height[r]:
l += 1
else:
... | assert Solution().maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49
assert Solution().maxArea([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 25 | conditional_block | |
Solution.py | class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
l, r = 0, len(height) - 1 | s = max(s, self.get_s(l, r, height))
if height[l] < height[r]:
l += 1
else:
r -= 1
return s
def get_s(self, i, j, height):
return (j - i) * min(height[i], height[j])
if __name__ == '__main__':
assert Solution().maxArea([1, 8... | s = 0
while l < r: | random_line_split |
Solution.py | class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
l, r = 0, len(height) - 1
s = 0
while l < r:
s = max(s, self.get_s(l, r, height))
if height[l] < height[r]:
l += 1
else:
... | (self, i, j, height):
return (j - i) * min(height[i], height[j])
if __name__ == '__main__':
assert Solution().maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49
assert Solution().maxArea([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 25
| get_s | identifier_name |
Solution.py | class Solution:
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
l, r = 0, len(height) - 1
s = 0
while l < r:
s = max(s, self.get_s(l, r, height))
if height[l] < height[r]:
l += 1
else:
... |
if __name__ == '__main__':
assert Solution().maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49
assert Solution().maxArea([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == 25
| return (j - i) * min(height[i], height[j]) | identifier_body |
procesoxml.py | __author__ = 'fer'
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from core.tableObjects import Table, Column
class Xml:
archivo = None
def __init__(self, ruta=None):
self.archivo = ruta
def get_doc(self) -> ElementTree:
... |
tb = Table()
tb.table_name = xmltabla.attrib['name']
for xmlcolumna in list(xmltabla):
assert isinstance(xmlcolumna, Element)
col = Column()
col.colname = xmlcolumna.attrib['name']
col.type = xmlcolumna.attrib['type'... | del tb | conditional_block |
procesoxml.py | __author__ = 'fer'
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from core.tableObjects import Table, Column
class Xml:
archivo = None
def __init__(self, ruta=None):
self.archivo = ruta
def get_doc(self) -> ElementTree:
... |
print('')
print('\r\n')
| '''
Imprime por pantalla la estructura de la base
de datos detectada
'''
doc = self.get_doc()
for tabla in doc._root:
#decimos a python que es un elemento
assert isinstance(tabla, Element)
print('Tabla: ' + tabla.attrib['name'])
... | identifier_body |
procesoxml.py | __author__ = 'fer'
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from core.tableObjects import Table, Column
class Xml:
archivo = None
def __init__(self, ruta=None):
self.archivo = ruta
def get_doc(self) -> ElementTree:
... |
def print_table_structure(self):
'''
Imprime por pantalla la estructura de la base
de datos detectada
'''
doc = self.get_doc()
for tabla in doc._root:
#decimos a python que es un elemento
assert isinstance(tabla, Element)
... | print(objeto.__str__())
'''
return tablas | random_line_split |
procesoxml.py | __author__ = 'fer'
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from core.tableObjects import Table, Column
class Xml:
archivo = None
def | (self, ruta=None):
self.archivo = ruta
def get_doc(self) -> ElementTree:
doc = ElementTree.parse(self.archivo)
return doc
def mapper_xml_to_objects(self):
doc = self.get_doc()
tablas = dict()
tb = None
for xmltabla in doc._root:
#decimos a... | __init__ | identifier_name |
latedays.js | function calculateLateDays(inputDate){
let select_menu = document.getElementById("g_id");
if(select_menu.selectedIndex === 0) |
var due_date_value = select_menu.options[select_menu.selectedIndex].getAttribute("data-due-date");
var new_due_date = new Date(inputDate);
var old_due_date = new Date(due_date_value);
var delta = (new_due_date.getTime() - old_due_date.getTime()) / (1000*60*60*24);
if (delta < 0) {
delta = 0... | {
alert("Please select a gradeable first!");
return;
} | conditional_block |
latedays.js | function calculateLateDays(inputDate){
let select_menu = document.getElementById("g_id");
if(select_menu.selectedIndex === 0){
alert("Please select a gradeable first!");
return;
}
var due_date_value = select_menu.options[select_menu.selectedIndex].getAttribute("data-due-date");
var n... | (user_id, datestamp) {
// Convert 'MM/DD/YYYY HH:MM:SS A' to 'MM/DD/YYYY'
//datestamp_mmddyy = datestamp.split(" ")[0];
var url = buildCourseUrl(['late_days', 'delete']);
var confirm = window.confirm("Are you sure you would like to delete this entry?");
if (confirm) {
$.ajax({
ur... | deleteLateDays | identifier_name |
latedays.js | function calculateLateDays(inputDate){
let select_menu = document.getElementById("g_id");
if(select_menu.selectedIndex === 0){
alert("Please select a gradeable first!");
return;
}
var due_date_value = select_menu.options[select_menu.selectedIndex].getAttribute("data-due-date");
var n... | if (confirm) {
$.ajax({
url: url,
type: "POST",
data: {
csrf_token: csrfToken,
user_id: user_id,
datestamp: datestamp
},
success: function() {
window.location.reload();
},
... | // Convert 'MM/DD/YYYY HH:MM:SS A' to 'MM/DD/YYYY'
//datestamp_mmddyy = datestamp.split(" ")[0];
var url = buildCourseUrl(['late_days', 'delete']);
var confirm = window.confirm("Are you sure you would like to delete this entry?"); | random_line_split |
latedays.js | function calculateLateDays(inputDate) |
$(document).ready(function() {
flatpickr("#late-calendar", {
plugins: [ShortcutButtonsPlugin(
{
button: [
{
label: "Now"
},
{
label: "End of t... | {
let select_menu = document.getElementById("g_id");
if(select_menu.selectedIndex === 0){
alert("Please select a gradeable first!");
return;
}
var due_date_value = select_menu.options[select_menu.selectedIndex].getAttribute("data-due-date");
var new_due_date = new Date(inputDate);
... | identifier_body |
copy-package-with-dependencies.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import fs from 'fs-extra';
import path from 'path';
import ignore from 'ignore';
const DEFAULT_BUILD_IGNORES = [
... |
const ignores = await fs
.readFile(path.join(packageDir, '.buildignore'), 'utf-8')
.then((l) => l.split('\n'))
.catch((_e) => [])
.then((l: Array<string>) => ignore().add(DEFAULT_BUILD_IGNORES.concat(l)));
await fs.copy(packageDir, targetDir, {
dereference: true,
recursive: true,
filter... | {
packageDir = await fs.readlink(packageDir);
} | conditional_block |
copy-package-with-dependencies.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import fs from 'fs-extra';
import path from 'path';
import ignore from 'ignore';
const DEFAULT_BUILD_IGNORES = [
... | {
packageDir = path.dirname(packageDir);
while (
path.basename(packageDir) === 'node_modules' ||
path.basename(packageDir).startsWith('@')
) {
packageDir = path.dirname(packageDir);
}
return packageDir;
} | identifier_body | |
copy-package-with-dependencies.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import fs from 'fs-extra';
import path from 'path';
import ignore from 'ignore';
const DEFAULT_BUILD_IGNORES = [
... | ) {
packageDir = path.dirname(packageDir);
}
return packageDir;
} | packageDir = path.dirname(packageDir);
while (
path.basename(packageDir) === 'node_modules' ||
path.basename(packageDir).startsWith('@') | random_line_split |
copy-package-with-dependencies.tsx | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
import fs from 'fs-extra';
import path from 'path';
import ignore from 'ignore';
const DEFAULT_BUILD_IGNORES = [
... | (
packageDir: string,
targetDir: string,
) {
await fs.remove(targetDir);
await copyPackageWithDependenciesRecursive(packageDir, targetDir, targetDir);
}
async function copyPackageWithDependenciesRecursive(
packageDir: string,
targetDir: string,
rootTargetDir: string,
) {
if (await fs.pathExists(targetD... | copyPackageWithDependencies | identifier_name |
settings.py | # Notice:
# If you are running this in production environment, generate
# these for your app at https://dev.twitter.com/apps/new
TWITTER = {
'AUTH': {
'consumer_key': 'XXXX',
'consumer_secret': 'XXXX',
'token': 'XXXX',
'token_secret': 'XXXX',
}
}
# We're pulling data from grap... | 'stats_counts.status.balanced-api.2xx',
'stats_counts.status.balanced-api.3xx',
'stats_counts.status.balanced-api.4xx',
],
'ERROR_TARGETS': [
'stats_counts.status.balanced-api.5xx',
'stats_counts.status.balanced-... | ]
},
'API': {
'OK_TARGETS': [ | random_line_split |
pages.py | from django.conf import settings
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login, logout
from django.core.context_processors import csrf
from skilltreeapp.forms import LoginForm
from django.shortcuts import render_to_response... | """
logout(request)
return HttpResponseRedirect('/') | random_line_split | |
pages.py | from django.conf import settings
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login, logout
from django.core.context_processors import csrf
from skilltreeapp.forms import LoginForm
from django.shortcuts import render_to_response... | (request):
params = {}
return render_to_response('pages/basic.html', params, context_instance=RequestContext(request))
def hybrid(request):
params = {}
return render_to_response('pages/hybrid.html', params, context_instance=RequestContext(request))
def tools_login(request):
""" Login a user. Calle... | basic | identifier_name |
pages.py | from django.conf import settings
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login, logout
from django.core.context_processors import csrf
from skilltreeapp.forms import LoginForm
from django.shortcuts import render_to_response... |
else:
form = LoginForm()
return render_to_response('pages/login.html', locals(), context_instance=RequestContext(request))
def tools_logout(request):
""" Manually log a user out.
"""
logout(request)
return HttpResponseRedirect('/')
| form = LoginForm(request.POST)
if form.is_valid():
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(r... | conditional_block |
pages.py | from django.conf import settings
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.auth import authenticate, login, logout
from django.core.context_processors import csrf
from skilltreeapp.forms import LoginForm
from django.shortcuts import render_to_response... | return HttpResponseRedirect('/')
else:
form = LoginForm()
return render_to_response('pages/login.html', locals(), context_instance=RequestContext(request))
def tools_logout(request):
""" Manually log a user out.
"""
logout(request)
return HttpResponseRedirect('/')
| """ Login a user. Called by @login_required decorator.
"""
c = {}
c.update(csrf(request))
if request.user.is_authenticated():
try:
return HttpResponseRedirect(request.GET['next'])
except:
return HttpResponseRedirect('/')
elif request.method == 'POST':
... | identifier_body |
performanceobserverentrylist.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::PerformanceObserverEntryListBinding;
us... |
}
| {
self.entries.borrow().get_entries_by_name_and_type(Some(name), entry_type)
} | identifier_body |
performanceobserverentrylist.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::PerformanceObserverEntryListBinding;
us... | (global: &GlobalScope, entries: PerformanceEntryList)
-> DomRoot<PerformanceObserverEntryList> {
let observer_entry_list = PerformanceObserverEntryList::new_inherited(entries);
reflect_dom_object(box observer_entry_list, global, PerformanceObserverEntryListBinding::Wrap)
}
}
impl Performanc... | new | identifier_name |
performanceobserverentrylist.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::PerformanceObserverEntryListBinding;
us... | }
#[allow(unrooted_must_root)]
pub fn new(global: &GlobalScope, entries: PerformanceEntryList)
-> DomRoot<PerformanceObserverEntryList> {
let observer_entry_list = PerformanceObserverEntryList::new_inherited(entries);
reflect_dom_object(box observer_entry_list, global, PerformanceOb... | fn new_inherited(entries: PerformanceEntryList) -> PerformanceObserverEntryList {
PerformanceObserverEntryList {
reflector_: Reflector::new(),
entries: DomRefCell::new(entries),
} | random_line_split |
navtreedata.js | var NAVTREE =
[
[ "MLX90621", "index.html", [
[ "MLX90621-Lite", "md__e_1__dropbox__projects__m_l_x90621-_lite__r_e_a_d_m_e.html", null ],
[ "Classes", "annotated.html", [
[ "Class List", "annotated.html", "annotated_dup" ],
[ "Class Index", "classes.html", null ],
[ "Class Members", "functi... | ] ]
];
var NAVTREEINDEX =
[
"_m_l_x90621_8cpp.html"
];
var SYNCONMSG = 'click to disable panel synchronisation';
var SYNCOFFMSG = 'click to enable panel synchronisation'; | ] ]
] ] | random_line_split |
config.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
if sys.version_info < (3,):
import ConfigParser
else:
import configparser as ConfigParser
class Config:
def | (self):
self.interval = 30
self.access_key_id = None
self.access_key_secret = None
self.domain_name = None
self.sub_domain_name = None
self.record_type = "A"
self.region_id = "cn-hangzhou"
self.configParser = ConfigParser.ConfigParser()
def loadConfi... | __init__ | identifier_name |
config.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
if sys.version_info < (3,):
import ConfigParser
else:
import configparser as ConfigParser
class Config:
def __init__(self):
self.interval = 30
self.access_key_id = None
self.access_key_secret = None
self.domain_name = N... |
if not self.record_type:
self.record_type = "A"
if not self.region_id:
self.region_id = "cn-hangzhou"
except Exception, e:
print "invalid config: {0}".format(e.message)
return False
if not self.access_key_id or not self.ac... | self.interval = 30 | conditional_block |
config.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
if sys.version_info < (3,):
import ConfigParser
else:
import configparser as ConfigParser
class Config:
| self.sub_domain_name = self.configParser.get("CONFIG", "sub_domain_name")
self.record_type = self.configParser.get("CONFIG", "record_type")
self.region_id = self.configParser.get("CONFIG", "region_id")
if not self.interval:
self.interval = 30
i... | def __init__(self):
self.interval = 30
self.access_key_id = None
self.access_key_secret = None
self.domain_name = None
self.sub_domain_name = None
self.record_type = "A"
self.region_id = "cn-hangzhou"
self.configParser = ConfigParser.ConfigParser()
d... | identifier_body |
config.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
if sys.version_info < (3,):
import ConfigParser
else:
import configparser as ConfigParser
class Config:
def __init__(self):
self.interval = 30
self.access_key_id = None
self.access_key_secret = None
self.domain_name = N... | self.record_type = self.configParser.get("CONFIG", "record_type")
self.region_id = self.configParser.get("CONFIG", "region_id")
if not self.interval:
self.interval = 30
if not self.record_type:
self.record_type = "A"
if not self... | random_line_split | |
fixed.rs | // Copyright 2013-2017, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib_ffi;
use glib::translate::*;
use Fixed;
use IsA;
use Value;
use Widget;
/... | <T: IsA<Widget>>(&self, item: &T) -> i32 {
assert!(has_widget(self, item), "this item isn't in the Fixed's widget list");
let mut value = Value::from(&0);
unsafe {
ffi::gtk_container_child_get_property(self.to_glib_none().0 as *mut _, item.as_ref().to_glib_none().0, "y".to_glib_none(... | get_child_y | identifier_name |
fixed.rs | // Copyright 2013-2017, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib_ffi;
use glib::translate::*;
use Fixed;
use IsA;
use Value;
use Widget;
/... | impl<O: IsA<Fixed>> FixedExtManual for O {
fn get_child_x<T: IsA<Widget>>(&self, item: &T) -> i32 {
assert!(has_widget(self, item), "this item isn't in the Fixed's widget list");
let mut value = Value::from(&0);
unsafe {
ffi::gtk_container_child_get_property(self.to_glib_none().0... | fn get_child_y<T: IsA<Widget>>(&self, item: &T) -> i32;
fn set_child_y<T: IsA<Widget>>(&self, item: &T, y: i32);
}
| random_line_split |
fixed.rs | // Copyright 2013-2017, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use ffi;
use glib_ffi;
use glib::translate::*;
use Fixed;
use IsA;
use Value;
use Widget;
/... |
fn set_child_x<T: IsA<Widget>>(&self, item: &T, x: i32) {
assert!(has_widget(self, item), "this item isn't in the Fixed's widget list");
unsafe {
ffi::gtk_container_child_set_property(self.to_glib_none().0 as *mut _, item.as_ref().to_glib_none().0, "x".to_glib_none().0, Value::from(&x)... | {
assert!(has_widget(self, item), "this item isn't in the Fixed's widget list");
let mut value = Value::from(&0);
unsafe {
ffi::gtk_container_child_get_property(self.to_glib_none().0 as *mut _, item.as_ref().to_glib_none().0, "x".to_glib_none().0, value.to_glib_none_mut().0);
... | identifier_body |
log.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... |
}
match CString::new(safe) {
Ok(cstr) => cstr,
_ => {
CString::new("<failed to encode string>").unwrap()
}
}
}
| {
safe.push(*c);
} | conditional_block |
log.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | return (c.SCLogMessage)(
level as i32,
to_safe_cstring(filename).as_ptr(),
line,
to_safe_cstring(function).as_ptr(),
code,
to_safe_cstring(message).as_ptr());
}
}
// Fall back if the Suricata C c... | random_line_split | |
log.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | {
let mut safe = Vec::with_capacity(val.len());
for c in val.as_bytes() {
if *c != 0 {
safe.push(*c);
}
}
match CString::new(safe) {
Ok(cstr) => cstr,
_ => {
CString::new("<failed to encode string>").unwrap()
}
}
} | identifier_body | |
log.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARR... | (val: &str) -> CString {
let mut safe = Vec::with_capacity(val.len());
for c in val.as_bytes() {
if *c != 0 {
safe.push(*c);
}
}
match CString::new(safe) {
Ok(cstr) => cstr,
_ => {
CString::new("<failed to encode string>").unwrap()
}
}
... | to_safe_cstring | identifier_name |
mdi.py | cstat.axis_mask
self.axes = []
self.polar = 0
axisnames = ['X', 'Y', 'Z', 'A', 'B', 'C', 'U', 'V', 'W']
for i in range(9):
if am & (1<<i):
self.axes.append(axisnames[i])
self.gcode = 'M2'
self.codes = {
'M3' : [_('Spindle CW'), 'S'... | t = self.get_text()
if t.find(".") == -1:
self.set_text(t + ".") | identifier_body | |
mdi.py | {
'M3' : [_('Spindle CW'), 'S'],
'M4' : [_('Spindle CCW'), 'S'],
'M6' : [_('Tool change'), 'T'],
'M61' : [_('Set tool number'), 'Q'],
'M66' : [_('Input control'), 'P', 'E', 'L', 'Q'],
# 'A' means 'the axes'
'G0' : [_('Straight rapid')... | keypad | identifier_name | |
mdi.py | 383, 384, 385, 400, 410,
# 411, 420, 421, 430, 431, 490, 530, 540, 550, 560,
# 570, 580, 590, 591, 592, 593, 610, 611, 640, 730,
# 760, 800, 810, 820, 830, 840, 850, 860, 870, 880,
# 890, 900, 901, 910, 911, 920, 921, 922, 923, 930,
# 940, 950,... |
self.gcode = 'M2'
self.codes = {
'M3' : [_('Spindle CW'), 'S'],
'M4' : [_('Spindle CCW'), 'S'],
'M6' : [_('Tool change'), 'T'],
'M61' : [_('Set tool number'), 'Q'],
'M66' : [_('Input control'), 'P', 'E', 'L', 'Q'],
# 'A' means '... | if am & (1<<i):
self.axes.append(axisnames[i]) | conditional_block |
mdi.py | , 383, 384, 385, 400, 410,
# 411, 420, 421, 430, 431, 490, 530, 540, 550, 560,
# 570, 580, 590, 591, 592, 593, 610, 611, 640, 730,
# 760, 800, 810, 820, 830, 840, 850, 860, 870, 880,
# 890, 900, 901, 910, 911, 920, 921, 922, 923, 930,
# 940, 950... |
self.mdi = mdi(emc)
for i in range(self.numlabels):
self.not_editing(i)
self.editing(self.selected)
self.set_text("G")
def not_editing(self, n):
e = self.eventboxes[n]
e.modify_bg(self.gtk.STATE_NORMAL, self.gtk.gdk.color_par... | self.numwords = 1
self.selected = 0
self.gtk = gtk | random_line_split |
user.js | try { require('mongoose').connect(process.env.MONGODB_URI); } catch (e) {}
const model = require('mongoose').model('User', { object: Object });
model._find = (args, exec) => {
args.skip = args.skip - 0;
args.limit = args.limit - 0;
const _id = args._id || false;
const sort = args.sort || {};
c... |
};
module.exports = model;
| {
model.find(where).
select(select).
limit(limit).
skip(skip).
sort(sort).
exec(exec);
} | conditional_block |
user.js | try { require('mongoose').connect(process.env.MONGODB_URI); } catch (e) {}
const model = require('mongoose').model('User', { object: Object });
model._find = (args, exec) => {
args.skip = args.skip - 0;
args.limit = args.limit - 0;
const _id = args._id || false; | const limit = args.limit > 0 && args.limit < 24 ? args.limit : 24;
const skip = args.skip > 0 ? args.skip : 0;
const select = args.select || {};
if (_id) {
model.findById(_id, exec);
} else {
model.find(where).
select(select).
limit(limit).
skip(skip).
sort(sort).
exec(exec);... | const sort = args.sort || {};
const where = args.where || {}; | random_line_split |
google-apps-script.base.d.ts | alert or a prompt. To determine which button the user clicked,
* use Button.
*
* // Display a dialog box with a message and "Yes" and "No" buttons.
* var ui = DocumentApp.getUi();
* var response = ui.alert('Are you sure you want to continue?', ui.ButtonSet.YES_NO);
*
* ... | * } catch (e) {
* // Logs an ERROR message.
* console.error('myFunction() yielded an error: ' + e);
* }
* console.timeEnd(label); // Stops the timer, logs execution duration. | random_line_split | |
plot.py | # Copyright (c) 2014 Alcatel-Lucent Enterprise
# All 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
#
# Un... |
self.plot[PLOT_SERIES] = self.series
def __str__(self):
js = self.plot
series = []
for s in self.series:
series.append(json.loads(str(s)))
js[PLOT_SERIES] = series
return json.dumps(js)
def __repr__(self):
return str(self)
| e = PlotSerie(x)
self.series.append(e) | conditional_block |
plot.py | # Copyright (c) 2014 Alcatel-Lucent Enterprise
# All 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
#
# Un... | (self):
js = self.plot
series = []
for s in self.series:
series.append(json.loads(str(s)))
js[PLOT_SERIES] = series
return json.dumps(js)
def __repr__(self):
return str(self)
| __str__ | identifier_name |
plot.py | # Copyright (c) 2014 Alcatel-Lucent Enterprise
# All 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
#
# Un... |
def __repr__(self):
return str(self)
| js = self.plot
series = []
for s in self.series:
series.append(json.loads(str(s)))
js[PLOT_SERIES] = series
return json.dumps(js) | identifier_body |
plot.py | # Copyright (c) 2014 Alcatel-Lucent Enterprise
# All 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
#
# Un... | e = PlotSerie(x)
self.series.append(e)
self.plot[PLOT_SERIES] = self.series
def __str__(self):
js = self.plot
series = []
for s in self.series:
series.append(json.loads(str(s)))
js[PLOT_SERIES] = series
return json.dumps(js... | self.unit_type = facette_to_json(PLOT_UNIT_TYPE, js, self.plot)
self.series = []
if js.get(PLOT_SERIES):
for x in js[PLOT_SERIES]: | random_line_split |
test_list_goals.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import pytest
from ... | (self):
Goal.clear()
self.assert_console_output(self._INSTALLED_HEADER)
TaskRegistrar(name=self._LIST_GOALS_NAME, action=ListGoals)\
.install().with_description(self._LIST_GOALS_DESC)
self.assert_console_output(
self._INSTALLED_HEADER,
' {0}: {1}'.format(self._LIST_GOALS_NAME, self._... | test_list_goals | identifier_name |
test_list_goals.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import pytest
from ... | ' alpaca_alpaca -> llama_llama [ltail=cluster_alpaca lhead=cluster_llama];',
'}',
options={ 'graph': True }
)
| Goal.clear()
TaskRegistrar(name=self._LIST_GOALS_NAME, action=ListGoals)\
.install().with_description(self._LIST_GOALS_DESC)
TaskRegistrar(name=self._LLAMA_NAME, action=ListGoalsTest.LlamaTask)\
.install().with_description(self._LLAMA_DESC)
TaskRegistrar(name=self._ALPACA_NAME, action=ListGoals... | identifier_body |
test_list_goals.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import pytest
from ... | ' llama_llama [label="llama"];',
' }',
' subgraph cluster_alpaca {\n node [style=filled];\n color = blue;\n label = "alpaca";',
' alpaca_alpaca [label="alpaca"];',
' }',
' alpaca_alpaca -> llama_llama [ltail=cluster_alpaca lhead=cluster_llama];',
'}',
o... | ' goals_goals [label="goals"];',
' }',
' subgraph cluster_llama {\n node [style=filled];\n color = blue;\n label = "llama";', | random_line_split |
messaging-api-request.js | /*! firebase-admin v5.5.1 */
"use strict";
/*!
* Copyright 2017 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
*
* Unles... |
return null;
};
/**
* Invokes the request handler with the provided request data.
*
* @param {string} host The host to which to send the request.
* @param {string} path The path to which to send the request.
* @param {Object} requestData The request data.
* @return {Promis... | {
if (typeof response.error === 'string') {
return response.error;
}
else {
return response.error.message;
}
} | conditional_block |
messaging-api-request.js | /*! firebase-admin v5.5.1 */
"use strict";
/*!
* Copyright 2017 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
*
* Unles... | (app) {
this.signedApiRequestHandler = new api_request_1.SignedApiRequestHandler(app);
}
/**
* @param {Object} response The response to check for errors.
* @return {string|null} The error code if present; null otherwise.
*/
FirebaseMessagingRequestHandler.getErrorCode = function (resp... | FirebaseMessagingRequestHandler | identifier_name |
messaging-api-request.js | /*! firebase-admin v5.5.1 */
"use strict";
/*!
* Copyright 2017 Google Inc.
* | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governin... | * 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
* | random_line_split |
messaging-api-request.js | /*! firebase-admin v5.5.1 */
"use strict";
/*!
* Copyright 2017 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
*
* Unles... |
/**
* @param {Object} response The response to check for errors.
* @return {string|null} The error code if present; null otherwise.
*/
FirebaseMessagingRequestHandler.getErrorCode = function (response) {
if (validator.isNonNullObject(response) && 'error' in response) {
if (ty... | {
this.signedApiRequestHandler = new api_request_1.SignedApiRequestHandler(app);
} | identifier_body |
sleep_schedule.py | from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random of... | (self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.e... | _get_next_sleep_schedule | identifier_name |
sleep_schedule.py | from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random of... |
# If sleep time is passed add one day
if next_time <= now:
next_time += timedelta(days=1)
times.append(next_time)
diffs = {}
for index in range(len(self.entries)):
diff = (times[index]-now).total_seconds()
if diff >= 0: diffs[ind... | for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seconds=self._get_random_offset(self.entries[index]['time_random_offset'])) | random_line_split |
sleep_schedule.py | from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random of... |
def _get_next_sleep_schedule(self):
now = datetime.now() + self.SCHEDULING_MARGIN
times = []
for index in range(len(self.entries)):
next_time = now.replace(hour=self.entries[index]['time'].hour, minute=self.entries[index]['time'].minute)
next_time += timedelta(seco... | if datetime.now() >= self._next_sleep:
return True
if datetime.now() >= self._current_sleep and datetime.now() < self._current_end:
self._next_duration = (self._current_end - datetime.now()).total_seconds()
return True
return False | identifier_body |
sleep_schedule.py | from datetime import datetime, timedelta
from time import sleep
from random import uniform
class SleepSchedule(object):
"""Pauses the execution of the bot every day for some time
Simulates the user going to sleep every day for some time, the sleep time
and the duration is changed every day by a random of... | sleep(self.LOG_INTERVAL_SECONDS)
sleep_to_go -= self.LOG_INTERVAL_SECONDS | conditional_block | |
app.js | angular.module('myApp', ['ui.router', 'ui.bootstrap', 'smoothScroll', 'ngStorage', 'ngSanitize', 'myApp.controllers', 'myApp.directives', 'myApp.filters'])
.run(
[ '$rootScope', '$state', '$stateParams',
function ($rootScope, $state, $stateParams) {
// It's very handy to add references to $stat... | }
]
); | }
}) | random_line_split |
taskexp.py | .
import sys
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject
from multiprocessing import Queue
import threading
from xmlrpc import client
import time
import bb
import bb.event
# Package Model
(COL_PKG_NAME) = (0)
# Dependency Model
(TYPE_DEP, TYPE_RDEP) = (0, 1)
(COL_DEP_TYPE, ... |
ret, error = server.runCommand(["generateDepTreeEvent", cmdline[1], cmdline[2]])
if error:
print("Error running command '%s': %s" % (cmdline, error))
return 1
elif ret != True:
print("Error running command '%s': returned %s" % (cmdline, ret))
retu... | print("This UI requires the -g option")
return 1 | conditional_block |
taskexp.py | .
import sys
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject
from multiprocessing import Queue
import threading
from xmlrpc import client
import time
import bb
import bb.event
# Package Model
(COL_PKG_NAME) = (0)
# Dependency Model
(TYPE_DEP, TYPE_RDEP) = (0, 1)
(COL_DEP_TYPE, ... |
class PackageReverseDepView(Gtk.TreeView):
def __init__(self, model, label):
Gtk.TreeView.__init__(self)
self.current = None
self.filter_model = model.filter_new()
self.filter_model.set_visible_func(self._filter)
self.set_model(self.filter_model)
self.append_column... | def __init__(self, model, dep_type, label):
Gtk.TreeView.__init__(self)
self.current = None
self.dep_type = dep_type
self.filter_model = model.filter_new()
self.filter_model.set_visible_func(self._filter, data=None)
self.set_model(self.filter_model)
self.append_co... | identifier_body |
taskexp.py | return False
return package == self.current
def set_current_package(self, package):
self.current = package
self.filter_model.refilter()
class PackageReverseDepView(Gtk.TreeView):
def __init__(self, model, label):
Gtk.TreeView.__init__(self)
self.current = None
... |
if isinstance(event, bb.command.CommandFailed):
print("Command execution failed: %s" % event.error)
return event.exitcode | random_line_split | |
taskexp.py | .
import sys
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject
from multiprocessing import Queue
import threading
from xmlrpc import client
import time
import bb
import bb.event
# Package Model
(COL_PKG_NAME) = (0)
# Dependency Model
(TYPE_DEP, TYPE_RDEP) = (0, 1)
(COL_DEP_TYPE, ... | (self, model, iter, data):
package = model[iter][COL_DEP_PACKAGE]
return package == self.current
def set_current_package(self, package):
self.current = package
self.filter_model.refilter()
class DepExplorer(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self)
... | _filter | identifier_name |
info.test.js | /* Copyright (c) 2014-2017 Richard Rodger and other contributors, MIT License */
var Code = require('code')
var Lab = require('lab')
var Seneca = require('seneca')
var lab = exports.lab = Lab.script()
var describe = lab.describe
var it = lab.it
var expect = Code.expect
describe('info', function () {
it('happy', ... | })
}) | }) | random_line_split |
search.rs | use std::io;
use std::collections::HashMap;
use asnom::structure::StructureTag;
use asnom::structures::{Tag, Sequence, Integer, OctetString, Boolean};
use asnom::common::TagClass::*;
use rfc4515::parse;
use futures::{Future, stream, Stream};
use tokio_service::Service;
use ldap::Ldap;
use service::{LdapMessage, Lda... | .map(|v| String::from_utf8(v).unwrap())
.collect();
let key = inner.pop().unwrap();
let keystr = String::from_utf8(key.expect_primitive().unwrap()).unwrap();
map.insert(keystr, valuev);
}
Some(map)
}
impl Ldap {
pub fn search(&... | .into_iter()
.map(|t| t.expect_primitive().unwrap()) | random_line_split |
search.rs | use std::io;
use std::collections::HashMap;
use asnom::structure::StructureTag;
use asnom::structures::{Tag, Sequence, Integer, OctetString, Boolean};
use asnom::common::TagClass::*;
use rfc4515::parse;
use futures::{Future, stream, Stream};
use tokio_service::Service;
use ldap::Ldap;
use service::{LdapMessage, Lda... | {
Reference(Vec<String>),
Object {
object_name: String,
attributes: HashMap<String, Vec<String>>,
},
}
impl SearchEntry {
pub fn construct(tag: Tag) -> SearchEntry {
match tag {
Tag::StructureTag(t) => {
match t.id {
// Search Res... | SearchEntry | identifier_name |
pin-unsound-issue-66544-clone.rs | use std::cell::Cell;
use std::marker::PhantomPinned;
use std::pin::Pin;
struct | <'a>(Cell<Option<&'a mut MyType<'a>>>, PhantomPinned);
impl<'a> Clone for &'a mut MyType<'a> {
//~^ ERROR E0751
fn clone(&self) -> &'a mut MyType<'a> {
self.0.take().unwrap()
}
}
fn main() {
let mut unpinned = MyType(Cell::new(None), PhantomPinned);
let bad_addr = &unpinned as *const MyTyp... | MyType | identifier_name |
pin-unsound-issue-66544-clone.rs | use std::cell::Cell;
use std::marker::PhantomPinned;
use std::pin::Pin;
| impl<'a> Clone for &'a mut MyType<'a> {
//~^ ERROR E0751
fn clone(&self) -> &'a mut MyType<'a> {
self.0.take().unwrap()
}
}
fn main() {
let mut unpinned = MyType(Cell::new(None), PhantomPinned);
let bad_addr = &unpinned as *const MyType<'_> as usize;
let mut p = Box::pin(MyType(Cell::ne... | struct MyType<'a>(Cell<Option<&'a mut MyType<'a>>>, PhantomPinned);
| random_line_split |
chart.component.ts | /// <reference path='components/jqwidgets.d.ts' />
import { Component, ViewChild, AfterViewInit, Input } from '@angular/core';
import { jqxChartComponent } from 'components/angular_jqxChart';
@Component({
selector: 'jqx-chart',
template: `<angularChart #reference width='100%' height='370px'></angularChart>`
... | sumAmount += currentItemValue;
newArray.push(currentItem);
}
average = sumAmount / records.length
this.amountFormFill(smallAmount, smallAmountMonth, bigAmount, bigAmountMonth, average);
return newArray;
}
});
settings: jqw... | smallAmount = currentItemValue;
smallAmountMonth = this.monthsNames[currentItem.uid];
}
| conditional_block |
chart.component.ts | /// <reference path='components/jqwidgets.d.ts' />
import { Component, ViewChild, AfterViewInit, Input } from '@angular/core';
import { jqxChartComponent } from 'components/angular_jqxChart';
@Component({
selector: 'jqx-chart',
template: `<angularChart #reference width='100%' height='370px'></angularChart>`
... | //Refresh the chart when the employeID is changed
refreshChart() : void
{
setTimeout(() => {
this.dataAdapter.dataBind();
}, 100)
};
//The method in which we update the 'amount' form with the new data
amountFormFill(smallAmount: number, smallAmountMonth: string, big... | this.myChart.createWidget(this.settings);
}
| identifier_body |
chart.component.ts | /// <reference path='components/jqwidgets.d.ts' />
import { Component, ViewChild, AfterViewInit, Input } from '@angular/core';
import { jqxChartComponent } from 'components/angular_jqxChart';
@Component({
selector: 'jqx-chart',
template: `<angularChart #reference width='100%' height='370px'></angularChart>`
... | ngAfterViewInit(): void
{
this.myChart.createWidget(this.settings);
}
//Refresh the chart when the employeID is changed
refreshChart() : void
{
setTimeout(() => {
this.dataAdapter.dataBind();
}, 100)
};
//The method in which we update the 'amou... | random_line_split | |
chart.component.ts | /// <reference path='components/jqwidgets.d.ts' />
import { Component, ViewChild, AfterViewInit, Input } from '@angular/core';
import { jqxChartComponent } from 'components/angular_jqxChart';
@Component({
selector: 'jqx-chart',
template: `<angularChart #reference width='100%' height='370px'></angularChart>`
... | : void
{
this.myChart.createWidget(this.settings);
}
//Refresh the chart when the employeID is changed
refreshChart() : void
{
setTimeout(() => {
this.dataAdapter.dataBind();
}, 100)
};
//The method in which we update the 'amount' form with the new... | AfterViewInit() | identifier_name |
refactorConvertExport_namedToDefault.ts | /// <reference path='fourslash.ts' />
// @Filename: /a.ts
/////*a*/export function f() {}/*b*/
// @Filename: /b.ts
////import { f } from "./a";
////import { f as g } from "./a";
////import { f, other } from "./a";
////
////export { f } from "./a";
////export { f as i } from "./a";
////export { f as default } from "./... |
"/b.ts":
`import f from "./a";
import g from "./a";
import f, { other } from "./a";
export { default as f } from "./a";
export { default as i } from "./a";
export { default } from "./a";
import * as a from "./a";
a.default();`,
},
}); | actionName: "Convert named export to default export",
actionDescription: "Convert named export to default export",
newContent: {
"/a.ts":
`export default function f() {}`, | random_line_split |
day-3.py | import sys
def | ():
moveList = sys.stdin.read().strip()
moves = {}
houseGrid = []
houseGrid.append([1])
moves['^'] = [-1, 0]
moves['v'] = [1, 0]
moves['<'] = [0, -1]
moves['>'] = [0, 1]
santa = {}
santa['x'] = 0
santa['y'] = 0
robo = {}
robo['x'] = 0
robo['y'] = 0
santaList = [(0,0)]
isSanta = True
for move in moveL... | solve | identifier_name |
day-3.py | import sys
def solve():
moveList = sys.stdin.read().strip()
moves = {}
houseGrid = []
houseGrid.append([1])
moves['^'] = [-1, 0]
moves['v'] = [1, 0]
moves['<'] = [0, -1]
moves['>'] = [0, 1]
santa = {}
santa['x'] = 0
santa['y'] = 0
robo = {}
robo['x'] = 0
robo['y'] = 0
santaList = [(0,0)]
isSanta = Tr... |
print(str(len(santaList)))
if __name__ == "__main__":
solve() | currentMove = moves[move]
if(isSanta):
isSanta = False
santa['y'] = santa['y'] + currentMove[0]
santa['x'] = santa['x'] + currentMove[1]
currentPosition = (santa['y'], santa['x'])
if not currentPosition in santaList:
santaList.append(currentPosition)
else:
isSanta = True
robo['y'] = robo['y... | conditional_block |
day-3.py | import sys
def solve():
moveList = sys.stdin.read().strip()
moves = {}
houseGrid = []
houseGrid.append([1])
moves['^'] = [-1, 0]
moves['v'] = [1, 0]
moves['<'] = [0, -1]
moves['>'] = [0, 1]
santa = {}
santa['x'] = 0
santa['y'] = 0
robo = {}
robo['x'] = 0
robo['y'] = 0
santaList = [(0,0)]
isSanta = Tr... | isSanta = True
robo['y'] = robo['y'] + currentMove[0]
robo['x'] = robo['x'] + currentMove[1]
currentPosition = (robo['y'], robo['x'])
if not currentPosition in santaList:
santaList.append(currentPosition)
print(str(len(santaList)))
if __name__ == "__main__":
solve() | if not currentPosition in santaList:
santaList.append(currentPosition)
else: | random_line_split |
day-3.py | import sys
def solve():
| if(isSanta):
isSanta = False
santa['y'] = santa['y'] + currentMove[0]
santa['x'] = santa['x'] + currentMove[1]
currentPosition = (santa['y'], santa['x'])
if not currentPosition in santaList:
santaList.append(currentPosition)
else:
isSanta = True
robo['y'] = robo['y'] + currentMove[0]
rob... | moveList = sys.stdin.read().strip()
moves = {}
houseGrid = []
houseGrid.append([1])
moves['^'] = [-1, 0]
moves['v'] = [1, 0]
moves['<'] = [0, -1]
moves['>'] = [0, 1]
santa = {}
santa['x'] = 0
santa['y'] = 0
robo = {}
robo['x'] = 0
robo['y'] = 0
santaList = [(0,0)]
isSanta = True
for move in moveList:
... | identifier_body |
test_compat.py | from django.db import models
from django.test import TestCase
from ..models.compat import YAMLField
class TestYAMLModel(models.Model):
yaml_field = YAMLField()
class TestYAMLField(TestCase):
...
def test_to_python(self):
yaml_data = """ | main:
- 1
- 2
- 3
"""
yaml_field = YAMLField()
yaml_field.to_python(yaml_data)
yaml_data = ""
yaml_field = YAMLField()
self.assertEqual(None, yaml_field.to_python(yaml_data))
yaml_data = """`"""
yaml_field = YAMLFiel... | random_line_split | |
test_compat.py | from django.db import models
from django.test import TestCase
from ..models.compat import YAMLField
class TestYAMLModel(models.Model):
yaml_field = YAMLField()
class TestYAMLField(TestCase):
...
def test_to_python(self):
yaml_data = """
main:
- 1
- 2
- 3
... | (self):
yaml_field = YAMLField()
self.assertEqual("", yaml_field.get_prep_value(None))
yaml_field = YAMLField()
data = {"aaa": "aaa😺",}
self.assertEqual(
"aaa: aaa😺\n",
yaml_field.get_prep_value(data)
)
| test_get_prep_value | identifier_name |
test_compat.py | from django.db import models
from django.test import TestCase
from ..models.compat import YAMLField
class TestYAMLModel(models.Model):
|
class TestYAMLField(TestCase):
...
def test_to_python(self):
yaml_data = """
main:
- 1
- 2
- 3
"""
yaml_field = YAMLField()
yaml_field.to_python(yaml_data)
yaml_data = ""
yaml_field = YAMLField()
self.assertEqual(... | yaml_field = YAMLField() | identifier_body |
cal_accuracy_v3.py | #! /usr/bin/env python
import utility_function as uf
import sys
import cv2
import numpy as np
def read_file_list(file_name):
# assume the first argument is the image name and the second one is the label
name_list = list()
label_list = list()
with open(file_name, "r") as f:
s = f.read()
... |
def read_fine_tune_res_file(file_name, res_list, label_num):
with open(file_name, "r") as f:
file_data = f.read()
file_data = uf.delete_last_empty_line(file_data)
data_list = file_data.split("\n")
if (len(data_list) == 0):
print("empty file " + file_name)
re... | with open(label_file, "r") as f:
s = f.read();
s = uf.delete_last_empty_line(s)
s_l = s.split("\n")
s_l = [s == "true" for s in s_l]
return s_l | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.