text
stringlengths 2
1.04M
| meta
dict |
---|---|
package apps
import (
"strings"
"github.com/dokku/dokku/plugins/common"
)
// ReportSingleApp is an internal function that displays the app report for one or more apps
func ReportSingleApp(appName string, format string, infoFlag string) error {
if err := common.VerifyAppName(appName); err != nil {
return err
}
flags := map[string]common.ReportFunc{
"--app-dir": reportDir,
"--app-deploy-source": reportDeploySource,
"--app-locked": reportLocked,
}
flagKeys := []string{}
for flagKey := range flags {
flagKeys = append(flagKeys, flagKey)
}
trimPrefix := false
uppercaseFirstCharacter := true
infoFlags := common.CollectReport(appName, infoFlag, flags)
return common.ReportSingleApp("app", appName, infoFlag, infoFlags, flagKeys, format, trimPrefix, uppercaseFirstCharacter)
}
func reportDir(appName string) string {
return common.AppRoot(appName)
}
func reportDeploySource(appName string) string {
deploySource := ""
if b, err := common.PlugnTriggerSetup("deploy-source", []string{appName}...).SetInput("").Output(); err != nil {
deploySource = strings.TrimSpace(string(b[:]))
}
return deploySource
}
func reportLocked(appName string) string {
locked := "false"
if appIsLocked(appName) {
locked = "true"
}
return locked
}
| {
"content_hash": "59df2ab3ba91b3a9a1866cc435be0750",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 122,
"avg_line_length": 24.73076923076923,
"alnum_prop": 0.7146189735614308,
"repo_name": "progrium/dokku",
"id": "ec69410bee22f93288b5d68a245905000ad3b7d3",
"size": "1286",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "plugins/apps/report.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "196"
},
{
"name": "Clojure",
"bytes": "666"
},
{
"name": "Go",
"bytes": "330"
},
{
"name": "HTML",
"bytes": "1752"
},
{
"name": "Java",
"bytes": "853"
},
{
"name": "JavaScript",
"bytes": "5714"
},
{
"name": "Makefile",
"bytes": "21735"
},
{
"name": "PHP",
"bytes": "43"
},
{
"name": "Python",
"bytes": "8327"
},
{
"name": "Ruby",
"bytes": "1282"
},
{
"name": "Scala",
"bytes": "2235"
},
{
"name": "Shell",
"bytes": "250504"
}
],
"symlink_target": ""
} |
@implementation PassbookCell
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame))];
if (self) {
UIView *cardView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame))];
cardView.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256)/255.f
green:arc4random_uniform(256)/255.f
blue:arc4random_uniform(256)/255.f
alpha:1];
cardView.layer.cornerRadius = 10;
cardView.layer.borderColor = [UIColor darkGrayColor].CGColor;
cardView.layer.borderWidth = 2;
cardView.clipsToBounds = YES;
[self.contentView addSubview:cardView];
self.layer.shadowColor = [UIColor blackColor].CGColor;
self.layer.shadowOffset = CGSizeMake(0, -2);
self.layer.shadowOpacity = .75;
self.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:10].CGPath;
self.clipsToBounds = NO;
}
return self;
}
- (void)setLabel:(NSString *)label
{
UILabel *cardLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 3, CGRectGetWidth(self.contentView.frame), 60)];
cardLabel.textAlignment = NSTextAlignmentLeft;
cardLabel.font = [UIFont fontWithName:@"Avenir-Medium" size:42];
cardLabel.textColor = [UIColor whiteColor];
cardLabel.backgroundColor = [UIColor clearColor];
cardLabel.text = label;
[self.contentView addSubview:cardLabel];
}
+ (NSString *)reuseId
{
return @"PassbookCellId";
}
@end
| {
"content_hash": "70bcf6aaf9188ed90c21bf519dd92dbc",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 122,
"avg_line_length": 39.13636363636363,
"alnum_prop": 0.6364692218350755,
"repo_name": "jaythrash/CollectionViewLayoutDemo",
"id": "6f4806d19375233f0bd7fdf11d8b78813db80ef8",
"size": "1936",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CollectionViewLayoutDemo/PassbookCell.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "28817"
}
],
"symlink_target": ""
} |
require 'spec_helper'
describe 'stdlib::ip_in_range' do
describe 'signature validation' do
it { is_expected.not_to eq(nil) }
it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{'stdlib::ip_in_range' expects 2 arguments, got none}) }
it { is_expected.to run.with_params('one', 'two', '3').and_raise_error(ArgumentError, %r{'stdlib::ip_in_range' expects 2 arguments, got 3}) }
it { is_expected.to run.with_params([], []).and_raise_error(ArgumentError, %r{'stdlib::ip_in_range' parameter 'ipaddress' expects a String value, got Array}) }
it { is_expected.to run.with_params('1.1.1.1', 7).and_raise_error(ArgumentError, %r{'stdlib::ip_in_range' parameter 'range' expects a value of type String or Array, got Integer}) }
end
describe 'basic validation inputs' do
it { is_expected.to run.with_params('192.168.100.12', '192.168.100.0/24').and_return(true) }
it { is_expected.to run.with_params('192.168.100.12', ['10.10.10.10/24', '192.168.100.0/24']).and_return(true) }
it { is_expected.to run.with_params('10.10.10.10', '192.168.100.0/24').and_return(false) }
end
end
| {
"content_hash": "513e2718af40ccc65373fc212a7d74d8",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 184,
"avg_line_length": 66.05882352941177,
"alnum_prop": 0.680320569902048,
"repo_name": "DavidS/puppetlabs-stdlib",
"id": "01d800ce6c2f801160edb2c36c615bcc2c41b715",
"size": "1123",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/functions/ip_in_range_spec.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Pascal",
"bytes": "14104"
},
{
"name": "Puppet",
"bytes": "1634"
},
{
"name": "Ruby",
"bytes": "674055"
}
],
"symlink_target": ""
} |
/*
* File: app/view/formAplicacion.js
*
* This file was generated by Sencha Architect version 4.1.2.
* http://www.sencha.com/products/architect/
*
* This file requires use of the Ext JS 5.1.x library, under independent license.
* License of Sencha Architect does not include license for Ext JS 5.1.x. For more
* details see http://www.sencha.com/license or contact [email protected].
*
* This file will be auto-generated each and everytime you save your project.
*
* Do NOT hand edit this file.
*/
Ext.define('hwtProCondicionUnidad.view.formAplicacion', {
extend: 'Ext.form.Panel',
alias: 'widget.formAplicacion',
requires: [
'hwtProCondicionUnidad.view.formAplicacionViewModel',
'Ext.button.Button',
'Ext.toolbar.Separator',
'Ext.toolbar.Fill',
'Ext.grid.Panel',
'Ext.view.Table',
'Ext.toolbar.Paging',
'Ext.grid.column.Column'
],
viewModel: {
type: 'formaplicacion'
},
id: 'formAplicacion',
itemId: 'formAplicacion',
bodyCls: 'formBackground',
bodyPadding: 10,
defaultListenerScope: true,
dockedItems: [
{
xtype: 'toolbar',
cls: 'toolbarBackground',
dock: 'top',
id: 'toolbarPrincipal',
itemId: 'toolbarPrincipal',
items: [
{
xtype: 'button',
id: 'btnVisualizar',
itemId: 'btnVisualizar',
width: 130,
iconCls: 'fa fa-eye icon16 iconColorDarkBlue',
text: 'Visualizar',
textAlign: 'left',
listeners: {
click: 'onButtonClickVisualizar'
}
},
{
xtype: 'button',
id: 'btnBuscar',
itemId: 'btnBuscar',
width: 130,
iconCls: 'fa fa-search icon16 iconColorDarkBlue',
text: 'Buscar',
textAlign: 'left',
listeners: {
click: 'onButtonClickBuscar'
}
},
{
xtype: 'tbseparator',
width: 50
},
{
xtype: 'button',
id: 'btnCrear',
itemId: 'btnCrear',
width: 130,
iconCls: 'fa fa-plus-square icon16 iconColorGreen',
text: 'Crear',
textAlign: 'left',
listeners: {
click: 'onButtonClickCrear'
}
},
{
xtype: 'button',
id: 'btnActualizar',
itemId: 'btnActualizar',
width: 130,
iconCls: 'fa fa-pencil-square icon16 iconColorGreen',
text: 'Actualizar',
textAlign: 'left',
listeners: {
click: 'onButtonClickActualizar'
}
},
{
xtype: 'tbseparator',
width: 50
},
{
xtype: 'button',
id: 'btnEliminar',
itemId: 'btnEliminar',
width: 130,
iconCls: 'fa fa-trash icon16 iconColorDarkRed',
text: 'Eliminar',
textAlign: 'left',
listeners: {
click: 'onButtonClickEliminar'
}
},
{
xtype: 'button',
id: 'btnReporte',
itemId: 'btnReporte',
width: 130,
iconCls: 'fa fa-th icon16 iconColorDarkBlue',
text: 'Reporte',
textAlign: 'left',
listeners: {
click: 'onButtonClickReporte'
}
},
{
xtype: 'tbfill'
},
{
xtype: 'button',
id: 'btnSalir',
itemId: 'btnSalir',
width: 130,
iconCls: 'fa fa-external-link-square icon16 iconColorRed',
text: 'Salir',
textAlign: 'left',
listeners: {
click: 'onButtonClickSalir'
}
}
]
}
],
items: [
{
xtype: 'gridpanel',
id: 'gridReporteCondicion',
itemId: 'gridReporteCondicion',
title: 'Reportes de Condición',
store: 'storeReporteCondicion',
dockedItems: [
{
xtype: 'pagingtoolbar',
dock: 'bottom',
width: 360,
displayInfo: true,
store: 'storeReporteCondicion'
}
],
columns: [
{
xtype: 'gridcolumn',
id: 'num_reporte',
itemId: 'num_reporte',
dataIndex: 'num_reporte',
text: 'Numero</br>Reporte'
},
{
xtype: 'gridcolumn',
id: 'vin',
itemId: 'vin',
width: 150,
dataIndex: 'vin',
text: 'Vin'
},
{
xtype: 'gridcolumn',
id: 'fecha_reporte',
itemId: 'fecha_reporte',
dataIndex: 'fecha_reporte',
text: 'Fecha</br>Reporte'
},
{
xtype: 'gridcolumn',
id: 'num_reparaciones',
itemId: 'num_reparaciones',
dataIndex: 'num_reparaciones',
text: 'Numero</br>Reparaciones'
},
{
xtype: 'gridcolumn',
renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {
var valorRetorno = Ext.util.Format.number(value, '0,000.00');
return valorRetorno;
},
id: 'precio_total_estimado',
itemId: 'precio_total_estimado',
align: 'right',
dataIndex: 'precio_total_estimado',
text: 'Precio Total</br>Estimado'
},
{
xtype: 'gridcolumn',
id: 'usuario',
itemId: 'usuario',
dataIndex: 'usuario',
text: 'Usuario'
}
],
listeners: {
itemclick: 'onGridReporteCondicionItemClick',
itemdblclick: 'onGridReporteCondicionItemDblClick'
}
}
],
onButtonClickVisualizar: function(button, e, eOpts) {
},
onButtonClickBuscar: function(button, e, eOpts) {
},
onButtonClickCrear: function(button, e, eOpts) {
elf.openWindow('winReporteCondicion');
var arrayCombos = new Array();
arrayCombos.push('OpcionSeccion');
arrayCombos.forEach(Ext.getCmp('formAplicacion').cargaComboComplejo);
console.warn(elf.getSessionData('user_id'));
elf.writeElement('tfUsuario',elf.getSessionData('user_id'));
},
onButtonClickActualizar: function(button, e, eOpts) {
},
onButtonClickEliminar: function(button, e, eOpts) {
Ext.getCmp('formAplicacion').eliminaCondicionUnidad();
},
onButtonClickReporte: function(button, e, eOpts) {
Ext.getCmp('formAplicacion').reporteCondicionUnidad();
},
onButtonClickSalir: function(button, e, eOpts) {
elf.stopApp('hwtProCondicionUnidad');
},
onGridReporteCondicionItemClick: function(dataview, record, item, index, e, eOpts) {
Ext.getCmp('gridReporteCondicion').recordActivo = record.data;
},
onGridReporteCondicionItemDblClick: function(dataview, record, item, index, e, eOpts) {
Ext.getCmp('formAplicacion').presentaRegistro();
},
extraeOpcionesCondicion: function() {
var apiController = 'apiCondicionUnidad';
var apiMethod = 'datosOpcionesCondicion';
var objJsonData = new Object();
objJsonData.codigoUnidad = Ext.getCmp('formAplicacion').codigoUnidad;
var objJsonRequest = new Object();
objJsonRequest.apiController = apiController;
objJsonRequest.apiMethod = apiMethod;
objJsonRequest.apiData = JSON.stringify(objJsonData);
var functionSuccess = function(){
var jsonData = elf.getInfoDataBridge(apiMethod);
/*Ext.getCmp('formAplicacion').filtrosDefecto();*/
elf.refreshGrid('gridReporteCondicion');
};
var functionFailure = function(){
var jsonData = elf.getInfoDataBridge(apiMethod);
console.warn('datosOpcionesCondicion:');
console.warn(jsonData);
};
elf.doDataBridge(objJsonRequest,
functionSuccess,
null,
functionFailure,
null);
},
extraeOpcionesUnidad: function() {
var apiController = 'apiUnidadUsada';
var apiMethod = 'datosOpciones';
var objJsonData = new Object();
objJsonData.codigoUnidad = Ext.getCmp('formAplicacion').codigoUnidad;
var objJsonRequest = new Object();
objJsonRequest.apiController = apiController;
objJsonRequest.apiMethod = apiMethod;
objJsonRequest.apiData = JSON.stringify(objJsonData);
var functionSuccess = function(){
var jsonData = elf.getInfoDataBridge(apiMethod);
Ext.getCmp('formAplicacion').filtrosDefecto();
elf.refreshGrid('gridUnidadUsada');
};
var functionFailure = function(){
var jsonData = elf.getInfoDataBridge(apiMethod);
console.warn('datosOpciones:');
console.warn(jsonData);
};
elf.doDataBridge(objJsonRequest,
functionSuccess,
null,
functionFailure,
null);
},
cargaCombo: function(element, index, array) {
var jsonData = elf.getInfoDataBridge('datosOpciones');
var idCombo = 'cbx' + element;
var listaCombo = 'opciones' + element;
if(Ext.getCmp(idCombo) !== undefined){
elf.setComboBox(idCombo,
jsonData,
listaCombo,
'descripcion',
'descripcion');
}
else{
console.warn('cargaOpciones: - No se encontro el ComboBox: ' + idCombo);
}
},
cargaComboComplejo: function(element, index, array) {
var jsonData = elf.getInfoDataBridge('datosOpcionesCondicion');
var idCombo = 'cbx' + element;
var listaCombo = 'opciones' + element;
console.info(jsonData);
if(Ext.getCmp(idCombo) !== undefined){
elf.setComboBox(idCombo,
jsonData,
listaCombo,
'codigo',
'descripcion');
}
else{
console.warn('cargaOpciones: - No se encontro el ComboBox: ' + idCombo);
}
},
presentaRegistro: function(pEstado) {
var reporteCondicion = Ext.getCmp('gridReporteCondicion').recordActivo;
console.warn(reporteCondicion);
var apiController = 'apiCondicionUnidad';
var apiMethod = 'datosReporteCondicion';
var objJsonData = new Object();
objJsonData.numReporte = reporteCondicion.num_reporte;
var objJsonRequest = new Object();
objJsonRequest.apiController = apiController;
objJsonRequest.apiMethod = apiMethod;
objJsonRequest.apiData = JSON.stringify(objJsonData);
var functionSuccess = function(){
var jsonData = elf.getInfoDataBridge(apiMethod);
var pModo = '';
if(pEstado === 'editar'){
pModo = 'edit';
}
elf.openWindow('winReporteCondicion');
var arrayCombos = new Array();
arrayCombos.push('OpcionSeccion');
arrayCombos.forEach(Ext.getCmp('formAplicacion').cargaComboComplejo);
var jsonData = elf.getInfoDataBridge('datosReporteCondicion');
elf.showRecord(jsonData,'hwtReporteCondicion',pModo);
elf.refreshGrid('gridReporteCondicionLinea');
var obj = Ext.getCmp('tfPrecioTotalEstimado');
console.warn('tfPrecioTotalEstimado');
console.warn(obj);
};
var functionFailure = function(){
var jsonData = elf.getInfoDataBridge(apiMethod);
elf.showInfo(jsonData,
'error');
};
elf.doDataBridge(objJsonRequest,
functionSuccess,
null,
functionFailure,
null);
},
eliminaCondicionUnidad: function() {
var recordReporteCondicion = Ext.getCmp('gridReporteCondicion').recordActivo;
if(recordReporteCondicion === undefined){
msgTipo = 'error';
msgTitulo = 'Eliminar Condiciones de la Unidad (Registro)';
msgContenido = 'Debe seleccionar un registro válido para realizar ésta operación';
elf.message(msgTipo,msgTitulo,msgContenido);
return;
}
var msgFuncion = function(){
var recordReporteCondicion = Ext.getCmp('gridReporteCondicion').recordActivo;
var apiController = 'apiCondicionUnidad';
var apiMethod = 'eliminaCondicionUnidad';
var objJsonData = new Object();
objJsonData.rowidCondicionUnidad = recordReporteCondicion.rowid;
var objJsonRequest = new Object();
objJsonRequest.apiController = apiController;
objJsonRequest.apiMethod = apiMethod;
objJsonRequest.apiData = JSON.stringify(objJsonData);
var functionSuccess = function(){
var jsonData = elf.getInfoDataBridge('eliminaCondicionUnidad');
elf.showInfo(jsonData,'information');
elf.refreshGrid('gridReporteCondicion');
};
var functionFailure = function(){
var jsonData = elf.getInfoDataBridge('eliminaCondicionUnidad');
elf.showInfo(jsonData,'error');
};
elf.doDataBridge(objJsonRequest,
functionSuccess,
null,
functionFailure,
null);
};
console.warn('recordReporteCondicion');
console.warn(recordReporteCondicion);
msgTipo = 'question';
msgTitulo = 'Eliminar Condiciones de la Unidad (Registro)';
msgContenido = 'Desea eliminar el registro de Condiciónes de la Unidad: ' + recordReporteCondicion.vin + '?';
elf.message(msgTipo,msgTitulo,msgContenido,msgFuncion);
},
reporteCondicionUnidad: function() {
var recordReporteCondicion = Ext.getCmp('gridReporteCondicion').recordActivo;
if(recordReporteCondicion === undefined){
msgTipo = 'error';
msgTitulo = 'Reporte de Condiciones de la Unidad (Registro)';
msgContenido = 'Debe seleccionar un registro válido para realizar ésta operación';
elf.message(msgTipo,msgTitulo,msgContenido);
return;
}
var apiController = 'apiCondicionUnidad';
var apiMethod = 'reporteCondicionUnidad';
var objJsonData = new Object();
objJsonData.rowidCondicionUnidad = recordReporteCondicion.rowid;
objJsonData.vinUnidad = recordReporteCondicion.vin;
objJsonData.numReporte = recordReporteCondicion.num_reporte;
var objJsonRequest = new Object();
objJsonRequest.apiController = apiController;
objJsonRequest.apiMethod = apiMethod;
objJsonRequest.apiData = JSON.stringify(objJsonData);
var functionSuccess = function(){
var jsonData = elf.getInfoDataBridge('reporteCondicionUnidad');
var archivoGenerado = elf.getGeneratedFile(jsonData.archivoGenerado.nombre);
window.open(archivoGenerado);
};
var functionFailure = function(){
var jsonData = elf.getInfoDataBridge('reporteCondicionUnidad');
elf.showInfo(jsonData,'error');
};
elf.doDataBridge(objJsonRequest,
functionSuccess,
null,
functionFailure,
null);
}
}); | {
"content_hash": "45a921946314b637c21f0b8f9932021c",
"timestamp": "",
"source": "github",
"line_count": 513,
"max_line_length": 117,
"avg_line_length": 34.33723196881092,
"alnum_prop": 0.5021856372409877,
"repo_name": "devmaster-terian/hwt-backend",
"id": "1178f65c5c68fb3bbc4983f4bb64216759624f27",
"size": "17623",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "gestion/aplicacion/hwtProCondicionUnidad/app/view/formAplicacion.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "8940"
},
{
"name": "ApacheConf",
"bytes": "14"
},
{
"name": "CSS",
"bytes": "75609178"
},
{
"name": "HTML",
"bytes": "4905468"
},
{
"name": "JavaScript",
"bytes": "67293340"
},
{
"name": "PHP",
"bytes": "19336265"
},
{
"name": "Python",
"bytes": "38400"
},
{
"name": "Ruby",
"bytes": "15395"
}
],
"symlink_target": ""
} |
package net.analizer.rxbuslib;
import junit.framework.Assert;
import net.analizer.rxbuslib.annotations.Subscribe;
import net.analizer.rxbuslib.annotations.SubscribeBehavior;
import net.analizer.rxbuslib.annotations.SubscribeTag;
/**
* A simple SubscriberEvent mock that records Strings.
* <p/>
* For testing fun, also includes a landmine method that Bus tests are
* required <em>not</em> to call ({@link #methodWithoutAnnotation(String)}).
*/
public class ModelCatcher {
Model model;
Model behaviorModel;
@Subscribe
public void subscribeModel(Model model) {
this.model = model;
}
@Subscribe(
tags = {@SubscribeTag("NotDefaultTag")}
)
public void hereHaveAStringWithTag(Model model) {
this.model = model;
}
@SubscribeBehavior
public void subscribeBehaviorModel(Model model) {
this.behaviorModel = model;
}
@SubscribeBehavior(
tags = {@SubscribeTag("NotDefaultTag")}
)
public void subscribeBehaviorModelWithTag(Model model) {
this.behaviorModel = model;
}
public void methodWithoutAnnotation(String string) {
Assert.fail("Event bus must not call methods without @Subscribe!");
}
}
| {
"content_hash": "1b01c5f597ad975e9b193bd88b60290b",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 76,
"avg_line_length": 26.695652173913043,
"alnum_prop": 0.6913680781758957,
"repo_name": "analizer1/RxBusLib",
"id": "709182b55736e1a89520e204ecc921b6f87b6e18",
"size": "1228",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rxbuslib/src/test/java/net/analizer/rxbuslib/ModelCatcher.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "181893"
}
],
"symlink_target": ""
} |
<!--
@license Apache-2.0
Copyright (c) 2018 The Stdlib Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title></title>
<style>
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
</style>
<style>
body {
box-sizing: border-box;
width: 100%;
padding: 40px;
}
#console {
width: 100%;
}
</style>
</head>
<body>
<p id="status">Running...</p>
<br>
<div id="console"></div>
<script type="text/javascript">
(function() {
'use strict';
// VARIABLES //
var methods = [
'log',
'error',
'warn',
'dir',
'debug',
'info',
'trace'
];
// MAIN //
/**
* Main.
*
* @private
*/
function main() {
var console;
var str;
var el;
var i;
// FIXME: IE9 has a non-standard `console.log` object (http://stackoverflow.com/questions/5538972/console-log-apply-not-working-in-ie9)
console = window.console || {};
for ( i = 0; i < methods.length; i++ ) {
console[ methods[ i ] ] = write;
}
el = document.querySelector( '#console' );
str = el.innerHTML;
/**
* Writes content to a DOM element. Note that this assumes a single argument and no substitution strings.
*
* @private
* @param {string} message - message
*/
function write( message ) {
str += '<p>'+message+'</p>';
el.innerHTML = str;
}
}
main();
})();
</script>
<script type="text/javascript" src="/docs/api/latest/@stdlib/blas/ext/base/dsnansum/benchmark_bundle.js"></script>
</body>
</html>
| {
"content_hash": "c344ec172e288f51508115bd101c494d",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 139,
"avg_line_length": 22.30666666666667,
"alnum_prop": 0.6228332337118948,
"repo_name": "stdlib-js/www",
"id": "7dda77acaf18ad631adb4064920d34ac7dbe61d8",
"size": "3346",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/docs/api/latest/@stdlib/blas/ext/base/dsnansum/benchmark.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "190538"
},
{
"name": "HTML",
"bytes": "158086013"
},
{
"name": "Io",
"bytes": "14873"
},
{
"name": "JavaScript",
"bytes": "5395746994"
},
{
"name": "Makefile",
"bytes": "40479"
},
{
"name": "Shell",
"bytes": "9744"
}
],
"symlink_target": ""
} |
<html lang="en">
<head>
<title>Symbol Names - Using as</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using as">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Symbols.html#Symbols" title="Symbols">
<link rel="prev" href="Setting-Symbols.html#Setting-Symbols" title="Setting Symbols">
<link rel="next" href="Dot.html#Dot" title="Dot">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<!--
This file documents the GNU Assembler "as".
Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
2000, 2001, 2002, 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation,
Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, with no Front-Cover Texts, and with no
Back-Cover Texts. A copy of the license is included in the
section entitled ``GNU Free Documentation License''.
-->
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="Symbol-Names"></a>
Next: <a rel="next" accesskey="n" href="Dot.html#Dot">Dot</a>,
Previous: <a rel="previous" accesskey="p" href="Setting-Symbols.html#Setting-Symbols">Setting Symbols</a>,
Up: <a rel="up" accesskey="u" href="Symbols.html#Symbols">Symbols</a>
<hr>
</div>
<h3 class="section">5.3 Symbol Names</h3>
<p><a name="index-symbol-names-213"></a><a name="index-names_002c-symbol-214"></a>Symbol names begin with a letter or with one of ‘<samp><span class="samp">._</span></samp>’. On most
machines, you can also use <code>$</code> in symbol names; exceptions are
noted in <a href="Machine-Dependencies.html#Machine-Dependencies">Machine Dependencies</a>. That character may be followed by any
string of digits, letters, dollar signs (unless otherwise noted for a
particular target machine), and underscores.
<p>Case of letters is significant: <code>foo</code> is a different symbol name
than <code>Foo</code>.
<p>Multibyte characters are supported. To generate a symbol name containing
multibyte characters enclose it within double quotes and use escape codes. cf
See <a href="Strings.html#Strings">Strings</a>. Generating a multibyte symbol name from a label is not
currently supported.
<p>Each symbol has exactly one name. Each name in an assembly language program
refers to exactly one symbol. You may use that symbol name any number of times
in a program.
<h4 class="subheading">Local Symbol Names</h4>
<p><a name="index-local-symbol-names-215"></a><a name="index-symbol-names_002c-local-216"></a>A local symbol is any symbol beginning with certain local label prefixes.
By default, the local label prefix is ‘<samp><span class="samp">.L</span></samp>’ for ELF systems or
‘<samp><span class="samp">L</span></samp>’ for traditional a.out systems, but each target may have its own
set of local label prefixes.
On the HPPA local symbols begin with ‘<samp><span class="samp">L$</span></samp>’.
<p>Local symbols are defined and used within the assembler, but they are
normally not saved in object files. Thus, they are not visible when debugging.
You may use the ‘<samp><span class="samp">-L</span></samp>’ option (see <a href="L.html#L">Include Local Symbols: <samp><span class="option">-L</span></samp></a>) to retain the local symbols in the object files.
<h4 class="subheading">Local Labels</h4>
<p><a name="index-local-labels-217"></a><a name="index-temporary-symbol-names-218"></a><a name="index-symbol-names_002c-temporary-219"></a>Local labels help compilers and programmers use names temporarily.
They create symbols which are guaranteed to be unique over the entire scope of
the input source code and which can be referred to by a simple notation.
To define a local label, write a label of the form ‘<samp><b>N</b><span class="samp">:</span></samp>’ (where <b>N</b>
represents any positive integer). To refer to the most recent previous
definition of that label write ‘<samp><b>N</b><span class="samp">b</span></samp>’, using the same number as when
you defined the label. To refer to the next definition of a local label, write
‘<samp><b>N</b><span class="samp">f</span></samp>’—the ‘<samp><span class="samp">b</span></samp>’ stands for “backwards” and the ‘<samp><span class="samp">f</span></samp>’ stands
for “forwards”.
<p>There is no restriction on how you can use these labels, and you can reuse them
too. So that it is possible to repeatedly define the same local label (using
the same number ‘<samp><b>N</b></samp>’), although you can only refer to the most recently
defined local label of that number (for a backwards reference) or the next
definition of a specific local label for a forward reference. It is also worth
noting that the first 10 local labels (‘<samp><b>0:</b></samp>’<small class="dots">...</small>‘<samp><b>9:</b></samp>’) are
implemented in a slightly more efficient manner than the others.
<p>Here is an example:
<pre class="smallexample"> 1: branch 1f
2: branch 1b
1: branch 2f
2: branch 1b
</pre>
<p>Which is the equivalent of:
<pre class="smallexample"> label_1: branch label_3
label_2: branch label_1
label_3: branch label_4
label_4: branch label_3
</pre>
<p>Local label names are only a notational device. They are immediately
transformed into more conventional symbol names before the assembler uses them.
The symbol names are stored in the symbol table, appear in error messages, and
are optionally emitted to the object file. The names are constructed using
these parts:
<dl>
<dt><em>local label prefix</em><dd>All local symbols begin with the system-specific local label prefix.
Normally both <samp><span class="command">as</span></samp> and <code>ld</code> forget symbols
that start with the local label prefix. These labels are
used for symbols you are never intended to see. If you use the
‘<samp><span class="samp">-L</span></samp>’ option then <samp><span class="command">as</span></samp> retains these symbols in the
object file. If you also instruct <code>ld</code> to retain these symbols,
you may use them in debugging.
<br><dt><var>number</var><dd>This is the number that was used in the local label definition. So if the
label is written ‘<samp><span class="samp">55:</span></samp>’ then the number is ‘<samp><span class="samp">55</span></samp>’.
<br><dt><kbd>C-B</kbd><dd>This unusual character is included so you do not accidentally invent a symbol
of the same name. The character has ASCII value of ‘<samp><span class="samp">\002</span></samp>’ (control-B).
<br><dt><em>ordinal number</em><dd>This is a serial number to keep the labels distinct. The first definition of
‘<samp><span class="samp">0:</span></samp>’ gets the number ‘<samp><span class="samp">1</span></samp>’. The 15th definition of ‘<samp><span class="samp">0:</span></samp>’ gets the
number ‘<samp><span class="samp">15</span></samp>’, and so on. Likewise the first definition of ‘<samp><span class="samp">1:</span></samp>’ gets
the number ‘<samp><span class="samp">1</span></samp>’ and its 15th definition gets ‘<samp><span class="samp">15</span></samp>’ as well.
</dl>
<p>So for example, the first <code>1:</code> may be named <code>.L1</code><kbd>C-B</kbd><code>1</code>, and
the 44th <code>3:</code> may be named <code>.L3</code><kbd>C-B</kbd><code>44</code>.
<h4 class="subheading">Dollar Local Labels</h4>
<p><a name="index-dollar-local-symbols-220"></a>
<code>as</code> also supports an even more local form of local labels called
dollar labels. These labels go out of scope (i.e., they become undefined) as
soon as a non-local label is defined. Thus they remain valid for only a small
region of the input source code. Normal local labels, by contrast, remain in
scope for the entire file, or until they are redefined by another occurrence of
the same local label.
<p>Dollar labels are defined in exactly the same way as ordinary local labels,
except that they have a dollar sign suffix to their numeric value, e.g.,
‘<samp><b>55$:</b></samp>’.
<p>They can also be distinguished from ordinary local labels by their transformed
names which use ASCII character ‘<samp><span class="samp">\001</span></samp>’ (control-A) as the magic character
to distinguish them from ordinary labels. For example, the fifth definition of
‘<samp><span class="samp">6$</span></samp>’ may be named ‘<samp><span class="samp">.L6</span><kbd>C-A</kbd><span class="samp">5</span></samp>’.
</body></html>
| {
"content_hash": "532bed2b2cf9dd83d6b2e21ca9816db6",
"timestamp": "",
"source": "github",
"line_count": 166,
"max_line_length": 232,
"avg_line_length": 57.933734939759034,
"alnum_prop": 0.7214307996256629,
"repo_name": "marduino/stm32Proj",
"id": "648d0814acd93cc7aefe92f6117ffe9a2c390e31",
"size": "9617",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tools/armgcc/share/doc/gcc-arm-none-eabi/html/as.html/Symbol-Names.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "23333"
},
{
"name": "C",
"bytes": "4470437"
},
{
"name": "C++",
"bytes": "655791"
},
{
"name": "HTML",
"bytes": "109"
},
{
"name": "Makefile",
"bytes": "10291"
}
],
"symlink_target": ""
} |
package com.facebook.nifty.client;
import com.facebook.nifty.core.NettyServerConfig;
import com.facebook.nifty.core.NiftySecurityHandlers;
public interface NiftyClientSecurityFactory
{
NiftySecurityHandlers getSecurityHandlers(int maxFrameSize, NettyClientConfig clientConfig);
}
| {
"content_hash": "864249978a2d1ec038f5022861b136af",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 96,
"avg_line_length": 28.7,
"alnum_prop": 0.8501742160278746,
"repo_name": "facebook/nifty",
"id": "97323a20326c24812feab532011b52643e4edda9",
"size": "889",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "nifty-client/src/main/java/com/facebook/nifty/client/NiftyClientSecurityFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "990123"
},
{
"name": "Thrift",
"bytes": "3860"
}
],
"symlink_target": ""
} |
let mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/login");
var usr_grupoSchemaJSON=new mongoose.Schema({
email:String ,
usuario:{type:mongoose.Schema.ObjectId,ref:"users"} ,//relacion usuario 1:M contactos
usr_grupo:{type:mongoose.Schema.ObjectId,ref:"usr_grupo"} ,//relacion grupo 1:M contactos
status:Number,//solicitud, autorizado
falta:Date
});
var mContacto = mongoose.model("contacto",usr_grupoSchemaJSON);
module.exports.mContacto=mContacto; | {
"content_hash": "2cc5733130bf77e4b62e4644812f4184",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 94,
"avg_line_length": 36.357142857142854,
"alnum_prop": 0.724950884086444,
"repo_name": "omiguelca/mensajeVisual",
"id": "a7df7e42bbc45d51278df804c6fce7cf7659d2d6",
"size": "509",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "models/contactos.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6656"
},
{
"name": "HTML",
"bytes": "8971"
},
{
"name": "JavaScript",
"bytes": "25434"
}
],
"symlink_target": ""
} |
import sys
if sys.platform == 'cli':
import clr
clr.AddReference('integrate')
from scipy__integrate__vode import *
| {
"content_hash": "4fbc6e0d7b6524fe17aa1686e259f030",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 40,
"avg_line_length": 16.25,
"alnum_prop": 0.6615384615384615,
"repo_name": "jasonmccampbell/scipy-refactor",
"id": "dc09f6ab84ad3025bf26023596ae5d7834002c28",
"size": "131",
"binary": false,
"copies": "53",
"ref": "refs/heads/refactor",
"path": "scipy/integrate/vode_clr.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "8030041"
},
{
"name": "C++",
"bytes": "22264450"
},
{
"name": "FORTRAN",
"bytes": "5883420"
},
{
"name": "Matlab",
"bytes": "32582"
},
{
"name": "Objective-C",
"bytes": "432"
},
{
"name": "Python",
"bytes": "6454690"
}
],
"symlink_target": ""
} |
tixastronauta/acc-ip
=============================
[](https://travis-ci.org/tixastronauta/acc-ip)
PHP 5 library to retrieve client's accurate IP Address
# Installing
Add this library as a composer dependency:
```
$ composer require tixastronauta/acc-ip
```
# Using
```php
require 'vendor/autoload.php'
use TixAstronauta\AccIp;
$accIp = new AccIp();
$ipAddress = $accIp->getIpAddress(); // this is the client's accurate IP Address. false on failure
```
# License
```
The MIT License (MIT)
Copyright (c) 2015 Tiago 'Tix' Carvalho
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
| {
"content_hash": "6b28753b292bc44e10e84ae6b99988ce",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 123,
"avg_line_length": 32.27450980392157,
"alnum_prop": 0.7612393681652491,
"repo_name": "tixastronauta/acc-ip",
"id": "84c8d15824c8857dd34b7fc8360e070ebdd24c8b",
"size": "1646",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "7143"
}
],
"symlink_target": ""
} |
<!--
@license Apache-2.0
Copyright (c) 2018 The Stdlib Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title></title>
<style>
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
</style>
<style>
body {
box-sizing: border-box;
width: 100%;
padding: 40px;
}
#console {
width: 100%;
}
</style>
</head>
<body>
<p id="status">Running...</p>
<br>
<div id="console"></div>
<script type="text/javascript">
(function() {
'use strict';
// VARIABLES //
var methods = [
'log',
'error',
'warn',
'dir',
'debug',
'info',
'trace'
];
// MAIN //
/**
* Main.
*
* @private
*/
function main() {
var console;
var str;
var el;
var i;
// FIXME: IE9 has a non-standard `console.log` object (http://stackoverflow.com/questions/5538972/console-log-apply-not-working-in-ie9)
console = window.console || {};
for ( i = 0; i < methods.length; i++ ) {
console[ methods[ i ] ] = write;
}
el = document.querySelector( '#console' );
str = el.innerHTML;
/**
* Writes content to a DOM element. Note that this assumes a single argument and no substitution strings.
*
* @private
* @param {string} message - message
*/
function write( message ) {
str += '<p>'+message+'</p>';
el.innerHTML = str;
}
}
main();
})();
</script>
<script type="text/javascript" src="/docs/api/latest/@stdlib/assert/is-nonnegative-number/test_bundle.js"></script>
</body>
</html>
| {
"content_hash": "c187e249616eb85301b28143bf3daea8",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 139,
"avg_line_length": 22.313333333333333,
"alnum_prop": 0.6229459217209441,
"repo_name": "stdlib-js/www",
"id": "4f10b8bb6675586de11cc86cdea95aacbb255a71",
"size": "3347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/docs/api/latest/@stdlib/assert/is-nonnegative-number/test.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "190538"
},
{
"name": "HTML",
"bytes": "158086013"
},
{
"name": "Io",
"bytes": "14873"
},
{
"name": "JavaScript",
"bytes": "5395746994"
},
{
"name": "Makefile",
"bytes": "40479"
},
{
"name": "Shell",
"bytes": "9744"
}
],
"symlink_target": ""
} |
package com.ryanmichela.sshd;
import org.bukkit.ChatColor;
import org.fusesource.jansi.Ansi;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.EnumMap;
import java.util.Map;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
public class ConsoleLogFormatter extends Formatter {
private SimpleDateFormat dateFormat;
public ConsoleLogFormatter() {
this.dateFormat = new SimpleDateFormat("HH:mm:ss");
}
public String format(LogRecord logrecord) {
try {
Class.forName("org.bukkit.craftbukkit.command.ColouredConsoleSender");
} catch (ClassNotFoundException ignored) {
// MEANS WE'RE ON PAPER/TACO/OTHER SHIT
colorize(logrecord);
}
StringBuilder stringbuilder = new StringBuilder();
stringbuilder.append(" [");
stringbuilder.append(this.dateFormat.format(logrecord.getMillis())).append(" ");
stringbuilder.append(logrecord.getLevel().getName()).append("]: ");
stringbuilder.append(this.formatMessage(logrecord));
stringbuilder.append('\n');
Throwable throwable = logrecord.getThrown();
if (throwable != null) {
StringWriter stringwriter = new StringWriter();
throwable.printStackTrace(new PrintWriter(stringwriter));
stringbuilder.append(stringwriter.toString());
}
return stringbuilder.toString();
}
private void colorize(LogRecord logrecord) {
// ORIGINAL CODE FROM org.bukkit.craftbukkit.command.ColouredConsoleSender
final Map<ChatColor, String> replacements = new EnumMap<>(ChatColor.class);
replacements
.put(ChatColor.BLACK, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).boldOff().toString());
replacements
.put(ChatColor.DARK_BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).boldOff().toString());
replacements.put(ChatColor.DARK_GREEN,
Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).boldOff().toString());
replacements
.put(ChatColor.DARK_AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).boldOff().toString());
replacements
.put(ChatColor.DARK_RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).boldOff().toString());
replacements.put(ChatColor.DARK_PURPLE,
Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).boldOff().toString());
replacements
.put(ChatColor.GOLD, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).boldOff().toString());
replacements.put(ChatColor.GRAY, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).boldOff().toString());
replacements
.put(ChatColor.DARK_GRAY, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLACK).bold().toString());
replacements.put(ChatColor.BLUE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.BLUE).bold().toString());
replacements.put(ChatColor.GREEN, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.GREEN).bold().toString());
replacements.put(ChatColor.AQUA, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.CYAN).bold().toString());
replacements.put(ChatColor.RED, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.RED).bold().toString());
replacements.put(ChatColor.LIGHT_PURPLE,
Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.MAGENTA).bold().toString());
replacements.put(ChatColor.YELLOW, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.YELLOW).bold().toString());
replacements.put(ChatColor.WHITE, Ansi.ansi().a(Ansi.Attribute.RESET).fg(Ansi.Color.WHITE).bold().toString());
replacements.put(ChatColor.MAGIC, Ansi.ansi().a(Ansi.Attribute.BLINK_SLOW).toString());
replacements.put(ChatColor.BOLD, Ansi.ansi().a(Ansi.Attribute.UNDERLINE_DOUBLE).toString());
replacements.put(ChatColor.STRIKETHROUGH, Ansi.ansi().a(Ansi.Attribute.STRIKETHROUGH_ON).toString());
replacements.put(ChatColor.UNDERLINE, Ansi.ansi().a(Ansi.Attribute.UNDERLINE).toString());
replacements.put(ChatColor.ITALIC, Ansi.ansi().a(Ansi.Attribute.ITALIC).toString());
replacements.put(ChatColor.RESET, Ansi.ansi().a(Ansi.Attribute.RESET).toString());
String result = logrecord.getMessage();
for (ChatColor color : ChatColor.values()) {
if (replacements.containsKey(color)) {
result = result.replaceAll("(?i)" + color.toString(), replacements.get(color));
} else {
result = result.replaceAll("(?i)" + color.toString(), "");
}
}
result += Ansi.ansi().reset().toString();
logrecord.setMessage(result);
}
}
| {
"content_hash": "8e7c5dad5f94057e70184ce3c8632339",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 120,
"avg_line_length": 49.2020202020202,
"alnum_prop": 0.6633134879901458,
"repo_name": "rmichela/Bukkit-SSHD",
"id": "4df169727835ed408db7df7dcef32309bf3d980d",
"size": "4909",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/ryanmichela/sshd/ConsoleLogFormatter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "50732"
}
],
"symlink_target": ""
} |
for i, force in pairs(game.forces) do
if force.technologies["advanced-material-processing"].researched then
force.recipes["alien-steel-plate"].enabled = true
end
if force.technologies["automation-2"].researched then
force.recipes["alien-steam-engine"].enabled = true
end
end | {
"content_hash": "308235396527226d78292f77e040c680",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 70,
"avg_line_length": 31.444444444444443,
"alnum_prop": 0.7667844522968198,
"repo_name": "renoth/factorio-alien-module",
"id": "e9192f1f76a304b567547a80172dd12072cff6f0",
"size": "283",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "alien-module/migrations/alien-module_1.0.1.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "35167"
}
],
"symlink_target": ""
} |
layout: page
title: Swift Blue Llc. Conference
date: 2016-05-24
author: Jean Gross
tags: weekly links, java
status: published
summary: Vivamus dictum massa ac orci aliquet dapibus. Interdum.
banner: images/banner/leisure-05.jpg
booking:
startDate: 06/09/2016
endDate: 06/10/2016
ctyhocn: DHNHSHX
groupCode: SBLC
published: true
---
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque porttitor feugiat lacus, non tristique orci rhoncus eu. Cras aliquam eros ut aliquam iaculis. Proin vehicula semper aliquet. Morbi dapibus sed turpis a sodales. Vivamus ultricies, ipsum quis sagittis convallis, lorem eros varius dui, at vestibulum leo dui et justo. Curabitur elementum neque sed nulla placerat condimentum. Duis feugiat risus risus, ac luctus nibh tristique vel.
1 Nunc pharetra tellus sed nunc commodo, ut condimentum dui faucibus
1 Integer quis ligula eleifend metus varius dictum.
Nullam condimentum non tortor sit amet ullamcorper. Donec nec sollicitudin dui. Suspendisse nec nisi a ligula ultrices gravida ac in augue. Cras risus dolor, consectetur laoreet accumsan ac, maximus sit amet neque. Cras vulputate mauris volutpat, lacinia purus in, pellentesque eros. Integer fringilla nibh nec arcu iaculis luctus. Sed blandit vulputate ex, et gravida felis fermentum eget. Aliquam vitae porttitor augue. Curabitur in nisi id arcu tincidunt hendrerit in non elit. Ut erat nulla, viverra sed sapien in, dignissim pellentesque sapien. Phasellus bibendum libero massa, vel aliquam enim commodo sed. Nulla auctor est dui, eu rutrum nibh porta sed.
| {
"content_hash": "dc2ea156bbd316d329e80f79a32e8616",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 660,
"avg_line_length": 76.33333333333333,
"alnum_prop": 0.8091079226450405,
"repo_name": "KlishGroup/prose-pogs",
"id": "9d469d9968221a1106db0b9bf70c8337fe01baed",
"size": "1607",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "pogs/D/DHNHSHX/SBLC/index.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package it.unitn.ing.rista.diffr.detector;
import it.unitn.ing.rista.diffr.*;
import it.unitn.ing.rista.awt.*;
import it.unitn.ing.rista.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* The TOFMultiDetector is a class
* <p/>
* Description
*
* @author Luca Lutterotti
* @version $Revision: 1.4 $, $Date: 2006/11/10 09:33:01 $
* @since JDK1.1
*/
public class TOFMultiDetector extends Detector {
public static String modelID = "Multi TOF detector";
public static String[] diclistc = {"_instrument_counter_bank_ID"};
public static String[] diclistcrm = {"_instrument_counter_bank_ID"};
protected static String[] classlistc = {"it.unitn.ing.rista.diffr.detector.TOFDetector"};
public static String[] classlistcs = {};
public TOFMultiDetector(XRDcat aobj, String alabel) {
super(aobj, alabel);
initXRD();
identifier = modelID;
IDlabel = modelID;
description = modelID;
}
public TOFMultiDetector(XRDcat aobj) {
this(aobj, modelID);
}
public TOFMultiDetector() {
identifier = modelID;
IDlabel = modelID;
description = modelID;
}
public void initConstant() {
Nstring = 0;
Nstringloop = 0;
Nparameter = 0;
Nparameterloop = 0;
Nsubordinate = 0;
Nsubordinateloop = 1;
}
public void initDictionary() {
for (int i = 0; i < totsubordinateloop; i++)
diclist[i] = diclistc[i];
System.arraycopy(diclistcrm, 0, diclistRealMeaning, 0, totsubordinateloop);
for (int i = 0; i < totsubordinateloop - totsubordinate; i++)
classlist[i] = classlistc[i];
for (int i = 0; i < totsubordinate - totparameterloop; i++)
classlists[i] = classlistcs[i];
}
public void initParameters() {
super.initParameters();
}
public int detectorsNumber() {
return numberofelementSubL(0);
}
public ListVector getDetectorList() {
return subordinateloopField[0];
}
public TOFDetector getDetector(int index) {
if (index >= 0 && index < detectorsNumber())
return (TOFDetector) getDetectorList().elementAt(index);
else
return null;
}
public TOFDetector addDetector() {
return (TOFDetector) addsubordinateloopField(0, new TOFDetector(this));
}
public TOFDetector addDetector(int index) {
if (index >= 0)
return (TOFDetector) addsubordinateloopField(0, new TOFDetector(this), index);
else
return addDetector();
}
public int getBankNumber(DiffrDataFile datafile) {
return datafile.getAngBankNumber();
}
public int getBankNumber(String bankID) {
// System.out.println("BankID from datafile: " + bankID);
for (int i = 0; i < detectorsNumber(); i++) {
// System.out.println("Detector: " + i + ": " + getDetector(i).getString(0));
if (getDetector(i).getString(0).equalsIgnoreCase(bankID))
return i;
}
return -1;
}
public double getThetaDetector(DiffrDataFile datafile, double twotheta) {
// System.out.println("Detector theta: " + getBankNumber(datafile) + " " + getDetector(getBankNumber(datafile)).getThetaDetector());
return (double) getDetector(getBankNumber(datafile)).getThetaDetector();
}
public double getEtaDetector(DiffrDataFile datafile) {
return (double) getDetector(getBankNumber(datafile)).getEtaDetector();
}
public void loadGemRotaxParameters(Frame aframe) {
String filename = Utility.browseFilename(aframe, "Choose the GEM-Rotax grouping file");
loadGemRotaxParameters(filename, true);
}
public void gemRotaxDropped(java.io.File[] files) {
boolean dropOld = true;
if (files != null && files.length > 0) {
if (files.length > 1)
dropOld = false;
for (int i = 0; i < files.length; i++) {
try {
loadGemRotaxParameters(files[i].getCanonicalPath(), dropOld);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void loadGemRotaxParameters(String filename, boolean dropOld) {
BufferedReader reader = Misc.getReader(filename);
if (reader != null) {
if (dropOld)
getDetectorList().removeAllItems();
try {
String token, tokenG;
String line;
StringTokenizer st;
line = reader.readLine();
line = Misc.removeUTF8BOM(line);
while (line != null) {
st = new StringTokenizer(line, " ,:\t\r\n");
token = st.nextToken();
token = st.nextToken();
token = st.nextToken();
int groupNumber = Integer.valueOf(tokenG = st.nextToken()).intValue();
double thetaAngle = Double.valueOf(token = st.nextToken()).doubleValue();
double etaAngle = Double.valueOf(token = st.nextToken()).doubleValue();
TOFDetector tofdetc = addDetector();
tofdetc.setTheta(thetaAngle);
tofdetc.setEta(etaAngle);
tofdetc.setString(0, "Group" + tokenG);
tofdetc.setLabel("Group" + tokenG);
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("Error in loading the grouping file!");
}
try {
reader.close();
} catch (IOException e) {
}
}
}
public JOptionsDialog getOptionsDialog(Frame parent) {
JOptionsDialog adialog = new TOFMultiDetector.JMultiBankTOFDetectorOptionsD(parent, this);
return adialog;
}
public class JMultiBankTOFDetectorOptionsD extends JOptionsDialog {
JSubordListPane detectorP;
public JMultiBankTOFDetectorOptionsD(Frame parent, XRDcat obj) {
super(parent, obj);
principalPanel.setLayout(new BorderLayout(6, 6));
detectorP = new JSubordListPane(this, false);
principalPanel.add(BorderLayout.CENTER, detectorP);
new FileDrop(principalPanel, new FileDrop.Listener() {
public void filesDropped(java.io.File[] files) {
// handle file drop
gemRotaxDropped(files);
} // end filesDropped
}); // end FileDrop.Listener
JPanel buttonP = new JPanel();
principalPanel.add(BorderLayout.NORTH, buttonP);
JButton loadB = new JButton("Load bank parameters (Gem-Rotax)");
buttonP.add(loadB);
loadB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
loadGemRotaxParameters(JMultiBankTOFDetectorOptionsD.this);
}
});
initParameters();
setTitle("Multi TOF detector characteristics");
pack();
}
public void initParameters() {
String labels[] = {"TOF theta angle (degrees):", "Eta angle (degrees):",
"Detector efficiency:", "Sample-detector distance (m):"};
detectorP.setList(TOFMultiDetector.this, 0, 4, labels);
}
public void retrieveParameters() {
detectorP.retrieveparlist();
}
}
}
| {
"content_hash": "0fa982f592e08f14158e93f645df448b",
"timestamp": "",
"source": "github",
"line_count": 241,
"max_line_length": 135,
"avg_line_length": 28.970954356846473,
"alnum_prop": 0.6506731595531366,
"repo_name": "luttero/Maud",
"id": "9df043011e48dd74cd3838d9564e594410a0fe7c",
"size": "7841",
"binary": false,
"copies": "1",
"ref": "refs/heads/version2",
"path": "src/it/unitn/ing/rista/diffr/detector/TOFMultiDetector.java",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "AGS Script",
"bytes": "114580"
},
{
"name": "CSS",
"bytes": "1270"
},
{
"name": "HTML",
"bytes": "10108"
},
{
"name": "Java",
"bytes": "15463899"
},
{
"name": "Objective-C",
"bytes": "103209"
},
{
"name": "Roff",
"bytes": "974"
}
],
"symlink_target": ""
} |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.connectopensource</groupId>
<artifactId>Production</artifactId>
<version>4.3.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>Common</artifactId>
<name>${project.artifactId}</name>
<packaging>pom</packaging>
<properties>
<skip.unpack>true</skip.unpack>
</properties>
<modules>
<module>Properties</module>
<module>CONNECTCoreLib</module>
<module>CONNECTCommonWeb</module>
</modules>
</project> | {
"content_hash": "633c7e40db060775707d89057182972c",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 204,
"avg_line_length": 39.1578947368421,
"alnum_prop": 0.6599462365591398,
"repo_name": "sailajaa/CONNECT",
"id": "b9dfcb1dd7a802d117d0eb5757fa5982cbf4d685",
"size": "744",
"binary": false,
"copies": "1",
"ref": "refs/heads/CONNECT_integration",
"path": "Product/Production/Common/pom.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "5539"
},
{
"name": "Groovy",
"bytes": "1641"
},
{
"name": "Java",
"bytes": "12552183"
},
{
"name": "Python",
"bytes": "773"
},
{
"name": "Shell",
"bytes": "14607"
},
{
"name": "XSLT",
"bytes": "35057"
}
],
"symlink_target": ""
} |
var EventEmitter = require('events').EventEmitter
, util = require('util')
, request = require('request').defaults({ jar: true });
var BasicRenderer = function() {};
util.inherits(BasicRenderer, EventEmitter);
BasicRenderer.prototype.render = function(url, actions, cookiejar) {
var renderer = this;
var conf = {url: url};
if (cookiejar) {
conf.jar = cookiejar;
}
request(conf, function (error, response, body) {
if (!error && response.statusCode == 200) {
renderer.emit('renderer.urlRendered', url, body);
} else if (error) {
this.emit('error', error);
}
});
}
module.exports = BasicRenderer;
| {
"content_hash": "3d9283e83f77c79d47f1148f5a3fd7b9",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 68,
"avg_line_length": 27.869565217391305,
"alnum_prop": 0.6536661466458659,
"repo_name": "ContentMine/thresher",
"id": "e99b9ceb8bdc754f9a4ab71ad7eecfd6faba6e29",
"size": "641",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/renderer/basic.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "491"
},
{
"name": "JavaScript",
"bytes": "191895"
}
],
"symlink_target": ""
} |
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://resources/cr_elements/icons.m.js';
import 'chrome://resources/cr_elements/shared_vars_css.m.js';
import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js';
import './strings.m.js';
import {I18nMixin} from 'chrome://resources/js/i18n_mixin.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';
import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {BrowserSwitchProxy, BrowserSwitchProxyImpl} from './browser_switch_proxy.js';
const MS_PER_SECOND: number = 1000;
enum LaunchError {
GENERIC_ERROR = 'genericError',
PROTOCOL_ERROR = 'protocolError',
}
const BrowserSwitchAppElementBase = I18nMixin(PolymerElement);
class BrowserSwitchAppElement extends BrowserSwitchAppElementBase {
static get is() {
return 'browser-switch-app';
}
static get template() {
return html`{__html_template__}`;
}
static get properties() {
return {
/**
* URL to launch in the alternative browser.
*/
url_: {
type: String,
value() {
return (new URLSearchParams(window.location.search)).get('url') || '';
},
},
/**
* Error message, or empty string if no error has occurred (yet).
*/
error_: {
type: String,
value: '',
},
/**
* Countdown displayed to the user, number of seconds until launching. If
* 0 or less, doesn't get displayed at all.
*/
secondCounter_: {
type: Number,
value: 0,
},
};
}
private url_: string;
private error_: string;
private secondCounter_: number;
/** @override */
connectedCallback() {
super.connectedCallback();
// If '?done=...' is specified in the URL, this tab was-reopened, or the
// entire browser was closed by LBS and re-opened. In that case, go to NTP
// instead.
const done = (new URLSearchParams(window.location.search)).has('done');
if (done) {
getProxy().gotoNewTabPage();
return;
}
// Sanity check the URL to make sure nothing really funky is going on.
const anchor = document.createElement('a');
anchor.href = this.url_;
if (!/^(file|http|https):$/.test(anchor.protocol)) {
this.error_ = LaunchError.PROTOCOL_ERROR;
return;
}
const milliseconds = loadTimeData.getInteger('launchDelay');
setTimeout(this.launchAndCloseTab_.bind(this), milliseconds);
this.startCountdown_(Math.floor(milliseconds / 1000));
}
private launchAndCloseTab_() {
// Mark this page with '?done=...' so that restoring the tab doesn't
// immediately re-trigger LBS.
history.pushState({}, '', '/?done=true');
getProxy().launchAlternativeBrowserAndCloseTab(this.url_).catch(() => {
this.error_ = LaunchError.GENERIC_ERROR;
});
}
private startCountdown_(seconds: number) {
this.secondCounter_ = seconds;
const intervalId = setInterval(() => {
this.secondCounter_--;
if (this.secondCounter_ <= 0) {
clearInterval(intervalId);
}
}, 1 * MS_PER_SECOND);
}
private computeTitle_(): string {
if (this.error_) {
return this.i18n('errorTitle', getBrowserName());
}
if (this.secondCounter_ > 0) {
return this.i18n('countdownTitle', this.secondCounter_, getBrowserName());
}
return this.i18n('openingTitle', getBrowserName());
}
private computeDescription_(): string {
if (this.error_) {
return this.i18n(
this.error_, getUrlHostname(this.url_), getBrowserName());
}
return this.i18n(
'description', getUrlHostname(this.url_), getBrowserName());
}
}
customElements.define(BrowserSwitchAppElement.is, BrowserSwitchAppElement);
function getBrowserName(): string {
return loadTimeData.getString('browserName');
}
function getUrlHostname(url: string): string {
const anchor = document.createElement('a');
anchor.href = url;
// Return entire url if parsing failed (which means the URL is bogus).
return anchor.hostname || url;
}
function getProxy(): BrowserSwitchProxy {
return BrowserSwitchProxyImpl.getInstance();
}
| {
"content_hash": "d523990066c63e547d7257157ddd10a3",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 100,
"avg_line_length": 28.873333333333335,
"alnum_prop": 0.6518125144308474,
"repo_name": "ric2b/Vivaldi-browser",
"id": "1a44751bc79920d10cd7bd8ce502771c3f98f5e4",
"size": "4331",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chromium/chrome/browser/resources/browser_switch/app.ts",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
'use strict';
class SecondaryHeading {
beforeRegister() {
this.is = 'secondary-heading';
this.properties = {
name: {
type: String
},
first: {
reflectToAttribute: true,
type: Boolean
}
};
}
created() { }
ready() { }
attached() { }
detached() { }
attributeChanged() { }
}
Polymer(SecondaryHeading);
| {
"content_hash": "4c6f0eb7b6a89f26df23b936448d3998",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 34,
"avg_line_length": 14.461538461538462,
"alnum_prop": 0.5292553191489362,
"repo_name": "JustinXinLiu/polymer-app-design",
"id": "38001e097dd4d1120ab5890306bd54b230845f45",
"size": "376",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/elements/secondary-heading/secondary-heading.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "650"
},
{
"name": "HTML",
"bytes": "82084"
},
{
"name": "JavaScript",
"bytes": "54205"
}
],
"symlink_target": ""
} |
{% extends "base.html" %}
{% block page_title %}<a href={% url 'mantises:detail-mantis' mantis.id %}>{{ mantis.name }}</a>'s Molt History{% endblock page_title %}
{% block content %}
{% if history %}
{% for molt in history %}
<div>
<a href="{% url 'mantises:edit-molt' molt.id %}">{{ molt.from_instar }} to {{ molt.to_instar }}</a>
</div>
{% endfor %}
{% else %}
<p>No molt history available.</p>
{% endif %}
{% endblock %} | {
"content_hash": "4c3b6450b1aa44b18a9892ce9b160141",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 136,
"avg_line_length": 27.529411764705884,
"alnum_prop": 0.5427350427350427,
"repo_name": "archen/mantistrack",
"id": "776de6a2dfc567dc46d8376ad899b23208781aff",
"size": "468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mantistrack/mantises/templates/mantises/molt_history.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3258"
},
{
"name": "JavaScript",
"bytes": "12461"
},
{
"name": "Python",
"bytes": "309698"
},
{
"name": "Shell",
"bytes": "5120"
}
],
"symlink_target": ""
} |
(function(){
'use strict';
var app = require('./app'),
config = require('./config');
// routes = require('./routes'),
// api = require('./routes/api'),
app.listen(config.port, function () {
console.log('Server started in ', config.env, ' mode, at port ', config.port);
});
// app.set('views', __dirname + '/views');
// app.set('view engine', 'jade');
// app.use(express.static(path.join(__dirname, 'public')));
// app.use(favicon(__dirname + '/app/favicon.ico'));
// serve index and view partials
// app.get('/', routes.index);
// app.get('/partials/:name', routes.partials);
// JSON API
// app.get('/api/name', api.name);
// redirect all others to the index (HTML5 history)
// app.get('*', routes.index);
})();
| {
"content_hash": "25a540fc3f2ad14fd71e3026409e625a",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 82,
"avg_line_length": 27.321428571428573,
"alnum_prop": 0.5803921568627451,
"repo_name": "ChefSocial/website-frontend",
"id": "749ece3b33ac67dd073c230829e23d6c426d20a7",
"size": "834",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/server.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "366"
},
{
"name": "HTML",
"bytes": "5130"
},
{
"name": "JavaScript",
"bytes": "7820"
}
],
"symlink_target": ""
} |
<div class="commune_descr limited">
<p>
Gentioux-Pigerolles est
un village
localisé dans le département de Creuse en Limousin. Elle totalisait 368 habitants en 2008.</p>
<p>Si vous pensez venir habiter à Gentioux-Pigerolles, vous pourrez facilement trouver une maison à acheter. </p>
<p>Le parc d'habitations, à Gentioux-Pigerolles, se décomposait en 2011 en 29 appartements et 328 maisons soit
un marché relativement équilibré.</p>
<p>À coté de Gentioux-Pigerolles sont localisées les communes de
<a href="{{VLROOT}}/immobilier/tarnac_19265/">Tarnac</a> localisée à 12 km, 331 habitants,
<a href="{{VLROOT}}/immobilier/villedieu_23264/">La Villedieu</a> à 10 km, 48 habitants,
<a href="{{VLROOT}}/immobilier/saint-yrieix-la-montagne_23249/">Saint-Yrieix-la-Montagne</a> à 11 km, 229 habitants,
<a href="{{VLROOT}}/immobilier/nouaille_23144/">La Nouaille</a> à 8 km, 250 habitants,
<a href="{{VLROOT}}/immobilier/royere-de-vassiviere_23165/">Royère-de-Vassivière</a> à 8 km, 576 habitants,
<a href="{{VLROOT}}/immobilier/beaumont-du-lac_87009/">Beaumont-du-Lac</a> localisée à 12 km, 155 habitants,
entre autres. De plus, Gentioux-Pigerolles est située à seulement 23 km de <a href="{{VLROOT}}/immobilier/aubusson_23008/">Aubusson</a>.</p>
<p>La ville propose quelques équipements sportifs, elle propose entre autres un terrain de sport et deux boucles de randonnée.</p>
</div>
| {
"content_hash": "1ba65c78943dd29944e42c9a89915e32",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 146,
"avg_line_length": 80.11111111111111,
"alnum_prop": 0.746879334257975,
"repo_name": "donaldinou/frontend",
"id": "deba4b861555ce737b313f76635c698e76fdaf24",
"size": "1468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Viteloge/CoreBundle/Resources/descriptions/23090.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3073"
},
{
"name": "CSS",
"bytes": "111338"
},
{
"name": "HTML",
"bytes": "58634405"
},
{
"name": "JavaScript",
"bytes": "88564"
},
{
"name": "PHP",
"bytes": "841919"
}
],
"symlink_target": ""
} |
"""
S. Van Hoey
2016-06-06
"""
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
from skimage.feature import canny
from skimage.segmentation import clear_border
from skimage.morphology import dilation, rectangle
from skimage.measure import regionprops
import cv2 as cv
from utils import (calculate_convexity,
calculate_circularity_reciprocal)
CHANNEL_CODE = {'blue': 0, 'green': 1, 'red': 2}
DEFAULT_FILTERS = {'circularity_reciprocal': {'min': 0.2, 'max': 1.6},
'convexity': {'min': 0.92}}
class NotAllowedChannel(Exception):
"""
Exception placeholder for easier debugging.
"""
pass
class Logger(object):
"""
Log the sequence of log statements performed
"""
def __init__(self):
self.log = []
def add_log(self, message):
"""add a log statement to the sequence"""
self.log.append(message)
def get_last_log(self):
return self.log[-1]
def print_log_sequence(self):
print("Steps undertaken since from raw image:")
print("\n".join(self.log))
print("\n")
def clear_log(self):
"""clear all the logs"""
self.log = []
def batchbubblekicker(data_path, channel, pipeline, *args):
"""
Given a folder with processable files and a channel to use, a sequence
of steps class as implemented in the pipelines.py file will be applied on
each of the individual images
:param data_path: folder containing images to process
:param channel: green | red | blue
:param pipeline: class from pipelines.py to use as processing sequence
:param args: arguments required by the pipeline
:return: dictionary with for each file the output binary image
"""
results = {}
for imgfile in os.listdir(data_path):
current_bubbler = pipeline(os.path.join(data_path, imgfile),
channel=channel)
results[imgfile] = current_bubbler.run(*args)
return results
class BubbleKicker(object):
def __init__(self, filename, channel='red'):
"""
This class contains a set of functions that can be applied to a
bubble image in order to derive a binary bubble-image and calculate the
statistics/distribution
:param filename: image file name
:param channel: green | red | blue
"""
self.raw_file = self._read_image(filename)
self.logs = Logger()
self._channel_control(channel)
self._channel = channel
self.raw_image = self.raw_file[:, :, CHANNEL_CODE[self._channel]]
self.current_image = self.raw_image.copy()
@staticmethod
def _read_image(filename):
"""read the image from a file and store
an RGB-image MxNx3
"""
image = cv.imread(filename)
return image
def reset_to_raw(self):
"""make the current image again the raw image"""
self.current_image = self.raw_image.copy()
self.logs.clear_log()
def switch_channel(self, channel):
"""change the color channel"""
self._channel_control(channel)
self._channel = channel
self.raw_image = self.raw_file[:, :, CHANNEL_CODE[self._channel]]
self.current_image = self.raw_image.copy()
self.logs.clear_log()
print("Currently using channel {}".format(self._channel))
def what_channel(self):
"""check the current working channel (R, G or B?)"""
print(self._channel)
@staticmethod
def _channel_control(channel):
"""check if channel is either red, green, blue"""
if channel not in ['red', 'green', 'blue']:
raise NotAllowedChannel('Not a valid channel for '
'RGB color scheme!')
def edge_detect_canny_opencv(self, threshold=[0.01, 0.5]):
"""perform the edge detection algorithm of Canny on the image using
the openCV package. Thresholds are respectively min and max threshodls for building
the gaussian."""
image = cv.Canny(self.current_image,
threshold[0],
threshold[1])
self.current_image = image
self.logs.add_log('edge-detect with thresholds {} -> {} '
'- opencv'.format(threshold[0], threshold[1]))
return image
def edge_detect_canny_skimage(self, sigma=3, threshold=[0.01, 0.5]):
"""perform the edge detection algorithm of Canny on the image using scikit package"""
image = canny(self.current_image,
sigma=sigma,
low_threshold=threshold[0],
high_threshold=threshold[1])
self.current_image = image
# append function to logs
self.logs.add_log('edge-detect with '
'thresholds {} -> {} and sigma {} '
'- skimage'.format(threshold[0],
threshold[1],
sigma))
return image
def adaptive_threshold_opencv(self, blocksize=91, cvalue=18):
"""
perform the edge detection algorithm of Canny on the image using an
adaptive threshold method for which the user can specify width of the
window of action and a C value used as reference for building
the gaussian distribution. This function uses the openCV package
Parameters
----------
blocksize:
cvalue:
"""
image = cv.adaptiveThreshold(self.current_image, 1,
cv.ADAPTIVE_THRESH_GAUSSIAN_C,
cv.THRESH_BINARY, blocksize, cvalue)
self.current_image = image
self.logs.add_log('adaptive threshold bubble detection '
'with blocksize {} and cvalue {} '
'- opencv'.format(blocksize, cvalue))
return image
def dilate_opencv(self, footprintsize=3):
"""perform the dilation of the image"""
# set up structuring element with footprintsize
kernel = np.ones((footprintsize, footprintsize), np.uint8)
# perform algorithm with given environment,
# store in same memory location
image = cv.dilate(self.current_image, kernel, iterations=1)
# update current image
self.current_image = image
# append function to logs
self.logs.add_log('dilate with footprintsize {} '
'- opencv'.format(footprintsize))
return image
def dilate_skimage(self):
"""perform the dilation of the image"""
# set up structuring element
# (@Giacomo, is (1, 90) and (1, 0) different? using rectangle here...
struct_env = rectangle(1, 1)
# perform algorithm with given environment,
# store in same memory location
image = dilation(self.current_image, selem=struct_env,
out=self.current_image)
# update current image
self.current_image = image
# append function to logs
self.logs.add_log('dilate - skimage')
return image
def fill_holes_opencv(self):
"""fill the holes of the image"""
# perform algorithm
h, w = self.current_image.shape[:2] # stores image sizes
mask = np.zeros((h + 2, w + 2), np.uint8)
# floodfill operates on the saved image itself
cv.floodFill(self.current_image, mask, (0, 0), 0)
# append function to logs
self.logs.add_log('fill holes - opencv')
return self.current_image
def clear_border_skimage(self, buffer_size=3, bgval=1):
"""clear the borders of the image using a belt of pixels definable in buffer_size and
asign a pixel value of bgval
Parameters
----------
buffer_size: int
indicates the belt of pixels around the image border that should be considered to
eliminate touching objects (default is 3)
bgvalue: int
all touching objects are set to this value (default is 1)
"""
# perform algorithm
image_inv = cv.bitwise_not(self.current_image)
image = clear_border(image_inv, buffer_size=buffer_size, bgval=bgval)
# update current image
self.current_image = image
# append function to logs
self.logs.add_log('clear border with buffer size {} and bgval {} '
'- skimage'.format(buffer_size, bgval))
return image
def erode_opencv(self, footprintsize=1):
"""erode detected edges with a given footprint. This function is meant to be used after dilation of the edges so to reset the original edge."""
kernel = np.ones((footprintsize, footprintsize), np.uint8)
image = cv.erode(self.current_image, kernel, iterations=1)
# update current image
self.current_image = image
# append function to logs
self.logs.add_log('erode with footprintsize {} '
'- opencv'.format(footprintsize))
return image
def what_have_i_done(self):
""" print the current log statements as a sequence of
performed steps"""
self.logs.print_log_sequence()
def plot(self):
"""plot the current image"""
fig, ax = plt.subplots()
ax.imshow(self.current_image, cmap=plt.cm.gray)
if len(self.logs.log) > 0:
ax.set_title(self.logs.log[-1])
return fig, ax
def _bubble_properties_table(binary_image):
"""provide a label for each bubble in the image"""
nbubbles, marker_image = cv.connectedComponents(1 - binary_image)
props = regionprops(marker_image)
bubble_properties = \
pd.DataFrame([{"label": bubble.label,
"area": bubble.area,
"centroid": bubble.centroid,
"convex_area": bubble.convex_area,
"equivalent_diameter": bubble.equivalent_diameter,
"perimeter": bubble.perimeter} for bubble in props])
bubble_properties["convexity"] = \
calculate_convexity(bubble_properties["perimeter"],
bubble_properties["area"])
bubble_properties["circularity_reciprocal"] = \
calculate_circularity_reciprocal(bubble_properties["perimeter"],
bubble_properties["area"])
bubble_properties = bubble_properties.set_index("label")
return nbubbles, marker_image, bubble_properties
def _bubble_properties_filter(property_table, id_image,
rules=DEFAULT_FILTERS):
"""exclude bubbles based on a set of rules
:return:
"""
bubble_props = property_table.copy()
all_ids = bubble_props.index.tolist()
for prop_name, ruleset in rules.items():
print(ruleset)
for rule, value in ruleset.items():
if rule == 'min':
bubble_props = \
bubble_props[bubble_props[prop_name] > value]
elif rule == 'max':
bubble_props = \
bubble_props[bubble_props[prop_name] < value]
else:
raise Exception("Rule not supported, "
"use min or max as filter")
removed_ids = [el for el in all_ids if el
not in bubble_props.index.tolist()]
for idb in removed_ids:
id_image[id_image == idb] = 0
return id_image, bubble_props
def bubble_properties_calculate(binary_image,
rules=DEFAULT_FILTERS):
"""
:param binary_image:
:param rules:
:return:
"""
# get the bubble identifications and properties
nbubbles, id_image, \
prop_table = _bubble_properties_table(binary_image)
# filter based on the defined rules
id_image, properties = _bubble_properties_filter(prop_table,
id_image, rules)
return id_image, properties
def bubble_properties_plot(property_table,
which_property="equivalent_diameter",
bins=20):
"""calculate and create the distribution plot"""
fontsize_labels = 14.
formatter = FuncFormatter(
lambda y, pos: "{:d}%".format(int(round(y * 100))))
fig, ax1 = plt.subplots()
ax1.hist(property_table[which_property], bins,
normed=0, cumulative=False, histtype='bar',
color='gray', ec='white')
ax1.get_xaxis().tick_bottom()
# left axis - histogram
ax1.set_ylabel(r'Frequency', color='gray',
fontsize=fontsize_labels)
ax1.spines['top'].set_visible(False)
# right axis - cumul distribution
ax2 = ax1.twinx()
ax2.hist(property_table[which_property],
bins, normed=1, cumulative=True,
histtype='step', color='k', linewidth= 3.)
ax2.yaxis.set_major_formatter(formatter)
ax2.set_ylabel(r'Cumulative percentage (%)', color='k',
fontsize=fontsize_labels)
ax2.spines['top'].set_visible(False)
ax2.set_ylim(0, 1.)
# additional options
ax1.set_xlim(0, property_table[which_property].max())
ax1.tick_params(axis='x', which='both', pad=10)
ax1.set_xlabel(which_property)
return fig, (ax1, ax2)
| {
"content_hash": "e6d8684fe3e72c6125ded133f2709e3e",
"timestamp": "",
"source": "github",
"line_count": 401,
"max_line_length": 151,
"avg_line_length": 34.51870324189526,
"alnum_prop": 0.5744834561479555,
"repo_name": "gbellandi/bubble_size_analysis",
"id": "6fe8a2134cb82f89b2a84bf203354a1a0036efac",
"size": "13842",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bubblekicker/bubblekicker.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "7791668"
},
{
"name": "Python",
"bytes": "19343"
}
],
"symlink_target": ""
} |
package turksem.util
import scala.collection.immutable.SortedSet
// basic, inefficient immutable union-find based on sets
class SetUnionFind[A] private (
val sets: Set[SortedSet[A]])(
implicit ord: Ordering[A]) {
def add(a: A): SetUnionFind[A] =
if(sets.forall(!_.contains(a))) new SetUnionFind(sets + SortedSet[A](a))
else this
def find(a: A) = for {
subset <- sets.find(_.contains(a))
} yield subset.head
def union(a: A, b: A): Option[SetUnionFind[A]] = for {
aSet <- sets.find(_.contains(a))
bSet <- sets.find(_.contains(b))
} yield if(aSet != bSet) { // TODO should be by reference for efficiency
new SetUnionFind(sets - aSet - bSet + (aSet ++ bSet))
} else this
def representatives: Set[A] = sets.map(_.head)
}
object SetUnionFind {
def empty[A](implicit ord: Ordering[A]): SetUnionFind[A] =
new SetUnionFind(Set[SortedSet[A]]())
}
| {
"content_hash": "6cd8424ad5a79a6e29be27829e4bbdf9",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 76,
"avg_line_length": 29.9,
"alnum_prop": 0.6555183946488294,
"repo_name": "julianmichael/mturk-semantics",
"id": "65957ef810560ebc89120d8ab15ad7dea7d5e826",
"size": "897",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "turksem/shared/src/main/scala/turksem/util/SetUnionFind.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2101"
},
{
"name": "Scala",
"bytes": "478749"
},
{
"name": "Shell",
"bytes": "5678"
}
],
"symlink_target": ""
} |
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.Objects.DataClasses;
namespace Cats.Models.Hubs.MetaModels
{
public sealed class CommoditySourceMetaModel
{
[Required(ErrorMessage="Commodity Source is required")]
public Int32 CommoditySourceID { get; set; }
[Required(ErrorMessage="Name is required")]
[StringLength(50)]
public String Name { get; set; }
public EntityCollection<ReceiptAllocation> ReceiptAllocations { get; set; }
public EntityCollection<Receive> Receives { get; set; }
}
}
| {
"content_hash": "909e5acad2cf51e06d7cb05b400491da",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 81,
"avg_line_length": 23.92,
"alnum_prop": 0.7324414715719063,
"repo_name": "ndrmc/cats",
"id": "513414aca74c9afac58a829d08a898063898bdff",
"size": "598",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Models/Cats.Models.Hub/MetaModels/CommoditySourceMetaModel.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "23179"
},
{
"name": "Batchfile",
"bytes": "220"
},
{
"name": "C#",
"bytes": "17077194"
},
{
"name": "CSS",
"bytes": "1272649"
},
{
"name": "HTML",
"bytes": "1205906"
},
{
"name": "JavaScript",
"bytes": "4300261"
},
{
"name": "PLpgSQL",
"bytes": "10605"
},
{
"name": "SQLPL",
"bytes": "11550"
},
{
"name": "Smalltalk",
"bytes": "10"
}
],
"symlink_target": ""
} |
/*
* Adapter for requesting bids from RTK Aardvark
* To request an RTK Aardvark Header bidding account
* or for additional integration support please contact [email protected]
*/
var utils = require('src/utils.js');
var bidfactory = require('src/bidfactory.js');
var bidmanager = require('src/bidmanager.js');
var adloader = require('src/adloader.js');
var Adapter = require('src/adapter.js').default;
var constants = require('src/constants.json');
var adaptermanager = require('src/adaptermanager');
const AARDVARK_CALLBACK_NAME = 'aardvarkResponse';
const AARDVARK_REQUESTS_MAP = 'aardvarkRequests';
const AARDVARK_BIDDER_CODE = 'aardvark';
const DEFAULT_REFERRER = 'thor.rtk.io';
const DEFAULT_ENDPOINT = 'thor.rtk.io';
var endpoint = DEFAULT_ENDPOINT;
function requestBids(bidderCode, callbackName, bidReqs) {
var ref = utils.getTopWindowLocation();
var ai = '';
const scs = [];
const bidIds = [];
ref = ref ? ref.host : DEFAULT_REFERRER;
for (var i = 0, l = bidReqs.length, bid, _ai, _sc, _endpoint; i < l; i += 1) {
bid = bidReqs[i];
_ai = utils.getBidIdParameter('ai', bid.params);
_sc = utils.getBidIdParameter('sc', bid.params);
if (!_ai || !_ai.length || !_sc || !_sc.length) { continue; }
_endpoint = utils.getBidIdParameter('host', bid.params);
if (_endpoint) { endpoint = _endpoint; }
if (!ai.length) { ai = _ai; }
if (_sc) { scs.push(_sc); }
bidIds.push(_sc + '=' + bid.bidId);
// Create the bidIdsMap for easier mapping back later
$$PREBID_GLOBAL$$[AARDVARK_REQUESTS_MAP][bidderCode][bid.bidId] = bid;
}
if (!ai.length || !scs.length) { return utils.logWarn('Bad bid request params given for adapter $' + bidderCode + ' (' + AARDVARK_BIDDER_CODE + ')'); }
adloader.loadScript([
'//' + endpoint + '/', ai, '/', scs.join('_'),
'/aardvark/?jsonp=$$PREBID_GLOBAL$$.', callbackName,
'&rtkreferer=', ref, '&', bidIds.join('&')
].join(''));
}
function registerBidResponse(bidderCode, rawBidResponse) {
if (rawBidResponse.error) { return utils.logWarn('Aardvark bid received with an error, ignoring... [' + rawBidResponse.error + ']'); }
if (!rawBidResponse.cid) { return utils.logWarn('Aardvark bid received without a callback id, ignoring...'); }
var bidObj = $$PREBID_GLOBAL$$[AARDVARK_REQUESTS_MAP][bidderCode][rawBidResponse.cid];
if (!bidObj) { return utils.logWarn('Aardvark request not found: ' + rawBidResponse.cid); }
if (bidObj.params.sc !== rawBidResponse.id) { return utils.logWarn('Aardvark bid received with a non matching shortcode ' + rawBidResponse.id + ' instead of ' + bidObj.params.sc); }
var bidResponse = bidfactory.createBid(constants.STATUS.GOOD, bidObj);
bidResponse.bidderCode = bidObj.bidder;
bidResponse.cpm = rawBidResponse.cpm;
bidResponse.ad = rawBidResponse.adm + utils.createTrackPixelHtml(decodeURIComponent(rawBidResponse.nurl));
bidResponse.width = bidObj.sizes[0][0];
bidResponse.height = bidObj.sizes[0][1];
bidmanager.addBidResponse(bidObj.placementCode, bidResponse);
$$PREBID_GLOBAL$$[AARDVARK_REQUESTS_MAP][bidderCode][rawBidResponse.cid].responded = true;
}
function registerAardvarkCallback(bidderCode, callbackName) {
$$PREBID_GLOBAL$$[callbackName] = function(rtkResponseObj) {
rtkResponseObj.forEach(function(bidResponse) {
registerBidResponse(bidderCode, bidResponse);
});
for (var bidRequestId in $$PREBID_GLOBAL$$[AARDVARK_REQUESTS_MAP][bidderCode]) {
if ($$PREBID_GLOBAL$$[AARDVARK_REQUESTS_MAP][bidderCode].hasOwnProperty(bidRequestId)) {
var bidRequest = $$PREBID_GLOBAL$$[AARDVARK_REQUESTS_MAP][bidderCode][bidRequestId];
if (!bidRequest.responded) {
var bidResponse = bidfactory.createBid(constants.STATUS.NO_BID, bidRequest);
bidResponse.bidderCode = bidRequest.bidder;
bidmanager.addBidResponse(bidRequest.placementCode, bidResponse);
}
}
}
};
}
const AardvarkAdapter = function() {
var baseAdapter = new Adapter(AARDVARK_BIDDER_CODE);
$$PREBID_GLOBAL$$[AARDVARK_REQUESTS_MAP] = $$PREBID_GLOBAL$$[AARDVARK_REQUESTS_MAP] || {};
baseAdapter.callBids = function (params) {
const bidderCode = baseAdapter.getBidderCode();
var callbackName = AARDVARK_CALLBACK_NAME;
if (bidderCode !== AARDVARK_BIDDER_CODE) { callbackName = [AARDVARK_CALLBACK_NAME, bidderCode].join('_'); }
$$PREBID_GLOBAL$$[AARDVARK_REQUESTS_MAP][bidderCode] = {};
registerAardvarkCallback(bidderCode, callbackName);
return requestBids(bidderCode, callbackName, params.bids || []);
};
return {
callBids: baseAdapter.callBids,
setBidderCode: baseAdapter.setBidderCode
};
};
adaptermanager.registerBidAdapter(new AardvarkAdapter(), 'aardvark');
module.exports = AardvarkAdapter;
| {
"content_hash": "18aa17ff3af7b7858f3bb0a1e278d643",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 183,
"avg_line_length": 38.483870967741936,
"alnum_prop": 0.6950963956412406,
"repo_name": "LiranMotola/Prebid.js",
"id": "27c5b6a23b5f7c2e986d64c85c6bfb5519b9e65a",
"size": "4772",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/aardvarkBidAdapter.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "165450"
},
{
"name": "JavaScript",
"bytes": "1507273"
}
],
"symlink_target": ""
} |
const argv = require('minimist')(process.argv.slice(2));
const cors = require('./amp-cors');
const pc = process;
const fs = require('fs');
const multer = require('multer');
const recaptchaRouter = require('express').Router();
const upload = multer();
const recaptchaMock = `
window.grecaptcha = {
ready: (callback) => callback(),
execute: () => Promise.resolve('recaptcha-mock')
};
`;
const recaptchaFrameRequestHandler = (req, res, next) => {
if (argv._.includes('unit') || argv._.includes('integration')) {
fs.promises.readFile(pc.cwd() + req.path, 'utf8').then((file) => {
file = file.replace(
/initRecaptcha\(.*\)/g,
'initRecaptcha("/recaptcha/mock.js?sitekey=")'
);
res.end(file);
});
} else {
next();
}
};
recaptchaRouter.get('/mock.js', (req, res) => {
res.end(recaptchaMock);
});
recaptchaRouter.post('/submit', upload.array(), (req, res) => {
cors.enableCors(req, res);
const responseJson = {
message: 'Success!',
};
Object.keys(req.body).forEach((bodyKey) => {
responseJson[bodyKey] = req.body[bodyKey];
});
const containsRecaptchaInResponse = Object.keys(responseJson).some(
(responseJsonKey) => {
return responseJsonKey.toLowerCase().includes('recaptcha');
}
);
if (containsRecaptchaInResponse) {
res.status(200).json(responseJson);
} else {
res.status(400).json({
message: 'Did not include a recaptcha token',
});
}
});
module.exports = {
recaptchaFrameRequestHandler,
recaptchaRouter,
};
| {
"content_hash": "226da48a3afd1cf973ebf9c004058577",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 70,
"avg_line_length": 23.272727272727273,
"alnum_prop": 0.6302083333333334,
"repo_name": "zhouyx/amphtml",
"id": "9f4946b09abe43b00de30b8d5d2f373b7e4d7198",
"size": "2163",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "build-system/server/recaptcha-router.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "824411"
},
{
"name": "CSS",
"bytes": "507630"
},
{
"name": "Go",
"bytes": "7443"
},
{
"name": "HTML",
"bytes": "2228745"
},
{
"name": "Java",
"bytes": "863928"
},
{
"name": "JavaScript",
"bytes": "17517371"
},
{
"name": "Python",
"bytes": "74492"
},
{
"name": "Shell",
"bytes": "19697"
},
{
"name": "Starlark",
"bytes": "16650"
},
{
"name": "Yacc",
"bytes": "23470"
}
],
"symlink_target": ""
} |
from setuptools import setup, find_packages
readme = open('README.txt').read()
setup(
name='matchtools',
version='0.1',
author='Russell J. Funk and Julian Katz-Samuels',
author_email='[email protected]',
license='',
description='Package that provides data-cleaning tools.',
long_description=open('README.txt').read(),
packages=['matchtools'],
) | {
"content_hash": "a658afb856fc0a0765a1c749828f7cce",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 61,
"avg_line_length": 30.833333333333332,
"alnum_prop": 0.6837837837837838,
"repo_name": "jkatzsam/matchtools",
"id": "e18c6bf642cb399b2fd80e42a1feefcb93bf0d3e",
"size": "370",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "setup.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "4124"
}
],
"symlink_target": ""
} |
package monix.reactive.internal.operators
import monix.execution.exceptions.DummyException
import monix.reactive.Observable
import scala.concurrent.duration.Duration.Zero
import scala.concurrent.duration._
import scala.util.Failure
object MapAccumulateSuite extends BaseOperatorSuite {
def createObservable(sourceCount: Int) = Some {
val o = Observable
.range(0L, sourceCount.toLong)
.mapAccumulate(0L)((acc, elem) => (acc + elem, acc * elem))
Sample(o, count(sourceCount), sum(sourceCount), Zero, Zero)
}
def count(sourceCount: Int) =
sourceCount
def observableInError(sourceCount: Int, ex: Throwable) = Some {
val o = createObservableEndingInError(Observable.range(0L, sourceCount.toLong), ex)
.mapAccumulate(0L)((acc, elem) => (acc + elem, acc * elem))
Sample(o, count(sourceCount), sum(sourceCount), Zero, Zero)
}
def sum(sourceCount: Int) = {
(0 until sourceCount)
.map(c => (0 until c).map(_.toLong).sum * c.toLong)
.sum
}
def brokenUserCodeObservable(sourceCount: Int, ex: Throwable) = Some {
val o = Observable.range(0L, sourceCount.toLong).mapAccumulate(0L) { (acc, elem) =>
if (elem == sourceCount - 1)
throw ex
else
(acc + elem, acc * elem)
}
Sample(o, count(sourceCount - 1), sum(sourceCount - 1), Zero, Zero)
}
override def cancelableObservables() = {
val sample = Observable
.range(1, 100)
.delayOnNext(1.second)
.mapAccumulate(0L)((acc, elem) => (acc + elem, acc * elem))
Seq(Sample(sample, 0, 0, 0.seconds, 0.seconds))
}
test("should trigger error if the initial state triggers errors") { implicit s =>
val ex = DummyException("dummy")
val obs = Observable(1, 2, 3, 4).mapAccumulate[Int, Int](throw ex)((acc, elem) => (acc + elem, acc * elem))
val f = obs.runAsyncGetFirst; s.tick()
assertEquals(f.value, Some(Failure(ex)))
}
}
| {
"content_hash": "c44750d07f2677ecab913da31ecff64f",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 111,
"avg_line_length": 30.967741935483872,
"alnum_prop": 0.6630208333333333,
"repo_name": "alexandru/monifu",
"id": "e5318e0a34628f9bab037646ac12606db67be7dc",
"size": "2593",
"binary": false,
"copies": "1",
"ref": "refs/heads/series/3.x",
"path": "monix-reactive/shared/src/test/scala/monix/reactive/internal/operators/MapAccumulateSuite.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "1366167"
}
],
"symlink_target": ""
} |
if [[ -z "$1" ]]; then it=20; else it=$1; fi
rm -r *.bak representatives*.csv *.gv candidates_representatives* *lvl1* problem points_representatives*.csv *rprtmp*
itm1=$(( $it - 1 ))
echo "git add segments.csv points_segments.csv patches.csv points_primitives.csv primitives_it${it}.bonmin.csv points_primitives_it$itm1.csv run.log" | {
"content_hash": "860ebb05815706143c2cd0b919292ca3",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 149,
"avg_line_length": 66.6,
"alnum_prop": 0.7237237237237237,
"repo_name": "NUAAXXY/globOpt",
"id": "a10c8297fa745caaada97f65786830c5e387528d",
"size": "345",
"binary": false,
"copies": "2",
"ref": "refs/heads/spatially_smooth",
"path": "RAPter/scripts/cleanupFolder.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "79972"
},
{
"name": "C++",
"bytes": "1358703"
},
{
"name": "CMake",
"bytes": "31244"
},
{
"name": "CSS",
"bytes": "950"
},
{
"name": "Gnuplot",
"bytes": "518"
},
{
"name": "HTML",
"bytes": "35161"
},
{
"name": "M",
"bytes": "353"
},
{
"name": "Mathematica",
"bytes": "2707"
},
{
"name": "Matlab",
"bytes": "96797"
},
{
"name": "Objective-C",
"bytes": "250"
},
{
"name": "Python",
"bytes": "132051"
},
{
"name": "Shell",
"bytes": "108272"
},
{
"name": "TeX",
"bytes": "27525"
}
],
"symlink_target": ""
} |
(function (global, exports) {
'use strict';
exports.testExtraShouldReturnFive = function () {
return 5;
};
exports.testExtraShouldCallToRuntime = function() {
return exports.runtime(3);
};
})
| {
"content_hash": "dd1e7ff3d02a1524f472491c6bff9a81",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 53,
"avg_line_length": 21.1,
"alnum_prop": 0.6682464454976303,
"repo_name": "dawangjiaowolaixunshan/runtime",
"id": "829ddee01a4c140aacbfa9ca4969daae9ad7929d",
"size": "379",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "deps/v8/test/cctest/test-extra.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "29659"
},
{
"name": "C",
"bytes": "853"
},
{
"name": "C++",
"bytes": "2139966"
},
{
"name": "JavaScript",
"bytes": "508976"
},
{
"name": "Python",
"bytes": "6276"
},
{
"name": "Shell",
"bytes": "3888"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "1e4d3e5ca60633fcba1aa7ba4ebbba63",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "54ee0f8de23c3fa70f6e285d93d9ceb9181e9c73",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Violaceae/Viola/Viola vivariensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package taglib
import (
"fmt"
"os"
"strings"
_ "testing"
)
func ExampleDecode() {
f, err := os.Open("testdata/BeatThee.mp3")
if err != nil {
panic(err)
}
fi, err := f.Stat()
if err != nil {
panic(err)
}
tag, err := Decode(f, fi.Size())
if err != nil {
panic(err)
}
fmt.Println("Title:", strings.TrimSpace(tag.Title()))
fmt.Println("Artist:", strings.TrimSpace(tag.Artist()))
fmt.Println("Album:", strings.TrimSpace(tag.Album()))
fmt.Println("Track:", tag.Track())
// Output:
// Title: Beat Thee
// Artist: Alexander Nakarada
// Album: Complete Discography (CC BY Attribution 4.0)
// Track: 189
}
| {
"content_hash": "d28647d5e24945ce4d8b96d40ad6611c",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 56,
"avg_line_length": 18.470588235294116,
"alnum_prop": 0.6273885350318471,
"repo_name": "hjfreyer/taglib-go",
"id": "ce20d76b18e78e28f7f36adad3e90435d7b2f050",
"size": "1238",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "taglib/taglib_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "24204"
}
],
"symlink_target": ""
} |
As of this version release notes can be found at [Releases](https://github.com/DominicTobias/universal-react/releases)
#### 1.0.0-rc1
- Hot reloading for reducers
- Stop app errors during server-side render from being silently swallowed in a promise
- `readyOnActions` returns a Promise which simplifies calling code
- Use Object.assign babel plugin
- Remove cruft/simplify
- Removed mocking in preference for having a real mock api
- Removed css/file loaders as they were too opinionated and not MVP
- Refactored app config so it's not a shared global but a shared import
- Use `componentDidMount` for `readyOnAction` calling as `componentWillMount` can leave the store in a half-way state when sent to the client
#### 1.0.0-beta
- Use Redux, the simplicity was nice but to scale a central store to dispatch to makes good sense.
- Shared app config.
- Data mocking.
- Upgrade to Babel6, react-router2
#### 0.2.3
- Make bundle path absolute so it works for deep urls
#### 0.2.2
- Fixed server so that is uses babel-core instead of babel (which is deprecated and also not delcared as a dep)
#### 0.2.1
- Minor cleanup of some now unused code and put utils in one file
#### 0.2.0
- Use react-helmet to manage title and meta (instead of custom)
#### 0.1.1
- Fix wrong error route handler (was using 404)
#### 0.1.0
- Initial release
| {
"content_hash": "9183722e2cf6f728c2107fdabec46fd9",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 142,
"avg_line_length": 31.022727272727273,
"alnum_prop": 0.7326007326007326,
"repo_name": "rhoffmann8/redux-jaca",
"id": "54eb8ad75a2d0a3fa84b293dc91f6f45232f519b",
"size": "1383",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "CHANGELOG.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4692"
},
{
"name": "HTML",
"bytes": "305"
},
{
"name": "JavaScript",
"bytes": "28678"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.ResourceManager.Compute.Models
{
public partial class GalleryList
{
internal static GalleryList DeserializeGalleryList(JsonElement element)
{
IReadOnlyList<Gallery> value = default;
string nextLink = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("value"))
{
List<Gallery> array = new List<Gallery>();
foreach (var item in property.Value.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.Null)
{
array.Add(null);
}
else
{
array.Add(Gallery.DeserializeGallery(item));
}
}
value = array;
continue;
}
if (property.NameEquals("nextLink"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
nextLink = property.Value.GetString();
continue;
}
}
return new GalleryList(value, nextLink);
}
}
}
| {
"content_hash": "627d3c1930d5a9588808596897c90350",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 79,
"avg_line_length": 33.111111111111114,
"alnum_prop": 0.43087248322147653,
"repo_name": "stankovski/azure-sdk-for-net",
"id": "a648fe88a5a4723bcfe0b29cead53de0aab83824",
"size": "1628",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/compute/Azure.ResourceManager.Compute/src/Generated/Models/GalleryList.Serialization.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "33972632"
},
{
"name": "Cucumber",
"bytes": "89597"
},
{
"name": "Shell",
"bytes": "675"
}
],
"symlink_target": ""
} |
/* PYRO's amazing stylesheet v1.0 */
* {margin: 0; padding:0;}
html, body {height: 100%; }
body {width:100%; background: white; font-size: 100%;
font-family: Arial, sans-serif;}
h1, h2, h3, h4, p {padding: 0 0 20px 0;}
a {text-decoration: none; color: #999; transition: color 2s linear; -moz-transition: color 2s linear; -webkit-transition: color 2s linear; -o-transition: color 2s linear;
}
a:hover {color:#333;}
.float-left {float: left;}
.float-right {float: right;}
.clear{clear: both;}
.section {padding: 0 20px;}
.section:first-child {padding-top: 0;}
.section:last-child {padding-bottom: 0;}
.button {margin: 10px 0;}
.button {
padding:5px 10px;
border: 1px solid gray;
font-weight: bold;
color: white;
background-color: #ff6100;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
box-shadow: gray 2px 2px 5px;
-moz-box-shadow: gray 2px 2px 5px;
-webkit-box-shadow: gray 2px 2px 5px;
-o-box-shadow: gray 2px 2px 5px;
transition: background 0.25s linear;
-moz-transition: background 0.25s linear;
-webkit-transition: background 0.25s linear;
-o-transition: background 0.25s linear;
}
.button:hover {background: orange; color: white;}
.button a, .button a:hover {display: block; color: white; width: 100%;}
#container {
min-width: 950px;
min-height: 100%;
position: relative;
}
#pyro-main {
overflow:auto;
padding-bottom: 35px; /* must be same height as the footer */
}
header {height: 125px; position: relative; margin: 0;}
header h1 {font-family: 'Sigmar One', sans-serif; font-size: 3em; font-weight: bold; color: #222; text-shadow: 0 0 4px white, 0 -5px 4px #FF3, 2px -10px 6px #FD3, -2px -15px 11px #F80, 2px -25px 18px #F20; position: absolute; bottom: 10px; padding-bottom: 0;}
header h1 span {display: inline-block; width:250px; font-family: Arial, sans-serif; font-size: 0.33em; /*color: #333;*/ font-weight: normal; text-shadow: 0px 1px 2px #999; -moz-text-shadow: 0px 1px 2px #999; -webkit-text-shadow: 0px 1px 2px #999;}
aside {width: 83px; margin: 0 20px 0 0;}
aside ul {/*width: 180px;*/}
aside ul li {margin: 11px 0; cursor: pointer;}
aside ul li:first-child {margin: 0 0 11px 0;}
aside ul li:last-child {margin: 11px 0 0 0;}
aside ul li a {color: #666;}
aside ul li a:hover {color: #333;}
aside .large.button {width: 90px; height:90px; position: relative; padding:0; list-style: none;}
aside .large.button a {display: block; text-align: center; line-height: 1.5; position:absolute;}
li#about a {margin-top: 35px;}
li#regrow a {margin-top: 25px;}
li#randomize a {margin-top: 25px;}
li#burn a {margin-top: 25px;}
#canvasDiv, canvas {width: 800px;}
canvas {margin: 0px 0px 20px 0px;}
#myCanvas {
height: 400px;
text-align: center;
border: 1px solid gray;
border-radius: 5px;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
box-shadow: gray 2px 2px 5px;
-moz-box-shadow: gray 2px 2px 5px;
-webkit-box-shadow: gray 2px 2px 5px;
-o-box-shadow: gray 2px 2px 5px;
background: white;
position: relative;
}
footer {
position: relative;
margin-top: -35px; /* negative value of footer height */
height: 35px;
clear:both;
}
footer p {color: #333; text-shadow: 0px 1px 2px #999; -moz-text-shadow: 0px 1px 2px #999; -webkit-text-shadow: 0px 1px 2px #999;}
footer a {color: gray;}
/* GitHub Ribbon styles */
#github-ribbon {position: absolute; top: 0; right: 0; border: 0;}
/* Modal Styles */
.modal.button {width:100px !important;}
.modal.button a {color: white; font-weight: bold; text-align: center; width:100px !important;}
/*Opera Fix for Sticky Footer - https://www.cssstickyfooter.com */
body:before {/* thanks to Maleika (Kohoutec)*/
content:"";
height:100%;
float:left;
width:0;
margin-top:-32767px;/* thank you Erik J - negate effect of float*/
}
| {
"content_hash": "3feaab78a0f7252d82dd7050d8631fa0",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 260,
"avg_line_length": 30.51219512195122,
"alnum_prop": 0.69597655209166,
"repo_name": "ystvns/ystvns.github.io",
"id": "7d0596dbc5fd8c7f1388b5405d95d70145f6cacc",
"size": "3753",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "css/pyro/style.css",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "72696"
},
{
"name": "CoffeeScript",
"bytes": "9750"
},
{
"name": "HTML",
"bytes": "27275"
},
{
"name": "JavaScript",
"bytes": "16808"
},
{
"name": "Ruby",
"bytes": "1349"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>coqoban: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.10.1 / coqoban - 8.7.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
coqoban
<small>
8.7.0
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-05-31 21:01:11 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-05-31 21:01:11 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-threads base
base-unix base
conf-findutils 1 Virtual package relying on findutils
coq 8.10.1 Formal proof management system
num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.09.1 The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.1 Official release 4.09.1
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.3 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "[email protected]"
homepage: "https://github.com/coq-contribs/coqoban"
license: "LGPL 2.1"
build: [make "-j%{jobs}%"]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Coqoban"]
depends: [
"ocaml"
"coq" {>= "8.7" & < "8.8~"}
]
tags: [ "keyword: Sokoban" "keyword: puzzles" "category: Miscellaneous/Logical Puzzles and Entertainment" "date: 2003-09-19" ]
authors: [ "Jasper Stein" ]
bug-reports: "https://github.com/coq-contribs/coqoban/issues"
dev-repo: "git+https://github.com/coq-contribs/coqoban.git"
synopsis: "Coqoban (Sokoban)"
description: """
A Coq implementation of Sokoban, the Japanese warehouse
keepers' game"""
flags: light-uninstall
url {
src: "https://github.com/coq-contribs/coqoban/archive/v8.7.0.tar.gz"
checksum: "md5=b18a3858f5d9c346d28eca093a4d3b2d"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-coqoban.8.7.0 coq.8.10.1</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.10.1).
The following dependencies couldn't be met:
- coq-coqoban -> coq < 8.8~ -> ocaml < 4.06.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-coqoban.8.7.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "63451ca884814c0bed445608efa2527c",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 166,
"avg_line_length": 41.05487804878049,
"alnum_prop": 0.5379474231397594,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "eb2268ae8619523892f4c49443dd90bc017ab787",
"size": "6758",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.09.1-2.0.6/released/8.10.1/coqoban/8.7.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="4M459H2KSN7T4">
<table>
<tr><td><input type="hidden" name="on0" value="Membership Types">Membership Types</td></tr><tr><td><select name="os0">
<option value="Adult">Adult : $30.00 USD - yearly</option>
<option value="Junior (under 18)">Junior (under 18) : $10.00 USD - yearly</option>
<option value="Family">Family : $60.00 USD - yearly</option>
</select> </td></tr>
</table>
<input type="hidden" name="currency_code" value="USD">
<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
</body>
</html> | {
"content_hash": "aff17932f9c718bd8f76bbd14a78c43a",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 177,
"avg_line_length": 47.666666666666664,
"alnum_prop": 0.6031468531468531,
"repo_name": "christothes/FriscoCyclingClub",
"id": "14b907ca387aa2cd811ecf0987d52d60dca7dc5a",
"size": "1144",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/partials/payTest.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "424"
},
{
"name": "JavaScript",
"bytes": "14448"
}
],
"symlink_target": ""
} |
package org.apache.geode.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Annotates a program element that exists, or is more widely visible than otherwise necessary, only
* for use in test code.
*
* <p>
* Introduced while mobbing with Michael Feathers. Name and javadoc borrowed from Guava and AssertJ
* (both are Apache License 2.0).
*/
@Documented
@Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.FIELD})
public @interface VisibleForTesting {
/** Optional description */
String value() default "";
}
| {
"content_hash": "cc366ffe709c2800d68ecfbe2c816eaf",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 100,
"avg_line_length": 27.869565217391305,
"alnum_prop": 0.7613104524180967,
"repo_name": "PurelyApplied/geode",
"id": "7080f49f3f7933f52a83c989677d2f7405ba4c01",
"size": "1430",
"binary": false,
"copies": "3",
"ref": "refs/heads/develop",
"path": "geode-common/src/main/java/org/apache/geode/annotations/VisibleForTesting.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "106708"
},
{
"name": "Dockerfile",
"bytes": "16965"
},
{
"name": "Go",
"bytes": "1205"
},
{
"name": "Groovy",
"bytes": "38270"
},
{
"name": "HTML",
"bytes": "3793466"
},
{
"name": "Java",
"bytes": "30089003"
},
{
"name": "JavaScript",
"bytes": "1781602"
},
{
"name": "Python",
"bytes": "29327"
},
{
"name": "Ruby",
"bytes": "6656"
},
{
"name": "Shell",
"bytes": "136665"
}
],
"symlink_target": ""
} |
package auth
import (
"errors"
"net/http"
)
var (
// ErrInvalidCredential is returned when the auth token does not authenticate correctly.
ErrInvalidCredential = errors.New("invalid authorization credential")
)
// AuthenticationHandler is an interface for authorizing a request
type AuthenticationHandler interface {
// AuthorizeRequest ...
AuthorizeRequest(req *http.Request) error
}
| {
"content_hash": "91cc09c2febfa64c6b9cef84fdbf4581",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 89,
"avg_line_length": 21.944444444444443,
"alnum_prop": 0.7772151898734178,
"repo_name": "steven-zou/harbor",
"id": "2e2173c3941b7720bfaea4817e27dffcb8c1b62c",
"size": "989",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "src/registryctl/auth/auth.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "65898"
},
{
"name": "Dockerfile",
"bytes": "15610"
},
{
"name": "Go",
"bytes": "2394949"
},
{
"name": "HTML",
"bytes": "323559"
},
{
"name": "JavaScript",
"bytes": "2238"
},
{
"name": "Makefile",
"bytes": "26935"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "PLSQL",
"bytes": "148"
},
{
"name": "PLpgSQL",
"bytes": "11853"
},
{
"name": "Python",
"bytes": "238276"
},
{
"name": "RobotFramework",
"bytes": "281940"
},
{
"name": "Shell",
"bytes": "68780"
},
{
"name": "Smarty",
"bytes": "26225"
},
{
"name": "TypeScript",
"bytes": "961483"
}
],
"symlink_target": ""
} |
define(['jquery','jqueryui'], function($){
// Hijack the default form and hide the submit button
// we'll be auto submitting the sort results
$('input[name=race_types_order]').hide();
$('#race_types_sortable')
.sortable()
// .disableSelection()
.bind('sortupdate', function(event, ui){
// build a list of id => order
// console.log(
// $('#race_types_sortable').sortable('serialize')
// );
// $('input[name=race_types_order]').text('Save').show();
$('#race_types_edit').trigger('submit');
});
$('#race_types_edit').bind('submit', function(event){
event.preventDefault();
var action = $(this).attr('action');
var data = $('#race_types_sortable').sortable('serialize');
$.getJSON(action, data, function(data){
// console.log('data');
// $('input[name=race_types_order]').val('Saved!').fadeOut('slow');
});
})
$('.race_type_description').bind('keyup', function(event){
event.preventDefault();
// console.log('update description for '+ $(this).data('race-type-id'));
$(this).siblings('.race_type_save').show();
});
$('.race_type_save').click(function(event){
event.preventDefault();
// get the new desc
var desc = $(this).siblings('.race_type_description').val();
$.getJSON( $(this).attr('href'), {'race_type_description': desc}, $.proxy(function(data){
$(this).hide(); //save button
// console.log(data);
}, this));
}).hide();
}); | {
"content_hash": "cb6c2194df7c3907868f99562a35e05f",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 91,
"avg_line_length": 31.043478260869566,
"alnum_prop": 0.6071428571428571,
"repo_name": "iufer/race",
"id": "83b9aa685249502c163c6af57119dbcb0529df34",
"size": "1428",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/js/views/setting.index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "332407"
},
{
"name": "PHP",
"bytes": "1594556"
},
{
"name": "Perl",
"bytes": "887"
},
{
"name": "Ruby",
"bytes": "237280"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/demo_rxbus_frag_12"
android:baselineAligned="false"
android:orientation="vertical"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:minHeight="220dp"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<FrameLayout
android:id="@+id/demo_rxbus_frag_1"
android:layout_weight="1"
android:layout_height="0dp"
android:layout_width="match_parent"
/>
<FrameLayout
android:id="@+id/demo_rxbus_frag_2"
android:layout_weight="1"
android:layout_height="0dp"
android:layout_width="match_parent"
/>
</LinearLayout>
| {
"content_hash": "93f4884ade2bc7ef7a60967956ed3ade",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 62,
"avg_line_length": 26.357142857142858,
"alnum_prop": 0.6327913279132791,
"repo_name": "cowthan/AyoWeibo",
"id": "2a70a68eb91b537028ddc096be3ba4d1216b887f",
"size": "738",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rxjavasample/src/main/res/layout/fragment_rxbus_demo.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "1510"
},
{
"name": "HTML",
"bytes": "992741"
},
{
"name": "Java",
"bytes": "5838792"
}
],
"symlink_target": ""
} |
try:
from weakref import WeakMethod
except ImportError:
from opencensus.common.backports import WeakMethod
import calendar
import datetime
import weakref
UTF8 = 'utf-8'
# Max length is 128 bytes for a truncatable string.
MAX_LENGTH = 128
ISO_DATETIME_REGEX = '%Y-%m-%dT%H:%M:%S.%fZ'
def get_truncatable_str(str_to_convert):
"""Truncate a string if exceed limit and record the truncated bytes
count.
"""
truncated, truncated_byte_count = check_str_length(
str_to_convert, MAX_LENGTH)
result = {
'value': truncated,
'truncated_byte_count': truncated_byte_count,
}
return result
def check_str_length(str_to_check, limit=MAX_LENGTH):
"""Check the length of a string. If exceeds limit, then truncate it.
:type str_to_check: str
:param str_to_check: String to check.
:type limit: int
:param limit: The upper limit of the length.
:rtype: tuple
:returns: The string it self if not exceeded length, or truncated string
if exceeded and the truncated byte count.
"""
str_bytes = str_to_check.encode(UTF8)
str_len = len(str_bytes)
truncated_byte_count = 0
if str_len > limit:
truncated_byte_count = str_len - limit
str_bytes = str_bytes[:limit]
result = str(str_bytes.decode(UTF8, errors='ignore'))
return (result, truncated_byte_count)
def to_iso_str(ts=None):
"""Get an ISO 8601 string for a UTC datetime."""
if ts is None:
ts = datetime.datetime.utcnow()
return ts.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
def timestamp_to_microseconds(timestamp):
"""Convert a timestamp string into a microseconds value
:param timestamp
:return time in microseconds
"""
timestamp_str = datetime.datetime.strptime(timestamp, ISO_DATETIME_REGEX)
epoch_time_secs = calendar.timegm(timestamp_str.timetuple())
epoch_time_mus = epoch_time_secs * 1e6 + timestamp_str.microsecond
return epoch_time_mus
def iuniq(ible):
"""Get an iterator over unique items of `ible`."""
items = set()
for item in ible:
if item not in items:
items.add(item)
yield item
def uniq(ible):
"""Get a list of unique items of `ible`."""
return list(iuniq(ible))
def window(ible, length):
"""Split `ible` into multiple lists of length `length`.
>>> list(window(range(5), 2))
[[0, 1], [2, 3], [4]]
"""
if length <= 0: # pragma: NO COVER
raise ValueError
ible = iter(ible)
while True:
elts = [xx for ii, xx in zip(range(length), ible)]
if elts:
yield elts
else:
break
def get_weakref(func):
"""Get a weak reference to bound or unbound `func`.
If `func` is unbound (i.e. has no __self__ attr) get a weakref.ref,
otherwise get a wrapper that simulates weakref.ref.
"""
if func is None:
raise ValueError
if not hasattr(func, '__self__'):
return weakref.ref(func)
return WeakMethod(func)
| {
"content_hash": "0490dcc264b3985c7297689de00499d8",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 77,
"avg_line_length": 25.837606837606838,
"alnum_prop": 0.6318226926893814,
"repo_name": "census-instrumentation/opencensus-python",
"id": "9ed6b0afed8fa832ba31a654a0d2e1826e6df3e1",
"size": "3607",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "opencensus/common/utils/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1856"
},
{
"name": "Makefile",
"bytes": "615"
},
{
"name": "Python",
"bytes": "1673591"
},
{
"name": "Shell",
"bytes": "4011"
}
],
"symlink_target": ""
} |
package com.geth1b.coding.design.patterns.creational.prototype;
/**
* - Copying is more efficient than creation of new object
*
* @author geth1b
*/
public class Prototype {
public static void main(String[] args) {
IPrototype prototype = new ConcretePrototype("Hello world");
ConcretePrototype obj = (ConcretePrototype) prototype.getClone();
System.out.println(obj);
}
public interface IPrototype {
Object getClone();
}
public static class ConcretePrototype implements IPrototype {
private String msg;
public ConcretePrototype(String msg) {
this.msg = msg;
}
@Override public Object getClone() {
return new ConcretePrototype(this.msg);
}
@Override public String toString() {
return msg;
}
}
}
| {
"content_hash": "8ec234e7d5c89bfe5b400540b0455a5d",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 69,
"avg_line_length": 24.34375,
"alnum_prop": 0.6842105263157895,
"repo_name": "yang458567/h1b-coding-interview",
"id": "a0974f723bd391f4c72bcb2c0041c7ba67ee8d41",
"size": "779",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/main/java/com/geth1b/coding/design/patterns/creational/prototype/Prototype.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1561736"
},
{
"name": "Shell",
"bytes": "1059"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YYProject.AdvancedDeletion
{
internal sealed class DefaultRmHelper : RmHelper
{
public override Boolean TryGetHolderListOfFiles(String[] fileNames, out RmProcessInfo[] result)
{
result = null;
if (NativeAPI.TryRmRegisterResources(base._SessionHandle, fileNames, null, null) && NativeAPI.TryRmGetList(base._SessionHandle, out var suggestion, out result))
{
return true;
}
return false;
}
}
}
| {
"content_hash": "ecd495a40c5e4773bf168ec3deec946f",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 172,
"avg_line_length": 26.416666666666668,
"alnum_prop": 0.6514195583596214,
"repo_name": "differentrain/DeletionTool",
"id": "c940454295e58a3aeaea54c3453c7389eb727241",
"size": "636",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/DeletionTool/AdvancedDeletion/Utilities/Win32API/RmHelper/DefaultRmHelper.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "76249"
}
],
"symlink_target": ""
} |
package ssh
import (
"io/ioutil"
"log"
"code.google.com/p/go.crypto/ssh"
)
func Config() *ssh.ServerConfig {
config := &ssh.ServerConfig{
PasswordCallback: func(conn *ssh.ServerConn, user, pass string) bool {
return user == "test" && pass == "test123"
},
}
config.NoClientAuth = true
pemBytes, err := ioutil.ReadFile("privkey")
if err != nil {
log.Fatal("Failed to load private key file: ", err)
}
if err = config.SetRSAPrivateKey(pemBytes); err != nil {
log.Fatal("Failed to parse private key: ", err)
}
return config
}
func Open(config *ssh.ServerConfig) *ssh.Listener {
conn, err := ssh.Listen("tcp", ":8765", config)
if err != nil {
log.Fatal("Failed to listen for connection")
}
return conn
}
| {
"content_hash": "5a9cbc4cca13e2f3c8aaedcd8936bb6d",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 72,
"avg_line_length": 22.151515151515152,
"alnum_prop": 0.66484268125855,
"repo_name": "kdorland/ssh_chat",
"id": "cfaad847ea3593b7f509def9f4126f27a2cd33dc",
"size": "731",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ssh/ssh.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "7015"
}
],
"symlink_target": ""
} |
package mpapi
import (
"database/sql"
"github.com/kierdavis/mealplanner/mpdata"
"github.com/kierdavis/mealplanner/mpdb"
"log"
"net/url"
"strconv"
"time"
)
// fetchSuggestions handles an API call to generate suggestions for a given date.
// Expected parameters: date. Returns: an array of suggestion objects.
func fetchSuggestions(params url.Values) (response JSONResponse) {
mpID, err := strconv.ParseUint(params.Get("mealplanid"), 10, 64)
if err != nil {
return JSONResponse{Error: "Invalid or missing 'mealplanid' parameter"}
}
dateServed, err := time.Parse(mpdata.JSONDateFormat, params.Get("date"))
if err != nil {
return JSONResponse{Error: "Invalid or missing 'date' parameter"}
}
var suggs []*mpdata.Suggestion
err = mpdb.WithConnection(func(db *sql.DB) (err error) {
return mpdb.WithTransaction(db, func(tx *sql.Tx) (err error) {
suggs, err = mpdb.GenerateSuggestions(tx, mpID, dateServed)
return err
})
})
if err != nil {
log.Printf("Database error: %s\n", err.Error())
return JSONResponse{Error: "Database error"}
}
return JSONResponse{Success: suggs}
}
| {
"content_hash": "67368a36b3117bcbf76f3ede24307256",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 81,
"avg_line_length": 27.024390243902438,
"alnum_prop": 0.7148014440433214,
"repo_name": "kierdavis/mealplanner",
"id": "58eee4639d3c5750b7da6c87eb9773fe0dc1713b",
"size": "1108",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mpapi/fetchsuggestions.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "3358"
},
{
"name": "Go",
"bytes": "75795"
},
{
"name": "HTML",
"bytes": "48905"
},
{
"name": "JavaScript",
"bytes": "53375"
}
],
"symlink_target": ""
} |
<template name="postPage">
<section class="home-container">
<div class="home-feed">
<div class="feed-page">
{{#with item}}
{{> feedPost}}
{{/with}}
</div>
</div>
</section>
</template>
| {
"content_hash": "e2ae1c77761ef2efc8f4b9ead0a80359",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 33,
"avg_line_length": 19.09090909090909,
"alnum_prop": 0.5619047619047619,
"repo_name": "BaseNY/base",
"id": "6b80632b1d1f1c42343f50ca4f0d38ddef3de8c4",
"size": "210",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "packages/app-posts/views/post_page.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "229328"
},
{
"name": "JavaScript",
"bytes": "74876"
},
{
"name": "Python",
"bytes": "249"
},
{
"name": "Ruby",
"bytes": "67"
}
],
"symlink_target": ""
} |
@class NSString;
@interface UBERNibDisplayPage : UBERWorkoutDisplayPage
{
NSString *_nibName;
}
+ (id)pageWithUID:(id)arg1 displayNameKey:(id)arg2 descriptionKey:(id)arg3 nibName:(id)arg4;
+ (id)pageWithUID:(id)arg1;
+ (id)predefinedPageKeys;
@property(copy, nonatomic) NSString *nibName; // @synthesize nibName=_nibName;
- (void).cxx_destruct;
- (id)instantiateWorkoutPage;
- (void)configureWithNibName:(id)arg1;
- (id)interactionViewWithFrame:(struct CGRect)arg1;
- (id)infoViewWithFrame:(struct CGRect)arg1;
- (id)previewImageWithSize:(struct CGSize)arg1;
@end
| {
"content_hash": "0653d20a62e940757683d9b9b2f38f0c",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 92,
"avg_line_length": 28.6,
"alnum_prop": 0.7604895104895105,
"repo_name": "JChanceHud/GearIndicator",
"id": "457cf0465c04da35bf83a4f3caa8d57c9be8283a",
"size": "747",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Fitness/UBERNibDisplayPage.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "108039"
},
{
"name": "C++",
"bytes": "1871"
},
{
"name": "Logos",
"bytes": "8"
},
{
"name": "Objective-C",
"bytes": "1948211"
},
{
"name": "Objective-C++",
"bytes": "3786"
}
],
"symlink_target": ""
} |
package com.sequenceiq.cloudbreak.clusterproxy;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
import java.util.Arrays;
import java.util.Set;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.test.util.ReflectionTestUtils;
@RunWith(Parameterized.class)
public class ClusterProxyEnablementServiceTest {
@Parameterized.Parameter
public String cloudPlatform;
@Parameterized.Parameter(1)
public boolean clusterProxyIntegrationEnabled;
@Parameterized.Parameter(2)
public boolean clusterProxyApplicable;
@Mock
private ClusterProxyConfiguration clusterProxyConfiguration;
@InjectMocks
private ClusterProxyEnablementService clusterProxyEnablementService;
@Before
public void setUp() throws Exception {
initMocks(this);
ReflectionTestUtils.setField(clusterProxyEnablementService, "clusterProxyDisabledPlatforms", Set.of("MOCK"));
}
@Test
public void isClusterProxyApplicable() {
when(clusterProxyConfiguration.isClusterProxyIntegrationEnabled()).thenReturn(clusterProxyIntegrationEnabled);
Assert.assertEquals(clusterProxyApplicable, clusterProxyEnablementService.isClusterProxyApplicable(cloudPlatform));
}
@Parameterized.Parameters(name = "{index}: clusterProxyEnablementService.clusterProxyApplicable(get cloudPlatform '{0}' "
+ "with clusterProxyIntegrationEnabled '{1}') = output is clusterProxyApplicable '{2}'")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "MOCK", true, false },
{ "MOCK", false, false },
{ "AWS", true, true },
{ "AWS", false, false },
{ "AZURE", true, true },
{ "AZURE", false, false }
});
}
} | {
"content_hash": "23b0347ba5b582551cb1ae3e5c95cd3c",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 125,
"avg_line_length": 32.61290322580645,
"alnum_prop": 0.7146389713155292,
"repo_name": "hortonworks/cloudbreak",
"id": "b30bb8f2a59aaefc30138e870f34157fac0a3632",
"size": "2022",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cluster-proxy/src/test/java/com/sequenceiq/cloudbreak/clusterproxy/ClusterProxyEnablementServiceTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "7535"
},
{
"name": "Dockerfile",
"bytes": "9586"
},
{
"name": "Fluent",
"bytes": "10"
},
{
"name": "FreeMarker",
"bytes": "395982"
},
{
"name": "Groovy",
"bytes": "523"
},
{
"name": "HTML",
"bytes": "9917"
},
{
"name": "Java",
"bytes": "55250904"
},
{
"name": "JavaScript",
"bytes": "47923"
},
{
"name": "Jinja",
"bytes": "190660"
},
{
"name": "Makefile",
"bytes": "8537"
},
{
"name": "PLpgSQL",
"bytes": "1830"
},
{
"name": "Perl",
"bytes": "17726"
},
{
"name": "Python",
"bytes": "29898"
},
{
"name": "SaltStack",
"bytes": "222692"
},
{
"name": "Scala",
"bytes": "11168"
},
{
"name": "Shell",
"bytes": "416225"
}
],
"symlink_target": ""
} |
<!--
DOM
=========
DOM stands for document object model.
DOM describes how HTML document works and how Java script can interact with HTML and dynamically change the contents of HTML document.
In HTML DOM all elements are represented as objects.
Java script can dynamically change the contents of the HTLM page by interacting with the DOM objects.
All the DOM objects have corresponding methods and properties.
Java script can change
- elements
- attributes
- css styles
- remove HTLM elements
- add HTML elements
- react to HTML events
- create HTML events
DOM Objects, methods and properties
===================================
DOM objects have methods and properties like any other objects.
Using these methods and objects javascript can interact with HTML elements.
HTLM DOM can be accessed with java script and other languages as well. Our focus is only on javascript.
methods - these are the actions that can be performed on HTLM elements.
properties - these are the values that can set for respective elements.
-->
<!DOCTYPE html>
<html>
<body>
<h1> DOM - Object methods and properties</h1>
<p id="p1">we will work with dom methods and properties</p>
<button id="button1" onclick="myFunction()">Click me</button>
<script>
document.getElementById("p1").innerHTML = "Hello World!";
function myFunction(){
document.getElementById("button1").innerHTML = "I was clicked";
}
</script>
</body>
</html>
| {
"content_hash": "9f7ff44b240476954658dac6c9d090d2",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 134,
"avg_line_length": 30.770833333333332,
"alnum_prop": 0.7129316181448883,
"repo_name": "santoshtechie9/javascript-examples",
"id": "0722b1f4f616be541ca834b2aa7a10a5e50b3700",
"size": "1477",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "DOM/1-DOM-overview.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "5132"
},
{
"name": "JavaScript",
"bytes": "7195"
}
],
"symlink_target": ""
} |
package com.avanza.astrix.context.mbeans;
public interface MBeanServerFacade {
void registerMBean(Object mbean, String folder, String name);
void unregisterMBean(String folder, String name);
}
| {
"content_hash": "3ee781e28e65a5e8c04a708e52c44b23",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 62,
"avg_line_length": 20,
"alnum_prop": 0.79,
"repo_name": "AvanzaBank/astrix",
"id": "09eb520051849629a476dc8b2599490c78c09853",
"size": "798",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "astrix-context/src/main/java/com/avanza/astrix/context/mbeans/MBeanServerFacade.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "966"
},
{
"name": "Java",
"bytes": "1470625"
},
{
"name": "Shell",
"bytes": "314"
}
],
"symlink_target": ""
} |
package org.wildfly.camel.examples.cxf;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService(serviceName="greeting", endpointInterface = "org.wildfly.camel.examples.cxf.GreetingService")
public class GreetingServiceImpl {
@WebMethod(operationName = "greet")
public String greet(@WebParam(name = "message") String message, @WebParam(name = "name") String name) {
return message + " " + name ;
}
}
| {
"content_hash": "656abb5512bbf339de7e7ea18c6343ad",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 107,
"avg_line_length": 30.866666666666667,
"alnum_prop": 0.7300215982721382,
"repo_name": "grgrzybek/wildfly-camel",
"id": "41295aa75bf5ee2ad7d066679e356b7d88556dcf",
"size": "1128",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "examples/camel-cxf/src/main/java/org/wildfly/camel/examples/cxf/GreetingServiceImpl.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Groovy",
"bytes": "8829"
},
{
"name": "Java",
"bytes": "565629"
},
{
"name": "Shell",
"bytes": "1279"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>org.eclipse.pdt.releng</artifactId>
<groupId>org.eclipse.php</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<groupId>org.eclipse.php</groupId>
<artifactId>org.eclipse.php.source</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>eclipse-feature</packaging>
</project>
| {
"content_hash": "dcf4aa43a129f5eb05055630e76a267f",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 99,
"avg_line_length": 37.375,
"alnum_prop": 0.725752508361204,
"repo_name": "asankas/developer-studio",
"id": "42c7bc80a22d82c66bff9b5360bd1c6ab62cfdeb",
"size": "598",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jaggery/org.eclipse.php.source-feature/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
CREATE TABLE order_item (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
order_id BIGINT(20),
target_type INT,
target_id BIGINT(20),
price FLOAT,
orig_price FLOAT,
quantity INT DEFAULT '1',
status TINYINT(4) DEFAULT '0',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
data TEXT COMMENT 'JSON with item details if needed',
PRIMARY KEY (id),
KEY order_id(order_id, target_type, target_id, price, status)
)
ENGINE = InnoDB
DEFAULT CHARSET = utf8
COLLATE = utf8_general_ci;
| {
"content_hash": "ecafdf1f4f848ef0edb59fa760b4a684",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 63,
"avg_line_length": 33.23529411764706,
"alnum_prop": 0.6194690265486725,
"repo_name": "dimaninc/di_core",
"id": "0caddafe064ef8647aa9ae3d6f5c0fdd0c202aec",
"size": "565",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sql/cart/order_item.sql",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "245644"
},
{
"name": "CoffeeScript",
"bytes": "24951"
},
{
"name": "HTML",
"bytes": "10872"
},
{
"name": "JavaScript",
"bytes": "255478"
},
{
"name": "PHP",
"bytes": "1760522"
},
{
"name": "Shell",
"bytes": "1742"
},
{
"name": "Stylus",
"bytes": "101414"
},
{
"name": "Twig",
"bytes": "32273"
}
],
"symlink_target": ""
} |
{% extends 'base.html' %}
{% block header %}
{% include 'explain_header.html' %}
{% endblock %}
{% block main %}
<div class="row">
<div class="main explain-preamble">Alrighty, the question was:</div>
</div>
<div class="row">
<div class="main explain">
{{ question|render_explained_question(given_answer) }}
<div class="next-question">
<a class="btn btn-primary" href="{{ url_for('ask_next_question') }}">
Next question
</a>
</div>
</div>
</div>
{% endblock %}
| {
"content_hash": "19e698a015f4780ab0125d34bc983a8f",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 85,
"avg_line_length": 28.285714285714285,
"alnum_prop": 0.5033670033670034,
"repo_name": "alexandershov/pydrill",
"id": "f37e318a34792a61e37a4e5644f0807a8af128b2",
"size": "594",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pydrill/templates/explain.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "173997"
},
{
"name": "HTML",
"bytes": "5115"
},
{
"name": "Python",
"bytes": "24631"
}
],
"symlink_target": ""
} |
using System;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
namespace OpenRiaServices.DomainServices.Server
{
internal static class DynamicMethodUtility
{
/// <summary>
/// Gets a factory method for a late-bound type.
/// </summary>
/// <remarks>
/// This method will return a delegate to a factory method that looks like this:
/// <code>
/// public object FactoryMethod([object[, object]*]) {
/// return <Constructor>([object[, object]*]);
/// }
/// </code>
/// </remarks>
/// <param name="ctor">The constructor to invoke.</param>
/// <param name="delegateType">The type of delegate to return.</param>
/// <returns>A factory method delegate.</returns>
public static Delegate GetFactoryMethod(ConstructorInfo ctor, Type delegateType)
{
ParameterInfo[] parameters = ctor.GetParameters();
Type[] ctorArgTypes = new Type[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
ctorArgTypes[i] = typeof(object);
}
DynamicMethod proxyMethod = new DynamicMethod("FactoryMethod", typeof(object), ctorArgTypes);
ILGenerator generator = proxyMethod.GetILGenerator();
for (int i = 0; i < parameters.Length; i++)
{
generator.Emit(OpCodes.Ldarg, i);
EmitFromObjectConversion(generator, parameters[i].ParameterType);
}
generator.Emit(OpCodes.Newobj, ctor);
generator.Emit(OpCodes.Ret);
return proxyMethod.CreateDelegate(delegateType);
}
/// <summary>
/// Gets an early-bound delegate for an instance method.
/// </summary>
/// <remarks>
/// This method will return a delegate to a proxy method that looks like this:
/// <code>
/// public object <MethodName>(DomainService target, object[] parameters) {
/// return ((<TargetType>)target).<MethodName>();
/// return ((<TargetType>)target).<MethodName>((<ParameterType>)parameters[0]);
/// }
/// </code>
/// </remarks>
/// <param name="method">The method that the delegate should invoke.</param>
/// <returns>A delegate.</returns>
public static Func<DomainService, object[], object> GetDelegateForMethod(MethodInfo method)
{
return (Func<DomainService, object[], object>)GetDynamicMethod(method).CreateDelegate(typeof(Func<DomainService, object[], object>));
}
/// <summary>
/// Emits a conversion to type object for the value on the stack.
/// </summary>
/// <param name="generator">The code generator to use.</param>
/// <param name="sourceType">The type of value on the stack.</param>
public static void EmitToObjectConversion(ILGenerator generator, Type sourceType)
{
if (sourceType.IsValueType)
{
generator.Emit(OpCodes.Box, sourceType);
}
}
/// <summary>
/// Emits a conversion from type object for the value on the stack.
/// </summary>
/// <param name="generator">The code generator to use.</param>
/// <param name="targetType">The type to which the value on the stack needs to be converted.</param>
public static void EmitFromObjectConversion(ILGenerator generator, Type targetType)
{
if (targetType.IsValueType)
{
Label continueLabel = generator.DefineLabel();
Label nonNullLabel = generator.DefineLabel();
generator.Emit(OpCodes.Dup);
generator.Emit(OpCodes.Brtrue, nonNullLabel);
// If the value is null, put a default value on the stack.
generator.Emit(OpCodes.Pop);
if (targetType == typeof(bool)
|| targetType == typeof(byte)
|| targetType == typeof(char)
|| targetType == typeof(short)
|| targetType == typeof(int)
|| targetType == typeof(sbyte)
|| targetType == typeof(ushort)
|| targetType == typeof(uint))
{
generator.Emit(OpCodes.Ldc_I4_0);
}
else if (targetType == typeof(long) || targetType == typeof(ulong))
{
generator.Emit(OpCodes.Ldc_I8, (long)0);
}
else if (targetType == typeof(float))
{
generator.Emit(OpCodes.Ldc_R4, (float)0);
}
else if (targetType == typeof(double))
{
generator.Emit(OpCodes.Ldc_R8, (double)0);
}
else
{
LocalBuilder defaultValueLocal = generator.DeclareLocal(targetType);
generator.Emit(OpCodes.Ldloca, defaultValueLocal);
generator.Emit(OpCodes.Initobj, targetType);
generator.Emit(OpCodes.Ldloc, defaultValueLocal);
}
generator.Emit(OpCodes.Br, continueLabel);
// If the value is not null, unbox it.
generator.MarkLabel(nonNullLabel);
generator.Emit(OpCodes.Unbox_Any, targetType);
generator.MarkLabel(continueLabel);
}
else
{
generator.Emit(OpCodes.Castclass, targetType);
}
}
private static DynamicMethod GetDynamicMethod(MethodInfo method)
{
Debug.Assert(!method.IsGenericMethodDefinition, "Cannot create DynamicMethods for generic methods.");
// We'll return null for void methods.
Type returnType = method.ReturnType;
bool isVoid = (returnType == typeof(void));
Type[] parameterTypes;
if (method.IsStatic)
{
parameterTypes = new Type[] { typeof(object[]) };
}
else
{
parameterTypes = new Type[] { typeof(DomainService), typeof(object[]) };
}
DynamicMethod proxyMethod = new DynamicMethod(method.Name, typeof(object), parameterTypes, /* restrictedSkipVisibility */ !method.IsPublic);
ILGenerator generator = proxyMethod.GetILGenerator();
// Cast the target object to its actual type.
if (!method.IsStatic)
{
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclass, method.DeclaringType);
}
OpCode parameterReference = method.IsStatic ? OpCodes.Ldarg_0 : OpCodes.Ldarg_1;
ParameterInfo[] parameters = method.GetParameters();
int conceptualParameterLength = parameters.Length;
LocalBuilder outCountLocal = null;
if (conceptualParameterLength > 0)
{
// Check if the last parameter is an out parameter used for count.
if (parameters[conceptualParameterLength - 1].IsOut)
{
conceptualParameterLength--;
outCountLocal = generator.DeclareLocal(typeof(int));
}
// Push the parameters on the stack.
for (int i = 0; i < conceptualParameterLength; i++)
{
generator.Emit(parameterReference);
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Ldelem_Ref);
EmitFromObjectConversion(generator, parameters[i].ParameterType);
}
// Load an address on the stack that points to a location
// where the count value should be stored.
if (outCountLocal != null)
{
generator.Emit(OpCodes.Ldloca, outCountLocal);
}
}
// Invoke the method.
if (method.IsVirtual)
{
generator.Emit(OpCodes.Callvirt, method);
}
else
{
generator.Emit(OpCodes.Call, method);
}
// Store the out parameter in the list of parameters.
if (outCountLocal != null)
{
generator.Emit(parameterReference);
generator.Emit(OpCodes.Ldc_I4, conceptualParameterLength);
generator.Emit(OpCodes.Ldloc, outCountLocal);
EmitToObjectConversion(generator, typeof(int));
generator.Emit(OpCodes.Stelem_Ref);
}
// Convert the return value to an object.
if (isVoid)
{
generator.Emit(OpCodes.Ldnull);
}
else if (returnType.IsValueType)
{
EmitToObjectConversion(generator, returnType);
}
generator.Emit(OpCodes.Ret);
return proxyMethod;
}
}
}
| {
"content_hash": "90af17c9e198580c13c5e47cacfb331b",
"timestamp": "",
"source": "github",
"line_count": 233,
"max_line_length": 152,
"avg_line_length": 39.88841201716738,
"alnum_prop": 0.5374435119431892,
"repo_name": "Daniel-Svensson/OpenRiaServiecs",
"id": "1cf87971160222984190c08f7088be4a0dd4e691",
"size": "9296",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "OpenRiaServices.DomainServices.Server/Framework/Data/DynamicMethodUtility.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "814"
},
{
"name": "Batchfile",
"bytes": "602"
},
{
"name": "C#",
"bytes": "19164300"
},
{
"name": "CSS",
"bytes": "5674"
},
{
"name": "HTML",
"bytes": "12455"
},
{
"name": "PowerShell",
"bytes": "1793"
},
{
"name": "Visual Basic",
"bytes": "4874395"
}
],
"symlink_target": ""
} |
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
| {
"content_hash": "28950cc19b5bce1037118f99150ea109",
"timestamp": "",
"source": "github",
"line_count": 41,
"max_line_length": 281,
"avg_line_length": 45.853658536585364,
"alnum_prop": 0.7851063829787234,
"repo_name": "WangGuibin/MyCodeSnippets",
"id": "35d44eda63fe0916de5a87af6599b9dd33f20379",
"size": "2044",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "工具类/时间类的处理/倒计时/倒计时/AppDelegate.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "594589"
},
{
"name": "C++",
"bytes": "60472"
},
{
"name": "DTrace",
"bytes": "412"
},
{
"name": "HTML",
"bytes": "4405"
},
{
"name": "Objective-C",
"bytes": "8138668"
},
{
"name": "Ruby",
"bytes": "19625"
},
{
"name": "Shell",
"bytes": "46552"
},
{
"name": "Swift",
"bytes": "183372"
}
],
"symlink_target": ""
} |
Collection of scripts for benchmarking various tools
## git-clone
`bin/benchmark-git-clone.sh` benchmarks several cloning strategies.
The appropriate cloning strategy can vary depending on the server implementation
(*eg.* JGit vs. regular git server).
| {
"content_hash": "7e5b74f5a01f63420e8e03b2e2bbc247",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 80,
"avg_line_length": 31.875,
"alnum_prop": 0.8,
"repo_name": "JcDelay/benchmarks",
"id": "876707285599efc60e0b76c0b23a03bcda78f3d3",
"size": "269",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Shell",
"bytes": "10998"
}
],
"symlink_target": ""
} |
package org.locationtech.geowave.format.landsat8.index;
import org.locationtech.geowave.core.index.persist.InternalPersistableRegistry;
import org.locationtech.geowave.core.index.persist.PersistableRegistrySpi;
public class Landsat8PersistableRegistry implements
PersistableRegistrySpi,
InternalPersistableRegistry {
@Override
public PersistableIdAndConstructor[] getSupportedPersistables() {
return new PersistableIdAndConstructor[] {
new PersistableIdAndConstructor((short) 1500, Landsat8TemporalBinningStrategy::new),};
}
}
| {
"content_hash": "e695b0750cee40f42335e979b3b4ad4a",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 94,
"avg_line_length": 34.8125,
"alnum_prop": 0.8186714542190305,
"repo_name": "ngageoint/geowave",
"id": "87ce6552c60e18fd90dbb33840565922533a7ba3",
"size": "992",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "extensions/cli/landsat8/src/main/java/org/locationtech/geowave/format/landsat8/index/Landsat8PersistableRegistry.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "5073"
},
{
"name": "CMake",
"bytes": "2032"
},
{
"name": "FreeMarker",
"bytes": "2879"
},
{
"name": "Gnuplot",
"bytes": "57750"
},
{
"name": "Groovy",
"bytes": "1323"
},
{
"name": "HTML",
"bytes": "1903"
},
{
"name": "Java",
"bytes": "7103026"
},
{
"name": "Protocol Buffer",
"bytes": "1525"
},
{
"name": "Puppet",
"bytes": "4039"
},
{
"name": "Scala",
"bytes": "26507"
},
{
"name": "Scheme",
"bytes": "20491"
},
{
"name": "Shell",
"bytes": "68381"
}
],
"symlink_target": ""
} |
void layout_fr_double_baseline( double *position, int nodes,
int *es, int edges, int dummy_dim,
int MAX_IT, double temp );
// version using sse (2way double, 128bit registers)
// 2x speedup over double baseline
void layout_fr_double_simd_only( double *position, int nodes,
int *es, int edges, int dummy_dim,
int MAX_IT, double temp );
// -------------------------
// single precision versions
// -------------------------
// float version of baseline
// ~ 1.6x faster than double prec => new baseline
void layout_fr_interleaved_baseline( float *position, int nodes,
int *es, int edges, int dummy_dim,
int MAX_IT, float temp );
// version using sse (4way float, 128bit registers)
// 1.5x speedup over float baseline
void layout_fr_interleaved_simd_only( float *position, int nodes,
int *es, int edges, int dummy_dim,
int MAX_IT, float temp );
// OpenMP version
// using private displacement vectors for each thread
// to avoid race conditions
void layout_fr_interleaved_omp_only( float *position, int nodes,
int *es, int edges, int dummy_dim,
int MAX_IT, float temp );
// first attempt to go hybrid (simd && OpenMP)
void layout_fr_interleaved( float *position, int nodes,
int *es, int edges, int dummy_dim,
int MAX_IT, float temp );
// ---------------------------------
// strided single precision versions
// ---------------------------------
// - idea: use 1D array for easier vectoriztion afterwards.
// is about 5% faster than float baseline
void layout_fr_baseline( float *position, int nodes,
int *es, int edges, int dummy_dim,
int MAX_IT, float temp );
// simd version based on layout_fr_stride
// this version is about 2.9x faster than float baseline and
// thus way better than layout_fr_simd
void layout_fr_simd_only( float *position, int nodes,
int *es, int edges, int dummy_dim,
int MAX_IT, float temp );
// strided ompenmp version
void layout_fr_omp_only( float *position, int nodes,
int *es, int edges, int dummy_dim,
int MAX_IT, float temp );
// second attempt to go hybrid
void layout_fr( float *position, int nodes,
int *es, int edges, int dummy_dim,
int MAX_IT, float temp );
| {
"content_hash": "040d0f6b12f9c9c6ea14a8279527096c",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 73,
"avg_line_length": 40.92424242424242,
"alnum_prop": 0.5338763420955202,
"repo_name": "sg-dev/pyFastLayout",
"id": "3c5a8ac03579845fe4ded45e53d4599990298cc8",
"size": "3037",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "fastlayout/fastlayout.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "804158"
},
{
"name": "Python",
"bytes": "37734"
}
],
"symlink_target": ""
} |
import os
import contextlib
import mock
from oslo_config import cfg
from oslo_utils import importutils
import six
import webob.exc
from neutron.api import extensions as api_ext
from neutron.common import config
from neutron import context as n_context
from neutron.manager import NeutronManager
from neutron.plugins.common import constants as svc_constants
from neutron.tests.unit.db import test_db_base_plugin_v2
import networking_cisco
from networking_cisco.plugins.cisco.common import (cisco_constants as
c_constants)
from networking_cisco.plugins.cisco.db.device_manager import (
hosting_device_manager_db as hdm_db)
from networking_cisco.plugins.cisco.device_manager.rpc import (
devmgr_rpc_cfgagent_api)
from networking_cisco.plugins.cisco.device_manager import service_vm_lib
from networking_cisco.plugins.cisco.extensions import ciscohostingdevicemanager
from networking_cisco.tests.unit.cisco.device_manager import (
device_manager_test_support)
policy_path = (os.path.abspath(networking_cisco.__path__[0]) +
'/../etc/policy.json')
DB_DM_PLUGIN_KLASS = (
'networking_cisco.plugins.cisco.db.device_manager.'
'hosting_device_manager_db.HostingDeviceManagerMixin')
NN_CATEGORY = ciscohostingdevicemanager.NETWORK_NODE_CATEGORY
NN_TEMPLATE_NAME = c_constants.NETWORK_NODE_TEMPLATE
NS_ROUTERTYPE_NAME = c_constants.NAMESPACE_ROUTER_TYPE
VM_CATEGORY = ciscohostingdevicemanager.VM_CATEGORY
VM_TEMPLATE_NAME = "CSR1kv_template"
VM_BOOTING_TIME = 420
VM_SLOT_CAPACITY = 3
VM_DESIRED_SLOTS_FREE = 3
VM_ROUTERTYPE_NAME = c_constants.CSR1KV_ROUTER_TYPE
HW_CATEGORY = ciscohostingdevicemanager.HARDWARE_CATEGORY
HW_TEMPLATE_NAME = "HW_template"
HW_ROUTERTYPE_NAME = "HW_router"
L3_ROUTER_NAT = svc_constants.L3_ROUTER_NAT
DEFAULT_SERVICE_TYPES = "router"
NETWORK_NODE_SERVICE_TYPES = "router:fwaas:vpn"
NOOP_DEVICE_DRIVER = ('networking_cisco.plugins.cisco.device_manager.'
'hosting_device_drivers.noop_hd_driver.'
'NoopHostingDeviceDriver')
NOOP_PLUGGING_DRIVER = ('networking_cisco.plugins.cisco.device_manager.'
'plugging_drivers.noop_plugging_driver.'
'NoopPluggingDriver')
TEST_DEVICE_DRIVER = NOOP_DEVICE_DRIVER
TEST_PLUGGING_DRIVER = ('networking_cisco.tests.unit.cisco.device_manager.'
'plugging_test_driver.TestPluggingDriver')
DESCRIPTION = "default description"
SHARED = True
ACTION = "allow"
ENABLED = True
ADMIN_STATE_UP = True
UNBOUND = None
REQUESTER = True
OTHER = False
DEFAULT_CREDENTIALS_ID = device_manager_test_support._uuid()
class DeviceManagerTestCaseMixin(object):
def _create_hosting_device(self, fmt, template_id, management_port_id,
admin_state_up, expected_res_status=None,
**kwargs):
data = {'hosting_device': self._get_test_hosting_device_attr(
template_id=template_id, management_port_id=management_port_id,
admin_state_up=admin_state_up, **kwargs)}
hd_req = self.new_create_request('hosting_devices', data, fmt)
if kwargs.get('set_context') and 'tenant_id' in kwargs:
# create a specific auth context for this request
hd_req.environ['neutron.context'] = n_context.Context(
'', kwargs['tenant_id'])
hd_res = hd_req.get_response(self.ext_api)
if expected_res_status:
self.assertEqual(hd_res.status_int, expected_res_status)
return hd_res
@contextlib.contextmanager
def hosting_device(self, template_id, management_port_id=None, fmt=None,
admin_state_up=True, no_delete=False,
set_port_device_id=True, **kwargs):
if not fmt:
fmt = self.fmt
res = self._create_hosting_device(fmt, template_id, management_port_id,
admin_state_up, **kwargs)
if res.status_int >= 400:
raise webob.exc.HTTPClientError(code=res.status_int)
hosting_device = self.deserialize(fmt or self.fmt, res)
if set_port_device_id is True and management_port_id is not None:
data = {'port': {
'device_id': hosting_device['hosting_device']['id'],
'device_owner': 'Nova'}}
req = self.new_update_request('ports', data, management_port_id)
res = self.deserialize(self.fmt, req.get_response(self.api))
yield hosting_device
if not no_delete:
self._delete('hosting_devices',
hosting_device['hosting_device']['id'])
def _create_hosting_device_template(self, fmt, name, enabled,
host_category,
expected_res_status=None, **kwargs):
data = {'hosting_device_template':
self._get_test_hosting_device_template_attr(
name=name, enabled=enabled, host_category=host_category,
**kwargs)}
hdt_req = self.new_create_request('hosting_device_templates', data,
fmt)
if kwargs.get('set_context') and 'tenant_id' in kwargs:
# create a specific auth context for this request
hdt_req.environ['neutron.context'] = n_context.Context(
'', kwargs['tenant_id'])
hdt_res = hdt_req.get_response(self.ext_api)
if expected_res_status:
self.assertEqual(hdt_res.status_int, expected_res_status)
return hdt_res
@contextlib.contextmanager
def hosting_device_template(self, fmt=None, name='device_template_1',
enabled=True, host_category=VM_CATEGORY,
no_delete=False, **kwargs):
if not fmt:
fmt = self.fmt
res = self._create_hosting_device_template(fmt, name, enabled,
host_category, **kwargs)
if res.status_int >= 400:
raise webob.exc.HTTPClientError(code=res.status_int)
hd_template = self.deserialize(fmt or self.fmt, res)
yield hd_template
if not no_delete:
self._delete('hosting_device_templates',
hd_template['hosting_device_template']['id'])
def _get_test_hosting_device_attr(self, template_id, management_port_id,
admin_state_up=True, **kwargs):
data = {
'tenant_id': kwargs.get('tenant_id', self._tenant_id),
'template_id': template_id,
'credentials_id': kwargs.get('credentials_id'),
'device_id': kwargs.get('device_id', 'mfc_device_id'),
'admin_state_up': admin_state_up,
'management_ip_address': kwargs.get('management_ip_address',
'10.0.100.10'),
'management_port_id': management_port_id,
'protocol_port': kwargs.get('protocol_port', 22),
'cfg_agent_id': kwargs.get('cfg_agent_id'),
'tenant_bound': kwargs.get('tenant_bound'),
'auto_delete': kwargs.get('auto_delete', False)}
return data
def _get_test_hosting_device_template_attr(self, name='device_template_1',
enabled=True,
host_category=VM_CATEGORY,
**kwargs):
data = {
'tenant_id': kwargs.get('tenant_id', self._tenant_id),
'name': name,
'enabled': enabled,
'host_category': host_category,
'service_types': kwargs.get('service_types',
DEFAULT_SERVICE_TYPES),
'image': kwargs.get('image'),
'flavor': kwargs.get('flavor'),
'default_credentials_id': kwargs.get('default_credentials_id',
DEFAULT_CREDENTIALS_ID),
'configuration_mechanism': kwargs.get('configuration_mechanism'),
'protocol_port': kwargs.get('protocol_port', 22),
'booting_time': kwargs.get('booting_time', 0),
'slot_capacity': kwargs.get('slot_capacity', 0),
'desired_slots_free': kwargs.get('desired_slots_free', 0),
'tenant_bound': kwargs.get('tenant_bound', []),
'device_driver': kwargs.get('device_driver', NOOP_DEVICE_DRIVER),
'plugging_driver': kwargs.get('plugging_driver',
NOOP_PLUGGING_DRIVER)}
return data
def _test_list_resources(self, resource, items,
neutron_context=None,
query_params=None):
if resource.endswith('y'):
resource_plural = resource.replace('y', 'ies')
else:
resource_plural = resource + 's'
res = self._list(resource_plural,
neutron_context=neutron_context,
query_params=query_params)
resource = resource.replace('-', '_')
self.assertEqual(sorted([i['id'] for i in res[resource_plural]]),
sorted([i[resource]['id'] for i in items]))
def _replace_hosting_device_status(self, attrs, old_status, new_status):
if attrs['status'] is old_status:
attrs['status'] = new_status
return attrs
def _test_create_hosting_device_templates(self):
# template for network nodes.
nnt = self._create_hosting_device_template(self.fmt, NN_TEMPLATE_NAME,
True, NN_CATEGORY)
nw_node_template = self.deserialize(self.fmt, nnt)
vmt = self._create_hosting_device_template(
self.fmt, VM_TEMPLATE_NAME, True, VM_CATEGORY,
booting_time=VM_BOOTING_TIME,
slot_capacity=VM_SLOT_CAPACITY,
desired_slots_free=VM_DESIRED_SLOTS_FREE,
device_driver=TEST_DEVICE_DRIVER,
plugging_driver=TEST_PLUGGING_DRIVER)
vm_template = self.deserialize(self.fmt, vmt)
hwt = self._create_hosting_device_template(
self.fmt, HW_TEMPLATE_NAME, True, HW_CATEGORY)
hw_template = self.deserialize(self.fmt, hwt)
return {'network_node': {'template': nw_node_template,
'router_type': NS_ROUTERTYPE_NAME},
'vm': {'template': vm_template,
'router_type': VM_ROUTERTYPE_NAME},
'hw': {'template': hw_template,
'router_type': HW_ROUTERTYPE_NAME}}
def _test_remove_hosting_device_templates(self):
for hdt in self._list('hosting_device_templates')[
'hosting_device_templates']:
self._delete('hosting_device_templates', hdt['id'])
class TestDeviceManagerDBPlugin(
test_db_base_plugin_v2.NeutronDbPluginV2TestCase,
DeviceManagerTestCaseMixin,
device_manager_test_support.DeviceManagerTestSupportMixin):
hdm_db.HostingDeviceManagerMixin.path_prefix = "/dev_mgr"
resource_prefix_map = dict(
(k, "/dev_mgr")
for k in ciscohostingdevicemanager.RESOURCE_ATTRIBUTE_MAP.keys())
def setUp(self, core_plugin=None, dm_plugin=None, ext_mgr=None):
if dm_plugin is None:
dm_plugin = DB_DM_PLUGIN_KLASS
service_plugins = {'dm_plugin_name': dm_plugin}
cfg.CONF.set_override('api_extensions_path',
device_manager_test_support.extensions_path)
# for these tests we need to enable overlapping ips
cfg.CONF.set_default('allow_overlapping_ips', True)
hdm_db.HostingDeviceManagerMixin.supported_extension_aliases = (
[ciscohostingdevicemanager.HOSTING_DEVICE_MANAGER_ALIAS])
super(TestDeviceManagerDBPlugin, self).setUp(
plugin=core_plugin, service_plugins=service_plugins,
ext_mgr=ext_mgr)
# Ensure we use policy definitions from our repo
cfg.CONF.set_override('policy_file', policy_path, 'oslo_policy')
if not ext_mgr:
self.plugin = importutils.import_object(dm_plugin)
ext_mgr = api_ext.PluginAwareExtensionManager(
device_manager_test_support.extensions_path,
{c_constants.DEVICE_MANAGER: self.plugin})
app = config.load_paste_app('extensions_test_app')
self.ext_api = api_ext.ExtensionMiddleware(app, ext_mgr=ext_mgr)
self._mock_l3_admin_tenant()
self._create_mgmt_nw_for_tests(self.fmt)
self._devmgr = NeutronManager.get_service_plugins()[
c_constants.DEVICE_MANAGER]
# in unit tests we don't use keystone so we mock that session
self._devmgr._svc_vm_mgr_obj = service_vm_lib.ServiceVMManager(
True, None, None, None, '', keystone_session=mock.MagicMock())
self._mock_svc_vm_create_delete(self._devmgr)
self._other_tenant_id = device_manager_test_support._uuid()
self._devmgr._core_plugin = NeutronManager.get_plugin()
def tearDown(self):
self._test_remove_all_hosting_devices()
self._remove_mgmt_nw_for_tests()
super(TestDeviceManagerDBPlugin, self).tearDown()
def test_create_vm_hosting_device(self):
with self.hosting_device_template() as hdt:
with self.port(subnet=self._mgmt_subnet) as mgmt_port:
creds = device_manager_test_support._uuid()
attrs = self._get_test_hosting_device_attr(
template_id=hdt['hosting_device_template']['id'],
management_port_id=mgmt_port['port']['id'],
auto_delete=True, credentials_id=creds)
with self.hosting_device(
template_id=hdt['hosting_device_template']['id'],
management_port_id=mgmt_port['port']['id'],
auto_delete=True, credentials_id=creds) as hd:
for k, v in six.iteritems(attrs):
self.assertEqual(hd['hosting_device'][k], v)
def test_create_hw_hosting_device(self):
with self.hosting_device_template(host_category=HW_CATEGORY) as hdt:
with self.port(subnet=self._mgmt_subnet) as mgmt_port:
creds = device_manager_test_support._uuid()
attrs = self._get_test_hosting_device_attr(
template_id=hdt['hosting_device_template']['id'],
management_port_id=mgmt_port['port']['id'],
credentials_id=creds)
with self.hosting_device(
template_id=hdt['hosting_device_template']['id'],
management_port_id=mgmt_port['port']['id'],
credentials_id=creds) as hd:
for k, v in six.iteritems(attrs):
self.assertEqual(hd['hosting_device'][k], v)
def test_show_hosting_device(self):
device_id = "device_XYZ"
with self.hosting_device_template() as hdt:
with self.port(subnet=self._mgmt_subnet) as mgmt_port:
creds = device_manager_test_support._uuid()
attrs = self._get_test_hosting_device_attr(
device_id=device_id,
template_id=hdt['hosting_device_template']['id'],
management_port_id=mgmt_port['port']['id'],
credentials_id=creds)
with self.hosting_device(
device_id=device_id,
template_id=hdt['hosting_device_template']['id'],
management_port_id=mgmt_port['port']['id'],
credentials_id=creds) as hd:
req = self.new_show_request(
'hosting_devices', hd['hosting_device']['id'],
fmt=self.fmt)
res = self.deserialize(self.fmt,
req.get_response(self.ext_api))
for k, v in six.iteritems(attrs):
self.assertEqual(res['hosting_device'][k], v)
def test_list_hosting_devices(self):
with self.hosting_device_template() as hdt:
hdt_id = hdt['hosting_device_template']['id']
with self.port(subnet=self._mgmt_subnet) as mgmt_port1,\
self.port(subnet=self._mgmt_subnet) as mgmt_port2,\
self.port(subnet=self._mgmt_subnet) as mgmt_port3:
mp1_id = mgmt_port1['port']['id']
mp2_id = mgmt_port2['port']['id']
mp3_id = mgmt_port3['port']['id']
with self.hosting_device(
name='hd1', template_id=hdt_id,
management_port_id=mp1_id) as hd1,\
self.hosting_device(
name='hd2', template_id=hdt_id,
management_port_id=mp2_id) as hd2,\
self.hosting_device(
name='hd3', template_id=hdt_id,
management_port_id=mp3_id) as hd3:
self._test_list_resources(
'hosting_device', [hd1, hd2, hd3],
query_params='template_id=' + hdt_id)
def test_update_hosting_device(self):
new_device_id = "device_XYZ"
with self.hosting_device_template() as hdt:
hdt_id = hdt['hosting_device_template']['id']
with self.port(subnet=self._mgmt_subnet) as mgmt_port:
mgmt_port_id = mgmt_port['port']['id']
creds = device_manager_test_support._uuid()
attrs = self._get_test_hosting_device_attr(
device_id=new_device_id,
template_id=hdt['hosting_device_template']['id'],
management_port_id=mgmt_port['port']['id'],
credentials_id=creds)
with self.hosting_device(
template_id=hdt_id,
management_port_id=mgmt_port_id,
credentials_id=creds) as hd:
data = {'hosting_device': {'device_id': new_device_id}}
req = self.new_update_request('hosting_devices', data,
hd['hosting_device']['id'])
res = self.deserialize(self.fmt,
req.get_response(self.ext_api))
for k, v in six.iteritems(attrs):
self.assertEqual(res['hosting_device'][k], v)
def test_delete_hosting_device_not_in_use_succeeds(self):
ctx = n_context.get_admin_context()
with self.hosting_device_template() as hdt:
hdt_id = hdt['hosting_device_template']['id']
with self.port(subnet=self._mgmt_subnet) as mgmt_port:
mgmt_port_id = mgmt_port['port']['id']
with self.hosting_device(template_id=hdt_id,
management_port_id=mgmt_port_id,
no_delete=True) as hd:
hd_id = hd['hosting_device']['id']
req = self.new_delete_request('hosting_devices', hd_id)
res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, 204)
self.assertRaises(
ciscohostingdevicemanager.HostingDeviceNotFound,
self.plugin.get_hosting_device, ctx, hd_id)
def test_delete_hosting_device_in_use_fails(self):
ctx = n_context.get_admin_context()
with self.hosting_device_template(slot_capacity=1) as hdt:
hdt_id = hdt['hosting_device_template']['id']
with self.port(subnet=self._mgmt_subnet) as mgmt_port:
mgmt_port_id = mgmt_port['port']['id']
with self.hosting_device(
template_id=hdt_id,
management_port_id=mgmt_port_id) as hd:
with mock.patch.object(
hdm_db.HostingDeviceManagerMixin,
'_dispatch_pool_maintenance_job'):
hd_id = hd['hosting_device']['id']
hd_db = self._devmgr._get_hosting_device(ctx, hd_id)
resource = self._get_fake_resource()
self.assertTrue(
self._devmgr.acquire_hosting_device_slots(
ctx, hd_db, resource, 'router', L3_ROUTER_NAT,
1))
self.assertRaises(
ciscohostingdevicemanager.HostingDeviceInUse,
self._devmgr.delete_hosting_device, ctx, hd_id)
req = self.new_show_request('hosting_devices', hd_id,
fmt=self.fmt)
res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, 200)
self._devmgr.release_hosting_device_slots(ctx, hd_db,
resource, 1)
def test_get_hosting_device_configuration(self):
with self.hosting_device_template() as hdt:
hdt_id = hdt['hosting_device_template']['id']
with self.port(subnet=self._mgmt_subnet) as mgmt_port:
mgmt_port_id = mgmt_port['port']['id']
with self.hosting_device(
template_id=hdt_id,
management_port_id=mgmt_port_id) as hd:
hd_id = hd['hosting_device']['id']
rpc = devmgr_rpc_cfgagent_api.DeviceMgrCfgAgentNotifyAPI(
self._devmgr)
self._devmgr.agent_notifiers = {
c_constants.AGENT_TYPE_CFG: rpc}
self._devmgr.get_cfg_agents_for_hosting_devices = None
with mock.patch.object(rpc.client, 'prepare',
return_value=rpc.client) as (
mock_prepare),\
mock.patch.object(rpc.client, 'call') as mock_call,\
mock.patch.object(
self._devmgr,
'get_cfg_agents_for_hosting_devices') as agt_mock:
agt_mock.return_value = [mock.MagicMock()]
agent_host = 'an_agent_host'
agt_mock.return_value[0].host = agent_host
fake_running_config = 'a fake running config'
mock_call.return_value = fake_running_config
ctx = n_context.Context(
user_id=None, tenant_id=None, is_admin=False,
overwrite=False)
res = self._devmgr.get_hosting_device_config(ctx,
hd_id)
self.assertEqual(res, fake_running_config)
agt_mock.assert_called_once_with(
mock.ANY, [hd_id], admin_state_up=True,
schedule=True)
mock_prepare.assert_called_with(server=agent_host)
mock_call.assert_called_with(
mock.ANY, 'get_hosting_device_configuration',
payload={'hosting_device_id': hd_id})
def test_get_hosting_device_configuration_no_agent_found(self):
ctx = n_context.Context(user_id=None, tenant_id=None, is_admin=False,
overwrite=False)
with self.hosting_device_template() as hdt:
hdt_id = hdt['hosting_device_template']['id']
with self.port(subnet=self._mgmt_subnet) as mgmt_port:
mgmt_port_id = mgmt_port['port']['id']
with self.hosting_device(
template_id=hdt_id,
management_port_id=mgmt_port_id) as hd:
hd_id = hd['hosting_device']['id']
rpc = devmgr_rpc_cfgagent_api.DeviceMgrCfgAgentNotifyAPI(
self._devmgr)
self._devmgr.agent_notifiers = {
c_constants.AGENT_TYPE_CFG: rpc}
self._devmgr.get_cfg_agents_for_hosting_devices = None
with mock.patch.object(rpc.client, 'prepare',
return_value=rpc.client) as (
mock_prepare),\
mock.patch.object(rpc.client, 'call') as mock_call,\
mock.patch.object(
self._devmgr,
'get_cfg_agents_for_hosting_devices') as agt_mock:
agt_mock.return_value = []
res = self._devmgr.get_hosting_device_config(ctx,
hd_id)
self.assertIsNone(res)
agt_mock.assert_called_once_with(
mock.ANY, [hd_id], admin_state_up=True,
schedule=True)
self.assertEqual(mock_prepare.call_count, 0)
self.assertEqual(mock_call.call_count, 0)
def test_hosting_device_policy(self):
device_id = "device_XYZ"
with self.hosting_device_template() as hdt:
hdt_id = hdt['hosting_device_template']['id']
tenant_id = hdt['hosting_device_template']['tenant_id']
with self.port(subnet=self._mgmt_subnet) as mgmt_port:
mgmt_port_id = mgmt_port['port']['id']
creds = device_manager_test_support._uuid()
with self.hosting_device(
device_id=device_id,
template_id=hdt_id,
management_port_id=mgmt_port_id,
credentials_id=creds) as hd:
hd_id = hd['hosting_device']['id']
# create fails
self._create_hosting_device(
self.fmt, hdt_id, mgmt_port_id, True,
webob.exc.HTTPForbidden.code,
tenant_id=tenant_id, set_context=True)
non_admin_ctx = n_context.Context('', tenant_id)
# show fails
self._show('hosting_devices', hd_id,
webob.exc.HTTPNotFound.code, non_admin_ctx)
# update fails
self._update('hosting_devices', hd_id,
{'hosting_device': {'name': 'new_name'}},
webob.exc.HTTPForbidden.code, non_admin_ctx)
# delete fails
self._delete('hosting_devices', hd_id,
webob.exc.HTTPNotFound.code, non_admin_ctx)
# get config fails
req = self.new_show_request(
'hosting_devices', hd_id, self.fmt,
'get_hosting_device_config')
req.environ['neutron.context'] = non_admin_ctx
res = req.get_response(self._api_for_resource(
'hosting_devices'))
self.assertEqual(webob.exc.HTTPNotFound.code,
res.status_int)
def test_create_vm_hosting_device_template(self):
attrs = self._get_test_hosting_device_template_attr()
with self.hosting_device_template() as hdt:
for k, v in six.iteritems(attrs):
self.assertEqual(hdt['hosting_device_template'][k], v)
def test_create_hw_hosting_device_template(self):
attrs = self._get_test_hosting_device_template_attr(
host_category=HW_CATEGORY)
with self.hosting_device_template(host_category=HW_CATEGORY) as hdt:
for k, v in six.iteritems(attrs):
self.assertEqual(hdt['hosting_device_template'][k], v)
def test_create_nn_hosting_device_template(self):
attrs = self._get_test_hosting_device_template_attr(
host_category=NN_CATEGORY)
with self.hosting_device_template(host_category=NN_CATEGORY) as hdt:
for k, v in six.iteritems(attrs):
self.assertEqual(hdt['hosting_device_template'][k], v)
def test_show_hosting_device_template(self):
name = "hosting_device_template1"
attrs = self._get_test_hosting_device_template_attr(name=name)
with self.hosting_device_template(name=name) as hdt:
req = self.new_show_request('hosting_device_templates',
hdt['hosting_device_template']['id'],
fmt=self.fmt)
res = self.deserialize(self.fmt,
req.get_response(self.ext_api))
for k, v in six.iteritems(attrs):
self.assertEqual(res['hosting_device_template'][k], v)
def test_list_hosting_device_templates(self):
with self.hosting_device_template(name='hdt1',
host_category=VM_CATEGORY,
image='an_image') as hdt1,\
self.hosting_device_template(name='hdt2',
host_category=HW_CATEGORY,
image='an_image') as hdt2,\
self.hosting_device_template(name='hdt3',
host_category=NN_CATEGORY,
image='an_image') as hdt3:
self._test_list_resources(
'hosting_device_template', [hdt1, hdt2, hdt3],
query_params='image=an_image')
def test_update_hosting_device_template(self):
name = "new_hosting_device_template1"
attrs = self._get_test_hosting_device_template_attr(name=name)
with self.hosting_device_template() as hdt:
data = {'hosting_device_template': {'name': name}}
req = self.new_update_request('hosting_device_templates', data,
hdt['hosting_device_template']['id'])
res = self.deserialize(self.fmt,
req.get_response(self.ext_api))
for k, v in six.iteritems(attrs):
self.assertEqual(res['hosting_device_template'][k], v)
def test_delete_hosting_device_template_not_in_use_succeeds(self):
ctx = n_context.get_admin_context()
with self.hosting_device_template(no_delete=True) as hdt:
hdt_id = hdt['hosting_device_template']['id']
req = self.new_delete_request('hosting_device_templates', hdt_id)
res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, 204)
self.assertRaises(
ciscohostingdevicemanager.HostingDeviceTemplateNotFound,
self._devmgr.get_hosting_device_template, ctx, hdt_id)
def test_delete_hosting_device_template_in_use_fails(self):
ctx = n_context.get_admin_context()
with self.hosting_device_template() as hdt:
hdt_id = hdt['hosting_device_template']['id']
with self.port(subnet=self._mgmt_subnet) as mgmt_port:
mgmt_port_id = mgmt_port['port']['id']
with self.hosting_device(template_id=hdt_id,
management_port_id=mgmt_port_id):
self.assertRaises(
ciscohostingdevicemanager.HostingDeviceTemplateInUse,
self._devmgr.delete_hosting_device_template, ctx,
hdt_id)
req = self.new_show_request('hosting_device_templates',
hdt_id, fmt=self.fmt)
res = req.get_response(self.ext_api)
self.assertEqual(res.status_int, 200)
def test_hosting_device_template_policy(self):
with self.hosting_device_template() as hdt:
hdt_id = hdt['hosting_device_template']['id']
tenant_id = hdt['hosting_device_template']['tenant_id']
# create fails
self._create_hosting_device_template(
self.fmt, 'my_template', True, 'Hardware',
webob.exc.HTTPForbidden.code,
tenant_id=tenant_id, set_context=True)
non_admin_ctx = n_context.Context('', tenant_id)
# show fail
self._show('hosting_device_templates', hdt_id,
webob.exc.HTTPNotFound.code, non_admin_ctx)
# update fail
self._update('hosting_device_templates', hdt_id,
{'hosting_device_template': {'enabled': False}},
webob.exc.HTTPForbidden.code, non_admin_ctx)
# delete fail
self._delete('hosting_device_templates', hdt_id,
webob.exc.HTTPNotFound.code, non_admin_ctx)
# driver request test helper
def _test_get_driver(self, get_method, id=None, test_for_none=False,
is_admin=False):
with self.hosting_device_template() as hdt:
context = self._get_test_context(
tenant_id=hdt['hosting_device_template']['tenant_id'],
is_admin=is_admin)
driver_getter = getattr(self._devmgr, get_method)
template_id = id or hdt['hosting_device_template']['id']
driver = driver_getter(context, template_id)
if test_for_none:
self.assertIsNone(driver)
else:
self.assertIsNotNone(driver)
# driver request tests
def test_get_hosting_device_driver(self):
self._test_get_driver('get_hosting_device_driver')
def test_get_non_existent_hosting_device_driver_returns_none(self):
self._test_get_driver('get_hosting_device_driver', 'bogus_id', True)
def test_get_plugging_device_driver(self):
self._test_get_driver('get_hosting_device_plugging_driver')
def test_get_non_existent_plugging_device_driver_returns_none(self):
self._test_get_driver('get_hosting_device_plugging_driver', 'bogus_id',
True)
# get device info tests
def test_get_device_info_for_agent(self):
device_id = "device_XYZ"
with self.hosting_device_template() as hdt, self.port(
subnet=self._mgmt_subnet) as mgmt_port:
creds = device_manager_test_support._uuid()
mgmt_ip = mgmt_port['port']['fixed_ips'][0]['ip_address']
with self.hosting_device(
device_id=device_id,
template_id=hdt['hosting_device_template']['id'],
management_port_id=mgmt_port['port']['id'],
credentials_id=creds) as hd:
context = self._get_test_context(
tenant_id=hdt['hosting_device_template']['tenant_id'],
is_admin=True)
hd_id = hd['hosting_device']['id']
hd_db = self._devmgr._get_hosting_device(context, hd_id)
info = self._devmgr.get_device_info_for_agent(context, hd_db)
self.assertEqual(info['management_ip_address'], mgmt_ip)
def test_get_device_info_for_agent_no_mgmt_port(self):
device_id = "device_XYZ"
with self.hosting_device_template() as hdt:
creds = device_manager_test_support._uuid()
mgmt_ip = '192.168.0.55'
with self.hosting_device(
device_id=device_id,
template_id=hdt['hosting_device_template']['id'],
management_ip_address=mgmt_ip,
management_port_id=None,
credentials_id=creds) as hd:
context = self._get_test_context(
tenant_id=hdt['hosting_device_template']['tenant_id'],
is_admin=True)
hd_id = hd['hosting_device']['id']
hd_db = self._devmgr._get_hosting_device(context, hd_id)
info = self._devmgr.get_device_info_for_agent(context, hd_db)
self.assertEqual(info['management_ip_address'], mgmt_ip)
def _set_ownership(self, bound_status, tenant_id, other_tenant_id=None):
if bound_status == UNBOUND:
return None
elif bound_status == OTHER:
return other_tenant_id or self._other_tenant_id
else:
return tenant_id
# slot allocation and release test helper:
# succeeds means returns True, fails means returns False
def _test_slots(self, expected_result=True, expected_bind=UNBOUND,
expected_allocation=VM_SLOT_CAPACITY,
num_requested=VM_SLOT_CAPACITY,
slot_capacity=VM_SLOT_CAPACITY, initial_bind=UNBOUND,
bind=False, auto_delete=True, is_admin=False,
pool_maintenance_expected=True, test_release=False,
expected_release_result=True, expected_final_allocation=0,
expected_release_bind=UNBOUND,
num_to_release=VM_SLOT_CAPACITY,
release_pool_maintenance_expected=True):
with self.hosting_device_template(
slot_capacity=slot_capacity) as hdt:
with self.port(subnet=self._mgmt_subnet) as mgmt_port:
resource = self._get_fake_resource()
tenant_bound = self._set_ownership(
initial_bind, resource['tenant_id'])
with self.hosting_device(
template_id=hdt['hosting_device_template']['id'],
management_port_id=mgmt_port['port']['id'],
tenant_bound=tenant_bound,
auto_delete=auto_delete) as hd:
context = self._get_test_context(
tenant_id=hdt['hosting_device_template']['tenant_id'],
is_admin=is_admin)
hd_db = self._devmgr._get_hosting_device(
context, hd['hosting_device']['id'])
with mock.patch.object(
hdm_db.HostingDeviceManagerMixin,
'_dispatch_pool_maintenance_job') as pm_mock:
result = self._devmgr.acquire_hosting_device_slots(
context, hd_db, resource, 'router', L3_ROUTER_NAT,
num_requested, bind)
allocation = self._devmgr.get_slot_allocation(
context, resource_id=resource['id'])
self.assertEqual(result, expected_result)
self.assertEqual(allocation, expected_allocation)
expected_bind = self._set_ownership(
expected_bind, resource['tenant_id'])
self.assertEqual(hd_db.tenant_bound, expected_bind)
if pool_maintenance_expected:
pm_mock.assert_called_once_with(mock.ANY)
num_calls = 1
else:
pm_mock.assert_not_called()
num_calls = 0
if test_release:
result = self._devmgr.release_hosting_device_slots(
context, hd_db, resource, num_to_release)
if not test_release:
return
allocation = self._devmgr.get_slot_allocation(
context, resource_id=resource['id'])
self.assertEqual(result, expected_release_result)
self.assertEqual(allocation,
expected_final_allocation)
expected_release_bind = self._set_ownership(
expected_release_bind, resource['tenant_id'])
self.assertEqual(hd_db.tenant_bound,
expected_release_bind)
if release_pool_maintenance_expected:
num_calls += 1
self.assertEqual(pm_mock.call_count, num_calls)
else:
# ensure we clean up everything
num_to_release = 0
to_clean_up = num_requested - num_to_release
if to_clean_up < 0:
to_clean_up = num_requested
if to_clean_up:
self._devmgr.release_hosting_device_slots(
context, hd_db, resource, to_clean_up)
# slot allocation tests
def test_acquire_with_slot_surplus_in_owned_hosting_device_succeeds(self):
self._test_slots(expected_bind=REQUESTER, initial_bind=REQUESTER,
bind=True)
def test_acquire_with_slot_surplus_in_shared_hosting_device_succeeds(self):
self._test_slots()
def test_acquire_with_slot_surplus_take_hosting_device_ownership_succeeds(
self):
self._test_slots(expected_bind=REQUESTER, initial_bind=UNBOUND,
bind=True)
def test_acquire_with_slot_surplus_drop_hosting_device_ownership_succeeds(
self):
self._test_slots(expected_bind=UNBOUND, initial_bind=REQUESTER,
bind=False)
def test_acquire_slots_release_hosting_device_ownership_affects_all(self):
#TODO(bobmel): Implement this unit test
pass
def test_acquire_slots_in_other_owned_hosting_device_fails(self):
self._test_slots(expected_result=False, expected_bind=OTHER,
expected_allocation=0, initial_bind=OTHER,
pool_maintenance_expected=False)
def test_acquire_slots_take_ownership_of_other_owned_hosting_device_fails(
self):
self._test_slots(expected_result=False, expected_bind=OTHER,
expected_allocation=0, initial_bind=OTHER,
bind=True, pool_maintenance_expected=False)
def test_acquire_slots_take_ownership_of_multi_tenant_hosting_device_fails(
self):
#TODO(bobmel): Implement this unit test
pass
def test_acquire_with_slot_deficit_in_owned_hosting_device_fails(self):
self._test_slots(expected_result=False, expected_bind=REQUESTER,
expected_allocation=0, initial_bind=REQUESTER,
num_requested=VM_SLOT_CAPACITY + 1)
def test_acquire_with_slot_deficit_in_shared_hosting_device_fails(self):
self._test_slots(expected_result=False, expected_bind=UNBOUND,
expected_allocation=0,
num_requested=VM_SLOT_CAPACITY + 1)
def test_acquire_with_slot_deficit_in_other_owned_hosting_device_fails(
self):
self._test_slots(expected_result=False, expected_bind=OTHER,
expected_allocation=0, initial_bind=OTHER,
num_requested=VM_SLOT_CAPACITY + 1,
pool_maintenance_expected=False)
# slot release tests
def test_release_allocated_slots_in_owned_hosting_device_succeeds(self):
self._test_slots(expected_bind=REQUESTER, initial_bind=REQUESTER,
bind=True, test_release=True,
expected_release_bind=REQUESTER,
expected_final_allocation=1,
num_to_release=VM_SLOT_CAPACITY - 1)
def test_release_allocated_slots_in_shared_hosting_device_succeeds(self):
self._test_slots(test_release=True, expected_final_allocation=1,
num_to_release=VM_SLOT_CAPACITY - 1)
def test_release_all_slots_returns_hosting_device_ownership(self):
self._test_slots(expected_bind=REQUESTER, initial_bind=REQUESTER,
bind=True, test_release=True,
expected_release_bind=UNBOUND)
def test_release_slots_in_other_owned_hosting_device_fails(self):
self._test_slots(expected_result=False, expected_bind=OTHER,
expected_allocation=0, initial_bind=OTHER,
pool_maintenance_expected=False,
test_release=True, expected_release_result=False,
expected_release_bind=OTHER,
expected_final_allocation=0,
num_to_release=VM_SLOT_CAPACITY - 1,
release_pool_maintenance_expected=False)
def test_release_too_many_slots_in_owned_hosting_device_fails(self):
self._test_slots(expected_bind=REQUESTER, initial_bind=REQUESTER,
bind=True, test_release=True,
expected_release_result=False,
expected_release_bind=REQUESTER,
expected_final_allocation=VM_SLOT_CAPACITY,
num_to_release=VM_SLOT_CAPACITY + 1)
def test_release_too_many_slots_in_shared_hosting_device_fails(self):
self._test_slots(test_release=True, expected_release_result=False,
expected_release_bind=UNBOUND,
expected_final_allocation=VM_SLOT_CAPACITY,
num_to_release=VM_SLOT_CAPACITY + 1)
def test_release_too_many_slots_in_other_owned_hosting_device_fails(
self):
self._test_slots(expected_result=False, expected_bind=OTHER,
expected_allocation=0, initial_bind=OTHER,
pool_maintenance_expected=False,
test_release=True, expected_release_result=False,
expected_release_bind=OTHER,
expected_final_allocation=0,
num_to_release=VM_SLOT_CAPACITY + 1,
release_pool_maintenance_expected=False)
def test_release_all_slots_by_negative_num_argument_shared_hosting_device(
self):
self._test_slots(test_release=True, expected_final_allocation=0,
num_to_release=-1)
def test_release_all_slots_by_negative_num_argument_owned_hosting_device(
self):
self._test_slots(expected_bind=REQUESTER, initial_bind=REQUESTER,
bind=True, test_release=True, expected_release_bind=UNBOUND,
expected_final_allocation=0, num_to_release=-1)
# hosting device deletion test helper
def _test_delete(self, to_delete=None, auto_delete=None, no_delete=None,
force_delete=True, expected_num_remaining=0):
auto_delete = auto_delete or [True, False, False, True, True]
no_delete = no_delete or [True, True, True, True, True]
with self.hosting_device_template() as hdt1,\
self.hosting_device_template() as hdt2:
hdt0_id = hdt1['hosting_device_template']['id']
hdt1_id = hdt2['hosting_device_template']['id']
with self.port(subnet=self._mgmt_subnet,
no_delete=no_delete[0]) as mgmt_port0,\
self.port(subnet=self._mgmt_subnet,
no_delete=no_delete[1]) as mgmt_port1,\
self.port(subnet=self._mgmt_subnet,
no_delete=no_delete[2]) as mgmt_port2,\
self.port(subnet=self._mgmt_subnet,
no_delete=no_delete[3]) as mgmt_port3,\
self.port(subnet=self._mgmt_subnet,
no_delete=no_delete[4]) as mgmt_port4:
mp0_id = mgmt_port0['port']['id']
mp1_id = mgmt_port1['port']['id']
mp2_id = mgmt_port2['port']['id']
mp3_id = mgmt_port3['port']['id']
mp4_id = mgmt_port4['port']['id']
with self.hosting_device(
device_id='0_hdt0_id', template_id=hdt0_id,
management_port_id=mp0_id, auto_delete=auto_delete[0],
no_delete=no_delete[0]),\
self.hosting_device(
device_id='1_hdt1_id', template_id=hdt1_id,
management_port_id=mp1_id, auto_delete=auto_delete[1],
no_delete=no_delete[1]),\
self.hosting_device(
device_id='2_hdt0_id', template_id=hdt0_id,
management_port_id=mp2_id, auto_delete=auto_delete[2],
no_delete=no_delete[2]),\
self.hosting_device(
device_id='3_hdt0_id', template_id=hdt0_id,
management_port_id=mp3_id,
auto_delete=auto_delete[3],
no_delete=no_delete[3]),\
self.hosting_device(
device_id='4_hdt1_id', template_id=hdt1_id,
management_port_id=mp4_id, auto_delete=auto_delete[4],
no_delete=no_delete[4]):
context = self._get_test_context(is_admin=True)
if to_delete is None:
self._devmgr.delete_all_hosting_devices(
context, force_delete)
elif to_delete == 0:
template = (
self._devmgr._get_hosting_device_template(
context, hdt0_id))
(self._devmgr.
delete_all_hosting_devices_by_template(
context, template, force_delete))
else:
template = (
self._devmgr._get_hosting_device_template(
context, hdt1_id))
(self._devmgr.
delete_all_hosting_devices_by_template(
context, template, force_delete))
result_hds = self._list(
'hosting_devices')['hosting_devices']
self.assertEqual(len(result_hds),
expected_num_remaining)
# hosting device deletion tests
def test_delete_all_hosting_devices(self):
self._test_delete()
def test_delete_all_managed_hosting_devices(self):
self._test_delete(no_delete=[True, False, False, True, True],
force_delete=False, expected_num_remaining=2)
def test_delete_all_hosting_devices_by_template(self):
self._test_delete(to_delete=1, expected_num_remaining=3,
no_delete=[False, True, False, False, True])
def test_delete_all_managed_hosting_devices_by_template(self):
self._test_delete(to_delete=1, expected_num_remaining=4,
no_delete=[False, False, False, False, True],
force_delete=False)
# handled failed hosting device test helper
def _test_failed_hosting_device(self, host_category=VM_CATEGORY,
expected_num_remaining=0,
auto_delete=True, no_delete=True):
with self.hosting_device_template(host_category=host_category) as hdt:
hdt_id = hdt['hosting_device_template']['id']
with self.port(subnet=self._mgmt_subnet,
no_delete=no_delete) as mgmt_port:
with self.hosting_device(
template_id=hdt_id,
management_port_id=mgmt_port['port']['id'],
auto_delete=auto_delete, no_delete=no_delete) as hd:
with mock.patch('neutron.manager.NeutronManager.'
'get_service_plugins'):
hd_id = hd['hosting_device']['id']
m2 = mock.MagicMock()
self._devmgr.agent_notifiers = {
c_constants.AGENT_TYPE_CFG: m2}
context = self._get_test_context()
self._devmgr.handle_non_responding_hosting_devices(
context, None, [hd_id])
result_hds = self._list('hosting_devices')[
'hosting_devices']
self.assertEqual(len(result_hds),
expected_num_remaining)
l3mock = (NeutronManager.get_service_plugins().get().
handle_non_responding_hosting_devices)
l3mock.assert_called_once_with(mock.ANY, mock.ANY,
{hd_id: {}})
if expected_num_remaining == 0:
m2.hosting_devices_removed.assert_called_once_with(
mock.ANY, {hd_id: {}}, False, None)
# handled failed hosting device tests
def test_failed_managed_vm_based_hosting_device_gets_deleted(self):
self._test_failed_hosting_device()
def test_failed_non_managed_vm_based_hosting_device_not_deleted(self):
self._test_failed_hosting_device(expected_num_remaining=1,
auto_delete=False, no_delete=False)
def test_failed_non_vm_based_hosting_device_not_deleted(self):
self._test_failed_hosting_device(host_category=HW_CATEGORY,
expected_num_remaining=1,
no_delete=False)
# hosting device pool maintenance test helper
def _test_pool_maintenance(self, desired_slots_free=10, slot_capacity=3,
host_category=VM_CATEGORY, expected=15,
define_credentials=True):
with self.hosting_device_template(
host_category=host_category, slot_capacity=slot_capacity,
desired_slots_free=desired_slots_free,
plugging_driver=TEST_PLUGGING_DRIVER) as hdt:
hdt_id = hdt['hosting_device_template']['id']
creds_id = (DEFAULT_CREDENTIALS_ID if define_credentials is True
else 'non_existent_id')
credentials = {'user_name': 'bob', 'password': 'tooEasy'}
with mock.patch.dict(
self.plugin._credentials,
{creds_id: credentials}),\
self.port(subnet=self._mgmt_subnet,
no_delete=True) as mgmt_port1,\
self.port(subnet=self._mgmt_subnet,
no_delete=True) as mgmt_port2:
with self.hosting_device(
template_id=hdt_id,
management_port_id=mgmt_port1['port']['id'],
auto_delete=True, no_delete=True),\
self.hosting_device(
template_id=hdt_id,
management_port_id=mgmt_port2['port']['id'],
auto_delete=True, no_delete=True):
context = self._get_test_context(is_admin=True)
template = self._devmgr._get_hosting_device_template(
context, hdt_id)
self._devmgr._gt_pool = mock.MagicMock()
self._devmgr._gt_pool.spawn_n.side_effect = (
lambda fcn, ctx, tmplt: fcn(ctx, tmplt))
self._devmgr._dispatch_pool_maintenance_job(
template)
result_hds = self._list(
'hosting_devices')['hosting_devices']
self.assertEqual(len(result_hds) * slot_capacity,
expected)
self._devmgr.delete_all_hosting_devices(context, True)
# hosting device pool maintenance tests
def test_vm_based_hosting_device_excessive_slot_deficit_adds_slots(self):
self._test_pool_maintenance()
def test_vm_based_hosting_device_excessive_slot_deficit_no_credentials(
self):
# no slots are added if credentials for template are missing
self._test_pool_maintenance(expected=6, define_credentials=False)
def test_vm_based_hosting_device_marginal_slot_deficit_no_change(self):
self._test_pool_maintenance(desired_slots_free=7, expected=6)
def test_vm_based_hosting_device_excessive_slot_surplus_removes_slots(
self):
self._test_pool_maintenance(desired_slots_free=3, expected=3)
def test_vm_based_hosting_device_marginal_slot_surplus_no_change(self):
self._test_pool_maintenance(desired_slots_free=5, expected=6)
def test_hw_based_hosting_device_no_change(self):
self._test_pool_maintenance(host_category=HW_CATEGORY, expected=6)
| {
"content_hash": "310981a18cbc32b789579ca8626c1825",
"timestamp": "",
"source": "github",
"line_count": 1124,
"max_line_length": 79,
"avg_line_length": 51.69928825622776,
"alnum_prop": 0.5309069007055585,
"repo_name": "CiscoSystems/networking-cisco",
"id": "58bd99006a1a96662cd02bf1d3d72e7dd3f955ac",
"size": "58744",
"binary": false,
"copies": "1",
"ref": "refs/heads/asr1k_liberty_master_wip",
"path": "networking_cisco/tests/unit/cisco/device_manager/test_db_device_manager.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Mako",
"bytes": "1043"
},
{
"name": "Python",
"bytes": "2082062"
},
{
"name": "Shell",
"bytes": "44368"
}
],
"symlink_target": ""
} |
Gone is a wiki engine written in [Go](http://golang.org). It's
* KISS,
* Convention over Configuration and
* designed with Developers and Admins in mind.
With Gone, you can
* display Markdown, HTML and Plaintext straight from the filesystem.
* edit just any file that's made of text.
* have all this without setup, no database needed, not even the tinyest configuration.
So go get it!
[](https://travis-ci.org/fxnn/gone)
[](https://godoc.org/github.com/fxnn/gone)
[](https://coveralls.io/github/fxnn/gone?branch=master)
## Installation
Assure that you have [Go installed](https://golang.org/doc/install).
Now, install the application via `go get`.
```console
$ go get github.com/fxnn/gone
```
Binary releases will follow.
## Usage
You can simply start Gone by calling its binary.
```console
$ gone
```
The current working directory will now be served on port `8080`.
* *Display content.*
The file `test.md` in that working directory is now accessible as `http://localhost:8080/test.md`.
It's a [Markdown](https://en.wikipedia.org/wiki/Markdown) file, but Gone delivers a rendered webpage.
Other files (text, HTML, PDF, ...) would simply be rendered as they are.
* *Editing just anything that's made of text.*
In your browser, append `?edit` in the address bar.
Gone now sends you a text editor, allowing you to edit your file.
Your file doesn't exist yet? Use `?create` instead.
* *Customize everything.*
Change how Gone looks.
Call `gone export-templates`, and you will get the HTML, CSS and JavaScript behind Gone's frontend.
Modify it as you like.
See `gone -help` for usage information and configuration options.
## Access Control
_**NOTE,** that these features **only** apply to **UNIX** based OSs.
Especially the Windows implementation currently does not support most of the
access control features._
Gone uses the file system's access control features.
Of course, the Gone process can't read or write files it doesn't have a
permission to.
For example, if the Gone process is run by user `joe`, it won't be able to read
a file only user `ann` has read permission for (as with `rw-------`).
Likewise, an anonymous user being not logged in can't read or write files
through Gone, except those who have _world_ permissions.
For example, a file `rw-rw-r--` might be read by an anonymous user, but he
won't be able to change that file.
Also, in a directory `rwxrwxr-x`, only a user being logged in may create new files.
Users can login by appending `?login` to the URL.
The login information is configured in a good old `.htpasswd` file, placed in the working directory
of the Gone process.
Authenticated users can read and write all files that are readable
resp. writeable by the Gone process.
Note that there's a brute force blocker.
After each failed login attempt, the login request will be answered with an
increasing delay of up to 10 seconds.
The request delay is imposed per user, per IP address and globally.
The global delay, however, grows ten times slower than the other delays.
### Security considerations
* Authentication information are submitted without encryption, so *use SSL*!
* Anyone may read *and write* files just by assigning world read/write permissions, so better
`chmod -R o-rw *` if you want to keep your stuff secret!
* Gone uses the working directory for content delivery, so better use a start script which
invokes `cd`!
## Index documents, file names
Calling a directory, Gone will look for a file named `index`.
Calling any file that does not exist (including `index`), Gone will try to look
for files with a extension appended and use the first one in alphabetic order.
So, the file `http://localhost:8080/test.md` could also be referenced as
`http://localhost:8080/test`, as long as no `test` file exists.
In the same way, an `index.md` file can be used as index document and will fulfill
the above requirements.
This mechanism is transparent to the user, no redirect will happen.
## Links
When you create files with the extension `url` and put a URL inside it, Gone will serve
it as a temporary `302` redirect.
Example:
```console
$ echo "https://github.com" > github.url
```
A call to `http://localhost:8080/github` will get you redirected to GitHub now.
## Templates
Gone uses some Go templates for its UI.
The templates are shipped inside the executable, but you can use custom versions of them.
For general information on Go HTML templates, see the [html/template godoc](https://golang.org/pkg/html/template/).
With your web root as working directory, invoke `gone export-templates`.
It creates a new folder `.templates` which will never be delivered via HTTP.
You'll find all templates inside and can modify them.
If you (re)start Gone now, it will use the templates from that directory.
Note, that you can also supply a custom template path.
See `gone -help` for more information.
## Future
Some day, Gone might be
* extensible. Plugin in version control, renderers, compilers or anything you like, cf. https://github.com/fxnn/gone/issues/29
* granting file access on a group level, using a `htgroup` file.
* searchable in full text.
## Development
If you want to modify sources in this project, you might find the following information helpful.
### Third party software
Please note that the project uses the vendoring tool https://github.com/kardianos/govendor.
Also, we use the standard go `vendor` folder, which means that all external projects are vendored and to be found in the `vendor` folder.
A list of projects and versions is managed under [vendor/vendor.json](vendor/vendor.json).
If you build with go-1.5, enable the [GO15VENDOREXPERIMENT](https://golang.org/s/go15vendor) flag.
Gone imports code from following projects:
* [abbot/go-http-auth](https://github.com/abbot/go-http-auth) for HTTP basic authentication
* [fsnotify/fsnotify](https://github.com/fsnotify/fsnotify) for watching files
* [gorilla](https://github.com/gorilla), a great web toolkit for Go, used for sessions and cookies
* [russross/blackfriday](https://github.com/russross/blackfriday), a well-made markdown processor for Go
* [shurcooL/sanitized_anchor_name](https://github.com/shurcooL/sanitized_anchor_name) for making strings URL-compatible
* [golang.org/x/crypto](https://golang.org/x/crypto) for session-related cryptography
* [golang.org/x/net/context](https://golang.org/x/net/context) for request-scoped values
* [fxnn/gopath](https://github.com/fxnn/gopath) for easy handling of filesystem paths
Also, the following commands are used to build gone:
* [pierre/gotestcover](https://github.com/pierrre/gotestcover) to run tests with coverage analysis on multiple packages
* [mjibson/esc](https://github.com/mjibson/esc) for embedding files into the binary
Gone's frontend wouldn't be anything without
* [ajaxorg/ace](https://github.com/ajaxorg/ace), a great in-browser editor
## Architecture
+------+
| main |
+------+
| | |
+---------+ | +---------+
v v v
+-------+ +------+ +--------+
| store | | http | | config |
+-------+ +------+ +--------+
/ | \
+--------+ | +--------+
v v v
+--------+ +--------+ +--------+
| viewer | | editor | | router |
+--------+ +--------+ +--------+
`main` just implements the startup logic and integrates all other top-level
components.
Depending on what `config` returns, a command is executed, which by default
starts up the web server.
From now on, we have to main parts.
On the one hand, there is the `store` that implements the whole storage.
Currently, the only usable storage engine is the filesystem.
On the other hand, there is the `http` package that serves HTTP requests using
different handlers.
The `router` component directs each request to the matching handler.
Handlers are implemented in the `viewer` and the `editor` package.
While the `editor` serves the editing UI, the `viewer` is responsible for
serving whatever file is requested.
Other noteable packages are as follows.
* The `http/failer` package delivers error pages for HTTP requests.
* The `http/templates` package caches and renders the templates used for HTML
output.
* The `resources` package encapsulates access to static resources, which are
bundled with each `gone` distribution.
See the [Godoc](http://godoc.org/github.com/fxnn/gone) for more information.
## License (MIT)
Licensed under the MIT License, see [LICENSE](LICENSE) file for more information.
| {
"content_hash": "f42606adb0cefcffaaf3fe5c2a4e6459",
"timestamp": "",
"source": "github",
"line_count": 227,
"max_line_length": 150,
"avg_line_length": 39.1057268722467,
"alnum_prop": 0.7183733243212798,
"repo_name": "fxnn/gone",
"id": "c81cb008d99ccaca30b59f14a6f01c017152368b",
"size": "8885",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "306580"
},
{
"name": "HTML",
"bytes": "2056"
},
{
"name": "JavaScript",
"bytes": "2224"
},
{
"name": "Shell",
"bytes": "1239"
}
],
"symlink_target": ""
} |
namespace blink {
class Modulator;
class ModuleScript;
class ModuleScriptLoaderClient;
class ModuleScriptLoaderRegistry;
class ResourceFetcher;
enum class ModuleGraphLevel;
// ModuleScriptLoader is responsible for loading a new single ModuleScript.
//
// ModuleScriptLoader constructs FetchParameters and asks ModuleScriptFetcher
// to fetch a script with the parameters. Then, it returns its client a compiled
// ModuleScript.
//
// ModuleScriptLoader(s) should only be used via Modulator and its ModuleMap.
class CORE_EXPORT ModuleScriptLoader final
: public GarbageCollected<ModuleScriptLoader>,
public ModuleScriptFetcher::Client {
enum class State {
kInitial,
// FetchParameters is being processed, and ModuleScriptLoader hasn't
// notifyFinished().
kFetching,
// Finished successfully or w/ error.
kFinished,
};
public:
ModuleScriptLoader(Modulator*,
const ScriptFetchOptions&,
ModuleScriptLoaderRegistry*,
ModuleScriptLoaderClient*);
ModuleScriptLoader(const ModuleScriptLoader&) = delete;
ModuleScriptLoader& operator=(const ModuleScriptLoader&) = delete;
~ModuleScriptLoader();
static void Fetch(const ModuleScriptFetchRequest&,
ResourceFetcher* fetch_client_settings_object_fetcher,
ModuleGraphLevel,
Modulator* module_map_settings_object,
ModuleScriptCustomFetchType,
ModuleScriptLoaderRegistry*,
ModuleScriptLoaderClient*);
// Implements ModuleScriptFetcher::Client.
void NotifyFetchFinishedSuccess(const ModuleScriptCreationParams&) override;
void NotifyFetchFinishedError(
const HeapVector<Member<ConsoleMessage>>& error_messages) override;
bool IsInitialState() const { return state_ == State::kInitial; }
bool HasFinished() const { return state_ == State::kFinished; }
void Trace(Visitor*) const override;
friend class WorkletModuleResponsesMapTest;
private:
void FetchInternal(const ModuleScriptFetchRequest&,
ResourceFetcher* fetch_client_settings_object_fetcher,
ModuleGraphLevel,
ModuleScriptCustomFetchType);
void AdvanceState(State new_state);
using PassKey = base::PassKey<ModuleScriptLoader>;
// PassKey should be private and cannot be accessed from outside, but allow
// accessing only from friend classes for testing.
static base::PassKey<ModuleScriptLoader> CreatePassKeyForTests() {
return PassKey();
}
#if DCHECK_IS_ON()
static const char* StateToString(State);
#endif
Member<Modulator> modulator_;
State state_ = State::kInitial;
const ScriptFetchOptions options_;
Member<ModuleScript> module_script_;
Member<ModuleScriptLoaderRegistry> registry_;
Member<ModuleScriptLoaderClient> client_;
Member<ModuleScriptFetcher> module_fetcher_;
#if DCHECK_IS_ON()
KURL url_;
#endif
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_LOADER_MODULESCRIPT_MODULE_SCRIPT_LOADER_H_
| {
"content_hash": "625503e71008f89dc5ed6808194c8633",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 86,
"avg_line_length": 33.857142857142854,
"alnum_prop": 0.7195715676728335,
"repo_name": "ric2b/Vivaldi-browser",
"id": "4bb9ac940d8c2af7ad7532de62028b62df93bcc5",
"size": "3968",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chromium/third_party/blink/renderer/core/loader/modulescript/module_script_loader.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.accengage.samples.coffeesample" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver
android:name="com.ad4screen.sdk.GCMHandler"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.accengage.samples.coffeesample" />
</intent-filter>
</receiver>
<activity
android:name=".activities.SampleSplashScreen"
android:icon="@mipmap/ic_launcher"
android:label="@string/title_activity_coffee_maker"
android:theme="@style/AppTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activities.SampleCoffeeMaker"
android:icon="@mipmap/ic_launcher"
android:label="@string/title_activity_coffee_maker"
android:theme="@style/AppTheme" >
</activity>
<activity
android:name=".activities.SampleMakeCoffee"
android:icon="@mipmap/ic_launcher"
android:label="@string/title_activity_make_coffee"
android:theme="@style/AppTheme" >
</activity>
<activity
android:name=".activities.SampleSettings"
android:icon="@mipmap/ic_launcher"
android:label="@string/title_activity_coffee_settings"
android:theme="@style/AppTheme" >
<!--
we are declaring a url schema a4ssample://p1 for this activity
Sending a Push with URL a4ssample://p1 will open this activity
-->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="p1"
android:scheme="a4ssample" />
</intent-filter>
</activity>
</application>
</manifest> | {
"content_hash": "d180d909c948a7937014e357f6f1ec2c",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 85,
"avg_line_length": 39.35820895522388,
"alnum_prop": 0.5851346226772848,
"repo_name": "Accengage/A4S-SDK-Samples-Android",
"id": "4ac84768e5d8c3048d3386a69acb8b1333922dad",
"size": "2637",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "AccSample/app/src/main/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "67284"
}
],
"symlink_target": ""
} |
#include "imap-urlauth-common.h"
#include "array.h"
#include "ioloop.h"
#include "net.h"
#include "fdpass.h"
#include "istream.h"
#include "ostream.h"
#include "str.h"
#include "strescape.h"
#include "eacces-error.h"
#include "llist.h"
#include "hostpid.h"
#include "execv-const.h"
#include "env-util.h"
#include "var-expand.h"
#include "restrict-access.h"
#include "master-service.h"
#include "master-interface.h"
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define IMAP_URLAUTH_PROTOCOL_MAJOR_VERSION 1
#define IMAP_URLAUTH_PROTOCOL_MINOR_VERSION 0
#define IMAP_URLAUTH_WORKER_SOCKET "imap-urlauth-worker"
/* max. length of input lines (URLs) */
#define MAX_INBUF_SIZE 2048
/* Disconnect client after idling this many milliseconds */
#define CLIENT_IDLE_TIMEOUT_MSECS (10*60*1000)
#define USER_EXECUTABLE "imap-urlauth-worker"
#define IS_STANDALONE() \
(getenv(MASTER_IS_PARENT_ENV) == NULL)
struct client *imap_urlauth_clients;
unsigned int imap_urlauth_client_count;
static int client_worker_connect(struct client *client);
static void client_worker_disconnect(struct client *client);
static void client_worker_input(struct client *client);
int client_create(const char *username, int fd_in, int fd_out,
const struct imap_urlauth_settings *set,
struct client **client_r)
{
struct client *client;
const char *app;
/* always use nonblocking I/O */
net_set_nonblock(fd_in, TRUE);
net_set_nonblock(fd_out, TRUE);
client = i_new(struct client, 1);
client->fd_in = fd_in;
client->fd_out = fd_out;
client->fd_ctrl = -1;
client->set = set;
if (client_worker_connect(client) < 0) {
i_free(client);
return -1;
}
/* determine user's special privileges */
i_array_init(&client->access_apps, 4);
if (username != NULL) {
if (set->imap_urlauth_submit_user != NULL &&
strcmp(set->imap_urlauth_submit_user, username) == 0) {
if (set->mail_debug)
i_debug("User %s has URLAUTH submit access", username);
app = "submit+";
array_append(&client->access_apps, &app, 1);
}
if (set->imap_urlauth_stream_user != NULL &&
strcmp(set->imap_urlauth_stream_user, username) == 0) {
if (set->mail_debug)
i_debug("User %s has URLAUTH stream access", username);
app = "stream";
array_append(&client->access_apps, &app, 1);
}
}
if (username != NULL)
client->username = i_strdup(username);
client->output = o_stream_create_fd(fd_out, (size_t)-1, FALSE);
imap_urlauth_client_count++;
DLLIST_PREPEND(&imap_urlauth_clients, client);
imap_urlauth_refresh_proctitle();
*client_r = client;
return 0;
}
void client_send_line(struct client *client, const char *fmt, ...)
{
va_list va;
ssize_t ret;
if (client->output->closed)
return;
va_start(va, fmt);
T_BEGIN {
string_t *str;
str = t_str_new(256);
str_vprintfa(str, fmt, va);
str_append(str, "\n");
ret = o_stream_send(client->output,
str_data(str), str_len(str));
i_assert(ret < 0 || (size_t)ret == str_len(str));
} T_END;
va_end(va);
}
static int client_worker_connect(struct client *client)
{
static const char handshake[] = "VERSION\timap-urlauth-worker\t1\t0\n";
const char *socket_path;
ssize_t ret;
unsigned char data;
socket_path = t_strconcat(client->set->base_dir,
"/"IMAP_URLAUTH_WORKER_SOCKET, NULL);
if (client->set->mail_debug)
i_debug("Connecting to worker socket %s", socket_path);
client->fd_ctrl = net_connect_unix_with_retries(socket_path, 1000);
if (client->fd_ctrl < 0) {
if (errno == EACCES) {
i_error("imap-urlauth-client: %s",
eacces_error_get("net_connect_unix",
socket_path));
} else {
i_error("imap-urlauth-client: net_connect_unix(%s) failed: %m",
socket_path);
}
return -1;
}
/* transfer one or two fds */
data = (client->fd_in == client->fd_out ? '0' : '1');
ret = fd_send(client->fd_ctrl, client->fd_in, &data, sizeof(data));
if (ret > 0 && client->fd_in != client->fd_out) {
data = '0';
ret = fd_send(client->fd_ctrl, client->fd_out,
&data, sizeof(data));
}
if (ret <= 0) {
if (ret < 0) {
i_error("fd_send(%s, %d) failed: %m",
socket_path, client->fd_ctrl);
} else {
i_error("fd_send(%s, %d) failed to send byte",
socket_path, client->fd_ctrl);
}
client_worker_disconnect(client);
return -1;
}
client->ctrl_output =
o_stream_create_fd(client->fd_ctrl, (size_t)-1, FALSE);
/* send protocol version handshake */
if (o_stream_send_str(client->ctrl_output, handshake) < 0) {
i_error("Error sending handshake to imap-urlauth worker: %m");
client_worker_disconnect(client);
return -1;
}
client->ctrl_input =
i_stream_create_fd(client->fd_ctrl, MAX_INBUF_SIZE, FALSE);
client->ctrl_io =
io_add(client->fd_ctrl, IO_READ, client_worker_input, client);
return 0;
}
void client_worker_disconnect(struct client *client)
{
client->worker_state = IMAP_URLAUTH_WORKER_STATE_INACTIVE;
if (client->ctrl_io != NULL)
io_remove(&client->ctrl_io);
if (client->ctrl_output != NULL)
o_stream_destroy(&client->ctrl_output);
if (client->ctrl_input != NULL)
i_stream_destroy(&client->ctrl_input);
if (client->fd_ctrl >= 0) {
net_disconnect(client->fd_ctrl);
client->fd_ctrl = -1;
}
}
static int
client_worker_input_line(struct client *client, const char *response)
{
const char *const *apps;
unsigned int count, i;
bool restart;
string_t *str;
int ret;
switch (client->worker_state) {
case IMAP_URLAUTH_WORKER_STATE_INACTIVE:
if (strcasecmp(response, "OK") != 0) {
client_disconnect(client, "Worker handshake failed");
return -1;
}
client->worker_state = IMAP_URLAUTH_WORKER_STATE_CONNECTED;
str = t_str_new(256);
str_append(str, "ACCESS\t");
if (client->username != NULL)
str_append_tabescaped(str, client->username);
if (client->set->mail_debug)
str_append(str, "\tdebug");
if (array_count(&client->access_apps) > 0) {
str_append(str, "\tapps=");
apps = array_get(&client->access_apps, &count);
str_append(str, apps[0]);
for (i = 1; i < count; i++) {
str_append_c(str, ',');
str_append_tabescaped(str, apps[i]);
}
}
str_append(str, "\n");
ret = o_stream_send(client->ctrl_output,
str_data(str), str_len(str));
i_assert(ret < 0 || (size_t)ret == str_len(str));
if (ret < 0) {
client_disconnect(client,
"Failed to send ACCESS control command to worker");
return -1;
}
break;
case IMAP_URLAUTH_WORKER_STATE_CONNECTED:
if (strcasecmp(response, "OK") != 0) {
client_disconnect(client,
"Failed to negotiate access parameters");
return -1;
}
client->worker_state = IMAP_URLAUTH_WORKER_STATE_ACTIVE;
break;
case IMAP_URLAUTH_WORKER_STATE_ACTIVE:
restart = TRUE;
if (strcasecmp(response, "DISCONNECTED") == 0) {
/* worker detected client disconnect */
restart = FALSE;
} else if (strcasecmp(response, "FINISHED") != 0) {
/* unknown response */
client_disconnect(client,
"Worker finished with unknown response");
return -1;
}
if (client->set->mail_debug)
i_debug("Worker finished successfully");
if (restart) {
/* connect to new worker for accessing different user */
client_worker_disconnect(client);
if (client_worker_connect(client) < 0) {
client_disconnect(client,
"Failed to connect to new worker");
return -1;
}
/* indicate success of "END" command */
client_send_line(client, "OK");
} else {
client_disconnect(client, "Client disconnected");
}
return -1;
default:
i_unreached();
}
return 0;
}
void client_worker_input(struct client *client)
{
struct istream *input = client->ctrl_input;
const char *line;
if (input->closed) {
/* disconnected */
client_disconnect(client, "Worker disconnected unexpectedly");
return;
}
switch (i_stream_read(input)) {
case -1:
/* disconnected */
client_disconnect(client, "Worker disconnected unexpectedly");
return;
case -2:
/* input buffer full */
client_disconnect(client, "Worker sent too large input");
return;
}
while ((line = i_stream_next_line(input)) != NULL) {
if (client_worker_input_line(client, line) < 0)
return;
}
}
void client_destroy(struct client *client, const char *reason)
{
i_set_failure_prefix("%s: ", master_service_get_name(master_service));
if (!client->disconnected) {
if (reason == NULL)
reason = "Connection closed";
i_info("Disconnected: %s", reason);
}
imap_urlauth_client_count--;
DLLIST_REMOVE(&imap_urlauth_clients, client);
if (client->to_idle != NULL)
timeout_remove(&client->to_idle);
client_worker_disconnect(client);
o_stream_destroy(&client->output);
net_disconnect(client->fd_in);
if (client->fd_in != client->fd_out)
net_disconnect(client->fd_out);
if (client->username != NULL)
i_free(client->username);
array_free(&client->access_apps);
i_free(client);
master_service_client_connection_destroyed(master_service);
imap_urlauth_refresh_proctitle();
}
static void client_destroy_timeout(struct client *client)
{
client_destroy(client, NULL);
}
void client_disconnect(struct client *client, const char *reason)
{
if (client->disconnected)
return;
client->disconnected = TRUE;
i_info("Disconnected: %s", reason);
client->to_idle = timeout_add(0, client_destroy_timeout, client);
}
void clients_destroy_all(void)
{
while (imap_urlauth_clients != NULL)
client_destroy(imap_urlauth_clients, "Server shutting down.");
}
| {
"content_hash": "12972b1243a70c2571f584612b446a8a",
"timestamp": "",
"source": "github",
"line_count": 378,
"max_line_length": 72,
"avg_line_length": 24.854497354497354,
"alnum_prop": 0.6642895156998403,
"repo_name": "LTD-Beget/dovecot",
"id": "653ba6757afb7f368fe03e90b5489f3ab9a7f8be",
"size": "9471",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/imap-urlauth/imap-urlauth-client.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "10591133"
},
{
"name": "C++",
"bytes": "89116"
},
{
"name": "Logos",
"bytes": "3470"
},
{
"name": "Objective-C",
"bytes": "1543"
},
{
"name": "Perl",
"bytes": "9273"
},
{
"name": "Python",
"bytes": "1626"
},
{
"name": "Shell",
"bytes": "7240"
}
],
"symlink_target": ""
} |
@implementation Verse (CoreDataProperties)
@dynamic chapter;
@dynamic book;
@dynamic verseNumber;
@dynamic text;
@end
| {
"content_hash": "cf055df7272eccc91a6c1269c7855481",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 42,
"avg_line_length": 15,
"alnum_prop": 0.7833333333333333,
"repo_name": "jonchui/BibleMem",
"id": "74085d08bfda0ce442b05193bacf28c613974e9d",
"size": "402",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "iOS/BibleMem_ObjC/NSManagedObjects/Verse+CoreDataProperties.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "117261"
},
{
"name": "Objective-C",
"bytes": "140310"
},
{
"name": "Ruby",
"bytes": "26"
},
{
"name": "Shell",
"bytes": "7953"
}
],
"symlink_target": ""
} |
#pragma once
#ifndef GEODE_PROXYREMOTEQUERYSERVICE_H_
#define GEODE_PROXYREMOTEQUERYSERVICE_H_
#include <geode/internal/geode_globals.hpp>
#include <memory>
#include "CqService.hpp"
#include "UserAttributes.hpp"
#include <geode/QueryService.hpp>
#include <geode/AuthenticatedView.hpp>
#include "ThinClientCacheDistributionManager.hpp"
#include <ace/Recursive_Thread_Mutex.h>
namespace apache {
namespace geode {
namespace client {
class CacheImpl;
class ThinClientPoolDM;
class APACHE_GEODE_EXPORT ProxyRemoteQueryService : public QueryService {
public:
ProxyRemoteQueryService(AuthenticatedView* cptr);
virtual ~ProxyRemoteQueryService() = default;
std::shared_ptr<Query> newQuery(std::string querystring) override;
virtual std::shared_ptr<CqQuery> newCq(
std::string querystr, const std::shared_ptr<CqAttributes>& cqAttr,
bool isDurable = false) override;
virtual std::shared_ptr<CqQuery> newCq(
std::string name, std::string querystr,
const std::shared_ptr<CqAttributes>& cqAttr,
bool isDurable = false) override;
virtual void closeCqs() override;
virtual QueryService::query_container_type getCqs() const override;
virtual std::shared_ptr<CqQuery> getCq(
const std::string& name) const override;
virtual void executeCqs() override;
virtual void stopCqs() override;
virtual std::shared_ptr<CqServiceStatistics> getCqServiceStatistics()
const override;
virtual std::shared_ptr<CacheableArrayList> getAllDurableCqsFromServer()
const override;
private:
[[noreturn]] static void unSupportedException(
const std::string& operationName);
void addCqQuery(const std::shared_ptr<CqQuery>& cqQuery);
void closeCqs(bool keepAlive);
std::shared_ptr<QueryService> m_realQueryService;
AuthenticatedView* m_authenticatedView;
query_container_type m_cqQueries;
// lock for cqQuery list;
mutable ACE_Recursive_Thread_Mutex m_cqQueryListLock;
friend class AuthenticatedView;
};
} // namespace client
} // namespace geode
} // namespace apache
#endif // GEODE_PROXYREMOTEQUERYSERVICE_H_
| {
"content_hash": "37026e04b675767fd5a79f1d08199f8c",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 74,
"avg_line_length": 27.56578947368421,
"alnum_prop": 0.7556085918854415,
"repo_name": "mmartell/geode-native",
"id": "9372f083c119aaf11f047551d28ce9262d0c8386",
"size": "2897",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "cppcache/src/ProxyRemoteQueryService.hpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "953"
},
{
"name": "C#",
"bytes": "3332023"
},
{
"name": "C++",
"bytes": "10048743"
},
{
"name": "CMake",
"bytes": "294924"
},
{
"name": "Dockerfile",
"bytes": "1787"
},
{
"name": "GAP",
"bytes": "73860"
},
{
"name": "Java",
"bytes": "408146"
},
{
"name": "Perl",
"bytes": "2704"
},
{
"name": "PowerShell",
"bytes": "20976"
},
{
"name": "Shell",
"bytes": "25767"
}
],
"symlink_target": ""
} |
/**
*
*/
package org.flowninja.persistence.mongodb.repositories;
import org.flowninja.persistence.mongodb.data.MongoAdminRecord;
import org.flowninja.types.generic.AdminKey;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.CrudRepository;
/**
* @author rainer
*
*/
public interface IMongoAdminRepository extends CrudRepository<MongoAdminRecord, AdminKey>, QueryDslPredicateExecutor<MongoAdminRecord> {
}
| {
"content_hash": "19d38661573a072f8ba0f69ba8569f08",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 136,
"avg_line_length": 27.941176470588236,
"alnum_prop": 0.8210526315789474,
"repo_name": "rbieniek/flow-ninja",
"id": "9504f4ddd053f643b93b9cf1fc7b5e2cb421f5fb",
"size": "475",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ninja-persistence-mongodb/src/main/java/org/flowninja/persistence/mongodb/repositories/IMongoAdminRepository.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2288"
},
{
"name": "HTML",
"bytes": "21350"
},
{
"name": "Java",
"bytes": "880123"
},
{
"name": "JavaScript",
"bytes": "8796"
}
],
"symlink_target": ""
} |
<?php
namespace Guzzle\Parser\Message;
abstract class AbstractMessageParser implements MessageParserInterface
{
protected function getUrlPartsFromMessage($requestUrl, array $parts)
{
$urlParts = array(
'path' => $requestUrl,
'scheme' => 'http'
);
if (isset($parts['headers']['Host'])) {
$urlParts['host'] = $parts['headers']['Host'];
} elseif (isset($parts['headers']['host'])) {
$urlParts['host'] = $parts['headers']['host'];
} else {
$urlParts['host'] = null;
}
if (false === strpos($urlParts['host'], ':')) {
$urlParts['port'] = '';
} else {
$hostParts = explode(':', $urlParts['host']);
$urlParts['host'] = trim($hostParts[0]);
$urlParts['port'] = (int) trim($hostParts[1]);
if ($urlParts['port'] == 443) {
$urlParts['scheme'] = 'https';
}
}
$path = $urlParts['path'];
$qpos = strpos($path, '?');
if ($qpos) {
$urlParts['query'] = substr($path, $qpos + 1);
$urlParts['path'] = substr($path, 0, $qpos);
} else {
$urlParts['query'] = '';
}
return $urlParts;
}
}
| {
"content_hash": "41f83d20657ffdd14783a9c356426b5a",
"timestamp": "",
"source": "github",
"line_count": 58,
"max_line_length": 70,
"avg_line_length": 16.96551724137931,
"alnum_prop": 0.6107723577235772,
"repo_name": "TropicalRobot/finding-beyond",
"id": "c88189601f15a2229dc4f6cfb5128efe20b1ae2e",
"size": "984",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/app/plugins/easyazon-pro-4.0.17/components/localization/lib/geoip/vendor/guzzle/guzzle/src/Guzzle/Parser/Message/AbstractMessageParser.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "373662"
},
{
"name": "JavaScript",
"bytes": "645951"
},
{
"name": "PHP",
"bytes": "2540687"
},
{
"name": "Ruby",
"bytes": "2383"
},
{
"name": "Shell",
"bytes": "602"
}
],
"symlink_target": ""
} |
\hypertarget{classMyOption_1_1DigitalPutOption}{}\section{My\+Option\+:\+:Digital\+Put\+Option Class Reference}
\label{classMyOption_1_1DigitalPutOption}\index{My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}}
{\ttfamily \#include $<$options.\+h$>$}
Inheritance diagram for My\+Option\+:\+:Digital\+Put\+Option\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=216pt]{classMyOption_1_1DigitalPutOption__inherit__graph}
\end{center}
\end{figure}
Collaboration diagram for My\+Option\+:\+:Digital\+Put\+Option\+:
\nopagebreak
\begin{figure}[H]
\begin{center}
\leavevmode
\includegraphics[width=216pt]{classMyOption_1_1DigitalPutOption__coll__graph}
\end{center}
\end{figure}
\subsection*{Public Member Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{classMyOption_1_1DigitalPutOption_a06d1c6c093b1bf2a1fcc24e46be8f06f}{Digital\+Put\+Option} (double \hyperlink{classMyOption_1_1Option_a6c6f01d75cde7e92d16a6d8d6f331a1d}{Spot}, double \hyperlink{classMyOption_1_1Option_a3033c483588ce26b175280c7f9dee8d1}{Strike}, double \hyperlink{classMyOption_1_1Option_aa8cb250427dece65ea49255d4102cc8d}{r}, double \hyperlink{classMyOption_1_1Option_a500979f4b32262594d895c4a83b58d1d}{d}, double \hyperlink{classMyOption_1_1Option_a5d6002c14b335c782873bf1437113513}{Vol}, double \hyperlink{classMyOption_1_1Option_ac1adacb417fede41d151b9cda05bcb3d}{Expiry})
\item
virtual \hyperlink{classMyOption_1_1DigitalPutOption_af373736d79c052e94761072593e37648}{$\sim$\+Digital\+Put\+Option} ()
\item
virtual double \hyperlink{classMyOption_1_1DigitalPutOption_a4f51d8bdbdddfbebf428cea500c5edf0}{Get\+Value} (double \hyperlink{classMyOption_1_1Option_a6c6f01d75cde7e92d16a6d8d6f331a1d}{Spot})
\item
virtual double \hyperlink{classMyOption_1_1DigitalPutOption_a3d26c1e53753a199a35f0769672e94cf}{Get\+Value} (double \hyperlink{classMyOption_1_1Option_a6c6f01d75cde7e92d16a6d8d6f331a1d}{Spot}, double \hyperlink{classMyOption_1_1Option_a5d6002c14b335c782873bf1437113513}{Vol}, double \hyperlink{classMyOption_1_1Option_ac1adacb417fede41d151b9cda05bcb3d}{Expiry})
\item
virtual double \hyperlink{classMyOption_1_1DigitalPutOption_ab55e215fef7a85bb06175a05548a3f77}{Get\+Value} (double \hyperlink{classMyOption_1_1Option_a6c6f01d75cde7e92d16a6d8d6f331a1d}{Spot}, double \hyperlink{classMyOption_1_1Option_aa8cb250427dece65ea49255d4102cc8d}{r}, double \hyperlink{classMyOption_1_1Option_a5d6002c14b335c782873bf1437113513}{Vol}, double \hyperlink{classMyOption_1_1Option_ac1adacb417fede41d151b9cda05bcb3d}{Expiry})
\item
virtual double \hyperlink{classMyOption_1_1DigitalPutOption_a20e33b1b8a221ea2200fd08f3c691c4a}{Get\+Delta} (double \hyperlink{classMyOption_1_1Option_a6c6f01d75cde7e92d16a6d8d6f331a1d}{Spot}, double \hyperlink{classMyOption_1_1Option_a5d6002c14b335c782873bf1437113513}{Vol}, double \hyperlink{classMyOption_1_1Option_ac1adacb417fede41d151b9cda05bcb3d}{Expiry})
\item
virtual double \hyperlink{classMyOption_1_1DigitalPutOption_a4eeb4d0c53f0075ee80e67270f4bd6a5}{Get\+Gamma} (double \hyperlink{classMyOption_1_1Option_a6c6f01d75cde7e92d16a6d8d6f331a1d}{Spot}, double \hyperlink{classMyOption_1_1Option_a5d6002c14b335c782873bf1437113513}{Vol}, double \hyperlink{classMyOption_1_1Option_ac1adacb417fede41d151b9cda05bcb3d}{Expiry})
\item
virtual long \hyperlink{classMyOption_1_1DigitalPutOption_a6e38fdd2a8d6f6f959e5cdb0a66e4057}{Is\+Touched} (double \hyperlink{classMyOption_1_1Option_a6c6f01d75cde7e92d16a6d8d6f331a1d}{Spot}) const
\item
virtual double \hyperlink{classMyOption_1_1DigitalPutOption_abadcbb78c02b4e6ee22d45da1c72f7b1}{Get\+Pay\+Off} (double \hyperlink{classMyOption_1_1Option_a6c6f01d75cde7e92d16a6d8d6f331a1d}{Spot}) const
\end{DoxyCompactItemize}
\subsection*{Additional Inherited Members}
\subsection{Constructor \& Destructor Documentation}
\hypertarget{classMyOption_1_1DigitalPutOption_a06d1c6c093b1bf2a1fcc24e46be8f06f}{}\label{classMyOption_1_1DigitalPutOption_a06d1c6c093b1bf2a1fcc24e46be8f06f}
\index{My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}!Digital\+Put\+Option@{Digital\+Put\+Option}}
\index{Digital\+Put\+Option@{Digital\+Put\+Option}!My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}}
\subsubsection{\texorpdfstring{Digital\+Put\+Option()}{DigitalPutOption()}}
{\footnotesize\ttfamily My\+Option\+::\+Digital\+Put\+Option\+::\+Digital\+Put\+Option (\begin{DoxyParamCaption}\item[{double}]{Spot, }\item[{double}]{Strike, }\item[{double}]{r, }\item[{double}]{d, }\item[{double}]{Vol, }\item[{double}]{Expiry }\end{DoxyParamCaption})}
\hypertarget{classMyOption_1_1DigitalPutOption_af373736d79c052e94761072593e37648}{}\label{classMyOption_1_1DigitalPutOption_af373736d79c052e94761072593e37648}
\index{My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}!````~Digital\+Put\+Option@{$\sim$\+Digital\+Put\+Option}}
\index{````~Digital\+Put\+Option@{$\sim$\+Digital\+Put\+Option}!My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}}
\subsubsection{\texorpdfstring{$\sim$\+Digital\+Put\+Option()}{~DigitalPutOption()}}
{\footnotesize\ttfamily virtual My\+Option\+::\+Digital\+Put\+Option\+::$\sim$\+Digital\+Put\+Option (\begin{DoxyParamCaption}{ }\end{DoxyParamCaption})\hspace{0.3cm}{\ttfamily [inline]}, {\ttfamily [virtual]}}
\subsection{Member Function Documentation}
\hypertarget{classMyOption_1_1DigitalPutOption_a20e33b1b8a221ea2200fd08f3c691c4a}{}\label{classMyOption_1_1DigitalPutOption_a20e33b1b8a221ea2200fd08f3c691c4a}
\index{My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}!Get\+Delta@{Get\+Delta}}
\index{Get\+Delta@{Get\+Delta}!My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}}
\subsubsection{\texorpdfstring{Get\+Delta()}{GetDelta()}}
{\footnotesize\ttfamily virtual double My\+Option\+::\+Digital\+Put\+Option\+::\+Get\+Delta (\begin{DoxyParamCaption}\item[{double}]{Spot, }\item[{double}]{Vol, }\item[{double}]{Expiry }\end{DoxyParamCaption})\hspace{0.3cm}{\ttfamily [virtual]}}
Implements \hyperlink{classMyOption_1_1Option_a4947bde99bb5e46b79aa0f36fd353d9b}{My\+Option\+::\+Option}.
\hypertarget{classMyOption_1_1DigitalPutOption_a4eeb4d0c53f0075ee80e67270f4bd6a5}{}\label{classMyOption_1_1DigitalPutOption_a4eeb4d0c53f0075ee80e67270f4bd6a5}
\index{My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}!Get\+Gamma@{Get\+Gamma}}
\index{Get\+Gamma@{Get\+Gamma}!My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}}
\subsubsection{\texorpdfstring{Get\+Gamma()}{GetGamma()}}
{\footnotesize\ttfamily virtual double My\+Option\+::\+Digital\+Put\+Option\+::\+Get\+Gamma (\begin{DoxyParamCaption}\item[{double}]{Spot, }\item[{double}]{Vol, }\item[{double}]{Expiry }\end{DoxyParamCaption})\hspace{0.3cm}{\ttfamily [virtual]}}
Implements \hyperlink{classMyOption_1_1Option_a4416faa432b5004e449394056c7f1363}{My\+Option\+::\+Option}.
\hypertarget{classMyOption_1_1DigitalPutOption_abadcbb78c02b4e6ee22d45da1c72f7b1}{}\label{classMyOption_1_1DigitalPutOption_abadcbb78c02b4e6ee22d45da1c72f7b1}
\index{My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}!Get\+Pay\+Off@{Get\+Pay\+Off}}
\index{Get\+Pay\+Off@{Get\+Pay\+Off}!My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}}
\subsubsection{\texorpdfstring{Get\+Pay\+Off()}{GetPayOff()}}
{\footnotesize\ttfamily virtual double My\+Option\+::\+Digital\+Put\+Option\+::\+Get\+Pay\+Off (\begin{DoxyParamCaption}\item[{double}]{Spot }\end{DoxyParamCaption}) const\hspace{0.3cm}{\ttfamily [virtual]}}
Implements \hyperlink{classMyOption_1_1Option_a4b6b84dc485153ffadfb32afa9bb52f3}{My\+Option\+::\+Option}.
\hypertarget{classMyOption_1_1DigitalPutOption_a4f51d8bdbdddfbebf428cea500c5edf0}{}\label{classMyOption_1_1DigitalPutOption_a4f51d8bdbdddfbebf428cea500c5edf0}
\index{My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}!Get\+Value@{Get\+Value}}
\index{Get\+Value@{Get\+Value}!My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}}
\subsubsection{\texorpdfstring{Get\+Value()}{GetValue()}\hspace{0.1cm}{\footnotesize\ttfamily [1/3]}}
{\footnotesize\ttfamily virtual double My\+Option\+::\+Digital\+Put\+Option\+::\+Get\+Value (\begin{DoxyParamCaption}\item[{double}]{Spot }\end{DoxyParamCaption})\hspace{0.3cm}{\ttfamily [virtual]}}
Implements \hyperlink{classMyOption_1_1Option_aff32b402a5e44fca9e5a22a142fbbdd6}{My\+Option\+::\+Option}.
\hypertarget{classMyOption_1_1DigitalPutOption_a3d26c1e53753a199a35f0769672e94cf}{}\label{classMyOption_1_1DigitalPutOption_a3d26c1e53753a199a35f0769672e94cf}
\index{My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}!Get\+Value@{Get\+Value}}
\index{Get\+Value@{Get\+Value}!My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}}
\subsubsection{\texorpdfstring{Get\+Value()}{GetValue()}\hspace{0.1cm}{\footnotesize\ttfamily [2/3]}}
{\footnotesize\ttfamily virtual double My\+Option\+::\+Digital\+Put\+Option\+::\+Get\+Value (\begin{DoxyParamCaption}\item[{double}]{Spot, }\item[{double}]{Vol, }\item[{double}]{Expiry }\end{DoxyParamCaption})\hspace{0.3cm}{\ttfamily [virtual]}}
Implements \hyperlink{classMyOption_1_1Option_a78fa248dcb939e0ebaefbb944d5d9cf8}{My\+Option\+::\+Option}.
\hypertarget{classMyOption_1_1DigitalPutOption_ab55e215fef7a85bb06175a05548a3f77}{}\label{classMyOption_1_1DigitalPutOption_ab55e215fef7a85bb06175a05548a3f77}
\index{My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}!Get\+Value@{Get\+Value}}
\index{Get\+Value@{Get\+Value}!My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}}
\subsubsection{\texorpdfstring{Get\+Value()}{GetValue()}\hspace{0.1cm}{\footnotesize\ttfamily [3/3]}}
{\footnotesize\ttfamily virtual double My\+Option\+::\+Digital\+Put\+Option\+::\+Get\+Value (\begin{DoxyParamCaption}\item[{double}]{Spot, }\item[{double}]{r, }\item[{double}]{Vol, }\item[{double}]{Expiry }\end{DoxyParamCaption})\hspace{0.3cm}{\ttfamily [virtual]}}
Implements \hyperlink{classMyOption_1_1Option_a62422d3dc60eabe65cfa94d2a452f5f8}{My\+Option\+::\+Option}.
\hypertarget{classMyOption_1_1DigitalPutOption_a6e38fdd2a8d6f6f959e5cdb0a66e4057}{}\label{classMyOption_1_1DigitalPutOption_a6e38fdd2a8d6f6f959e5cdb0a66e4057}
\index{My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}!Is\+Touched@{Is\+Touched}}
\index{Is\+Touched@{Is\+Touched}!My\+Option\+::\+Digital\+Put\+Option@{My\+Option\+::\+Digital\+Put\+Option}}
\subsubsection{\texorpdfstring{Is\+Touched()}{IsTouched()}}
{\footnotesize\ttfamily virtual long My\+Option\+::\+Digital\+Put\+Option\+::\+Is\+Touched (\begin{DoxyParamCaption}\item[{double}]{Spot }\end{DoxyParamCaption}) const\hspace{0.3cm}{\ttfamily [virtual]}}
Implements \hyperlink{classMyOption_1_1Option_ade57d2fcb9f22f3c2a57d75f55444c33}{My\+Option\+::\+Option}.
The documentation for this class was generated from the following file\+:\begin{DoxyCompactItemize}
\item
\hyperlink{options_8h}{options.\+h}\end{DoxyCompactItemize}
| {
"content_hash": "de6b71146a3d35c6f5967886b93c90e6",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 603,
"avg_line_length": 79.00709219858156,
"alnum_prop": 0.7712746858168761,
"repo_name": "calvin456/intro_derivative_pricing",
"id": "41e3682160f576a02f99df121d436aee38fe8235",
"size": "11140",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/include/latex/classMyOption_1_1DigitalPutOption.tex",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "695"
},
{
"name": "C",
"bytes": "36155"
},
{
"name": "C++",
"bytes": "1441313"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "39d796237c963034ce60ac6396d9fd4e",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "416b76aa207480e19c2ae04637d76d1b33f33824",
"size": "176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Polygalaceae/Polygala/Polygala schinziana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "ff3eb3e0d941bdfb68fd75552ad73eda",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "512b02a3c2085e07c40bba6aaed07b91c5ffd5a0",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Rutaceae/Agathosma/Agathosma blaerioides/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
@interface GRGraffitiGestureRecognizer : UIGestureRecognizer
-(id)initWithLanguage:( GRGraffitiAlphabets )language_id_
recognitionMethod:( GRRecognitionMethods )method_id_
target:( id )target_
action:( SEL )action_;
//@@ ItemType : NSString
@property ( nonatomic, retain, readonly ) NSArray* detectedLetters;
@property ( nonatomic, assign ) GRGraffitiAlphabets languageId;
@property ( nonatomic, assign ) GRRecognitionMethods methodId;
@property ( nonatomic, assign ) BOOL shouldDumpPointsToFile;
@end
| {
"content_hash": "ccb0434e0271eaa467ebaff04807a414",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 67,
"avg_line_length": 31.88235294117647,
"alnum_prop": 0.7380073800738007,
"repo_name": "dodikk/iPalmGraffiti",
"id": "56f833a4cf3c2a8f95ea63c816af073b44dfa972",
"size": "708",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/GraffitiRecognizers/GraffitiRecognizers/GRGraffitiGestureRecognizer.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "2109"
},
{
"name": "Objective-C",
"bytes": "40934"
},
{
"name": "Python",
"bytes": "1336"
}
],
"symlink_target": ""
} |
namespace remoting {
CapturerHelper::CapturerHelper() : size_most_recent_(0, 0) {
}
CapturerHelper::~CapturerHelper() {
}
void CapturerHelper::ClearInvalidRects() {
base::AutoLock auto_inval_rects_lock(inval_rects_lock_);
inval_rects_.clear();
}
void CapturerHelper::InvalidateRects(const InvalidRects& inval_rects) {
base::AutoLock auto_inval_rects_lock(inval_rects_lock_);
InvalidRects temp_rects;
std::set_union(inval_rects_.begin(), inval_rects_.end(),
inval_rects.begin(), inval_rects.end(),
std::inserter(temp_rects, temp_rects.begin()));
inval_rects_.swap(temp_rects);
}
void CapturerHelper::InvalidateScreen(const gfx::Size& size) {
base::AutoLock auto_inval_rects_lock(inval_rects_lock_);
inval_rects_.clear();
inval_rects_.insert(gfx::Rect(0, 0, size.width(), size.height()));
}
void CapturerHelper::InvalidateFullScreen() {
if (size_most_recent_ != gfx::Size(0, 0))
InvalidateScreen(size_most_recent_);
}
bool CapturerHelper::IsCaptureFullScreen(const gfx::Size& size) {
base::AutoLock auto_inval_rects_lock(inval_rects_lock_);
return inval_rects_.size() == 1u &&
inval_rects_.begin()->x() == 0 && inval_rects_.begin()->y() == 0 &&
inval_rects_.begin()->width() == size.width() &&
inval_rects_.begin()->height() == size.height();
}
void CapturerHelper::SwapInvalidRects(InvalidRects& inval_rects) {
base::AutoLock auto_inval_rects_lock(inval_rects_lock_);
inval_rects.swap(inval_rects_);
}
const gfx::Size& CapturerHelper::size_most_recent() const {
return size_most_recent_;
}
void CapturerHelper::set_size_most_recent(const gfx::Size& size) {
size_most_recent_ = size;
}
} // namespace remoting
| {
"content_hash": "d367afd071d3c63b5cf0227065edc631",
"timestamp": "",
"source": "github",
"line_count": 55,
"max_line_length": 73,
"avg_line_length": 31.054545454545455,
"alnum_prop": 0.6826697892271663,
"repo_name": "Crystalnix/house-of-life-chromium",
"id": "eba7c1260821c6ff0e0b5d7ba38f0c0492780a5c",
"size": "1964",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "remoting/host/capturer_helper.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "3418"
},
{
"name": "C",
"bytes": "88445923"
},
{
"name": "C#",
"bytes": "73756"
},
{
"name": "C++",
"bytes": "77228136"
},
{
"name": "Emacs Lisp",
"bytes": "6648"
},
{
"name": "F#",
"bytes": "381"
},
{
"name": "Go",
"bytes": "3744"
},
{
"name": "Java",
"bytes": "11354"
},
{
"name": "JavaScript",
"bytes": "6191433"
},
{
"name": "Objective-C",
"bytes": "4023654"
},
{
"name": "PHP",
"bytes": "97796"
},
{
"name": "Perl",
"bytes": "92217"
},
{
"name": "Python",
"bytes": "5604932"
},
{
"name": "Ruby",
"bytes": "937"
},
{
"name": "Shell",
"bytes": "1234672"
},
{
"name": "Tcl",
"bytes": "200213"
}
],
"symlink_target": ""
} |
/**
* Hyperion
* utilities.hpp
*
* @author: Evangelos Mavropoulos <[email protected]>
* @date: 14/8/2016
*/
#ifndef UTILITIES_HPP_
#define UTILITIES_HPP_
#include <image.hpp>
namespace utilities {
void fromImageToMat(Mat &, Image &);
}
#endif /* UTILITIES_HPP_ */
| {
"content_hash": "36dfbf7691a3a76dd4b35ea5d2543972",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 54,
"avg_line_length": 14.578947368421053,
"alnum_prop": 0.6678700361010831,
"repo_name": "evmavrop/Hyperion",
"id": "d85be4afeb23110c07a64531e94c472a8fa583e3",
"size": "277",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Hyperion/inc/utilities.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "19562"
}
],
"symlink_target": ""
} |
"""
Code to deal with binding site test cases.
"""
from _biopsy import *
from binding_hit import *
import random
def calc_sensitivity( tp, fn ):
return tp + fn and float(tp)/(float(tp)+float(fn)) or 0
def calc_specificity( tn, fp ):
return tn + fp and float(tn)/(float(tn)+float(fp)) or 0
def evaluate_discriminator_at_threshold(
discriminators,
truths,
threshold
):
"""Evaluates a discriminator at a given threshold and returns
(sensitivity, specificity)"""
tp = fp = fn = tn = 0
for d, should_be_positive in zip(discriminators, truths):
is_positive = d >= threshold
if should_be_positive and is_positive: tp += 1
elif should_be_positive and not is_positive: fn += 1
elif not should_be_positive and is_positive: fp += 1
elif not should_be_positive and not is_positive: tn += 1
sensitivity = calc_sensitivity(tp,fn)
specificity = calc_specificity(tn,fp)
return ( sensitivity, specificity )
def add_negatives_to_test_case( tc, pssm_names ):
"""Generates random negative test cases"""
# hash the positives to generate seed for random
rand = random.Random( "".join( tc.positives ).__hash__() )
tc.negatives = SequenceVec()
while len(tc.negatives) != len(tc.positives):
p = rand.choice(pssm_names)
if p not in tc.positives:
tc.negatives.append(p)
TestCase.add_negatives_from = add_negatives_to_test_case
#
# Our tests are passed around as tuples:
# test[0] is the test case
# test[1] is whether this is a positive test
#
class Test:
def __init__( self, tc, truth ):
self.tc = tc
self._truth = truth
def truth( self ):
return self._truth
def pssms( self ):
return self.truth() and self.tc.positives or self.tc.negatives
def sequences( self ):
return self.tc.sequences
def test_case_truth( test ):
"""Should a pssm be a positive or a negative test case input?"""
return test.truth()
class PhyloClassifier:
"""Classifies tests. Returns a prob [0,1] for whether the pssm is predicted
to be in the test case"""
def __init__( self, threshold, phylo_threshold ):
self._threshold = threshold
self._phylo_threshold = phylo_threshold
self._p_bindings = { }
def __call__( self, test ):
hits = score_pssms_on_phylo_sequences(
test.pssms(),
test.sequences(),
self._threshold,
self._phylo_threshold )[ 0 ]
p_bindings = get_max_p_binding_over_hits( hits )
return (
0 != len(p_bindings)
and max(p_bindings.values())
or 0.0
)
class NonPhyloClassifier:
"""Classifies tests. Returns a prob [0,1] for whether the pssm is predicted
to be in the test case"""
def __init__( self, threshold ):
self._threshold = threshold
self._p_bindings = { }
def __call__( self, test ):
hits = score_pssms_on_sequence(
test.pssms(),
test.sequences()[0],
self._threshold )
p_bindings = get_max_p_binding_over_hits( hits )
result = (
0 != len(p_bindings)
and max(p_bindings.values())
or 0.0
)
# print test.truth(), result, test.pssms()
return result
class TransfacClassifier:
"""Classifies tests. Returns a prob [0,1] for whether any pssm is predicted
to be in the test case"""
def __init__( self, threshold_fn = get_transfac_pssm_min_fp_threshold ):
self._threshold_fn = threshold_fn
def __call__( self, test ):
for pssm in test.pssms():
p = get_pssm(pssm).pssm
l = len(p)
try:
threshold = self._threshold_fn( pssm )
except:
print '********** Cannot get threshold for:', pssm, '**********'
continue
for i in range( len( test.sequences()[0] ) - l + 1 ):
s = test.sequences()[0][i:i+l]
if threshold <= score_pssm( p, s ):
return 1.0
s_rc = reverse_complement( s )
if threshold <= score_pssm( p, s_rc ):
return 1.0
# print s, test_case.sequences[0][-l:]
return 0.0
def generate_test_inputs( test_cases, max_num_sequences = 6 ):
"""A generator for test inputs"""
# for each test case
for tc in test_cases:
print '# seqs: %d, # pssms: %d, seq lengths: %s' % (
len( tc.sequences ),
len( tc.positives ),
','.join( str( len( s ) ) for s in tc.sequences )
)
if len( tc.sequences ) > max_num_sequences:
print 'Too many sequences, skipping...'
continue
yield Test( tc, True )
yield Test( tc, False )
def evaluate_test_case_classifier(
test_cases,
classifier,
truth,
num_thresholds = 100
):
"""Analyses the test cases"""
discriminators = [ classifier( i ) for i in generate_test_inputs( test_cases ) ]
truths = [ truth( i ) for i in generate_test_inputs( test_cases ) ]
print '# tests:', len(truths)
# for i in range(len(truths)):
# print truths[i], discriminators[i]
# for each threshold
roc_points = { }
for t in [ float(i) / ( num_thresholds - 1 ) for i in range(num_thresholds) ]:
# Sensitivity and specificity
(sensitivity, specificity) = \
evaluate_discriminator_at_threshold(
discriminators,
truths,
t )
# print sensitivity, specificity
roc_points[ t ] = (
sensitivity,
1.0 - specificity
)
return roc_points
def plot_roc_points(
roc_points,
**keywords
):
from pylab import plot
x = []
y = []
thresholds = roc_points.keys()
thresholds.sort()
for t in thresholds:
# print t, point
y.append( roc_points[t][0] )
x.append( roc_points[t][1] )
# print x
# print y
x.sort()
y.sort()
plot( x, y, **keywords )
| {
"content_hash": "ab0d4a3ed6a01c7f6a8cd31e58b3ebcc",
"timestamp": "",
"source": "github",
"line_count": 200,
"max_line_length": 84,
"avg_line_length": 31.275,
"alnum_prop": 0.5528377298161471,
"repo_name": "JohnReid/biopsy",
"id": "6235f400862eeee08a32e4fe260b1681d9047b8e",
"size": "6292",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Python/biopsy/test_case.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "2639"
},
{
"name": "C",
"bytes": "392541"
},
{
"name": "C++",
"bytes": "3946426"
},
{
"name": "Gnuplot",
"bytes": "42000"
},
{
"name": "Python",
"bytes": "976684"
},
{
"name": "R",
"bytes": "2714"
},
{
"name": "Shell",
"bytes": "3356"
},
{
"name": "TeX",
"bytes": "4212"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.cosmos.implementation;
import com.azure.cosmos.implementation.apachecommons.lang.StringUtils;
/**
* While this class is public, but it is not part of our published public APIs.
* This is meant to be internally used only by our sdk.
*/
public class Strings {
public static final String Emtpy = "";
public static boolean isNullOrWhiteSpace(String str) {
return StringUtils.isEmpty(str) || StringUtils.isWhitespace(str);
}
public static boolean isNullOrEmpty(String str) {
return StringUtils.isEmpty(str);
}
public static String toString(boolean value) {
return Boolean.toString(value);
}
public static String toString(int value) {
return Integer.toString(value);
}
public static boolean areEqual(String str1, String str2) {
return StringUtils.equals(str1, str2);
}
public static boolean areEqualIgnoreCase(String str1, String str2) {
return StringUtils.equalsIgnoreCase(str1, str2);
}
public static boolean containsIgnoreCase(String str1, String str2) {
return StringUtils.containsIgnoreCase(str1, str2);
}
public static String fromCamelCaseToUpperCase(String str) {
if (str == null) {
return null;
}
StringBuilder result = new StringBuilder(str);
int i = 1;
while (i < result.length()) {
if (Character.isUpperCase(result.charAt(i))) {
result.insert(i, '_');
i += 2;
} else {
result.replace(i, i + 1, Character.toString(Character.toUpperCase(result.charAt(i))));
i ++;
}
}
return result.toString();
}
}
| {
"content_hash": "c61851e73239325af1fe6b488ccabaf6",
"timestamp": "",
"source": "github",
"line_count": 61,
"max_line_length": 102,
"avg_line_length": 29.868852459016395,
"alnum_prop": 0.6344676180021954,
"repo_name": "selvasingh/azure-sdk-for-java",
"id": "8050bf096d56080dee661a0a7c983be6aee1011a",
"size": "1822",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sdk/cosmos/azure-cosmos/src/main/java/com/azure/cosmos/implementation/Strings.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "29891970"
},
{
"name": "JavaScript",
"bytes": "6198"
},
{
"name": "PowerShell",
"bytes": "160"
},
{
"name": "Shell",
"bytes": "609"
}
],
"symlink_target": ""
} |
from string import Template
from datetime import date
bitcoinDir = "./";
inFile = bitcoinDir+"/share/qt/Info.plist"
outFile = "Sealandcoin-Qt.app/Contents/Info.plist"
version = "unknown";
fileForGrabbingVersion = bitcoinDir+"bitcoin-qt.pro"
for line in open(fileForGrabbingVersion):
lineArr = line.replace(" ", "").split("=");
if lineArr[0].startswith("VERSION"):
version = lineArr[1].replace("\n", "");
fIn = open(inFile, "r")
fileContent = fIn.read()
s = Template(fileContent)
newFileContent = s.substitute(VERSION=version,YEAR=date.today().year)
fOut = open(outFile, "w");
fOut.write(newFileContent);
print "Info.plist fresh created"
| {
"content_hash": "543a5d7e02e7bdbebeedfa5357ab21bb",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 69,
"avg_line_length": 27.375,
"alnum_prop": 0.710806697108067,
"repo_name": "FromTheSea/Freedom",
"id": "b9dcc00bbea8aa167b1d12a73e2c09bcbb97adba",
"size": "903",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "share/qt/clean_mac_info_plist.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "32790"
},
{
"name": "C++",
"bytes": "2615877"
},
{
"name": "CSS",
"bytes": "1127"
},
{
"name": "Groff",
"bytes": "18284"
},
{
"name": "HTML",
"bytes": "50615"
},
{
"name": "Makefile",
"bytes": "13405"
},
{
"name": "NSIS",
"bytes": "6022"
},
{
"name": "Objective-C",
"bytes": "1052"
},
{
"name": "Objective-C++",
"bytes": "5864"
},
{
"name": "Python",
"bytes": "69729"
},
{
"name": "QMake",
"bytes": "14751"
},
{
"name": "Shell",
"bytes": "13173"
}
],
"symlink_target": ""
} |
import unittest
from cupy import testing
import cupyx.scipy.special # NOQA
import numpy
import warnings
@testing.gpu
@testing.with_requires('scipy')
class TestPolygamma(unittest.TestCase):
@testing.with_requires('scipy>=1.1.0')
@testing.for_all_dtypes(no_complex=True)
@testing.numpy_cupy_allclose(atol=1e-5, scipy_name='scp')
def test_arange(self, xp, scp, dtype):
import scipy.special # NOQA
a = testing.shaped_arange((2, 3), xp, dtype)
b = testing.shaped_arange((2, 3), xp, dtype)
return scp.special.polygamma(a, b)
@testing.with_requires('scipy>=1.1.0')
@testing.for_all_dtypes(no_complex=True)
@testing.numpy_cupy_allclose(atol=1e-3, rtol=1e-3, scipy_name='scp')
def test_linspace(self, xp, scp, dtype):
import scipy.special # NOQA
a = numpy.tile(numpy.arange(5), 200).astype(dtype)
b = numpy.linspace(-30, 30, 1000, dtype=dtype)
a = xp.asarray(a)
b = xp.asarray(b)
return scp.special.polygamma(a, b)
@testing.for_all_dtypes(no_complex=True)
@testing.numpy_cupy_allclose(atol=1e-2, rtol=1e-3, scipy_name='scp')
def test_scalar(self, xp, scp, dtype):
import scipy.special # NOQA
# polygamma in scipy returns numpy.float64 value when inputs scalar.
# whatever type input is.
return scp.special.polygamma(
dtype(2.), dtype(1.5)).astype(numpy.float32)
@testing.with_requires('scipy>=1.1.0')
@testing.for_all_dtypes(no_complex=True)
@testing.numpy_cupy_allclose(atol=1e-2, rtol=1e-3, scipy_name='scp')
def test_inf_and_nan(self, xp, scp, dtype):
import scipy.special # NOQA
x = numpy.array([-numpy.inf, numpy.nan, numpy.inf]).astype(dtype)
a = numpy.tile(x, 3)
b = numpy.repeat(x, 3)
a = xp.asarray(a)
b = xp.asarray(b)
with warnings.catch_warnings():
warnings.simplefilter('ignore')
return scp.special.polygamma(a, b)
| {
"content_hash": "08100f4cae4f41625d5c68422e666420",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 76,
"avg_line_length": 33.898305084745765,
"alnum_prop": 0.6315,
"repo_name": "cupy/cupy",
"id": "1b34c19b819cb47e3ae8256f684ef4ca48419a8d",
"size": "2000",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/cupyx_tests/scipy_tests/special_tests/test_polygamma.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "38"
},
{
"name": "C",
"bytes": "712019"
},
{
"name": "C++",
"bytes": "895316"
},
{
"name": "Cuda",
"bytes": "151799"
},
{
"name": "Cython",
"bytes": "1996454"
},
{
"name": "Dockerfile",
"bytes": "40251"
},
{
"name": "PowerShell",
"bytes": "7361"
},
{
"name": "Python",
"bytes": "4841354"
},
{
"name": "Shell",
"bytes": "24521"
}
],
"symlink_target": ""
} |
// Author: Prasanna V. Loganathar
// Created: 9:26 AM 20-01-2015
// Project: RedScooby
// License: http://www.apache.org/licenses/LICENSE-2.0
using System;
using System.Threading;
using System.Threading.Tasks;
namespace RedScooby.Infrastructure.Framework
{
public class SynchronizationContextDispatcher : IDispatcher
{
private static SynchronizationContext _uiContext;
public void Run<T>(Action<T> action, T state)
{
if (CheckAccess())
{
action(state);
}
else
{
Dispatch(action, state);
}
}
public void Initialize()
{
_uiContext = SynchronizationContext.Current;
if (_uiContext == null)
{
throw new Exception("Synchronization context unavailable.");
}
Scheduler = TaskScheduler.FromCurrentSynchronizationContext();
}
public void Dispatch(Action action)
{
_uiContext.Post(o => action(), null);
}
public void Dispatch<T>(Action<T> action, T state)
{
_uiContext.Post(s => action((T) s), state);
}
public bool CheckAccess()
{
return SynchronizationContext.Current == _uiContext;
}
public void Run(Action action)
{
if (CheckAccess())
{
action();
}
else
{
Dispatch(action);
}
}
public TaskScheduler Scheduler { get; private set; }
}
}
| {
"content_hash": "eb0f7c2325d6c9e47190e4da76317ef1",
"timestamp": "",
"source": "github",
"line_count": 69,
"max_line_length": 76,
"avg_line_length": 23.666666666666668,
"alnum_prop": 0.515003061849357,
"repo_name": "prasannavl/RedScooby",
"id": "6d4095e3ee5cc91c520d13f30e473a6eb7695568",
"size": "1635",
"binary": false,
"copies": "1",
"ref": "refs/heads/oss",
"path": "src/RedScooby.Core/Infrastructure/Framework/SynchronizationContextDispatcher.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLogTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('log', function (Blueprint $table) {
$table->increments('id');
$table->string('server_id');
$table->string('action');
$table->string('acting_user');
$table->text('extra_data');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('log');
}
}
| {
"content_hash": "9b1255aa4d0f1d6580a2fcb158a01e49",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 59,
"avg_line_length": 20.97142857142857,
"alnum_prop": 0.5367847411444142,
"repo_name": "mrkirby153/KirBotPanel",
"id": "764dd312bde1449d4cdebb14e38ccc21f3cac9d0",
"size": "734",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "database/migrations/2017_08_05_231021_create_log_table.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Blade",
"bytes": "11280"
},
{
"name": "JavaScript",
"bytes": "5050"
},
{
"name": "PHP",
"bytes": "209070"
},
{
"name": "Shell",
"bytes": "852"
},
{
"name": "TypeScript",
"bytes": "193263"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
namespace Flashcards21.Data
{
public interface IStorage
{
List<String> GetAllCardBoxIDs();
void StoreCardBox(string filename, string title, string description, int nofCards);
DAL.CardBoxDTO LoadCardBox(String filename);
void UpdateCardBox(string _filename, int position, DateTime _lastAccessed, int[] cards);
void DeleteCardBox(string filename);
DAL.CardDTO LoadCard(String filename, int position);
void StoreCard(string boxfilename, int position, string question, string answer, string image);
BitmapImage LoadImage(string boxname, string imagename);
}
}
| {
"content_hash": "b76aebc8453b4e8a00512f3a456fce55",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 103,
"avg_line_length": 34.45454545454545,
"alnum_prop": 0.7269129287598944,
"repo_name": "nitesis/furry-sniffle",
"id": "9d10d7214246c529bf7aba90ac3d34eefcc06e56",
"size": "760",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Flashcards21/Data/IStorage.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "49865"
}
],
"symlink_target": ""
} |
package opsworks
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/internal/protocol/jsonrpc"
"github.com/aws/aws-sdk-go/internal/signer/v4"
)
// Welcome to the AWS OpsWorks API Reference. This guide provides descriptions,
// syntax, and usage examples about AWS OpsWorks actions and data types, including
// common parameters and error codes.
//
// AWS OpsWorks is an application management service that provides an integrated
// experience for overseeing the complete application lifecycle. For information
// about this product, go to the AWS OpsWorks (http://aws.amazon.com/opsworks/)
// details page.
//
// SDKs and CLI
//
// The most common way to use the AWS OpsWorks API is by using the AWS Command
// Line Interface (CLI) or by using one of the AWS SDKs to implement applications
// in your preferred language. For more information, see:
//
// AWS CLI (http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)
// AWS SDK for Java (http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/opsworks/AWSOpsWorksClient.html)
// AWS SDK for .NET (http://docs.aws.amazon.com/sdkfornet/latest/apidocs/html/N_Amazon_OpsWorks.htm)
// AWS SDK for PHP 2 (http://docs.aws.amazon.com/aws-sdk-php-2/latest/class-Aws.OpsWorks.OpsWorksClient.html)
// AWS SDK for Ruby (http://docs.aws.amazon.com/AWSRubySDK/latest/AWS/OpsWorks/Client.html)
// AWS SDK for Node.js (http://aws.amazon.com/documentation/sdkforjavascript/)
// AWS SDK for Python(Boto) (http://docs.pythonboto.org/en/latest/ref/opsworks.html)
// Endpoints
//
// AWS OpsWorks supports only one endpoint, opsworks.us-east-1.amazonaws.com
// (HTTPS), so you must connect to that endpoint. You can then use the API to
// direct AWS OpsWorks to create stacks in any AWS Region.
//
// Chef Versions
//
// When you call CreateStack, CloneStack, or UpdateStack we recommend you use
// the ConfigurationManager parameter to specify the Chef version. The recommended
// value for Linux stacks, which is also the default value, is currently 11.10.
// Windows stacks use Chef 12.2. For more information, see Chef Versions (http://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-chef11.html).
//
// You can also specify Chef 11.4 or Chef 0.9 for your Linux stack. However,
// Chef 0.9 has been deprecated. We do not recommend using Chef 0.9 for new
// stacks, and we recommend migrating your existing Chef 0.9 stacks to Chef
// 11.10 as soon as possible.
type OpsWorks struct {
*aws.Service
}
// Used for custom service initialization logic
var initService func(*aws.Service)
// Used for custom request initialization logic
var initRequest func(*aws.Request)
// New returns a new OpsWorks client.
func New(config *aws.Config) *OpsWorks {
service := &aws.Service{
Config: aws.DefaultConfig.Merge(config),
ServiceName: "opsworks",
APIVersion: "2013-02-18",
JSONVersion: "1.1",
TargetPrefix: "OpsWorks_20130218",
}
service.Initialize()
// Handlers
service.Handlers.Sign.PushBack(v4.Sign)
service.Handlers.Build.PushBack(jsonrpc.Build)
service.Handlers.Unmarshal.PushBack(jsonrpc.Unmarshal)
service.Handlers.UnmarshalMeta.PushBack(jsonrpc.UnmarshalMeta)
service.Handlers.UnmarshalError.PushBack(jsonrpc.UnmarshalError)
// Run custom service initialization if present
if initService != nil {
initService(service)
}
return &OpsWorks{service}
}
// newRequest creates a new request for a OpsWorks operation and runs any
// custom request initialization.
func (c *OpsWorks) newRequest(op *aws.Operation, params, data interface{}) *aws.Request {
req := aws.NewRequest(c.Service, op, params, data)
// Run custom request initialization if present
if initRequest != nil {
initRequest(req)
}
return req
}
| {
"content_hash": "05892a8475dc930d222434a687a893a6",
"timestamp": "",
"source": "github",
"line_count": 95,
"max_line_length": 156,
"avg_line_length": 39.71578947368421,
"alnum_prop": 0.7524516300026504,
"repo_name": "digantsh/aws-sdk-go",
"id": "0d4366aa7f54fa34b3fcb6b83836b7f7961a513c",
"size": "3828",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "service/opsworks/service.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Cucumber",
"bytes": "22856"
},
{
"name": "Go",
"bytes": "9357055"
},
{
"name": "HTML",
"bytes": "3690"
},
{
"name": "Makefile",
"bytes": "1742"
},
{
"name": "Ruby",
"bytes": "7365"
}
],
"symlink_target": ""
} |
'use strict';
require('configureForRelayOSS');
const RelayClassic_DEPRECATED = require('RelayClassic_DEPRECATED');
const RelayQuery = require('../RelayQuery');
const RelayQueryTransform = require('../RelayQueryTransform');
const RelayTestUtils = require('RelayTestUtils');
describe('RelayQueryTransform', () => {
const {getNode} = RelayTestUtils;
let query;
beforeEach(() => {
const variables = {
first: 10,
after: 'offset',
};
const fragment = RelayClassic_DEPRECATED.QL`
fragment on User {
friends(first:$first,after:$after) {
edges {
node {
id
name
address {
city
}
}
}
}
}
`;
query = getNode(
RelayClassic_DEPRECATED.QL`
query {
node(id:"4") {
id
${fragment}
friends(first:$first,after:$after) {
edges {
node {
id
lastName
address {
city
}
}
}
}
}
}
`,
null,
variables,
);
});
it('returns original input', () => {
class NoOp extends RelayQueryTransform<any> {}
const transform = new NoOp();
const output = transform.visit(query, null);
expect(output).toBe(query);
});
it('returns null if field visitors all return null for scalars', () => {
class Nullify extends RelayQueryTransform<any> {
visitField(field: RelayQuery.Field, state: any): ?RelayQuery.Node {
if (!field.canHaveSubselections()) {
return null;
}
return this.traverse(field, state);
}
}
const transform = new Nullify();
const output = transform.visit(query, null);
expect(output).toBe(null);
});
it('returns cloned versions of fields', () => {
class RemoveIDs extends RelayQueryTransform<Array> {
visitField(field: RelayQuery.Field, state: Array): ?RelayQuery.Node {
// print `id` but filter from output
state.push(field.getSchemaName());
if (field.getSchemaName() === 'id') {
return null;
}
return this.traverse(field, state);
}
}
const transform = new RemoveIDs();
let fields = [];
const output = transform.visit(query, fields);
var expectedFields = [];
function traverse(node: RelayQuery.Node): void {
if (node instanceof RelayQuery.Field) {
expectedFields.push(node.getSchemaName());
}
node.getChildren().forEach(c => traverse(c));
}
traverse(output);
// output should be missing the id fields
expect(expectedFields.length).not.toBe(fields.length);
fields = fields.filter(name => name !== 'id');
expect(fields.length).toBe(expectedFields.length);
expect(fields.every((f, ii) => f === expectedFields[ii])).toBe(true);
});
});
| {
"content_hash": "32fa5dbbccfe851f39c10378fa2c0b0f",
"timestamp": "",
"source": "github",
"line_count": 116,
"max_line_length": 75,
"avg_line_length": 25.525862068965516,
"alnum_prop": 0.5555555555555556,
"repo_name": "apalm/relay",
"id": "82807d06a79587100ce639806eae157860160f80",
"size": "3181",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/react-relay/classic/query/__tests__/RelayQueryTransform-test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "297"
},
{
"name": "HTML",
"bytes": "111245"
},
{
"name": "JavaScript",
"bytes": "1218468"
},
{
"name": "Shell",
"bytes": "2878"
}
],
"symlink_target": ""
} |
namespace OldestFamilyMember
{
using System.Collections.Generic;
using System.Linq;
public class Family
{
private List<Person> members;
public Family()
{
this.members = new List<Person>();
}
public void AddMember(Person member)
{
this.members.Add(member);
}
public Person GetOldestMember()
{
return this.members
.OrderByDescending(p => p.Age)
.FirstOrDefault();
}
}
} | {
"content_hash": "24ad8a4becbbd8f172c4c6e74dcbeb09",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 47,
"avg_line_length": 21.6,
"alnum_prop": 0.5166666666666667,
"repo_name": "NikolaySpasov/Softuni",
"id": "ed9191fafb7cf6a18e2b27f3fc9e22207cca47e9",
"size": "542",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "C# OOP Basics/03. Exercise - Defining Classes/03. Oldest Family Member/Family.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1159007"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "248d09f3f183108c8532558c9b3129dc",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "0c11600c762f91f6fca028ae96b57fe546f47f5f",
"size": "185",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Rosales/Urticaceae/Pipturus/Pipturus verticillatus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
setTimeout(function() {
return 1;
}, 0);
| {
"content_hash": "571a7e7eaca1d8e4cb686bdd650ad82a",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 23,
"avg_line_length": 14.333333333333334,
"alnum_prop": 0.6046511627906976,
"repo_name": "danielstjules/buddy.js",
"id": "ccf040ba30d0827fead71db3245ea29ccb32d10a",
"size": "43",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/fixtures/ignore.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "40049"
}
],
"symlink_target": ""
} |
CC=gcc
CFLAGS=-Wall
.PHONY: clean distclean
default: chat
nothing:
chat: chat.h chat.c client.c server.c io.h io.c
$(CC) $(CFLAGS) -o chat chat.c client.c server.c io.c
clean:
$(RM) *~
distclean: clean
$(RM) chat
| {
"content_hash": "00a181aa3a416719bfd0fbbd7a7a719b",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 54,
"avg_line_length": 13.8125,
"alnum_prop": 0.669683257918552,
"repo_name": "kpjim-axl/oslab-ntua",
"id": "05fef29144860f5c5e5b6af2aac9eea673064ed4",
"size": "221",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "2/src/chat/crypt/Makefile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "195982"
},
{
"name": "Makefile",
"bytes": "3504"
},
{
"name": "Shell",
"bytes": "1022"
}
],
"symlink_target": ""
} |
package net.diamonddominion.esaych.survival;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.diamonddominion.esaych.CustomPlugin;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPistonRetractEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
public class DemiGodPackage implements Listener {
private CustomPlugin plugin;
private BlockLog bl = new BlockLog(plugin);
private ArrayList<Material> disallowedBlocks = new ArrayList<Material>();
private ArrayList<Material> unclickableBlocks = new ArrayList<Material>();
private ArrayList<Material> unbreakableBlocks = new ArrayList<Material>();
private ArrayList<String> disallowedCommands = new ArrayList<String>();
// private Map<TNTPrimed, String> godTNT = new HashMap<TNTPrimed, String>();
// private Map<Block, String> explodedBlocks = new HashMap<Block, String>();
// private Map<Block, String> explodedBlockData = new HashMap<Block, String>();
public DemiGodPackage(CustomPlugin plugin) {
this.plugin = plugin;
}
public void enable() {
plugin.getServer().getPluginManager().registerEvents(this, plugin);
populateDisallowedBlocks(); // Blocks you can't take out of inv
populateUnclickableBlocks();// Blocks you can't open/right click
populateUnbreakableBocks(); // Blocks you can't break
populateDisallowedCommands();//Commands you can't type
// startTntWatch();
log("Enabled");
}
public void disable() {
bl.saveLog();
// if (explodedBlocks.size() > 0) {
// Set<Block> set = explodedBlocks.keySet();
// for (Block b : set) { //Loop through all logged exploded blocks
// b.setTypeId(Integer.parseInt(explodedBlockData.get(b).split(";")[0]));
// b.setData(Byte.parseByte(explodedBlockData.get(b).split(";")[1]));
// if (b.getType().equals(Material.WALL_SIGN) || b.getType().equals(Material.SIGN_POST)) {
// Sign sign = (Sign) b.getState();
// sign.setLine(0, explodedBlockData.get(b).split(";")[2]);
// sign.setLine(1, explodedBlockData.get(b).split(";")[3]);
// sign.setLine(2, explodedBlockData.get(b).split(";")[4]);
// sign.setLine(3, explodedBlockData.get(b).split(";")[5]);
// }
// }
// explodedBlockData.clear();
// explodedBlocks.clear();
// }
}
public boolean creativeCommand(CommandSender sender, String[] args) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("save"))
return onReloadCommand(sender, args);
}
if (!(sender instanceof Player)) {
msg(sender, "You may NOT get creative mode. :P");
return true;
}
Player p = (Player) sender;
if (p.getWorld().getName().equals("Build") || p.getWorld().getName().equals("Destruction")) {
if (p.getGameMode().equals(GameMode.CREATIVE)) {
msg(p, "You are already in creative mode");
return true;
}
p.setGameMode(GameMode.CREATIVE);
return true;
}
if (!p.hasPermission("customplugin.creative")) {
msg(p, "You must purchase the DemiGod class for this command.");
return true;
}
if (p.getGameMode() == GameMode.CREATIVE) {
msg(p, "You are already in Creative Mode! Try /survival");
return true;
}
int a = 0;
for (ItemStack i : p.getInventory()) {
if (i != null)
a++;
}
boolean helm = (p.getInventory().getHelmet() != null);
boolean ches = (p.getInventory().getChestplate() != null);
boolean legg = (p.getInventory().getLeggings() != null);
boolean boot = (p.getInventory().getBoots() != null);
if (a > 0 || helm || ches || legg || boot) {
msg(p, "You must clear your inventory completely to switch to creative mode.");
return true;
}
p.setGameMode(GameMode.CREATIVE);
return true;
}
public boolean survivalCommand(CommandSender sender, String[] args) {
if (!(sender instanceof Player)) {
msg(sender, "Trying to troll?? NOT WORKING.");
return true;
}
Player p = (Player) sender;
if (p.getWorld().getName().equals("Build") || p.getWorld().getName().equals("Destruction")) {
if (p.getGameMode().equals(GameMode.SURVIVAL)) {
msg(p, "You are already in survival mode");
return true;
}
p.setGameMode(GameMode.SURVIVAL);
return true;
}
if (!p.hasPermission("customplugin.creative")) {
msg(p, "You must purchase the DemiGod class for this command.");
return true;
}
if (p.getGameMode() == GameMode.SURVIVAL) {
msg(p, "You are already in Survival Mode! Try /creative");
return true;
}
clearInv(p);
return true;
}
@SuppressWarnings("deprecation")
public void clearInv(Player p) {
p.getInventory().clear();
p.getInventory().setHelmet(new ItemStack(0));
p.getInventory().setChestplate(new ItemStack(0));
p.getInventory().setLeggings(new ItemStack(0));
p.getInventory().setBoots(new ItemStack(0));
p.setGameMode(GameMode.SURVIVAL);
}
public boolean onReloadCommand(CommandSender sender, String[] args) {
if (sender instanceof Player) {
if (sender.isOp()) {
bl.saveLog();
msg(sender, "Creative BlockLog saved.");
} else {
msg(sender, "You do not have permission.");
}
} else {
msg(sender, "Creative BlockLog saved.");
}
return true;
}
private boolean res(Player player) {
// return player.getGameMode() == GameMode.CREATIVE && !player.isOp();
return player.getGameMode() == GameMode.CREATIVE && (player.hasPermission("customplugin.creative.restrict") || (plugin.voteRewards.rewardCache.containsKey(player.getName()) && plugin.voteRewards.rewardCache.get(player.getName()).containsKey(3)));
// return player.getGameMode() == GameMode.CREATIVE && player.hasPermission("customplugin.creative") && !player.isOp();
}
//================================================================================================================
private void populateDisallowedBlocks() {
disallowedBlocks.add(Material.BEDROCK);
disallowedBlocks.add(Material.MONSTER_EGG);
disallowedBlocks.add(Material.MONSTER_EGGS);
disallowedBlocks.add(Material.ENCHANTED_BOOK);
disallowedBlocks.add(Material.COMMAND);
disallowedBlocks.add(Material.ENDER_PORTAL_FRAME);
disallowedBlocks.add(Material.EYE_OF_ENDER);
disallowedBlocks.add(Material.POTION);
disallowedBlocks.add(Material.ITEM_FRAME);
disallowedBlocks.add(Material.MINECART);
disallowedBlocks.add(Material.SADDLE);
disallowedBlocks.add(Material.BOAT);
disallowedBlocks.add(Material.STORAGE_MINECART);
disallowedBlocks.add(Material.POWERED_MINECART);
disallowedBlocks.add(Material.FISHING_ROD);
disallowedBlocks.add(Material.EXPLOSIVE_MINECART);
disallowedBlocks.add(Material.HOPPER_MINECART);
disallowedBlocks.add(Material.EXP_BOTTLE);
disallowedBlocks.add(Material.LAVA_BUCKET);
disallowedBlocks.add(Material.EGG);
disallowedBlocks.add(Material.TNT);
}
private void populateUnclickableBlocks() {
unclickableBlocks.add(Material.CHEST);
unclickableBlocks.add(Material.HOPPER);
unclickableBlocks.add(Material.DISPENSER);
unclickableBlocks.add(Material.DROPPER);
unclickableBlocks.add(Material.FURNACE);
unclickableBlocks.add(Material.BREWING_STAND);
unclickableBlocks.add(Material.TRAPPED_CHEST);
unclickableBlocks.add(Material.ENDER_CHEST);
unclickableBlocks.add(Material.TNT);
}
private void populateUnbreakableBocks() {
unbreakableBlocks.add(Material.BEDROCK);
}
private void populateDisallowedCommands() {
disallowedCommands.add("/enderchest");
disallowedCommands.add("/echest");
disallowedCommands.add("/vc");
disallowedCommands.add("/vchest");
disallowedCommands.add("/virtualchest");
disallowedCommands.add("/kit");
disallowedCommands.add("/ekit");
}
//===============================================================================================================
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event) {
if (res(event.getPlayer())) {
msg(event.getPlayer(), "You may not drop items in creative mode!");
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
if (res(event.getPlayer())) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerDeathEvent(EntityDeathEvent event) {
if (event.getEntity() instanceof Player) {
Player player = (Player) event.getEntity();
if (res(player)) {
event.getDrops().clear();
}
}
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
if (res(event.getPlayer())) {
bl.write(event.getBlock(), event.getPlayer());
}
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled())
return;
WorldGuardPlugin wg = plugin.getWorldGuard();
boolean canBuild;
if (wg == null) {
canBuild = true;
} else {
canBuild = wg.canBuild(event.getPlayer(), event.getBlock());
}
if (bl.isLogged(event.getBlock()) && canBuild) {
if (!res(event.getPlayer())) {
msg(event.getPlayer(), "A creative mode player placed this block.");
}
event.setCancelled(true);
event.getBlock().setType(Material.AIR);
bl.remove(event.getBlock());
}
}
@EventHandler
public void onBlockPistonEvent(BlockPistonExtendEvent event) {
for (Block b : event.getBlocks()) {
if (bl.isLogged(b)) {
event.setCancelled(true);
// animateBlock(b);
}
}
}
@EventHandler
public void onBlockPistonContract(BlockPistonRetractEvent event) {
if (event.getBlock().getType().equals(Material.PISTON_STICKY_BASE)) {
if (!event.getBlock().getType().equals(Material.AIR))
if (bl.isLogged(event.getBlock())) {
event.setCancelled(true);
}
}
}
// private void animateBlock(final Block b) {
// final Material type = b.getType();
// plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
// @Override
// public void run() {
// b.setType(Material.REDSTONE_BLOCK);
// }
// }, 5);
// plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
// @Override
// public void run() {
// b.setType(type);
// }
// }, 10);
// }
// @EventHandler
// public void onBlocksFall(BlockPhysicsEvent event) {
//// if ((event.getBlock().getType().equals(Material.SAND) || event.getBlock().getType().equals(Material.GRAVEL)) && bl.isLogged(event.getBlock())) {
//// event.getBlock().setType(Material.AIR);
//// event.setCancelled(true);
// bl.remove(event.getBlock());
//// }
// }
@SuppressWarnings("deprecation")
@EventHandler
public void onPlayerClick(InventoryClickEvent event) {
if (res((Player) event.getWhoClicked())) {
// log("Cursor: " + event.getCursor().getType().name());
// log("CurrentItem: " + event.getCurrentItem().getType().name());
if (event.getCurrentItem() != null) {
if (disallowedBlocks.contains(event.getCurrentItem().getType())) {
event.setCurrentItem(new ItemStack(Material.AIR));
event.setCancelled(true);
}
}
if (event.getCursor() != null) {
if (disallowedBlocks.contains(event.getCursor().getType())) {
event.setCancelled(true);
}
}
}
if (event.getWhoClicked().getGameMode().equals(GameMode.CREATIVE)) {
if (event.getCurrentItem() != null) {
if (event.getCurrentItem().getType().equals(Material.MONSTER_EGG)) {
event.setCurrentItem(new ItemStack(Material.AIR));
event.setCancelled(true);
}
}
if (event.getCursor() != null) {
if (event.getCursor().getType().equals(Material.MONSTER_EGG)) {
event.setCursor(new ItemStack(Material.AIR));
event.setCancelled(true);
}
}
}
}
@EventHandler (priority = EventPriority.LOWEST)
public void onPlayerInteract(PlayerInteractEvent event) {
if (res(event.getPlayer())) {
Block cB = event.getClickedBlock();
if (cB != null) {
if (event.getAction() == Action.RIGHT_CLICK_BLOCK) {
if (unclickableBlocks.contains(cB.getType())) {
event.setCancelled(true);
msg(event.getPlayer(), "You may not use this block.");
}
if (cB.getType().equals(Material.WALL_SIGN) || cB.getType().equals(Material.SIGN_POST)) {
final Sign sign = (Sign) cB.getState();
if (sign.getLine(0).equals(ChatColor.DARK_BLUE + "[Buy]")) {
sign.setLine(0, "");
sign.update();
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
sign.setLine(0, ChatColor.DARK_BLUE + "[Buy]");
sign.update();
}
}, 1);
}
if (sign.getLine(0).equals(ChatColor.DARK_BLUE + "[Sell]")) {
sign.setLine(0, "");
sign.update();
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
sign.setLine(0, ChatColor.DARK_BLUE + "[Sell]");
sign.update();
}
}, 1);
}
}
} else if (event.getAction() == Action.LEFT_CLICK_BLOCK) {
if (unbreakableBlocks.contains(cB.getType())) {
event.setCancelled(true);
msg(event.getPlayer(), "You may not break this block.");
}
}
}
}
if (event.isCancelled())
return;
// if (!event.getClickedBlock().getType().equals(Material.TNT))
// return;
// if (bl.isLogged(event.getClickedBlock())) {
// final Block tnt = event.getClickedBlock();
// final Player player = event.getPlayer();
// if (tnt.getWorld().getName().equals("Survival") || tnt.getWorld().getName().equals("PeaceWorld"))
// plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
// @Override
// public void run() {
// if (tnt.getType() != Material.AIR)
// return;
// if (player.getItemInHand() != null && player.getItemInHand().getType().equals(Material.FLINT_AND_STEEL)) {
// log("LIT!");
// bl.remove(tnt);
// for (Entity possibleTNT : tnt.getWorld().getEntities()) {
// if (possibleTNT instanceof TNTPrimed) {
// TNTPrimed tntEnt = (TNTPrimed) possibleTNT;
// log(tntEnt.getSource().toString());
// if (tntEnt.getSource().equals(player)) {
// godTNT.put(tntEnt, player.getName());
// log(player.getName() + " just lit tnt at " + tntEnt.getLocation().toString());
// }
// }
// }
// }
// }
// }, 1);
// }
}
@EventHandler
public void onPlayerSendCommand(PlayerCommandPreprocessEvent event) {
if (res(event.getPlayer())) {
String command = event.getMessage().split(" ")[0];
if (disallowedCommands.contains(command)) {
event.setCancelled(true);
msg(event.getPlayer(), "You may not type that command.");
}
}
}
@EventHandler (priority=EventPriority.LOWEST)
public void onPlayerChangeWorld(PlayerChangedWorldEvent event) {
if (res(event.getPlayer())) {
clearInv(event.getPlayer());
}
}
@EventHandler (priority=EventPriority.LOWEST)
public void onPlayerQuitGame(PlayerQuitEvent event) {
if (res(event.getPlayer())) {
clearInv(event.getPlayer());
}
}
@EventHandler
public void onPlayerPunch(EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof Player && res((Player) event.getDamager())) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerTouchEntity(PlayerInteractEntityEvent event) {
if (res(event.getPlayer())) {
event.setCancelled(true);
}
}
// @EventHandler
// public void onTNTPrimeEvent (ExplosionPrimeEvent event) {
// log("PRIMED");
// }
// @EventHandler
// public void onRedstoneEvent (BlockRedstoneEvent event) {
// final Block tnt = event.getBlock();
// if (tnt.getType().equals(Material.TNT)) {
// if (bl.isLogged(tnt)) {
// log("TNT CURRENT: " + event.getNewCurrent());
// plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
// @Override
// public void run() {
// if (tnt.getTypeId() != 0)
// return;
// log("LIT!");
// bl.remove(tnt);
// for (Entity possibleTNT : tnt.getWorld().getEntities()) {
// if (possibleTNT instanceof TNTPrimed) {
// TNTPrimed tntEnt = (TNTPrimed) possibleTNT;
// log(tntEnt.getSource().toString());
// godTNT.put(tntEnt, "REDSTONE");
// log("REDSTONE just lit tnt at " + tntEnt.getLocation().toString());
// }
// }
// }
// }, 1);
// }
// }
// }
// @SuppressWarnings("deprecation")
// @EventHandler
// public void onExplodeEvent(EntityExplodeEvent event) {
// log("EXPLODE");
//
// if (event.isCancelled())
// return;
// for (Block block : event.blockList()) {
// if (bl.isLogged(block)) {
// block.setType(Material.AIR);
// bl.remove(block);
// }
// if (block.getType().equals(Material.TNT)) {
// block.setType(Material.AIR);
// }
// }
// if (event.getEntity() instanceof TNTPrimed) {
// if (godTNT.keySet().contains(event.getEntity())) {
// // for (Block b : event.blockList()) {
// // if (b.getType().equals(Material.WALL_SIGN) || b.getType().equals(Material.SIGN_POST)) {
// // explodedBlocks.put(b, godTNT.get(event.getEntity()));
// // Sign sign = (Sign) b.getState();
// // String signData = ";" + sign.getLine(0) + ";" + sign.getLine(1) + ";" + sign.getLine(2) + ";" + sign.getLine(3);
// // explodedBlockData.put(b, b.getTypeId() + ";" + b.getData() + signData);
// // b.setTypeId(0);
// // }
// // }
// for (Block b : event.blockList()) {
// // if (!(b.getType().equals(Material.WALL_SIGN) || b.getType().equals(Material.SIGN_POST))) {
// explodedBlocks.put(b, godTNT.get(event.getEntity()));
// explodedBlockData.put(b, b.getTypeId() + ";" + b.getData());
// b.setType(Material.AIR);
// // }
// }
// godTNT.remove(event.getEntity());
// }
// }
// }
// private void startTntWatch() {
// plugin.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() {
// @SuppressWarnings("deprecation")
// @Override
// public void run() {
// if (explodedBlocks.size() > 0) {
// ArrayList<String> alreadyGened = new ArrayList<String>(); //This allows for several people to regen at the same time
// ArrayList<Block> toRemove = new ArrayList<Block>();
// Set<Block> set = explodedBlocks.keySet();
// for (Block b : set) { //Loop through all logged exploded blocks
// String playerName = explodedBlocks.get(b);
// if (!alreadyGened.contains(playerName)) { //If the player hasn't already been covered
// b = getLowestBlockPerPlayer(playerName);
//// int typeID = Integer.parseInt(explodedBlockData.get(b).split(";")[0]);
//// if (typeID == 63 || typeID == 68) {
//// if (typeID == 68) {
//// for (Block wallBlock : getPlayerBlocksExploded(playerName)) {
//// if (wallBlock.getLocation().distance(b.getLocation()) == 1) {
//// b = wallBlock;
//// typeID = Integer.parseInt(explodedBlockData.get(b).split(";")[0]);
//// if (typeID == 68) {
//// continue;
//// }
//// }
//// }
//// }
//// if (typeID == 68 || typeID == 68) {
//// Sign sign = (Sign) b.getState();
//// sign.setLine(0, explodedBlockData.get(b).split(";")[2]);
//// sign.setLine(1, explodedBlockData.get(b).split(";")[3]);
//// sign.setLine(2, explodedBlockData.get(b).split(";")[4]);
//// sign.setLine(3, explodedBlockData.get(b).split(";")[5]);
//// sign.update();
//// }
//// }
// b.setTypeId(Integer.parseInt(explodedBlockData.get(b).split(";")[0]));
// b.setData(Byte.parseByte(explodedBlockData.get(b).split(";")[1]));
// alreadyGened.add(playerName);
// explodedBlockData.remove(b);
// toRemove.add(b);
// }
// }
// for (Block b : toRemove) {
// explodedBlocks.remove(b);
// }
// }
// }
// }, 20 * 10, 1);
// }
// private ArrayList<Block> getPlayerBlocksExploded(String p) {
// ArrayList<Block> data = new ArrayList<Block>();
// for (Block b : explodedBlocks.keySet()) {
// if (explodedBlocks.get(b).equals(p)) {
// data.add(b);
// }
// }
// return data;
// }
// private Block getLowestBlockPerPlayer (String p) {
// int lowest = 300;
// Block block = null;
// for (Block b : getPlayerBlocksExploded(p)) {
// if (b.getLocation().getBlockY() < lowest) {
// lowest = b.getLocation().getBlockY();
// block = b;
// }
// }
// return block;
// }
private void msg(CommandSender sender, String msg) {
if (sender instanceof Player) {
((Player) sender).sendMessage(ChatColor.DARK_RED + "["
+ ChatColor.GOLD + "CREATIVE" + ChatColor.DARK_RED + "] "
+ ChatColor.WHITE + ChatColor.translateAlternateColorCodes('&', msg));
} else {
log(msg);
}
}
private void log(String info) {
plugin.getLogger().info("<CreativeMode> " + info);
}
}
class BlockLog {
private File blockLogFile;
private FileConfiguration blockLog;
private Plugin plugin;
public BlockLog(Plugin plugin)
{
this.plugin = plugin;
blockLogFile = new File("CreativeBlockLog.yml");
blockLog = YamlConfiguration.loadConfiguration(blockLogFile);
}
public List<String> getList() {
@SuppressWarnings("unchecked")
List<String> blocks = (List<String>) blockLog.getList("blocks");
if (blocks == null) {
blocks = new ArrayList<String>();
}
return blocks;
}
public void write(Block block, Player player) {
List<String> blocks = getList();
blocks.add(getData(block, player));
blockLog.set("blocks", blocks);
}
public void remove(Block block) {
List<String> blocks = getList();
List<String> newBlocks = new ArrayList<String>();
for (String log : blocks) {
if (!log.contains(getTitle(block)))
newBlocks.add(log);
}
blockLog.set("blocks", newBlocks);
}
public boolean isLogged(Block block) {
for (String s : getList()) {
if (s.contains(getTitle(block))) {
return true;
}
}
return false;
}
public void saveLog() {
if (blockLog == null || blockLogFile == null) {
plugin.getLogger().severe("Could not save config to " + blockLogFile);
return;
}
try {
blockLog.save(blockLogFile);
} catch (IOException ex) {
plugin.getLogger().severe("Could not save config to " + blockLogFile);
}
}
private String getTitle(Block b) {
return b.getWorld().getName() + ";" + b.getX() + ";" + b.getY() + ";" + b.getZ();
}
private String getData(Block b, Player p) {
return getTitle(b) + ";" + b.getType().name() + ";" + p.getName();
}
} | {
"content_hash": "d7bd4682c162cfd77758d5e0b44a14ba",
"timestamp": "",
"source": "github",
"line_count": 720,
"max_line_length": 248,
"avg_line_length": 32.768055555555556,
"alnum_prop": 0.6512948755986945,
"repo_name": "Esaych/DDCustomPlugin",
"id": "f7ea17343225927ef7972ab574e6dfb9ac0f5c0f",
"size": "23593",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/net/diamonddominion/esaych/survival/DemiGodPackage.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "462562"
}
],
"symlink_target": ""
} |
#define VER_INTERNAL_NAME "path_set"
#define VER_FILE_DESCRIPTION "Modify system and user environment variables"
#define VER_MAJOR 1
#define VER_MINOR 7
#define VER_STRING2 "1.7"
#include "ver_defaults.h"
| {
"content_hash": "e36e0e31c45bcc394ea604e2e6fb04a0",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 75,
"avg_line_length": 28.25,
"alnum_prop": 0.6991150442477876,
"repo_name": "rasa/path_set",
"id": "fbf1bf66071fde1182e43520ddaacb44c0fb8d27",
"size": "297",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "version.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "600"
},
{
"name": "C++",
"bytes": "10517"
},
{
"name": "Makefile",
"bytes": "17272"
}
],
"symlink_target": ""
} |
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class FileUpload {
@Test
public void run() throws InterruptedException {
System.out.println(System.getProperty("user.dir"));
WebDriver fd = new FirefoxDriver();
fd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
fd.get(GlobalConstants.LOGIN_PAGE_URL);
fd.findElement(By.name("log")).sendKeys(GlobalConstants.USER_NAME);
fd.findElement(By.name("pwd")).sendKeys(GlobalConstants.PASSWORD);
fd.findElement(By.name("wp-submit")).click();
fd.findElement(By.linkText("Customize Your Site"));
fd.navigate().to(GlobalConstants.THEME_UPLOAD_PAGE_URL);
fd.findElement(By.name("themezip")).sendKeys(GlobalConstants.THEME_ZIP_FILE_PATH);
WebElement installNow = fd.findElement(By.name("install-theme-submit"));
System.out.println(installNow.isEnabled());
if(installNow.isEnabled())
{
installNow.submit();
}
Thread.sleep(2000);
fd.quit();
}
}
| {
"content_hash": "612e9035ab6b15f5923a5d1d05993cc1",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 84,
"avg_line_length": 27.404761904761905,
"alnum_prop": 0.733275412684622,
"repo_name": "sandeepsajiru/wordpressSelenium",
"id": "c8e523ce008ae4e2b2acb2d6c6ded6b62260a144",
"size": "1151",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/FileUpload.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "28796"
}
],
"symlink_target": ""
} |
<?php
namespace ARIPD\AdminBundle\Util\VPOS;
class YKB {
public $XML_SERVICE_URL;
public $mid;
public $tid;
// no-TDS
public $tranDateRequired = 1;
public $amount;
public $ccno;
public $currencyCode = 'YT';
public $cvc;
public $expDate;
public $installment;
public $XID;
// TDS
public $OOS_TDS_SERVICE_URL;
public $posnetid;
public $cardHolderName;
public $tranType = 'Sale';
public $bankData;
public $merchantData;
public $sign;
public $wpAmount = 0;
public function __construct() {
}
public function notds_xmldata1() {
return "xmldata=" . "<posnetRequest>" . "<mid>$this->mid</mid>"
. "<tid>$this->tid</tid>"
. "<tranDateRequired>$this->tranDateRequired</tranDateRequired>"
. "<sale>" . "<amount>$this->amount</amount>"
. "<ccno>$this->ccno</ccno>"
. "<currencyCode>$this->currencyCode</currencyCode>"
. "<cvc>$this->cvc</cvc>" . "<expDate>$this->expDate</expDate>"
. "<installment>$this->installment</installment>"
. "<orderID>$this->XID</orderID>" . "</sale>"
. "</posnetRequest>";
}
public function init_curl($request) {
$ch = curl_init(); // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $this->XML_SERVICE_URL); // set url to post to
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request/*$this->notds_xmldata1()*/); // add POST fields
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // return into a variable
curl_setopt($ch, CURLOPT_TIMEOUT, 90); // times out after 90s
$result = curl_exec($ch); // run the whole process
if (curl_errno($ch)) {
print curl_error($ch);
} else {
curl_close($ch);
}
return $result;
}
public function tds_xmldata1() {
return "xmldata=" . "<posnetRequest>" . "<mid>$this->mid</mid>"
. "<tid>$this->tid</tid>" . "<oosRequestData>"
. "<posnetid>$this->posnetid</posnetid>"
. "<ccno>$this->ccno</ccno>"
. "<expDate>$this->expDate</expDate>" . "<cvc>$this->cvc</cvc>"
. "<amount>$this->amount</amount>"
. "<currencyCode>$this->currencyCode</currencyCode>"
. "<installment>$this->installment</installment>"
. "<XID>$this->XID</XID>"
. "<cardHolderName>$this->cardHolderName</cardHolderName>"
. "<tranType>$this->tranType</tranType>" . "</oosRequestData>"
. "</posnetRequest>";
}
public function tds_xmldata2() {
return "xmldata=" . "<posnetRequest>" . "<mid>$this->mid</mid>"
. "<tid>$this->tid</tid>" . "<oosResolveMerchantData>"
. "<bankData>$this->bankData</bankData>"
. "<merchantData>$this->merchantData</merchantData>"
. "<sign>$this->sign</sign>" . "</oosResolveMerchantData>"
. "</posnetRequest>";
}
public function tds_xmldata3() {
return "xmldata=" . "<posnetRequest>" . "<mid>$this->mid</mid>"
. "<tid>$this->tid</tid>" . "<oosTranData>"
. "<bankData>$this->bankData</bankData>"
. "<wpAmount>$this->wpAmount</wpAmount>" . "</oosTranData>"
. "</posnetRequest>";
}
}
| {
"content_hash": "9d08439ae567076f2ccf2865aaa516ff",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 95,
"avg_line_length": 30.745098039215687,
"alnum_prop": 0.6087372448979592,
"repo_name": "gobb/albatros",
"id": "2a0c05f78a018581221e829a9d567497c4958460",
"size": "3136",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/ARIPD/AdminBundle/Util/VPOS/YKB.php",
"mode": "33261",
"license": "mit",
"language": [],
"symlink_target": ""
} |
int GetMaxLightSerializedSize() {
return std::max(
{GetPointLightSerializedSize(), GetAreaLightSerializedSize(), GetEnvLightSerializedSize()});
}
const ADFloat *SampleDirect(const ADFloat *buffer,
const ADBSphere &sceneSphere,
const ADVector3 &pos,
const ADVector3 &normal,
const ADVector2 rndParam,
const ADFloat time,
const bool isStatic,
ADVector3 &dirToLight,
ADVector3 &lightContrib,
ADFloat &cosAtLight,
ADFloat &directPdf,
ADFloat &emissionPdf) {
ADFloat type;
buffer = Deserialize(buffer, type);
std::vector<CondExprCPtr> ret = CreateCondExprVec(9);
BeginIf(Eq(type, (Float)LightType::PointLight), ret);
{
ADVector3 dirToLight;
ADVector3 lightContrib;
ADFloat cosAtLight;
ADFloat directPdf;
ADFloat emissionPdf;
SampleDirectPointLight(buffer,
sceneSphere,
pos,
normal,
rndParam,
time,
isStatic,
dirToLight,
lightContrib,
cosAtLight,
directPdf,
emissionPdf);
SetCondOutput({dirToLight[0],
dirToLight[1],
dirToLight[2],
lightContrib[0],
lightContrib[1],
lightContrib[2],
cosAtLight,
directPdf,
emissionPdf});
}
BeginElseIf(Eq(type, (Float)LightType::AreaLight));
{
ADVector3 dirToLight;
ADVector3 lightContrib;
ADFloat cosAtLight;
ADFloat directPdf;
ADFloat emissionPdf;
SampleDirectAreaLight(buffer,
sceneSphere,
pos,
normal,
rndParam,
time,
isStatic,
dirToLight,
lightContrib,
cosAtLight,
directPdf,
emissionPdf);
SetCondOutput({dirToLight[0],
dirToLight[1],
dirToLight[2],
lightContrib[0],
lightContrib[1],
lightContrib[2],
cosAtLight,
directPdf,
emissionPdf});
}
BeginElseIf(Eq(type, (Float)LightType::EnvLight));
{
ADVector3 dirToLight;
ADVector3 lightContrib;
ADFloat cosAtLight;
ADFloat directPdf;
ADFloat emissionPdf;
SampleDirectEnvLight(buffer,
sceneSphere,
pos,
normal,
rndParam,
time,
isStatic,
dirToLight,
lightContrib,
cosAtLight,
directPdf,
emissionPdf);
SetCondOutput({dirToLight[0],
dirToLight[1],
dirToLight[2],
lightContrib[0],
lightContrib[1],
lightContrib[2],
cosAtLight,
directPdf,
emissionPdf});
}
BeginElse();
{
SetCondOutput({Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0)});
}
EndIf();
dirToLight[0] = ret[0];
dirToLight[1] = ret[1];
dirToLight[2] = ret[2];
lightContrib[0] = ret[3];
lightContrib[1] = ret[4];
lightContrib[2] = ret[5];
cosAtLight = ret[6];
directPdf = ret[7];
emissionPdf = ret[8];
buffer += (GetMaxLightSerializedSize() - 1);
return buffer;
}
const ADFloat *Emission(const ADFloat *buffer,
const ADBSphere &sceneSphere,
const ADVector3 &dirToLight,
const ADVector3 &normalOnLight,
const ADFloat time,
ADVector3 &emission,
ADFloat &directPdf,
ADFloat &emissionPdf) {
ADFloat type;
buffer = Deserialize(buffer, type);
std::vector<CondExprCPtr> ret = CreateCondExprVec(5);
BeginIf(Eq(type, (Float)LightType::AreaLight), ret);
{
ADVector3 emission;
ADFloat directPdf;
ADFloat emissionPdf;
EmissionAreaLight(
buffer, sceneSphere, dirToLight, normalOnLight, time, emission, directPdf, emissionPdf);
SetCondOutput({emission[0], emission[1], emission[2], directPdf, emissionPdf});
}
BeginElseIf(Eq(type, (Float)LightType::EnvLight));
{
ADVector3 emission;
ADFloat directPdf;
ADFloat emissionPdf;
EmissionEnvLight(
buffer, sceneSphere, dirToLight, normalOnLight, time, emission, directPdf, emissionPdf);
SetCondOutput({emission[0], emission[1], emission[2], directPdf, emissionPdf});
}
BeginElse();
{
SetCondOutput({Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0)});
}
EndIf();
emission[0] = ret[0];
emission[1] = ret[1];
emission[2] = ret[2];
directPdf = ret[3];
emissionPdf = ret[4];
buffer += (GetMaxLightSerializedSize() - 1);
return buffer;
}
const ADFloat *Emit(const ADFloat *buffer,
const ADBSphere &sceneSphere,
const ADVector2 rndParamPos,
const ADVector2 rndParamDir,
const ADFloat time,
const bool isStatic,
ADRay &ray,
ADVector3 &emission,
ADFloat &cosAtLight,
ADFloat &emissionPdf,
ADFloat &directPdf) {
ADFloat type;
buffer = Deserialize(buffer, type);
std::vector<CondExprCPtr> ret = CreateCondExprVec(12);
BeginIf(Eq(type, (Float)LightType::PointLight), ret);
{
ADRay ray;
ADVector3 emission;
ADFloat cosAtLight;
ADFloat emissionPdf;
ADFloat directPdf;
EmitPointLight(buffer,
sceneSphere,
rndParamPos,
rndParamDir,
time,
isStatic,
ray,
emission,
cosAtLight,
emissionPdf,
directPdf);
SetCondOutput({ray.org[0],
ray.org[1],
ray.org[2],
ray.dir[0],
ray.dir[1],
ray.dir[2],
emission[0],
emission[1],
emission[2],
cosAtLight,
emissionPdf,
directPdf});
}
BeginElseIf(Eq(type, (Float)LightType::AreaLight));
{
ADRay ray;
ADVector3 emission;
ADFloat cosAtLight;
ADFloat emissionPdf;
ADFloat directPdf;
EmitAreaLight(buffer,
sceneSphere,
rndParamPos,
rndParamDir,
time,
isStatic,
ray,
emission,
cosAtLight,
emissionPdf,
directPdf);
SetCondOutput({ray.org[0],
ray.org[1],
ray.org[2],
ray.dir[0],
ray.dir[1],
ray.dir[2],
emission[0],
emission[1],
emission[2],
cosAtLight,
emissionPdf,
directPdf});
}
BeginElseIf(Eq(type, (Float)LightType::EnvLight));
{
ADRay ray;
ADVector3 emission;
ADFloat cosAtLight;
ADFloat emissionPdf;
ADFloat directPdf;
EmitEnvLight(buffer,
sceneSphere,
rndParamPos,
rndParamDir,
time,
isStatic,
ray,
emission,
cosAtLight,
emissionPdf,
directPdf);
SetCondOutput({ray.org[0],
ray.org[1],
ray.org[2],
ray.dir[0],
ray.dir[1],
ray.dir[2],
emission[0],
emission[1],
emission[2],
cosAtLight,
emissionPdf,
directPdf});
}
BeginElse();
{
SetCondOutput({Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0),
Const<ADFloat>(0.0)});
}
EndIf();
ray.org[0] = ret[0];
ray.org[1] = ret[1];
ray.org[2] = ret[2];
ray.dir[0] = ret[3];
ray.dir[1] = ret[4];
ray.dir[2] = ret[5];
emission[0] = ret[6];
emission[1] = ret[7];
emission[2] = ret[8];
cosAtLight = ret[9];
emissionPdf = ret[10];
directPdf = ret[11];
buffer += (GetMaxLightSerializedSize() - 1);
return buffer;
}
| {
"content_hash": "7690ea279501f1f4a6ba537d2889bbd5",
"timestamp": "",
"source": "github",
"line_count": 318,
"max_line_length": 100,
"avg_line_length": 34.430817610062896,
"alnum_prop": 0.4117270983651475,
"repo_name": "BachiLi/dpt",
"id": "7fa2ad10f3c1361a16870276d2dcec1750aff676",
"size": "11057",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/light.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "1102546"
}
],
"symlink_target": ""
} |
/* ------------------
* AbstractGraph.java
* ------------------
* (C) Copyright 2003-2008, by Barak Naveh and Contributors.
*
* Original Author: Barak Naveh
* Contributor(s): Christian Hammer
* Vladimir Kostyukov
*
* $Id$
*
* Changes
* -------
* 24-Jul-2003 : Initial revision (BN);
* 11-Mar-2004 : Made generic (CH);
* 07-May-2006 : Changed from List<Edge> to Set<Edge> (JVS);
* 28-May-2006 : Moved connectivity info from edge to graph (JVS);
* 14-Jun-2012 : Added hashCode() and equals() methods implementation (VK);
*
*/
package org.jgrapht.graph;
import java.util.*;
import org.jgrapht.*;
import org.jgrapht.util.*;
/**
* A skeletal implementation of the <tt>Graph</tt> interface, to minimize the
* effort required to implement graph interfaces. This implementation is
* applicable to both: directed graphs and undirected graphs.
*
* @author Barak Naveh
* @see Graph
* @see DirectedGraph
* @see UndirectedGraph
*/
public abstract class AbstractGraph<V, E>
implements Graph<V, E>
{
/**
* Construct a new empty graph object.
*/
protected AbstractGraph()
{
}
/**
* @see Graph#containsEdge(Object, Object)
*/
@Override public boolean containsEdge(V sourceVertex, V targetVertex)
{
return getEdge(sourceVertex, targetVertex) != null;
}
/**
* @see Graph#removeAllEdges(Collection)
*/
@Override public boolean removeAllEdges(Collection<? extends E> edges)
{
boolean modified = false;
for (E e : edges) {
modified |= removeEdge(e);
}
return modified;
}
/**
* @see Graph#removeAllEdges(Object, Object)
*/
@Override public Set<E> removeAllEdges(V sourceVertex, V targetVertex)
{
Set<E> removed = getAllEdges(sourceVertex, targetVertex);
if (removed == null) {
return null;
}
removeAllEdges(removed);
return removed;
}
/**
* @see Graph#removeAllVertices(Collection)
*/
@Override public boolean removeAllVertices(Collection<? extends V> vertices)
{
boolean modified = false;
for (V v : vertices) {
modified |= removeVertex(v);
}
return modified;
}
/**
* Returns a string of the parenthesized pair (V, E) representing this
* G=(V,E) graph. 'V' is the string representation of the vertex set, and
* 'E' is the string representation of the edge set.
*
* @return a string representation of this graph.
*/
@Override public String toString()
{
return toStringFromSets(
vertexSet(),
edgeSet(),
(this instanceof DirectedGraph<?, ?>));
}
/**
* Ensures that the specified vertex exists in this graph, or else throws
* exception.
*
* @param v vertex
*
* @return <code>true</code> if this assertion holds.
*
* @throws NullPointerException if specified vertex is <code>null</code>.
* @throws IllegalArgumentException if specified vertex does not exist in
* this graph.
*/
protected boolean assertVertexExist(V v)
{
if (containsVertex(v)) {
return true;
} else if (v == null) {
throw new NullPointerException();
} else {
throw new IllegalArgumentException(
"no such vertex in graph: " + v.toString());
}
}
/**
* Removes all the edges in this graph that are also contained in the
* specified edge array. After this call returns, this graph will contain no
* edges in common with the specified edges. This method will invoke the
* {@link Graph#removeEdge(Object)} method.
*
* @param edges edges to be removed from this graph.
*
* @return <tt>true</tt> if this graph changed as a result of the call.
*
* @see Graph#removeEdge(Object)
* @see Graph#containsEdge(Object)
*/
protected boolean removeAllEdges(E [] edges)
{
boolean modified = false;
for (int i = 0; i < edges.length; i++) {
modified |= removeEdge(edges[i]);
}
return modified;
}
/**
* Helper for subclass implementations of toString( ).
*
* @param vertexSet the vertex set V to be printed
* @param edgeSet the edge set E to be printed
* @param directed true to use parens for each edge (representing directed);
* false to use curly braces (representing undirected)
*
* @return a string representation of (V,E)
*/
protected String toStringFromSets(
Collection<? extends V> vertexSet,
Collection<? extends E> edgeSet,
boolean directed)
{
List<String> renderedEdges = new ArrayList<String>();
StringBuffer sb = new StringBuffer();
for (E e : edgeSet) {
if ((e.getClass() != DefaultEdge.class)
&& (e.getClass() != DefaultWeightedEdge.class))
{
sb.append(e.toString());
sb.append("=");
}
if (directed) {
sb.append("(");
} else {
sb.append("{");
}
sb.append(getEdgeSource(e));
sb.append(",");
sb.append(getEdgeTarget(e));
if (directed) {
sb.append(")");
} else {
sb.append("}");
}
// REVIEW jvs 29-May-2006: dump weight somewhere?
renderedEdges.add(sb.toString());
sb.setLength(0);
}
return "(" + vertexSet + ", " + renderedEdges + ")";
}
/**
* Returns a hash code value for this graph. The hash code of a graph is
* defined to be the sum of the hash codes of vertices and edges in the
* graph. It is also based on graph topology and edges weights.
*
* @return the hash code value this graph
*
* @see Object#hashCode()
*/
@Override public int hashCode()
{
int hash = vertexSet().hashCode();
for (E e : edgeSet()) {
int part = e.hashCode();
int source = getEdgeSource(e).hashCode();
int target = getEdgeTarget(e).hashCode();
// see http://en.wikipedia.org/wiki/Pairing_function (VK);
int pairing =
((source + target)
* (source + target + 1) / 2) + target;
part = (27 * part) + pairing;
long weight = (long) getEdgeWeight(e);
part = (27 * part) + (int) (weight ^ (weight >>> 32));
hash += part;
}
return hash;
}
/**
* Indicates whether some other object is "equal to" this graph. Returns
* <code>true</code> if the given object is also a graph, the two graphs are
* instances of the same graph class, have identical vertices and edges sets
* with the same weights.
*
* @param obj object to be compared for equality with this graph
*
* @return <code>true</code> if the specified object is equal to this graph
*
* @see Object#equals(Object)
*/
@Override public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
return false;
}
TypeUtil<Graph<V, E>> typeDecl = null;
Graph<V, E> g = TypeUtil.uncheckedCast(obj, typeDecl);
if (!vertexSet().equals(g.vertexSet())) {
return false;
}
if (edgeSet().size() != g.edgeSet().size()) {
return false;
}
for (E e : edgeSet()) {
V source = getEdgeSource(e);
V target = getEdgeTarget(e);
if (!g.containsEdge(e)) {
return false;
}
if (!g.getEdgeSource(e).equals(source)
|| !g.getEdgeTarget(e).equals(target))
{
return false;
}
if (Math.abs(getEdgeWeight(e) - g.getEdgeWeight(e)) > 10e-7) {
return false;
}
}
return true;
}
}
// End AbstractGraph.java
| {
"content_hash": "073f4f3c4d5e3b2519a20ba15d3df65a",
"timestamp": "",
"source": "github",
"line_count": 302,
"max_line_length": 80,
"avg_line_length": 27.387417218543046,
"alnum_prop": 0.5491476242292347,
"repo_name": "Alejandro-Frech/AnalisisAlgoritmos",
"id": "6edcb5fbe57fd6f92912ccf80957c8d4a4f5d717",
"size": "8990",
"binary": false,
"copies": "9",
"ref": "refs/heads/master",
"path": "src/org/jgrapht/graph/AbstractGraph.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "12210"
},
{
"name": "Java",
"bytes": "1122159"
}
],
"symlink_target": ""
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.LanguageServer.Handler.RequestExecutionQueue;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Context for requests handled by <see cref="IRequestHandler"/>
/// </summary>
internal readonly struct RequestContext
{
/// <summary>
/// This will be the <see cref="NonMutatingDocumentChangeTracker"/> for non-mutating requests because they're not allowed to change documents
/// </summary>
private readonly IDocumentChangeTracker _documentChangeTracker;
/// <summary>
/// Contains the LSP text for all opened LSP documents from when this request was processed in the queue.
/// </summary>
/// <remarks>
/// This is a snapshot of the source text that reflects the LSP text based on the order of this request in the queue.
/// It contains text that is consistent with all prior LSP text sync notifications, but LSP text sync requests
/// which are ordered after this one in the queue are not reflected here.
/// </remarks>
private readonly ImmutableDictionary<Uri, SourceText> _trackedDocuments;
/// <summary>
/// The solution state that the request should operate on, if the handler requires an LSP solution, or <see langword="null"/> otherwise
/// </summary>
public readonly Solution? Solution;
/// <summary>
/// The client capabilities for the request.
/// </summary>
public readonly ClientCapabilities ClientCapabilities;
/// <summary>
/// The LSP client making the request
/// </summary>
public readonly string? ClientName;
/// <summary>
/// The document that the request is for, if applicable. This comes from the <see cref="TextDocumentIdentifier"/> returned from the handler itself via a call to <see cref="IRequestHandler{RequestType, ResponseType}.GetTextDocumentIdentifier(RequestType)"/>.
/// </summary>
public readonly Document? Document;
/// <summary>
/// The languages supported by the server making the request.
/// </summary>
public readonly ImmutableArray<string> SupportedLanguages;
public readonly IGlobalOptionService GlobalOptions;
/// <summary>
/// Tracing object that can be used to log information about the status of requests.
/// </summary>
private readonly Action<string> _traceInformation;
public RequestContext(
Solution? solution,
Action<string> traceInformation,
ClientCapabilities clientCapabilities,
string? clientName,
Document? document,
IDocumentChangeTracker documentChangeTracker,
ImmutableDictionary<Uri, SourceText> trackedDocuments,
ImmutableArray<string> supportedLanguages,
IGlobalOptionService globalOptions)
{
Document = document;
Solution = solution;
ClientCapabilities = clientCapabilities;
ClientName = clientName;
SupportedLanguages = supportedLanguages;
GlobalOptions = globalOptions;
_documentChangeTracker = documentChangeTracker;
_traceInformation = traceInformation;
_trackedDocuments = trackedDocuments;
}
public static RequestContext? Create(
bool requiresLSPSolution,
TextDocumentIdentifier? textDocument,
string? clientName,
ILspLogger logger,
ClientCapabilities clientCapabilities,
LspWorkspaceManager lspWorkspaceManager,
IDocumentChangeTracker documentChangeTracker,
ImmutableArray<string> supportedLanguages,
IGlobalOptionService globalOptions)
{
// Retrieve the current LSP tracked text as of this request.
// This is safe as all creation of request contexts cannot happen concurrently.
var trackedDocuments = lspWorkspaceManager.GetTrackedLspText();
// If the handler doesn't need an LSP solution we do two important things:
// 1. We don't bother building the LSP solution for perf reasons
// 2. We explicitly don't give the handler a solution or document, even if we could
// so they're not accidentally operating on stale solution state.
if (!requiresLSPSolution)
{
return new RequestContext(solution: null, logger.TraceInformation, clientCapabilities, clientName, document: null, documentChangeTracker, trackedDocuments, supportedLanguages, globalOptions);
}
// Go through each registered workspace, find the solution that contains the document that
// this request is for, and then updates it based on the state of the world as we know it, based on the
// text content in the document change tracker.
Document? document = null;
var workspaceSolution = lspWorkspaceManager.TryGetHostLspSolution();
if (textDocument is not null)
{
// we were given a request associated with a document. Find the corresponding roslyn
// document for this. If we can't, we cannot proceed.
document = lspWorkspaceManager.GetLspDocument(textDocument, clientName);
if (document != null)
workspaceSolution = document.Project.Solution;
}
if (workspaceSolution == null)
{
logger.TraceError("Could not find appropriate solution for operation");
return null;
}
var context = new RequestContext(
workspaceSolution,
logger.TraceInformation,
clientCapabilities,
clientName,
document,
documentChangeTracker,
trackedDocuments,
supportedLanguages,
globalOptions);
return context;
}
/// <summary>
/// Allows a mutating request to open a document and start it being tracked.
/// Mutating requests are serialized by the execution queue in order to prevent concurrent access.
/// </summary>
public void StartTracking(Uri uri, SourceText initialText)
=> _documentChangeTracker.StartTracking(uri, initialText);
/// <summary>
/// Allows a mutating request to update the contents of a tracked document.
/// Mutating requests are serialized by the execution queue in order to prevent concurrent access.
/// </summary>
public void UpdateTrackedDocument(Uri uri, SourceText changedText)
=> _documentChangeTracker.UpdateTrackedDocument(uri, changedText);
public SourceText GetTrackedDocumentSourceText(Uri documentUri)
{
Contract.ThrowIfFalse(_trackedDocuments.ContainsKey(documentUri), $"Attempted to get text for {documentUri} which is not open.");
return _trackedDocuments[documentUri];
}
/// <summary>
/// Allows a mutating request to close a document and stop it being tracked.
/// Mutating requests are serialized by the execution queue in order to prevent concurrent access.
/// </summary>
public void StopTracking(Uri uri)
=> _documentChangeTracker.StopTracking(uri);
public bool IsTracking(Uri documentUri)
=> _trackedDocuments.ContainsKey(documentUri);
/// <summary>
/// Logs an informational message.
/// </summary>
public void TraceInformation(string message)
=> _traceInformation(message);
}
}
| {
"content_hash": "6a9b51a29179f7c29661900f4fd5bd88",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 265,
"avg_line_length": 45.01639344262295,
"alnum_prop": 0.6462733673221656,
"repo_name": "sharwell/roslyn",
"id": "424d747c7d6a329e95694340b80bd98e119e1f27",
"size": "8240",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Features/LanguageServer/Protocol/Handler/RequestContext.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "1C Enterprise",
"bytes": "257760"
},
{
"name": "Batchfile",
"bytes": "8025"
},
{
"name": "C#",
"bytes": "141191940"
},
{
"name": "C++",
"bytes": "5602"
},
{
"name": "CMake",
"bytes": "9153"
},
{
"name": "Dockerfile",
"bytes": "2450"
},
{
"name": "F#",
"bytes": "549"
},
{
"name": "PowerShell",
"bytes": "243533"
},
{
"name": "Shell",
"bytes": "94467"
},
{
"name": "Visual Basic .NET",
"bytes": "71837994"
}
],
"symlink_target": ""
} |
// SPDX-License-Identifier: MIT
package protocol
import "github.com/caixw/apidoc/v7/core"
// TextDocumentIdentifier text documents are identified using a URI.
// On the protocol level, URIs are passed as strings.
// The corresponding JSON structure looks like this:
type TextDocumentIdentifier struct {
// The text document's URI.
URI core.URI `json:"uri"`
}
// VersionedTextDocumentIdentifier an identifier to denote a specific version of a text document.
type VersionedTextDocumentIdentifier struct {
TextDocumentIdentifier
// The version number of this document. If a versioned text document identifier
// is sent from the server to the client and the file is not open in the editor
// (the server has not received an open notification before) the server can send
// `null` to indicate that the version is known and the content on disk is the
// truth (as speced with document content ownership).
//
// The version number of a document will increase after each change, including
// undo/redo. The number doesn't need to be consecutive.
Version int `json:"version,omitempty"`
}
// TextDocumentPositionParams a parameter literal used in requests to pass a text document and a position inside that document.
type TextDocumentPositionParams struct {
// The text document.
TextDocument TextDocumentIdentifier `json:"textDocument"`
// The position inside the text document.
Position core.Position `json:"position"`
}
// TextDocumentClientCapabilities text document specific client capabilities.
type TextDocumentClientCapabilities struct {
Synchronization *struct {
// Whether text document synchronization supports dynamic registration.
DynamicRegistration bool `json:"dynamicRegistration,omitempty"`
// The client supports sending will save notifications.
WillSave bool `json:"willSave,omitempty"`
// The client supports sending a will save request and
// waits for a response providing text edits which will
// be applied to the document before it is saved.
WillSaveWaitUntil bool `json:"willSaveWaitUntil,omitempty"`
// The client supports did save notifications.
DidSave bool `json:"didSave,omitempty"`
} `json:"synchronization,omitempty"`
// Capabilities specific to the `textDocument/completion`
Completion *CompletionClientCapabilities `json:"completion,omitempty"`
// Capabilities specific to the `textDocument/hover`
Hover *HoverCapabilities `json:"hover,omitempty"`
// Capabilities specific to the `textDocument/textDocument/semanticTokens/*`
SemanticTokens *SemanticTokensClientCapabilities `json:"semanticTokens,omitempty"`
// Capabilities specific to the `textDocument/references` request.
References *ReferenceClientCapabilities `json:"references,omitempty"`
// Capabilities specific to the `textDocument/definition`.
//
// Since 3.14.0
Definition *DefinitionClientCapabilities `json:"definition,omitempty"`
// Capabilities specific to `textDocument/publishDiagnostics`.
PublishDiagnostics *PublishDiagnosticsClientCapabilities `json:"publishDiagnostics,omitempty"`
// Capabilities specific to `textDocument/foldingRange` requests.
//
// Since 3.10.0
FoldingRange *FoldingRangeClientCapabilities `json:"foldingRange,omitempty"`
}
// ServerCapabilitiesTextDocumentSyncOptions 服务端对文档同步的支持项
type ServerCapabilitiesTextDocumentSyncOptions struct {
// Open and close notifications are sent to the server.
// If omitted open close notification should not be sent.
OpenClose bool `json:"openClose,omitempty"`
// Change notifications are sent to the server. See TextDocumentSyncKind.None, TextDocumentSyncKind.Full
// and TextDocumentSyncKind.Incremental. If omitted it defaults to TextDocumentSyncKind.None.
Change TextDocumentSyncKind `json:"change,omitempty"`
}
// TextDocumentRegistrationOptions General text document registration options
type TextDocumentRegistrationOptions struct {
// A document selector to identify the scope of the registration. If set to null
// the document selector provided on the client side will be used.
DocumentSelector DocumentSelector `json:"documentSelector,omitempty"`
}
// DocumentSelector is the combination of one or more document filters
type DocumentSelector []DocumentFilter
// DocumentFilter denotes a document through properties like language,
// scheme or pattern. An example is a filter that applies to TypeScript files on disk.
// Another example is a filter the applies to JSON files with name package.json:
//
// { language: 'typescript', scheme: 'file' }
// { language: 'json', pattern: '**/package.json' }
type DocumentFilter struct {
// A language id, like `typescript`.
Language string `json:"language,omitempty"`
// A Uri [scheme](#Uri.scheme), like `file` or `untitled`.
Scheme string `json:"scheme,omitempty"`
// A glob pattern, like `*.{ts,js}`.
//
// Glob patterns can have the following syntax:
// - `*` to match one or more characters in a path segment
// - `?` to match on one character in a path segment
// - `**` to match any number of path segments, including none
// - `{}` to group conditions (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)
// - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)
// - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)
Pattern string `json:"pattern,omitempty"`
}
// DidChangeTextDocumentParams textDocument/didChange 的参数
type DidChangeTextDocumentParams struct {
// The document that did change. The version number points
// to the version after all provided content changes have been applied.
TextDocument VersionedTextDocumentIdentifier `json:"textDocument"`
// The actual content changes. The content changes describe single state changes
// to the document. So if there are two content changes c1 (at array index 0) and
// c2 (at array index 1) for a document in state S then c1 moves the document from
// S to S' and c2 from S' to S''. So c1 is computed on the state S and c2 is computed
// on the state S'.
//
// To mirror the content of a document using change events use the following approach:
// - start with the same initial content
// - apply the 'textDocument/didChange' notifications in the order you recevie them.
// - apply the `TextDocumentContentChangeEvent`s in a single notification in the order
// you receive them.
ContentChanges []TextDocumentContentChangeEvent `json:"contentChanges"`
}
// Blocks 返回 core.Block 的列表
func (p *DidChangeTextDocumentParams) Blocks() []core.Block {
blocks := make([]core.Block, 0, len(p.ContentChanges))
for _, c := range p.ContentChanges {
blk := core.Block{
Data: []byte(c.Text),
Location: core.Location{
URI: p.TextDocument.URI,
},
}
if c.Range != nil {
blk.Location.Range = *c.Range
}
blocks = append(blocks, blk)
}
return blocks
}
// TextDocumentContentChangeEvent an event describing a change to a text document.
// If range and rangeLength are omitted the new text is considered to be
// the full content of the document.
type TextDocumentContentChangeEvent struct {
// The range of the document that changed.
Range *core.Range `json:"range,omitempty"`
// The new text for the provided range.
// The new text of the whole document.
//
// 如果没有 Range 内容,表示整个文档内容;否则表示 Range 表示的内容
Text string `json:"text"`
// The optional length of the range that got replaced.
//
// @deprecated use range instead.
RangeLength int `json:"rangeLength,omitempty"`
}
| {
"content_hash": "e104074b8c3b9e0d2f42aaca3ae74c9c",
"timestamp": "",
"source": "github",
"line_count": 184,
"max_line_length": 156,
"avg_line_length": 41.16847826086956,
"alnum_prop": 0.7584158415841584,
"repo_name": "caixw/apidoc",
"id": "3831e6d860f54fdd7a603386fd51590a8f111dd3",
"size": "7669",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "internal/lsp/protocol/textdocument.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "348"
},
{
"name": "Dockerfile",
"bytes": "112"
},
{
"name": "Go",
"bytes": "750447"
},
{
"name": "PHP",
"bytes": "171"
},
{
"name": "Shell",
"bytes": "672"
}
],
"symlink_target": ""
} |
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Classdirectory
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| {
"content_hash": "df1e7769ae86809a04130896181c3167",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 82,
"avg_line_length": 33.388888888888886,
"alnum_prop": 0.7653910149750416,
"repo_name": "CCSU-CS416F17/CS416F17CourseInfo",
"id": "1ec26d26b73ec7ca6dfb7a8da2d8c23a82f15c30",
"size": "601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "railsdemos/class11-01-2017/classdirectory/config/application.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17063"
},
{
"name": "CoffeeScript",
"bytes": "2532"
},
{
"name": "HTML",
"bytes": "207355"
},
{
"name": "Java",
"bytes": "712436"
},
{
"name": "JavaScript",
"bytes": "6463"
},
{
"name": "Ruby",
"bytes": "158344"
}
],
"symlink_target": ""
} |
import type {Path} from '../paths'
import type {SanityDocument} from '../documents'
export interface Reference {
_type: string
_ref: string
_key?: string
_weak?: boolean
_strengthenOnPublish?: {
type: string
weak?: boolean
template?: {id: string; params: Record<string, string | number | boolean>}
}
}
export interface WeakReference extends Reference {
_weak: true
}
export type ReferenceFilterSearchOptions = {
filter?: string
params?: Record<string, unknown>
tag?: string
}
export type ReferenceFilterResolver = (options: {
document: SanityDocument
parent?: Record<string, unknown> | Record<string, unknown>[]
parentPath: Path
}) => ReferenceFilterSearchOptions | Promise<ReferenceFilterSearchOptions>
export type ReferenceFilterOptions =
| {filter: ReferenceFilterResolver}
| {filter: string; filterParams?: Record<string, unknown>}
export type ReferenceOptions = {disableNew: boolean} & ReferenceFilterOptions
| {
"content_hash": "16d41957975c19b3dd7e0d325c2e3b55",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 78,
"avg_line_length": 26.72222222222222,
"alnum_prop": 0.7318087318087318,
"repo_name": "sanity-io/sanity",
"id": "7acc76eb9454c2fd4b673566cf1a42def12bfe45",
"size": "962",
"binary": false,
"copies": "1",
"ref": "refs/heads/next",
"path": "packages/@sanity/types/src/reference/types.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "235048"
},
{
"name": "HTML",
"bytes": "181261"
},
{
"name": "JavaScript",
"bytes": "1485414"
},
{
"name": "Shell",
"bytes": "1303"
},
{
"name": "TypeScript",
"bytes": "3980581"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.