text stringlengths 2 1.04M | meta dict |
|---|---|
package org.robolectric.shadows;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.ComponentName;
import org.robolectric.annotation.Implements;
import org.robolectric.annotation.Implementation;
@Implements(SearchManager.class)
public class ShadowSearchManager {
@Implementation
public SearchableInfo getSearchableInfo(ComponentName componentName) {
// Prevent Robolectric from calling through
return null;
}
}
| {
"content_hash": "50c8d00f478ff9498836e8617f0495b4",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 72,
"avg_line_length": 27.58823529411765,
"alnum_prop": 0.8208955223880597,
"repo_name": "qx/FullRobolectricTestSample",
"id": "cd1ba759ba66b7419e63e96415b3c9d1c96e0754",
"size": "469",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/robolectric/shadows/ShadowSearchManager.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2754039"
},
{
"name": "Ruby",
"bytes": "628"
},
{
"name": "Shell",
"bytes": "8486"
}
],
"symlink_target": ""
} |
@interface IBAInputStreamLineReaderTests : GHTestCase {
}
@end
| {
"content_hash": "6cf0a0c07b192de0f5007caba579db04",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 55,
"avg_line_length": 16,
"alnum_prop": 0.796875,
"repo_name": "ittybittyapps/ittybittybits",
"id": "ec9da8ec5b9f5ca83cab9189f6aeac5a4abefa56",
"size": "833",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/Foundation/IBAInputStreamLineReaderTests.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "19536"
},
{
"name": "Objective-C",
"bytes": "763214"
}
],
"symlink_target": ""
} |
package com.greencatsoft.d3.event
import scala.scalajs.js
import scala.scalajs.js.UndefOr
import org.scalajs.dom.Node
import com.greencatsoft.d3.selection.{ ElementIterator, Selection }
@js.native
trait EventSource[A <: Node, B <: Selection[A, B]] extends js.Object {
def on(event: String): UndefOr[js.ThisFunction] = js.native
def on[T](event: String, listener: ElementIterator[A, T]): B = js.native
def on[T](event: String, listener: ElementIterator[A, T], capture: Boolean): B = js.native
def transition(): B = js.native
def interrupt(): B = js.native
}
| {
"content_hash": "b6fcc83a1dd4c028bd3acefc26f603b6",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 92,
"avg_line_length": 26.181818181818183,
"alnum_prop": 0.7204861111111112,
"repo_name": "greencatsoft/scalajs-d3",
"id": "ba87e1fdd6f6825632af41ffbaad4b51b0ddd27d",
"size": "576",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/scala/com/greencatsoft/d3/event/EventSource.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "25874"
}
],
"symlink_target": ""
} |
#include <string.h> /* for memset */
#include "GUI.h"
#include "BUTTON.h"
#include "FRAMEWIN.h"
#include "TEXT.h"
#include "DIALOG.h"
#if GUI_WINSUPPORT
/*********************************************************************
*
* Defaults
*
**********************************************************************
*/
#ifndef MESSAGEBOX_BORDER
#define MESSAGEBOX_BORDER 4
#endif
#ifndef MESSAGEBOX_XSIZEOK
#define MESSAGEBOX_XSIZEOK 50
#endif
#ifndef MESSAGEBOX_YSIZEOK
#define MESSAGEBOX_YSIZEOK 20
#endif
#ifndef MESSAGEBOX_BKCOLOR
#define MESSAGEBOX_BKCOLOR GUI_WHITE
#endif
#define ID_FRAME 100
/*********************************************************************
*
* Static functions
*
**********************************************************************
*/
static WM_RESULT _MESSAGEBOX_cbCallback(WM_MESSAGE * pMsg) {
WM_HWIN hWin = pMsg->hWin;
switch (pMsg->MsgId) {
case WM_INIT_DIALOG:
FRAMEWIN_SetClientColor(hWin, MESSAGEBOX_BKCOLOR);
break;
case WM_KEY:
{
int Key = ((WM_KEY_INFO*)(pMsg->Data.p))->Key;
switch (Key) {
case GUI_KEY_ESCAPE:
GUI_EndDialog(hWin, 1); /* End dialog with return value 1 if <ESC> is pressed */
break;
case GUI_KEY_ENTER:
GUI_EndDialog(hWin, 0); /* End dialog with return value 0 if <ENTER> is pressed */
break;
}
}
break;
case WM_NOTIFY_PARENT:
{
int NCode = pMsg->Data.v; /* Get notification code */
int Id = WM_GetId(pMsg->hWinSrc); /* Get control ID */
switch (NCode) {
case WM_NOTIFICATION_RELEASED: /* React only if released */
if (Id == GUI_ID_OK) {
GUI_EndDialog(hWin, 0); /* End dialog with return value 0 if OK */
}
break;
}
}
break;
default:
WM_DefaultProc(pMsg);
}
}
/*********************************************************************
*
* Exported routines
*
**********************************************************************
*/
int GUI_MessageBox(const char * sMessage, const char * sCaption, int Flags) {
GUI_WIDGET_CREATE_INFO _aDialogCreate[3]; /* 0: FrameWin, 1: Text, 2: Button */
int BorderSize = FRAMEWIN_GetDefaultBorderSize(); /* Default border size of frame window */
int xSizeFrame = MESSAGEBOX_XSIZEOK + 2 * BorderSize + MESSAGEBOX_BORDER * 2; /* XSize of frame window */
int ySizeFrame; /* YSize of frame window */
int x0, y0; /* Position of frame window */
int xSizeMessage; /* Length in pixels of message */
int xSizeCaption; /* Length in pixels of caption */
int ySizeCaption; /* YSize of caption */
int ySizeMessage; /* YSize of message */
GUI_RECT Rect;
const GUI_FONT * pOldFont;
/* Zeroinit variables */
memset(_aDialogCreate, 0, sizeof(_aDialogCreate));
/* Get dimension of message */
pOldFont = GUI_SetFont(TEXT_GetDefaultFont());
GUI_GetTextExtend(&Rect, sMessage, 255);
xSizeMessage = Rect.x1 - Rect.x0 + MESSAGEBOX_BORDER * 2;
ySizeMessage = Rect.y1 - Rect.y0 + 1;
if (xSizeFrame < (xSizeMessage + 4 + MESSAGEBOX_BORDER * 2))
xSizeFrame = xSizeMessage + 4 + MESSAGEBOX_BORDER * 2;
ySizeCaption = GUI_GetYSizeOfFont(FRAMEWIN_GetDefaultFont());
if (ySizeCaption < FRAMEWIN_GetDefaultCaptionSize())
ySizeCaption = FRAMEWIN_GetDefaultCaptionSize();
ySizeFrame = ySizeMessage + /* size of message */
MESSAGEBOX_YSIZEOK + /* size of button */
ySizeCaption + /* caption size */
MESSAGEBOX_BORDER * 3 + /* inner border - text, text - button, button - bottom */
BorderSize * 2 + /* top & bottom border */
1; /* inner border */
/* Get xsize of caption */
xSizeCaption = GUI_GetStringDistX(sCaption);
if (xSizeFrame < xSizeCaption + BorderSize * 2)
xSizeFrame = xSizeCaption + BorderSize * 2;
/* Check maximum */
if (xSizeFrame > LCD_GET_XSIZE())
xSizeFrame = LCD_GET_XSIZE();
if (ySizeFrame > LCD_GET_YSIZE())
ySizeFrame = LCD_GET_YSIZE();
/* Calculate position of framewin */
x0 = (LCD_GET_XSIZE() - xSizeFrame) / 2;
y0 = (LCD_GET_YSIZE() - ySizeFrame) / 2;
/* Fill frame win ressource */
_aDialogCreate[0].pfCreateIndirect = FRAMEWIN_CreateIndirect;
_aDialogCreate[0].pName = sCaption;
_aDialogCreate[0].x0 = x0;
_aDialogCreate[0].y0 = y0;
_aDialogCreate[0].xSize = xSizeFrame;
_aDialogCreate[0].ySize = ySizeFrame;
if (Flags & GUI_MESSAGEBOX_CF_MOVEABLE) {
_aDialogCreate[0].Flags = FRAMEWIN_CF_MOVEABLE;
}
/* Fill text ressource */
_aDialogCreate[1].pfCreateIndirect = TEXT_CreateIndirect;
_aDialogCreate[1].pName = sMessage;
_aDialogCreate[1].x0 = (xSizeFrame - xSizeMessage - BorderSize * 2) / 2;
_aDialogCreate[1].y0 = MESSAGEBOX_BORDER;
_aDialogCreate[1].xSize = xSizeMessage;
_aDialogCreate[1].ySize = ySizeMessage;
_aDialogCreate[1].Para = GUI_TA_TOP | GUI_TA_HCENTER;
/* Fill button ressource */
_aDialogCreate[2].pfCreateIndirect = BUTTON_CreateIndirect;
_aDialogCreate[2].pName = "OK";
_aDialogCreate[2].Id = GUI_ID_OK;
_aDialogCreate[2].x0 = (xSizeFrame - MESSAGEBOX_XSIZEOK - BorderSize * 2) / 2;
_aDialogCreate[2].y0 = MESSAGEBOX_BORDER * 2 + ySizeMessage;
_aDialogCreate[2].xSize = MESSAGEBOX_XSIZEOK;
_aDialogCreate[2].ySize = MESSAGEBOX_YSIZEOK;
/* Exec dialog */
GUI_ExecDialogBox(_aDialogCreate, GUI_COUNTOF(_aDialogCreate), _MESSAGEBOX_cbCallback, 0, 0, 0);
GUI_SetFont(pOldFont);
return 0;
}
#else
void GUI_MessageBox_C(void) {} /* avoid empty object files */
#endif /* GUI_WINSUPPORT */
| {
"content_hash": "d1813fb70fda0be1ef98b3f96d073308",
"timestamp": "",
"source": "github",
"line_count": 167,
"max_line_length": 121,
"avg_line_length": 39.131736526946106,
"alnum_prop": 0.5112471308339709,
"repo_name": "byxob/calendar",
"id": "40941694a3a2f3cb137d05d44ae0cb570005bae5",
"size": "7492",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gui/Widget/messagebox.c",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "17761"
},
{
"name": "C",
"bytes": "13326850"
},
{
"name": "C++",
"bytes": "60565"
}
],
"symlink_target": ""
} |
<?php
/**
* This file is part of the Minty templating library.
* (c) Dániel Buga <daniel@bugadani.hu>
*
* For licensing information see the LICENSE file.
*/
namespace Minty\Compiler\Operators\ArithmeticOperators;
use Minty\Compiler\Operators\SimpleBinaryOperator;
class RemainderOperator extends SimpleBinaryOperator
{
public function operators()
{
return '%';
}
public function compileOperator()
{
return ' % ';
}
}
| {
"content_hash": "916ce44156096eebd17c45e6eccd331e",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 55,
"avg_line_length": 18,
"alnum_prop": 0.6816239316239316,
"repo_name": "bugadani/Minty",
"id": "5acc6ecdee0a2c7060531e8a33424093bebc4438",
"size": "469",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Compiler/Operators/ArithmeticOperators/RemainderOperator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "233736"
}
],
"symlink_target": ""
} |
<div id="myCarousel" class="carousel slide carousel-fade hidden-xs-up mb-3" data-ride="carousel">
<div class="carousel-inner">
@foreach ($slideshow->slides as $slide)
@if ($loop->first)
<div class="carousel-item active">
@else
<div class="carousel-item">
@endif
<img src="{{url('/')}}/storage/slides/{{$slide->image}}" class="d-block w-100">
<div class="container">
<div class="carousel-caption">
</div>
</div>
</div>
@endforeach
</div>
<!-- Controls -->
</div>
<!-- /.carousel --> | {
"content_hash": "e7f2da984c4efd7c1978fc23dfc19374",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 97,
"avg_line_length": 30,
"alnum_prop": 0.5578947368421052,
"repo_name": "bishopm/base",
"id": "615f294604aa3d9b5a9129ef310fbf66fc166566",
"size": "570",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Resources/views/shared/carousel-back.blade.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "206922"
},
{
"name": "HTML",
"bytes": "264805"
},
{
"name": "JavaScript",
"bytes": "838943"
},
{
"name": "PHP",
"bytes": "380718"
}
],
"symlink_target": ""
} |
import {parseAndGetExpression} from '../../../utils';
import {expect} from 'chai';
describe('ArrayPattern', () => {
it('should return correct type', () => {
expect(parseAndGetExpression('[x] = [1]').left.type).to.equal('ArrayPattern');
});
it('should accept empty pattern', () => {
var assignment = parseAndGetExpression('[] = [1]');
var pattern = assignment.left;
expect(pattern.elements.length).to.equal(0);
});
it('should accept 1-element array', () => {
var assignment = parseAndGetExpression('[ x ] = [ 1 ]');
var pattern = assignment.left;
expect(pattern.elements.length).to.equal(1);
expect(pattern.elements[0].type).to.equal('Identifier');
});
it('should accept multiple elements array', () => {
var assignment = parseAndGetExpression('[ x , y ] = [1]');
var pattern = assignment.left;
expect(pattern.elements.length).to.equal(2);
expect(pattern.elements[0].type).to.equal('Identifier');
expect(pattern.elements[0].name).to.equal('x');
expect(pattern.elements[1].type).to.equal('Identifier');
expect(pattern.elements[1].name).to.equal('y');
});
it('should accept nested pattern', () => {
var assignment = parseAndGetExpression('[ {x , y} ] = [1]');
var pattern = assignment.left;
expect(pattern.elements.length).to.equal(1);
expect(pattern.elements[0].type).to.equal('ObjectPattern');
});
it('should accept nested member expression', () => {
var assignment = parseAndGetExpression('[ g.x ] = [1]');
var pattern = assignment.left;
expect(pattern.elements.length).to.equal(1);
expect(pattern.elements[0].type).to.equal('MemberExpression');
expect(pattern.elements[0].object.name).to.equal('g');
expect(pattern.elements[0].property.name).to.equal('x');
});
it('should accept holes', () => {
var assignment = parseAndGetExpression('[ , x , , y , , ] = [1]');
var pattern = assignment.left;
expect(pattern.elements.length).to.equal(5);
expect(pattern.elements[0]).to.equal(null);
expect(pattern.elements[1].type).to.equal('Identifier');
expect(pattern.elements[2]).to.equal(null);
expect(pattern.elements[3].type).to.equal('Identifier');
expect(pattern.elements[4]).to.equal(null);
});
it('should accept holes-only', () => {
var assignment = parseAndGetExpression('[,,,] = [1]');
var pattern = assignment.left;
expect(pattern.elements.length).to.equal(3);
expect(pattern.elements[0]).to.equal(null);
expect(pattern.elements[1]).to.equal(null);
});
});
| {
"content_hash": "abe301cec446d4ad04c10f460d8b9a9b",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 86,
"avg_line_length": 41.378787878787875,
"alnum_prop": 0.6012449652142072,
"repo_name": "markelog/cst",
"id": "b8fe8a954a63c36f3ee31ca2e882c11e70fc179e",
"size": "2731",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/lib/elements/types/ArrayPattern.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "562330"
}
],
"symlink_target": ""
} |
package virthandler
import (
"fmt"
"net/http"
"strings"
"github.com/jeevatkm/go-model"
"k8s.io/client-go/kubernetes"
kubeapi "k8s.io/client-go/pkg/api"
"k8s.io/client-go/pkg/api/errors"
kubev1 "k8s.io/client-go/pkg/api/v1"
"k8s.io/client-go/pkg/util/workqueue"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"kubevirt.io/kubevirt/pkg/api/v1"
"kubevirt.io/kubevirt/pkg/kubecli"
"kubevirt.io/kubevirt/pkg/logging"
"kubevirt.io/kubevirt/pkg/virt-handler/virtwrap"
)
func NewVMController(lw cache.ListerWatcher, domainManager virtwrap.DomainManager, recorder record.EventRecorder, restClient rest.RESTClient, clientset *kubernetes.Clientset, host string) (cache.Store, workqueue.RateLimitingInterface, *kubecli.Controller) {
queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())
dispatch := NewVMHandlerDispatch(domainManager, recorder, &restClient, clientset, host)
indexer, informer := kubecli.NewController(lw, queue, &v1.VM{}, dispatch)
return indexer, queue, informer
}
func NewVMHandlerDispatch(domainManager virtwrap.DomainManager, recorder record.EventRecorder, restClient *rest.RESTClient, clientset *kubernetes.Clientset, host string) kubecli.ControllerDispatch {
return &VMHandlerDispatch{
domainManager: domainManager,
recorder: recorder,
restClient: *restClient,
clientset: clientset,
host: host,
}
}
type VMHandlerDispatch struct {
domainManager virtwrap.DomainManager
recorder record.EventRecorder
restClient rest.RESTClient
clientset *kubernetes.Clientset
host string
}
func (d *VMHandlerDispatch) Execute(store cache.Store, queue workqueue.RateLimitingInterface, key interface{}) {
// Fetch the latest Vm state from cache
obj, exists, err := store.GetByKey(key.(string))
if err != nil {
queue.AddRateLimited(key)
return
}
// Retrieve the VM
var vm *v1.VM
if !exists {
_, name, err := cache.SplitMetaNamespaceKey(key.(string))
if err != nil {
// TODO do something more smart here
queue.AddRateLimited(key)
return
}
vm = v1.NewVMReferenceFromName(name)
// If we don't have the VM in the cache, it could be that it is currently migrating to us
result := d.restClient.Get().Name(vm.GetObjectMeta().GetName()).Resource("vms").Namespace(kubeapi.NamespaceDefault).Do()
if result.Error() == nil {
// So the VM still seems to exist
fetchedVM, err := result.Get()
if err != nil {
// Since there was no fetch error, this should have worked, let's back off
queue.AddRateLimited(key)
return
}
if fetchedVM.(*v1.VM).Status.MigrationNodeName == d.host {
// OK, this VM is migrating to us, don't interrupt it
queue.Forget(key)
return
}
} else if result.Error().(*errors.StatusError).Status().Code != int32(http.StatusNotFound) {
// Something went wrong, let's try again later
queue.AddRateLimited(key)
return
}
// The VM is deleted on the cluster, let's go on with the deletion on the host
} else {
vm = obj.(*v1.VM)
}
logging.DefaultLogger().V(3).Info().Object(vm).Msg("Processing VM update.")
// Process the VM
if !exists {
// Since the VM was not in the cache, we delete it
err = d.domainManager.KillVM(vm)
} else if isWorthSyncing(vm) {
// Synchronize the VM state
vm, err = MapPersistentVolumes(vm, d.clientset.CoreV1().RESTClient(), kubeapi.NamespaceDefault)
if err == nil {
// TODO check if found VM has the same UID like the domain, if not, delete the Domain first
// Only sync if the VM is not marked as migrating. Everything except shutting down the VM is not permitted when it is migrating.
// TODO MigrationNodeName should be a pointer
if vm.Status.MigrationNodeName == "" {
err = d.domainManager.SyncVM(vm)
} else {
queue.Forget(key)
return
}
}
// Update VM status to running
if err == nil && vm.Status.Phase != v1.Running {
obj, err = kubeapi.Scheme.Copy(vm)
if err == nil {
vm = obj.(*v1.VM)
vm.Status.Phase = v1.Running
err = d.restClient.Put().Resource("vms").Body(vm).
Name(vm.ObjectMeta.Name).Namespace(kubeapi.NamespaceDefault).Do().Error()
}
}
}
if err != nil {
// Something went wrong, reenqueue the item with a delay
logging.DefaultLogger().Error().Object(vm).Reason(err).Msg("Synchronizing the VM failed.")
d.recorder.Event(vm, kubev1.EventTypeWarning, v1.SyncFailed.String(), err.Error())
queue.AddRateLimited(key)
return
}
logging.DefaultLogger().V(3).Info().Object(vm).Msg("Synchronizing the VM succeeded.")
queue.Forget(key)
return
}
// Almost everything in the VM object maps exactly to its domain counterpart
// One exception is persistent volume claims. This function looks up each PV
// and inserts a corrected disk entry into the VM's device map.
func MapPersistentVolumes(vm *v1.VM, restClient cache.Getter, namespace string) (*v1.VM, error) {
vmCopy := &v1.VM{}
model.Copy(vmCopy, vm)
for idx, disk := range vmCopy.Spec.Domain.Devices.Disks {
if disk.Type == "PersistentVolumeClaim" {
logging.DefaultLogger().V(3).Info().Object(vm).Msgf("Mapping PersistentVolumeClaim: %s", disk.Source.Name)
// Look up existing persistent volume
obj, err := restClient.Get().Namespace(namespace).Resource("persistentvolumeclaims").Name(disk.Source.Name).Do().Get()
if err != nil {
logging.DefaultLogger().Error().Reason(err).Msg("unable to look up persistent volume claim")
return vm, fmt.Errorf("unable to look up persistent volume claim: %v", err)
}
pvc := obj.(*kubev1.PersistentVolumeClaim)
if pvc.Status.Phase != kubev1.ClaimBound {
logging.DefaultLogger().Error().Msg("attempted use of unbound persistent volume")
return vm, fmt.Errorf("attempted use of unbound persistent volume claim: %s", pvc.Name)
}
// Look up the PersistentVolume this PVC is bound to
// Note: This call is not namespaced!
obj, err = restClient.Get().Resource("persistentvolumes").Name(pvc.Spec.VolumeName).Do().Get()
if err != nil {
logging.DefaultLogger().Error().Reason(err).Msg("unable to access persistent volume record")
return vm, fmt.Errorf("unable to access persistent volume record: %v", err)
}
pv := obj.(*kubev1.PersistentVolume)
if pv.Spec.ISCSI != nil {
logging.DefaultLogger().Object(vm).Info().Msg("Mapping iSCSI PVC")
newDisk := v1.Disk{}
newDisk.Type = "network"
newDisk.Device = "disk"
newDisk.Target = disk.Target
newDisk.Driver = new(v1.DiskDriver)
newDisk.Driver.Type = "raw"
newDisk.Driver.Name = "qemu"
newDisk.Source.Name = fmt.Sprintf("%s/%d", pv.Spec.ISCSI.IQN, pv.Spec.ISCSI.Lun)
newDisk.Source.Protocol = "iscsi"
hostPort := strings.Split(pv.Spec.ISCSI.TargetPortal, ":")
newDisk.Source.Host = &v1.DiskSourceHost{}
newDisk.Source.Host.Name = hostPort[0]
if len(hostPort) > 1 {
newDisk.Source.Host.Port = hostPort[1]
}
vmCopy.Spec.Domain.Devices.Disks[idx] = newDisk
} else {
logging.DefaultLogger().Object(vm).Error().Msg(fmt.Sprintf("Referenced PV %v is backed by an unsupported storage type", pv))
}
}
}
return vmCopy, nil
}
func isWorthSyncing(vm *v1.VM) bool {
return vm.Status.Phase != v1.Succeeded && vm.Status.Phase != v1.Failed
}
| {
"content_hash": "d83b9073c31ee359a101716aae447c6b",
"timestamp": "",
"source": "github",
"line_count": 212,
"max_line_length": 257,
"avg_line_length": 34.37735849056604,
"alnum_prop": 0.7041712403951701,
"repo_name": "sungwonh/kubevirt",
"id": "6243a9b362a85017933c5986d2e47df481c888b6",
"size": "7288",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/virt-handler/vm.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "373079"
},
{
"name": "Makefile",
"bytes": "842"
},
{
"name": "Shell",
"bytes": "23049"
}
],
"symlink_target": ""
} |
require 'spec_helper'
require 'examples/auto_option'
RSpec.describe 'auto_option.rb' do
suppress_puts
it { expect(AutoOptionCommand.parse('-e Lorem').params).to eq(echo: 'Lorem') }
it { expect(AutoOptionCommand.parse('--eko Lorem').params).to eq(echo: 'Lorem') }
it { expect(AutoOptionCommand.parse('--eko="Lorem ipsum"').params).to eq(echo: 'Lorem ipsum') }
it { expect { AutoOptionCommand.parse('--echo Value').params }.to raise_error(Clin::HelpError) }
end
| {
"content_hash": "5f342ecd679b2d662810458ad6f8e199",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 98,
"avg_line_length": 42.90909090909091,
"alnum_prop": 0.7055084745762712,
"repo_name": "timcolonel/clin",
"id": "ae6073c1144c762b7feccf63c52c927593d19a2f",
"size": "472",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/examples/auto_option_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "147377"
}
],
"symlink_target": ""
} |
<?php
/**
* Message translations.
*
* This file is automatically generated by 'yii message/extract' command.
* It contains the localizable messages extracted from source code.
* You may modify this file by translating the extracted messages.
*
* Each array element represents the translation (value) of a message (key).
* If the value is empty, the message is considered as not translated.
* Messages that no longer need translation will have their translations
* enclosed between a pair of '@@' marks.
*
* Message string can be used with plural forms format. Check i18n section
* of the guide for details.
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
return [
'Become this user' => 'السيطرة على حساب هذا العضو',
'Delete' => 'حذف',
'Disabled' => 'غير مفعل',
'Enabled' => 'مفعّل',
'Save' => 'حفظ',
'Unapproved' => 'لم تتم الموافقة عليه',
'User not found!' => 'لم يتم إيجااد العضو!',
'You cannot delete yourself!' => 'لا تستطيع حذف نفسك!',
];
| {
"content_hash": "5a9384845c522312643861d36159e444",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 76,
"avg_line_length": 35.714285714285715,
"alnum_prop": 0.68,
"repo_name": "LeonidLyalin/vova",
"id": "e215721948366b8dc5b58c586da61921ce98c7fb",
"size": "1088",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/humhub/protected/humhub/modules/admin/messages/ar/controllers_UserController.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "227"
},
{
"name": "Batchfile",
"bytes": "3096"
},
{
"name": "CSS",
"bytes": "824207"
},
{
"name": "HTML",
"bytes": "25309"
},
{
"name": "JavaScript",
"bytes": "1284304"
},
{
"name": "PHP",
"bytes": "8757729"
},
{
"name": "Ruby",
"bytes": "375"
},
{
"name": "Shell",
"bytes": "3256"
}
],
"symlink_target": ""
} |
<?php
namespace Proxies\__CG__\CMS\Entity;
/**
* DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR
*/
class Article extends \CMS\Entity\Article implements \Doctrine\ORM\Proxy\Proxy
{
/**
* @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with
* three parameters, being respectively the proxy object to be initialized, the method that triggered the
* initialization process and an array of ordered parameters that were passed to that method.
*
* @see \Doctrine\Common\Persistence\Proxy::__setInitializer
*/
public $__initializer__;
/**
* @var \Closure the callback responsible of loading properties that need to be copied in the cloned object
*
* @see \Doctrine\Common\Persistence\Proxy::__setCloner
*/
public $__cloner__;
/**
* @var boolean flag indicating if this object was already initialized
*
* @see \Doctrine\Common\Persistence\Proxy::__isInitialized
*/
public $__isInitialized__ = false;
/**
* @var array properties to be lazy loaded, with keys being the property
* names and values being their default values
*
* @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties
*/
public static $lazyPropertiesDefaults = [];
/**
* @param \Closure $initializer
* @param \Closure $cloner
*/
public function __construct($initializer = null, $cloner = null)
{
$this->__initializer__ = $initializer;
$this->__cloner__ = $cloner;
}
/**
*
* @return array
*/
public function __sleep()
{
if ($this->__isInitialized__) {
return ['__isInitialized__', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'id', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'name', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'slug', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'content', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'author', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'createdDate', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'lastEditor', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'editTime', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'lang', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'routes'];
}
return ['__isInitialized__', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'id', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'name', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'slug', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'content', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'author', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'createdDate', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'lastEditor', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'editTime', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'lang', '' . "\0" . 'CMS\\Entity\\Article' . "\0" . 'routes'];
}
/**
*
*/
public function __wakeup()
{
if ( ! $this->__isInitialized__) {
$this->__initializer__ = function (Article $proxy) {
$proxy->__setInitializer(null);
$proxy->__setCloner(null);
$existingProperties = get_object_vars($proxy);
foreach ($proxy->__getLazyProperties() as $property => $defaultValue) {
if ( ! array_key_exists($property, $existingProperties)) {
$proxy->$property = $defaultValue;
}
}
};
}
}
/**
*
*/
public function __clone()
{
$this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', []);
}
/**
* Forces initialization of the proxy
*/
public function __load()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, '__load', []);
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __isInitialized()
{
return $this->__isInitialized__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitialized($initialized)
{
$this->__isInitialized__ = $initialized;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setInitializer(\Closure $initializer = null)
{
$this->__initializer__ = $initializer;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __getInitializer()
{
return $this->__initializer__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
*/
public function __setCloner(\Closure $cloner = null)
{
$this->__cloner__ = $cloner;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific cloning logic
*/
public function __getCloner()
{
return $this->__cloner__;
}
/**
* {@inheritDoc}
* @internal generated method: use only when explicitly handling proxy specific loading logic
* @static
*/
public function __getLazyProperties()
{
return self::$lazyPropertiesDefaults;
}
/**
* {@inheritDoc}
*/
public function getRoutes()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getRoutes', []);
return parent::getRoutes();
}
/**
* {@inheritDoc}
*/
public function setRoutes($routes)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setRoutes', [$routes]);
return parent::setRoutes($routes);
}
/**
* {@inheritDoc}
*/
public function addRoute($route)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'addRoute', [$route]);
return parent::addRoute($route);
}
/**
* {@inheritDoc}
*/
public function removeRoute($route)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'removeRoute', [$route]);
return parent::removeRoute($route);
}
/**
* {@inheritDoc}
*/
public function getId()
{
if ($this->__isInitialized__ === false) {
return (int) parent::getId();
}
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', []);
return parent::getId();
}
/**
* {@inheritDoc}
*/
public function setName($name)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setName', [$name]);
return parent::setName($name);
}
/**
* {@inheritDoc}
*/
public function getName()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getName', []);
return parent::getName();
}
/**
* {@inheritDoc}
*/
public function setSlug($slug)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setSlug', [$slug]);
return parent::setSlug($slug);
}
/**
* {@inheritDoc}
*/
public function getSlug()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getSlug', []);
return parent::getSlug();
}
/**
* {@inheritDoc}
*/
public function setContent($content)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setContent', [$content]);
return parent::setContent($content);
}
/**
* {@inheritDoc}
*/
public function getContent()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getContent', []);
return parent::getContent();
}
/**
* {@inheritDoc}
*/
public function setAuthor($author)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setAuthor', [$author]);
return parent::setAuthor($author);
}
/**
* {@inheritDoc}
*/
public function getAuthor()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getAuthor', []);
return parent::getAuthor();
}
/**
* {@inheritDoc}
*/
public function setCreatedDate($createdDate)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setCreatedDate', [$createdDate]);
return parent::setCreatedDate($createdDate);
}
/**
* {@inheritDoc}
*/
public function getCreatedDate()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getCreatedDate', []);
return parent::getCreatedDate();
}
/**
* {@inheritDoc}
*/
public function setLastEditor($lastEditor)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setLastEditor', [$lastEditor]);
return parent::setLastEditor($lastEditor);
}
/**
* {@inheritDoc}
*/
public function getLastEditor()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getLastEditor', []);
return parent::getLastEditor();
}
/**
* {@inheritDoc}
*/
public function setEditTime($editTime)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setEditTime', [$editTime]);
return parent::setEditTime($editTime);
}
/**
* {@inheritDoc}
*/
public function getEditTime()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getEditTime', []);
return parent::getEditTime();
}
/**
* {@inheritDoc}
*/
public function getLang()
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'getLang', []);
return parent::getLang();
}
/**
* {@inheritDoc}
*/
public function setLang($lang)
{
$this->__initializer__ && $this->__initializer__->__invoke($this, 'setLang', [$lang]);
return parent::setLang($lang);
}
}
| {
"content_hash": "f7d26db1207b7bd9b68abeb0dc1d008e",
"timestamp": "",
"source": "github",
"line_count": 411,
"max_line_length": 583,
"avg_line_length": 25.287104622871045,
"alnum_prop": 0.5280477244299048,
"repo_name": "MyRayTech/CMSFul",
"id": "b1d9e6d6c1011459c876527a0239d2e998e8a38d",
"size": "10393",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "etc/cache/prod/doctrine/orm/Proxies/__CG__CMSEntityArticle.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "777"
},
{
"name": "CSS",
"bytes": "2929801"
},
{
"name": "HTML",
"bytes": "54458"
},
{
"name": "JavaScript",
"bytes": "4793501"
},
{
"name": "PHP",
"bytes": "280308"
},
{
"name": "Shell",
"bytes": "4109"
},
{
"name": "Vue",
"bytes": "35669"
}
],
"symlink_target": ""
} |
* Allow user to remove featured image (#186)
* Use featured image for social sharing thumbnail if there is one ([#192](https://github.com/Differential/meteor-blog/issues/192))
* Add config to suppress loading CDN font-awesome ([#189](https://github.com/Differential/meteor-blog/issues/189))
* Fix crash caused by empty blog posts
* Fix `shareit` issue with Twitter cards ([#193](https://github.com/Differential/meteor-blog/pull/193))
### v0.7.0
* Upgrade `vsivsi:file-collection` to 1.1.0 ([#171](https://github.com/Differential/meteor-blog/issues/171) and [#180](https://github.com/Differential/meteor-blog/issues/180))
### v0.6.4
* Upgrade `medium-editor`, `medium-editor-insert-plugin` libs to 1.0 versions ([#164](https://github.com/Differential/meteor-blog/issues/164))
* Add Swift syntax highlighting ([#156](https://github.com/Differential/meteor-blog/issues/156))
* Allow user to upload a featured image for a post! ([#161](https://github.com/Differential/meteor-blog/pull/161))
* Optionally make drafts inaccessible to public via `Blog.config` ([#163](https://github.com/Differential/meteor-blog/pull/163))
* Fix bugs related to `side-comments.js` ([#157](https://github.com/Differential/meteor-blog/pull/157) and [#170](https://github.com/Differential/meteor-blog/pull/170))
* Upgrade `shareit` package and move to `lovetostrike:shareit` ([#155](https://github.com/Differential/meteor-blog/pull/155) and [#175](https://github.com/Differential/meteor-blog/pull/175))
### v0.6.3
* Fix pagination
### v0.6.2
* Allow user to upload blog images to S3 ([#141](https://github.com/Differential/meteor-blog/pull/141))
* Add 'Edit this Post' link to blog post ([#146](https://github.com/Differential/meteor-blog/pull/146))
* Make blog more SEO-friendly ([#137](https://github.com/Differential/meteor-blog/pull/137))
* Fix many bugs related to medium-editor ([#150](https://github.com/Differential/meteor-blog/pull/150), [#145](https://github.com/Differential/meteor-blog/pull/145), [#142](https://github.com/Differential/meteor-blog/pull/142))
* Fix bugs related to `side-comments.js` ([#143](https://github.com/Differential/meteor-blog/pull/143) and [#144](https://github.com/Differential/meteor-blog/pull/144))
* Upgrade `medium-editor`, `medium-editor-insert-plugin` libs
### v0.6.1
* Upgrade `fast-render` to fix DDP-related issues.
* Enable IR's `dataNotFound` hook only for blog post route, not globally ([#132](https://github.com/Differential/meteor-blog/issues/132))
* Fix bug where `Add Blog Post` button only edits first post ([#118](https://github.com/Differential/meteor-blog/issues/118))
### v0.6.0
_NOTE: `0.6.0` is probably only compatible with Meteor `1.0` and higher._
* Make compatible with Meteor `1.0`
* Fix bugs [#109](https://github.com/Differential/meteor-blog/issues/109), [#120](https://github.com/Differential/meteor-blog/issues/120), [#121](https://github.com/Differential/meteor-blog/issues/121), [#119](https://github.com/Differential/meteor-blog/issues/119).
### v0.5.10
* Fix lots of issues with medium editor and code blocks
* Fix bug where post body was showing up blank or wrong in editor
### v0.5.9
* Autosave blog post after 5 seconds of inactivity ([#90](https://github.com/Differential/meteor-blog/issues/90))
* Add [`fast-render`](https://atmospherejs.com/meteorhacks/fast-render) package by default ([#110](https://github.com/Differential/meteor-blog/pull/110))
* Use [`subs-manager`](https://atmospherejs.com/meteorhacks/subs-manager) to improve subscription performance ([#110](https://github.com/Differential/meteor-blog/pull/110))
* Fix bugs [#106](https://github.com/Differential/meteor-blog/pull/106), [#109](https://github.com/Differential/meteor-blog/issues/109)
* Upgrade `medium-editor`, `medium-editor-insert-plugin` libs
### v0.5.7
* Fix blank body bug (`0.5.5`), copy-and-paste bug (`0.5.6`) for good?
### v0.5.6
* Fix copy-and-paste bug broken in `0.5.5`
* Add prefix to `load-more` pager class to avoid potential conflicts ([#99](https://github.com/Differential/meteor-blog/issues/99))
* Fix CSS on mobile screens ([#98](https://github.com/Differential/meteor-blog/pull/98))
* Fix 404/notFound templates after upgrade
* Redirect user back to blog index upon logout ([#95](https://github.com/Differential/meteor-blog/pull/95))
### v0.5.5
* Fix bug where post body was not showing up in editor
### v0.5.4
_NOTE: `0.5.4` is only compatible with Meteor `0.9.0` and higher._
* Make compatible with Meteor `0.9.0`
### v0.5.3
* Fix bugs ([#81](https://github.com/Differential/meteor-blog/issues/81), [#78](https://github.com/Differential/meteor-blog/issues/78), [#85](https://github.com/Differential/meteor-blog/issues/85))
* Improve UX where saving tags on posts was unclear
* Add template helper to display latest posts
* Upgrade `medium-editor`, `medium-editor-insert-plugin` libs
### v0.5.2
* Support syntax highlighting ([#76](https://github.com/Differential/meteor-blog/pull/76))
* Add `author` role ([#72](https://github.com/Differential/meteor-blog/issues/72))
* Remove social sharing code and add `shareit` package as a dependency
* Refactor template overriding code to use `UI.dynamic`
### v0.5.0
_NOTE: `0.5.0` is only compatible with Meteor `0.8.2` and higher. Also, the `0.4.0` migration is taken out, so if you are running `0.3.0` of this package, you must upgrade to `0.4.0` first and then upgrade to `0.5.0`._
* Changes to blog editor
* Allow basic image uploading and storage in _gridFS_ ([#57](https://github.com/Differential/meteor-blog/issues/57))
* Add HTML mode to blog editor ([#61](https://github.com/Differential/meteor-blog/pull/61))
* Add tag autocomplete to blog editor ([#62](https://github.com/Differential/meteor-blog/pull/62))
* Add commenting capabilities
* Allow user to configure a [DISQUS](http://disqus.com) ID to enable DISQUS comments
* Add [SideComments.js](http://aroc.github.io/side-comments-demo/) (experimental!) ([#60](https://github.com/Differential/meteor-blog/pull/60))
* Allow user to provide custom `notFoundTemplate` ([#65](https://github.com/Differential/meteor-blog/pull/65))
### v0.4.4
* Allow user to override blog excerpt function ([#52](https://github.com/Differential/meteor-blog/pull/52))
* Add minor performance improvements
* Fix minor bugs
### v0.4.3
* Fix bug where LESS files were imported twice ([#48](https://github.com/Differential/meteor-blog/pull/48))
* Add support for `meteor-roles` groups
### v0.4.2
* Fix bugs with pagination ([#44](https://github.com/Differential/meteor-blog/issues/44)), author profile, and T9n.
### v0.4.0
_NOTE: In `0.4.0`, blog contents are stored as HTML, not markdown. There is an automatic migration step if you upgrade, but you may want to backup your blog posts first._
* Complete re-write of blog administrative interface
* Replace Ace Editor with Medium Editor
* Replace administrative blog list with fancy table
* Add Google+ authorship link to blog posts
### v0.3.0
_NOTE: `0.3.0` is not guaranteed to work with Meteor `0.7.x` and below. If you are using an older version of Meteor, use Blog `0.2.13`._
* Meteor `0.8.x` compatibility
### v0.2.12
* Add basic tagging of blog posts
* Save on publication data ([#33](https://github.com/Differential/meteor-blog/issues/33))
* Some preparations for Meteor Blaze
### v0.2.11
* Remove `parsleyjs` as a dependency
* Maintain package JS when user overrides view templates ([#28](https://github.com/Differential/meteor-blog/issues/28))
* Add keyboard shortcut to toggle `Preview` mode
* Ensure blog post slugs are unique
* Allow user to override admin templates ([#31](https://github.com/Differential/meteor-blog/issues/31))
* Tweak default CSS for blog list padding and blog post image margins
### v0.2.8
* Unnecessary code cleanup
* Remove hard dependency on moment.js version
* Rename method to minimize conflict
* Fix blog author in model
* Improve RSS
### v0.2.7
* Update to iron-router 0.6.2
* Fixed a few bugs (issues [#16](https://github.com/Differential/meteor-blog/issues/16) and [#17](https://github.com/Differential/meteor-blog/issues/17))
* Add server-side RSS feed
### v0.2.6
_NOTE: If you were using the `excerpt` helper before (`data.excerpt()`), it is now a field (`data.excerpt`)._
* Publish less data to blog index.
* Replace EpicEditor with Ace Editor
* Add simple 'Load More' pagination
* Turn admin roles off by default
### v0.2.5
* Support for fast-render, if your app is using it
* Ensure there is an index on the `slug` field for posts
* Hide draft posts from crawlers
* Improve FB share link
* Make default theme more narrow
* Require `blogAdmin` role to be allowed to admin posts
### v0.2.4
* Remove 'urlify2' package (was crashing phantomjs in production)
### v0.2.3
* Take out Bootstrap 3 files by default (user must add manually)
* Fix bug getting blog post thumbnail
* Publish only blog authors
### v0.2.2
* Fix bug where every blog author was 'Mystery author' on blog index page
* Fix sorting of blogs on index and admin pages
* Fix flash status message
* Rename 'user' model to 'author' (to help avoid conflicts)
### v0.2.1
* Rename 404 template
* Allow user to override package templates
* Add experimental handlebar helpers for blog content
* Fix a few bugs related to joining blog to author
### v0.2.0
_NOTE: `iron-router` 0.6.x is not backwards-compatible with earlier versions_
* Upgrade iron-router to 0.6.1 and minimongoid to 0.8.3
* Add 404 template
* Rename some files/folders to match http://github.com/Differential/meteor-boilerplate
### v0.1.0
* Initial release
| {
"content_hash": "2b4392ac3c0d515cc88606757f15afa8",
"timestamp": "",
"source": "github",
"line_count": 219,
"max_line_length": 266,
"avg_line_length": 43.76255707762557,
"alnum_prop": 0.7303839732888147,
"repo_name": "dj0nes/meteor-blog",
"id": "3284d8bae12b57a8a59edc0b261b17db57217d17",
"size": "9610",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "CHANGES.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "16489"
},
{
"name": "CoffeeScript",
"bytes": "37630"
},
{
"name": "HTML",
"bytes": "10154"
},
{
"name": "JavaScript",
"bytes": "331923"
}
],
"symlink_target": ""
} |
title: "Hyperband"
sub_link: "optimization-engine/hyperband"
code_link: " core/polyaxon/polyflow/matrix/hyperband.py"
meta_title: "Polyaxon Optimization Engine - Hyperband Specification - Polyaxon References"
meta_description: "Hyperband is a relatively new method for tuning iterative algorithms. It performs random sampling and attempts to gain an edge by using time spent optimizing in the best way. The algorithm tries a large number of random configurations/experiments, then decides which configurations to keep based on their progress."
visibility: public
status: published
tags:
- reference
- polyaxon
- experimentation
- hyperparameter-optimization
sidebar: "automation"
---
<blockquote class="commercial">This is part of our commercial offering.</blockquote>

{{autogenerated}}
| {
"content_hash": "13d49e2b3d9f63dc1ec117303419b4ad",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 334,
"avg_line_length": 44.2,
"alnum_prop": 0.7895927601809954,
"repo_name": "polyaxon/polyaxon",
"id": "14b55baccf91868180ddfed10c41d67c08441f38",
"size": "888",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "site/templates/docs/automation/optimization-engine/hyperband.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "1989"
},
{
"name": "Python",
"bytes": "5201898"
},
{
"name": "Shell",
"bytes": "1565"
}
],
"symlink_target": ""
} |
package com.example.template4fx.control.dialog;
import com.example.template4fx.Keys;
import com.example.template4fx.fx.DialogEvent;
import com.example.template4fx.skin.ValuePickerSkin;
import javafx.application.Platform;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.scene.Node;
import javafx.scene.control.Skin;
import javafx.scene.input.KeyEvent;
public class ValuePicker<T>
extends AbstractDialog
{
private final ObjectProperty<T> selected = new SimpleObjectProperty<>();
private final FilteredList<T> items;
private final Node source;
public ValuePicker( Node source, ObservableList<T> items )
{
super( "", null );
getStyleClass().add( "value-picker" );
this.source = source;
this.items = new FilteredList<>( items, p -> true );
initialize();
}
@Override
public void handleKeyEvent( KeyEvent event )
{
if ( Keys.ESCAPE.match( event ) )
{
event.consume();
cancel();
}
else if ( Keys.ENTER.match( event ) && selected.get() != null )
{
event.consume();
success();
}
}
private void initialize()
{
filter.addListener(
( observable, oldValue, newValue ) ->
items.setPredicate( item -> newValue == null || newValue.isEmpty() || matches( item, newValue ) ) );
selected.set( items.stream().findFirst().orElse( null ) );
}
private boolean matches( T item, String filter )
{
return item.toString().toLowerCase().startsWith( filter.toLowerCase() );
}
public void success()
{
fireEvent( DialogEvent.successEvent() );
close();
}
public void cancel()
{
fireEvent( DialogEvent.cancelEvent() );
close();
}
private void close()
{
setClosed( true );
Platform.runLater( source::requestFocus );
}
@Override
protected Skin<?> createDefaultSkin()
{
return new ValuePickerSkin<>( this );
}
@Override
public String getUserAgentStylesheet()
{
return getUserAgentStylesheet( ValuePicker.class, "ValuePicker.css" );
}
private final StringProperty filter = new SimpleStringProperty();
public String getFilter()
{
return filter.get();
}
public StringProperty filterProperty()
{
return filter;
}
public void setFilter( String filter )
{
this.filter.set( filter );
}
private final StringProperty promptText = new SimpleStringProperty();
public String getPromptText()
{
return promptText.get();
}
public StringProperty promptTextProperty()
{
return promptText;
}
public void setPromptText( String promptText )
{
this.promptText.set( promptText );
}
public T getSelected()
{
return selected.get();
}
public ObjectProperty<T> selectedProperty()
{
return selected;
}
public void setSelected( T selected )
{
this.selected.set( selected );
}
public ObservableList<T> getItems()
{
return items;
}
}
| {
"content_hash": "0ed66e2278d2db9d9b62a401bedb94b8",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 116,
"avg_line_length": 23.27027027027027,
"alnum_prop": 0.6251451800232288,
"repo_name": "oscar-ahlen/template4fx",
"id": "940fb62e6f22bf6ede51af6180204673f05a637c",
"size": "3444",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/java/com/example/template4fx/control/dialog/ValuePicker.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "28249"
},
{
"name": "Java",
"bytes": "81306"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace spec\Sylius\Component\Core\Provider;
use Doctrine\Common\Collections\ArrayCollection;
use PhpSpec\ObjectBehavior;
use Sylius\Component\Core\Calculator\ProductVariantPriceCalculatorInterface;
use Sylius\Component\Core\Model\ChannelInterface;
use Sylius\Component\Core\Model\ProductInterface;
use Sylius\Component\Core\Model\ProductVariantInterface;
use Sylius\Component\Core\Provider\ProductVariantsPricesProviderInterface;
use Sylius\Component\Product\Model\ProductOptionValueInterface;
/**
* @author Mateusz Zalewski <mateusz.zalewski@lakion.com>
*/
final class ProductVariantsPricesProviderSpec extends ObjectBehavior
{
function let(ProductVariantPriceCalculatorInterface $productVariantPriceCalculator): void
{
$this->beConstructedWith($productVariantPriceCalculator);
}
function it_implements_a_variants_prices_provider_interface(): void
{
$this->shouldImplement(ProductVariantsPricesProviderInterface::class);
}
function it_provides_array_containing_product_variant_options_map_with_corresponding_price(
ChannelInterface $channel,
ProductInterface $tShirt,
ProductOptionValueInterface $black,
ProductOptionValueInterface $large,
ProductOptionValueInterface $small,
ProductOptionValueInterface $white,
ProductVariantInterface $blackLargeTShirt,
ProductVariantInterface $blackSmallTShirt,
ProductVariantInterface $whiteLargeTShirt,
ProductVariantInterface $whiteSmallTShirt,
ProductVariantPriceCalculatorInterface $productVariantPriceCalculator
): void {
$tShirt->getVariants()->willReturn(new ArrayCollection([
$blackSmallTShirt->getWrappedObject(),
$whiteSmallTShirt->getWrappedObject(),
$blackLargeTShirt->getWrappedObject(),
$whiteLargeTShirt->getWrappedObject(),
]));
$blackSmallTShirt->getOptionValues()->willReturn(
new ArrayCollection([$black->getWrappedObject(), $small->getWrappedObject()])
);
$whiteSmallTShirt->getOptionValues()->willReturn(
new ArrayCollection([$white->getWrappedObject(), $small->getWrappedObject()])
);
$blackLargeTShirt->getOptionValues()->willReturn(
new ArrayCollection([$black->getWrappedObject(), $large->getWrappedObject()])
);
$whiteLargeTShirt->getOptionValues()->willReturn(
new ArrayCollection([$white->getWrappedObject(), $large->getWrappedObject()])
);
$productVariantPriceCalculator->calculate($blackSmallTShirt, ['channel' => $channel])->willReturn(1000);
$productVariantPriceCalculator->calculate($whiteSmallTShirt, ['channel' => $channel])->willReturn(1500);
$productVariantPriceCalculator->calculate($blackLargeTShirt, ['channel' => $channel])->willReturn(2000);
$productVariantPriceCalculator->calculate($whiteLargeTShirt, ['channel' => $channel])->willReturn(2500);
$black->getOptionCode()->willReturn('t_shirt_color');
$white->getOptionCode()->willReturn('t_shirt_color');
$small->getOptionCode()->willReturn('t_shirt_size');
$large->getOptionCode()->willReturn('t_shirt_size');
$black->getCode()->willReturn('black');
$white->getCode()->willReturn('white');
$small->getCode()->willReturn('small');
$large->getCode()->willReturn('large');
$this->provideVariantsPrices($tShirt, $channel)->shouldReturn([
[
't_shirt_color' => 'black',
't_shirt_size' => 'small',
'value' => 1000,
],
[
't_shirt_color' => 'white',
't_shirt_size' => 'small',
'value' => 1500,
],
[
't_shirt_color' => 'black',
't_shirt_size' => 'large',
'value' => 2000,
],
[
't_shirt_color' => 'white',
't_shirt_size' => 'large',
'value' => 2500,
],
]);
}
}
| {
"content_hash": "272166598b254914540316fbb200c0ca",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 112,
"avg_line_length": 39.86538461538461,
"alnum_prop": 0.6452001929570671,
"repo_name": "ylastapis/Sylius",
"id": "1004fe002a592d145dfc30d68eac8213f452ae02",
"size": "4357",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Sylius/Component/Core/spec/Provider/ProductVariantsPricesProviderSpec.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "601"
},
{
"name": "CSS",
"bytes": "2192"
},
{
"name": "Gherkin",
"bytes": "813593"
},
{
"name": "HTML",
"bytes": "305193"
},
{
"name": "JavaScript",
"bytes": "72306"
},
{
"name": "PHP",
"bytes": "6802898"
},
{
"name": "Shell",
"bytes": "29158"
}
],
"symlink_target": ""
} |
package redis.seek;
import java.util.List;
public class Result {
private long count;
private List<String> ids;
private double time;
public double getTime() {
return time;
}
public long getTotalCount() {
return count;
}
public List<String> getIds() {
return ids;
}
public Result(long count, List<String> ids, double time) {
super();
this.count = count;
this.ids = ids;
this.time = time;
}
} | {
"content_hash": "38744a54c4040cf4b520dcac4482f17b",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 62,
"avg_line_length": 17.678571428571427,
"alnum_prop": 0.5717171717171717,
"repo_name": "xetorthio/seek",
"id": "036c56735449b0b4dc05b68470f792ed955fd33e",
"size": "495",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/redis/seek/Result.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "36332"
}
],
"symlink_target": ""
} |
import abc
import time
import copy
import re
import cwbot.util.DebugThreading as threading
from cwbot.util.tryRequest import tryRequest
from cwbot.kolextra.request.ClanRaidLogRequest import ClanRaidLogRequest
from cwbot.managers.MultiChannelManager import MultiChannelManager
from cwbot.database import database
class LogDict(dict):
""" A dict with supressed __str__ and __repr__ to prevent clogging up
the CLI """
def __str__(self):
return "{Event Log}"
def __repr__(self):
return "{Event Log}"
class BaseClanDungeonChannelManager(MultiChannelManager):
""" Subclass of MultiChannelManager that incorporates Dungeon chat
and Raid Logs. Subclasses of this manager should specialize these functions
for individual channel. Modules under this manager are initialized with
event data from the clan raid log and also receive periodic updates.
Dungeon chat is separated and passed to the process_dungeon extended call,
and log data is passed there as well. Periodic log updates are processed
as well.
"""
capabilities = set(['chat', 'inventory', 'admin', 'hobopolis', 'dread'])
_csvFile = None # override this in child classes
__initialRaidlog = None
__raidlogDownloadLock = threading.RLock()
_lastChatNum = None
delay = 300
def __init__(self, parent, identity, iData, config):
""" Initialize the BaseClanDungeonChannelManager """
self.__eventLock = threading.RLock() # lock for reading events
# LOCK THIS BEFORE
# LOCKING self._syncLock
self.__initialized = False
self.__lastEvents = None
self._lastEventCheck = 0
self._logEntryDb = []
printDbLoad = False
if self._csvFile is not None:
self._logEntryDb = database.csvDatabase(self._csvFile)
printDbLoad = True
with self.__raidlogDownloadLock:
if self.__initialRaidlog is None:
rl = ClanRaidLogRequest(iData.session)
result = tryRequest(rl,
numTries=5,
initialDelay=0.5,
scaleFactor=2)
self.__initialRaidlog = result
self.__lastEvents = self.__initialRaidlog
super(BaseClanDungeonChannelManager, self).__init__(parent,
identity,
iData,
config)
if printDbLoad:
self._log.info("Loaded {} entries of data from {}."
.format(len(self._logEntryDb), self._csvFile))
self.__initialized = True
def _configure(self, config):
""" Additional configuration for the log_check_interval option """
super(BaseClanDungeonChannelManager, self)._configure(config)
try:
self.delay = min(self.delay,
int(config.setdefault('log_check_interval', 15)))
except ValueError:
raise Exception("Error in module config: "
"(BaseClanDungeonChannelManager) "
"log_check_interval must be integral")
def _moduleInitData(self):
""" The initData here is the last read raid log events. """
d = self._filterEvents(self.lastEvents)
d['event-db'] = self._logEntryDb
return d
@property
def lastEvents(self):
""" get the last-read events """
with self.__eventLock:
return copy.deepcopy(self.__lastEvents)
@lastEvents.setter
def lastEvents(self, val):
with self.__eventLock:
self.__lastEvents = copy.deepcopy(val)
@lastEvents.deleter
def lastEvents(self):
with self.__eventLock:
del self.__lastEvents
def _getRaidLog(self, noThrow=True, force=False):
""" Access the raid log and store it locally """
with self.__raidlogDownloadLock:
if not self.__initialized and not force:
return self.lastEvents
self._log.debug("Reading clan raid logs...")
rl = ClanRaidLogRequest(self.session)
result = tryRequest(rl, nothrow=noThrow, numTries=5,
initialDelay=0.5, scaleFactor=2)
if result is None:
self._log.warning("Could not read clan raid logs.")
return self.lastEvents
with self._syncLock:
self._raiseEvent("new_raid_log", None, LogDict(result))
return result
def _updateLogs(self, force=False):
""" Read new logs and parse them if it is time. Then call the
process_log extended call of each module. """
with self.__raidlogDownloadLock:
if time.time() - self._lastEventCheck >= self.delay or force:
result = self._getRaidLog()
return result
return self.lastEvents
def _processDungeonChat(self, msg, checkNum):
"""
This function is called when messages are received from Dungeon.
Like parseChat, the value checkNum is identical for chats received
at the same time.
"""
replies = []
with self.__raidlogDownloadLock:
if self._lastChatNum != checkNum:
# get new events
self._lastChatNum = checkNum
evts = self._updateLogs(force=True)
else:
evts = self.lastEvents
with self.__eventLock:
raidlog = self._filterEvents(evts)
with self._syncLock:
txt = msg['text']
for m in self._modules:
mod = m.module
printStr = mod.extendedCall('process_dungeon',
txt, raidlog)
if printStr is not None:
replies.extend(printStr.split("\n"))
self._syncState()
return replies
def parseChat(self, msg, checkNum):
""" Override of parseChat to split dungeon chat off from "regular"
chat """
if self._chatApplies(msg, checkNum):
if msg['userName'].lower() == 'dungeon' and msg['userId'] == -2:
return self._processDungeonChat(msg, checkNum)
else:
return self._processChat(msg, checkNum)
return []
def cleanup(self):
with self.__eventLock:
self.__initialized = False
MultiChannelManager.cleanup(self)
def _heartbeat(self):
""" Update logs in heartbeat """
if self.__initialized:
self._updateLogs()
super(BaseClanDungeonChannelManager, self)._heartbeat()
def _eventCallback(self, eData):
MultiChannelManager._eventCallback(self, eData)
if eData.subject == "new_raid_log":
raidlog = dict((k,v) for k,v in eData.data.items())
self.lastEvents = raidlog
if not self.__initialized:
return
self._notifyModulesOfNewRaidLog(raidlog)
elif eData.subject == "request_raid_log":
if self.lastEvents is not None:
self._eventReply(LogDict(self.lastEvents))
def _notifyModulesOfNewRaidLog(self, raidlog):
# it's important not to process the log while responding
# to chat, so we need a lock here.
if not self.__initialized:
return
# important to keep this ordering for the locks
with self.__eventLock:
with self._syncLock:
self._log.debug("{} received new log".format(self.identity))
self._lastEventCheck = time.time()
filteredLog = self._filterEvents(raidlog)
self._handleNewRaidlog(filteredLog)
for m in self._modules:
mod = m.module
mod.extendedCall('process_log', filteredLog)
self._syncState()
def _dbMatchRaidLog(self, raidlog):
try:
eventList = []
for e in raidlog['events']:
e['db-match'] = {}
for dbEntry in self._logEntryDb:
if dbEntry['category'].strip() == e['category']:
if re.search(dbEntry['regex'], e['event']):
if not e['db-match']:
e['db-match'] = dbEntry
else:
raise KeyError("Duplicate match in database: "
"event {} matches '{}' and "
"'{}'"
.format(e['event'],
e['db-match']['regex'],
dbEntry['regex']))
eventList.append(e)
raidlog['events'] = eventList
return raidlog
except Exception:
print(raidlog)
raise
############# Override the following:
def _filterEvents(self, raidlog):
""" This function is used by subclasses to remove unrelated event
information. """
return self._dbMatchRaidLog(raidlog)
def _handleNewRaidlog(self, raidlog):
""" This function is called when new raidlogs are downloaded. """
pass
@abc.abstractmethod
def active(self):
pass
| {
"content_hash": "264ee568d581b97ab8248d45fccbf5b0",
"timestamp": "",
"source": "github",
"line_count": 269,
"max_line_length": 79,
"avg_line_length": 38.2639405204461,
"alnum_prop": 0.5080151559312154,
"repo_name": "ijzer/cwbot-ndy",
"id": "e79b6d2385c3a0c67607674bbe2a32565e1c8512",
"size": "10293",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cwbot/managers/BaseClanDungeonChannelManager.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "2986880"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.1">
<Document uuid="6dea10e0-fc48-4ff0-83c2-b0e9b9751fe2">
<InternalInfo>
<xr:GeneratedType name="DocumentObject._ДемоСписаниеБезналичныхДенежныхСредств" category="Object">
<xr:TypeId>2e372836-5068-4949-af3c-8ac9ff12ab89</xr:TypeId>
<xr:ValueId>0266c1d1-7cdc-45bf-a267-48d31125614b</xr:ValueId>
</xr:GeneratedType>
<xr:GeneratedType name="DocumentRef._ДемоСписаниеБезналичныхДенежныхСредств" category="Ref">
<xr:TypeId>ebbd4c30-0c1e-46e4-91fc-3d2ee55876f9</xr:TypeId>
<xr:ValueId>f5c3ed46-e182-4822-a852-1ae75c8df569</xr:ValueId>
</xr:GeneratedType>
<xr:GeneratedType name="DocumentSelection._ДемоСписаниеБезналичныхДенежныхСредств" category="Selection">
<xr:TypeId>88064989-622a-479e-a866-b519001bdead</xr:TypeId>
<xr:ValueId>7bc3bac8-d947-4b77-8885-85da9e19dc23</xr:ValueId>
</xr:GeneratedType>
<xr:GeneratedType name="DocumentList._ДемоСписаниеБезналичныхДенежныхСредств" category="List">
<xr:TypeId>993cb272-3884-4a23-8114-0af3e1713c98</xr:TypeId>
<xr:ValueId>9e82a512-08e9-4486-a354-eabb8666be6b</xr:ValueId>
</xr:GeneratedType>
<xr:GeneratedType name="DocumentManager._ДемоСписаниеБезналичныхДенежныхСредств" category="Manager">
<xr:TypeId>24d912bd-da93-4031-9e4f-497b5c5ba00b</xr:TypeId>
<xr:ValueId>df88c479-d4a2-498f-bff6-90b93842ab64</xr:ValueId>
</xr:GeneratedType>
</InternalInfo>
<Properties>
<Name>_ДемоСписаниеБезналичныхДенежныхСредств</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Демо: Списание безналичных денежных средств</v8:content>
</v8:item>
</Synonym>
<Comment/>
<UseStandardCommands>true</UseStandardCommands>
<Numerator/>
<NumberType>String</NumberType>
<NumberLength>11</NumberLength>
<NumberAllowedLength>Fixed</NumberAllowedLength>
<NumberPeriodicity>Year</NumberPeriodicity>
<CheckUnique>true</CheckUnique>
<Autonumbering>true</Autonumbering>
<StandardAttributes>
<xr:StandardAttribute name="Posted">
<xr:LinkByType/>
<xr:FillChecking>DontCheck</xr:FillChecking>
<xr:MultiLine>false</xr:MultiLine>
<xr:FillFromFillingValue>false</xr:FillFromFillingValue>
<xr:CreateOnInput>Auto</xr:CreateOnInput>
<xr:MaxValue xsi:nil="true"/>
<xr:ToolTip/>
<xr:ExtendedEdit>false</xr:ExtendedEdit>
<xr:Format/>
<xr:ChoiceForm/>
<xr:QuickChoice>Auto</xr:QuickChoice>
<xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput>
<xr:EditFormat/>
<xr:PasswordMode>false</xr:PasswordMode>
<xr:MarkNegatives>false</xr:MarkNegatives>
<xr:MinValue xsi:nil="true"/>
<xr:Synonym/>
<xr:Comment/>
<xr:FullTextSearch>Use</xr:FullTextSearch>
<xr:ChoiceParameterLinks/>
<xr:FillValue xsi:nil="true"/>
<xr:Mask/>
<xr:ChoiceParameters/>
</xr:StandardAttribute>
<xr:StandardAttribute name="Ref">
<xr:LinkByType/>
<xr:FillChecking>DontCheck</xr:FillChecking>
<xr:MultiLine>false</xr:MultiLine>
<xr:FillFromFillingValue>false</xr:FillFromFillingValue>
<xr:CreateOnInput>Auto</xr:CreateOnInput>
<xr:MaxValue xsi:nil="true"/>
<xr:ToolTip/>
<xr:ExtendedEdit>false</xr:ExtendedEdit>
<xr:Format/>
<xr:ChoiceForm/>
<xr:QuickChoice>Auto</xr:QuickChoice>
<xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput>
<xr:EditFormat/>
<xr:PasswordMode>false</xr:PasswordMode>
<xr:MarkNegatives>false</xr:MarkNegatives>
<xr:MinValue xsi:nil="true"/>
<xr:Synonym/>
<xr:Comment/>
<xr:FullTextSearch>Use</xr:FullTextSearch>
<xr:ChoiceParameterLinks/>
<xr:FillValue xsi:nil="true"/>
<xr:Mask/>
<xr:ChoiceParameters/>
</xr:StandardAttribute>
<xr:StandardAttribute name="DeletionMark">
<xr:LinkByType/>
<xr:FillChecking>DontCheck</xr:FillChecking>
<xr:MultiLine>false</xr:MultiLine>
<xr:FillFromFillingValue>false</xr:FillFromFillingValue>
<xr:CreateOnInput>Auto</xr:CreateOnInput>
<xr:MaxValue xsi:nil="true"/>
<xr:ToolTip/>
<xr:ExtendedEdit>false</xr:ExtendedEdit>
<xr:Format/>
<xr:ChoiceForm/>
<xr:QuickChoice>Auto</xr:QuickChoice>
<xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput>
<xr:EditFormat/>
<xr:PasswordMode>false</xr:PasswordMode>
<xr:MarkNegatives>false</xr:MarkNegatives>
<xr:MinValue xsi:nil="true"/>
<xr:Synonym/>
<xr:Comment/>
<xr:FullTextSearch>Use</xr:FullTextSearch>
<xr:ChoiceParameterLinks/>
<xr:FillValue xsi:nil="true"/>
<xr:Mask/>
<xr:ChoiceParameters/>
</xr:StandardAttribute>
<xr:StandardAttribute name="Date">
<xr:LinkByType/>
<xr:FillChecking>ShowError</xr:FillChecking>
<xr:MultiLine>false</xr:MultiLine>
<xr:FillFromFillingValue>false</xr:FillFromFillingValue>
<xr:CreateOnInput>Auto</xr:CreateOnInput>
<xr:MaxValue xsi:nil="true"/>
<xr:ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Дата документа</v8:content>
</v8:item>
</xr:ToolTip>
<xr:ExtendedEdit>false</xr:ExtendedEdit>
<xr:Format/>
<xr:ChoiceForm/>
<xr:QuickChoice>Auto</xr:QuickChoice>
<xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput>
<xr:EditFormat/>
<xr:PasswordMode>false</xr:PasswordMode>
<xr:MarkNegatives>false</xr:MarkNegatives>
<xr:MinValue xsi:nil="true"/>
<xr:Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Дата</v8:content>
</v8:item>
</xr:Synonym>
<xr:Comment/>
<xr:FullTextSearch>Use</xr:FullTextSearch>
<xr:ChoiceParameterLinks/>
<xr:FillValue xsi:type="xs:dateTime">0001-01-01T00:00:00</xr:FillValue>
<xr:Mask/>
<xr:ChoiceParameters/>
</xr:StandardAttribute>
<xr:StandardAttribute name="Number">
<xr:LinkByType/>
<xr:FillChecking>DontCheck</xr:FillChecking>
<xr:MultiLine>false</xr:MultiLine>
<xr:FillFromFillingValue>false</xr:FillFromFillingValue>
<xr:CreateOnInput>Auto</xr:CreateOnInput>
<xr:MaxValue xsi:nil="true"/>
<xr:ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Номер документа</v8:content>
</v8:item>
</xr:ToolTip>
<xr:ExtendedEdit>false</xr:ExtendedEdit>
<xr:Format/>
<xr:ChoiceForm/>
<xr:QuickChoice>Auto</xr:QuickChoice>
<xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput>
<xr:EditFormat/>
<xr:PasswordMode>false</xr:PasswordMode>
<xr:MarkNegatives>false</xr:MarkNegatives>
<xr:MinValue xsi:nil="true"/>
<xr:Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Номер</v8:content>
</v8:item>
</xr:Synonym>
<xr:Comment/>
<xr:FullTextSearch>Use</xr:FullTextSearch>
<xr:ChoiceParameterLinks/>
<xr:FillValue xsi:type="xs:string"> </xr:FillValue>
<xr:Mask/>
<xr:ChoiceParameters/>
</xr:StandardAttribute>
</StandardAttributes>
<Characteristics/>
<BasedOn/>
<InputByString>
<xr:Field>Document._ДемоСписаниеБезналичныхДенежныхСредств.StandardAttribute.Number</xr:Field>
</InputByString>
<CreateOnInput>Use</CreateOnInput>
<SearchStringModeOnInputByString>Begin</SearchStringModeOnInputByString>
<FullTextSearchOnInputByString>DontUse</FullTextSearchOnInputByString>
<ChoiceDataGetModeOnInputByString>Directly</ChoiceDataGetModeOnInputByString>
<DefaultObjectForm>Document._ДемоСписаниеБезналичныхДенежныхСредств.Form.ФормаДокумента</DefaultObjectForm>
<DefaultListForm>Document._ДемоСписаниеБезналичныхДенежныхСредств.Form.ФормаСписка</DefaultListForm>
<DefaultChoiceForm/>
<AuxiliaryObjectForm/>
<AuxiliaryListForm/>
<AuxiliaryChoiceForm/>
<Posting>Allow</Posting>
<RealTimePosting>Allow</RealTimePosting>
<RegisterRecordsDeletion>AutoDeleteOff</RegisterRecordsDeletion>
<RegisterRecordsWritingOnPost>WriteSelected</RegisterRecordsWritingOnPost>
<SequenceFilling>AutoFillOff</SequenceFilling>
<RegisterRecords/>
<PostInPrivilegedMode>true</PostInPrivilegedMode>
<UnpostInPrivilegedMode>true</UnpostInPrivilegedMode>
<IncludeHelpInContents>false</IncludeHelpInContents>
<DataLockFields/>
<DataLockControlMode>Automatic</DataLockControlMode>
<FullTextSearch>Use</FullTextSearch>
<ObjectPresentation>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Демо: Списание безналичных ДС</v8:content>
</v8:item>
</ObjectPresentation>
<ExtendedObjectPresentation>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Демо: Списание безналичных денежных средств</v8:content>
</v8:item>
</ExtendedObjectPresentation>
<ListPresentation>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Демо: Списания безналичных ДС</v8:content>
</v8:item>
</ListPresentation>
<ExtendedListPresentation>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Демо: Списания безналичных денежных средств</v8:content>
</v8:item>
</ExtendedListPresentation>
<Explanation>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Данные о списании безналичных денежных средств с расчетных счетов организации предприятия</v8:content>
</v8:item>
</Explanation>
<ChoiceHistoryOnInput>DontUse</ChoiceHistoryOnInput>
</Properties>
<ChildObjects>
<Attribute uuid="60e90e91-f6cc-4f96-ad2f-2ccca11caf70">
<Properties>
<Name>ДатаВходящегоДокумента</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Дата входящего документа</v8:content>
</v8:item>
</Synonym>
<Comment/>
<Type>
<v8:Type>xs:dateTime</v8:Type>
<v8:DateQualifiers>
<v8:DateFractions>Date</v8:DateFractions>
</v8:DateQualifiers>
</Type>
<PasswordMode>false</PasswordMode>
<Format/>
<EditFormat/>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Дата первичного документа, полученного из банка.</v8:content>
</v8:item>
</ToolTip>
<MarkNegatives>false</MarkNegatives>
<Mask/>
<MultiLine>false</MultiLine>
<ExtendedEdit>false</ExtendedEdit>
<MinValue xsi:nil="true"/>
<MaxValue xsi:nil="true"/>
<FillFromFillingValue>false</FillFromFillingValue>
<FillValue xsi:type="xs:dateTime">0001-01-01T00:00:00</FillValue>
<FillChecking>ShowError</FillChecking>
<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
<ChoiceParameterLinks/>
<ChoiceParameters/>
<QuickChoice>Auto</QuickChoice>
<CreateOnInput>Auto</CreateOnInput>
<ChoiceForm/>
<LinkByType/>
<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>
<Indexing>DontIndex</Indexing>
<FullTextSearch>Use</FullTextSearch>
</Properties>
</Attribute>
<Attribute uuid="49ef20da-a480-41a2-8e1b-c511194a97d2">
<Properties>
<Name>НомерВходящегоДокумента</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Номер входящего документа</v8:content>
</v8:item>
</Synonym>
<Comment/>
<Type>
<v8:Type>xs:string</v8:Type>
<v8:StringQualifiers>
<v8:Length>11</v8:Length>
<v8:AllowedLength>Variable</v8:AllowedLength>
</v8:StringQualifiers>
</Type>
<PasswordMode>false</PasswordMode>
<Format/>
<EditFormat/>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Номер первичного документа, полученного из банка.</v8:content>
</v8:item>
</ToolTip>
<MarkNegatives>false</MarkNegatives>
<Mask/>
<MultiLine>false</MultiLine>
<ExtendedEdit>false</ExtendedEdit>
<MinValue xsi:nil="true"/>
<MaxValue xsi:nil="true"/>
<FillFromFillingValue>false</FillFromFillingValue>
<FillValue xsi:type="xs:string"/>
<FillChecking>ShowError</FillChecking>
<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
<ChoiceParameterLinks/>
<ChoiceParameters/>
<QuickChoice>Auto</QuickChoice>
<CreateOnInput>Auto</CreateOnInput>
<ChoiceForm/>
<LinkByType/>
<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>
<Indexing>DontIndex</Indexing>
<FullTextSearch>Use</FullTextSearch>
</Properties>
</Attribute>
<Attribute uuid="2af2300d-8ee0-4fc6-8a18-1f0462deb7b4">
<Properties>
<Name>НазначениеПлатежа</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Назначение платежа</v8:content>
</v8:item>
</Synonym>
<Comment/>
<Type>
<v8:Type>xs:string</v8:Type>
<v8:StringQualifiers>
<v8:Length>210</v8:Length>
<v8:AllowedLength>Variable</v8:AllowedLength>
</v8:StringQualifiers>
</Type>
<PasswordMode>false</PasswordMode>
<Format/>
<EditFormat/>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Назначение платежа получателю</v8:content>
</v8:item>
</ToolTip>
<MarkNegatives>false</MarkNegatives>
<Mask/>
<MultiLine>false</MultiLine>
<ExtendedEdit>false</ExtendedEdit>
<MinValue xsi:nil="true"/>
<MaxValue xsi:nil="true"/>
<FillFromFillingValue>true</FillFromFillingValue>
<FillValue xsi:type="xs:string"/>
<FillChecking>DontCheck</FillChecking>
<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
<ChoiceParameterLinks/>
<ChoiceParameters/>
<QuickChoice>Auto</QuickChoice>
<CreateOnInput>Auto</CreateOnInput>
<ChoiceForm/>
<LinkByType/>
<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>
<Indexing>DontIndex</Indexing>
<FullTextSearch>Use</FullTextSearch>
</Properties>
</Attribute>
<Attribute uuid="14587a79-1ca8-46b5-8b98-999b4d8d58b2">
<Properties>
<Name>Организация</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Организация</v8:content>
</v8:item>
</Synonym>
<Comment/>
<Type>
<v8:Type>cfg:CatalogRef._ДемоОрганизации</v8:Type>
</Type>
<PasswordMode>false</PasswordMode>
<Format/>
<EditFormat/>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Организация предприятия, от имени которой оформляется документ.</v8:content>
</v8:item>
</ToolTip>
<MarkNegatives>false</MarkNegatives>
<Mask/>
<MultiLine>false</MultiLine>
<ExtendedEdit>false</ExtendedEdit>
<MinValue xsi:nil="true"/>
<MaxValue xsi:nil="true"/>
<FillFromFillingValue>true</FillFromFillingValue>
<FillValue xsi:type="xr:DesignTimeRef">55adb97e-a84e-453e-8020-7665bb2abdef.00000000-0000-0000-0000-000000000000</FillValue>
<FillChecking>ShowError</FillChecking>
<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
<ChoiceParameterLinks/>
<ChoiceParameters/>
<QuickChoice>Auto</QuickChoice>
<CreateOnInput>Auto</CreateOnInput>
<ChoiceForm/>
<LinkByType/>
<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>
<Indexing>DontIndex</Indexing>
<FullTextSearch>Use</FullTextSearch>
</Properties>
</Attribute>
<Attribute uuid="d4ab4e95-c6cd-44df-a21a-ac20c47a7a6d">
<Properties>
<Name>БанковскийСчет</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Банковский счет</v8:content>
</v8:item>
</Synonym>
<Comment/>
<Type>
<v8:Type>cfg:CatalogRef._ДемоБанковскиеСчета</v8:Type>
</Type>
<PasswordMode>false</PasswordMode>
<Format/>
<EditFormat/>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Банковский счет организации, по которому оформляется операция</v8:content>
</v8:item>
</ToolTip>
<MarkNegatives>false</MarkNegatives>
<Mask/>
<MultiLine>false</MultiLine>
<ExtendedEdit>false</ExtendedEdit>
<MinValue xsi:nil="true"/>
<MaxValue xsi:nil="true"/>
<FillFromFillingValue>true</FillFromFillingValue>
<FillValue xsi:nil="true"/>
<FillChecking>ShowError</FillChecking>
<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
<ChoiceParameterLinks>
<xr:Link>
<xr:Name>Отбор.Владелец</xr:Name>
<xr:DataPath xsi:type="xs:string">Document._ДемоСписаниеБезналичныхДенежныхСредств.Attribute.Организация</xr:DataPath>
<xr:ValueChange>Clear</xr:ValueChange>
</xr:Link>
</ChoiceParameterLinks>
<ChoiceParameters/>
<QuickChoice>Auto</QuickChoice>
<CreateOnInput>Auto</CreateOnInput>
<ChoiceForm/>
<LinkByType/>
<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>
<Indexing>DontIndex</Indexing>
<FullTextSearch>Use</FullTextSearch>
</Properties>
</Attribute>
<Attribute uuid="20bebcc4-6037-4126-8db5-01c340435f18">
<Properties>
<Name>Получатель</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Получатель</v8:content>
</v8:item>
</Synonym>
<Comment/>
<Type>
<v8:Type>cfg:CatalogRef._ДемоКонтрагенты</v8:Type>
</Type>
<PasswordMode>false</PasswordMode>
<Format/>
<EditFormat/>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Поставщик, которому производится оплата или клиент, которому возвращаются денежные средства</v8:content>
</v8:item>
</ToolTip>
<MarkNegatives>false</MarkNegatives>
<Mask/>
<MultiLine>false</MultiLine>
<ExtendedEdit>false</ExtendedEdit>
<MinValue xsi:nil="true"/>
<MaxValue xsi:nil="true"/>
<FillFromFillingValue>true</FillFromFillingValue>
<FillValue xsi:nil="true"/>
<FillChecking>ShowError</FillChecking>
<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
<ChoiceParameterLinks/>
<ChoiceParameters/>
<QuickChoice>Auto</QuickChoice>
<CreateOnInput>Auto</CreateOnInput>
<ChoiceForm/>
<LinkByType/>
<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>
<Indexing>DontIndex</Indexing>
<FullTextSearch>Use</FullTextSearch>
</Properties>
</Attribute>
<Attribute uuid="acb715d5-0636-49cd-862f-af764bf73695">
<Properties>
<Name>СчетПолучателя</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Счет получателя</v8:content>
</v8:item>
</Synonym>
<Comment/>
<Type>
<v8:Type>cfg:CatalogRef._ДемоБанковскиеСчета</v8:Type>
</Type>
<PasswordMode>false</PasswordMode>
<Format/>
<EditFormat/>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Банковский счет контрагента или организации, на который перечисляются денежные средства</v8:content>
</v8:item>
</ToolTip>
<MarkNegatives>false</MarkNegatives>
<Mask/>
<MultiLine>false</MultiLine>
<ExtendedEdit>false</ExtendedEdit>
<MinValue xsi:nil="true"/>
<MaxValue xsi:nil="true"/>
<FillFromFillingValue>true</FillFromFillingValue>
<FillValue xsi:nil="true"/>
<FillChecking>ShowError</FillChecking>
<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
<ChoiceParameterLinks>
<xr:Link>
<xr:Name>Отбор.Владелец</xr:Name>
<xr:DataPath xsi:type="xs:string">Document._ДемоСписаниеБезналичныхДенежныхСредств.Attribute.Получатель</xr:DataPath>
<xr:ValueChange>Clear</xr:ValueChange>
</xr:Link>
</ChoiceParameterLinks>
<ChoiceParameters/>
<QuickChoice>Auto</QuickChoice>
<CreateOnInput>Auto</CreateOnInput>
<ChoiceForm/>
<LinkByType/>
<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>
<Indexing>DontIndex</Indexing>
<FullTextSearch>Use</FullTextSearch>
</Properties>
</Attribute>
<Attribute uuid="89b8198f-29a6-40a9-9889-d243de50ca25">
<Properties>
<Name>СуммаДокумента</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Сумма документа</v8:content>
</v8:item>
</Synonym>
<Comment/>
<Type>
<v8:Type>xs:decimal</v8:Type>
<v8:NumberQualifiers>
<v8:Digits>15</v8:Digits>
<v8:FractionDigits>2</v8:FractionDigits>
<v8:AllowedSign>Nonnegative</v8:AllowedSign>
</v8:NumberQualifiers>
</Type>
<PasswordMode>false</PasswordMode>
<Format/>
<EditFormat/>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Сумма документа.</v8:content>
</v8:item>
</ToolTip>
<MarkNegatives>true</MarkNegatives>
<Mask/>
<MultiLine>false</MultiLine>
<ExtendedEdit>false</ExtendedEdit>
<MinValue xsi:nil="true"/>
<MaxValue xsi:nil="true"/>
<FillFromFillingValue>true</FillFromFillingValue>
<FillValue xsi:type="xs:decimal">0</FillValue>
<FillChecking>ShowError</FillChecking>
<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
<ChoiceParameterLinks/>
<ChoiceParameters/>
<QuickChoice>Auto</QuickChoice>
<CreateOnInput>Auto</CreateOnInput>
<ChoiceForm/>
<LinkByType/>
<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>
<Indexing>DontIndex</Indexing>
<FullTextSearch>Use</FullTextSearch>
</Properties>
</Attribute>
<Attribute uuid="881225e2-0421-4bbc-9c4c-7fa7e1a9db42">
<Properties>
<Name>ПроведеноБанком</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Проведено банком</v8:content>
</v8:item>
</Synonym>
<Comment/>
<Type>
<v8:Type>xs:boolean</v8:Type>
</Type>
<PasswordMode>false</PasswordMode>
<Format/>
<EditFormat/>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Наличие подтверждения банка о списании денежных средств</v8:content>
</v8:item>
</ToolTip>
<MarkNegatives>false</MarkNegatives>
<Mask/>
<MultiLine>false</MultiLine>
<ExtendedEdit>false</ExtendedEdit>
<MinValue xsi:nil="true"/>
<MaxValue xsi:nil="true"/>
<FillFromFillingValue>false</FillFromFillingValue>
<FillValue xsi:nil="true"/>
<FillChecking>DontCheck</FillChecking>
<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
<ChoiceParameterLinks/>
<ChoiceParameters/>
<QuickChoice>Auto</QuickChoice>
<CreateOnInput>Auto</CreateOnInput>
<ChoiceForm/>
<LinkByType/>
<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>
<Indexing>DontIndex</Indexing>
<FullTextSearch>Use</FullTextSearch>
</Properties>
</Attribute>
<Attribute uuid="d36253f8-51a1-4123-8ea0-475fceaa0bdb">
<Properties>
<Name>ДатаПроведенияБанком</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Дата проведения банком</v8:content>
</v8:item>
</Synonym>
<Comment/>
<Type>
<v8:Type>xs:dateTime</v8:Type>
<v8:DateQualifiers>
<v8:DateFractions>Date</v8:DateFractions>
</v8:DateQualifiers>
</Type>
<PasswordMode>false</PasswordMode>
<Format/>
<EditFormat/>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Дата списания денежных средств с расчетного счета</v8:content>
</v8:item>
</ToolTip>
<MarkNegatives>false</MarkNegatives>
<Mask/>
<MultiLine>false</MultiLine>
<ExtendedEdit>false</ExtendedEdit>
<MinValue xsi:nil="true"/>
<MaxValue xsi:nil="true"/>
<FillFromFillingValue>true</FillFromFillingValue>
<FillValue xsi:nil="true"/>
<FillChecking>ShowError</FillChecking>
<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
<ChoiceParameterLinks/>
<ChoiceParameters/>
<QuickChoice>Auto</QuickChoice>
<CreateOnInput>Auto</CreateOnInput>
<ChoiceForm/>
<LinkByType/>
<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>
<Indexing>DontIndex</Indexing>
<FullTextSearch>Use</FullTextSearch>
</Properties>
</Attribute>
<Attribute uuid="2739ad64-11db-4e61-bb5e-0bf824158141">
<Properties>
<Name>Комментарий</Name>
<Synonym>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Комментарий</v8:content>
</v8:item>
</Synonym>
<Comment/>
<Type>
<v8:Type>xs:string</v8:Type>
<v8:StringQualifiers>
<v8:Length>0</v8:Length>
<v8:AllowedLength>Variable</v8:AllowedLength>
</v8:StringQualifiers>
</Type>
<PasswordMode>false</PasswordMode>
<Format/>
<EditFormat/>
<ToolTip>
<v8:item>
<v8:lang>ru</v8:lang>
<v8:content>Произвольный текст</v8:content>
</v8:item>
</ToolTip>
<MarkNegatives>false</MarkNegatives>
<Mask/>
<MultiLine>true</MultiLine>
<ExtendedEdit>true</ExtendedEdit>
<MinValue xsi:nil="true"/>
<MaxValue xsi:nil="true"/>
<FillFromFillingValue>false</FillFromFillingValue>
<FillValue xsi:type="xs:string"/>
<FillChecking>DontCheck</FillChecking>
<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>
<ChoiceParameterLinks/>
<ChoiceParameters/>
<QuickChoice>Auto</QuickChoice>
<CreateOnInput>Auto</CreateOnInput>
<ChoiceForm/>
<LinkByType/>
<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>
<Indexing>DontIndex</Indexing>
<FullTextSearch>Use</FullTextSearch>
</Properties>
</Attribute>
<Form>ФормаДокумента</Form>
<Form>ФормаСписка</Form>
</ChildObjects>
</Document>
</MetaDataObject> | {
"content_hash": "2d7c698254d70b1da5c1a16c02ae4c22",
"timestamp": "",
"source": "github",
"line_count": 762,
"max_line_length": 867,
"avg_line_length": 34.4514435695538,
"alnum_prop": 0.6675300929452994,
"repo_name": "oleynikova/final_task",
"id": "10425ef15bdf26783e2844cd5440d0b1c958a1a3",
"size": "27957",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/cf/Documents/_ДемоСписаниеБезналичныхДенежныхСредств.xml",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "1C Enterprise",
"bytes": "77226"
},
{
"name": "Cucumber",
"bytes": "20584"
},
{
"name": "GCC Machine Description",
"bytes": "506"
},
{
"name": "Shell",
"bytes": "3533"
}
],
"symlink_target": ""
} |
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2006 INRIA
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Mathieu Lacage <mathieu.lacage@sophia.inria.fr>
* The idea to use a std c++ map came from GTNetS
*/
#include "map-scheduler.h"
#include "event-impl.h"
#include "assert.h"
#include "log.h"
#include <string>
NS_LOG_COMPONENT_DEFINE ("MapScheduler");
namespace ns3 {
NS_OBJECT_ENSURE_REGISTERED (MapScheduler);
TypeId
MapScheduler::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::MapScheduler")
.SetParent<Scheduler> ()
.AddConstructor<MapScheduler> ()
;
return tid;
}
MapScheduler::MapScheduler ()
{
NS_LOG_FUNCTION (this);
}
MapScheduler::~MapScheduler ()
{
NS_LOG_FUNCTION (this);
}
void
MapScheduler::Insert (const Event &ev)
{
NS_LOG_FUNCTION (this << ev.impl << ev.key.m_ts << ev.key.m_uid);
std::pair<EventMapI,bool> result;
result = m_list.insert (std::make_pair (ev.key, ev.impl));
NS_ASSERT (result.second);
}
bool
MapScheduler::IsEmpty (void) const
{
NS_LOG_FUNCTION (this);
return m_list.empty ();
}
Scheduler::Event
MapScheduler::PeekNext (void) const
{
NS_LOG_FUNCTION (this);
EventMapCI i = m_list.begin ();
NS_ASSERT (i != m_list.end ());
Event ev;
ev.impl = i->second;
ev.key = i->first;
NS_LOG_DEBUG (this << ev.impl << ev.key.m_ts << ev.key.m_uid);
return ev;
}
Scheduler::Event
MapScheduler::RemoveNext (void)
{
NS_LOG_FUNCTION (this);
EventMapI i = m_list.begin ();
NS_ASSERT (i != m_list.end ());
Event ev;
ev.impl = i->second;
ev.key = i->first;
m_list.erase (i);
NS_LOG_DEBUG (this << ev.impl << ev.key.m_ts << ev.key.m_uid);
return ev;
}
void
MapScheduler::Remove (const Event &ev)
{
NS_LOG_FUNCTION (this << ev.impl << ev.key.m_ts << ev.key.m_uid);
EventMapI i = m_list.find (ev.key);
NS_ASSERT (i->second == ev.impl);
m_list.erase (i);
}
} // namespace ns3
| {
"content_hash": "8f46dd5e5163718c574d86c97a012a03",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 76,
"avg_line_length": 24.133333333333333,
"alnum_prop": 0.6716653512233622,
"repo_name": "Chiru/NVE_Simulation",
"id": "2df7045246ff0bd0e35d41ab8b831813f41948cb",
"size": "2534",
"binary": false,
"copies": "55",
"ref": "refs/heads/master",
"path": "NS3/src/core/model/map-scheduler.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "587430"
},
{
"name": "C++",
"bytes": "15139819"
},
{
"name": "DOT",
"bytes": "2792"
},
{
"name": "M",
"bytes": "5446"
},
{
"name": "Matlab",
"bytes": "18438"
},
{
"name": "Objective-C",
"bytes": "15035"
},
{
"name": "Perl",
"bytes": "302841"
},
{
"name": "Prolog",
"bytes": "2793"
},
{
"name": "Python",
"bytes": "32484684"
},
{
"name": "Scala",
"bytes": "51"
},
{
"name": "Shell",
"bytes": "7282"
}
],
"symlink_target": ""
} |
import path from 'path';
import { parseStackTraceLine } from '../utilsBundle';
import { isUnderTest } from './';
export function rewriteErrorMessage<E extends Error>(e: E, newMessage: string): E {
const lines: string[] = (e.stack?.split('\n') || []).filter(l => l.startsWith(' at '));
e.message = newMessage;
const errorTitle = `${e.name}: ${e.message}`;
if (lines.length)
e.stack = `${errorTitle}\n${lines.join('\n')}`;
return e;
}
const CORE_DIR = path.resolve(__dirname, '..', '..');
const CORE_LIB = path.join(CORE_DIR, 'lib');
const CORE_SRC = path.join(CORE_DIR, 'src');
const TEST_DIR_SRC = path.resolve(CORE_DIR, '..', 'playwright-test');
const TEST_DIR_LIB = path.resolve(CORE_DIR, '..', '@playwright', 'test');
const COVERAGE_PATH = path.join(CORE_DIR, '..', '..', 'tests', 'config', 'coverage.js');
export type StackFrame = {
file: string,
line?: number,
column?: number,
function?: string,
};
export type ParsedStackTrace = {
allFrames: StackFrame[];
frames: StackFrame[];
frameTexts: string[];
apiName: string | undefined;
};
export function captureRawStack(): string {
const stackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = 30;
const error = new Error();
const stack = error.stack!;
Error.stackTraceLimit = stackTraceLimit;
return stack;
}
export function isInternalFileName(file: string, functionName?: string): boolean {
// Node 16+ has node:internal.
if (file.startsWith('internal') || file.startsWith('node:'))
return true;
// EventEmitter.emit has 'events.js' file.
if (file === 'events.js' && functionName?.endsWith('emit'))
return true;
return false;
}
export function captureStackTrace(rawStack?: string): ParsedStackTrace {
const stack = rawStack || captureRawStack();
const isTesting = isUnderTest();
type ParsedFrame = {
frame: StackFrame;
frameText: string;
inCore: boolean;
};
let parsedFrames = stack.split('\n').map(line => {
const { frame, fileName } = parseStackTraceLine(line);
if (!frame || !frame.file || !fileName)
return null;
if (!process.env.PWDEBUGIMPL && isInternalFileName(frame.file, frame.function))
return null;
if (!process.env.PWDEBUGIMPL && isTesting && fileName.includes(COVERAGE_PATH))
return null;
const inCore = fileName.startsWith(CORE_LIB) || fileName.startsWith(CORE_SRC);
const parsed: ParsedFrame = {
frame: {
file: fileName,
line: frame.line,
column: frame.column,
function: frame.function,
},
frameText: line,
inCore
};
return parsed;
}).filter(Boolean) as ParsedFrame[];
let apiName = '';
const allFrames = parsedFrames;
// Deepest transition between non-client code calling into client code
// is the api entry.
for (let i = 0; i < parsedFrames.length - 1; i++) {
if (parsedFrames[i].inCore && !parsedFrames[i + 1].inCore) {
const frame = parsedFrames[i].frame;
apiName = normalizeAPIName(frame.function);
if (!process.env.PWDEBUGIMPL)
parsedFrames = parsedFrames.slice(i + 1);
break;
}
}
function normalizeAPIName(name?: string): string {
if (!name)
return '';
const match = name.match(/(API|JS|CDP|[A-Z])(.*)/);
if (!match)
return name;
return match[1].toLowerCase() + match[2];
}
// Hide all test runner and library frames in the user stack (event handlers produce them).
parsedFrames = parsedFrames.filter((f, i) => {
if (process.env.PWDEBUGIMPL)
return true;
if (f.frame.file.startsWith(TEST_DIR_SRC) || f.frame.file.startsWith(TEST_DIR_LIB))
return false;
if (f.frame.file.startsWith(CORE_DIR))
return false;
return true;
});
return {
allFrames: allFrames.map(p => p.frame),
frames: parsedFrames.map(p => p.frame),
frameTexts: parsedFrames.map(p => p.frameText),
apiName
};
}
export function splitErrorMessage(message: string): { name: string, message: string } {
const separationIdx = message.indexOf(':');
return {
name: separationIdx !== -1 ? message.slice(0, separationIdx) : '',
message: separationIdx !== -1 && separationIdx + 2 <= message.length ? message.substring(separationIdx + 2) : message,
};
}
| {
"content_hash": "fa60d5c5cfdb3ce75e0540120ee888aa",
"timestamp": "",
"source": "github",
"line_count": 135,
"max_line_length": 122,
"avg_line_length": 31.525925925925925,
"alnum_prop": 0.6482612781954887,
"repo_name": "microsoft/playwright",
"id": "f8b60663cc1049d6537f1180bad900f0ba476a60",
"size": "4857",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "packages/playwright-core/src/utils/stackTrace.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "291"
},
{
"name": "C",
"bytes": "7890"
},
{
"name": "C#",
"bytes": "2296"
},
{
"name": "C++",
"bytes": "116810"
},
{
"name": "CMake",
"bytes": "2704"
},
{
"name": "CSS",
"bytes": "103622"
},
{
"name": "HTML",
"bytes": "339177"
},
{
"name": "Java",
"bytes": "16271"
},
{
"name": "JavaScript",
"bytes": "75700"
},
{
"name": "Makefile",
"bytes": "377"
},
{
"name": "Objective-C",
"bytes": "63418"
},
{
"name": "PowerShell",
"bytes": "4150"
},
{
"name": "Python",
"bytes": "2965"
},
{
"name": "Shell",
"bytes": "43661"
},
{
"name": "Svelte",
"bytes": "3358"
},
{
"name": "TypeScript",
"bytes": "5956124"
},
{
"name": "Vue",
"bytes": "6225"
}
],
"symlink_target": ""
} |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ssl::context_base::no_tlsv1_1</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../ssl__context_base.html" title="ssl::context_base">
<link rel="prev" href="no_tlsv1.html" title="ssl::context_base::no_tlsv1">
<link rel="next" href="no_tlsv1_2.html" title="ssl::context_base::no_tlsv1_2">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="no_tlsv1.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../ssl__context_base.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="no_tlsv1_2.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="boost_asio.reference.ssl__context_base.no_tlsv1_1"></a><a class="link" href="no_tlsv1_1.html" title="ssl::context_base::no_tlsv1_1">ssl::context_base::no_tlsv1_1</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="boost_asio.indexterm.ssl__context_base.no_tlsv1_1"></a>
Disable
TLS v1.1.
</p>
<pre class="programlisting">static const long no_tlsv1_1 = implementation_defined;
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2021 Christopher
M. Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="no_tlsv1.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../ssl__context_base.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="no_tlsv1_2.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| {
"content_hash": "90951c7c3b39c7a43bd2154c697356d6",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 433,
"avg_line_length": 62.07843137254902,
"alnum_prop": 0.6174984207201516,
"repo_name": "davehorton/drachtio-server",
"id": "eada798184c4a5a95adba8dc43673d0f752dab67",
"size": "3167",
"binary": false,
"copies": "2",
"ref": "refs/heads/main",
"path": "deps/boost_1_77_0/doc/html/boost_asio/reference/ssl__context_base/no_tlsv1_1.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "662596"
},
{
"name": "Dockerfile",
"bytes": "1330"
},
{
"name": "JavaScript",
"bytes": "60639"
},
{
"name": "M4",
"bytes": "35273"
},
{
"name": "Makefile",
"bytes": "5960"
},
{
"name": "Shell",
"bytes": "47298"
}
],
"symlink_target": ""
} |
var tree = {
'/': {
'index.html': '<html><body><h1>Hi!</h1></body></html>',
'README.md': 'Test readme.',
'assets': {
'app.js': '// app.js content',
'app.css': '/* app.css content */'
}
}
};
var fs = new FileTree(tree);
var arrayContains = function(arrayA, arrayB) {
for(var b=0; b<arrayB.length; b++) {
if(arrayA.indexOf(arrayB[b]) === -1) {
return false;
}
}
return arrayA.length == arrayB.length;
}
QUnit.test("listing the root folder", function( assert ) {
var actualFiles = fs.list('/'),
expectedFiles = ['index.html', 'README.md', 'assets'];
assert.ok(arrayContains(actualFiles, expectedFiles) == true);
});
QUnit.test("listing a sub folder", function( assert ) {
var actualFiles = fs.list('/assets'),
expectedFiles = ['app.css', 'app.js'];
assert.ok(arrayContains(actualFiles, expectedFiles) == true, actualFiles.toString());
});
QUnit.test("reading a file", function( assert ) {
assert.ok(fs.read('/assets/app.js') == '// app.js content');
});
QUnit.test("writing a file", function( assert ) {
fs.write('/assets/test.txt', 'test')
var actualFiles = fs.list('/assets'),
expectedFiles = ['app.css', 'app.js', 'test.txt'];
assert.ok(fs.read('/assets/test.txt') == 'test', "Read written file: Passed!" );
assert.ok(arrayContains(actualFiles, expectedFiles) == true, "List directory again: Passed!" );
});
| {
"content_hash": "25ac5eec4ac059668fc6e5d26ca241be",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 97,
"avg_line_length": 29.4375,
"alnum_prop": 0.607926397735315,
"repo_name": "AVGP/filetree.js",
"id": "6ecdb705cb0aa32436d0fbd0a676fa7c28f79431",
"size": "1413",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2479"
}
],
"symlink_target": ""
} |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reactive.Linq;
using Microsoft.Extensions.Logging;
using RoyalRoad.Core.Common;
using RoyalRoad.Core.Entities;
var races = globalCache.CategoryByType<Category>("Race");
var classes = globalCache.CategoryByType<Class>("Class");
var areaId = (string)options["areaId"];
var list = new List<Monster>();
var total = NumberUtil.Next(5) + 1;
for (var i = 0; i < total; ++i) {
list.Add(new Monster(races.Random().Id, classes.Random(), NumberUtil.Next(10) + 1, areaId));
}
return list; | {
"content_hash": "88c5a1cfabc7494c8703e0ee4d5aea52",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 94,
"avg_line_length": 32.88235294117647,
"alnum_prop": 0.738819320214669,
"repo_name": "huytrongnguyen/royal-road",
"id": "b625e7b90e93458558b37cb29721567724e4153d",
"size": "559",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/RoyalRoad.Resources/scripts/CREATE_MONSTER.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "67494"
},
{
"name": "CSS",
"bytes": "12259"
},
{
"name": "JavaScript",
"bytes": "71347"
}
],
"symlink_target": ""
} |
'use strict';
var util = require('util'),
shelljs = require('shelljs'),
generators = require('yeoman-generator'),
chalk = require('chalk'),
jhiCore = require('jhipster-core'),
scriptBase = require('../generator-base');
var JDLGenerator = generators.Base.extend({});
util.inherits(JDLGenerator, scriptBase);
module.exports = JDLGenerator.extend({
constructor: function () {
generators.Base.apply(this, arguments);
this.argument('jdlFiles', {type: Array, required: true});
},
initializing: {
validate: function () {
this.jdlFiles && this.jdlFiles.forEach(function (key) {
if (!shelljs.test('-f', key)) {
this.env.error(chalk.red(`\nCould not find ${ key }, make sure the path is correct!\n`));
}
}, this);
},
getConfig: function () {
this.baseName = this.config.get('baseName');
this.prodDatabaseType = this.config.get('prodDatabaseType');
this.skipClient = this.config.get('skipClient');
}
},
default: {
insight: function () {
var insight = this.insight();
insight.trackWithEvent('generator', 'import-jdl');
},
parseJDL: function () {
this.log('The jdl is being parsed.');
try {
var jdlObject = jhiCore.convertToJDL(jhiCore.parseFromFiles(this.jdlFiles), this.prodDatabaseType);
var entities = jhiCore.convertToJHipsterJSON({
jdlObject: jdlObject,
databaseType: this.prodDatabaseType
});
this.log('Writing entity JSON files.');
jhiCore.exportToJSON(entities, this.options['force']);
} catch (e) {
this.log(e.message || e);
this.error(`\nError while parsing entities from JDL\n`);
}
},
generateEntities: function () {
this.log('Generating entities.');
try {
this.getExistingEntities().forEach(function (entity) {
this.composeWith('jhipster:entity', {
options: {
regenerate: true,
'skip-install': true
},
args: [entity.name]
}, {
local: require.resolve('../entity')
});
}, this);
} catch (e) {
this.error(`Error while generating entities from parsed JDL\n${ e }`);
}
}
},
install: function () {
var injectJsFilesToIndex = function () {
this.log('\n' + chalk.bold.green('Running gulp Inject to add javascript to index\n'));
this.spawnCommand('gulp', ['inject:app']);
};
if (!this.options['skip-install'] && !this.skipClient) {
injectJsFilesToIndex.call(this);
}
}
});
| {
"content_hash": "fc8a832a829b0c5c3d264d9c9e3baaf8",
"timestamp": "",
"source": "github",
"line_count": 91,
"max_line_length": 115,
"avg_line_length": 33.38461538461539,
"alnum_prop": 0.5052666227781435,
"repo_name": "axel-halin/Thesis-JHipster",
"id": "5f58d067d1657c09ed7275bcbeffbace3136c01d",
"size": "3038",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "FML-brute/node_modules/generator-jhipster/generators/import-jdl/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "10012"
},
{
"name": "CSS",
"bytes": "140785"
},
{
"name": "Groovy",
"bytes": "648"
},
{
"name": "HTML",
"bytes": "69438"
},
{
"name": "Java",
"bytes": "489408"
},
{
"name": "JavaScript",
"bytes": "116875"
},
{
"name": "Matlab",
"bytes": "6354"
},
{
"name": "Shell",
"bytes": "14300"
}
],
"symlink_target": ""
} |
<?php
/**
* Skeleton subclass for representing a row from the 'fooditems' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
* @package propel.generator.fbapp
*/
class Fooditems extends BaseFooditems
{
}
| {
"content_hash": "5934292e7ac293b4df03ca7320483869",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 71,
"avg_line_length": 20.72222222222222,
"alnum_prop": 0.7211796246648794,
"repo_name": "royrusso/fishbase",
"id": "b82765fdd01b16eeedc419363a17179c65d1a068",
"size": "373",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classes/fbapp/Fooditems.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "54469"
},
{
"name": "JavaScript",
"bytes": "257574"
},
{
"name": "PHP",
"bytes": "43155398"
}
],
"symlink_target": ""
} |
"""
Support for local control of entities by emulating the Phillips Hue bridge.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/emulated_hue/
"""
import logging
from aiohttp import web
import voluptuous as vol
from homeassistant import util
from homeassistant.const import (
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP,
)
from homeassistant.components.http import REQUIREMENTS # NOQA
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.deprecation import get_deprecated
import homeassistant.helpers.config_validation as cv
from homeassistant.util.json import load_json, save_json
from homeassistant.components.http import real_ip
from .hue_api import (
HueUsernameView, HueAllLightsStateView, HueOneLightStateView,
HueOneLightChangeView, HueGroupView, HueAllGroupsStateView)
from .upnp import DescriptionXmlView, UPNPResponderThread
DOMAIN = 'emulated_hue'
_LOGGER = logging.getLogger(__name__)
NUMBERS_FILE = 'emulated_hue_ids.json'
CONF_HOST_IP = 'host_ip'
CONF_LISTEN_PORT = 'listen_port'
CONF_ADVERTISE_IP = 'advertise_ip'
CONF_ADVERTISE_PORT = 'advertise_port'
CONF_UPNP_BIND_MULTICAST = 'upnp_bind_multicast'
CONF_OFF_MAPS_TO_ON_DOMAINS = 'off_maps_to_on_domains'
CONF_EXPOSE_BY_DEFAULT = 'expose_by_default'
CONF_EXPOSED_DOMAINS = 'exposed_domains'
CONF_TYPE = 'type'
CONF_ENTITIES = 'entities'
CONF_ENTITY_NAME = 'name'
CONF_ENTITY_HIDDEN = 'hidden'
TYPE_ALEXA = 'alexa'
TYPE_GOOGLE = 'google_home'
DEFAULT_LISTEN_PORT = 8300
DEFAULT_UPNP_BIND_MULTICAST = True
DEFAULT_OFF_MAPS_TO_ON_DOMAINS = ['script', 'scene']
DEFAULT_EXPOSE_BY_DEFAULT = True
DEFAULT_EXPOSED_DOMAINS = [
'switch', 'light', 'group', 'input_boolean', 'media_player', 'fan'
]
DEFAULT_TYPE = TYPE_GOOGLE
CONFIG_ENTITY_SCHEMA = vol.Schema({
vol.Optional(CONF_ENTITY_NAME): cv.string,
vol.Optional(CONF_ENTITY_HIDDEN): cv.boolean
})
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Optional(CONF_HOST_IP): cv.string,
vol.Optional(CONF_LISTEN_PORT, default=DEFAULT_LISTEN_PORT): cv.port,
vol.Optional(CONF_ADVERTISE_IP): cv.string,
vol.Optional(CONF_ADVERTISE_PORT): cv.port,
vol.Optional(CONF_UPNP_BIND_MULTICAST): cv.boolean,
vol.Optional(CONF_OFF_MAPS_TO_ON_DOMAINS): cv.ensure_list,
vol.Optional(CONF_EXPOSE_BY_DEFAULT): cv.boolean,
vol.Optional(CONF_EXPOSED_DOMAINS): cv.ensure_list,
vol.Optional(CONF_TYPE, default=DEFAULT_TYPE):
vol.Any(TYPE_ALEXA, TYPE_GOOGLE),
vol.Optional(CONF_ENTITIES):
vol.Schema({cv.entity_id: CONFIG_ENTITY_SCHEMA})
})
}, extra=vol.ALLOW_EXTRA)
ATTR_EMULATED_HUE = 'emulated_hue'
ATTR_EMULATED_HUE_NAME = 'emulated_hue_name'
ATTR_EMULATED_HUE_HIDDEN = 'emulated_hue_hidden'
async def async_setup(hass, yaml_config):
"""Activate the emulated_hue component."""
config = Config(hass, yaml_config.get(DOMAIN, {}))
app = web.Application()
app['hass'] = hass
real_ip.setup_real_ip(app, False, [])
# We misunderstood the startup signal. You're not allowed to change
# anything during startup. Temp workaround.
# pylint: disable=protected-access
app._on_startup.freeze()
await app.startup()
runner = None
site = None
DescriptionXmlView(config).register(app, app.router)
HueUsernameView().register(app, app.router)
HueAllLightsStateView(config).register(app, app.router)
HueOneLightStateView(config).register(app, app.router)
HueOneLightChangeView(config).register(app, app.router)
HueAllGroupsStateView(config).register(app, app.router)
HueGroupView(config).register(app, app.router)
upnp_listener = UPNPResponderThread(
config.host_ip_addr, config.listen_port,
config.upnp_bind_multicast, config.advertise_ip,
config.advertise_port)
async def stop_emulated_hue_bridge(event):
"""Stop the emulated hue bridge."""
upnp_listener.stop()
if site:
await site.stop()
if runner:
await runner.cleanup()
async def start_emulated_hue_bridge(event):
"""Start the emulated hue bridge."""
upnp_listener.start()
nonlocal site
nonlocal runner
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, config.host_ip_addr, config.listen_port)
try:
await site.start()
except OSError as error:
_LOGGER.error("Failed to create HTTP server at port %d: %s",
config.listen_port, error)
else:
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STOP, stop_emulated_hue_bridge)
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START,
start_emulated_hue_bridge)
return True
class Config:
"""Hold configuration variables for the emulated hue bridge."""
def __init__(self, hass, conf):
"""Initialize the instance."""
self.hass = hass
self.type = conf.get(CONF_TYPE)
self.numbers = None
self.cached_states = {}
if self.type == TYPE_ALEXA:
_LOGGER.warning(
'Emulated Hue running in legacy mode because type has been '
'specified. More info at https://goo.gl/M6tgz8')
# Get the IP address that will be passed to the Echo during discovery
self.host_ip_addr = conf.get(CONF_HOST_IP)
if self.host_ip_addr is None:
self.host_ip_addr = util.get_local_ip()
_LOGGER.info(
"Listen IP address not specified, auto-detected address is %s",
self.host_ip_addr)
# Get the port that the Hue bridge will listen on
self.listen_port = conf.get(CONF_LISTEN_PORT)
if not isinstance(self.listen_port, int):
self.listen_port = DEFAULT_LISTEN_PORT
_LOGGER.info(
"Listen port not specified, defaulting to %s",
self.listen_port)
# Get whether or not UPNP binds to multicast address (239.255.255.250)
# or to the unicast address (host_ip_addr)
self.upnp_bind_multicast = conf.get(
CONF_UPNP_BIND_MULTICAST, DEFAULT_UPNP_BIND_MULTICAST)
# Get domains that cause both "on" and "off" commands to map to "on"
# This is primarily useful for things like scenes or scripts, which
# don't really have a concept of being off
self.off_maps_to_on_domains = conf.get(CONF_OFF_MAPS_TO_ON_DOMAINS)
if not isinstance(self.off_maps_to_on_domains, list):
self.off_maps_to_on_domains = DEFAULT_OFF_MAPS_TO_ON_DOMAINS
# Get whether or not entities should be exposed by default, or if only
# explicitly marked ones will be exposed
self.expose_by_default = conf.get(
CONF_EXPOSE_BY_DEFAULT, DEFAULT_EXPOSE_BY_DEFAULT)
# Get domains that are exposed by default when expose_by_default is
# True
self.exposed_domains = conf.get(
CONF_EXPOSED_DOMAINS, DEFAULT_EXPOSED_DOMAINS)
# Calculated effective advertised IP and port for network isolation
self.advertise_ip = conf.get(
CONF_ADVERTISE_IP) or self.host_ip_addr
self.advertise_port = conf.get(
CONF_ADVERTISE_PORT) or self.listen_port
self.entities = conf.get(CONF_ENTITIES, {})
def entity_id_to_number(self, entity_id):
"""Get a unique number for the entity id."""
if self.type == TYPE_ALEXA:
return entity_id
if self.numbers is None:
self.numbers = _load_json(self.hass.config.path(NUMBERS_FILE))
# Google Home
for number, ent_id in self.numbers.items():
if entity_id == ent_id:
return number
number = '1'
if self.numbers:
number = str(max(int(k) for k in self.numbers) + 1)
self.numbers[number] = entity_id
save_json(self.hass.config.path(NUMBERS_FILE), self.numbers)
return number
def number_to_entity_id(self, number):
"""Convert unique number to entity id."""
if self.type == TYPE_ALEXA:
return number
if self.numbers is None:
self.numbers = _load_json(self.hass.config.path(NUMBERS_FILE))
# Google Home
assert isinstance(number, str)
return self.numbers.get(number)
def get_entity_name(self, entity):
"""Get the name of an entity."""
if entity.entity_id in self.entities and \
CONF_ENTITY_NAME in self.entities[entity.entity_id]:
return self.entities[entity.entity_id][CONF_ENTITY_NAME]
return entity.attributes.get(ATTR_EMULATED_HUE_NAME, entity.name)
def is_entity_exposed(self, entity):
"""Determine if an entity should be exposed on the emulated bridge.
Async friendly.
"""
if entity.attributes.get('view') is not None:
# Ignore entities that are views
return False
domain = entity.domain.lower()
explicit_expose = entity.attributes.get(ATTR_EMULATED_HUE, None)
explicit_hidden = entity.attributes.get(ATTR_EMULATED_HUE_HIDDEN, None)
if entity.entity_id in self.entities and \
CONF_ENTITY_HIDDEN in self.entities[entity.entity_id]:
explicit_hidden = \
self.entities[entity.entity_id][CONF_ENTITY_HIDDEN]
if explicit_expose is True or explicit_hidden is False:
expose = True
elif explicit_expose is False or explicit_hidden is True:
expose = False
else:
expose = None
get_deprecated(entity.attributes, ATTR_EMULATED_HUE_HIDDEN,
ATTR_EMULATED_HUE, None)
domain_exposed_by_default = \
self.expose_by_default and domain in self.exposed_domains
# Expose an entity if the entity's domain is exposed by default and
# the configuration doesn't explicitly exclude it from being
# exposed, or if the entity is explicitly exposed
is_default_exposed = \
domain_exposed_by_default and expose is not False
return is_default_exposed or expose
def _load_json(filename):
"""Wrapper, because we actually want to handle invalid json."""
try:
return load_json(filename)
except HomeAssistantError:
pass
return {}
| {
"content_hash": "bd407d3ab3bb91a42488aa09bb07d369",
"timestamp": "",
"source": "github",
"line_count": 296,
"max_line_length": 79,
"avg_line_length": 35.604729729729726,
"alnum_prop": 0.6494923617041465,
"repo_name": "PetePriority/home-assistant",
"id": "07ecb9d265a98d42bd04250ed0822b8cc341f6d7",
"size": "10539",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "homeassistant/components/emulated_hue/__init__.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1175"
},
{
"name": "Dockerfile",
"bytes": "1073"
},
{
"name": "Python",
"bytes": "13985647"
},
{
"name": "Ruby",
"bytes": "745"
},
{
"name": "Shell",
"bytes": "17364"
}
],
"symlink_target": ""
} |
#pragma once
#include <boost/test/included/unit_test.hpp>
using boost::unit_test_framework::test_suite;
#ifdef XML_BACKEND
#include "XMLDocument.h"
using namespace Oak;
void test_OpenXMLDoc()
{
XML::Document document1;
BOOST_CHECK(document1.isNull());
BOOST_REQUIRE(document1.load(std::string(RESOURCE_PATH)+"test_doc.xml"));
BOOST_CHECK(!document1.isNull());
XML::Document document2 = document1;
BOOST_CHECK(document1 == document2);
document2 = XML::Document();
document2.clone(document1);
BOOST_CHECK(document1 != document2);
}
test_suite* Test_XMLDoc()
{
test_suite* test = BOOST_TEST_SUITE( "XMLDoc" );
test->add(BOOST_TEST_CASE(&test_OpenXMLDoc));
return test;
}
#endif XML_BACKEND
| {
"content_hash": "e0bdaa1abb89e483d53d7e69891e9e53",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 77,
"avg_line_length": 17.904761904761905,
"alnum_prop": 0.6848404255319149,
"repo_name": "MNL82/oakmodelview",
"id": "c39621a0d99a1f794e0808da212ce5fe979b30ac",
"size": "1105",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Lib/TestOakModel/Test_XMLDoc.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "980"
},
{
"name": "C++",
"bytes": "965270"
},
{
"name": "QMake",
"bytes": "18126"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:duration="550"
android:propertyName="pathData"
android:valueFrom="@string/nine_path"
android:valueTo="@string/eight_path"
android:valueType="pathType"/>
</set> | {
"content_hash": "cf0d0b41552ab2bc077193b93f7bd58a",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 64,
"avg_line_length": 36.77777777777778,
"alnum_prop": 0.6586102719033232,
"repo_name": "BorislavKamenov/morpher",
"id": "1937ee7638c89702d89cbd2e4a77fabcae7f47ea",
"size": "331",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "morpher/src/main/res/animator/nine_to_eight_object_animator.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "15889"
}
],
"symlink_target": ""
} |
<?php
namespace Task;
class TaskSearchHelperNEW
{
private $taskSearchHelperDA;
/**
* Master array holds:
* - tag This is the tag seen in the task comments
* - task This is the tag title
* - user This is the user name
* - page This is the page to search for (where to start looking in the database = quantity * page)
* - quantity This is the quantity to receive back
* - sortBy This is ascending (1) or descending (0)
* - wildCard This is a string that we will try and find anywhere in the database
*
* Tag, task and user have the option to set whether you are searching by id (0) or by string (1)
*
* The array will look something like this
*
* $masterArray = array(
* $tag = array (value = "hoursAdded",
* searchBy = 1),
* $task = array(value = 120,
* searchBy = 0),
* $dateFrom = STILL WORKING THIS OUT,
* sortBy = 1
* );
*
* @var array
*/
private $primarySearchData = array();
private $searchFilters = array();
/* ARRAY VALUES
*
* This is to allow for easy naming and to hopefully reduce typos throughout the code
*/
private $ref_tag = 'tag';
private $ref_task = 'task';
private $ref_user = 'member';
private $ref_wildCard = 'wildCard';
private $ref_value = 'value';
private $ref_searchById = 'searchById';
private $ref_page = 'page';
private $ref_quantity = 'quantity';
private $ref_sortByDesc = 'sortByDesc';
/**
* Constructor
*/
function __construct()
{
$this->taskSearchHelperDA = new TaskSearchHelperDA();
}
/**
* Sets the database PDO object
*
* @param unknown $database
*/
public function setDatabase($database)
{
$this->taskSearchHelperDA->setDatabase($database);
}
/**
* Sets the tag you want to search for
*
* @param string || int $value
* @param boolean $searchById
*/
public function setTag($value, $searchById)
{
$this->primarySearchData[$this->ref_tag][$this->ref_value] = $value;
$this->primarySearchData[$this->ref_tag][$this->ref_searchById] = $searchById;
}
/**
* Sets the task you want to seach for
*
* @param string || int $value
* @param boolean $searchById
*/
public function setTask($value, $searchById)
{
$this->primarySearchData[$this->ref_task][$this->ref_value] = $value;
$this->primarySearchData[$this->ref_task][$this->ref_searchById] = $searchById;
}
/**
* Sets the user you want to seach for
*
* @param string || int $value
* @param boolean $searchById
*/
public function setUser($value, $searchById)
{
$this->primarySearchData[$this->ref_user][$this->ref_value] = $value;
$this->primarySearchData[$this->ref_user][$this->ref_searchById] = $searchById;
}
/**
* Sets a customer where clause for the query
*
* @param unknown $name
* @param unknown $value
* @param unknown $searchById
*/
public function setCustomWhere($name, $value, $searchById)
{
$this->primarySearchData[$name][$this->ref_value] = $value;
$this->primarySearchData[$name][$this->ref_searchById] = $searchById;
}
/**
* Sets the page you want to search for
*
* @param int $value
*/
public function setPage($value)
{
$this->searchFilters[$this->ref_page] = $value;
}
/**
* Sets how many rows to search for
*
* @param int $value
*/
public function setQuantity($value)
{
$this->searchFilters[$this->ref_quantity] = $value;
}
/**
* Sets whether you want to sort the response by ascending or descending
*
* @param boolean $sortByDesc
*/
public function setSortByDesc($sortByDesc)
{
$this->searchFilters[$this->ref_sortByDesc] = $sortByDesc;
}
/**
* A general search function
*
* Will try and find this string in the tag, task and user
*
* @param string $stringToFind
*/
public function justFindThisAnywhere($stringToFind)
{
$this->master[$this->ref_wildCard] = $stringToFind;
}
/**
* Removes the tag from the search query
*/
public function removeTag()
{
if(isset($this->primarySearchData[$this->ref_tag]))
{
unset($this->primarySearchData[$this->ref_tag]);
}
}
/**
* Removes the task from the search query
*/
public function removeTask()
{
if(isset($this->primarySearchData[$this->ref_task]))
{
unset($this->primarySearchData[$this->ref_task]);
}
}
/**
* Removes the user from the search query
*/
public function removeUser()
{
if(isset($this->primarySearchData[$this->ref_user]))
{
unset($this->primarySearchData[$this->ref_user]);
}
}
/**
* Removes the end date from the search query
*/
public function removePage()
{
if(isset($this->searchFilters[$this->ref_page]))
{
unset($this->searchFilters[$this->ref_page]);
}
}
/**
* Removes the start and end date from the search query
*/
public function removeQuantity()
{
if(isset($this->searchFilters[$this->ref_quantity]))
{
unset($this->searchFilters[$this->ref_quantity]);
}
}
/**
* Removes the the wild card string from the search query
*/
public function removeFindThisAnywhere()
{
if(isset($this->masterArray[$this->ref_wildCard]))
{
unset($this->masterArray[$this->ref_wildCard]);
}
}
/**
* Gets the tag, returns false if the tag is not set
*/
public function getTag()
{
if(isset($this->primarySearchData[$this->ref_tag]))
{
return $this->primarySearchData[$this->ref_tag];
}else
{
return false;
}
}
/**
* Gets the task
*/
public function getTask()
{
return $this->primarySearchData[$this->ref_task];
}
/**
* Gets the user
*/
public function getUser()
{
return $this->primarySearchData[$this->ref_user];
}
/**
* Gets the page
*/
public function getPage()
{
return $this->searchFilters[$this->ref_page];
}
/**
* Gets the quantity
*/
public function getQuantity()
{
return $this->searchFilters[$this->ref_quantity];
}
/**
* Gets the wild card
*/
public function getWildCard()
{
return $this->masterArray[$this->ref_wildCard];
}
/**
* Returns true if the value is set
*
* @return boolean
*/
private function valueIsSet($firstLevel, $secondLevel)
{
if($secondLevel === false)
{
if(isset($this->masterArray[$firstLevel]))
{
return true;
}else
{
return false;
}
}else
{
if(isset($this->masterArray[$firstLevel][$secondLevel]))
{
return true;
}else
{
return false;
}
}
}
/**
* Search
*/
public function search($searchOption)
{
$this->setSearchFilters();
$response = $this->taskSearchHelperDA->performSearch($searchOption, $this->primarySearchData);
return $response;
}
/**
* Search for tags
*/
private function searchForTags()
{
/* SET THE PRIMARY TABLE */
$this->taskSearchHelperDA->setPrimarySearch($this->ref_tag, $this->primarySearchData[$this->ref_tag]);
/* CHECK IF WE ARE SEARCHING FOR TAGS IN A SPECIFIC TASK */
if(isset($this->primarySearchData[$this->ref_task]))
{
$this->taskSearchHelperDA->addSearchCriteria($this->ref_task, $this->getTask());
}
/* CHECK IF WE ARE SEARCHING FOR TAGS FROM A SPECIFIC USER */
if(isset($this->primarySearchData[$this->ref_user]))
{
$this->taskSearchHelperDA->addSearchCriteria($this->ref_user, $this->getUser());
}
}
/**
* Search for tasks
*/
private function searchForTasks()
{
/* SET THE PRIMARY TABLE */
$this->taskSearchHelperDA->setPrimarySearch($this->ref_task, $this->primarySearchData[$this->ref_task]);
/* CHECK IF WE ARE SEARCHING FOR TASKS THAT A SPECIFIC USER IS A PART OF */
if(isset($this->primarySearchData[$this->ref_user]))
{
$this->taskSearchHelperDA->addSearchCriteria($this->getUser());
}
}
/**
* Sets the search filters for the taskSearchHelperDA object
*/
private function setSearchFilters()
{
if(sizeof($this->searchFilters) > 0)
{
$this->taskSearchHelperDA->setSearchFilters($this->searchFilters);
}
}
/**
* Creates an array that holds information about the error
*
* @return string
*/
public function createError($comment, $attributeThatErrored)
{
$errorMessage = array();
$errorMessage['success'] = false;
$errorMessage['error']['location'] = $attributeThatErrored;
$errorMessage['error']['message'] = $comment;
return $errorMessage;
}
} | {
"content_hash": "d46134000d2646aa86c3d892c3fd6cec",
"timestamp": "",
"source": "github",
"line_count": 387,
"max_line_length": 106,
"avg_line_length": 21.356589147286822,
"alnum_prop": 0.6465819721718088,
"repo_name": "HexagonSystems/website",
"id": "8fee8056e36418fc08b8580c5970efc34123c6a9",
"size": "8265",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "App/Package/Task/Model/TaskSearchHelperNEW.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "696411"
},
{
"name": "JavaScript",
"bytes": "104103"
},
{
"name": "PHP",
"bytes": "396262"
},
{
"name": "Perl",
"bytes": "398"
}
],
"symlink_target": ""
} |
/* tslint:disable */
require('reflect-metadata');
import http = require("http");
import express = require("express");
var bodyParser = require("body-parser");
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
import * as config from './config';
import * as securityConfig from './security-config';
import {router} from './core/exports';
import {repositoryMap} from './core/exports';
import {Container} from './di';
import * as data from './mongoose';
//---------sequelize setting-----------------------------
import * as seqData from "./sequelizeimp";
var Main = require('./core');
Main(config, securityConfig, __dirname, data.entityServiceInst, seqData.sequelizeService);
//var Main = require('./core')(config, securityConfig, __dirname, data.entityServiceInst, seqData.sequelizeService);
data.connect();
data.generateSchema();
seqData.sequelizeService.connect();
seqData.generateSchema();
var app = express();
Main.register(app);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(require('morgan')('combined'));
app.use(require('cookie-parser')());
var expressSession = require('express-session');
app.use(expressSession({ secret: 'mySecretKey', resave: false, saveUninitialized: false }));
app.use(bodyParser.json());
app.use(passport.initialize());
app.use(passport.session());
app.use("/", router);
var server = (<any>http).createServer(app);
server.listen(23548);
| {
"content_hash": "bdbbdb06dca9d0f2fff5cf29c76e7f8b",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 116,
"avg_line_length": 38.026315789473685,
"alnum_prop": 0.7038062283737024,
"repo_name": "asishsahoo/Node-Data",
"id": "faba9eecfb01c0cb0e043743cdcab6037918b8c0",
"size": "1447",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "server.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1206"
},
{
"name": "JavaScript",
"bytes": "3125"
},
{
"name": "TypeScript",
"bytes": "413566"
}
],
"symlink_target": ""
} |
module.exports = {
root: true,
parser: 'babel-eslint',
parserOptions: {
sourceType: 'module'
},
env: {
browser: true
},
// https://github.com/feross/standard/blob/master/RULES.md#javascript-standard-style
extends: 'standard',
// required to lint *.wpy files
plugins: [
'html'
],
settings: {
'html/html-extensions': ['.html', '.wpy']
},
// add your custom rules here
'rules': {
// allow paren-less arrow functions
'arrow-parens': 0,
// allow async-await
'generator-star-spacing': 0,
"semi": [ "warn", "always" ],
"no-multi-spaces": 0,
'padded-blocks': 0,
//'indent': ['error', 2],
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0,
'space-before-function-paren': 0
}
}
| {
"content_hash": "33f04e56d40b1f0f69c408f02d58f00c",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 86,
"avg_line_length": 25.484848484848484,
"alnum_prop": 0.5707491082045184,
"repo_name": "bbxyard/bbxyard",
"id": "1f9b5eca85ffcdc262d006fe10373c862942c7dc",
"size": "841",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "yard/skills/36-wx/wepy-demo/.eslintrc.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7428641"
},
{
"name": "C++",
"bytes": "83747"
},
{
"name": "CMake",
"bytes": "41295"
},
{
"name": "CSS",
"bytes": "301801"
},
{
"name": "Dockerfile",
"bytes": "5878"
},
{
"name": "FreeMarker",
"bytes": "390"
},
{
"name": "Go",
"bytes": "671497"
},
{
"name": "HTML",
"bytes": "286756"
},
{
"name": "Hack",
"bytes": "3607"
},
{
"name": "Java",
"bytes": "657537"
},
{
"name": "JavaScript",
"bytes": "4256151"
},
{
"name": "Jupyter Notebook",
"bytes": "4216"
},
{
"name": "Makefile",
"bytes": "201213"
},
{
"name": "PHP",
"bytes": "17097"
},
{
"name": "PLpgSQL",
"bytes": "1527"
},
{
"name": "Python",
"bytes": "174912"
},
{
"name": "Shell",
"bytes": "49630"
},
{
"name": "Smarty",
"bytes": "140501"
},
{
"name": "TSQL",
"bytes": "39860"
},
{
"name": "TypeScript",
"bytes": "209250"
},
{
"name": "Vue",
"bytes": "1169665"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "934e56d5da2bd6e3b4c0bcaf39398569",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "edee9745caeb84178b391165b923b0254142c61c",
"size": "176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Scrophulariaceae/Herpestis/Herpestis laxiflora/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
Working With Entities
#####################
CodeIgniter supports Entity classes as a first-class citizen in it's database layer, while keeping
them completely optional to use. They are commonly used as part of the Repository pattern, but can
be used directly with the :doc:`Model </database/model>` if that fits your needs better.
.. contents:: Page Contents
:local:
Entity Usage
============
At its core, an Entity class is simply a class that represents a single database row. It has class properties
to represent the database columns, and provides any additional methods to implement the business logic for
that row. The core feature, though, is that it doesn't know anything about how to persist itself. That's the
responsibility of the model or the repository class. That way, if anything changes on how you need to save the
object, you don't have to change how that object is used throughout the application. This makes it possible to
use JSON or XML files to store the objects during a rapid prototyping stage, and then easily switch to a
database when you've proven the concept works.
Lets walk through a very simple User Entity and how we'd work with it to help make things clear.
Assume you have a database table named ``users`` that has the following schema::
id - integer
username - string
email - string
password - string
created_at - datetime
Create the Entity Class
-----------------------
Now create a new Entity class. Since there's no default location to store these classes, and it doesn't fit
in with the existing directory structure, create a new directory at **application/Entities**. Create the
Entity itself at **application/Entities/User.php**.
::
<?php namespace App\Entities;
use CodeIgniter\Entity;
class User extends Entity
{
protected $id;
protected $username;
protected $email;
protected $password;
protected $created_at;
protected $updated_at;
}
At its simplest, this is all you need to do, though we'll make it more useful in a minute. Note that all of the
database columns are represented in the Entity. This is required for the Model to populate the fields.
Create the Model
----------------
Create the model first at **application/Models/UserModel.php** so that we can interact with it::
<?php namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $allowedFields = [
'username', 'email', 'password'
];
protected $returnType = 'App\Entities\User';
protected $useTimestamps = true;
}
The model uses the ``users`` table in the database for all of its activities. We've set the ``$allowedFields`` property
to include all of the fields that we want outside classes to change. The ``id``, ``created_at``, and ``updated_at`` fields
are handled automatically by the class or the database, so we don't want to change those. Finally, we've set our Entity
class as the ``$returnType``. This ensures that all methods on the model that return rows from the database will return
instances of our User Entity class instead of an object or array like normal.
Working With the Entity Class
-----------------------------
Now that all of the pieces are in place, you would work with the Entity class as you would any other class::
$user = $userModel->find($id);
// Display
echo $user->username;
echo $user->email;
// Updating
unset($user->username);
if (! isset($user->username)
{
$user->username = 'something new';
}
$userModel->save($user);
// Create
$user = new App\Entities\User();
$user->username = 'foo';
$user->email = 'foo@example.com';
$userModel->save($user);
You may have noticed that the User class has all of the properties as **protected** not **public**, but you can still
access them as if they were public properties. The base class, **CodeIgniter\Entity**, takes care of this for you, as
well as providing the ability to check the properties with **isset()**, or **unset()** the property.
When the User is passed to the model's **save()** method, it automatically takes care of reading the protected properties
and saving any changes to columns listed in the model's **$allowedFields** property. It also knows whether to create
a new row, or update an existing one.
Filling Properties Quickly
--------------------------
The Entity class also provides a method, ``fill()`` that allows you to shove an array of key/value pairs into the class
and populate the class properties. Only properties that already exist on the class can be populated in this way.
::
$data = $this->request->getPost();
$user = new App\Entities\User();
$user->fill($data);
$userModel->save($user);
Handling Business Logic
=======================
While the examples above are convenient, they don't help enforce any business logic. The base Entity class implements
some smart ``__get()`` and ``__set()`` methods that will check for special methods and use those instead of using
the class properties directly, allowing you to enforce any business logic or data conversion that you need.
Here's an updated User entity to provide some examples of how this could be used::
<?php namespace App\Entities;
use CodeIgniter\Entity;
class User extends Entity
{
protected $id;
protected $username;
protected $email;
protected $password;
protected $created_at;
protected $updated_at;
public function setPassword(string $pass)
{
$this->password = password_hash($pass, PASSWORD_BCRYPT);
return $this;
}
public function setCreatedAt(string $dateString)
{
$this->created_at = new \DateTime($datetime, new \DateTimeZone('UTC'));
return $this;
}
public function getCreatedAt(string $format = 'Y-m-d H:i:s')
{
$timezone = isset($this->timezone)
? $this->timezone
: app_timezone();
$this->created_at->setTimezone($timezone);
return $format === true
? $this->created_at
: $this->created_at->format($format);
}
}
The first thing to notice is the name of the methods we've added. For each one, the class expects the snake_case
column name to be converted into PascalCase, and prefixed with either ``set`` or ``get``. These methods will then
be automatically called whenever you set or retrieve the class property using the direct syntax (i.e. $user->email).
The methods do not need to be public unless you want them accessed from other classes. For example, the ``created_at``
class property will be access through the ``setCreatedAt()`` and ``getCreatedAt()`` methods.
In the ``setPassword()`` method we ensure that the password is always hashed.
In ``setCreatedOn()`` we convert the string we receive from the model into a DateTime object, ensuring that our timezone
is UTC so we can easily convert the the viewer's current timezone. In ``getCreatedAt()``, it converts the time to
a formatted string in the application's current timezone.
While fairly simple, these examples show that using Entity classes can provide a very flexible way to enforce
business logic and create objects that are pleasant to use.
::
// Auto-hash the password - both do the same thing
$user->password = 'my great password';
$user->setPassword('my great password');
Data Mapping
============
At many points in your career, you will run into situations where the use of an application has changed and the
original column names in the database no longer make sense. Or you find that your coding style prefers camelCase
class properties, but your database schema required snake_case names. These situations can be easily handled
with the Entity class' data mapping features.
As an example, imagine your have the simplified User Entity that is used throughout your application::
<?php namespace App\Entities;
use CodeIgniter\Entity;
class User extends Entity
{
protected $id;
protected $name; // Represents a username
protected $email;
protected $password;
protected $created_at;
protected $updated_at;
}
Your boss comes to you and says that no one uses usernames anymore, so you're switching to just use emails for login.
But they do want to personalize the application a bit, so they want you to change the name field to represent a user's
full name now, not their username like it does currently. To keep things tidy and ensure things continue making sense
in the database you whip up a migration to rename the `name` field to `full_name` for clarity.
Ignoring how contrived this example is, we now have two choices on how to fix the User class. We could modify the class
property from ``$name`` to ``$full_name``, but that would require changes throughout the application. Instead, we can
simply map the ``full_name`` column in the database to the ``$name`` property, and be done with the Entity changes::
<?php namespace App\Entities;
use CodeIgniter\Entity;
class User extends Entity
{
protected $id;
protected $name; // Represents a full name now
protected $email;
protected $password;
protected $created_at;
protected $updated_at;
protected $_options = [
'datamap' => [
'full_name' => 'name'
]
];
}
By adding our new database name to the ``$datamap`` array, we can tell the class what class property the database column
should be accessible through. The key of the array is the name of the column in the database, where the value in the array
is class property to map it to.
In this example, when the model sets the ``full_name`` field on the User class, it actually assigns that value to the
class' ``$name`` property, so it can be set and retrieved through ``$user->name``. The value will still be accessible
through the original ``$user->full_name``, also, as this is needed for the model to get the data back out and save it
to the database. However, ``unset`` and ``isset`` only work on the mapped property, ``$name``, not on the original name,
``full_name``.
Mutators
========
Date Mutators
-------------
By default, the Entity class will convert fields named `created_at`, `updated_at`, or `deleted_at` into
:doc:`Time </libraries/time>` instances whenever they are set or retrieved. The Time class provides a large number
of helpful methods in a immutable, localized way.
You can define which properties are automatically converted by adding the name to the **options['dates']** array::
<?php namespace App\Entities;
use CodeIgniter\Entity;
class User extends Entity
{
protected $id;
protected $name; // Represents a full name now
protected $email;
protected $password;
protected $created_at;
protected $updated_at;
protected $_options = [
'dates' => ['created_at', 'updated_at', 'deleted_at'],
];
}
Now, when any of those properties are set, they will be converted to a Time instance, using the application's
current timezone, as set in **application/Config/App.php**::
$user = new App\Entities\User();
// Converted to Time instance
$user->created_at = 'April 15, 2017 10:30:00';
// Can now use any Time methods:
echo $user->created_at->humanize();
echo $user->created_at->setTimezone('Europe/London')->toDateString();
Property Casting
----------------
You can specify that properties in your Entity should be converted to common data types with the **casts** entry in
the **$_options** property. The **casts** option should be an array where the key is the name of the class property,
and the value is the data type it should be cast to. Casting only affects when values are read. No conversions happen
that affect the permanent value in either the entity or the database. Properties can be cast to any of the following
data types: **integer**, **float**, **double**, **string**, **boolean**, **object**, **array**, **datetime**, and
**timestamp**.
For example, if you had a User entity with an **is_banned** property, you can cast it as a boolean::
<?php namespace App\Entities;
use CodeIgniter\Entity;
class User extends Entity
{
protected $is_banned;
protected $_options = [
'casts' => [
'is_banned' => 'boolean'
]
];
}
Array Casting
-------------
Array casting is especially useful with fields that store serialized arrays or json in them. When cast as an array,
they will automatically be unserialized when you read the property's value. Unlike the rest of the data types that
you can cast properties into, the **array** cast type will serialize the value whenever the property is set::
<?php namespace App\Entities;
use CodeIgniter\Entity;
class User extends Entity
{
protected $options;
protected $_options = [
'casts' => [
'options' => 'array'
]
];
}
$user = $userModel->find(15);
$options = $user->options;
$options['foo'] = 'bar';
$user->options = $options;
$userModel->save($user);
| {
"content_hash": "4e26065f0ecb10f13499fe80740cbf80",
"timestamp": "",
"source": "github",
"line_count": 361,
"max_line_length": 122,
"avg_line_length": 37.46260387811634,
"alnum_prop": 0.678645371191955,
"repo_name": "JakeAi/MinnichRW",
"id": "b85eb8cae809ff21e4e4bbf4716052f8aeb9eff3",
"size": "13546",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "user_guide_src/source/database/entities.rst",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "143163"
},
{
"name": "HTML",
"bytes": "43514"
},
{
"name": "JavaScript",
"bytes": "324797"
},
{
"name": "Makefile",
"bytes": "4808"
},
{
"name": "PHP",
"bytes": "3115963"
},
{
"name": "PLSQL",
"bytes": "1411"
},
{
"name": "Python",
"bytes": "11560"
}
],
"symlink_target": ""
} |
<?php
/**
* Model
*
* Extension of the Model class with DB access methods.
*/
namespace AFX\DbFilter;
use Base\App;
use Base\MVC\Model\DbModel;
class Model extends DbModel
{
// Overload $db
// Overload $table
// Primary key
protected $primaryKey;
// Field order
protected $order = null;
// Generates a new Filter for operating on rows in the table
function filter ($key, $value)
{
// Return DB Filter
$f = new Filter($this->db, $this->table);
return $f->filter($key, $value);
}
// Adds a new row to the table
function add ($data)
{
$q = 'INSERT INTO `%s` (%s) VALUES (%s)';
list($keys, $values, $params) = $this->parseInsertRow($data);
$query = sprintf($q, $this->table, $keys, $values);
$q = $this->db->sql($query);
return $q->execute($params);
}
// Generates parts for an INSERT row from a data set
protected function parseInsertRow ($data)
{
$keys = '';
$values = '';
$params = [];
foreach ($data as $key => $value)
{
if (strlen($values) > 0)
{
$keys .= ',';
$values .= ',';
}
$keys .= sprintf('`%s`', $key);
if (is_array($value))
{
if (isset($value[0]))
{
// SQL Expression
$values .= current($value);
}
else
{
// Expression with prepared segment
$values .= key($value);
$params = array_merge($params, current($value));
}
}
else
{
$values .= '?';
$params[] = $value;
}
}
return [$keys, $values, $params];
}
// Removes an entry based on the primary key
function delete ($key)
{
$q = $this->db->sql(sprintf('DELETE FROM `%s` WHERE `%s` = ?', $this->table, $this->primaryKey));
return $q->execute([$key]);
}
// Returns a single row from the table matching a primary key
function get ($id)
{
$q = $this->db->sql(sprintf('SELECT * FROM `%s` WHERE `%s` = ? LIMIT 1', $this->table, $this->primaryKey));
if ($q->execute([$id]))
{
return new Result($q->fetch(\PDO::FETCH_ASSOC));
}
else
{
return false;
}
}
// Sets result set data for updating
function set ($id, $data)
{
$updateValues = [];
$updates = '';
foreach ($data as $key => $value)
{
if ($updates !== '')
{
$updates .= ',';
}
if (is_array($value))
{
if (isset($value[0]))
{
$updates .= sprintf('`%s` = %s', $key, current($value));
}
else
{
$updates .= key($value);
$updateValues[] = current($value);
}
}
else
{
$updates .= sprintf('`%s` = ?', $key);
$updateValues[] = $value;
}
}
$q = $this->db->sql(sprintf('UPDATE `%s` SET %s WHERE `%s` = ?', $this->table, $updates, $this->primaryKey));
return $q->execute(array_merge($updateValues, [$id]));
}
// Sets a viewport for retrieving entries in the table
function display ($rowCount, $page)
{
$this->display = [$page * $rowCount, $rowCount];
return $this;
}
// Sets the field order for retrieving entries in the table
function order ($key, $asc)
{
$this->order = [$key, $asc];
return $this;
}
// Returns all rows in the table
function rows ()
{
if ($this->display !== null)
{
$q = $this->db->sql(sprintf('SELECT * FROM `%s` %s LIMIT %d, %d', $this->table, $this->orderString(), $this->display[0], $this->display[1]));
}
else
{
$q = $this->db->sql(sprintf('SELECT * FROM `%s` %s', $this->table, $this->orderString()));
}
if ($q->execute())
{
return $q->fetchAll();
}
else
{
return false;
}
}
// Returns a count of all rows in the table
function rowCount ()
{
$q = $this->db->sql(sprintf('SELECT COUNT(*) as row_count FROM `%s`', $this->table));
if ($q->execute())
{
return (int)$q->fetch(\PDO::FETCH_ASSOC)['row_count'];
}
else
{
return false;
}
}
// Generates the ORDER BY clause in an SQL statement
protected function orderString ()
{
if ($this->order == null)
{
return '';
}
else
{
return sprintf('ORDER BY `%s` %s', $this->order[0], $this->order[1]);
}
}
} | {
"content_hash": "4e15540cbebce22e9423185372e595bc",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 144,
"avg_line_length": 21.448453608247423,
"alnum_prop": 0.5337659216534487,
"repo_name": "todd-x86/appframelite",
"id": "f3ec7d22a012f0ededc314a43dd3eb416241b365",
"size": "4161",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "vendor/AFX/DbFilter/Model.class.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "83667"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "67fb4942ae1cc375d99870ff6bbe016f",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "d2e8bf16ef3956d9533c024a61146d78675ba75c",
"size": "171",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Boraginales/Boraginaceae/Cordia/Cordia meziana/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"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 throttle down OpenGL ES frame rates. 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 inactive 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": "f0cef57f17a92101aae52edde541ecbc",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 281,
"avg_line_length": 53.48571428571429,
"alnum_prop": 0.7863247863247863,
"repo_name": "muccy/MUKPullToRevealControl",
"id": "1251fae38054651712efd9bf02afe378556078d7",
"size": "2038",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/MUKPullToRevealControl/Classes/App Delegate/AppDelegate.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "56013"
},
{
"name": "Ruby",
"bytes": "1136"
}
],
"symlink_target": ""
} |
#ifndef Foundation_StreamChannel_INCLUDED
#define Foundation_StreamChannel_INCLUDED
#include "Poco/Foundation.h"
#include "Poco/Channel.h"
#include "Poco/Mutex.h"
#include <ostream>
namespace Poco {
class Foundation_API StreamChannel: public Channel
/// A channel that writes to an ostream.
///
/// Only the message's text is written, followed
/// by a newline.
///
/// Chain this channel to a FormattingChannel with an
/// appropriate Formatter to control what is contained
/// in the text.
{
public:
StreamChannel(std::ostream& str);
/// Creates the channel.
void log(const Message& msg);
/// Logs the given message to the channel's stream.
protected:
virtual ~StreamChannel();
private:
std::ostream& _str;
FastMutex _mutex;
};
} // namespace Poco
#endif // Foundation_StreamChannel_INCLUDED
| {
"content_hash": "498b620434c8b30b669b0775af6c108e",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 56,
"avg_line_length": 19.511111111111113,
"alnum_prop": 0.6765375854214123,
"repo_name": "Patrick-Bay/SocialCastr",
"id": "97614e5afa7ccd106b9154e5117e7f8f042b457a",
"size": "2567",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "third party/openRTMFP-Cumulus/CumulusLib/include/Poco/StreamChannel.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "1501010"
},
{
"name": "C",
"bytes": "3530600"
},
{
"name": "C++",
"bytes": "5191362"
},
{
"name": "CSS",
"bytes": "1765"
},
{
"name": "JavaScript",
"bytes": "77484"
},
{
"name": "PHP",
"bytes": "174258"
}
],
"symlink_target": ""
} |
#include "gtest/gtest.h"
#include <string>
#include "protocol_handler/protocol_handler.h"
#include "protocol_handler/protocol_handler_impl.h"
#include "protocol/bson_object_keys.h"
#include "protocol/common.h"
#include "protocol_handler/control_message_matcher.h"
#include "protocol_handler/mock_protocol_handler.h"
#include "protocol_handler/mock_protocol_observer.h"
#include "protocol_handler/mock_protocol_handler_settings.h"
#include "protocol_handler/mock_session_observer.h"
#include "connection_handler/mock_connection_handler.h"
#ifdef ENABLE_SECURITY
#include "security_manager/mock_security_manager.h"
#include "security_manager/mock_ssl_context.h"
#endif // ENABLE_SECURITY
#include "transport_manager/mock_transport_manager.h"
#include "utils/make_shared.h"
#include "utils/test_async_waiter.h"
#include <bson_object.h>
namespace test {
namespace components {
namespace protocol_handler_test {
// Id passed as NULL for new session establishing
#define NEW_SESSION_ID 0u
#define SESSION_START_REJECT 0u
// Protocol Handler Entities
using protocol_handler::ProtocolHandlerImpl;
using protocol_handler::ServiceType;
using protocol_handler::RawMessage;
using protocol_handler::RawMessagePtr;
using protocol_handler::PROTECTION_ON;
using protocol_handler::PROTECTION_OFF;
using protocol_handler::PROTOCOL_VERSION_1;
using protocol_handler::PROTOCOL_VERSION_2;
using protocol_handler::PROTOCOL_VERSION_3;
using protocol_handler::PROTOCOL_VERSION_4;
using protocol_handler::PROTOCOL_VERSION_5;
using protocol_handler::PROTOCOL_VERSION_MAX;
using protocol_handler::FRAME_TYPE_CONTROL;
using protocol_handler::FRAME_TYPE_SINGLE;
using protocol_handler::FRAME_TYPE_FIRST;
using protocol_handler::FRAME_TYPE_CONSECUTIVE;
using protocol_handler::FRAME_TYPE_MAX_VALUE;
using protocol_handler::MAXIMUM_FRAME_DATA_V2_SIZE;
using protocol_handler::FRAME_DATA_START_SERVICE;
using protocol_handler::FRAME_DATA_START_SERVICE_ACK;
using protocol_handler::FRAME_DATA_END_SERVICE_NACK;
using protocol_handler::FRAME_DATA_END_SERVICE_ACK;
using protocol_handler::FRAME_DATA_END_SERVICE;
using protocol_handler::FRAME_DATA_HEART_BEAT;
using protocol_handler::FRAME_DATA_HEART_BEAT_ACK;
using protocol_handler::FRAME_DATA_SERVICE_DATA_ACK;
using protocol_handler::FRAME_DATA_SINGLE;
using protocol_handler::FRAME_DATA_FIRST;
using protocol_handler::FRAME_DATA_LAST_CONSECUTIVE;
using protocol_handler::kRpc;
using protocol_handler::kControl;
using protocol_handler::kAudio;
using protocol_handler::kMobileNav;
using protocol_handler::kBulk;
using protocol_handler::kInvalidServiceType;
// For TM states
using transport_manager::TransportManagerListener;
using transport_manager::E_SUCCESS;
using transport_manager::DeviceInfo;
// For CH entities
using connection_handler::DeviceHandle;
// Google Testing Framework Entities
using ::testing::Return;
using ::testing::ReturnRefOfCopy;
using ::testing::ReturnNull;
using ::testing::An;
using ::testing::AnyOf;
using ::testing::ByRef;
using ::testing::DoAll;
using ::testing::SaveArg;
using ::testing::Eq;
using ::testing::_;
using ::testing::Invoke;
using ::testing::SetArgReferee;
using ::testing::SetArgPointee;
typedef std::vector<uint8_t> UCharDataVector;
// custom action to call a member function with 6 arguments
ACTION_P4(InvokeMemberFuncWithArg2, ptr, memberFunc, a, b) {
(ptr->*memberFunc)(a, b);
}
namespace {
const uint32_t kAsyncExpectationsTimeout = 10000u;
const uint32_t kMicrosecondsInMillisecond = 1000u;
const uint32_t kAddSessionWaitTimeMs = 100u;
}
class ProtocolHandlerImplTest : public ::testing::Test {
protected:
void InitProtocolHandlerImpl(const size_t period_msec,
const size_t max_messages,
bool malformed_message_filtering = false,
const size_t malformd_period_msec = 0u,
const size_t malformd_max_messages = 0u,
const int32_t multiframe_waiting_timeout = 0,
const size_t maximum_payload_size = 0u) {
ON_CALL(protocol_handler_settings_mock, maximum_payload_size())
.WillByDefault(Return(maximum_payload_size));
ON_CALL(protocol_handler_settings_mock, message_frequency_time())
.WillByDefault(Return(period_msec));
ON_CALL(protocol_handler_settings_mock, message_frequency_count())
.WillByDefault(Return(max_messages));
ON_CALL(protocol_handler_settings_mock, malformed_message_filtering())
.WillByDefault(Return(malformed_message_filtering));
ON_CALL(protocol_handler_settings_mock, malformed_frequency_time())
.WillByDefault(Return(malformd_period_msec));
ON_CALL(protocol_handler_settings_mock, malformed_frequency_count())
.WillByDefault(Return(malformd_max_messages));
ON_CALL(protocol_handler_settings_mock, multiframe_waiting_timeout())
.WillByDefault(Return(multiframe_waiting_timeout));
#ifdef ENABLE_SECURITY
ON_CALL(protocol_handler_settings_mock, force_protected_service())
.WillByDefault(ReturnRefOfCopy(force_protected_services));
ON_CALL(protocol_handler_settings_mock, force_unprotected_service())
.WillByDefault(ReturnRefOfCopy(force_unprotected_services));
#endif
protocol_handler_impl.reset(
new ProtocolHandlerImpl(protocol_handler_settings_mock,
session_observer_mock,
connection_handler_mock,
transport_manager_mock));
tm_listener = protocol_handler_impl.get();
}
void SetUp() OVERRIDE {
InitProtocolHandlerImpl(0u, 0u);
connection_id = 0xAu;
session_id = 0xFFu;
connection_key = 0xFF00AAu;
message_id = 0xABCDEFu;
some_data.resize(256, 0xAB);
// Expect ConnectionHandler support methods call (conversion, check
// heartbeat)
EXPECT_CALL(session_observer_mock, KeyFromPair(connection_id, _))
.
// Return some connection_key
WillRepeatedly(Return(connection_key));
EXPECT_CALL(session_observer_mock, IsHeartBeatSupported(connection_id, _))
.
// Return false to avoid call KeepConnectionAlive
WillRepeatedly(Return(false));
}
void TearDown() OVERRIDE {
const_cast<protocol_handler::impl::FromMobileQueue&>(
protocol_handler_impl->get_from_mobile_queue()).WaitDumpQueue();
const_cast<protocol_handler::impl::ToMobileQueue&>(
protocol_handler_impl->get_to_mobile_queue()).WaitDumpQueue();
}
// Emulate connection establish
void AddConnection() {
tm_listener->OnConnectionEstablished(DeviceInfo(DeviceHandle(1u),
std::string("mac"),
std::string("name"),
std::string("BTMAC")),
connection_id);
}
protocol_handler::SessionContext GetSessionContext(
const transport_manager::ConnectionUID connection_id,
const uint8_t initial_session_id,
const uint8_t new_session_id,
const protocol_handler::ServiceType service_type,
const uint32_t hash_id,
const bool protection_flag) {
return protocol_handler::SessionContext(connection_id,
initial_session_id,
new_session_id,
service_type,
hash_id,
protection_flag);
}
void AddSession(const ::utils::SharedPtr<TestAsyncWaiter>& waiter,
uint32_t& times) {
using namespace protocol_handler;
ASSERT_TRUE(NULL != waiter.get());
AddConnection();
const ServiceType start_service = kRpc;
#ifdef ENABLE_SECURITY
// For enabled protection callback shall use protection ON
const bool callback_protection_flag = PROTECTION_ON;
#else
// For disabled protection callback shall ignore protection income flad and
// use protection OFF
const bool callback_protection_flag = PROTECTION_OFF;
#endif // ENABLE_SECURITY
const protocol_handler::SessionContext context =
GetSessionContext(connection_id,
NEW_SESSION_ID,
session_id,
start_service,
HASH_ID_WRONG,
callback_protection_flag);
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
start_service,
callback_protection_flag,
An<const BsonObject*>()))
.
// Return sessions start success
WillOnce(DoAll(
NotifyTestAsyncWaiter(waiter),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
context,
ByRef(empty_rejected_param_))));
times++;
// Expect send Ack with PROTECTION_OFF (on no Security Manager)
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK,
PROTECTION_OFF)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS)));
times++;
SendControlMessage(
PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
usleep(kAddSessionWaitTimeMs * kMicrosecondsInMillisecond);
}
#ifdef ENABLE_SECURITY
// Emulate security manager initilization establish
void AddSecurityManager() {
protocol_handler_impl->set_security_manager(&security_manager_mock);
}
#endif // ENABLE_SECURITY
void SendTMMessage(uint8_t connection_id,
uint8_t version,
bool protection,
uint8_t frameType,
uint8_t serviceType,
uint8_t frameData,
uint8_t sessionId,
uint32_t dataSize,
uint32_t messageID,
const uint8_t* data = 0) {
// Create packet
const ProtocolPacket packet(connection_id,
version,
protection,
frameType,
serviceType,
frameData,
sessionId,
dataSize,
messageID,
data);
// Emulate receive packet from transoprt manager
tm_listener->OnTMMessageReceived(packet.serializePacket());
}
void SetProtocolVersion2() {
// Set protocol version 2
ON_CALL(protocol_handler_settings_mock, max_supported_protocol_version())
.WillByDefault(Return(PROTOCOL_VERSION_2));
}
void SendControlMessage(bool protection,
uint8_t service_type,
uint8_t sessionId,
uint32_t frame_data,
uint32_t dataSize = 0u,
const uint8_t* data = NULL) {
SendTMMessage(connection_id,
PROTOCOL_VERSION_3,
protection,
FRAME_TYPE_CONTROL,
service_type,
frame_data,
sessionId,
dataSize,
message_id,
data);
}
testing::NiceMock<MockProtocolHandlerSettings> protocol_handler_settings_mock;
::utils::SharedPtr<ProtocolHandlerImpl> protocol_handler_impl;
TransportManagerListener* tm_listener;
// Uniq connection
::transport_manager::ConnectionUID connection_id;
// Id of established session
uint8_t session_id;
// Uniq id as connection_id and session_id in one
uint32_t connection_key;
uint32_t message_id;
UCharDataVector some_data;
// Strict mocks (same as all methods EXPECT_CALL().Times(0))
testing::NiceMock<connection_handler_test::MockConnectionHandler>
connection_handler_mock;
testing::StrictMock<transport_manager_test::MockTransportManager>
transport_manager_mock;
testing::StrictMock<protocol_handler_test::MockSessionObserver>
session_observer_mock;
#ifdef ENABLE_SECURITY
testing::NiceMock<security_manager_test::MockSecurityManager>
security_manager_mock;
testing::NiceMock<security_manager_test::MockSSLContext> ssl_context_mock;
std::vector<int> force_protected_services;
std::vector<int> force_unprotected_services;
#endif // ENABLE_SECURITY
std::vector<std::string> empty_rejected_param_;
};
#ifdef ENABLE_SECURITY
class OnHandshakeDoneFunctor {
public:
OnHandshakeDoneFunctor(const uint32_t connection_key,
security_manager::SSLContext::HandshakeResult error)
: connection_key(connection_key), result(error) {}
void operator()(security_manager::SecurityManagerListener* listener) const {
listener->OnHandshakeDone(connection_key, result);
}
private:
const uint32_t connection_key;
const security_manager::SSLContext::HandshakeResult result;
};
#endif // ENABLE_SECURITY
/*
* ProtocolHandler shall skip empty message
*/
TEST_F(ProtocolHandlerImplTest, RecieveEmptyRawMessage) {
tm_listener->OnTMMessageReceived(RawMessagePtr());
}
/*
* ProtocolHandler shall disconnect on no connection
*/
TEST_F(ProtocolHandlerImplTest, RecieveOnUnknownConnection) {
EXPECT_CALL(transport_manager_mock, DisconnectForce(connection_id))
.WillOnce(Return(E_SUCCESS));
SendTMMessage(connection_id,
PROTOCOL_VERSION_3,
PROTECTION_OFF,
FRAME_TYPE_CONTROL,
kRpc,
FRAME_DATA_START_SERVICE,
NEW_SESSION_ID,
0,
message_id);
}
/*
* ProtocolHandler shall send NAck on session_observer rejection
* Check protection flag OFF for all services from kControl to kBulk
*/
TEST_F(ProtocolHandlerImplTest,
StartSession_Unprotected_SessionObserverReject) {
using namespace protocol_handler;
const int call_times = 5;
AddConnection();
TestAsyncWaiter waiter;
uint32_t times = 0;
ServiceType service_type;
// Expect ConnectionHandler check
EXPECT_CALL(
session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
AnyOf(kControl, kRpc, kAudio, kMobileNav, kBulk),
PROTECTION_OFF,
An<const BsonObject*>()))
.Times(call_times)
.
// Return sessions start rejection
WillRepeatedly(
DoAll(NotifyTestAsyncWaiter(&waiter),
SaveArg<2>(&service_type),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
GetSessionContext(connection_id,
NEW_SESSION_ID,
SESSION_START_REJECT,
service_type,
HASH_ID_WRONG,
PROTECTION_OFF),
ByRef(empty_rejected_param_))));
times += call_times;
// Expect send NAck
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_NACK,
PROTECTION_OFF)))
.Times(call_times)
.WillRepeatedly(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times += call_times;
SendControlMessage(
PROTECTION_OFF, kControl, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
SendControlMessage(
PROTECTION_OFF, kRpc, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
SendControlMessage(
PROTECTION_OFF, kAudio, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
SendControlMessage(
PROTECTION_OFF, kMobileNav, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
SendControlMessage(
PROTECTION_OFF, kBulk, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout));
}
/*
* ProtocolHandler shall send NAck on session_observer rejection
* Emulate getting PROTECTION_ON and check protection flag OFF in NAck
* For ENABLE_SECURITY=OFF session_observer shall be called with protection flag
* OFF
*/
TEST_F(ProtocolHandlerImplTest, StartSession_Protected_SessionObserverReject) {
using namespace protocol_handler;
const int call_times = 5;
AddConnection();
#ifdef ENABLE_SECURITY
// For enabled protection callback shall use protection ON
const bool callback_protection_flag = PROTECTION_ON;
#else
// For disabled protection callback shall ignore protection income flag and
// use protection OFF
const bool callback_protection_flag = PROTECTION_OFF;
#endif // ENABLE_SECURITY
TestAsyncWaiter waiter;
uint32_t times = 0;
ServiceType service_type;
// Expect ConnectionHandler check
EXPECT_CALL(
session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
AnyOf(kControl, kRpc, kAudio, kMobileNav, kBulk),
callback_protection_flag,
An<const BsonObject*>()))
.Times(call_times)
.
// Return sessions start rejection
WillRepeatedly(DoAll(
NotifyTestAsyncWaiter(&waiter),
SaveArg<2>(&service_type),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
GetSessionContext(connection_id,
NEW_SESSION_ID,
SESSION_START_REJECT,
service_type,
HASH_ID_WRONG,
callback_protection_flag),
ByRef(empty_rejected_param_))));
times += call_times;
// Expect send NAck with encryption OFF
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_NACK,
PROTECTION_OFF)))
.Times(call_times)
.WillRepeatedly(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times += call_times;
SendControlMessage(
PROTECTION_ON, kControl, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
SendControlMessage(
PROTECTION_ON, kRpc, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
SendControlMessage(
PROTECTION_ON, kAudio, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
SendControlMessage(
PROTECTION_ON, kMobileNav, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
SendControlMessage(
PROTECTION_ON, kBulk, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout));
}
/*
* ProtocolHandler shall send Ack on session_observer accept
* Check protection flag OFF
*/
TEST_F(ProtocolHandlerImplTest,
StartSession_Unprotected_SessionObserverAccept) {
using namespace protocol_handler;
AddConnection();
const ServiceType start_service = kRpc;
TestAsyncWaiter waiter;
uint32_t times = 0;
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
start_service,
PROTECTION_OFF,
An<const BsonObject*>()))
.
// Return sessions start success
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
GetSessionContext(connection_id,
NEW_SESSION_ID,
session_id,
start_service,
HASH_ID_WRONG,
PROTECTION_OFF),
ByRef(empty_rejected_param_))));
times++;
SetProtocolVersion2();
// Expect send Ack
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(
ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times++;
SendControlMessage(
PROTECTION_OFF, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout));
}
/*
* ProtocolHandler shall send Ack on session_observer accept
* Emulate getting PROTECTION_ON and check protection flag OFF in Ack
* For ENABLE_SECURITY=OFF session_observer shall be called with protection flag
* OFF
*/
TEST_F(ProtocolHandlerImplTest, StartSession_Protected_SessionObserverAccept) {
SetProtocolVersion2();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
static std::vector<uint8_t> CreateVectorFromBsonObject(const BsonObject* bo) {
std::vector<uint8_t> output;
if (bo != NULL) {
size_t len = bson_object_size(const_cast<BsonObject*>(bo));
uint8_t* bytes = bson_object_to_bytes(const_cast<BsonObject*>(bo));
output.assign(bytes, bytes + len);
free(bytes);
}
return output;
}
/*
* Simulate two StartService messages of video service from mobile.
* Session observer accepts the first message with delay, while rejects the
* second message immediately.
*/
TEST_F(ProtocolHandlerImplTest,
StartSession_Unprotected_Multiple_SessionObserverAcceptAndReject) {
using namespace protocol_handler;
ON_CALL(protocol_handler_settings_mock, max_supported_protocol_version())
.WillByDefault(Return(PROTOCOL_VERSION_5));
const size_t maximum_payload_size = 1000;
InitProtocolHandlerImpl(0u, 0u, false, 0u, 0u, 0, maximum_payload_size);
const ServiceType start_service = kMobileNav;
const ::transport_manager::ConnectionUID connection_id1 = 0xAu;
const uint8_t session_id1 = 1u;
const ::transport_manager::ConnectionUID connection_id2 = 0xBu;
const uint8_t session_id2 = 2u;
EXPECT_CALL(session_observer_mock, IsHeartBeatSupported(connection_id1, _))
.WillRepeatedly(Return(false));
EXPECT_CALL(session_observer_mock, IsHeartBeatSupported(connection_id2, _))
.WillRepeatedly(Return(false));
// Add two connections
tm_listener->OnConnectionEstablished(DeviceInfo(DeviceHandle(1u),
std::string("mac"),
std::string("name"),
std::string("BTMAC")),
connection_id1);
tm_listener->OnConnectionEstablished(DeviceInfo(DeviceHandle(2u),
std::string("mac"),
std::string("name"),
std::string("BTMAC")),
connection_id2);
TestAsyncWaiter waiter;
uint32_t times = 0;
BsonObject bson_params1;
bson_object_initialize_default(&bson_params1);
bson_object_put_string(&bson_params1,
protocol_handler::strings::video_protocol,
const_cast<char*>("RAW"));
bson_object_put_string(&bson_params1,
protocol_handler::strings::video_codec,
const_cast<char*>("H264"));
std::vector<uint8_t> params1 = CreateVectorFromBsonObject(&bson_params1);
uint8_t generated_session_id1 = 100;
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id1,
session_id1,
start_service,
PROTECTION_OFF,
An<const BsonObject*>()))
// don't call NotifySessionStartedContext() immediately, instead call it
// after second OnSessionStartedCallback()
.WillOnce(NotifyTestAsyncWaiter(&waiter));
times++;
BsonObject bson_params2;
bson_object_initialize_default(&bson_params2);
bson_object_put_string(&bson_params2,
protocol_handler::strings::video_protocol,
const_cast<char*>("RTP"));
bson_object_put_string(&bson_params2,
protocol_handler::strings::video_codec,
const_cast<char*>("H265"));
std::vector<uint8_t> params2 = CreateVectorFromBsonObject(&bson_params2);
std::vector<std::string> rejected_param_list;
rejected_param_list.push_back(protocol_handler::strings::video_codec);
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id2,
session_id2,
start_service,
PROTECTION_OFF,
An<const BsonObject*>()))
.WillOnce(DoAll(
NotifyTestAsyncWaiter(&waiter),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
GetSessionContext(connection_id2,
session_id2,
SESSION_START_REJECT,
start_service,
HASH_ID_WRONG,
PROTECTION_OFF),
ByRef(rejected_param_list)),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
GetSessionContext(connection_id1,
session_id1,
generated_session_id1,
start_service,
HASH_ID_WRONG,
PROTECTION_OFF),
ByRef(empty_rejected_param_))));
times++;
BsonObject bson_ack_params;
bson_object_initialize_default(&bson_ack_params);
bson_object_put_int64(
&bson_ack_params, protocol_handler::strings::mtu, maximum_payload_size);
bson_object_put_string(&bson_ack_params,
protocol_handler::strings::video_protocol,
const_cast<char*>("RAW"));
bson_object_put_string(&bson_ack_params,
protocol_handler::strings::video_codec,
const_cast<char*>("H264"));
std::vector<uint8_t> ack_params =
CreateVectorFromBsonObject(&bson_ack_params);
bson_object_deinitialize(&bson_ack_params);
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK,
PROTECTION_OFF,
connection_id1,
Eq(ack_params))))
.WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times++;
BsonArray bson_arr;
bson_array_initialize(&bson_arr, rejected_param_list.size());
for (unsigned int i = 0; i < rejected_param_list.size(); i++) {
bson_array_add_string(&bson_arr,
const_cast<char*>(rejected_param_list[i].c_str()));
}
BsonObject bson_nack_params;
bson_object_initialize_default(&bson_nack_params);
bson_object_put_array(
&bson_nack_params, protocol_handler::strings::rejected_params, &bson_arr);
std::vector<uint8_t> nack_params =
CreateVectorFromBsonObject(&bson_nack_params);
bson_object_deinitialize(&bson_nack_params);
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_NACK,
PROTECTION_OFF,
connection_id2,
Eq(nack_params))))
.WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times++;
SendTMMessage(connection_id1,
PROTOCOL_VERSION_5,
PROTECTION_OFF,
FRAME_TYPE_CONTROL,
start_service,
FRAME_DATA_START_SERVICE,
session_id1,
params1.size(),
message_id,
params1.size() > 0 ? ¶ms1[0] : NULL);
SendTMMessage(connection_id2,
PROTOCOL_VERSION_5,
PROTECTION_OFF,
FRAME_TYPE_CONTROL,
start_service,
FRAME_DATA_START_SERVICE,
session_id2,
params2.size(),
message_id,
params2.size() > 0 ? ¶ms2[0] : NULL);
EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout));
bson_object_deinitialize(&bson_params1);
bson_object_deinitialize(&bson_params2);
}
// TODO(EZamakhov): add test for get_hash_id/set_hash_id from
// protocol_handler_impl.cc
/*
* ProtocolHandler shall send NAck on session_observer rejection
*/
TEST_F(ProtocolHandlerImplTest, EndSession_SessionObserverReject) {
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
const ServiceType service = kRpc;
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionEndedCallback(
connection_id, session_id, An<uint32_t*>(), service))
.
// reject session start
WillOnce(
DoAll(NotifyTestAsyncWaiter(waiter), Return(SESSION_START_REJECT)));
times++;
SetProtocolVersion2();
// Expect send NAck
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(
ControlMessage(FRAME_DATA_END_SERVICE_NACK, PROTECTION_OFF)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS)));
times++;
SendControlMessage(
PROTECTION_OFF, service, session_id, FRAME_DATA_END_SERVICE);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
/*
* ProtocolHandler shall send NAck on wrong hash code
*/
TEST_F(ProtocolHandlerImplTest, EndSession_Success) {
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
const ServiceType service = kRpc;
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionEndedCallback(
connection_id, session_id, An<uint32_t*>(), service))
.
// return sessions start success
WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(connection_key)));
times++;
SetProtocolVersion2();
// Expect send Ack
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(
ControlMessage(FRAME_DATA_END_SERVICE_ACK, PROTECTION_OFF)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS)));
times++;
SendControlMessage(
PROTECTION_OFF, service, session_id, FRAME_DATA_END_SERVICE);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
#ifdef ENABLE_SECURITY
TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionProtocoloV1) {
using namespace protocol_handler;
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Add security manager
AddSecurityManager();
const ServiceType start_service = kRpc;
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
start_service,
PROTECTION_OFF,
An<const BsonObject*>()))
.
// Return sessions start success
WillOnce(
DoAll(NotifyTestAsyncWaiter(waiter),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
GetSessionContext(connection_id,
NEW_SESSION_ID,
session_id,
start_service,
HASH_ID_WRONG,
PROTECTION_OFF),
ByRef(empty_rejected_param_))));
times++;
SetProtocolVersion2();
// Expect send Ack with PROTECTION_OFF (on no Security Manager)
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(
ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS)))
.RetiresOnSaturation();
times++;
SendTMMessage(connection_id,
PROTOCOL_VERSION_1,
PROTECTION_ON,
FRAME_TYPE_CONTROL,
start_service,
FRAME_DATA_START_SERVICE,
NEW_SESSION_ID,
0,
message_id);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
/*
* ProtocolHandler shall not call Security logics on start session with
* PROTECTION_OFF
*/
TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionUnprotected) {
using namespace protocol_handler;
AddConnection();
// Add security manager
AddSecurityManager();
const ServiceType start_service = kRpc;
TestAsyncWaiter waiter;
uint32_t times = 0;
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
start_service,
PROTECTION_OFF,
An<const BsonObject*>()))
.
// Return sessions start success
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
GetSessionContext(connection_id,
NEW_SESSION_ID,
session_id,
start_service,
HASH_ID_WRONG,
PROTECTION_OFF),
ByRef(empty_rejected_param_))));
times++;
SetProtocolVersion2();
// Expect send Ack with PROTECTION_OFF (on no Security Manager)
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(
ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times++;
SendControlMessage(
PROTECTION_OFF, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout));
}
/*
* ProtocolHandler shall send Ack with PROTECTION_OFF on fail SLL creation
*/
TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionProtected_Fail) {
using namespace protocol_handler;
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
TestAsyncWaiter waiter;
uint32_t times = 0;
protocol_handler::SessionContext context = GetSessionContext(connection_id,
NEW_SESSION_ID,
session_id,
start_service,
HASH_ID_WRONG,
PROTECTION_ON);
context.is_new_service_ = true;
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
start_service,
PROTECTION_ON,
An<const BsonObject*>()))
.
// Return sessions start success
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
context,
ByRef(empty_rejected_param_))));
times++;
SetProtocolVersion2();
// Expect start protection for unprotected session
EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
.
// Return fail protection
WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), ReturnNull()));
times++;
// Expect send Ack with PROTECTION_OFF (on fail SLL creation)
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(
ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times++;
SendControlMessage(
PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout));
}
/*
* ProtocolHandler shall send Ack with PROTECTION_ON on already established and
* initialized SLLContext
*/
TEST_F(ProtocolHandlerImplTest,
SecurityEnable_StartSessionProtected_SSLInitialized) {
using namespace protocol_handler;
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
TestAsyncWaiter waiter;
uint32_t times = 0;
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
start_service,
PROTECTION_ON,
An<const BsonObject*>()))
.
// Return sessions start success
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
GetSessionContext(connection_id,
NEW_SESSION_ID,
session_id,
start_service,
HASH_ID_WRONG,
PROTECTION_ON),
ByRef(empty_rejected_param_))));
times++;
SetProtocolVersion2();
// call new SSLContext creation
EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
.
// Return new SSLContext
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter), Return(&ssl_context_mock)));
times++;
// Initilization check
EXPECT_CALL(ssl_context_mock, IsInitCompleted())
.
// emulate SSL is initilized
WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true)));
times++;
// Expect service protection enable
EXPECT_CALL(session_observer_mock,
SetProtectionFlag(connection_key, start_service))
.WillOnce(NotifyTestAsyncWaiter(&waiter));
times++;
// Expect send Ack with PROTECTION_ON (on SSL is initilized)
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(
ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times++;
SendControlMessage(
PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout));
}
/*
* ProtocolHandler shall send Ack with PROTECTION_OFF on session handshhake fail
*/
TEST_F(ProtocolHandlerImplTest,
SecurityEnable_StartSessionProtected_HandshakeFail) {
using namespace protocol_handler;
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
TestAsyncWaiter waiter;
uint32_t times = 0;
protocol_handler::SessionContext context = GetSessionContext(connection_id,
NEW_SESSION_ID,
session_id,
start_service,
HASH_ID_WRONG,
PROTECTION_ON);
context.is_new_service_ = true;
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
start_service,
PROTECTION_ON,
An<const BsonObject*>()))
.
// Return sessions start success
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
context,
ByRef(empty_rejected_param_))));
times++;
std::vector<int> services;
// TODO(AKutsan) : APPLINK-21398 use named constants instead of magic numbers
services.push_back(0x0A);
services.push_back(0x0B);
EXPECT_CALL(protocol_handler_settings_mock, force_protected_service())
.WillOnce(ReturnRefOfCopy(services));
// call new SSLContext creation
EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
.
// Return new SSLContext
WillOnce(Return(&ssl_context_mock));
// Initilization check
EXPECT_CALL(ssl_context_mock, IsInitCompleted())
.
// emulate SSL is not initilized
WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(false)));
times++;
// Pending handshake check
EXPECT_CALL(ssl_context_mock, IsHandshakePending())
.
// emulate is pending
WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true)));
times++;
// Expect add listener for handshake result
EXPECT_CALL(security_manager_mock, AddListener(_))
// Emulate handshake fail
.WillOnce(Invoke(OnHandshakeDoneFunctor(
connection_key,
security_manager::SSLContext::Handshake_Result_Fail)));
// Expect send Ack with PROTECTION_OFF (on fail handshake)
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(
ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times++;
SendControlMessage(
PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout));
}
/*
* ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake
* success
*/
TEST_F(ProtocolHandlerImplTest,
SecurityEnable_StartSessionProtected_HandshakeSuccess) {
using namespace protocol_handler;
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
// No services are protected
std::vector<int> services;
ON_CALL(protocol_handler_settings_mock, force_protected_service())
.WillByDefault(ReturnRefOfCopy(services));
TestAsyncWaiter waiter;
uint32_t times = 0;
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
start_service,
PROTECTION_ON,
An<const BsonObject*>()))
.
// Return sessions start success
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
GetSessionContext(connection_id,
NEW_SESSION_ID,
session_id,
start_service,
HASH_ID_WRONG,
PROTECTION_ON),
ByRef(empty_rejected_param_))));
times++;
// call new SSLContext creation
EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
.
// Return new SSLContext
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter), Return(&ssl_context_mock)));
times++;
// Initilization check
EXPECT_CALL(ssl_context_mock, IsInitCompleted())
.
// emulate SSL is not initilized
WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(false)));
times++;
// Pending handshake check
EXPECT_CALL(ssl_context_mock, IsHandshakePending())
.
// emulate is pending
WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true)));
times++;
// Expect add listener for handshake result
EXPECT_CALL(security_manager_mock, AddListener(_))
// Emulate handshake fail
.WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter),
Invoke(OnHandshakeDoneFunctor(
connection_key,
security_manager::SSLContext::Handshake_Result_Success))));
times++;
// Listener check SSLContext
EXPECT_CALL(session_observer_mock,
GetSSLContext(connection_key, start_service))
.
// Emulate protection for service is not enabled
WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), ReturnNull()));
times++;
// Expect service protection enable
EXPECT_CALL(session_observer_mock,
SetProtectionFlag(connection_key, start_service))
.WillOnce(NotifyTestAsyncWaiter(&waiter));
times++;
// Expect send Ack with PROTECTION_OFF (on fail handshake)
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(
ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times++;
SendControlMessage(
PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout));
}
/*
* ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake
* success
*/
TEST_F(
ProtocolHandlerImplTest,
SecurityEnable_StartSessionProtected_HandshakeSuccess_ServiceProtectedBefore) {
using namespace protocol_handler;
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
std::vector<int> services;
ON_CALL(protocol_handler_settings_mock, force_protected_service())
.WillByDefault(ReturnRefOfCopy(services));
TestAsyncWaiter waiter;
uint32_t times = 0;
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
start_service,
PROTECTION_ON,
An<const BsonObject*>()))
.
// Return sessions start success
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
GetSessionContext(connection_id,
NEW_SESSION_ID,
session_id,
start_service,
HASH_ID_WRONG,
PROTECTION_ON),
ByRef(empty_rejected_param_))));
times++;
// call new SSLContext creation
EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
.
// Return new SSLContext
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter), Return(&ssl_context_mock)));
times++;
// Initilization check
EXPECT_CALL(ssl_context_mock, IsInitCompleted())
.
// emulate SSL is not initilized
WillOnce(Return(false));
// Pending handshake check
EXPECT_CALL(ssl_context_mock, IsHandshakePending())
.
// emulate is pending
WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(true)));
times++;
// Expect add listener for handshake result
EXPECT_CALL(security_manager_mock, AddListener(_))
// Emulate handshake fail
.WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter),
Invoke(OnHandshakeDoneFunctor(
connection_key,
security_manager::SSLContext::Handshake_Result_Success))));
times++;
// Listener check SSLContext
EXPECT_CALL(session_observer_mock,
GetSSLContext(connection_key, start_service))
.
// Emulate protection for service is not enabled
WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), ReturnNull()));
times++;
// Expect service protection enable
EXPECT_CALL(session_observer_mock,
SetProtectionFlag(connection_key, start_service))
.WillOnce(NotifyTestAsyncWaiter(&waiter));
times++;
// Expect send Ack with PROTECTION_OFF (on fail handshake)
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(
ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times++;
SendControlMessage(
PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout));
}
/*
* ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake
* success
*/
TEST_F(ProtocolHandlerImplTest,
SecurityEnable_StartSessionProtected_HandshakeSuccess_SSLIsNotPending) {
using namespace protocol_handler;
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
std::vector<int> services;
ON_CALL(protocol_handler_settings_mock, force_protected_service())
.WillByDefault(ReturnRefOfCopy(services));
TestAsyncWaiter waiter;
uint32_t times = 0;
// Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
OnSessionStartedCallback(connection_id,
NEW_SESSION_ID,
start_service,
PROTECTION_ON,
An<const BsonObject*>()))
.
// Return sessions start success
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter),
InvokeMemberFuncWithArg2(protocol_handler_impl.get(),
&ProtocolHandler::NotifySessionStarted,
GetSessionContext(connection_id,
NEW_SESSION_ID,
session_id,
start_service,
HASH_ID_WRONG,
PROTECTION_ON),
ByRef(empty_rejected_param_))));
times++;
// call new SSLContext creation
EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
.
// Return new SSLContext
WillOnce(
DoAll(NotifyTestAsyncWaiter(&waiter), Return(&ssl_context_mock)));
times++;
// Initilization check
EXPECT_CALL(ssl_context_mock, IsInitCompleted())
.
// emulate SSL is not initilized
WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(false)));
times++;
// Pending handshake check
EXPECT_CALL(ssl_context_mock, IsHandshakePending())
.
// emulate is pending
WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(false)));
times++;
// Wait restart handshake operation
EXPECT_CALL(security_manager_mock, StartHandshake(connection_key))
.WillOnce(NotifyTestAsyncWaiter(&waiter));
times++;
// Expect add listener for handshake result
EXPECT_CALL(security_manager_mock, AddListener(_))
// Emulate handshake fail
.WillOnce(Invoke(OnHandshakeDoneFunctor(
connection_key,
security_manager::SSLContext::Handshake_Result_Success)));
// Listener check SSLContext
EXPECT_CALL(session_observer_mock,
GetSSLContext(connection_key, start_service))
.
// Emulate protection for service is not enabled
WillOnce(ReturnNull());
// Expect service protection enable
EXPECT_CALL(session_observer_mock,
SetProtectionFlag(connection_key, start_service));
// Expect send Ack with PROTECTION_OFF (on fail handshake)
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(
ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(&waiter), Return(E_SUCCESS)));
times++;
SendControlMessage(
PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
EXPECT_TRUE(waiter.WaitFor(times, kAsyncExpectationsTimeout));
}
#endif // ENABLE_SECURITY
TEST_F(ProtocolHandlerImplTest, DISABLED_FloodVerification) {
const size_t period_msec = 10000;
const size_t max_messages = 1000;
InitProtocolHandlerImpl(period_msec, max_messages);
AddConnection();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect flood notification to CH
EXPECT_CALL(session_observer_mock, OnApplicationFloodCallBack(connection_key))
.WillOnce(NotifyTestAsyncWaiter(waiter));
times++;
ON_CALL(protocol_handler_settings_mock, message_frequency_time())
.WillByDefault(Return(period_msec));
ON_CALL(protocol_handler_settings_mock, message_frequency_count())
.WillByDefault(Return(max_messages));
for (size_t i = 0; i < max_messages + 1; ++i) {
SendTMMessage(connection_id,
PROTOCOL_VERSION_3,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
}
EXPECT_TRUE(waiter->WaitFor(times, period_msec));
}
TEST_F(ProtocolHandlerImplTest, DISABLED_FloodVerification_ThresholdValue) {
const size_t period_msec = 10000;
const size_t max_messages = 1000;
InitProtocolHandlerImpl(period_msec, max_messages);
AddConnection();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
ON_CALL(protocol_handler_settings_mock, message_frequency_time())
.WillByDefault(Return(period_msec));
ON_CALL(protocol_handler_settings_mock, message_frequency_count())
.WillByDefault(Return(max_messages));
// Expect NO flood notification to CH
EXPECT_CALL(session_observer_mock, OnApplicationFloodCallBack(connection_key))
.Times(0);
for (size_t i = 0; i < max_messages - 1; ++i) {
SendTMMessage(connection_id,
PROTOCOL_VERSION_3,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
}
EXPECT_TRUE(waiter->WaitFor(times, period_msec));
}
TEST_F(ProtocolHandlerImplTest, DISABLED_FloodVerification_VideoFrameSkip) {
const size_t period_msec = 10000;
const size_t max_messages = 1000;
InitProtocolHandlerImpl(period_msec, max_messages);
AddConnection();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect NO flood notification to CH on video data streaming
for (size_t i = 0; i < max_messages + 1; ++i) {
SendTMMessage(connection_id,
PROTOCOL_VERSION_3,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kMobileNav,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
}
EXPECT_TRUE(waiter->WaitFor(times, period_msec));
}
TEST_F(ProtocolHandlerImplTest, DISABLED_FloodVerification_AudioFrameSkip) {
const size_t period_msec = 10000;
const size_t max_messages = 1000;
InitProtocolHandlerImpl(period_msec, max_messages);
AddConnection();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect NO flood notification to CH on video data streaming
for (size_t i = 0; i < max_messages + 1; ++i) {
SendTMMessage(connection_id,
PROTOCOL_VERSION_3,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kAudio,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
}
EXPECT_TRUE(waiter->WaitFor(times, period_msec));
}
TEST_F(ProtocolHandlerImplTest, DISABLED_FloodVerificationDisable) {
const size_t period_msec = 0;
const size_t max_messages = 0;
InitProtocolHandlerImpl(period_msec, max_messages);
AddConnection();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect NO flood notification to session observer
for (size_t i = 0; i < max_messages + 1; ++i) {
SendTMMessage(connection_id,
PROTOCOL_VERSION_3,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
}
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest, MalformedVerificationDisable) {
const size_t period_msec = 10000;
const size_t max_messages = 100;
InitProtocolHandlerImpl(0u, 0u, false, period_msec, max_messages);
AddConnection();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect malformed notification to CH
EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
.Times(max_messages);
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
for (size_t i = 0; i < max_messages; ++i) {
SendTMMessage(connection_id,
malformed_version,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
}
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest, DISABLED_MalformedLimitVerification) {
const size_t period_msec = 10000;
const size_t max_messages = 100;
InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages);
AddConnection();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect malformed notification to CH
EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
.WillOnce(NotifyTestAsyncWaiter(waiter));
times++;
// Sending malformed packets
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
for (size_t i = 0; i < max_messages * 2; ++i) {
// Malformed message
SendTMMessage(connection_id,
malformed_version,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
// Common message
SendTMMessage(connection_id,
PROTOCOL_VERSION_1,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
}
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest,
DISABLED_MalformedLimitVerification_MalformedStock) {
const size_t period_msec = 10000;
const size_t max_messages = 100;
InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages);
AddConnection();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect malformed notification to CH
EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
.WillOnce(NotifyTestAsyncWaiter(waiter));
times++;
// Sending malformed packets
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
const uint8_t malformed_frame_type = FRAME_TYPE_MAX_VALUE;
const uint8_t malformed_service_type = kInvalidServiceType;
for (size_t i = 0; i < max_messages * 2; ++i) {
// Malformed message 1
SendTMMessage(connection_id,
malformed_version,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
// Malformed message 2
SendTMMessage(connection_id,
PROTOCOL_VERSION_1,
PROTECTION_OFF,
malformed_frame_type,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
// Malformed message 3
SendTMMessage(connection_id,
PROTOCOL_VERSION_1,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
malformed_service_type,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
// Common message
SendTMMessage(connection_id,
PROTOCOL_VERSION_1,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
}
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_MalformedOnly) {
const size_t period_msec = 10000;
const size_t max_messages = 100;
InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages);
AddConnection();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect NO malformed notification to CH
EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
.Times(0);
// Sending malformed packets
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
const uint8_t malformed_frame_type = FRAME_TYPE_MAX_VALUE;
const uint8_t malformed_service_type = kInvalidServiceType;
for (size_t i = 0; i < max_messages * 2; ++i) {
// Malformed message 1
SendTMMessage(connection_id,
malformed_version,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
// Malformed message 2
SendTMMessage(connection_id,
PROTOCOL_VERSION_1,
PROTECTION_OFF,
malformed_frame_type,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
// Malformed message 3
SendTMMessage(connection_id,
PROTOCOL_VERSION_1,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
malformed_service_type,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
// No common message
}
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_NullTimePeriod) {
const size_t period_msec = 0;
const size_t max_messages = 1000;
InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages);
AddConnection();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect no malformed notification to CH
EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
.Times(0);
// Sending malformed packets
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
for (size_t i = 0; i < max_messages + 1; ++i) {
SendTMMessage(connection_id,
malformed_version,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
}
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_NullCount) {
const size_t period_msec = 10000;
const size_t max_messages = 0;
InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages);
AddConnection();
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect no malformed notification to CH
EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
.Times(0);
// Sending malformed packets
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
for (size_t i = 0; i < max_messages + 1; ++i) {
SendTMMessage(connection_id,
malformed_version,
PROTECTION_OFF,
FRAME_TYPE_SINGLE,
kControl,
FRAME_DATA_SINGLE,
session_id,
some_data.size(),
message_id,
&some_data[0]);
}
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest,
SendEndServicePrivate_NoConnection_MessageNotSent) {
// Expect check connection with ProtocolVersionUsed
EXPECT_CALL(session_observer_mock,
ProtocolVersionUsed(connection_id, session_id, _))
.WillOnce(Return(false));
// Expect not send End Service
EXPECT_CALL(transport_manager_mock, SendMessageToDevice(_)).Times(0);
// Act
protocol_handler_impl->SendEndSession(connection_id, session_id);
}
TEST_F(ProtocolHandlerImplTest,
DISABLED_SendEndServicePrivate_EndSession_MessageSent) {
// Arrange
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect check connection with ProtocolVersionUsed
EXPECT_CALL(session_observer_mock,
ProtocolVersionUsed(connection_id, session_id, _))
.WillOnce(Return(true));
// Expect send End Service
EXPECT_CALL(
transport_manager_mock,
SendMessageToDevice(ExpectedMessage(
FRAME_TYPE_CONTROL, FRAME_DATA_END_SERVICE, PROTECTION_OFF, kRpc)))
.WillOnce(Return(E_SUCCESS));
// Act
protocol_handler_impl->SendEndSession(connection_id, session_id);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest,
SendEndServicePrivate_ServiceTypeControl_MessageSent) {
// Arrange
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect check connection with ProtocolVersionUsed
EXPECT_CALL(session_observer_mock,
ProtocolVersionUsed(connection_id, session_id, _))
.WillOnce(Return(true));
// Expect send End Service
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONTROL,
FRAME_DATA_END_SERVICE,
PROTECTION_OFF,
kControl)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS)));
times++;
// Act
protocol_handler_impl->SendEndService(connection_id, session_id, kControl);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest, SendHeartBeat_NoConnection_NotSent) {
// Expect check connection with ProtocolVersionUsed
EXPECT_CALL(session_observer_mock,
ProtocolVersionUsed(connection_id, session_id, _))
.WillOnce(Return(false));
// Expect not send HeartBeat
EXPECT_CALL(transport_manager_mock, SendMessageToDevice(_)).Times(0);
// Act
protocol_handler_impl->SendHeartBeat(connection_id, session_id);
}
TEST_F(ProtocolHandlerImplTest, SendHeartBeat_Successful) {
// Arrange
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect check connection with ProtocolVersionUsed
EXPECT_CALL(session_observer_mock,
ProtocolVersionUsed(connection_id, session_id, _))
.WillOnce(Return(true));
// Expect send HeartBeat
EXPECT_CALL(
transport_manager_mock,
SendMessageToDevice(ExpectedMessage(
FRAME_TYPE_CONTROL, FRAME_DATA_HEART_BEAT, PROTECTION_OFF, kControl)))
.WillOnce(Return(E_SUCCESS));
// Act
protocol_handler_impl->SendHeartBeat(connection_id, session_id);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest, SendHeartBeatAck_Successful) {
// Arrange
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect double check connection and protocol version with
// ProtocolVersionUsed
EXPECT_CALL(session_observer_mock, ProtocolVersionUsed(connection_id, _, _))
.WillRepeatedly(
DoAll(SetArgReferee<2>(PROTOCOL_VERSION_3), Return(true)));
// Expect send HeartBeatAck
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONTROL,
FRAME_DATA_HEART_BEAT_ACK,
PROTECTION_OFF,
kControl)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS)));
times++;
// Act
SendControlMessage(
PROTECTION_OFF, kControl, session_id, FRAME_DATA_HEART_BEAT);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest,
DISABLED_SendHeartBeatAck_WrongProtocolVersion_NotSent) {
// Arrange
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
// Expect two checks of connection and protocol version with
// ProtocolVersionUsed
EXPECT_CALL(session_observer_mock, ProtocolVersionUsed(connection_id, _, _))
.Times(2)
.WillRepeatedly(
DoAll(SetArgReferee<2>(PROTOCOL_VERSION_1), Return(true)));
// Expect not send HeartBeatAck
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONTROL,
FRAME_DATA_HEART_BEAT_ACK,
PROTECTION_OFF,
kControl))).Times(0);
// Act
SendControlMessage(
PROTECTION_OFF, kControl, session_id, FRAME_DATA_HEART_BEAT);
SendControlMessage(
PROTECTION_OFF, kControl, session_id, FRAME_DATA_HEART_BEAT);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest,
SendMessageToMobileApp_SendSingleControlMessage) {
// Arrange
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
const bool is_final = true;
const uint32_t total_data_size = 1;
UCharDataVector data(total_data_size);
RawMessagePtr message = utils::MakeShared<RawMessage>(
connection_key, PROTOCOL_VERSION_3, &data[0], total_data_size, kControl);
// Expect getting pair from key from session observer
EXPECT_CALL(session_observer_mock,
PairFromKey(message->connection_key(), _, _))
.WillOnce(
DoAll(SetArgPointee<1>(connection_id), SetArgPointee<2>(session_id)));
#ifdef ENABLE_SECURITY
// Expect getting ssl context
EXPECT_CALL(session_observer_mock,
GetSSLContext(message->connection_key(), message->service_type()))
.WillOnce(Return(&ssl_context_mock));
#endif // ENABLE_SECURITY
// Expect send message to mobile
EXPECT_CALL(
transport_manager_mock,
SendMessageToDevice(ExpectedMessage(
FRAME_TYPE_SINGLE, FRAME_DATA_SINGLE, PROTECTION_OFF, kControl)))
.WillOnce(Return(E_SUCCESS));
// Act
protocol_handler_impl->SendMessageToMobileApp(message, is_final);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest,
SendMessageToMobileApp_SendSingleNonControlMessage) {
// Arrange
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
const bool is_final = true;
const uint32_t total_data_size = 1;
UCharDataVector data(total_data_size);
RawMessagePtr message = utils::MakeShared<RawMessage>(
connection_key, PROTOCOL_VERSION_3, &data[0], total_data_size, kRpc);
// Expect getting pair from key from session observer
EXPECT_CALL(session_observer_mock,
PairFromKey(message->connection_key(), _, _))
.WillOnce(
DoAll(SetArgPointee<1>(connection_id), SetArgPointee<2>(session_id)));
#ifdef ENABLE_SECURITY
// Expect getting ssl context
EXPECT_CALL(session_observer_mock,
GetSSLContext(message->connection_key(), message->service_type()))
.Times(2)
.WillRepeatedly(
DoAll(NotifyTestAsyncWaiter(waiter), Return(&ssl_context_mock)));
times += 2;
AddSecurityManager();
#endif // ENABLE_SECURITY
// Expect send message to mobile
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ExpectedMessage(
FRAME_TYPE_SINGLE, FRAME_DATA_SINGLE, PROTECTION_OFF, kRpc)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS)));
times++;
// Act
protocol_handler_impl->SendMessageToMobileApp(message, is_final);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest, SendMessageToMobileApp_SendMultiframeMessage) {
// Arrange
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
const bool is_final = true;
const uint32_t total_data_size = MAXIMUM_FRAME_DATA_V2_SIZE * 2;
UCharDataVector data(total_data_size);
const uint8_t first_consecutive_frame = 0x01;
RawMessagePtr message = utils::MakeShared<RawMessage>(
connection_key, PROTOCOL_VERSION_3, &data[0], total_data_size, kBulk);
// Expect getting pair from key from session observer
EXPECT_CALL(session_observer_mock,
PairFromKey(message->connection_key(), _, _))
.WillOnce(
DoAll(SetArgPointee<1>(connection_id), SetArgPointee<2>(session_id)));
#ifdef ENABLE_SECURITY
// Expect getting ssl context
EXPECT_CALL(session_observer_mock,
GetSSLContext(message->connection_key(), message->service_type()))
.Times(4)
.WillRepeatedly(
DoAll(NotifyTestAsyncWaiter(waiter), Return(&ssl_context_mock)));
times += 4;
AddSecurityManager();
#endif // ENABLE_SECURITY
// Expect sending message frame by frame to mobile
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ExpectedMessage(
FRAME_TYPE_FIRST, FRAME_DATA_FIRST, PROTECTION_OFF, kBulk)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS)));
times++;
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONSECUTIVE,
first_consecutive_frame,
PROTECTION_OFF,
kBulk)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS)));
times++;
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONSECUTIVE,
FRAME_DATA_LAST_CONSECUTIVE,
PROTECTION_OFF,
kBulk)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS)));
times++;
// Act
protocol_handler_impl->SendMessageToMobileApp(message, is_final);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest, SendServiceDataAck_PreVersion5) {
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
EXPECT_CALL(session_observer_mock, PairFromKey(connection_key, _, _))
.WillOnce(
DoAll(SetArgPointee<1>(connection_id), SetArgPointee<2>(session_id)));
EXPECT_CALL(session_observer_mock, ProtocolVersionUsed(connection_id, _, _))
.WillRepeatedly(
DoAll(SetArgReferee<2>(PROTOCOL_VERSION_4), Return(true)));
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONTROL,
FRAME_DATA_SERVICE_DATA_ACK,
PROTECTION_OFF,
kMobileNav)))
.WillOnce(DoAll(NotifyTestAsyncWaiter(waiter), Return(E_SUCCESS)));
times++;
protocol_handler_impl->SendFramesNumber(connection_key, 0);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
TEST_F(ProtocolHandlerImplTest, SendServiceDataAck_AfterVersion5) {
::utils::SharedPtr<TestAsyncWaiter> waiter =
utils::MakeShared<TestAsyncWaiter>();
uint32_t times = 0;
AddSession(waiter, times);
EXPECT_CALL(session_observer_mock, PairFromKey(connection_key, _, _))
.WillOnce(
DoAll(SetArgPointee<1>(connection_id), SetArgPointee<2>(session_id)));
EXPECT_CALL(session_observer_mock, ProtocolVersionUsed(connection_id, _, _))
.WillRepeatedly(
DoAll(SetArgReferee<2>(PROTOCOL_VERSION_5), Return(true)));
// It is expected that Service Data ACK is NOT sent for version 5+
EXPECT_CALL(transport_manager_mock,
SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONTROL,
FRAME_DATA_SERVICE_DATA_ACK,
PROTECTION_OFF,
kMobileNav))).Times(0);
protocol_handler_impl->SendFramesNumber(connection_key, 0);
EXPECT_TRUE(waiter->WaitFor(times, kAsyncExpectationsTimeout));
}
} // namespace protocol_handler_test
} // namespace components
} // namespace test
| {
"content_hash": "5a372cd1678d8492a0984a447bb3dc2b",
"timestamp": "",
"source": "github",
"line_count": 2222,
"max_line_length": 83,
"avg_line_length": 37.5040504050405,
"alnum_prop": 0.59656322749418,
"repo_name": "APCVSRepo/sdl_core",
"id": "77de1705dabbbb5e008805f462e0b1d881c5c9ee",
"size": "84904",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/protocol_handler/test/protocol_handler_tm_test.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "10491"
},
{
"name": "C++",
"bytes": "18387258"
},
{
"name": "CMake",
"bytes": "417637"
},
{
"name": "HTML",
"bytes": "1138"
},
{
"name": "M4",
"bytes": "25347"
},
{
"name": "Makefile",
"bytes": "139997"
},
{
"name": "PLpgSQL",
"bytes": "12824"
},
{
"name": "Python",
"bytes": "779378"
},
{
"name": "Shell",
"bytes": "692158"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.iotevents.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Information about the configuration of an input.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/iotevents-2018-07-27/InputConfiguration" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InputConfiguration implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The name of the input.
* </p>
*/
private String inputName;
/**
* <p>
* A brief description of the input.
* </p>
*/
private String inputDescription;
/**
* <p>
* The ARN of the input.
* </p>
*/
private String inputArn;
/**
* <p>
* The time the input was created.
* </p>
*/
private java.util.Date creationTime;
/**
* <p>
* The last time the input was updated.
* </p>
*/
private java.util.Date lastUpdateTime;
/**
* <p>
* The status of the input.
* </p>
*/
private String status;
/**
* <p>
* The name of the input.
* </p>
*
* @param inputName
* The name of the input.
*/
public void setInputName(String inputName) {
this.inputName = inputName;
}
/**
* <p>
* The name of the input.
* </p>
*
* @return The name of the input.
*/
public String getInputName() {
return this.inputName;
}
/**
* <p>
* The name of the input.
* </p>
*
* @param inputName
* The name of the input.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InputConfiguration withInputName(String inputName) {
setInputName(inputName);
return this;
}
/**
* <p>
* A brief description of the input.
* </p>
*
* @param inputDescription
* A brief description of the input.
*/
public void setInputDescription(String inputDescription) {
this.inputDescription = inputDescription;
}
/**
* <p>
* A brief description of the input.
* </p>
*
* @return A brief description of the input.
*/
public String getInputDescription() {
return this.inputDescription;
}
/**
* <p>
* A brief description of the input.
* </p>
*
* @param inputDescription
* A brief description of the input.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InputConfiguration withInputDescription(String inputDescription) {
setInputDescription(inputDescription);
return this;
}
/**
* <p>
* The ARN of the input.
* </p>
*
* @param inputArn
* The ARN of the input.
*/
public void setInputArn(String inputArn) {
this.inputArn = inputArn;
}
/**
* <p>
* The ARN of the input.
* </p>
*
* @return The ARN of the input.
*/
public String getInputArn() {
return this.inputArn;
}
/**
* <p>
* The ARN of the input.
* </p>
*
* @param inputArn
* The ARN of the input.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InputConfiguration withInputArn(String inputArn) {
setInputArn(inputArn);
return this;
}
/**
* <p>
* The time the input was created.
* </p>
*
* @param creationTime
* The time the input was created.
*/
public void setCreationTime(java.util.Date creationTime) {
this.creationTime = creationTime;
}
/**
* <p>
* The time the input was created.
* </p>
*
* @return The time the input was created.
*/
public java.util.Date getCreationTime() {
return this.creationTime;
}
/**
* <p>
* The time the input was created.
* </p>
*
* @param creationTime
* The time the input was created.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InputConfiguration withCreationTime(java.util.Date creationTime) {
setCreationTime(creationTime);
return this;
}
/**
* <p>
* The last time the input was updated.
* </p>
*
* @param lastUpdateTime
* The last time the input was updated.
*/
public void setLastUpdateTime(java.util.Date lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
/**
* <p>
* The last time the input was updated.
* </p>
*
* @return The last time the input was updated.
*/
public java.util.Date getLastUpdateTime() {
return this.lastUpdateTime;
}
/**
* <p>
* The last time the input was updated.
* </p>
*
* @param lastUpdateTime
* The last time the input was updated.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public InputConfiguration withLastUpdateTime(java.util.Date lastUpdateTime) {
setLastUpdateTime(lastUpdateTime);
return this;
}
/**
* <p>
* The status of the input.
* </p>
*
* @param status
* The status of the input.
* @see InputStatus
*/
public void setStatus(String status) {
this.status = status;
}
/**
* <p>
* The status of the input.
* </p>
*
* @return The status of the input.
* @see InputStatus
*/
public String getStatus() {
return this.status;
}
/**
* <p>
* The status of the input.
* </p>
*
* @param status
* The status of the input.
* @return Returns a reference to this object so that method calls can be chained together.
* @see InputStatus
*/
public InputConfiguration withStatus(String status) {
setStatus(status);
return this;
}
/**
* <p>
* The status of the input.
* </p>
*
* @param status
* The status of the input.
* @return Returns a reference to this object so that method calls can be chained together.
* @see InputStatus
*/
public InputConfiguration withStatus(InputStatus status) {
this.status = status.toString();
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getInputName() != null)
sb.append("InputName: ").append(getInputName()).append(",");
if (getInputDescription() != null)
sb.append("InputDescription: ").append(getInputDescription()).append(",");
if (getInputArn() != null)
sb.append("InputArn: ").append(getInputArn()).append(",");
if (getCreationTime() != null)
sb.append("CreationTime: ").append(getCreationTime()).append(",");
if (getLastUpdateTime() != null)
sb.append("LastUpdateTime: ").append(getLastUpdateTime()).append(",");
if (getStatus() != null)
sb.append("Status: ").append(getStatus());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof InputConfiguration == false)
return false;
InputConfiguration other = (InputConfiguration) obj;
if (other.getInputName() == null ^ this.getInputName() == null)
return false;
if (other.getInputName() != null && other.getInputName().equals(this.getInputName()) == false)
return false;
if (other.getInputDescription() == null ^ this.getInputDescription() == null)
return false;
if (other.getInputDescription() != null && other.getInputDescription().equals(this.getInputDescription()) == false)
return false;
if (other.getInputArn() == null ^ this.getInputArn() == null)
return false;
if (other.getInputArn() != null && other.getInputArn().equals(this.getInputArn()) == false)
return false;
if (other.getCreationTime() == null ^ this.getCreationTime() == null)
return false;
if (other.getCreationTime() != null && other.getCreationTime().equals(this.getCreationTime()) == false)
return false;
if (other.getLastUpdateTime() == null ^ this.getLastUpdateTime() == null)
return false;
if (other.getLastUpdateTime() != null && other.getLastUpdateTime().equals(this.getLastUpdateTime()) == false)
return false;
if (other.getStatus() == null ^ this.getStatus() == null)
return false;
if (other.getStatus() != null && other.getStatus().equals(this.getStatus()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getInputName() == null) ? 0 : getInputName().hashCode());
hashCode = prime * hashCode + ((getInputDescription() == null) ? 0 : getInputDescription().hashCode());
hashCode = prime * hashCode + ((getInputArn() == null) ? 0 : getInputArn().hashCode());
hashCode = prime * hashCode + ((getCreationTime() == null) ? 0 : getCreationTime().hashCode());
hashCode = prime * hashCode + ((getLastUpdateTime() == null) ? 0 : getLastUpdateTime().hashCode());
hashCode = prime * hashCode + ((getStatus() == null) ? 0 : getStatus().hashCode());
return hashCode;
}
@Override
public InputConfiguration clone() {
try {
return (InputConfiguration) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.iotevents.model.transform.InputConfigurationMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| {
"content_hash": "f2aad8385cea9af371800045f81e51b5",
"timestamp": "",
"source": "github",
"line_count": 409,
"max_line_length": 137,
"avg_line_length": 26.9119804400978,
"alnum_prop": 0.5725447442536568,
"repo_name": "jentfoo/aws-sdk-java",
"id": "0406b01ccfd5f66c0311c6b10496a5bf7aace61d",
"size": "11587",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-iotevents/src/main/java/com/amazonaws/services/iotevents/model/InputConfiguration.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "270"
},
{
"name": "FreeMarker",
"bytes": "173637"
},
{
"name": "Gherkin",
"bytes": "25063"
},
{
"name": "Java",
"bytes": "356214839"
},
{
"name": "Scilab",
"bytes": "3924"
},
{
"name": "Shell",
"bytes": "295"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace minNum
{
class minNum
{
static void Main(string[] args)
{
var n = int.Parse(Console.ReadLine());
var min = int.MaxValue;
for (int i = 0; i < n; i++)
{
var num = int.Parse(Console.ReadLine());
if (num<min)
{
min = num;
}
}
Console.WriteLine(min);
}
}
}
| {
"content_hash": "d676bd3a579e9f3d69fccd9fd3c84b5b",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 56,
"avg_line_length": 20.5,
"alnum_prop": 0.4564459930313589,
"repo_name": "delian1986/SoftUni-C-Sharp-repo",
"id": "2ee68197a5002f089f7bea1053b1e81f6eda53a9",
"size": "576",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Programming Basics/05.Cycles (For Loops)/ForCycleLekcia/minNum/minNum.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "111"
},
{
"name": "C#",
"bytes": "1666528"
},
{
"name": "CSS",
"bytes": "513"
},
{
"name": "HTML",
"bytes": "31742"
},
{
"name": "JavaScript",
"bytes": "225478"
}
],
"symlink_target": ""
} |
namespace base {
template <typename T>
struct DefaultSingletonTraits;
} // namespace base
namespace content {
class BrowserContext;
} // namespace content
namespace views {
class AXAuraObjWrapper;
class View;
} // namespace views
using AuraAXTreeSerializer =
ui::AXTreeSerializer<views::AXAuraObjWrapper*,
ui::AXNodeData,
ui::AXTreeData>;
// Manages a tree of automation nodes.
class AutomationManagerAura : public extensions::AutomationActionAdapter {
public:
// Get the single instance of this class.
static AutomationManagerAura* GetInstance();
// Enable automation support for views.
void Enable(content::BrowserContext* context);
// Disable automation support for views.
void Disable();
// Handle an event fired upon a |View|.
void HandleEvent(content::BrowserContext* context,
views::View* view,
ui::AXEvent event_type);
void HandleAlert(content::BrowserContext* context, const std::string& text);
// AutomationActionAdapter implementation.
void DoDefault(int32 id) override;
void Focus(int32 id) override;
void MakeVisible(int32 id) override;
void SetSelection(int32 anchor_id,
int32 anchor_offset,
int32 focus_id,
int32 focus_offset) override;
void ShowContextMenu(int32 id) override;
private:
friend struct base::DefaultSingletonTraits<AutomationManagerAura>;
AutomationManagerAura();
virtual ~AutomationManagerAura();
// Reset all state in this manager.
void ResetSerializer();
void SendEvent(content::BrowserContext* context,
views::AXAuraObjWrapper* aura_obj,
ui::AXEvent event_type);
// Whether automation support for views is enabled.
bool enabled_;
// Holds the active views-based accessibility tree. A tree currently consists
// of all views descendant to a |Widget| (see |AXTreeSourceViews|).
// A tree becomes active when an event is fired on a descendant view.
scoped_ptr<AXTreeSourceAura> current_tree_;
// Serializes incremental updates on the currently active tree
// |current_tree_|.
scoped_ptr<AuraAXTreeSerializer> current_tree_serializer_;
bool processing_events_;
std::vector<std::pair<views::AXAuraObjWrapper*, ui::AXEvent>> pending_events_;
DISALLOW_COPY_AND_ASSIGN(AutomationManagerAura);
};
#endif // CHROME_BROWSER_UI_AURA_ACCESSIBILITY_AUTOMATION_MANAGER_AURA_H_
| {
"content_hash": "c73feaf74577ffb8fd77340ffc87cc18",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 80,
"avg_line_length": 30.54320987654321,
"alnum_prop": 0.7029102667744543,
"repo_name": "Workday/OpenFrame",
"id": "503252c1617e6467de9602d12f6ce367a50baadc",
"size": "3059",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "chrome/browser/ui/aura/accessibility/automation_manager_aura.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package edu.wustl.catissuecore.bizlogic.magetab;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.AbstractSDRFNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.SourceNode;
import uk.ac.ebi.arrayexpress2.magetab.datamodel.sdrf.node.attribute.ProviderAttribute;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.common.util.logger.Logger;
import gov.nih.nci.logging.api.util.StringUtils;
public class ProviderTransformer extends AbstractTransformer {
private static transient final Logger logger = Logger
.getCommonLogger(ProviderTransformer.class);
public ProviderTransformer() {
super("Provider", "Provider", "PI");
}
@Override
public void transform(Specimen specimen, AbstractSDRFNode sdrfNode) {
SourceNode sourceNode;
if (sdrfNode instanceof SourceNode) {
sourceNode = (SourceNode) sdrfNode;
} else {
logger.debug("Got a node which needs has no provider attribute for specimen"
+ (StringUtils.isBlank(specimen.getLabel()) ? StringUtils
.isBlank(specimen.getBarcode()) ? specimen
.getLabel() + "_ID" : specimen.getBarcode()
: specimen.getLabel()));
return;
}
CollectionProtocol cp = specimen.getSpecimenCollectionGroup()
.getCollectionProtocolRegistration().getCollectionProtocol();
if (cp != null && cp.getPrincipalInvestigator() != null) {
ProviderAttribute providerAttribute = new ProviderAttribute();
providerAttribute.setNodeName(cp.getPrincipalInvestigator()
.getLastName()
+ ", "
+ cp.getPrincipalInvestigator().getFirstName());
providerAttribute.setNodeType("Provider");
sourceNode.provider = providerAttribute;
}
}
@Override
public boolean isMageTabSpec() {
return true;
}
}
| {
"content_hash": "89c571be3279f011bbe2c3819440a9f8",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 88,
"avg_line_length": 40.88461538461539,
"alnum_prop": 0.6373471307619943,
"repo_name": "NCIP/catissue-core",
"id": "061ade1f9ecc1810ce3dfc195a677bc26120a44a",
"size": "2408",
"binary": false,
"copies": "1",
"ref": "refs/heads/trunk",
"path": "software/caTissue/modules/core/src/main/java/edu/wustl/catissuecore/bizlogic/magetab/ProviderTransformer.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "263825"
},
{
"name": "CSS",
"bytes": "355520"
},
{
"name": "Java",
"bytes": "11570343"
},
{
"name": "JavaScript",
"bytes": "957613"
},
{
"name": "Shell",
"bytes": "1912"
},
{
"name": "XSLT",
"bytes": "256376"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pl">
<head>
<!-- Generated by javadoc (1.8.0_60) on Wed Mar 30 11:39:23 CEST 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class play.libs.F.Tuple (Play! API)</title>
<meta name="date" content="2016-03-30">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class play.libs.F.Tuple (Play! API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../play/libs/F.Tuple.html" title="class in play.libs">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?play/libs/class-use/F.Tuple.html" target="_top">Frames</a></li>
<li><a href="F.Tuple.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class play.libs.F.Tuple" class="title">Uses of Class<br>play.libs.F.Tuple</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../play/libs/F.Tuple.html" title="class in play.libs">F.Tuple</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#play.libs">play.libs</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="play.libs">
<!-- -->
</a>
<h3>Uses of <a href="../../../play/libs/F.Tuple.html" title="class in play.libs">F.Tuple</a> in <a href="../../../play/libs/package-summary.html">play.libs</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../play/libs/F.Tuple.html" title="class in play.libs">F.Tuple</a> in <a href="../../../play/libs/package-summary.html">play.libs</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../play/libs/F.T2.html" title="class in play.libs">F.T2</a><A,B></span></code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../play/libs/package-summary.html">play.libs</a> that return <a href="../../../play/libs/F.Tuple.html" title="class in play.libs">F.Tuple</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <A,B> <a href="../../../play/libs/F.Tuple.html" title="class in play.libs">F.Tuple</a><A,B></code></td>
<td class="colLast"><span class="typeNameLabel">F.</span><code><span class="memberNameLink"><a href="../../../play/libs/F.html#Tuple-A-B-">Tuple</a></span>(A a,
B b)</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../play/libs/package-summary.html">play.libs</a> that return types with arguments of type <a href="../../../play/libs/F.Tuple.html" title="class in play.libs">F.Tuple</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <A,B> <a href="../../../play/libs/F.Promise.html" title="class in play.libs">F.Promise</a><<a href="../../../play/libs/F.Tuple.html" title="class in play.libs">F.Tuple</a><A,B>></code></td>
<td class="colLast"><span class="typeNameLabel">F.Promise.</span><code><span class="memberNameLink"><a href="../../../play/libs/F.Promise.html#wait2-play.libs.F.Promise-play.libs.F.Promise-">wait2</a></span>(<a href="../../../play/libs/F.Promise.html" title="class in play.libs">F.Promise</a><A> tA,
<a href="../../../play/libs/F.Promise.html" title="class in play.libs">F.Promise</a><B> tB)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../play/libs/F.Tuple.html" title="class in play.libs">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?play/libs/class-use/F.Tuple.html" target="_top">Frames</a></li>
<li><a href="F.Tuple.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><a href="http://guillaume.bort.fr">Guillaume Bort</a> & <a href="http://www.zenexity.fr">zenexity</a> - Distributed under <a href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache 2 licence</a>, without any warrantly</small></p>
</body>
</html>
| {
"content_hash": "582edbf7c7ddeea129f59513c040f618",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 310,
"avg_line_length": 42.21134020618557,
"alnum_prop": 0.6351202833068751,
"repo_name": "play1-maven-plugin/play1-maven-plugin.github.io",
"id": "1ef53e12da79793940049b92723dc36df84accde",
"size": "8189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "external-apidocs/com/google/code/maven-play-plugin/org/playframework/play/1.4.2/play/libs/class-use/F.Tuple.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "245466"
},
{
"name": "HTML",
"bytes": "161333450"
},
{
"name": "JavaScript",
"bytes": "11578"
}
],
"symlink_target": ""
} |
<?php
// Set up the global CI functions in their most minimal core representation
if ( ! function_exists('get_instance'))
{
function &get_instance()
{
$test = CI_TestCase::instance();
$test = $test->ci_instance();
return $test;
}
}
// --------------------------------------------------------------------
if ( ! function_exists('get_config'))
{
function &get_config()
{
$test = CI_TestCase::instance();
$config = $test->ci_get_config();
return $config;
}
}
if ( ! function_exists('config_item'))
{
function config_item($item)
{
$config =& get_config();
if ( ! isset($config[$item]))
{
return FALSE;
}
return $config[$item];
}
}
if ( ! function_exists('get_mimes'))
{
/**
* Returns the MIME types array from config/mimes.php
*
* @return array
*/
function &get_mimes()
{
static $_mimes = array();
if (empty($_mimes))
{
$path = realpath(PROJECT_BASE.'application/config/mimes.php');
if (is_file($path))
{
$_mimes = include($path);
}
}
return $_mimes;
}
}
// --------------------------------------------------------------------
if ( ! function_exists('load_class'))
{
function load_class($class, $directory = 'libraries', $prefix = 'CI_')
{
if ($directory !== 'core' OR $prefix !== 'CI_')
{
throw new Exception('Not Implemented: Non-core load_class()');
}
$test = CI_TestCase::instance();
$obj =& $test->ci_core_class($class);
if (is_string($obj))
{
throw new Exception('Bad Isolation: Use ci_set_core_class to set '.$class);
}
return $obj;
}
}
// This is sort of meh. Should probably be mocked up with
// controllable output, so that we can test some of our
// security code. The function itself will be tested in the
// bootstrap testsuite.
// --------------------------------------------------------------------
if ( ! function_exists('remove_invisible_characters'))
{
function remove_invisible_characters($str, $url_encoded = TRUE)
{
$non_displayables = array();
// every control character except newline (dec 10)
// carriage return (dec 13), and horizontal tab (dec 09)
if ($url_encoded)
{
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
}
$non_displayables[] = '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S'; // 00-08, 11, 12, 14-31, 127
do
{
$str = preg_replace($non_displayables, '', $str, -1, $count);
}
while ($count);
return $str;
}
}
// Clean up error messages
// --------------------------------------------------------------------
if ( ! function_exists('show_error'))
{
function show_error($message, $status_code = 500, $heading = 'An Error Was Encountered')
{
throw new RuntimeException('CI Error: '.$message);
}
}
if ( ! function_exists('show_404'))
{
function show_404($page = '', $log_error = TRUE)
{
throw new RuntimeException('CI Error: 404');
}
}
if ( ! function_exists('_exception_handler'))
{
function _exception_handler($severity, $message, $filepath, $line)
{
throw new RuntimeException('CI Exception: '.$message.' | '.$filepath.' | '.$line);
}
}
// We assume a few things about our environment ...
// --------------------------------------------------------------------
if ( ! function_exists('is_php'))
{
function is_php($version = '5.0.0')
{
return ! (version_compare(PHP_VERSION, $version) < 0);
}
}
if ( ! function_exists('is_really_writable'))
{
function is_really_writable($file)
{
return is_writable($file);
}
}
if ( ! function_exists('is_loaded'))
{
function &is_loaded()
{
$loaded = array();
return $loaded;
}
}
if ( ! function_exists('log_message'))
{
function log_message($level, $message, $php_error = FALSE)
{
return TRUE;
}
}
if ( ! function_exists('set_status_header'))
{
function set_status_header($code = 200, $text = '')
{
return TRUE;
}
} | {
"content_hash": "d81747910e23972cd66c637026f7aae4",
"timestamp": "",
"source": "github",
"line_count": 193,
"max_line_length": 92,
"avg_line_length": 20.04663212435233,
"alnum_prop": 0.5606099767381753,
"repo_name": "FreKil/Kmom03",
"id": "0ccfe1ea4b9a57cb730b01955a054ad6561b6c42",
"size": "3869",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "CodeIgniter/tests/mocks/core/common.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "734"
},
{
"name": "PHP",
"bytes": "1797111"
},
{
"name": "Python",
"bytes": "10215"
}
],
"symlink_target": ""
} |
{% extends "layout.html" %}
{% block body %}
<legend>{{ app.i18n.nav.about }}</legend>
<p style="padding: 20px;">
<strong>switchIt v0.9.3</strong><br />
by Christian schilling
</p>
{% endblock %} | {
"content_hash": "79c2397815729e0235da1519e515046e",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 41,
"avg_line_length": 16.833333333333332,
"alnum_prop": 0.6188118811881188,
"repo_name": "cschilling/switchIt",
"id": "8f30e096557a52775fd2f62f726fc13b9a5740e4",
"size": "202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/static/about.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "28754"
}
],
"symlink_target": ""
} |
<?php
namespace Dan\Services\ShortLinks;
use Dan\Contracts\ShortLinkContract;
use Dan\Support\Web;
class Links implements ShortLinkContract
{
/**
* Create the short link.
*
* @param $link
*
* @return mixed
*/
public function create($link)
{
$data = Web::post('https://links.ml/add', ['url' => $link]);
$json = json_decode($data, true);
if ($json == false) {
return $link;
}
if (!$json['success']) {
return $link;
}
return $json['url'];
}
}
| {
"content_hash": "d588db1c6f59272ebab1bd51f46a9a94",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 68,
"avg_line_length": 17.363636363636363,
"alnum_prop": 0.5095986038394416,
"repo_name": "UclCommander/Dan",
"id": "e474b6c8aa58cc6e31f3e3b00f8589bc175cbeca",
"size": "573",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Services/ShortLinks/Links.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "328592"
}
],
"symlink_target": ""
} |
<?php
/**
* Editor class for creating and adjusting users. This class guarantees data
* integrity and writes logs when user information changes.
*
* @task config Configuration
* @task edit Creating and Editing Users
* @task role Editing Roles
* @task email Adding, Removing and Changing Email
* @task internal Internals
*/
final class PhabricatorUserEditor extends PhabricatorEditor {
private $logs = array();
/* -( Creating and Editing Users )----------------------------------------- */
/**
* @task edit
*/
public function createNewUser(
PhabricatorUser $user,
PhabricatorUserEmail $email) {
if ($user->getID()) {
throw new Exception('User has already been created!');
}
if ($email->getID()) {
throw new Exception('Email has already been created!');
}
if (!PhabricatorUser::validateUsername($user->getUsername())) {
$valid = PhabricatorUser::describeValidUsername();
throw new Exception("Username is invalid! {$valid}");
}
// Always set a new user's email address to primary.
$email->setIsPrimary(1);
// If the primary address is already verified, also set the verified flag
// on the user themselves.
if ($email->getIsVerified()) {
$user->setIsEmailVerified(1);
}
$this->willAddEmail($email);
$user->openTransaction();
try {
$user->save();
$email->setUserPHID($user->getPHID());
$email->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
// We might have written the user but failed to write the email; if
// so, erase the IDs we attached.
$user->setID(null);
$user->setPHID(null);
$user->killTransaction();
throw $ex;
}
$log = PhabricatorUserLog::initializeNewLog(
$this->requireActor(),
$user->getPHID(),
PhabricatorUserLog::ACTION_CREATE);
$log->setNewValue($email->getAddress());
$log->save();
$user->saveTransaction();
return $this;
}
/**
* @task edit
*/
public function updateUser(
PhabricatorUser $user,
PhabricatorUserEmail $email = null) {
if (!$user->getID()) {
throw new Exception('User has not been created yet!');
}
$user->openTransaction();
$user->save();
if ($email) {
$email->save();
}
$log = PhabricatorUserLog::initializeNewLog(
$this->requireActor(),
$user->getPHID(),
PhabricatorUserLog::ACTION_EDIT);
$log->save();
$user->saveTransaction();
return $this;
}
/**
* @task edit
*/
public function changePassword(
PhabricatorUser $user,
PhutilOpaqueEnvelope $envelope) {
if (!$user->getID()) {
throw new Exception('User has not been created yet!');
}
$user->openTransaction();
$user->reload();
$user->setPassword($envelope);
$user->save();
$log = PhabricatorUserLog::initializeNewLog(
$this->requireActor(),
$user->getPHID(),
PhabricatorUserLog::ACTION_CHANGE_PASSWORD);
$log->save();
$user->saveTransaction();
}
/**
* @task edit
*/
public function changeUsername(PhabricatorUser $user, $username) {
$actor = $this->requireActor();
if (!$user->getID()) {
throw new Exception('User has not been created yet!');
}
if (!PhabricatorUser::validateUsername($username)) {
$valid = PhabricatorUser::describeValidUsername();
throw new Exception("Username is invalid! {$valid}");
}
$old_username = $user->getUsername();
$user->openTransaction();
$user->reload();
$user->setUsername($username);
try {
$user->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
$user->setUsername($old_username);
$user->killTransaction();
throw $ex;
}
$log = PhabricatorUserLog::initializeNewLog(
$actor,
$user->getPHID(),
PhabricatorUserLog::ACTION_CHANGE_USERNAME);
$log->setOldValue($old_username);
$log->setNewValue($username);
$log->save();
$user->saveTransaction();
$user->sendUsernameChangeEmail($actor, $old_username);
}
/* -( Editing Roles )------------------------------------------------------ */
/**
* @task role
*/
public function makeAdminUser(PhabricatorUser $user, $admin) {
$actor = $this->requireActor();
if (!$user->getID()) {
throw new Exception('User has not been created yet!');
}
$user->openTransaction();
$user->beginWriteLocking();
$user->reload();
if ($user->getIsAdmin() == $admin) {
$user->endWriteLocking();
$user->killTransaction();
return $this;
}
$log = PhabricatorUserLog::initializeNewLog(
$actor,
$user->getPHID(),
PhabricatorUserLog::ACTION_ADMIN);
$log->setOldValue($user->getIsAdmin());
$log->setNewValue($admin);
$user->setIsAdmin((int)$admin);
$user->save();
$log->save();
$user->endWriteLocking();
$user->saveTransaction();
return $this;
}
/**
* @task role
*/
public function makeSystemAgentUser(PhabricatorUser $user, $system_agent) {
$actor = $this->requireActor();
if (!$user->getID()) {
throw new Exception('User has not been created yet!');
}
$user->openTransaction();
$user->beginWriteLocking();
$user->reload();
if ($user->getIsSystemAgent() == $system_agent) {
$user->endWriteLocking();
$user->killTransaction();
return $this;
}
$log = PhabricatorUserLog::initializeNewLog(
$actor,
$user->getPHID(),
PhabricatorUserLog::ACTION_SYSTEM_AGENT);
$log->setOldValue($user->getIsSystemAgent());
$log->setNewValue($system_agent);
$user->setIsSystemAgent((int)$system_agent);
$user->save();
$log->save();
$user->endWriteLocking();
$user->saveTransaction();
return $this;
}
/**
* @task role
*/
public function disableUser(PhabricatorUser $user, $disable) {
$actor = $this->requireActor();
if (!$user->getID()) {
throw new Exception('User has not been created yet!');
}
$user->openTransaction();
$user->beginWriteLocking();
$user->reload();
if ($user->getIsDisabled() == $disable) {
$user->endWriteLocking();
$user->killTransaction();
return $this;
}
$log = PhabricatorUserLog::initializeNewLog(
$actor,
$user->getPHID(),
PhabricatorUserLog::ACTION_DISABLE);
$log->setOldValue($user->getIsDisabled());
$log->setNewValue($disable);
$user->setIsDisabled((int)$disable);
$user->save();
$log->save();
$user->endWriteLocking();
$user->saveTransaction();
return $this;
}
/**
* @task role
*/
public function approveUser(PhabricatorUser $user, $approve) {
$actor = $this->requireActor();
if (!$user->getID()) {
throw new Exception('User has not been created yet!');
}
$user->openTransaction();
$user->beginWriteLocking();
$user->reload();
if ($user->getIsApproved() == $approve) {
$user->endWriteLocking();
$user->killTransaction();
return $this;
}
$log = PhabricatorUserLog::initializeNewLog(
$actor,
$user->getPHID(),
PhabricatorUserLog::ACTION_APPROVE);
$log->setOldValue($user->getIsApproved());
$log->setNewValue($approve);
$user->setIsApproved($approve);
$user->save();
$log->save();
$user->endWriteLocking();
$user->saveTransaction();
return $this;
}
/* -( Adding, Removing and Changing Email )-------------------------------- */
/**
* @task email
*/
public function addEmail(
PhabricatorUser $user,
PhabricatorUserEmail $email) {
$actor = $this->requireActor();
if (!$user->getID()) {
throw new Exception('User has not been created yet!');
}
if ($email->getID()) {
throw new Exception('Email has already been created!');
}
// Use changePrimaryEmail() to change primary email.
$email->setIsPrimary(0);
$email->setUserPHID($user->getPHID());
$this->willAddEmail($email);
$user->openTransaction();
$user->beginWriteLocking();
$user->reload();
try {
$email->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
$user->endWriteLocking();
$user->killTransaction();
throw $ex;
}
$log = PhabricatorUserLog::initializeNewLog(
$actor,
$user->getPHID(),
PhabricatorUserLog::ACTION_EMAIL_ADD);
$log->setNewValue($email->getAddress());
$log->save();
$user->endWriteLocking();
$user->saveTransaction();
return $this;
}
/**
* @task email
*/
public function removeEmail(
PhabricatorUser $user,
PhabricatorUserEmail $email) {
$actor = $this->requireActor();
if (!$user->getID()) {
throw new Exception('User has not been created yet!');
}
if (!$email->getID()) {
throw new Exception('Email has not been created yet!');
}
$user->openTransaction();
$user->beginWriteLocking();
$user->reload();
$email->reload();
if ($email->getIsPrimary()) {
throw new Exception("Can't remove primary email!");
}
if ($email->getUserPHID() != $user->getPHID()) {
throw new Exception('Email not owned by user!');
}
$email->delete();
$log = PhabricatorUserLog::initializeNewLog(
$actor,
$user->getPHID(),
PhabricatorUserLog::ACTION_EMAIL_REMOVE);
$log->setOldValue($email->getAddress());
$log->save();
$user->endWriteLocking();
$user->saveTransaction();
$this->revokePasswordResetLinks($user);
return $this;
}
/**
* @task email
*/
public function changePrimaryEmail(
PhabricatorUser $user,
PhabricatorUserEmail $email) {
$actor = $this->requireActor();
if (!$user->getID()) {
throw new Exception('User has not been created yet!');
}
if (!$email->getID()) {
throw new Exception('Email has not been created yet!');
}
$user->openTransaction();
$user->beginWriteLocking();
$user->reload();
$email->reload();
if ($email->getUserPHID() != $user->getPHID()) {
throw new Exception('User does not own email!');
}
if ($email->getIsPrimary()) {
throw new Exception('Email is already primary!');
}
if (!$email->getIsVerified()) {
throw new Exception('Email is not verified!');
}
$old_primary = $user->loadPrimaryEmail();
if ($old_primary) {
$old_primary->setIsPrimary(0);
$old_primary->save();
}
$email->setIsPrimary(1);
$email->save();
$log = PhabricatorUserLog::initializeNewLog(
$actor,
$user->getPHID(),
PhabricatorUserLog::ACTION_EMAIL_PRIMARY);
$log->setOldValue($old_primary ? $old_primary->getAddress() : null);
$log->setNewValue($email->getAddress());
$log->save();
$user->endWriteLocking();
$user->saveTransaction();
if ($old_primary) {
$old_primary->sendOldPrimaryEmail($user, $email);
}
$email->sendNewPrimaryEmail($user);
$this->revokePasswordResetLinks($user);
return $this;
}
/**
* Verify a user's email address.
*
* This verifies an individual email address. If the address is the user's
* primary address and their account was not previously verified, their
* account is marked as email verified.
*
* @task email
*/
public function verifyEmail(
PhabricatorUser $user,
PhabricatorUserEmail $email) {
$actor = $this->requireActor();
if (!$user->getID()) {
throw new Exception('User has not been created yet!');
}
if (!$email->getID()) {
throw new Exception('Email has not been created yet!');
}
$user->openTransaction();
$user->beginWriteLocking();
$user->reload();
$email->reload();
if ($email->getUserPHID() != $user->getPHID()) {
throw new Exception(pht('User does not own email!'));
}
if (!$email->getIsVerified()) {
$email->setIsVerified(1);
$email->save();
$log = PhabricatorUserLog::initializeNewLog(
$actor,
$user->getPHID(),
PhabricatorUserLog::ACTION_EMAIL_VERIFY);
$log->setNewValue($email->getAddress());
$log->save();
}
if (!$user->getIsEmailVerified()) {
// If the user just verified their primary email address, mark their
// account as email verified.
$user_primary = $user->loadPrimaryEmail();
if ($user_primary->getID() == $email->getID()) {
$user->setIsEmailVerified(1);
$user->save();
}
}
$user->endWriteLocking();
$user->saveTransaction();
}
/* -( Internals )---------------------------------------------------------- */
/**
* @task internal
*/
private function willAddEmail(PhabricatorUserEmail $email) {
// Hard check before write to prevent creation of disallowed email
// addresses. Normally, the application does checks and raises more
// user friendly errors for us, but we omit the courtesy checks on some
// pathways like administrative scripts for simplicity.
if (!PhabricatorUserEmail::isValidAddress($email->getAddress())) {
throw new Exception(PhabricatorUserEmail::describeValidAddresses());
}
if (!PhabricatorUserEmail::isAllowedAddress($email->getAddress())) {
throw new Exception(PhabricatorUserEmail::describeAllowedAddresses());
}
$application_email = id(new PhabricatorMetaMTAApplicationEmailQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withAddresses(array($email->getAddress()))
->executeOne();
if ($application_email) {
throw new Exception($application_email->getInUseMessage());
}
}
private function revokePasswordResetLinks(PhabricatorUser $user) {
// Revoke any outstanding password reset links. If an attacker compromises
// an account, changes the email address, and sends themselves a password
// reset link, it could otherwise remain live for a short period of time
// and allow them to compromise the account again later.
PhabricatorAuthTemporaryToken::revokeTokens(
$user,
array($user->getPHID()),
array(
PhabricatorAuthSessionEngine::ONETIME_TEMPORARY_TOKEN_TYPE,
PhabricatorAuthSessionEngine::PASSWORD_TEMPORARY_TOKEN_TYPE,
));
}
}
| {
"content_hash": "6985937b3e9805544b9f63299bbb5048",
"timestamp": "",
"source": "github",
"line_count": 606,
"max_line_length": 80,
"avg_line_length": 24.902640264026402,
"alnum_prop": 0.5759724339010006,
"repo_name": "coursera/phabricator",
"id": "5c3ff67a6c13c27aafffc93e22efa17463a3e2c8",
"size": "15091",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/applications/people/editor/PhabricatorUserEditor.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "282166"
},
{
"name": "JavaScript",
"bytes": "725897"
},
{
"name": "Makefile",
"bytes": "6426"
},
{
"name": "PHP",
"bytes": "11370957"
},
{
"name": "Python",
"bytes": "12260"
},
{
"name": "Shell",
"bytes": "8229"
}
],
"symlink_target": ""
} |
using System;
using Newtonsoft.Json.Linq;
using Naveego.Live;
namespace Naveego
{
public class Connection
{
public Guid Id { get; set; }
public string Name { get; set; }
public string RunAt { get; set; }
public string Type { get; set; }
public string Status { get; set; }
public BusinessApplicationRef Application { get; set; }
public DateTime? StatusDate { get; set; }
public GuidReference SyncClient { get; set; }
public JObject Settings { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public DateTime ModifiedOn { get; set; }
public string ModifiedBy { get; set; }
public LiveStatus Live { get; set; }
}
}
| {
"content_hash": "28415c7b48a8912e1fbf412c58e00576",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 63,
"avg_line_length": 22.07894736842105,
"alnum_prop": 0.5637663885578069,
"repo_name": "Naveego/naveego-net",
"id": "94bec841c42b687d3c16744776b8a7cc2ef570ba",
"size": "1429",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Naveego/Connection.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#include "Class_Objects.h"
#include "Sales_item.h"
#include "Screen.h"
void Define_Sales_item_Objects(void)
{
Sales_item empty; // use the default constructor
empty.Print_Information();
Sales_item Primer_3rd_Edition("0-201-82470-1");
Primer_3rd_Edition.Print_Information();
Sales_item Primer_4th_Edition(std::cin);
Primer_4th_Edition.Print_Information();
}
void Test_Screen_Class(void)
{
Screen myscreen(5, 3);
const Screen blank(5, 3);
char ch = myscreen.get(); // Call Screen::get(void)
ch = myscreen.get(0, 0); // Call Screen::get(index, index)
/* Move cursor to given position,
* and set that character.
*/
myscreen.move(4, 0).set('#'); /* This statement equals to
myscreen.move(4, 0);
myscreen.set('#');
*/
#if 0
/* Move cursor to given position, set that character
* and display the screen.
*/
myscreen.move(4, 0).set('#').display(std::cout);
/* The below code will fail if display is a const member function
* display return a const reference.
* We cannot call set on a const.
*/
myscreen.display(std::cout).set('*');
#else
myscreen.set('#').display(std::cout); // calls non-const version
blank.display(std::cout); // calls const version
#endif
}
| {
"content_hash": "bce83a6733415a93a8d6c9fa3878d9f7",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 67,
"avg_line_length": 24.21153846153846,
"alnum_prop": 0.6489277204130263,
"repo_name": "Frederick-Hsu/CPP_Primer",
"id": "7ebcb1389fb7f0eb0305188db1d9908876b98511",
"size": "1644",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Study_Class/Study_Class/Classes/Class_Objects.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "17576"
},
{
"name": "C++",
"bytes": "272209"
},
{
"name": "Makefile",
"bytes": "25599"
},
{
"name": "Shell",
"bytes": "2928"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/lang
http://www.springframework.org/schema/lang/spring-lang-2.0.xsd"
>
<bean id="foo" class="java.lang.String" depends-on="bsn,groovy,ruby,<error>unknown</error>"/>
<bean class="Customizer" id="customizer"/>
<lang:bsh script-interfaces="java.lang.Object,<error>unknown</error>" scope="<error>unknown</error>" id="bsn" script-source="<error>unknown</error>"/>
<lang:bsh script-interfaces="java.lang.Object" scope="prototype" id="bsn1" script-source="lang-schema.xml"/>
<lang:groovy script-source="<error>unknown</error>" id="groovy" customizer-ref="<error>foo</error>"/>
<lang:groovy script-source="lang-schema.xml" id="groovy2" customizer-ref="customizer"/>
<lang:jruby script-interfaces="java.lang.Object,<error>unknown</error>" id="ruby" script-source="<error>unknown</error>"/>
</beans> | {
"content_hash": "2440bb93dd3e44f3e12ce66b3e51f9e7",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 152,
"avg_line_length": 49.458333333333336,
"alnum_prop": 0.7337826453243471,
"repo_name": "consulo/consulo-spring",
"id": "3cb77c517439739b4489d641f3806e449c1737ed",
"size": "1187",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spring-tests/testData/lang-schema/lang-schema.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "6976"
},
{
"name": "Java",
"bytes": "2765692"
},
{
"name": "Lex",
"bytes": "3178"
}
],
"symlink_target": ""
} |
@interface IDEPreferencePaneToolbarItem : NSToolbarItem
{
}
- (BOOL)validateMenuItem:(id)arg1;
@end
| {
"content_hash": "c1e19e0b82b3758cf8bdb83f103681af",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 55,
"avg_line_length": 12.875,
"alnum_prop": 0.7669902912621359,
"repo_name": "XVimProject/XVim2",
"id": "2c82bff51206c6dd913d34827b29fc4f0d31c7f9",
"size": "280",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XVim2/XcodeHeader/IDEKit/IDEPreferencePaneToolbarItem.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3672"
},
{
"name": "C",
"bytes": "65096"
},
{
"name": "C++",
"bytes": "10438"
},
{
"name": "Makefile",
"bytes": "2176"
},
{
"name": "Objective-C",
"bytes": "5172541"
},
{
"name": "Python",
"bytes": "1161"
},
{
"name": "Ruby",
"bytes": "1083"
},
{
"name": "Shell",
"bytes": "593"
},
{
"name": "Swift",
"bytes": "24720"
}
],
"symlink_target": ""
} |
namespace gvisor {
namespace testing {
// Opens the replica end of the passed master as R/W and nonblocking. It does
// not set the replica as the controlling TTY.
PosixErrorOr<FileDescriptor> OpenReplica(const FileDescriptor& master);
// Identical to the above OpenReplica, but flags are all specified by the
// caller.
PosixErrorOr<FileDescriptor> OpenReplica(const FileDescriptor& master,
int flags);
// Get the number of the replica end of the master.
PosixErrorOr<int> ReplicaID(const FileDescriptor& master);
} // namespace testing
} // namespace gvisor
#endif // GVISOR_TEST_UTIL_PTY_UTIL_H_
| {
"content_hash": "992f51d6b4dfbf1ffca48a86a8f75eae",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 77,
"avg_line_length": 34.10526315789474,
"alnum_prop": 0.7191358024691358,
"repo_name": "google/gvisor",
"id": "0cca2182c82b67ebc1affcfad89757af4a9022f6",
"size": "1395",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/util/pty_util.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "153442"
},
{
"name": "C",
"bytes": "32010"
},
{
"name": "C++",
"bytes": "3956729"
},
{
"name": "Dockerfile",
"bytes": "11649"
},
{
"name": "Go",
"bytes": "14556808"
},
{
"name": "HTML",
"bytes": "18035"
},
{
"name": "Handlebars",
"bytes": "103"
},
{
"name": "JavaScript",
"bytes": "983"
},
{
"name": "Makefile",
"bytes": "40575"
},
{
"name": "Python",
"bytes": "6200"
},
{
"name": "Ruby",
"bytes": "2430"
},
{
"name": "SCSS",
"bytes": "4134"
},
{
"name": "Shell",
"bytes": "60834"
},
{
"name": "Starlark",
"bytes": "655995"
}
],
"symlink_target": ""
} |
/**
*
*
* Authors:
* - Alexandros Lemesios
*/
"use strict";
const chai = require("chai");
const should = chai.should();
const fs = require("fs");
const printer = require("./../../printer")();
describe("Printer tests", () => {
it("should create a report with 3 rows and 4 headers and compare it with a masterFile report. The two reports should be equal", (done) => {
const data =
[
{
customerName: 'ind ind',
fileManager: 'administrator',
relationshipDate: "2016-12-04",
customerRisk: 720
},
{
customerName: 'ind 2 ind 2',
fileManager: 'administrator',
relationshipDate:" 2016-12-04",
customerRisk: 340
},
{
customerName: 'Test Test',
fileManager: 'administrator',
relationshipDate: "2016-12-04",
customerRisk: 640
}
];
const name = "Missing Addresses - Individual.pdf"
const headers = [ "Customer name", "File manager", "Relationship Started", "Customer Risk"];
const options = {landscape: true};
const title = "Missing addresses";
// let masterFile = fs.readFileSync(`./tmp/${name}`, "utf8");
printer.print(name, headers, data , options, title, (err, reportName) => {
let createdFile = fs.readFileSync(`./../test/${name}`, "utf8");
// removeTrash(createdFile).should.equal(removeTrash(masterFile));
done();
});
});
it("should create a report with 2 rows and three headers and then compare it to the master report", (done) => {
const data =
[
{
customerName: 'ind ind',
relationshipDate: "2016-12-04",
customerRisk: 720
},
{
customerName: 'ind 2 ind 2',
relationshipDate:" 2016-12-04",
customerRisk: 340
}
]
const name = "(1)Missing addresses - Individual.pdf"
const headers = [ "Customer name", "Relationship Started", "Customer Risk"];
const options = {landscape: true};
const title = "Missing addresses";
let masterFile = fs.readFileSync(`./tmp/${name}`, "utf8");
printer.print(name, headers, data, options, title, (err, reportName) => {
let createdFile = fs.readFileSync(`./../test/${name}`, "utf8");
removeTrash(createdFile).should.equal(removeTrash(masterFile));
done();
});
});
});
const removeTrash = (str) => {
let splitted = str.split("\n");
for (let i = 0; i < splitted.length; i++) {
if (splitted[i].includes("CreationDate")) {
splitted.splice(i, 1);
}
}
return splitted.join("\n");
}
| {
"content_hash": "b5ddfa47bcc48e3f8c50a5caa14c9d07",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 141,
"avg_line_length": 29.06741573033708,
"alnum_prop": 0.5833011209895632,
"repo_name": "A1exLemesios/knex-training",
"id": "5210e8ebb3b117368e52961ba4f057b43b328bf2",
"size": "2587",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "printer/test/index.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "17745"
}
],
"symlink_target": ""
} |
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document;
import com.yahoo.text.Utf8Array;
import com.yahoo.text.Utf8String;
/**
* A full document type name. The name is case sensitive. This is a <i>value object</i>.
*
* @author bratseth
*/
public final class DataTypeName {
private final Utf8String name;
/**
* Creates a document name from a string of the form "name"
*
* @param name The name string to parse.
* @throws NumberFormatException if the version part of the name is present but is not a number
*/
public DataTypeName(String name) {
this.name = new Utf8String(name);
}
public DataTypeName(Utf8Array name) {
this.name = new Utf8String(name);
}
public DataTypeName(Utf8String name) {
this.name = new Utf8String(name);
}
public String getName() { return name.toString(); }
@Override
public String toString() { return name.toString(); }
@Override
public int hashCode() { return name.hashCode(); }
@Override
public boolean equals(Object obj) {
if (!(obj instanceof DataTypeName)) return false;
DataTypeName datatype = (DataTypeName)obj;
return this.name.equals(datatype.name);
}
}
| {
"content_hash": "75cd110ddf1d437a91e73bfd5b352a5e",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 104,
"avg_line_length": 27.914893617021278,
"alnum_prop": 0.6646341463414634,
"repo_name": "vespa-engine/vespa",
"id": "ef9ddd2b21dd798723cbcf15e532c30a221a0bd4",
"size": "1312",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "document/src/main/java/com/yahoo/document/DataTypeName.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "8130"
},
{
"name": "C",
"bytes": "60315"
},
{
"name": "C++",
"bytes": "29580035"
},
{
"name": "CMake",
"bytes": "593981"
},
{
"name": "Emacs Lisp",
"bytes": "91"
},
{
"name": "GAP",
"bytes": "3312"
},
{
"name": "Go",
"bytes": "560664"
},
{
"name": "HTML",
"bytes": "54520"
},
{
"name": "Java",
"bytes": "40814190"
},
{
"name": "JavaScript",
"bytes": "73436"
},
{
"name": "LLVM",
"bytes": "6152"
},
{
"name": "Lex",
"bytes": "11499"
},
{
"name": "Makefile",
"bytes": "5553"
},
{
"name": "Objective-C",
"bytes": "12369"
},
{
"name": "Perl",
"bytes": "23134"
},
{
"name": "Python",
"bytes": "52392"
},
{
"name": "Roff",
"bytes": "17506"
},
{
"name": "Ruby",
"bytes": "10690"
},
{
"name": "Shell",
"bytes": "268737"
},
{
"name": "Yacc",
"bytes": "14735"
}
],
"symlink_target": ""
} |
package com.easternedgerobotics.rov.io.joystick;
import com.easternedgerobotics.rov.value.MotionValue;
import net.java.games.input.Component;
import net.java.games.input.Event;
import rx.Observable;
import java.util.List;
public class LogitechExtremeJoystick implements Joystick {
public static final int AXIS_INDEX_HEAVE = 3;
public static final int AXIS_INDEX_SWAY = 0;
public static final int AXIS_INDEX_SURGE = 1;
public static final int AXIS_INDEX_YAW = 2;
private final Observable<Event> events;
private final List<Component> axes;
private final List<Component> buttons;
public LogitechExtremeJoystick(
final Observable<Event> events,
final List<Component> axes,
final List<Component> buttons
) {
this.events = events.share();
this.axes = axes;
this.buttons = buttons;
}
/**
* Returns the stream of button presses.
*
* @return the stream of button presses.
*/
@Override
public final Observable<Boolean> button(final int index) {
final Observable<Event> buttonEvents = events.filter(
event -> buttons.indexOf(event.getComponent()) == (index - 1));
return buttonEvents.map(event -> event.getValue() == 1f);
}
/**
* Returns the Observable stream of joystick motion.
*
* @return a stream of motion values.
*/
@Override
public final Observable<MotionValue> axes() {
final Observable<Boolean> joystickTrigger = button(1).startWith(false);
return Observable.switchOnNext(
joystickTrigger.map(press ->
events.filter(this::isAxisEvent).map(e -> createMotionValue(press))));
}
private boolean isAxisEvent(final Event event) {
return event.getComponent().getIdentifier() instanceof Component.Identifier.Axis;
}
private MotionValue createMotionValue(final boolean rolling) {
final float heave = axes.get(AXIS_INDEX_HEAVE).getPollData();
final float sway = -axes.get(AXIS_INDEX_SWAY).getPollData();
final float surge = axes.get(AXIS_INDEX_SURGE).getPollData();
final float yaw = axes.get(AXIS_INDEX_YAW).getPollData();
if (rolling) {
return new MotionValue(heave, 0, surge, 0, yaw, -sway);
}
return new MotionValue(heave, sway, surge, 0, yaw, 0);
}
}
| {
"content_hash": "104573494690bf73c2272a6bbb220296",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 89,
"avg_line_length": 30.21518987341772,
"alnum_prop": 0.6581483033095936,
"repo_name": "EasternEdgeRobotics/2016",
"id": "912f47c316dd6e5d6a22f04b6a4e62caea19a54a",
"size": "2387",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/com/easternedgerobotics/rov/io/joystick/LogitechExtremeJoystick.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "1495"
},
{
"name": "Java",
"bytes": "235460"
},
{
"name": "Kotlin",
"bytes": "3993"
},
{
"name": "Python",
"bytes": "612"
},
{
"name": "Shell",
"bytes": "1284"
}
],
"symlink_target": ""
} |
package org.elasticsearch.indices.warmer;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.service.IndexService;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.shard.service.IndexShard;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.threadpool.ThreadPool;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
*/
public class InternalIndicesWarmer extends AbstractComponent implements IndicesWarmer {
private final ThreadPool threadPool;
private final ClusterService clusterService;
private final IndicesService indicesService;
private final CopyOnWriteArrayList<Listener> listeners = new CopyOnWriteArrayList<Listener>();
@Inject
public InternalIndicesWarmer(Settings settings, ThreadPool threadPool, ClusterService clusterService, IndicesService indicesService) {
super(settings);
this.threadPool = threadPool;
this.clusterService = clusterService;
this.indicesService = indicesService;
}
@Override
public void addListener(Listener listener) {
listeners.add(listener);
}
@Override
public void removeListener(Listener listener) {
listeners.remove(listener);
}
public void warm(final ShardId shardId, final Engine.Searcher searcher) {
final IndexMetaData indexMetaData = clusterService.state().metaData().index(shardId.index().name());
if (indexMetaData == null) {
return;
}
if (!indexMetaData.settings().getAsBoolean("index.warm.enabled", settings.getAsBoolean("index.warm.enabled", true))) {
return;
}
IndexService indexService = indicesService.indexService(shardId.index().name());
if (indexService == null) {
return;
}
IndexShard indexShard = indexService.shard(shardId.id());
if (indexShard == null) {
return;
}
if (logger.isTraceEnabled()) {
logger.trace("[{}][{}] warming [{}]", shardId.index().name(), shardId.id(), searcher.reader());
}
indexShard.warmerService().onPreWarm();
long time = System.nanoTime();
for (final Listener listener : listeners) {
final CountDownLatch latch = new CountDownLatch(1);
threadPool.executor(listener.executor()).execute(new Runnable() {
@Override
public void run() {
try {
listener.warm(shardId, indexMetaData, searcher);
} catch (Throwable e) {
logger.warn("[{}][{}] failed to warm [{}]", e, shardId.index().name(), shardId.id(), listener);
} finally {
latch.countDown();
}
}
});
try {
latch.await();
} catch (InterruptedException e) {
return;
}
}
long took = System.nanoTime() - time;
indexShard.warmerService().onPostWarm(took);
if (logger.isTraceEnabled()) {
logger.trace("[{}][{}] warming took [{}]", shardId.index().name(), shardId.id(), new TimeValue(took, TimeUnit.NANOSECONDS));
}
}
}
| {
"content_hash": "ceaa209fe1c43f1bbab3c7801401a5f3",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 138,
"avg_line_length": 37.19191919191919,
"alnum_prop": 0.6409560021727322,
"repo_name": "chanil1218/elasticsearch",
"id": "8bee5ea33aa3f33c0d8faa3a9ac30570341a8579",
"size": "4487",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/elasticsearch/indices/warmer/InternalIndicesWarmer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
set -x
composer self-update
originalDirectory=$(pwd)
cd ..
wget https://github.com/wikimedia/mediawiki/archive/$MW.tar.gz
tar -zxf $MW.tar.gz
mv mediawiki-$MW phase3
cd phase3
if [ "$MW" != "1.21.0" ]
then
composer require 'phpunit/phpunit=3.7.*' --prefer-source
fi
if [ "$DB" == "postgres" ]
then
psql -c 'create database its_a_mw;' -U postgres
php maintenance/install.php --dbtype $DBTYPE --dbuser postgres --dbname its_a_mw --pass nyan TravisWiki admin --scriptpath /TravisWiki
else
mysql -e 'create database its_a_mw;'
php maintenance/install.php --dbtype $DBTYPE --dbuser root --dbname its_a_mw --dbpath $(pwd) --pass nyan TravisWiki admin --scriptpath /TravisWiki
fi
cd extensions
cp -r $originalDirectory ParserHooks
cd ParserHooks
composer install --prefer-source
if [ "$MW" == "1.21.0" ]
then
composer require 'phpunit/phpunit=3.7.*' --prefer-source
fi
cd ../..
echo 'require_once( __DIR__ . "/extensions/ParserHooks/ParserHooks.php" );' >> LocalSettings.php
echo 'error_reporting(E_ALL| E_STRICT);' >> LocalSettings.php
echo 'ini_set("display_errors", 1);' >> LocalSettings.php
echo '$wgShowExceptionDetails = true;' >> LocalSettings.php
echo '$wgDevelopmentWarnings = true;' >> LocalSettings.php
echo "putenv( 'MW_INSTALL_PATH=$(pwd)' );" >> LocalSettings.php
php maintenance/update.php --quick
| {
"content_hash": "b95034f3332f95f25ed96f09cf34bb1c",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 147,
"avg_line_length": 26.019607843137255,
"alnum_prop": 0.7121326299924642,
"repo_name": "stuartbman/mediawiki-vagrant",
"id": "c7b97b01b2bae49884aca82724bc17c4a94eea8b",
"size": "1341",
"binary": false,
"copies": "5",
"ref": "refs/heads/master",
"path": "mediawiki/vendor/mediawiki/parser-hooks/build/travis/before_script.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3446"
},
{
"name": "Batchfile",
"bytes": "495"
},
{
"name": "CSS",
"bytes": "480614"
},
{
"name": "Cucumber",
"bytes": "16201"
},
{
"name": "HTML",
"bytes": "225396"
},
{
"name": "JavaScript",
"bytes": "3366202"
},
{
"name": "Makefile",
"bytes": "5945"
},
{
"name": "Nginx",
"bytes": "513"
},
{
"name": "PHP",
"bytes": "22034302"
},
{
"name": "PLSQL",
"bytes": "60144"
},
{
"name": "PLpgSQL",
"bytes": "32705"
},
{
"name": "Pascal",
"bytes": "1044"
},
{
"name": "Perl",
"bytes": "31741"
},
{
"name": "Puppet",
"bytes": "409448"
},
{
"name": "Python",
"bytes": "35272"
},
{
"name": "Ruby",
"bytes": "341717"
},
{
"name": "SQLPL",
"bytes": "705"
},
{
"name": "Shell",
"bytes": "47587"
}
],
"symlink_target": ""
} |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/analytics/admin/v1beta/resources.proto
namespace Google\Analytics\Admin\V1beta;
use UnexpectedValueException;
/**
* The category selected for this property, used for industry benchmarking.
*
* Protobuf type <code>google.analytics.admin.v1beta.IndustryCategory</code>
*/
class IndustryCategory
{
/**
* Industry category unspecified
*
* Generated from protobuf enum <code>INDUSTRY_CATEGORY_UNSPECIFIED = 0;</code>
*/
const INDUSTRY_CATEGORY_UNSPECIFIED = 0;
/**
* Automotive
*
* Generated from protobuf enum <code>AUTOMOTIVE = 1;</code>
*/
const AUTOMOTIVE = 1;
/**
* Business and industrial markets
*
* Generated from protobuf enum <code>BUSINESS_AND_INDUSTRIAL_MARKETS = 2;</code>
*/
const BUSINESS_AND_INDUSTRIAL_MARKETS = 2;
/**
* Finance
*
* Generated from protobuf enum <code>FINANCE = 3;</code>
*/
const FINANCE = 3;
/**
* Healthcare
*
* Generated from protobuf enum <code>HEALTHCARE = 4;</code>
*/
const HEALTHCARE = 4;
/**
* Technology
*
* Generated from protobuf enum <code>TECHNOLOGY = 5;</code>
*/
const TECHNOLOGY = 5;
/**
* Travel
*
* Generated from protobuf enum <code>TRAVEL = 6;</code>
*/
const TRAVEL = 6;
/**
* Other
*
* Generated from protobuf enum <code>OTHER = 7;</code>
*/
const OTHER = 7;
/**
* Arts and entertainment
*
* Generated from protobuf enum <code>ARTS_AND_ENTERTAINMENT = 8;</code>
*/
const ARTS_AND_ENTERTAINMENT = 8;
/**
* Beauty and fitness
*
* Generated from protobuf enum <code>BEAUTY_AND_FITNESS = 9;</code>
*/
const BEAUTY_AND_FITNESS = 9;
/**
* Books and literature
*
* Generated from protobuf enum <code>BOOKS_AND_LITERATURE = 10;</code>
*/
const BOOKS_AND_LITERATURE = 10;
/**
* Food and drink
*
* Generated from protobuf enum <code>FOOD_AND_DRINK = 11;</code>
*/
const FOOD_AND_DRINK = 11;
/**
* Games
*
* Generated from protobuf enum <code>GAMES = 12;</code>
*/
const GAMES = 12;
/**
* Hobbies and leisure
*
* Generated from protobuf enum <code>HOBBIES_AND_LEISURE = 13;</code>
*/
const HOBBIES_AND_LEISURE = 13;
/**
* Home and garden
*
* Generated from protobuf enum <code>HOME_AND_GARDEN = 14;</code>
*/
const HOME_AND_GARDEN = 14;
/**
* Internet and telecom
*
* Generated from protobuf enum <code>INTERNET_AND_TELECOM = 15;</code>
*/
const INTERNET_AND_TELECOM = 15;
/**
* Law and government
*
* Generated from protobuf enum <code>LAW_AND_GOVERNMENT = 16;</code>
*/
const LAW_AND_GOVERNMENT = 16;
/**
* News
*
* Generated from protobuf enum <code>NEWS = 17;</code>
*/
const NEWS = 17;
/**
* Online communities
*
* Generated from protobuf enum <code>ONLINE_COMMUNITIES = 18;</code>
*/
const ONLINE_COMMUNITIES = 18;
/**
* People and society
*
* Generated from protobuf enum <code>PEOPLE_AND_SOCIETY = 19;</code>
*/
const PEOPLE_AND_SOCIETY = 19;
/**
* Pets and animals
*
* Generated from protobuf enum <code>PETS_AND_ANIMALS = 20;</code>
*/
const PETS_AND_ANIMALS = 20;
/**
* Real estate
*
* Generated from protobuf enum <code>REAL_ESTATE = 21;</code>
*/
const REAL_ESTATE = 21;
/**
* Reference
*
* Generated from protobuf enum <code>REFERENCE = 22;</code>
*/
const REFERENCE = 22;
/**
* Science
*
* Generated from protobuf enum <code>SCIENCE = 23;</code>
*/
const SCIENCE = 23;
/**
* Sports
*
* Generated from protobuf enum <code>SPORTS = 24;</code>
*/
const SPORTS = 24;
/**
* Jobs and education
*
* Generated from protobuf enum <code>JOBS_AND_EDUCATION = 25;</code>
*/
const JOBS_AND_EDUCATION = 25;
/**
* Shopping
*
* Generated from protobuf enum <code>SHOPPING = 26;</code>
*/
const SHOPPING = 26;
private static $valueToName = [
self::INDUSTRY_CATEGORY_UNSPECIFIED => 'INDUSTRY_CATEGORY_UNSPECIFIED',
self::AUTOMOTIVE => 'AUTOMOTIVE',
self::BUSINESS_AND_INDUSTRIAL_MARKETS => 'BUSINESS_AND_INDUSTRIAL_MARKETS',
self::FINANCE => 'FINANCE',
self::HEALTHCARE => 'HEALTHCARE',
self::TECHNOLOGY => 'TECHNOLOGY',
self::TRAVEL => 'TRAVEL',
self::OTHER => 'OTHER',
self::ARTS_AND_ENTERTAINMENT => 'ARTS_AND_ENTERTAINMENT',
self::BEAUTY_AND_FITNESS => 'BEAUTY_AND_FITNESS',
self::BOOKS_AND_LITERATURE => 'BOOKS_AND_LITERATURE',
self::FOOD_AND_DRINK => 'FOOD_AND_DRINK',
self::GAMES => 'GAMES',
self::HOBBIES_AND_LEISURE => 'HOBBIES_AND_LEISURE',
self::HOME_AND_GARDEN => 'HOME_AND_GARDEN',
self::INTERNET_AND_TELECOM => 'INTERNET_AND_TELECOM',
self::LAW_AND_GOVERNMENT => 'LAW_AND_GOVERNMENT',
self::NEWS => 'NEWS',
self::ONLINE_COMMUNITIES => 'ONLINE_COMMUNITIES',
self::PEOPLE_AND_SOCIETY => 'PEOPLE_AND_SOCIETY',
self::PETS_AND_ANIMALS => 'PETS_AND_ANIMALS',
self::REAL_ESTATE => 'REAL_ESTATE',
self::REFERENCE => 'REFERENCE',
self::SCIENCE => 'SCIENCE',
self::SPORTS => 'SPORTS',
self::JOBS_AND_EDUCATION => 'JOBS_AND_EDUCATION',
self::SHOPPING => 'SHOPPING',
];
public static function name($value)
{
if (!isset(self::$valueToName[$value])) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no name defined for value %s', __CLASS__, $value));
}
return self::$valueToName[$value];
}
public static function value($name)
{
$const = __CLASS__ . '::' . strtoupper($name);
if (!defined($const)) {
throw new UnexpectedValueException(sprintf(
'Enum %s has no value defined for name %s', __CLASS__, $name));
}
return constant($const);
}
}
| {
"content_hash": "f864d694c7d16725f722300360e3b30b",
"timestamp": "",
"source": "github",
"line_count": 229,
"max_line_length": 85,
"avg_line_length": 27.528384279475983,
"alnum_prop": 0.5704314720812182,
"repo_name": "googleapis/google-cloud-php",
"id": "887b34452f65284fdb1ef408cdc17b6d393080cf",
"size": "6304",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "AnalyticsAdmin/src/V1beta/IndustryCategory.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "3333"
},
{
"name": "PHP",
"bytes": "47981731"
},
{
"name": "Python",
"bytes": "413107"
},
{
"name": "Shell",
"bytes": "8171"
}
],
"symlink_target": ""
} |
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var User = new Schema({
github: {
id: String,
displayName: String,
username: String,
publicRepos: Number
},
nbrClicks: {
clicks: Number
},
testObj:{thing:Number},
totalMins:Number
});
module.exports = mongoose.model('User', User);
| {
"content_hash": "5caaeadb28341783ed09c9e981e2bb3d",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 47,
"avg_line_length": 13.037037037037036,
"alnum_prop": 0.6363636363636364,
"repo_name": "calicode/Dailyprogress",
"id": "922211c4677b3f470d23e79aca346603f23ecd4f",
"size": "352",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/users.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3092"
},
{
"name": "HTML",
"bytes": "4582"
},
{
"name": "JavaScript",
"bytes": "288088"
}
],
"symlink_target": ""
} |
package com.querydsl.sql.spatial;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.geolatte.geom.codec.db.sqlserver.Decoders;
import org.geolatte.geom.codec.db.sqlserver.Encoders;
import org.jetbrains.annotations.Nullable;
import org.geolatte.geom.Geometry;
import org.geolatte.geom.codec.Wkt;
import com.querydsl.sql.types.AbstractType;
class SQLServerGeometryType extends AbstractType<Geometry> {
public static final SQLServerGeometryType DEFAULT = new SQLServerGeometryType();
private static final int DEFAULT_SRID = 4326;
public SQLServerGeometryType() {
super(Types.BLOB);
}
@Override
public Class<Geometry> getReturnedClass() {
return Geometry.class;
}
@Override
@Nullable
public Geometry getValue(ResultSet rs, int startIndex) throws SQLException {
byte[] bytes = rs.getBytes(startIndex);
if (bytes != null) {
return Decoders.decode(bytes);
} else {
return null;
}
}
@Override
public void setValue(PreparedStatement st, int startIndex, Geometry value) throws SQLException {
byte[] bytes = Encoders.encode(value);
st.setBytes(startIndex, bytes);
}
@Override
public String getLiteral(Geometry geometry) {
String str = Wkt.newEncoder(Wkt.Dialect.POSTGIS_EWKT_1).encode(geometry);
if (geometry.getSRID() > -1) {
return "geometry::STGeomFromText('" + str + "', " + geometry.getSRID() + ")";
} else {
return "geometry::STGeomFromText('" + str + "', " + DEFAULT_SRID + ")";
}
}
}
| {
"content_hash": "cdcebc025471250299c7ed549c0621bf",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 100,
"avg_line_length": 28.05,
"alnum_prop": 0.6660724896019014,
"repo_name": "lpandzic/querydsl",
"id": "67f33ebf845b61226b1af21da350e239f56e1aab",
"size": "2305",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "querydsl-sql-spatial/src/main/java/com/querydsl/sql/spatial/SQLServerGeometryType.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3436"
},
{
"name": "Clojure",
"bytes": "1890"
},
{
"name": "Java",
"bytes": "6461569"
},
{
"name": "Kotlin",
"bytes": "16982"
},
{
"name": "Puppet",
"bytes": "1212"
},
{
"name": "Ruby",
"bytes": "389"
},
{
"name": "Scala",
"bytes": "135114"
},
{
"name": "Shell",
"bytes": "2062"
},
{
"name": "XSLT",
"bytes": "35687"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
<title>Importing data from EEG devices — MNE 1.0.3 documentation</title>
<!-- Loaded before other Sphinx assets -->
<link href="../../_static/styles/theme.css?digest=1999514e3f237ded88cf" rel="stylesheet">
<link href="../../_static/styles/pydata-sphinx-theme.css?digest=1999514e3f237ded88cf" rel="stylesheet">
<link rel="stylesheet"
href="../../_static/vendor/fontawesome/5.13.0/css/all.min.css">
<link rel="preload" as="font" type="font/woff2" crossorigin
href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-solid-900.woff2">
<link rel="preload" as="font" type="font/woff2" crossorigin
href="../../_static/vendor/fontawesome/5.13.0/webfonts/fa-brands-400.woff2">
<link rel="stylesheet" type="text/css" href="../../_static/pygments.css" />
<link rel="stylesheet" type="text/css" href="../../_static/graphviz.css" />
<link rel="stylesheet" type="text/css" href="../../_static/bootstrap_divs.css" />
<link rel="stylesheet" type="text/css" href="../../_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="../../_static/sg_gallery.css" />
<link rel="stylesheet" type="text/css" href="../../_static/sg_gallery-binder.css" />
<link rel="stylesheet" type="text/css" href="../../_static/sg_gallery-dataframe.css" />
<link rel="stylesheet" type="text/css" href="../../_static/sg_gallery-rendered-html.css" />
<link rel="stylesheet" type="text/css" href="../../_static/style.css" />
<!-- Pre-loaded scripts that we'll load fully later -->
<link rel="preload" as="script" href="../../_static/scripts/pydata-sphinx-theme.js?digest=1999514e3f237ded88cf">
<script data-url_root="../../" id="documentation_options" src="../../_static/documentation_options.js"></script>
<script src="../../_static/jquery.js"></script>
<script src="../../_static/underscore.js"></script>
<script src="../../_static/doctools.js"></script>
<script src="../../_static/bootstrap_divs.js"></script>
<script src="../../_static/clipboard.min.js"></script>
<script src="../../_static/copybutton.js"></script>
<link rel="shortcut icon" href="../../_static/favicon.ico"/>
<link rel="index" title="Index" href="../../genindex.html" />
<link rel="search" title="Search" href="../../search.html" />
<link rel="next" title="Importing data from fNIRS devices" href="30_reading_fnirs_data.html" />
<link rel="prev" title="Importing data from MEG devices" href="10_reading_meg_data.html" />
<link rel="canonical" href="https://mne.tools/stable/index.html" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="docsearch:language" content="None">
<!-- Google Analytics -->
<script async="" src="https://www.google-analytics.com/analytics.js"></script>
<script>
window.ga = window.ga || function () {
(ga.q = ga.q || []).push(arguments) };
ga.l = +new Date;
ga('create', 'UA-37225609-1', 'auto');
ga('set', 'anonymizeIp', true);
ga('send', 'pageview');
</script>
</head>
<body data-spy="scroll" data-target="#bd-toc-nav" data-offset="60">
<div class="container-fluid" id="banner"></div>
<nav class="navbar navbar-light navbar-expand-lg bg-light fixed-top bd-navbar" id="navbar-main"><div class="container-xl">
<div id="navbar-start">
<a class="navbar-brand" href="../../index.html">
<img src="../../_static/mne_logo_small.svg" class="logo" alt="logo">
</a>
</div>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-collapsible" aria-controls="navbar-collapsible" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div id="navbar-collapsible" class="col-lg-9 collapse navbar-collapse">
<div id="navbar-center" class="mr-auto">
<div class="navbar-center-item">
<ul id="navbar-main-elements" class="navbar-nav">
<li class="toctree-l1 nav-item">
<a class="reference internal nav-link" href="../../install/index.html">
Install
</a>
</li>
<li class="toctree-l1 current active nav-item">
<a class="reference internal nav-link" href="../../overview/index.html">
Documentation
</a>
</li>
<li class="toctree-l1 nav-item">
<a class="reference internal nav-link" href="../../python_reference.html">
API Reference
</a>
</li>
<li class="toctree-l1 nav-item">
<a class="reference internal nav-link" href="../../overview/get_help.html">
Get help
</a>
</li>
<li class="toctree-l1 nav-item">
<a class="reference internal nav-link" href="../../overview/development.html">
Development
</a>
</li>
</ul>
</div>
</div>
<div id="navbar-end">
<div class="navbar-end-item">
<div class="dropdown" id="version_switcher">
<button type="button" class="btn btn-primary btn-sm navbar-btn dropdown-toggle" id="version_switcher_button" data-toggle="dropdown">
1.0 <!-- this text may get changed later by javascript -->
<span class="caret"></span>
</button>
<div id="version_switcher_menu" class="dropdown-menu list-group-flush py-0" aria-labelledby="version_switcher_button">
<!-- dropdown will be populated by javascript on page load -->
</div>
</div>
<!-- NOTE: this JS must live here (not in our global JS file) because it relies
on being processed by Jinja before it is run (specifically for replacing
variables auto_tutorials/io/20_reading_eeg_data and {'json_url': 'https://mne.tools/dev/_static/versions.json', 'url_template': 'https://mne.tools/{version}/', 'version_match': '1.0'}.
-->
<script type="text/javascript">
// Check if corresponding page path exists in other version of docs
// and, if so, go there instead of the homepage of the other docs version
function checkPageExistsAndRedirect(event) {
const currentFilePath = "auto_tutorials/io/20_reading_eeg_data.html",
tryUrl = event.target.getAttribute("href");
let otherDocsHomepage = tryUrl.replace(currentFilePath, "");
$.ajax({
type: 'HEAD',
url: tryUrl,
// if the page exists, go there
success: function() {
location.href = tryUrl;
}
}).fail(function() {
location.href = otherDocsHomepage;
});
// this prevents the browser from following the href of the clicked node
// (which is fine because this function takes care of redirecting)
return false;
}
// Populate the version switcher from the JSON config file
(function () {
$.getJSON("https://mne.tools/dev/_static/versions.json", function(data, textStatus, jqXHR) {
const currentFilePath = "auto_tutorials/io/20_reading_eeg_data.html";
// create links to the corresponding page in the other docs versions
$.each(data, function(index, entry) {
// if no custom name specified (e.g., "latest"), use version string
if (!("name" in entry)) {
entry.name = entry.version;
}
// create the node
const node = document.createElement("a");
node.setAttribute("class", "list-group-item list-group-item-action py-1");
node.textContent = `${entry.name}`;
node.setAttribute("href", `${entry.url}${currentFilePath}`);
// on click, AJAX calls will check if the linked page exists before
// trying to redirect, and if not, will redirect to the homepage
// for that version of the docs.
node.onclick = checkPageExistsAndRedirect;
// Add dataset values for the version and name in case people want
// to apply CSS styling based on this information.
node.dataset["versionName"] = entry.name;
node.dataset["version"] = entry.version;
$("#version_switcher_menu").append(node);
// replace dropdown button text with the preferred display name of
// this version, rather than using sphinx's 1.0 variable.
// also highlight the dropdown entry for the currently-viewed
// version's entry
if (entry.version == "1.0") {
node.classList.add("active");
let btn = document.getElementById("version_switcher_button");
btn.innerText = btn.dataset["activeVersionName"] = entry.name;
btn.dataset["activeVersion"] = entry.version;
}
});
});
})();
</script>
</div>
<div class="navbar-end-item">
<ul id="navbar-icon-links" class="navbar-nav" aria-label="Quick Links">
<li class="nav-item">
<a class="nav-link" href="https://github.com/mne-tools/mne-python" rel="noopener" target="_blank" title="GitHub"><span><i class="fab fa-github-square"></i></span>
<label class="sr-only">GitHub</label></a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://twitter.com/mne_python" rel="noopener" target="_blank" title="Twitter"><span><i class="fab fa-twitter-square"></i></span>
<label class="sr-only">Twitter</label></a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://mne.discourse.group/" rel="noopener" target="_blank" title="Discourse"><span><i class="fab fa-discourse"></i></span>
<label class="sr-only">Discourse</label></a>
</li>
<li class="nav-item">
<a class="nav-link" href="https://discord.gg/rKfvxTuATa" rel="noopener" target="_blank" title="Discord"><span><i class="fab fa-discord"></i></span>
<label class="sr-only">Discord</label></a>
</li>
</ul>
</div>
</div>
</div>
</div>
</nav>
<div class="container-xl">
<div class="row">
<!-- Only show if we have sidebars configured, else just a small margin -->
<div class="col-12 col-md-3 bd-sidebar">
<div class="sidebar-start-items"><form class="bd-search d-flex align-items-center" action="../../search.html" method="get">
<i class="icon fas fa-search"></i>
<input type="search" class="form-control" name="q" id="search-input" placeholder="Search the docs ..." aria-label="Search the docs ..." autocomplete="off" >
</form><nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<div class="bd-toc-item active">
<ul class="current nav bd-sidenav">
<li class="toctree-l1 current active has-children">
<a class="reference internal" href="../index.html">
Tutorials
</a>
<input checked="" class="toctree-checkbox" id="toctree-checkbox-1" name="toctree-checkbox-1" type="checkbox"/>
<label for="toctree-checkbox-1">
<i class="fas fa-chevron-down">
</i>
</label>
<ul class="current">
<li class="toctree-l2 has-children">
<a class="reference internal" href="../intro/index.html">
Introductory tutorials
</a>
<input class="toctree-checkbox" id="toctree-checkbox-2" name="toctree-checkbox-2" type="checkbox"/>
<label for="toctree-checkbox-2">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../intro/10_overview.html">
Overview of MEG/EEG analysis with MNE-Python
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../intro/15_inplace.html">
Modifying data in-place
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../intro/20_events_from_raw.html">
Parsing events from raw data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../intro/30_info.html">
The Info data structure
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../intro/40_sensor_locations.html">
Working with sensor locations
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../intro/50_configure_mne.html">
Configuring MNE-Python
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../intro/70_report.html">
Getting started with mne.Report
</a>
</li>
</ul>
</li>
<li class="toctree-l2 current active has-children">
<a class="reference internal" href="index.html">
Reading data for different recording systems
</a>
<input checked="" class="toctree-checkbox" id="toctree-checkbox-3" name="toctree-checkbox-3" type="checkbox"/>
<label for="toctree-checkbox-3">
<i class="fas fa-chevron-down">
</i>
</label>
<ul class="current">
<li class="toctree-l3">
<a class="reference internal" href="10_reading_meg_data.html">
Importing data from MEG devices
</a>
</li>
<li class="toctree-l3 current active">
<a class="current reference internal" href="#">
Importing data from EEG devices
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="30_reading_fnirs_data.html">
Importing data from fNIRS devices
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="60_ctf_bst_auditory.html">
Working with CTF data: the Brainstorm auditory dataset
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../raw/index.html">
Working with continuous data
</a>
<input class="toctree-checkbox" id="toctree-checkbox-4" name="toctree-checkbox-4" type="checkbox"/>
<label for="toctree-checkbox-4">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../raw/10_raw_overview.html">
The Raw data structure: continuous data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../raw/20_event_arrays.html">
Working with events
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../raw/30_annotate_raw.html">
Annotating continuous data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../raw/40_visualize_raw.html">
Built-in plotting methods for Raw objects
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../preprocessing/index.html">
Preprocessing
</a>
<input class="toctree-checkbox" id="toctree-checkbox-5" name="toctree-checkbox-5" type="checkbox"/>
<label for="toctree-checkbox-5">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/10_preprocessing_overview.html">
Overview of artifact detection
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/15_handling_bad_channels.html">
Handling bad channels
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/20_rejecting_bad_data.html">
Rejecting bad data spans and breaks
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/25_background_filtering.html">
Background information on filtering
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/30_filtering_resampling.html">
Filtering and resampling data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/35_artifact_correction_regression.html">
Repairing artifacts with regression
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/40_artifact_correction_ica.html">
Repairing artifacts with ICA
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/45_projectors_background.html">
Background on projectors and projections
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/50_artifact_correction_ssp.html">
Repairing artifacts with SSP
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/55_setting_eeg_reference.html">
Setting the EEG reference
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/59_head_positions.html">
Extracting and visualizing subject head movement
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/60_maxwell_filtering_sss.html">
Signal-space separation (SSS) and Maxwell filtering
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../preprocessing/70_fnirs_processing.html">
Preprocessing functional near-infrared spectroscopy (fNIRS) data
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../epochs/index.html">
Segmenting continuous data into epochs
</a>
<input class="toctree-checkbox" id="toctree-checkbox-6" name="toctree-checkbox-6" type="checkbox"/>
<label for="toctree-checkbox-6">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../epochs/10_epochs_overview.html">
The Epochs data structure: discontinuous data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../epochs/20_visualize_epochs.html">
Visualizing epoched data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../epochs/30_epochs_metadata.html">
Working with Epoch metadata
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../epochs/40_autogenerate_metadata.html">
Auto-generating Epochs metadata
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../epochs/50_epochs_to_data_frame.html">
Exporting Epochs to Pandas DataFrames
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../epochs/60_make_fixed_length_epochs.html">
Divide continuous data into equally-spaced epochs
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../evoked/index.html">
Estimating evoked responses
</a>
<input class="toctree-checkbox" id="toctree-checkbox-7" name="toctree-checkbox-7" type="checkbox"/>
<label for="toctree-checkbox-7">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../evoked/10_evoked_overview.html">
The Evoked data structure: evoked/averaged data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../evoked/20_visualize_evoked.html">
Visualizing Evoked data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../evoked/30_eeg_erp.html">
EEG processing and Event Related Potentials (ERPs)
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../evoked/40_whitened.html">
Plotting whitened data
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../time-freq/index.html">
Time-frequency analysis
</a>
<input class="toctree-checkbox" id="toctree-checkbox-8" name="toctree-checkbox-8" type="checkbox"/>
<label for="toctree-checkbox-8">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../time-freq/20_sensors_time_frequency.html">
Frequency and time-frequency sensor analysis
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../time-freq/50_ssvep.html">
Frequency-tagging: Basic analysis of an SSVEP/vSSR dataset
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../forward/index.html">
Forward models and source spaces
</a>
<input class="toctree-checkbox" id="toctree-checkbox-9" name="toctree-checkbox-9" type="checkbox"/>
<label for="toctree-checkbox-9">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../forward/10_background_freesurfer.html">
FreeSurfer MRI reconstruction
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../forward/20_source_alignment.html">
Source alignment and coordinate frames
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../forward/25_automated_coreg.html">
Using an automated approach to coregistration
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../forward/30_forward.html">
Head model and forward computation
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../forward/35_eeg_no_mri.html">
EEG forward operator with a template MRI
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../forward/50_background_freesurfer_mne.html">
How MNE uses FreeSurfer’s outputs
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../forward/80_fix_bem_in_blender.html">
Editing BEM surfaces in Blender
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../forward/90_compute_covariance.html">
Computing a covariance matrix
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../inverse/index.html">
Source localization and inverses
</a>
<input class="toctree-checkbox" id="toctree-checkbox-10" name="toctree-checkbox-10" type="checkbox"/>
<label for="toctree-checkbox-10">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../inverse/10_stc_class.html">
The SourceEstimate data structure
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../inverse/20_dipole_fit.html">
Source localization with equivalent current dipole (ECD) fit
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../inverse/30_mne_dspm_loreta.html">
Source localization with MNE, dSPM, sLORETA, and eLORETA
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../inverse/35_dipole_orientations.html">
The role of dipole orientations in distributed source localization
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../inverse/40_mne_fixed_free.html">
Computing various MNE solutions
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../inverse/50_beamformer_lcmv.html">
Source reconstruction using an LCMV beamformer
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../inverse/60_visualize_stc.html">
Visualize source time courses (stcs)
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../inverse/70_eeg_mri_coords.html">
EEG source localization given electrode locations on an MRI
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../inverse/80_brainstorm_phantom_elekta.html">
Brainstorm Elekta phantom dataset tutorial
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../inverse/85_brainstorm_phantom_ctf.html">
Brainstorm CTF phantom dataset tutorial
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../inverse/90_phantom_4DBTi.html">
4D Neuroimaging/BTi phantom dataset tutorial
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../stats-sensor-space/index.html">
Statistical analysis of sensor data
</a>
<input class="toctree-checkbox" id="toctree-checkbox-11" name="toctree-checkbox-11" type="checkbox"/>
<label for="toctree-checkbox-11">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../stats-sensor-space/10_background_stats.html">
Statistical inference
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../stats-sensor-space/20_erp_stats.html">
Visualising statistical significance thresholds on EEG data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../stats-sensor-space/40_cluster_1samp_time_freq.html">
Non-parametric 1 sample cluster statistic on single trial power
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../stats-sensor-space/50_cluster_between_time_freq.html">
Non-parametric between conditions cluster statistic on single trial power
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../stats-sensor-space/75_cluster_ftest_spatiotemporal.html">
Spatiotemporal permutation F-test on full sensor data
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../stats-source-space/index.html">
Statistical analysis of source estimates
</a>
<input class="toctree-checkbox" id="toctree-checkbox-12" name="toctree-checkbox-12" type="checkbox"/>
<label for="toctree-checkbox-12">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../stats-source-space/20_cluster_1samp_spatiotemporal.html">
Permutation t-test on source data with spatio-temporal clustering
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../stats-source-space/30_cluster_ftest_spatiotemporal.html">
2 samples permutation test on source data with spatio-temporal clustering
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../stats-source-space/60_cluster_rmANOVA_spatiotemporal.html">
Repeated measures ANOVA on source data with spatio-temporal clustering
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../stats-source-space/70_cluster_rmANOVA_time_freq.html">
Mass-univariate twoway repeated measures ANOVA on single trial power
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../machine-learning/index.html">
Machine learning models of neural activity
</a>
<input class="toctree-checkbox" id="toctree-checkbox-13" name="toctree-checkbox-13" type="checkbox"/>
<label for="toctree-checkbox-13">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../machine-learning/30_strf.html">
Spectro-temporal receptive field (STRF) estimation on continuous data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../machine-learning/50_decoding.html">
Decoding (MVPA)
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../clinical/index.html">
Clinical applications
</a>
<input class="toctree-checkbox" id="toctree-checkbox-14" name="toctree-checkbox-14" type="checkbox"/>
<label for="toctree-checkbox-14">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../clinical/10_ieeg_localize.html">
Locating intracranial electrode contacts
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../clinical/20_seeg.html">
Working with sEEG data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../clinical/30_ecog.html">
Working with ECoG data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../clinical/60_sleep.html">
Sleep stage classification from polysomnography (PSG) data
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../simulation/index.html">
Simulation
</a>
<input class="toctree-checkbox" id="toctree-checkbox-15" name="toctree-checkbox-15" type="checkbox"/>
<label for="toctree-checkbox-15">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../simulation/10_array_objs.html">
Creating MNE-Python data structures from scratch
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../simulation/70_point_spread.html">
Corrupt known signal with point spread
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../simulation/80_dics.html">
DICS for power mapping
</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1 has-children">
<a class="reference internal" href="../../auto_examples/index.html">
Examples
</a>
<input class="toctree-checkbox" id="toctree-checkbox-16" name="toctree-checkbox-16" type="checkbox"/>
<label for="toctree-checkbox-16">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../../auto_examples/io/index.html">
Input/Output
</a>
<input class="toctree-checkbox" id="toctree-checkbox-17" name="toctree-checkbox-17" type="checkbox"/>
<label for="toctree-checkbox-17">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/io/elekta_epochs.html">
Getting averaging info from .fif files
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/io/read_neo_format.html">
How to use data in neural ensemble (NEO) format
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/io/read_noise_covariance_matrix.html">
Reading/Writing a noise covariance matrix
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/io/read_xdf.html">
Reading XDF EEG data
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../../auto_examples/simulation/index.html">
Data Simulation
</a>
<input class="toctree-checkbox" id="toctree-checkbox-18" name="toctree-checkbox-18" type="checkbox"/>
<label for="toctree-checkbox-18">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/simulation/simulate_evoked_data.html">
Generate simulated evoked data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/simulation/simulate_raw_data.html">
Generate simulated raw data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/simulation/simulated_raw_data_using_subject_anatomy.html">
Simulate raw data using subject anatomy
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/simulation/source_simulator.html">
Generate simulated source data
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../../auto_examples/preprocessing/index.html">
Preprocessing
</a>
<input class="toctree-checkbox" id="toctree-checkbox-19" name="toctree-checkbox-19" type="checkbox"/>
<label for="toctree-checkbox-19">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/css.html">
Cortical Signal Suppression (CSS) for removal of cortical signals
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/define_target_events.html">
Define target events based on time lag, plot evoked response
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/eeg_csd.html">
Transform EEG data using current source density (CSD)
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/eog_artifact_histogram.html">
Show EOG artifact timing
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/find_ref_artifacts.html">
Find MEG reference channel artifacts
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/fnirs_artifact_removal.html">
Visualise NIRS artifact correction methods
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/ica_comparison.html">
Compare the different ICA algorithms in MNE
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/interpolate_bad_channels.html">
Interpolate bad channels for MEG/EEG channels
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/movement_compensation.html">
Maxwell filter data with movement compensation
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/movement_detection.html">
Annotate movement artifacts and reestimate dev_head_t
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/muscle_detection.html">
Annotate muscle artifacts
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/otp.html">
Plot sensor denoising using oversampled temporal projection
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/shift_evoked.html">
Shifting time-scale in evoked data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/virtual_evoked.html">
Remap MEG channel types
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/preprocessing/xdawn_denoising.html">
XDAWN Denoising
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../../auto_examples/visualization/index.html">
Visualization
</a>
<input class="toctree-checkbox" id="toctree-checkbox-20" name="toctree-checkbox-20" type="checkbox"/>
<label for="toctree-checkbox-20">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/3d_to_2d.html">
How to convert 3D electrode positions to a 2D image
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/brain.html">
Plotting with
<code class="docutils literal notranslate">
<span class="pre">
mne.viz.Brain
</span>
</code>
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/channel_epochs_image.html">
Visualize channel over epochs as an image
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/eeg_on_scalp.html">
Plotting EEG sensors on the scalp
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/eeglab_head_sphere.html">
How to plot topomaps the way EEGLAB does
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/evoked_arrowmap.html">
Plotting topographic arrowmaps of evoked data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/evoked_topomap.html">
Plotting topographic maps of evoked data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/evoked_whitening.html">
Whitening evoked data with a noise covariance
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/meg_sensors.html">
Plotting sensor layouts of MEG systems
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/mne_helmet.html">
Plot the MNE brain and helmet
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/montage_sgskip.html">
Plotting sensor layouts of EEG systems
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/parcellation.html">
Plot a cortical parcellation
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/publication_figure.html">
Make figures more publication ready
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/roi_erpimage_by_rt.html">
Plot single trial activity, grouped by ROI and sorted by RT
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/sensor_noise_level.html">
Show noise levels from empty room data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/ssp_projs_sensitivity_map.html">
Sensitivity map of SSP projections
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/topo_compare_conditions.html">
Compare evoked responses for different conditions
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/topo_customized.html">
Plot custom topographies for MEG sensors
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/visualization/xhemi.html">
Cross-hemisphere comparison
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../../auto_examples/time_frequency/index.html">
Time-Frequency Examples
</a>
<input class="toctree-checkbox" id="toctree-checkbox-21" name="toctree-checkbox-21" type="checkbox"/>
<label for="toctree-checkbox-21">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/time_frequency/compute_csd.html">
Compute a cross-spectral density (CSD) matrix
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/time_frequency/compute_source_psd_epochs.html">
Compute Power Spectral Density of inverse solution from single epochs
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/time_frequency/source_label_time_frequency.html">
Compute power and phase lock in label of the source space
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/time_frequency/source_power_spectrum.html">
Compute source power spectral density (PSD) in a label
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/time_frequency/source_power_spectrum_opm.html">
Compute source power spectral density (PSD) of VectorView and OPM data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/time_frequency/source_space_time_frequency.html">
Compute induced power in the source space with dSPM
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/time_frequency/temporal_whitening.html">
Temporal whitening with AR model
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/time_frequency/time_frequency_erds.html">
Compute and visualize ERDS maps
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/time_frequency/time_frequency_global_field_power.html">
Explore event-related dynamics for specific frequency bands
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/time_frequency/time_frequency_simulated.html">
Time-frequency on simulated data (Multitaper vs. Morlet vs. Stockwell)
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../../auto_examples/stats/index.html">
Statistics Examples
</a>
<input class="toctree-checkbox" id="toctree-checkbox-22" name="toctree-checkbox-22" type="checkbox"/>
<label for="toctree-checkbox-22">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/stats/cluster_stats_evoked.html">
Permutation F-test on sensor data with 1D cluster level
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/stats/fdr_stats_evoked.html">
FDR correction on T-test on sensor data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/stats/linear_regression_raw.html">
Regression on continuous data (rER[P/F])
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/stats/sensor_permutation_test.html">
Permutation T-test on sensor data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/stats/sensor_regression.html">
Analysing continuous features with binning and regression in sensor space
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../../auto_examples/decoding/index.html">
Machine Learning (Decoding, Encoding, and MVPA)
</a>
<input class="toctree-checkbox" id="toctree-checkbox-23" name="toctree-checkbox-23" type="checkbox"/>
<label for="toctree-checkbox-23">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/decoding_csp_eeg.html">
Motor imagery decoding from EEG data using the Common Spatial Pattern (CSP)
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/decoding_csp_timefreq.html">
Decoding in time-frequency space using Common Spatial Patterns (CSP)
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/decoding_rsa_sgskip.html">
Representational Similarity Analysis
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/decoding_spatio_temporal_source.html">
Decoding source space data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/decoding_spoc_CMC.html">
Continuous Target Decoding with SPoC
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/decoding_time_generalization_conditions.html">
Decoding sensor space data with generalization across time and conditions
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/decoding_unsupervised_spatial_filter.html">
Analysis of evoked response using ICA and PCA reduction techniques
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/decoding_xdawn_eeg.html">
XDAWN Decoding From EEG data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/ems_filtering.html">
Compute effect-matched-spatial filtering (EMS)
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/linear_model_patterns.html">
Linear classifier on sensor data with plot patterns and filters
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/receptive_field_mtrf.html">
Receptive Field Estimation and Prediction
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/decoding/ssd_spatial_filters.html">
Compute Spectro-Spatial Decomposition (SSD) spatial filters
</a>
</li>
</ul>
</li>
<li class="toctree-l2">
<a class="reference internal" href="../../auto_examples/connectivity/index.html">
Connectivity Analysis Examples
</a>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../../auto_examples/forward/index.html">
Forward modeling
</a>
<input class="toctree-checkbox" id="toctree-checkbox-24" name="toctree-checkbox-24" type="checkbox"/>
<label for="toctree-checkbox-24">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/forward/forward_sensitivity_maps.html">
Display sensitivity maps for EEG and MEG sensors
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/forward/left_cerebellum_volume_source.html">
Generate a left cerebellum volume source space
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/forward/source_space_morphing.html">
Use source space morphing
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../../auto_examples/inverse/index.html">
Inverse problem and source analysis
</a>
<input class="toctree-checkbox" id="toctree-checkbox-25" name="toctree-checkbox-25" type="checkbox"/>
<label for="toctree-checkbox-25">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/compute_mne_inverse_epochs_in_label.html">
Compute MNE-dSPM inverse solution on single epochs
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/compute_mne_inverse_raw_in_label.html">
Compute sLORETA inverse solution on raw data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/compute_mne_inverse_volume.html">
Compute MNE-dSPM inverse solution on evoked data in volume source space
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/custom_inverse_solver.html">
Source localization with a custom inverse solver
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/dics_source_power.html">
Compute source power using DICS beamformer
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/evoked_ers_source_power.html">
Compute evoked ERS source power using DICS, LCMV beamformer, and dSPM
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/gamma_map_inverse.html">
Compute a sparse inverse solution using the Gamma-MAP empirical Bayesian method
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/label_activation_from_stc.html">
Extracting time course from source_estimate object
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/label_from_stc.html">
Generate a functional label from source estimates
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/label_source_activations.html">
Extracting the time series of activations in a label
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/mixed_norm_inverse.html">
Compute sparse inverse solution with mixed norm: MxNE and irMxNE
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/mixed_source_space_inverse.html">
Compute MNE inverse solution on evoked data with a mixed source space
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/mne_cov_power.html">
Compute source power estimate by projecting the covariance with MNE
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/morph_surface_stc.html">
Morph surface source estimate
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/morph_volume_stc.html">
Morph volumetric source estimate
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/multidict_reweighted_tfmxne.html">
Compute iterative reweighted TF-MxNE with multiscale time-frequency dictionary
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/psf_ctf_label_leakage.html">
Visualize source leakage among labels using a circular graph
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/psf_ctf_vertices.html">
Plot point-spread functions (PSFs) and cross-talk functions (CTFs)
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/psf_ctf_vertices_lcmv.html">
Compute cross-talk functions for LCMV beamformers
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/rap_music.html">
Compute Rap-Music on evoked data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/read_inverse.html">
Reading an inverse operator
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/read_stc.html">
Reading an STC file
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/resolution_metrics.html">
Compute spatial resolution metrics in source space
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/resolution_metrics_eegmeg.html">
Compute spatial resolution metrics to compare MEG with EEG+MEG
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/snr_estimate.html">
Estimate data SNR using an inverse
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/source_space_snr.html">
Computing source space SNR
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/time_frequency_mixed_norm_inverse.html">
Compute MxNE with time-frequency sparse prior
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/inverse/vector_mne_solution.html">
Plotting the full vector-valued MNE solution
</a>
</li>
</ul>
</li>
<li class="toctree-l2 has-children">
<a class="reference internal" href="../../auto_examples/datasets/index.html">
Examples on open datasets
</a>
<input class="toctree-checkbox" id="toctree-checkbox-26" name="toctree-checkbox-26" type="checkbox"/>
<label for="toctree-checkbox-26">
<i class="fas fa-chevron-down">
</i>
</label>
<ul>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/datasets/brainstorm_data.html">
Brainstorm raw (median nerve) dataset
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/datasets/hf_sef_data.html">
HF-SEF dataset
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/datasets/limo_data.html">
Single trial linear regression analysis with the LIMO dataset
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/datasets/opm_data.html">
Optically pumped magnetometer (OPM) data
</a>
</li>
<li class="toctree-l3">
<a class="reference internal" href="../../auto_examples/datasets/spm_faces_dataset_sgskip.html">
From raw data to dSPM on SPM Faces dataset
</a>
</li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../glossary.html">
Glossary
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../overview/implementation.html">
Implementation details
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../overview/design_philosophy.html">
Design philosophy
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../overview/datasets_index.html">
Example datasets
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../generated/commands.html">
Command-line tools
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../overview/migrating.html">
Migrating from other analysis software
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../overview/cookbook.html">
The typical M/EEG workflow
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../overview/cite.html">
How to cite MNE-Python
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../../cited.html">
Papers citing MNE-Python
</a>
</li>
</ul>
</div>
</nav>
</div>
<div class="sidebar-end-items">
</div>
</div>
<div class="d-none d-xl-block col-xl-2 bd-toc">
<div class="toc-item">
<div class="tocsection onthispage mt-5 pt-1 pb-3">
<i class="fas fa-list"></i> On this page
</div>
<nav id="bd-toc-nav">
<ul class="visible nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#brainvision-vhdr-vmrk-eeg">
BrainVision (.vhdr, .vmrk, .eeg)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#european-data-format-edf">
European data format (.edf)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#biosemi-data-format-bdf">
BioSemi data format (.bdf)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#general-data-format-gdf">
General data format (.gdf)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#neuroscan-cnt-cnt">
Neuroscan CNT (.cnt)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#egi-simple-binary-egi">
EGI simple binary (.egi)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#egi-mff-mff">
EGI MFF (.mff)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#eeglab-files-set-fdt">
EEGLAB files (.set, .fdt)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#nicolet-data">
Nicolet (.data)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#eximia-eeg-data-nxe">
eXimia EEG data (.nxe)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#persyst-eeg-data-lay-dat">
Persyst EEG data (.lay, .dat)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#nihon-kohden-eeg-data-eeg-21e-pnt-log">
Nihon Kohden EEG data (.eeg, .21e, .pnt, .log)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#xdf-data-xdf-xdfz">
XDF data (.xdf, .xdfz)
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#setting-eeg-references">
Setting EEG references
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#reading-electrode-locations-and-head-shapes-for-eeg-recordings">
Reading electrode locations and head shapes for EEG recordings
</a>
</li>
</ul>
</nav>
</div>
<div class="toc-item">
</div>
</div>
<main class="col-12 col-md-9 col-xl-7 py-md-5 pl-md-5 pr-md-4 bd-content" role="main">
<div>
<div class="sphx-glr-download-link-note admonition note">
<p class="admonition-title">Note</p>
<p>Click <a class="reference internal" href="#sphx-glr-download-auto-tutorials-io-20-reading-eeg-data-py"><span class="std std-ref">here</span></a>
to download the full example code</p>
</div>
<section class="sphx-glr-example-title" id="importing-data-from-eeg-devices">
<span id="tut-imorting-eeg-data"></span><span id="sphx-glr-auto-tutorials-io-20-reading-eeg-data-py"></span><h1>Importing data from EEG devices<a class="headerlink" href="#importing-data-from-eeg-devices" title="Permalink to this headline">#</a></h1>
<p>MNE includes various functions and utilities for reading EEG data and electrode
locations.</p>
<section id="brainvision-vhdr-vmrk-eeg">
<span id="import-bv"></span><h2>BrainVision (.vhdr, .vmrk, .eeg)<a class="headerlink" href="#brainvision-vhdr-vmrk-eeg" title="Permalink to this headline">#</a></h2>
<p>The BrainVision file format consists of three separate files:</p>
<ol class="arabic simple">
<li><p>A text header file (<code class="docutils literal notranslate"><span class="pre">.vhdr</span></code>) containing meta data.</p></li>
<li><p>A text marker file (<code class="docutils literal notranslate"><span class="pre">.vmrk</span></code>) containing information about events in the
data.</p></li>
<li><p>A binary data file (<code class="docutils literal notranslate"><span class="pre">.eeg</span></code>) containing the voltage values of the EEG.</p></li>
</ol>
<p>Both text files are based on the <a class="reference external" href="https://en.wikipedia.org/wiki/INI_file">INI format</a>
consisting of</p>
<ul class="simple">
<li><p>sections marked as <code class="docutils literal notranslate"><span class="pre">[square</span> <span class="pre">brackets]</span></code>,</p></li>
<li><p>comments marked as <code class="docutils literal notranslate"><span class="pre">;</span> <span class="pre">comment</span></code>,</p></li>
<li><p>and key-value pairs marked as <code class="docutils literal notranslate"><span class="pre">key=value</span></code>.</p></li>
</ul>
<p>Brain Products provides documentation for their core BrainVision file format.
The format specification is hosted on the
<a class="reference external" href="https://www.brainproducts.com/productdetails.php?id=21&tab=5">Brain Products website</a>.</p>
<p>BrainVision EEG files can be read using <a class="reference internal" href="../../generated/mne.io.read_raw_brainvision.html#mne.io.read_raw_brainvision" title="mne.io.read_raw_brainvision"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_brainvision()</span></code></a>,
passing the <code class="docutils literal notranslate"><span class="pre">.vhdr</span></code> header file as the argument.</p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>Renaming BrainVision files can be problematic due to their
multi-file structure. See this
<a class="reference external" href="https://mne.tools/mne-bids/stable/auto_examples/rename_brainvision_files.html#sphx-glr-auto-examples-rename-brainvision-files-py">example</a>
for instructions.</p>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>For <em>writing</em> BrainVision files, you can use the Python package
<a class="reference external" href="https://pypi.org/project/pybv/">pybv</a>.</p>
</div>
</section>
<section id="european-data-format-edf">
<span id="import-edf"></span><h2>European data format (.edf)<a class="headerlink" href="#european-data-format-edf" title="Permalink to this headline">#</a></h2>
<p><a class="reference external" href="http://www.edfplus.info/specs/edf.html">EDF</a> and
<a class="reference external" href="http://www.edfplus.info/specs/edfplus.html">EDF+</a> files can be read using
<a class="reference internal" href="../../generated/mne.io.read_raw_edf.html#mne.io.read_raw_edf" title="mne.io.read_raw_edf"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_edf()</span></code></a>. Both variants are 16-bit formats.</p>
<p>EDF+ files may contain annotation channels which can be used to store trigger
and event information. These annotations are available in <code class="docutils literal notranslate"><span class="pre">raw.annotations</span></code>.</p>
<p>Writing EDF files is not supported natively yet. <a class="reference external" href="https://gist.github.com/skjerns/bc660ef59dca0dbd53f00ed38c42f6be">This gist</a> or
<a class="reference external" href="https://github.com/cbrnr/mnelab">MNELAB</a> (both of which use
<a class="reference external" href="https://github.com/holgern/pyedflib">pyedflib</a> under the hood) can be used
to export any <a class="reference internal" href="../../generated/mne.io.Raw.html#mne.io.Raw" title="mne.io.Raw"><code class="xref py py-class docutils literal notranslate"><span class="pre">mne.io.Raw</span></code></a> object to EDF/EDF+/BDF/BDF+.</p>
</section>
<section id="biosemi-data-format-bdf">
<span id="import-biosemi"></span><h2>BioSemi data format (.bdf)<a class="headerlink" href="#biosemi-data-format-bdf" title="Permalink to this headline">#</a></h2>
<p>The <a class="reference external" href="http://www.biosemi.com/faq/file_format.htm">BDF format</a> is a 24-bit
variant of the EDF format used by EEG systems manufactured by BioSemi. It can
be imported with <a class="reference internal" href="../../generated/mne.io.read_raw_bdf.html#mne.io.read_raw_bdf" title="mne.io.read_raw_bdf"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_bdf()</span></code></a>.</p>
<p>BioSemi amplifiers do not perform “common mode noise rejection” automatically.
The signals in the EEG file are the voltages between each electrode and the CMS
active electrode, which still contain some CM noise (50 Hz, ADC reference
noise, etc.). The <a class="reference external" href="https://www.biosemi.com/faq/cms&drl.htm">BioSemi FAQ</a>
provides more details on this topic.
Therefore, it is advisable to choose a reference (e.g., a single channel like Cz,
average of linked mastoids, average of all electrodes, etc.) after importing
BioSemi data to avoid losing signal information. The data can be re-referenced
later after cleaning if desired.</p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>Data samples in a BDF file are represented in a 3-byte
(24-bit) format. Since 3-byte raw data buffers are not presently
supported in the FIF format, these data will be changed to 4-byte
integers in the conversion.</p>
</div>
</section>
<section id="general-data-format-gdf">
<span id="import-gdf"></span><h2>General data format (.gdf)<a class="headerlink" href="#general-data-format-gdf" title="Permalink to this headline">#</a></h2>
<p>GDF files can be read using <a class="reference internal" href="../../generated/mne.io.read_raw_gdf.html#mne.io.read_raw_gdf" title="mne.io.read_raw_gdf"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_gdf()</span></code></a>.</p>
<p><a class="reference external" href="https://arxiv.org/abs/cs/0608052">GDF (General Data Format)</a> is a flexible
format for biomedical signals that overcomes some of the limitations of the
EDF format. The original specification (GDF v1) includes a binary header
and uses an event table. An updated specification (GDF v2) was released in
2011 and adds fields for additional subject-specific information (gender,
age, etc.) and allows storing several physical units and other properties.
Both specifications are supported by MNE.</p>
</section>
<section id="neuroscan-cnt-cnt">
<span id="import-cnt"></span><h2>Neuroscan CNT (.cnt)<a class="headerlink" href="#neuroscan-cnt-cnt" title="Permalink to this headline">#</a></h2>
<p>CNT files can be read using <a class="reference internal" href="../../generated/mne.io.read_raw_cnt.html#mne.io.read_raw_cnt" title="mne.io.read_raw_cnt"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_cnt()</span></code></a>.
Channel locations can be read from a montage or the file header. If read
from the header, the data channels (channels that are not assigned to EOG, ECG,
EMG or MISC) are fit to a sphere and assigned a z-value accordingly. If a
non-data channel does not fit to the sphere, it is assigned a z-value of 0.</p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>Reading channel locations from the file header may be dangerous, as the
x_coord and y_coord in the ELECTLOC section of the header do not necessarily
translate to absolute locations. Furthermore, EEG electrode locations that
do not fit to a sphere will distort the layout when computing the z-values.
If you are not sure about the channel locations in the header, using a
montage is encouraged.</p>
</div>
</section>
<section id="egi-simple-binary-egi">
<span id="import-egi"></span><h2>EGI simple binary (.egi)<a class="headerlink" href="#egi-simple-binary-egi" title="Permalink to this headline">#</a></h2>
<p>EGI simple binary files can be read using <a class="reference internal" href="../../generated/mne.io.read_raw_egi.html#mne.io.read_raw_egi" title="mne.io.read_raw_egi"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_egi()</span></code></a>.
EGI raw files are simple binary files with a header and can be exported by the
EGI Netstation acquisition software.</p>
</section>
<section id="egi-mff-mff">
<span id="import-mff"></span><h2>EGI MFF (.mff)<a class="headerlink" href="#egi-mff-mff" title="Permalink to this headline">#</a></h2>
<p>EGI MFF files can be read with <a class="reference internal" href="../../generated/mne.io.read_raw_egi.html#mne.io.read_raw_egi" title="mne.io.read_raw_egi"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_egi()</span></code></a>.</p>
</section>
<section id="eeglab-files-set-fdt">
<span id="import-set"></span><h2>EEGLAB files (.set, .fdt)<a class="headerlink" href="#eeglab-files-set-fdt" title="Permalink to this headline">#</a></h2>
<p>EEGLAB .set files (which sometimes come with a separate .fdt file) can be read
using <a class="reference internal" href="../../generated/mne.io.read_raw_eeglab.html#mne.io.read_raw_eeglab" title="mne.io.read_raw_eeglab"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_eeglab()</span></code></a> and <a class="reference internal" href="../../generated/mne.read_epochs_eeglab.html#mne.read_epochs_eeglab" title="mne.read_epochs_eeglab"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.read_epochs_eeglab()</span></code></a>.</p>
</section>
<section id="nicolet-data">
<span id="import-nicolet"></span><h2>Nicolet (.data)<a class="headerlink" href="#nicolet-data" title="Permalink to this headline">#</a></h2>
<p>These files can be read with <a class="reference internal" href="../../generated/mne.io.read_raw_nicolet.html#mne.io.read_raw_nicolet" title="mne.io.read_raw_nicolet"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_nicolet()</span></code></a>.</p>
</section>
<section id="eximia-eeg-data-nxe">
<span id="import-nxe"></span><h2>eXimia EEG data (.nxe)<a class="headerlink" href="#eximia-eeg-data-nxe" title="Permalink to this headline">#</a></h2>
<p>EEG data from the Nexstim eXimia system can be read with
<a class="reference internal" href="../../generated/mne.io.read_raw_eximia.html#mne.io.read_raw_eximia" title="mne.io.read_raw_eximia"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_eximia()</span></code></a>.</p>
</section>
<section id="persyst-eeg-data-lay-dat">
<span id="import-persyst"></span><h2>Persyst EEG data (.lay, .dat)<a class="headerlink" href="#persyst-eeg-data-lay-dat" title="Permalink to this headline">#</a></h2>
<p>EEG data from the Persyst system can be read with
<a class="reference internal" href="../../generated/mne.io.read_raw_persyst.html#mne.io.read_raw_persyst" title="mne.io.read_raw_persyst"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_persyst()</span></code></a>.</p>
<p>Note that subject metadata may not be properly imported because Persyst
sometimes changes its specification from version to version. Please let us know
if you encounter a problem.</p>
</section>
<section id="nihon-kohden-eeg-data-eeg-21e-pnt-log">
<h2>Nihon Kohden EEG data (.eeg, .21e, .pnt, .log)<a class="headerlink" href="#nihon-kohden-eeg-data-eeg-21e-pnt-log" title="Permalink to this headline">#</a></h2>
<p>EEG data from the Nihon Kohden (NK) system can be read using the
<a class="reference internal" href="../../generated/mne.io.read_raw_nihon.html#mne.io.read_raw_nihon" title="mne.io.read_raw_nihon"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.io.read_raw_nihon()</span></code></a> function.</p>
<p>Files with the following extensions will be read:</p>
<ul class="simple">
<li><p>The <code class="docutils literal notranslate"><span class="pre">.eeg</span></code> file contains the actual raw EEG data.</p></li>
<li><p>The <code class="docutils literal notranslate"><span class="pre">.pnt</span></code> file contains metadata related to the recording such as the
measurement date.</p></li>
<li><p>The <code class="docutils literal notranslate"><span class="pre">.log</span></code> file contains annotations for the recording.</p></li>
<li><p>The <code class="docutils literal notranslate"><span class="pre">.21e</span></code> file contains channel and electrode information.</p></li>
</ul>
<p>Reading <code class="docutils literal notranslate"><span class="pre">.11d</span></code>, <code class="docutils literal notranslate"><span class="pre">.cmt</span></code>, <code class="docutils literal notranslate"><span class="pre">.cn2</span></code>, and <code class="docutils literal notranslate"><span class="pre">.edf</span></code> files is currently not
supported.</p>
<p>Note that not all subject metadata may be properly read because NK changes the
specification sometimes from version to version. Please let us know if you
encounter a problem.</p>
</section>
<section id="xdf-data-xdf-xdfz">
<h2>XDF data (.xdf, .xdfz)<a class="headerlink" href="#xdf-data-xdf-xdfz" title="Permalink to this headline">#</a></h2>
<p>MNE-Python does not support loading
<a class="reference external" href="https://github.com/sccn/xdf/wiki/Specifications">XDF</a> files out of the box,
because the inherent flexibility of the XDF format makes it difficult to
provide a one-size-fits-all function. For example, XDF supports signals from
various modalities recorded with different sampling rates. However, it is
relatively straightforward to import only a specific stream (such as EEG
signals) using the <a class="reference external" href="https://github.com/xdf-modules/pyxdf">pyxdf</a> package.
See <a class="reference internal" href="../../auto_examples/io/read_xdf.html#ex-read-xdf"><span class="std std-ref">Reading XDF EEG data</span></a> for a simple example.</p>
<p>A more sophisticated version, which supports selection of specific streams as
well as converting marker streams into annotations, is available in
<a class="reference external" href="https://github.com/cbrnr/mnelab">MNELAB</a>. If you want to use this
functionality in a script, MNELAB records its history (View - History), which
contains all commands required to load an XDF file after successfully loading
that file with the graphical user interface.</p>
</section>
<section id="setting-eeg-references">
<h2>Setting EEG references<a class="headerlink" href="#setting-eeg-references" title="Permalink to this headline">#</a></h2>
<p>The preferred method for applying an EEG reference in MNE is
<a class="reference internal" href="../../generated/mne.set_eeg_reference.html#mne.set_eeg_reference" title="mne.set_eeg_reference"><code class="xref py py-func docutils literal notranslate"><span class="pre">mne.set_eeg_reference()</span></code></a>, or equivalent instance methods like
<a class="reference internal" href="../../generated/mne.io.Raw.html#mne.io.Raw.set_eeg_reference" title="mne.io.Raw.set_eeg_reference"><code class="xref py py-meth docutils literal notranslate"><span class="pre">raw.set_eeg_reference()</span></code></a>. By default,
the data are assumed to already be properly referenced. See
<a class="reference internal" href="../preprocessing/55_setting_eeg_reference.html#tut-set-eeg-ref"><span class="std std-ref">Setting the EEG reference</span></a> for more information.</p>
</section>
<section id="reading-electrode-locations-and-head-shapes-for-eeg-recordings">
<h2>Reading electrode locations and head shapes for EEG recordings<a class="headerlink" href="#reading-electrode-locations-and-head-shapes-for-eeg-recordings" title="Permalink to this headline">#</a></h2>
<p>Some EEG formats (e.g., EGI, EDF/EDF+, BDF) contain neither electrode locations
nor head shape digitization information. Therefore, this information has to be
provided separately. For that purpose, all raw instances have a
<a class="reference internal" href="../../generated/mne.io.Raw.html#mne.io.Raw.set_montage" title="mne.io.Raw.set_montage"><code class="xref py py-meth docutils literal notranslate"><span class="pre">mne.io.Raw.set_montage()</span></code></a> method to set electrode locations.</p>
<p>When using locations of fiducial points, the digitization data are converted to
the MEG head coordinate system employed in the MNE software, see
<a class="reference internal" href="../../overview/implementation.html#coordinate-systems"><span class="std std-ref">MEG/EEG and MRI coordinate systems</span></a>.</p>
<p><strong>Estimated memory usage:</strong> 9 MB</p>
<div class="sphx-glr-footer sphx-glr-footer-example docutils container" id="sphx-glr-download-auto-tutorials-io-20-reading-eeg-data-py">
<div class="sphx-glr-download sphx-glr-download-python docutils container">
<p><a class="reference download internal" download="" href="../../_downloads/b223d1f49d709da2f789c9e41b556c5a/20_reading_eeg_data.py"><code class="xref download docutils literal notranslate"><span class="pre">Download</span> <span class="pre">Python</span> <span class="pre">source</span> <span class="pre">code:</span> <span class="pre">20_reading_eeg_data.py</span></code></a></p>
</div>
<div class="sphx-glr-download sphx-glr-download-jupyter docutils container">
<p><a class="reference download internal" download="" href="../../_downloads/afbdbca3a62dcdd6fc01894cd11b97b4/20_reading_eeg_data.ipynb"><code class="xref download docutils literal notranslate"><span class="pre">Download</span> <span class="pre">Jupyter</span> <span class="pre">notebook:</span> <span class="pre">20_reading_eeg_data.ipynb</span></code></a></p>
</div>
</div>
<p class="sphx-glr-signature"><a class="reference external" href="https://sphinx-gallery.github.io">Gallery generated by Sphinx-Gallery</a></p>
</section>
</section>
</div>
<!-- Previous / next buttons -->
<div class='prev-next-area'>
<a class='left-prev' id="prev-link" href="10_reading_meg_data.html" title="previous page">
<i class="fas fa-angle-left"></i>
<div class="prev-next-info">
<p class="prev-next-subtitle">previous</p>
<p class="prev-next-title">Importing data from MEG devices</p>
</div>
</a>
<a class='right-next' id="next-link" href="30_reading_fnirs_data.html" title="next page">
<div class="prev-next-info">
<p class="prev-next-subtitle">next</p>
<p class="prev-next-title">Importing data from fNIRS devices</p>
</div>
<i class="fas fa-angle-right"></i>
</a>
</div>
</main>
</div>
</div>
<script src="https://mne.tools/versionwarning.js"></script>
<!-- Scripts loaded after <body> so the DOM is not blocked -->
<script src="../../_static/scripts/pydata-sphinx-theme.js?digest=1999514e3f237ded88cf"></script>
<footer class="footer mt-5 mt-md-0">
<div class="container">
<div class="footer-item">
<p class="text-center text-muted small">© Copyright 2012–2022, MNE Developers. Last updated <time datetime="2022-05-27T17:47:54.886015+00:00" class="localized">2022-05-27 17:47 UTC</time>
<script type="text/javascript">$(function () { $("time.localized").each(function () { var el = $(this); el.text(new Date(el.attr("datetime")).toLocaleString([], {dateStyle: "medium", timeStyle: "long"})); }); } )</script></p>
</div>
</div>
</footer>
</body>
</html> | {
"content_hash": "0b0fce45390f3f39335ee62593f175a5",
"timestamp": "",
"source": "github",
"line_count": 1894,
"max_line_length": 524,
"avg_line_length": 43.04065469904963,
"alnum_prop": 0.6440707074424368,
"repo_name": "mne-tools/mne-tools.github.io",
"id": "46654fe3e054499f47116ee5a614e450d3b1f086",
"size": "81528",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "1.0/auto_tutorials/io/20_reading_eeg_data.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "708696"
},
{
"name": "Dockerfile",
"bytes": "1820"
},
{
"name": "HTML",
"bytes": "1526247783"
},
{
"name": "JavaScript",
"bytes": "1323087"
},
{
"name": "Jupyter Notebook",
"bytes": "24820047"
},
{
"name": "Python",
"bytes": "18575494"
}
],
"symlink_target": ""
} |
var APP_TITLE = 'brekkie';
var requestFailed = function(jqxhr, textStatus, error)
{
var err = textStatus + ", " + error;
console.log( "Request Failed: " + err );
}
var finishTitleFadeout = function()
{
mainMenu.transitionIn();
}
var finishMenuFadeout = function(recipeFileName)
{
recipeStepper.loadRecipe(recipeFileName);
}
var titleArea = new TitleArea();
var mainMenu = new MainMenu();
var recipeStepper = new RecipeStepper();
titleArea.fadeTitleIn();
$('#slidePanel').click(function() {$('#backbutton').css('visibility', 'hidden'); recipeStepper.nextState();});
$('#backbutton').click(function() {$(this).css('visibility', 'hidden'); recipeStepper.prevState();});
| {
"content_hash": "c7aff62bf56c5f41f84f4f6819426575",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 110,
"avg_line_length": 25.25925925925926,
"alnum_prop": 0.6994134897360704,
"repo_name": "danbolt/brekkie",
"id": "027e4f522b04412e0925c4df1213f8d2883b66e3",
"size": "682",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "js/main.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2173"
},
{
"name": "JavaScript",
"bytes": "6268"
}
],
"symlink_target": ""
} |
package hr.openbracketdelware;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
/**
* @author debmalyajash
*
*/
public class SpecialPathInStrangeTree {
/**
* @param args
*/
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
// n denoting number of vertices in the given tree.
int n = in.nextInt();
int[] arr = new int[n - 1];
// The second line contains n -1 space-separated integers, where the
// i th integer p[i] denotes the edge between vertexes i + 1 and
// p[i].
for (int i = 0; i < n - 1; i++) {
arr[i] = in.nextInt();
}
// The next line contains n space-separated integers, where ith
// integer denotes the number that was written on the vertex i.
int[] vertexWeigt = new int[n];
for (int i = 0; i < n; i++) {
vertexWeigt[i] = in.nextInt();
}
System.out.println(calculateNumberOfSpecialPath(arr, vertexWeigt));
}
}
static class StrangePath {
/**
* Each path will have unique weights.
*/
Set<Integer> weights;
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "StrangePath [weights=" + weights + "]";
}
}
/**
* A special path is a sequence of vertices v1,v2,v3,...,vm such that:
*
* There is an edge between vi and v(i+1) for each i < m.
*
* If we write down the integers written on every vertex , no integer will
* occur more than once.
*
* @param arr
* - edges
* @param vw
* - vertex weights
* @return total number of special paths
*
* example arr - 1,2,3 vw - 1,2,1,2 edges 1->2, 2->3, 3->4
*
*/
public static int calculateNumberOfSpecialPath(int[] arr, int[] vw) {
int count = vw.length;
// It will store all the strange paths.
List<StrangePath> strangePathList = new ArrayList<>();
// This map will maintain vertex wise strange path list.
Map<Integer, List<Integer>> strangePathMap = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
// the edge between vertexes i + 1 and p[i] ( arr[i] )
if (vw[i + 1] != vw[arr[i] - 1]) {
List<Integer> existing = strangePathMap.get(arr[i] - 1);
if (existing != null) {
// Check whether can be added in any existing or not.
for (int index : existing) {
if (strangePathList.get(index - 1).weights.add(vw[arr[i] - 1]) || strangePathList.get(index - 1).weights.add(vw[i + 1])) {
count += 2;
// List<Integer> existingPathList = strangePathMap.get(arr[i] - 1);
// if (existingPathList == null) {
// existingPathList = new ArrayList<>();
// }
// existingPathList.add(index);
// strangePathMap.put(arr[i] - 1, existingPathList);
}
}
}
List<Integer> existingPathList = strangePathMap.get(arr[i] - 1);
if (existingPathList == null) {
existingPathList = new ArrayList<>();
}
StrangePath newPath = new StrangePath();
newPath.weights = new HashSet<>();
newPath.weights.add(vw[arr[i] - 1]);
newPath.weights.add(vw[i + 1]);
strangePathList.add(newPath);
existingPathList.add(strangePathList.size());
strangePathMap.put(arr[i] - 1, existingPathList);
existingPathList = strangePathMap.get(arr[i]);
if (existingPathList == null) {
existingPathList = new ArrayList<>();
}
existingPathList.add(strangePathList.size());
strangePathMap.put(arr[i], existingPathList);
// System.out.println("strangePathMap " + strangePathMap);
// System.out.println("strangePathList " + strangePathList);
count += 2;
}
}
return count;
}
public static int calculateNumberOfSpecialPath1(int[] arr, int[] vw) {
int count = vw.length;
// It will store all the strange paths.
List<StrangePath> strangePathList = new ArrayList<>();
// This map will maintain vertex wise strange path list.
Map<Integer, List<Integer>> strangePathMap = new HashMap<>();
for (int i = 0; i < arr.length; i++) {
// the edge between vertexes i + 1 and p[i] ( arr[i] )
if (vw[i + 1] != vw[arr[i] - 1]) {
List<Integer> existing = strangePathMap.get(arr[i] - 1);
if (existing != null) {
// Check whether can be added in any existing or not.
for (int index : existing) {
if (strangePathList.get(index).weights.add(vw[arr[i] - 1])) {
count += 2;
List<Integer> existingPathList = strangePathMap.get(arr[i] - 1);
if (existingPathList == null) {
existingPathList = new ArrayList<>();
}
existingPathList.add(index);
strangePathMap.put(arr[i] - 1, existingPathList);
}
}
}
List<Integer> existingPathList = strangePathMap.get(arr[i] - 1);
if (existingPathList == null) {
existingPathList = new ArrayList<>();
}
StrangePath newPath = new StrangePath();
newPath.weights = new HashSet<>();
newPath.weights.add(vw[arr[i] - 1]);
newPath.weights.add(vw[i + 1]);
existingPathList.add(strangePathList.size());
strangePathMap.put(arr[i] - 1, existingPathList);
strangePathList.add(newPath);
existingPathList = strangePathMap.get(arr[i]);
if (existingPathList == null) {
existingPathList = new ArrayList<>();
}
newPath = new StrangePath();
newPath.weights = new HashSet<>();
newPath.weights.add(vw[arr[i] - 1]);
newPath.weights.add(vw[i + 1]);
existingPathList.add(strangePathList.size());
strangePathList.add(newPath);
strangePathMap.put(arr[i], existingPathList);
count += 2;
}
}
return count;
}
public static int calculateNumberOfSpecialPath0(int[] arr, int[] vw) {
int count = vw.length;
for (int i = 0; i < arr.length; i++) {
// the edge between vertexes i + 1 and p[i] ( arr[i] )
if (vw[i + 1] != vw[arr[i] - 1]) {
count += 2;
}
}
return count;
}
}
| {
"content_hash": "5192ce6e9266576c048aed8cc8243c2e",
"timestamp": "",
"source": "github",
"line_count": 216,
"max_line_length": 128,
"avg_line_length": 27.694444444444443,
"alnum_prop": 0.6183550651955868,
"repo_name": "debmalya/symmetrical-eureka",
"id": "886a23e40e3af17c28ca1442c2ce4abc1a81d8a2",
"size": "6595",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/hr/openbracketdelware/SpecialPathInStrangeTree.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "1371"
},
{
"name": "C++",
"bytes": "403"
},
{
"name": "Java",
"bytes": "798967"
},
{
"name": "Python",
"bytes": "839"
},
{
"name": "Shell",
"bytes": "190"
}
],
"symlink_target": ""
} |
from django.conf import settings
from django.core.cache import cache
from django.db import models
from django.utils.functional import classproperty
from taggit.managers import TaggableManager
from translator.util import get_key
class TranslationBase(models.Model):
key = models.CharField(max_length=255, unique=True)
description = models.TextField()
tags = TaggableManager(blank=True)
class Meta:
abstract = True
def __unicode__(self):
return self.key
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
all_translation_keys = self.__class__.objects.all().values_list('key', flat=True)
for l in settings.LANGUAGES:
cache.delete_many([get_key(l[0], k, self.cache_key_prefix) for k in all_translation_keys])
return super().save(force_insert, force_update, using, update_fields)
@classproperty
def cache_key_prefix(self):
"""To separate cache keys, we need to specify a unique prefix per model."""
return self._meta.db_table
class Translation(TranslationBase):
pass
| {
"content_hash": "aa4743cac8627cbe34c81c5a40eb23e2",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 102,
"avg_line_length": 31.8,
"alnum_prop": 0.7026055705300989,
"repo_name": "dreipol/django-translator",
"id": "c146b3661759a2059b813bcf1bc41239820ee034",
"size": "1128",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "translator/models.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "8267"
}
],
"symlink_target": ""
} |
jQuery.noConflict();
// only use Zepto if it's supported
Zepto = '__proto__' in {} ? Zepto : undefined;
// Initialize Foundation
(function($){
$(function(){ $(document).foundation(); });
})(jQuery);
| {
"content_hash": "8f78e2a02872afb51cf971665c30e490",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 46,
"avg_line_length": 28.714285714285715,
"alnum_prop": 0.6368159203980099,
"repo_name": "KitchnSink/Project-Spatula",
"id": "41dac0b86f8188b7ff1c116b1ee3a04ede327b60",
"size": "962",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/assets/javascripts/application.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "40812"
},
{
"name": "JavaScript",
"bytes": "34043"
},
{
"name": "Ruby",
"bytes": "55723"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "6a85fde5d3f7dc4bb8389745fe1b3cc8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 10.307692307692308,
"alnum_prop": 0.6940298507462687,
"repo_name": "mdoering/backbone",
"id": "48654719e7e0cc0358b1e8be6a666718f6c6ec79",
"size": "193",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Liliopsida/Poales/Bromeliaceae/Tillandsia/Tillandsia mitlaensis/Tillandsia mitlaensis tulensis/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
layout: default
title: "Women In Sport"
---
{% include interests/women-in-sport.md %}
### Who is interested in Women In Sport?
* [Barbara Keeley]({{ site.baseurl }}/members/barbara-keeley.html)
| {
"content_hash": "a73e0bfd1c374153548f3b96a5951ac4",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 66,
"avg_line_length": 18.09090909090909,
"alnum_prop": 0.6884422110552764,
"repo_name": "JeniT/childs-guide-to-parliament",
"id": "9d21ce170291098ac358cb987f208a09dcf5f863",
"size": "319",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "interests/women-in-sport.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "210544"
},
{
"name": "JavaScript",
"bytes": "6242"
},
{
"name": "Python",
"bytes": "11600"
},
{
"name": "Ruby",
"bytes": "48"
}
],
"symlink_target": ""
} |
@implementation UIViewController (QMUI)
void qmui_loadViewIfNeeded (id current_self, SEL current_cmd) {
// 主动调用 self.view,从而触发 loadView,以模拟 iOS 9.0 以下的系统 loadViewIfNeeded 行为
QMUILog(@"%@", ((UIViewController *)current_self).view);
}
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// 为 description 增加更丰富的信息
ReplaceMethod([UIViewController class], @selector(description), @selector(qmui_description));
// 兼容 iOS 9.0 以下的版本对 loadViewIfNeeded 方法的调用
if (![[UIViewController class] instancesRespondToSelector:@selector(loadViewIfNeeded)]) {
Class metaclass = [self class];
BOOL success = class_addMethod(metaclass, @selector(loadViewIfNeeded), (IMP)qmui_loadViewIfNeeded, "v@:");
QMUILog(@"%@ %s, success = %@", NSStringFromClass([self class]), __func__, StringFromBOOL(success));
}
// 实现 AutomaticallyRotateDeviceOrientation 开关的功能
ReplaceMethod([UIViewController class], @selector(viewWillAppear:), @selector(qmui_viewWillAppear:));
});
}
- (NSString *)qmui_description {
NSString *result = [NSString stringWithFormat:@"%@\nsuperclass:\t\t\t\t%@\ntitle:\t\t\t\t\t%@\nview:\t\t\t\t\t%@", [self qmui_description], NSStringFromClass(self.superclass), self.title, [self isViewLoaded] ? self.view : nil];
if ([self isKindOfClass:[UINavigationController class]]) {
UINavigationController *navController = (UINavigationController *)self;
NSString *navDescription = [NSString stringWithFormat:@"\nviewControllers(%@):\t\t%@\ntopViewController:\t\t%@\nvisibleViewController:\t%@", @(navController.viewControllers.count), [self descriptionWithViewControllers:navController.viewControllers], [navController.topViewController qmui_description], [navController.visibleViewController qmui_description]];
result = [result stringByAppendingString:navDescription];
} else if ([self isKindOfClass:[UITabBarController class]]) {
UITabBarController *tabBarController = (UITabBarController *)self;
NSString *tabBarDescription = [NSString stringWithFormat:@"\nviewControllers(%@):\t\t%@\nselectedViewController(%@):\t%@", @(tabBarController.viewControllers.count), [self descriptionWithViewControllers:tabBarController.viewControllers], @(tabBarController.selectedIndex), [tabBarController.selectedViewController qmui_description]];
result = [result stringByAppendingString:tabBarDescription];
}
return result;
}
- (NSString *)descriptionWithViewControllers:(NSArray<UIViewController *> *)viewControllers {
NSMutableString *string = [[NSMutableString alloc] init];
[string appendString:@"(\n"];
for (NSInteger i = 0, l = viewControllers.count; i < l; i++) {
[string appendFormat:@"\t\t\t\t\t\t\t[%@]%@%@\n", @(i), [viewControllers[i] qmui_description], i < l - 1 ? @"," : @""];
}
[string appendString:@"\t\t\t\t\t\t)"];
return [string copy];
}
- (void)qmui_viewWillAppear:(BOOL)animated {
[self qmui_viewWillAppear:animated];
if (!AutomaticallyRotateDeviceOrientation) {
return;
}
UIInterfaceOrientation statusBarOrientation = [[UIApplication sharedApplication] statusBarOrientation];
UIDeviceOrientation deviceOrientationBeforeChangingByHelper = [QMUIHelper sharedInstance].orientationBeforeChangingByHelper;
BOOL shouldConsiderBeforeChanging = deviceOrientationBeforeChangingByHelper != UIDeviceOrientationUnknown;
UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
// 虽然这两者的 unknow 值是相同的,但在启动 App 时可能只有其中一个是 unknown
if (statusBarOrientation == UIInterfaceOrientationUnknown || deviceOrientation == UIDeviceOrientationUnknown) return;
// 如果当前设备方向和界面支持的方向不一致,则主动进行旋转
UIDeviceOrientation deviceOrientationToRotate = [self interfaceOrientationMask:self.supportedInterfaceOrientations containsDeviceOrientation:deviceOrientation] ? deviceOrientation : [self deviceOrientationWithInterfaceOrientationMask:self.supportedInterfaceOrientations];
// 之前没用私有接口修改过,拿就按最标准的方式去旋转
if (!shouldConsiderBeforeChanging) {
if ([QMUIHelper rotateToDeviceOrientation:deviceOrientationToRotate]) {
[QMUIHelper sharedInstance].orientationBeforeChangingByHelper = deviceOrientation;
} else {
[QMUIHelper sharedInstance].orientationBeforeChangingByHelper = UIDeviceOrientationUnknown;
}
return;
}
// 用私有接口修改过方向,但下一个界面和当前界面方向不相同,则要把修改前记录下来的那个设备方向考虑进来
deviceOrientationToRotate = [self interfaceOrientationMask:self.supportedInterfaceOrientations containsDeviceOrientation:deviceOrientationBeforeChangingByHelper] ? deviceOrientationBeforeChangingByHelper : [self deviceOrientationWithInterfaceOrientationMask:self.supportedInterfaceOrientations];
[QMUIHelper rotateToDeviceOrientation:deviceOrientationToRotate];
}
- (UIDeviceOrientation)deviceOrientationWithInterfaceOrientationMask:(UIInterfaceOrientationMask)mask {
if ((mask & UIInterfaceOrientationMaskAll) == UIInterfaceOrientationMaskAll) {
return [UIDevice currentDevice].orientation;
}
if ((mask & UIInterfaceOrientationMaskAllButUpsideDown) == UIInterfaceOrientationMaskAllButUpsideDown) {
return [UIDevice currentDevice].orientation;
}
if ((mask & UIInterfaceOrientationMaskPortrait) == UIInterfaceOrientationMaskPortrait) {
return UIDeviceOrientationPortrait;
}
if ((mask & UIInterfaceOrientationMaskLandscape) == UIInterfaceOrientationMaskLandscape) {
return [UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft ? UIDeviceOrientationLandscapeLeft : UIDeviceOrientationLandscapeRight;
}
if ((mask & UIInterfaceOrientationMaskLandscapeLeft) == UIInterfaceOrientationMaskLandscapeLeft) {
return UIDeviceOrientationLandscapeRight;
}
if ((mask & UIInterfaceOrientationMaskLandscapeRight) == UIInterfaceOrientationMaskLandscapeRight) {
return UIDeviceOrientationLandscapeLeft;
}
if ((mask & UIInterfaceOrientationMaskPortraitUpsideDown) == UIInterfaceOrientationMaskPortraitUpsideDown) {
return UIDeviceOrientationPortraitUpsideDown;
}
return [UIDevice currentDevice].orientation;
}
- (BOOL)interfaceOrientationMask:(UIInterfaceOrientationMask)mask containsDeviceOrientation:(UIDeviceOrientation)deviceOrientation {
if (deviceOrientation == UIDeviceOrientationUnknown) {
return YES;// YES 表示不用额外处理
}
if ((mask & UIInterfaceOrientationMaskAll) == UIInterfaceOrientationMaskAll) {
return YES;
}
if ((mask & UIInterfaceOrientationMaskAllButUpsideDown) == UIInterfaceOrientationMaskAllButUpsideDown) {
return UIInterfaceOrientationPortraitUpsideDown != deviceOrientation;
}
if ((mask & UIInterfaceOrientationMaskPortrait) == UIInterfaceOrientationMaskPortrait) {
return UIInterfaceOrientationPortrait == deviceOrientation;
}
if ((mask & UIInterfaceOrientationMaskLandscape) == UIInterfaceOrientationMaskLandscape) {
return UIInterfaceOrientationLandscapeLeft == deviceOrientation || UIInterfaceOrientationLandscapeRight == deviceOrientation;
}
if ((mask & UIInterfaceOrientationMaskLandscapeLeft) == UIInterfaceOrientationMaskLandscapeLeft) {
return UIInterfaceOrientationLandscapeLeft == deviceOrientation;
}
if ((mask & UIInterfaceOrientationMaskLandscapeRight) == UIInterfaceOrientationMaskLandscapeRight) {
return UIInterfaceOrientationLandscapeRight == deviceOrientation;
}
if ((mask & UIInterfaceOrientationMaskPortraitUpsideDown) == UIInterfaceOrientationMaskPortraitUpsideDown) {
return UIInterfaceOrientationPortraitUpsideDown == deviceOrientation;
}
return YES;
}
- (UIViewController *)qmui_previousViewController {
if (self.navigationController.viewControllers && self.navigationController.viewControllers.count > 1 && self.navigationController.topViewController == self) {
NSUInteger count = self.navigationController.viewControllers.count;
return (UIViewController *)[self.navigationController.viewControllers objectAtIndex:count - 2];
}
return nil;
}
- (NSString *)qmui_previousViewControllerTitle {
UIViewController *previousViewController = [self qmui_previousViewController];
if (previousViewController) {
return previousViewController.title;
}
return nil;
}
- (BOOL)qmui_isPresented {
UIViewController *viewController = self;
if (self.navigationController) {
if (self.navigationController.qmui_rootViewController != self) {
return NO;
}
viewController = self.navigationController;
}
BOOL result = viewController.presentingViewController.presentedViewController == viewController;
return result;
}
- (UIViewController *)qmui_visibleViewControllerIfExist {
if (self.presentedViewController) {
return [self.presentedViewController qmui_visibleViewControllerIfExist];
}
if ([self isKindOfClass:[UINavigationController class]]) {
return [((UINavigationController *)self).visibleViewController qmui_visibleViewControllerIfExist];
}
if ([self isKindOfClass:[UITabBarController class]]) {
return [((UITabBarController *)self).selectedViewController qmui_visibleViewControllerIfExist];
}
if ([self isViewLoaded] && self.view.window) {
return self;
} else {
NSLog(@"qmui_visibleViewControllerIfExist:,找不到可见的viewController。self = %@, self.view.window = %@", self, self.view.window);
return nil;
}
}
- (BOOL)qmui_respondQMUINavigationControllerDelegate {
return [[self class] conformsToProtocol:@protocol(QMUINavigationControllerDelegate)];
}
- (BOOL)qmui_isViewLoadedAndVisible {
return self.isViewLoaded && self.view.window;
}
- (CGFloat)qmui_navigationBarMaxYInViewCoordinator {
if (!self.isViewLoaded) {
return 0;
}
if (!self.navigationController.navigationBar || self.navigationController.navigationBarHidden) {
return 0;
}
CGRect navigationBarFrame = CGRectIntersection(self.view.bounds, [self.view convertRect:self.navigationController.navigationBar.frame fromView:self.navigationController.navigationBar.superview]);
CGFloat result = CGRectGetMaxY(navigationBarFrame);
return result;
}
- (CGFloat)qmui_toolbarSpacingInViewCoordinator {
if (!self.isViewLoaded) {
return 0;
}
if (!self.navigationController.toolbar || self.navigationController.toolbarHidden) {
return 0;
}
CGRect toolbarFrame = CGRectIntersection(self.view.bounds, [self.view convertRect:self.navigationController.toolbar.frame fromView:self.navigationController.toolbar.superview]);
CGFloat result = CGRectGetHeight(self.view.bounds) - CGRectGetMinY(toolbarFrame);
return result;
}
- (CGFloat)qmui_tabBarSpacingInViewCoordinator {
if (!self.isViewLoaded) {
return 0;
}
if (!self.tabBarController.tabBar || self.tabBarController.tabBar.hidden) {
return 0;
}
CGRect tabBarFrame = CGRectIntersection(self.view.bounds, [self.view convertRect:self.tabBarController.tabBar.frame fromView:self.tabBarController.tabBar.superview]);
CGFloat result = CGRectGetHeight(self.view.bounds) - CGRectGetMinY(tabBarFrame);
return result;
}
@end
@interface UIViewController ()
@property(nonatomic, assign) BOOL qmui_isViewDidAppear;
@end
@implementation UIViewController (Data)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
ReplaceMethod(self.class, @selector(viewDidAppear:), @selector(qmui_viewDidAppear:));
});
}
- (void)qmui_viewDidAppear:(BOOL)animated {
[self qmui_viewDidAppear:animated];
self.qmui_isViewDidAppear = YES;
if (self.qmui_didAppearAndLoadDataBlock && self.qmui_isViewDidAppear && self.qmui_dataLoaded) {
self.qmui_didAppearAndLoadDataBlock();
self.qmui_didAppearAndLoadDataBlock = nil;
}
}
static char kAssociatedObjectKey_isViewDidAppear;
- (void)setQmui_isViewDidAppear:(BOOL)qmui_isViewDidAppear {
objc_setAssociatedObject(self, &kAssociatedObjectKey_isViewDidAppear, @(qmui_isViewDidAppear), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)qmui_isViewDidAppear {
return [((NSNumber *)objc_getAssociatedObject(self, &kAssociatedObjectKey_isViewDidAppear)) boolValue];
}
static char kAssociatedObjectKey_didAppearAndLoadDataBlock;
- (void)setQmui_didAppearAndLoadDataBlock:(void (^)())qmui_didAppearAndLoadDataBlock {
objc_setAssociatedObject(self, &kAssociatedObjectKey_didAppearAndLoadDataBlock, qmui_didAppearAndLoadDataBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (void (^)())qmui_didAppearAndLoadDataBlock {
return (void (^)())objc_getAssociatedObject(self, &kAssociatedObjectKey_didAppearAndLoadDataBlock);
}
static char kAssociatedObjectKey_dataLoaded;
- (void)setQmui_dataLoaded:(BOOL)qmui_dataLoaded {
objc_setAssociatedObject(self, &kAssociatedObjectKey_dataLoaded, @(qmui_dataLoaded), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (self.qmui_didAppearAndLoadDataBlock && qmui_dataLoaded && self.qmui_isViewDidAppear) {
self.qmui_didAppearAndLoadDataBlock();
self.qmui_didAppearAndLoadDataBlock = nil;
}
}
- (BOOL)isQmui_dataLoaded {
return [((NSNumber *)objc_getAssociatedObject(self, &kAssociatedObjectKey_dataLoaded)) boolValue];
}
@end
@implementation UIViewController (Runtime)
- (BOOL)qmui_hasOverrideUIKitMethod:(SEL)selector {
// 排序依照 Xcode Interface Builder 里的控件排序,但保证子类在父类前面
NSMutableArray<Class> *viewControllerSuperclasses = [[NSMutableArray alloc] initWithObjects:
[UIImagePickerController class],
[UINavigationController class],
[UITableViewController class],
[UICollectionViewController class],
[UITabBarController class],
[UISplitViewController class],
[UIPageViewController class],
[UIViewController class],
nil];
if (NSClassFromString(@"UIAlertController")) {
[viewControllerSuperclasses addObject:[UIAlertController class]];
}
if (NSClassFromString(@"UISearchController")) {
[viewControllerSuperclasses addObject:[UISearchController class]];
}
for (NSInteger i = 0, l = viewControllerSuperclasses.count; i < l; i++) {
Class superclass = viewControllerSuperclasses[i];
if ([self qmui_hasOverrideMethod:selector ofSuperclass:superclass]) {
return YES;
}
}
return NO;
}
@end
| {
"content_hash": "e133b4202c6edc5c198973c0119eba7c",
"timestamp": "",
"source": "github",
"line_count": 325,
"max_line_length": 366,
"avg_line_length": 46.09538461538462,
"alnum_prop": 0.7233829517388692,
"repo_name": "boai/BAWeChat",
"id": "f7037a4586586d60f000204cfe297795bc321247",
"size": "15727",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WeChat/Pods/QMUIKit/QMUIKit/UIKitExtensions/UIViewController+QMUI.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "28258"
},
{
"name": "Objective-C",
"bytes": "4218867"
},
{
"name": "Ruby",
"bytes": "12789"
}
],
"symlink_target": ""
} |
namespace Dike.Core.Mail.Smtp
{
/// <summary>
/// Implement this interface to store the SMTP sender configuration
/// </summary>
/// <seealso cref="Dike.Core.Mail.IEmailSenderConfiguration" />
public interface ISmtpEmailSenderConfiguration
: IEmailSenderConfiguration
{
#region Properties
/// <summary>
/// Gets the domain name to login to the SMTP server.
/// </summary>
/// <value>The domain name to login to the SMTP server.</value>
string Domain
{
get;
}
/// <summary>
/// Gets a value indicating whether to enable SSL.
/// </summary>
/// <value><c>true</c> to enable SSL; otherwise, <c>false</c>.</value>
bool EnableSsl
{
get;
}
/// <summary>
/// Gets the SMTP host name or IP address.
/// </summary>
/// <value>The SMTP host name or IP address.</value>
string Host
{
get;
}
/// <summary>
/// Gets the password to login to the SMTP server.
/// </summary>
/// <value>The password to login to the SMTP server.</value>
string Password
{
get;
}
/// <summary>
/// Gets the SMTP port.
/// </summary>
/// <value>The SMTP port.</value>
int Port
{
get;
}
/// <summary>
/// Gets a value indicating whether to use the default credentials.
/// </summary>
/// <value><c>true</c> to use the default credentials; otherwise, <c>false</c>.</value>
bool UseDefaultCredentials
{
get;
}
/// <summary>
/// Gets the user name to login to the SMTP server.
/// </summary>
/// <value>The user name to login to the SMTP server.</value>
string UserName
{
get;
}
#endregion Properties
}
} | {
"content_hash": "b11b286688af85acd1dd8f1220e4b750",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 95,
"avg_line_length": 26,
"alnum_prop": 0.4985014985014985,
"repo_name": "IngbertPalm/project.dike",
"id": "dbdb3a25859adcc1056de69c8f35d800afcc770b",
"size": "2004",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Dike.Core/Mail/Smtp/ISmtpEmailSenderConfiguration.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "3735688"
},
{
"name": "CSS",
"bytes": "260971"
},
{
"name": "JavaScript",
"bytes": "7937"
},
{
"name": "TypeScript",
"bytes": "1181"
}
],
"symlink_target": ""
} |
<?php
namespace OAuth2\Storage;
class PdoTest extends BaseTest
{
public function testCreatePdoStorageUsingPdoClass()
{
$pdo = new \PDO(sprintf('sqlite://%s', Bootstrap::getInstance()->getSqliteDir()));
$storage = new Pdo($pdo);
$this->assertNotNull($storage->getClientDetails('oauth_test_client'));
}
public function testCreatePdoStorageUsingDSN()
{
$dsn = sprintf('sqlite://%s', Bootstrap::getInstance()->getSqliteDir());
$storage = new Pdo($dsn);
$this->assertNotNull($storage->getClientDetails('oauth_test_client'));
}
public function testCreatePdoStorageUsingConfig()
{
$config = array('dsn' => sprintf('sqlite://%s', Bootstrap::getInstance()->getSqliteDir()));
$storage = new Pdo($config);
$this->assertNotNull($storage->getClientDetails('oauth_test_client'));
}
public function testCreatePdoStorageWithoutDSNThrowsException()
{
$config = array('username' => 'brent', 'password' => 'brentisaballer');
$storage = new Pdo($config);
}
}
| {
"content_hash": "9172f398195ec1521c5695f2f12829ec",
"timestamp": "",
"source": "github",
"line_count": 37,
"max_line_length": 99,
"avg_line_length": 29.2972972972973,
"alnum_prop": 0.6365313653136532,
"repo_name": "Onidca/Cloudika",
"id": "d09435112925b96369fbfac9fe5c2a40509205b7",
"size": "1084",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "vendor/bshaffer/oauth2-server-php/test/OAuth2/Storage/PdoTest.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "1205"
},
{
"name": "CSS",
"bytes": "966843"
},
{
"name": "Clojure",
"bytes": "2271"
},
{
"name": "Gherkin",
"bytes": "529"
},
{
"name": "Go",
"bytes": "16039"
},
{
"name": "HTML",
"bytes": "4536731"
},
{
"name": "JavaScript",
"bytes": "1497854"
},
{
"name": "Makefile",
"bytes": "3596"
},
{
"name": "PHP",
"bytes": "9570682"
},
{
"name": "Python",
"bytes": "37904"
},
{
"name": "Ruby",
"bytes": "6412"
},
{
"name": "Shell",
"bytes": "33368"
},
{
"name": "Smarty",
"bytes": "601021"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jsast: 13 s</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.11.2 / jsast - 2.0.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
jsast
<small>
2.0.0
<span class="label label-success">13 s</span>
</small>
</h1>
<p><em><script>document.write(moment("2020-08-31 05:47:56 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-08-31 05:47:56 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
conf-m4 1 Virtual package relying on m4
coq 8.11.2 Formal proof management system
num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.11.0 The OCaml compiler (virtual package)
ocaml-base-compiler 4.11.0 Official release 4.11.0
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.8.1 A library manager for OCaml
# opam file:
opam-version: "2.0"
synopsis: "A minimal JavaScript syntax tree carved out of the JsCert project"
description: """
A minimal JavaScript syntax tree carved out of the JsCert project, with additional support for let bindings and using native floats.
"""
maintainer: "Jerome Simeon <jeromesimeon@me.com>"
authors: [
"Martin Bodin <>"
"Arthur Charguéraud <>"
"Daniele Filaretti <>"
"Philippa Gardner <>"
"Sergio Maffeis <>"
"Daiva Naudziuniene <>"
"Alan Schmitt <>"
"Gareth Smith <>"
"Josh Auerbach <>"
"Martin Hirzel <>"
"Louis Mandel <>"
"Avi Shinnar <>"
"Jerome Simeon <>"
]
license: "BSD-2-Clause"
homepage: "https://github.com/querycert/jsast"
bug-reports: "https://github.com/querycert/jsast/issues"
dev-repo: "git+https://github.com/querycert/jsast/tree/JsAst"
build: [
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
depends: [
"coq" { >= "8.11.2" }
]
tags: [ "keyword:javascript" "keyword:compiler" "date:2020-07-29" "logpath:JsAst" ]
url {
src: "https://github.com/querycert/jsast/archive/v2.0.0.tar.gz"
checksum: "md5=cdda0e39036bbcb08fb5d048299dd103"
}
</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-jsast.2.0.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>0</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>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-jsast.2.0.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>7 s</dd>
</dl>
<h2>Install</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 2h opam install -y -v coq-jsast.2.0.0 coq.8.11.2</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>13 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 148 K</p>
<ul>
<li>76 K <code>../ocaml-base-compiler.4.11.0/lib/coq/user-contrib/JsAst/JsSyntax.vo</code></li>
<li>38 K <code>../ocaml-base-compiler.4.11.0/lib/coq/user-contrib/JsAst/JsNumber.vo</code></li>
<li>20 K <code>../ocaml-base-compiler.4.11.0/lib/coq/user-contrib/JsAst/JsSyntax.glob</code></li>
<li>6 K <code>../ocaml-base-compiler.4.11.0/lib/coq/user-contrib/JsAst/JsSyntax.v</code></li>
<li>4 K <code>../ocaml-base-compiler.4.11.0/lib/coq/user-contrib/JsAst/JsNumber.glob</code></li>
<li>4 K <code>../ocaml-base-compiler.4.11.0/lib/coq/user-contrib/JsAst/JsNumber.v</code></li>
</ul>
<h2>Uninstall</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-jsast.2.0.0</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">
<small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small>
</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": "0fd2b77f600155f6a9a5242d0be4b4f8",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 157,
"avg_line_length": 42.42458100558659,
"alnum_prop": 0.5431919936792204,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "5a901155c71877317d89235b74cd838b581d3a9d",
"size": "7597",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.11.0-2.0.7/released/8.11.2/jsast/2.0.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_151) on Thu Dec 05 05:02:11 MST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.wildfly.swarm.config.management.security_realm.UsersAuthentication.UsersAuthenticationResources (BOM: * : All 2.6.0.Final API)</title>
<meta name="date" content="2019-12-05">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.wildfly.swarm.config.management.security_realm.UsersAuthentication.UsersAuthenticationResources (BOM: * : All 2.6.0.Final API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/UsersAuthentication.UsersAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.6.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/UsersAuthentication.UsersAuthenticationResources.html" target="_top">Frames</a></li>
<li><a href="UsersAuthentication.UsersAuthenticationResources.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.wildfly.swarm.config.management.security_realm.UsersAuthentication.UsersAuthenticationResources" class="title">Uses of Class<br>org.wildfly.swarm.config.management.security_realm.UsersAuthentication.UsersAuthenticationResources</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/UsersAuthentication.UsersAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">UsersAuthentication.UsersAuthenticationResources</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.wildfly.swarm.config.management.security_realm">org.wildfly.swarm.config.management.security_realm</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.wildfly.swarm.config.management.security_realm">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/UsersAuthentication.UsersAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">UsersAuthentication.UsersAuthenticationResources</a> in <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/package-summary.html">org.wildfly.swarm.config.management.security_realm</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/package-summary.html">org.wildfly.swarm.config.management.security_realm</a> that return <a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/UsersAuthentication.UsersAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">UsersAuthentication.UsersAuthenticationResources</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/UsersAuthentication.UsersAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">UsersAuthentication.UsersAuthenticationResources</a></code></td>
<td class="colLast"><span class="typeNameLabel">UsersAuthentication.</span><code><span class="memberNameLink"><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/UsersAuthentication.html#subresources--">subresources</a></span>()</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/wildfly/swarm/config/management/security_realm/UsersAuthentication.UsersAuthenticationResources.html" title="class in org.wildfly.swarm.config.management.security_realm">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage">Thorntail API, 2.6.0.Final</div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/wildfly/swarm/config/management/security_realm/class-use/UsersAuthentication.UsersAuthenticationResources.html" target="_top">Frames</a></li>
<li><a href="UsersAuthentication.UsersAuthenticationResources.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2019 <a href="http://www.jboss.org">JBoss by Red Hat</a>. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "37f9e4d884f3e1b96ffcaccea2ef4214",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 503,
"avg_line_length": 49.44642857142857,
"alnum_prop": 0.6685927530997954,
"repo_name": "wildfly-swarm/wildfly-swarm-javadocs",
"id": "dce0d2fbeeb22d4b03a307fcdd952e3b7e68d50a",
"size": "8307",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2.6.0.Final/apidocs/org/wildfly/swarm/config/management/security_realm/class-use/UsersAuthentication.UsersAuthenticationResources.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
namespace dstuecken\Notify;
use dstuecken\Notify\Handler\NullHandler;
use dstuecken\Notify\Interfaces\HandlerInterface;
use dstuecken\Notify\Interfaces\NotificationInterface;
use dstuecken\Notify\Type\DetailedNotification;
use Psr\Log\LoggerInterface;
/**
* Class NotificationCenter
*
* @package dstuecken\Notify
* @author Dennis Stücken <dstuecken@me.com>
*/
class NotificationCenter
implements LoggerInterface
{
/**
* Debug
*/
const DEBUG = 100;
/**
* Informative
*/
const INFO = 200;
/**
* Notices
*/
const NOTICE = 250;
/**
* Warnings or Exceptions
*/
const WARNING = 300;
/**
* Runtime errors
*/
const ERROR = 400;
/**
* Critical problems
*/
const CRITICAL = 500;
/**
* Alerts
*/
const ALERT = 550;
/**
* Problematic issues
*/
const EMERGENCY = 600;
/**
* The handler stack
*
* @var HandlerInterface[]
*/
protected $handlers;
/**
* @var NotificationInterface[]
*/
protected $notifications = [];
/**
* @param HandlerInterface[] $handlers Optional stack of handlers, the first one in the array is called first, etc.
*/
public function __construct(array $handlers = [])
{
$this->handlers = $handlers;
}
/**
* Factory method for a better method chaining experience
*
* @param array $handlers
*
* @return NotificationCenter
*/
public static function factory(array $handlers = [])
{
return new self($handlers);
}
/**
* Push handler to stack.
*
* @param HandlerInterface $handler
*
* @return $this
*/
public function addHandler(HandlerInterface $handler)
{
array_unshift($this->handlers, $handler);
return $this;
}
/**
* Pops last handler from stack
*
* @return HandlerInterface
*/
public function popHandler()
{
if (!$this->handlers)
{
throw new \LogicException('Your handler stack is empty.');
}
return array_shift($this->handlers);
}
/**
* Returns all the handlers associated to this manager.
*
* @return HandlerInterface[]
*/
public function getHandlers()
{
return $this->handlers;
}
/**
* @param $byClassName
*
* @return HandlerInterface
*/
public function getRegisteredHandler($byClassName)
{
foreach ($this->handlers as $handler)
{
if (is_a($handler, $byClassName))
{
return $handler;
}
}
throw new \InvalidArgumentException('There is no handler named "' . $byClassName . '" registered.');
}
/**
* Handles notification for every handler
*
* @param NotificationInterface $notification the notification instanceitself
* @param int $level Level of this notification
*
* @return bool
*/
public function notify(NotificationInterface $notification, $level = self::INFO)
{
if (!$this->handlers)
{
$this->addHandler(new NullHandler());
}
foreach ($this->getHandlers() as $handler)
{
if ($handler->shouldHandle($notification, $level))
{
if (false === $handler->handle($notification, $level))
{
return false;
}
}
}
return true;
}
/**
* Adds a new notification message to the queue as an attribute aware notification
*
* @param mixed $level The log level
* @param string $message notification message (body)
* @param array $context notification parameters
*
* @return bool record processed or not?
*/
public function log($level, $message, array $context = [])
{
return $this->notify(
new DetailedNotification($message, '', $context),
$level
);
}
/**
* Debug level notification
*
* @param string $message notification message (body)
* @param array $context notification parameters
*
* @return bool record processed or not?
*/
public function debug($message, array $context = [])
{
return $this->notify(
new DetailedNotification($message, '', $context),
static::DEBUG
);
}
/**
* Info level notification
*
* @param string $message notification message (body)
* @param array $context notification parameters
*
* @return bool record processed or not?
*/
public function info($message, array $context = [])
{
return $this->notify(
new DetailedNotification($message, '', $context),
static::INFO
);
}
/**
* Notice level notification
*
* @param string $message notification message (body)
* @param array $context notification parameters
*
* @return bool record processed or not?
*/
public function notice($message, array $context = [])
{
return $this->notify(
new DetailedNotification($message, '', $context),
static::NOTICE
);
}
/**
* Warning level notification
*
* @param string $message notification message (body)
* @param array $context notification parameters
*
* @return bool record processed or not?
*/
public function warning($message, array $context = [])
{
return $this->notify(
new DetailedNotification($message, '', $context),
static::WARNING
);
}
/**
* Error level notification
*
* @param string $message notification message (body)
* @param array $context notification parameters
*
* @return bool record processed or not?
*/
public function error($message, array $context = [])
{
return $this->notify(
new DetailedNotification($message, '', $context),
static::ERROR
);
}
/**
* Critical level notification
*
* @param string $message notification message (body)
* @param array $context notification parameters
*
* @return bool record processed or not?
*/
public function critical($message, array $context = [])
{
return $this->notify(
new DetailedNotification($message, '', $context),
static::CRITICAL
);
}
/**
* Alert level notification
*
* @param string $message notification message (body)
* @param array $context notification parameters
*
* @return bool record processed or not?
*/
public function alert($message, array $context = [])
{
return $this->notify(
new DetailedNotification($message, '', $context),
static::ALERT
);
}
/**
* Emergency level notification
*
* @param string $message notification message (body)
* @param array $context notification parameters
*
* @return bool record processed or not?
*/
public function emergency($message, array $context = [])
{
return $this->notify(
new DetailedNotification($message, '', $context),
static::EMERGENCY
);
}
}
| {
"content_hash": "c0fe816c01d4cd3860292aadabe024bd",
"timestamp": "",
"source": "github",
"line_count": 323,
"max_line_length": 119,
"avg_line_length": 23.238390092879257,
"alnum_prop": 0.5544897415401012,
"repo_name": "dstuecken/notify",
"id": "f7632723ea0327567bd09cdbb920b0e4ff0744fd",
"size": "7507",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/NotificationCenter.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "36744"
}
],
"symlink_target": ""
} |
'use strict';
describe('Service: MedBatch', function () {
// load the service's module
beforeEach(module('tdpharmaClientApp'));
// instantiate service
var MedBatch;
beforeEach(inject(function (_MedBatch_) {
MedBatch = _MedBatch_;
}));
it('should do something', function () {
expect(!!MedBatch).toBe(true);
});
});
| {
"content_hash": "100afcfa527c494bc2b2327b5786fdf9",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 43,
"avg_line_length": 19.055555555555557,
"alnum_prop": 0.641399416909621,
"repo_name": "tdang2/tdpharma-client",
"id": "8371e67db7c8e3d386c3de5a2b7105e8cfdd97ad",
"size": "343",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/components/models/medBatch/medBatch.service.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "CSS",
"bytes": "5303"
},
{
"name": "HTML",
"bytes": "58874"
},
{
"name": "JavaScript",
"bytes": "129675"
}
],
"symlink_target": ""
} |
// ----------------------------------------------------------------------------
// Copyright 2007-2015, GeoTelematic Solutions, Inc.
// All rights reserved
// ----------------------------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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.
//
// ----------------------------------------------------------------------------
// Change History:
// 2011/07/15 Martin D. Flynn
// -Initial release
// 2011/08/21 Martin D. Flynn
// -Fixed JSON parsing.
// 2011/10/03 Martin D. Flynn
// -Added multiple-name lookup support
// 2013/03/01 Martin D. Flynn
// -Added 'null' object support
// 2013/04/08 Martin D. Flynn
// -Handle parsing of arrays within arrays
// 2013/08/06 Martin D. Flynn
// -Added "JSONParsingContext" for easier debugging of syntax errors
// -Added support for "/*...*/" comments (NOTE: this is a non-standard feature
// which is NOT supported by other JSON parsers, including JavaScript).
// 2013/11/11 Martin D. Flynn
// -Added additional overflow checking.
// 2014/09/25 Martin D. Flynn
// -Added "toString(boolean inclPrefix)" to JSON object.
// ----------------------------------------------------------------------------
package org.opengts.util;
import java.util.*;
import java.io.IOException;
import java.io.InputStream;
public class JSON
{
// ------------------------------------------------------------------------
private static final boolean CASE_SENSITIVE = false;
private static boolean NameEquals(String n1, String n2)
{
if ((n1 == null) || (n2 == null)) {
return false;
} else
if (CASE_SENSITIVE) {
return n1.equals(n2);
} else {
return n1.equalsIgnoreCase(n2);
}
}
// ------------------------------------------------------------------------
private static final String INDENT = " ";
/**
*** Return indent spaces
**/
private static String indent(int count)
{
return StringTools.replicateString(INDENT,count);
}
// ------------------------------------------------------------------------
private static final char ESCAPE_CHAR = '\\';
/**
*** Converts the specified String to a JSON escaped value String.<br>
*** @param s The String to convert to a JSON encoded String
*** @return The JSON encoded String
**/
public static String escapeJSON(String s)
{
if (s != null) {
StringBuffer sb = new StringBuffer();
int len = s.length();
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
if (ch == ESCAPE_CHAR) {
sb.append(ESCAPE_CHAR).append(ESCAPE_CHAR);
} else
if (ch == '\n') {
sb.append(ESCAPE_CHAR).append('n');
} else
if (ch == '\r') {
sb.append(ESCAPE_CHAR).append('r');
} else
if (ch == '\t') {
sb.append(ESCAPE_CHAR).append('t');
} else
//if (ch == '\'') {
// sb.append(ESCAPE_CHAR).append('\''); <-- should not be escaped
//} else
if (ch == '\"') {
sb.append(ESCAPE_CHAR).append('\"');
} else
if ((ch >= 0x0020) && (ch <= 0x007e)) {
sb.append(ch);
} else {
// ignore character?
sb.append(ch);
}
}
return sb.toString();
} else {
return "";
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** JSON Parsing Context
**/
public static class JSONParsingContext
{
private int index = 0;
private int line = 1;
public JSONParsingContext() {
this.index = 0;
this.line = 1;
}
public int getIndex() {
return this.index;
}
public void incrementIndex(int val) {
this.index += val;
}
public void incrementIndex() {
this.index++;
}
public int getLine() {
return this.line;
}
public void incrementLine() {
this.line++;
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(this.line);
sb.append("/");
sb.append(this.index);
return sb.toString();
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
/**
*** JSON Parse Exception
**/
public static class JSONParsingException
extends Exception
{
private int index = 0;
private int line = 0;
public JSONParsingException(String msg, JSONParsingContext context) {
super(msg);
this.index = (context != null)? context.getIndex() : -1;
this.line = (context != null)? context.getLine() : -1;
}
public int getIndex() {
return this.index;
}
public int getLine() {
return this.line;
}
public String toString() { // JSON.JSONParsingException
String s = super.toString();
return s + " ["+this.line+"/"+this.index+"]";
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// JSON._Object
/**
*** JSON Object class
**/
public static class _Object
extends Vector<JSON._KeyValue>
{
private boolean formatIndent = true;
/**
*** Constructor
**/
public _Object() {
super();
}
/**
*** Constructor
**/
public _Object(Vector<JSON._KeyValue> list) {
this();
this.addAll(list);
}
/**
*** Constructor
**/
public _Object(JSON._KeyValue... kv) {
this();
if (kv != null) {
for (int i = 0; i < kv.length; i++) {
this.add(kv[i]);
}
}
}
// --------------------------------------
/**
*** Adds a key/value pair to this object
**/
public boolean addKeyValue(JSON._KeyValue kv) {
return super.add(kv);
}
public boolean add(JSON._KeyValue kv) {
return super.add(kv);
}
/**
*** Adds a key/value pair to this object
**/
public boolean addKeyValue(String key, String value) {
return this.add(new JSON._KeyValue(key, value));
}
/**
*** Adds a key/value pair to this object
**/
public boolean addKeyValue(String key, int value) {
return this.add(new JSON._KeyValue(key, value));
}
/**
*** Adds a key/value pair to this object
**/
public boolean addKeyValue(String key, long value) {
return this.add(new JSON._KeyValue(key, value));
}
/**
*** Adds a key/value pair to this object
**/
public boolean addKeyValue(String key, double value) {
return this.add(new JSON._KeyValue(key, value));
}
/**
*** Adds a key/value pair to this object
**/
public boolean addKeyValue(String key, boolean value) {
return this.add(new JSON._KeyValue(key, value));
}
/**
*** Adds a key/value pair to this object
**/
public boolean addKeyValue(String key, JSON._Array value) {
return this.add(new JSON._KeyValue(key, value));
}
/**
*** Adds a key/value pair to this object
**/
public boolean addKeyValue(String key, JSON._Object value) {
return this.add(new JSON._KeyValue(key, value));
}
/**
*** Adds a key/value pair to this object
**/
public boolean addKeyValue(String key, JSON._Value value) {
return this.add(new JSON._KeyValue(key, value));
}
// --------------------------------------
/**
*** Gets the number of key/value pairs in this object
**/
public int getKeyValueCount() {
return super.size();
}
/**
*** Gets the key/value pair at the specified index
**/
public JSON._KeyValue getKeyValueAt(int ndx) {
if ((ndx >= 0) && (ndx < this.size())) {
return this.get(ndx);
} else {
return null;
}
}
// --------------------------------------
/**
*** Gets the key/value pair for the specified name
**/
public JSON._KeyValue getKeyValue(String n) {
if (n != null) {
for (JSON._KeyValue kv : this) {
String kvn = kv.getKey();
if (JSON.NameEquals(n,kvn)) {
return kv;
}
}
}
return null;
}
/**
*** Gets the JSON._Value for the specified name
**/
public JSON._Value getValueForName(String n) {
JSON._KeyValue kv = this.getKeyValue(n);
return (kv != null)? kv.getValue() : null;
}
/**
*** Gets the JSON._Value for the specified name
**/
public JSON._Value getValueForName(String name[]) {
if (name != null) {
for (String n : name) {
JSON._Value jv = this.getValueForName(n);
if (jv != null) {
return jv;
}
}
}
return null;
}
// --------------------------------------
/**
*** Gets the JSON._Array for the specified name
**/
public JSON._Array getArrayForName(String name, JSON._Array dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getArrayValue(dft) : dft;
}
/**
*** Gets the JSON._Array for the specified name
**/
public JSON._Array getArrayForName(String name[], JSON._Array dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getArrayValue(dft) : dft;
}
// --------------------------------------
/**
*** Gets the JSON._Array for the specified name
**/
public String[] getStringArrayForName(String name, String dft[]) {
JSON._Value jv = this.getValueForName(name);
JSON._Array ar = (jv != null)? jv.getArrayValue(null) : null;
return (ar != null)? ar.getStringArray() : dft;
}
/**
*** Gets the JSON._Array for the specified name
**/
public String[] getStringArrayForName(String name[], String dft[]) {
JSON._Value jv = this.getValueForName(name);
JSON._Array ar = (jv != null)? jv.getArrayValue(null) : null;
return (ar != null)? ar.getStringArray() : dft;
}
// --------------------------------------
/**
*** Gets the JSON._Object value for the specified name
**/
public JSON._Object getObjectForName(String name, JSON._Object dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getObjectValue(dft) : dft;
}
/**
*** Gets the JSON._Object value for the specified name
**/
public JSON._Object getObjectForName(String name[], JSON._Object dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getObjectValue(dft) : dft;
}
// --------------------------------------
/**
*** Gets the String value for the specified name
**/
public String getStringForName(String name, String dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getStringValue(dft) : dft;
}
/**
*** Gets the String value for the specified name
**/
public String getStringForName(String name[], String dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getStringValue(dft) : dft;
}
// --------------------------------------
/**
*** Gets the Integer value for the specified name
**/
public int getIntForName(String name, int dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getIntValue(dft) : dft;
}
/**
*** Gets the Integer value for the specified name
**/
public int getIntForName(String name[], int dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getIntValue(dft) : dft;
}
// --------------------------------------
/**
*** Gets the Long value for the specified name
**/
public long getLongForName(String name, long dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getLongValue(dft) : dft;
}
/**
*** Gets the Long value for the specified name
**/
public long getLongForName(String name[], long dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getLongValue(dft) : dft;
}
// --------------------------------------
/**
*** Gets the Double value for the specified name
**/
public double getDoubleForName(String name, double dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getDoubleValue(dft) : dft;
}
/**
*** Gets the Double value for the specified name
**/
public double getDoubleForName(String name[], double dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getDoubleValue(dft) : dft;
}
// --------------------------------------
/**
*** Gets the String value for the specified name
**/
public boolean getBooleanForName(String name, boolean dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getBooleanValue(dft) : dft;
}
/**
*** Gets the String value for the specified name
**/
public boolean getBooleanForName(String name[], boolean dft) {
JSON._Value jv = this.getValueForName(name);
return (jv != null)? jv.getBooleanValue(dft) : dft;
}
// --------------------------------------
/**
*** Gets a list of all key names in this object
**/
public Collection<String> getKeyNames() {
Collection<String> keyList = new Vector<String>();
for (JSON._KeyValue kv : this) {
keyList.add(kv.getKey());
}
return keyList;
}
/**
*** Print object contents (for debug purposes only)
**/
public void debugDisplayObject(int level) {
String pfx0 = StringTools.replicateString(INDENT,level);
String pfx1 = StringTools.replicateString(INDENT,level+1);
for (String key : this.getKeyNames()) {
JSON._KeyValue kv = this.getKeyValue(key);
Object val = kv.getValue().getObjectValue();
Print.sysPrintln(pfx0 + key + " ==> " + StringTools.className(val));
if (val instanceof JSON._Object) {
JSON._Object obj = (JSON._Object)val;
obj.debugDisplayObject(level+1);
} else
if (val instanceof JSON._Array) {
JSON._Array array = (JSON._Array)val;
for (JSON._Value jv : array) {
Object av = jv.getObjectValue();
Print.sysPrintln(pfx1 + " ==> " + StringTools.className(av));
if (av instanceof JSON._Object) {
JSON._Object obj = (JSON._Object)av;
obj.debugDisplayObject(level+2);
}
}
}
}
}
// --------------------------------------
/**
*** Set format indent state
**/
public _Object setFormatIndent(boolean indent) {
this.formatIndent = indent;
return this;
}
/**
*** Write a String representation of this instance to the StringBuffer
**/
public StringBuffer toStringBuffer(int prefix, StringBuffer sb) {
if (sb == null) { sb = new StringBuffer(); }
boolean fullFormat = this.formatIndent && (prefix >= 0);
String pfx0 = fullFormat? JSON.indent(prefix) : "";
String pfx1 = fullFormat? JSON.indent(prefix+1) : "";
sb.append("{");
if (fullFormat) {
sb.append("\n");
}
if (this.size() > 0) {
int size = this.size();
for (int i = 0; i < size; i++) {
JSON._KeyValue kv = this.get(i);
sb.append(pfx1);
kv.toStringBuffer((fullFormat?(prefix+1):-1),sb);
if ((i + 1) < size) {
sb.append(",");
}
if (fullFormat) {
sb.append("\n");
}
}
}
sb.append(pfx0).append("}");
if (fullFormat && (prefix == 0)) {
sb.append("\n");
}
return sb;
}
/**
*** Returns a String representation of this instance
**/
public String toString() { // JSON._Object
return this.toStringBuffer(0,null).toString();
}
/**
*** Returns a String representation of this instance
**/
public String toString(boolean inclPrefix) { // JSON._Object
return this.toStringBuffer((inclPrefix?0:-1),null).toString();
}
}
// ------------------------------------------------------------------------
/**
*** Parse a JSON Comment from the specified String, starting at the
*** specified location
**/
public static String parse_Comment(String v, JSONParsingContext context)
throws JSONParsingException
{
if (context == null) { context = new JSONParsingContext(); }
int len = StringTools.length(v);
String val = null;
/* skip leading whitespace */
for (;context.getIndex() < len;) {
char ch = v.charAt(context.getIndex());
if (Character.isWhitespace(ch)) {
context.incrementIndex(); // consume space
if (ch == '\n') { context.incrementLine(); }
continue; // skip space
} else {
break;
}
}
/* next characters must be "/*" */
int startLine = context.getLine();
int startIndex = context.getIndex();
if ((startIndex + 2) >= len) {
throw new JSONParsingException("Overflow", context);
} else
if ((v.charAt(startIndex ) != '/') ||
(v.charAt(startIndex+1) != '*') ) {
throw new JSONParsingException("Invalid beginning of comment", context);
}
context.incrementIndex(2);
/* parse comment body */
StringBuffer comment = new StringBuffer();
commentParse:
for (;context.getIndex() < len;) {
char ch = v.charAt(context.getIndex());
if (Character.isWhitespace(ch)) {
context.incrementIndex(); // consume space
if (ch == '\n') { context.incrementLine(); }
comment.append(ch);
continue; // skip space
} else
if (ch == '*') {
context.incrementIndex();
int ndx = context.getIndex();
if (ndx >= len) {
throw new JSONParsingException("Overflow", context);
} else
if ((v.charAt(ndx) == '/')) {
context.incrementIndex(); // consume final '/'
break commentParse;
} else {
comment.append(ch);
}
continue;
} else {
comment.append(ch);
context.incrementIndex();
}
} // commentParse
val = comment.toString().trim();
/* return comment */
return val;
}
// ------------------------------------------------------------------------
/**
*** Parse a JSON Object from the specified String.
*** Does not return null.
**/
public static _Object parse_Object(String v)
throws JSONParsingException
{
return JSON.parse_Object(v,new JSONParsingContext());
}
/**
*** Parse a JSON Object from the specified String, starting at the
*** specified location.
*** Does not return null.
**/
public static _Object parse_Object(String v, JSONParsingContext context)
throws JSONParsingException
{
if (context == null) { context = new JSONParsingContext(); }
int len = StringTools.length(v);
JSON._Object obj = null;
boolean comp = false;
objectParse:
for (;context.getIndex() < len;) {
char ch = v.charAt(context.getIndex());
if (Character.isWhitespace(ch)) {
// -- skip whitespace
context.incrementIndex(); // consume space
if (ch == '\n') { context.incrementLine(); }
continue; // skip space
} else
if (ch == '/') {
// -- start of comment (non-standard JSON)
String comment = JSON.parse_Comment(v, context);
continue; // skip comment
} else
if (ch == '{') {
// -- start of object
if (obj != null) {
throw new JSONParsingException("Object already started", context);
}
context.incrementIndex();
obj = new JSON._Object();
} else
if (ch == '\"') {
// -- "key": VALUE
if (obj == null) {
throw new JSONParsingException("No start of Object", context);
}
JSON._KeyValue kv = JSON.parse_KeyValue(v, context);
if (kv == null) {
throw new JSONParsingException("Invalid KeyValue ...", context);
}
obj.add(kv);
} else
if (ch == ',') {
// -- ignore extraneous commas (non-standard JSON)
context.incrementIndex();
} else
if (ch == '}') {
// -- end of object
context.incrementIndex();
if (obj != null) {
comp = true; // iff Object is defined
}
break objectParse;
} else {
// -- invalid character
throw new JSONParsingException("Invalid JSON syntax ...", context);
}
} // objectParse
/* object completed? */
if (!comp || (obj == null)) {
throw new JSONParsingException("Incomplete Object", context);
}
/* return object */
return obj;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// JSON._KeyValue
/**
*** JSON Key/Value pair
**/
public static class _KeyValue
{
private String key = null;
private JSON._Value value = null;
/**
*** Constructor
**/
public _KeyValue(String key, JSON._Value value) {
this.key = key;
this.value = value;
}
/**
*** Constructor
**/
public _KeyValue(String key, String value) {
this.key = key;
this.value = new JSON._Value(value);
}
/**
*** Constructor
**/
public _KeyValue(String key, long value) {
this.key = key;
this.value = new JSON._Value(value);
}
/**
*** Constructor
**/
public _KeyValue(String key, double value) {
this.key = key;
this.value = new JSON._Value(value);
}
/**
*** Constructor
**/
public _KeyValue(String key, boolean value) {
this.key = key;
this.value = new JSON._Value(value);
}
/**
*** Constructor
**/
public _KeyValue(String key, JSON._Array value) {
this.key = key;
this.value = new JSON._Value(value);
}
/**
*** Constructor
**/
public _KeyValue(String key, JSON._Object value) {
this.key = key;
this.value = new JSON._Value(value);
}
/**
*** Gets the key of this key/value pair
**/
public String getKey() {
return this.key;
}
/**
*** Gets the value of this key/value pair
**/
public JSON._Value getValue() {
return this.value;
}
/**
*** Write a String representation of this instance to the StringBuffer
**/
public StringBuffer toStringBuffer(int prefix, StringBuffer sb) {
if (sb == null) { sb = new StringBuffer(); }
sb.append("\"").append(this.key).append("\"");
sb.append(":");
if (prefix >= 0) {
sb.append(" ");
}
if (this.value != null) {
this.value.toStringBuffer(prefix,sb);
} else {
sb.append("null");
}
return sb;
}
/**
*** Returns a String representation of this instance
**/
public String toString() { // JSON._KeyValue
return this.toStringBuffer(1,null).toString();
}
}
/**
*** Parse a Key/Value pair from the specified String at the specified location
**/
public static JSON._KeyValue parse_KeyValue(String v, JSONParsingContext context)
throws JSONParsingException
{
if (context == null) { context = new JSONParsingContext(); }
int len = StringTools.length(v);
JSON._KeyValue kv = null;
boolean comp = false;
String key = null;
boolean colon = false;
keyvalParse:
for (;context.getIndex() < len;) {
char ch = v.charAt(context.getIndex());
if (Character.isWhitespace(ch)) {
context.incrementIndex(); // consume space
if (ch == '\n') { context.incrementLine(); }
continue; // skip space
} else
if (ch == '/') {
String comment = JSON.parse_Comment(v, context);
continue; // skip comment
} else
if (!colon && (ch == '\"')) {
// Key
key = JSON.parse_String(v, context);
if (key == null) {
throw new JSONParsingException("Invalid key String", context);
}
} else
if (ch == ':') {
if (colon) {
throw new JSONParsingException("More than one ':'", context);
} else
if (key == null) {
throw new JSONParsingException("Key not defined", context);
}
context.incrementIndex();
colon = true;
} else {
// JSON._Value
JSON._Value val = JSON.parse_Value(v, context);
if (val == null) {
throw new JSONParsingException("Invalid value", context);
}
kv = new JSON._KeyValue(key,val);
comp = true;
break keyvalParse;
}
} // keyvalParse
/* key/value completed? */
if (!comp) {
throw new JSONParsingException("Incomplete Key/Value", context);
}
/* return key/value */
return kv; // may be null
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// JSON._Value
/**
*** JSON Value
**/
public static class _Value
{
private Object value = null;
/**
*** Constructor
**/
public _Value() {
this.value = null;
}
/**
*** Constructor
**/
public _Value(String v) {
this.value = v;
}
/**
*** Constructor
**/
public _Value(Integer v) {
this.value = (v != null)? new Long(v.longValue()) : null;
}
/**
*** Constructor
**/
public _Value(int v) {
this.value = new Long((long)v);
}
/**
*** Constructor
**/
public _Value(Long v) {
this.value = v;
}
/**
*** Constructor
**/
public _Value(long v) {
this.value = new Long(v);
}
/**
*** Constructor
**/
public _Value(Double v) {
this.value = v;
}
/**
*** Constructor
**/
public _Value(double v) {
this.value = new Double(v);
}
/**
*** Constructor
**/
public _Value(Boolean v) {
this.value = v;
}
/**
*** Constructor
**/
public _Value(boolean v) {
this.value = new Boolean(v);
}
/**
*** Constructor
**/
public _Value(JSON._Array v) {
this.value = v;
}
/**
*** Constructor
**/
public _Value(JSON._Object v) {
this.value = v;
}
// -----------------------------------------
/**
*** Gets the value
*** (may be null)
**/
public Object getObjectValue() {
return this.value;
}
// -----------------------------------------
/**
*** Returns true if this value represents a nul Object
**/
public boolean isNullValue() {
return (this.value == null);
}
// -----------------------------------------
/**
*** Returns true if this value represents a String
**/
public boolean isStringValue() {
return (this.value instanceof String);
}
/**
*** Gets the String representation of this value if the value type is one of
*** String, Number, or Boolean
**/
public String getStringValue(String dft) {
if (this.value instanceof String) {
return (String)this.value;
} else
if (this.value instanceof Number) {
return this.value.toString();
} else
if (this.value instanceof Boolean) {
return this.value.toString();
} else {
return dft;
}
}
// -----------------------------------------
/**
*** Returns true if this value represents an Integer
**/
public boolean isIntValue() {
return (this.value instanceof Integer);
}
/**
*** Gets the Integer representation of this value if the value type is one of
*** Number(intValue), String(parseInt), or Boolean('0' if false, '1' otherwise)
**/
public int getIntValue(int dft) {
if (this.value instanceof Number) {
return ((Number)this.value).intValue();
} else
if (this.value instanceof String) {
return StringTools.parseInt(this.value,dft);
} else
if (this.value instanceof Boolean) {
return ((Boolean)this.value).booleanValue()? 1 : 0;
} else {
return dft;
}
}
// -----------------------------------------
/**
*** Returns true if this value represents a Long
**/
public boolean isLongValue() {
return (this.value instanceof Long);
}
/**
*** Gets the Long representation of this value if the value type is one of
*** Number(longValue), String(parseLong), or Boolean('0' if false, '1' otherwise)
**/
public long getLongValue(long dft) {
if (this.value instanceof Number) {
return ((Number)this.value).longValue();
} else
if (this.value instanceof String) {
return StringTools.parseLong(this.value,dft);
} else
if (this.value instanceof Boolean) {
return ((Boolean)this.value).booleanValue()? 1L : 0L;
} else {
return dft;
}
}
// -----------------------------------------
/**
*** Returns true if this value represents a Double
**/
public boolean isDoubleValue() {
return (this.value instanceof Double);
}
/**
*** Gets the Double representation of this value if the value type is one of
*** Number(doubleValue), String(parseDouble), or Boolean('0.0' if false, '1.0' otherwise)
**/
public double getDoubleValue(double dft) {
if (this.value instanceof Number) {
return ((Number)this.value).doubleValue();
} else
if (this.value instanceof String) {
return StringTools.parseDouble(this.value,dft);
} else
if (this.value instanceof Boolean) {
return ((Boolean)this.value).booleanValue()? 1.0 : 0.0;
} else {
return dft;
}
}
// -----------------------------------------
/**
*** Returns true if this value represents a Boolean
**/
public boolean isBooleanValue() {
return (this.value instanceof Boolean);
}
/**
*** Gets the Boolean representation of this value if the value type is one of
*** Boolean(booleanValue), String(parseBoolean), or Number(false if '0', true otherwise)
**/
public boolean getBooleanValue(boolean dft) {
if (this.value instanceof Boolean) {
return ((Boolean)this.value).booleanValue();
} else
if (this.value instanceof String) {
return StringTools.parseBoolean(this.value,dft);
} else
if (this.value instanceof Number) {
return (((Number)this.value).longValue() != 0L)? true : false;
} else {
return dft;
}
}
// -----------------------------------------
/**
*** Returns true if this value represents a JSON._Array
**/
public boolean isArrayValue() {
return (this.value instanceof JSON._Array);
}
/**
*** Gets the JSON._Array value
**/
public JSON._Array getArrayValue(JSON._Array dft) {
if (this.value instanceof JSON._Array) {
return (JSON._Array)this.value;
} else {
return dft;
}
}
// -----------------------------------------
/**
*** Returns true if this value represents a JSON._Object
**/
public boolean isObjectValue() {
return (this.value instanceof JSON._Object);
}
/**
*** Gets the JSON._Object value
**/
public JSON._Object getObjectValue(JSON._Object dft) {
if (this.value instanceof JSON._Object) {
return (JSON._Object)this.value;
} else {
return dft;
}
}
// -----------------------------------------
/**
*** Returns the class of the value object
**/
public Class getValueClass() {
return (this.value != null)? this.value.getClass() : null;
}
/**
*** Write a String representation of this instance to the StringBuffer
**/
public StringBuffer toStringBuffer(int prefix, StringBuffer sb) {
if (sb == null) { sb = new StringBuffer(); }
if (this.value == null) {
sb.append("null");
} else
if (this.value instanceof String) {
sb.append("\"");
sb.append(JSON.escapeJSON((String)this.value));
sb.append("\"");
} else
if (this.value instanceof Number) {
sb.append(this.value.toString());
} else
if (this.value instanceof Boolean) {
sb.append(this.value.toString());
} else
if (this.value instanceof JSON._Object) {
((JSON._Object)this.value).toStringBuffer(prefix, sb);
} else
if (this.value instanceof JSON._Array) {
((JSON._Array)this.value).toStringBuffer(prefix, sb);
} else {
// ignore
}
return sb;
}
/**
*** Returns a String representation of this instance
**/
public String toString() { // JSON._Value
return this.toStringBuffer(0,null).toString();
}
}
/**
*** Parse a JSON Array from the specified String
**/
public static JSON._Value parse_Value(String v)
throws JSONParsingException
{
return JSON.parse_Value(v, new JSONParsingContext());
}
/**
*** Parse JSON Value
**/
public static JSON._Value parse_Value(String v, JSONParsingContext context)
throws JSONParsingException
{
if (context == null) { context = new JSONParsingContext(); }
int len = StringTools.length(v);
JSON._Value val = null;
boolean comp = false;
valueParse:
for (;context.getIndex() < len;) {
char ch = v.charAt(context.getIndex());
if (Character.isWhitespace(ch)) {
context.incrementIndex(); // consume space
if (ch == '\n') { context.incrementLine(); }
continue; // skip space
} else
if (ch == '/') {
String comment = JSON.parse_Comment(v, context);
continue; // skip comment
} else
if (ch == '\"') {
// parse String
String sval = JSON.parse_String(v, context);
if (sval == null) {
throw new JSONParsingException("Invalid String value", context);
} else {
val = new JSON._Value(sval);
}
comp = true;
break valueParse;
} else
if ((ch == '-') || (ch == '+') || Character.isDigit(ch)) {
// parse Number
Number num = JSON.parse_Number(v, context);
if (num == null) {
throw new JSONParsingException("Invalid Number value", context);
} else
if (num instanceof Double) {
val = new JSON._Value((Double)num);
} else
if (num instanceof Integer) {
val = new JSON._Value((Integer)num);
} else
if (num instanceof Long) {
val = new JSON._Value((Long)num);
} else {
throw new JSONParsingException("Unsupported Number type: " + StringTools.className(num), context);
}
comp = true;
break valueParse;
} else
if (ch == 't') {
// true
context.incrementIndex();
int ndx = context.getIndex();
if ((ndx + 2) >= len) {
throw new JSONParsingException("Overflow", context);
} else
if ((v.charAt(ndx ) == 'r') &&
(v.charAt(ndx+1) == 'u') &&
(v.charAt(ndx+2) == 'e') ) {
context.incrementIndex(3);
val = new JSON._Value(Boolean.TRUE);
} else {
throw new JSONParsingException("Invalid Boolean 'true'", context);
}
comp = true;
break valueParse;
} else
if (ch == 'f') {
// false
context.incrementIndex();
int ndx = context.getIndex();
if ((ndx + 3) >= len) {
throw new JSONParsingException("Overflow", context);
} else
if ((v.charAt(ndx ) == 'a') &&
(v.charAt(ndx+1) == 'l') &&
(v.charAt(ndx+2) == 's') &&
(v.charAt(ndx+3) == 'e') ) {
context.incrementIndex(4);
val = new JSON._Value(Boolean.FALSE);
} else {
throw new JSONParsingException("Invalid Boolean 'false'", context);
}
comp = true;
break valueParse;
} else
if (ch == 'n') {
// null
context.incrementIndex();
int ndx = context.getIndex();
if ((ndx + 2) >= len) {
throw new JSONParsingException("Overflow", context);
} else
if ((v.charAt(ndx ) == 'u') &&
(v.charAt(ndx+1) == 'l') &&
(v.charAt(ndx+2) == 'l') ) {
context.incrementIndex(3);
val = new JSON._Value((JSON._Object)null); // null object
} else {
throw new JSONParsingException("Invalid 'null'", context);
}
comp = true;
break valueParse;
} else
if (ch == '[') {
// JSON._Array
JSON._Array array = JSON.parse_Array(v, context);
if (array == null) {
throw new JSONParsingException("Invalid array", context);
}
val = new JSON._Value(array);
comp = true;
break valueParse;
} else
if (ch == '{') {
// JSON._Object
JSON._Object obj = JSON.parse_Object(v, context);
if (obj == null) {
throw new JSONParsingException("Invalid object", context);
}
val = new JSON._Value(obj);
comp = true;
break valueParse;
} else {
throw new JSONParsingException("Invalid character", context);
}
} // valueParse
/* value completed? */
if (!comp) {
throw new JSONParsingException("Incomplete Value", context);
}
/* return value */
return val; // may be null
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// JSON._Array
/**
*** JSON Array
**/
public static class _Array
extends Vector<JSON._Value>
{
private boolean formatIndent = true;
/**
*** Constructor
**/
public _Array() {
super();
}
/**
*** Constructor
*** An Array of other Values
**/
public _Array(JSON._Value... array) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
this.add(array[i]);
}
}
}
/**
*** Constructor
*** An Array of Strings
**/
public _Array(String... array) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
this.addValue(array[i]);
}
}
}
/**
*** Constructor
*** An Array of Longs
**/
public _Array(long... array) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
this.addValue(array[i]);
}
}
}
/**
*** Constructor
*** An Array of Doubles
**/
public _Array(double... array) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
this.addValue(array[i]);
}
}
}
/**
*** Constructor
*** An Array of Booleans
**/
public _Array(boolean... array) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
this.addValue(array[i]);
}
}
}
/**
*** Constructor
*** An Array of Objects
**/
public _Array(JSON._Object... array) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
this.addValue(array[i]);
}
}
}
/**
*** Constructor
*** An Array of other Arrays
**/
public _Array(JSON._Array... array) {
if (array != null) {
for (int i = 0; i < array.length; i++) {
this.addValue(array[i]);
}
}
}
/**
*** Constructor
**/
/*
private _Array(Collection list) {
if (list != null) {
for (Object val : list) {
if (val == null) {
this.addValue("");
} else
if (val instanceof JSON._Value) {
this.addValue((JSON._Value)val);
} else
if (val instanceof JSON._Object) {
this.addValue((JSON._Object)val);
} else
if (val instanceof JSON._Array) {
this.addValue((JSON._Array)val);
} else
if (val instanceof String) {
this.addValue((String)val);
} else
if (val instanceof Long) {
this.addValue(((Long)val).longValue());
} else
if (val instanceof Double) {
this.addValue(((Double)val).doubleValue());
} else
if (val instanceof Boolean) {
this.addValue(((Boolean)val).booleanValue());
} else {
Print.logInfo("Unrecognized data type: " + StringTools.className(val));
this.addValue(val.toString());
}
}
}
}
*/
// --------------------------------------
/**
*** Add a JSON._Value to this JSON._Array
**/
public boolean add(JSON._Value value) {
return super.add(value);
}
/**
*** Add a JSON._Value to this JSON._Array
**/
public boolean addValue(JSON._Value value) {
return this.add(value);
}
/**
*** Add a String to this JSON._Array
**/
public boolean addValue(String value) {
return this.add(new JSON._Value(value));
}
/**
*** Add a Long to this JSON._Array
**/
public boolean addValue(long value) {
return this.add(new JSON._Value(value));
}
/**
*** Add a Double to this JSON._Array
**/
public boolean addValue(double value) {
return this.add(new JSON._Value(value));
}
/**
*** Add a Boolean to this JSON._Array
**/
public boolean addValue(boolean value) {
return this.add(new JSON._Value(value));
}
/**
*** Add a JSON._Object to this JSON._Array
**/
public boolean addValue(JSON._Object value) {
return this.add(new JSON._Value(value));
}
/**
*** Add a JSON._Array to this JSON._Array
**/
public boolean addValue(JSON._Array value) {
return this.add(new JSON._Value(value));
}
// --------------------------------------
/**
*** Returns the JSON._Value at the specified index
**/
public JSON._Value getValueAt(int ndx) {
if ((ndx >= 0) && (ndx < this.size())) {
return this.get(ndx);
} else {
return null;
}
}
/**
*** Returns the JSON._Object value at the specified index
**/
public JSON._Object getObjectValueAt(int ndx, JSON._Object dft) {
if ((ndx >= 0) && (ndx < this.size())) {
JSON._Value jv = this.get(ndx);
return (jv != null)? jv.getObjectValue(dft) : dft;
} else {
return dft;
}
}
/**
*** Returns the JSON._Array value at the specified index
**/
public JSON._Array getArrayValueAt(int ndx, JSON._Array dft) {
if ((ndx >= 0) && (ndx < this.size())) {
JSON._Value jv = this.get(ndx);
return (jv != null)? jv.getArrayValue(dft) : dft;
} else {
return dft;
}
}
/**
*** Returns the String value at the specified index
**/
public String getStringValueAt(int ndx, String dft) {
if ((ndx >= 0) && (ndx < this.size())) {
JSON._Value jv = this.get(ndx);
return (jv != null)? jv.getStringValue(dft) : dft;
} else {
return dft;
}
}
/**
*** Returns the Integer value at the specified index
**/
public int getIntValueAt(int ndx, int dft) {
if ((ndx >= 0) && (ndx < this.size())) {
JSON._Value jv = this.get(ndx);
return (jv != null)? jv.getIntValue(dft) : dft;
} else {
return dft;
}
}
/**
*** Returns the Long value at the specified index
**/
public long getLongValueAt(int ndx, long dft) {
if ((ndx >= 0) && (ndx < this.size())) {
JSON._Value jv = this.get(ndx);
return (jv != null)? jv.getLongValue(dft) : dft;
} else {
return dft;
}
}
/**
*** Returns the Double value at the specified index
**/
public double getDoubleValueAt(int ndx, double dft) {
if ((ndx >= 0) && (ndx < this.size())) {
JSON._Value jv = this.get(ndx);
return (jv != null)? jv.getDoubleValue(dft) : dft;
} else {
return dft;
}
}
/**
*** Returns the Boolean value at the specified index
**/
public boolean getBooleanValueAt(int ndx, boolean dft) {
if ((ndx >= 0) && (ndx < this.size())) {
JSON._Value jv = this.get(ndx);
return (jv != null)? jv.getBooleanValue(dft) : dft;
} else {
return dft;
}
}
// --------------------------------------
/**
*** Returns a String array of values contained in this JSON Array
**/
public String[] getStringArray() {
String v[] = new String[this.size()];
for (int i = 0; i < v.length; i++) {
v[i] = this.getStringValueAt(i,"");
}
return v;
}
/**
*** Returns an int array of values contained in this JSON Array
**/
public int[] getIntArray() {
int v[] = new int[this.size()];
for (int i = 0; i < v.length; i++) {
v[i] = this.getIntValueAt(i,0);
}
return v;
}
/**
*** Returns a long array of values contained in this JSON Array
**/
public long[] getLongArray() {
long v[] = new long[this.size()];
for (int i = 0; i < v.length; i++) {
v[i] = this.getLongValueAt(i,0L);
}
return v;
}
/**
*** Returns a double array of values contained in this JSON Array
**/
public double[] getDoubleArray() {
double v[] = new double[this.size()];
for (int i = 0; i < v.length; i++) {
v[i] = this.getDoubleValueAt(i,0L);
}
return v;
}
// --------------------------------------
/**
*** Gets the number of items in this array
*** @return The number of items in this array
**/
public int size() {
return super.size();
}
/**
*** Returns true if this array is empty
*** @return True if this array is empty
**/
public boolean isEmpty() {
return super.isEmpty();
}
// --------------------------------------
/**
*** Set format indent state
**/
public _Array setFormatIndent(boolean indent) {
this.formatIndent = indent;
return this;
}
/**
*** Write a String representation of this instance to the StringBuffer
**/
public StringBuffer toStringBuffer(int prefix, StringBuffer sb) {
if (sb == null) { sb = new StringBuffer(); }
boolean fullFormat = this.formatIndent && (prefix >= 0);
String pfx0 = fullFormat? JSON.indent(prefix) : "";
String pfx1 = fullFormat? JSON.indent(prefix+1) : "";
sb.append("[");
if (fullFormat) {
sb.append("\n");
}
int size = this.size();
for (int i = 0; i < this.size(); i++) {
JSON._Value v = this.get(i);
sb.append(pfx1);
v.toStringBuffer((fullFormat?(prefix+1):-1), sb);
if ((i + 1) < size) {
sb.append(",");
}
if (fullFormat) {
sb.append("\n");
}
}
sb.append(pfx0).append("]");
return sb;
}
/**
*** Returns a String representation of this instance
**/
public String toString() { // JSON._Array
return this.toStringBuffer(1,null).toString();
}
}
/**
*** Parse a JSON Array from the specified String
**/
public static JSON._Array parse_Array(String v)
throws JSONParsingException
{
return JSON.parse_Array(v, new JSONParsingContext());
}
/**
*** Parse JSON Array from the specified String
**/
public static JSON._Array parse_Array(String v, JSONParsingContext context)
throws JSONParsingException
{
if (context == null) { context = new JSONParsingContext(); }
int len = StringTools.length(v);
JSON._Array array = null;
boolean comp = false;
arrayParse:
for (;context.getIndex() < len;) {
char ch = v.charAt(context.getIndex());
if (Character.isWhitespace(ch)) {
context.incrementIndex(); // consume space
if (ch == '\n') { context.incrementLine(); }
continue; // skip space
} else
if (ch == '/') {
String comment = JSON.parse_Comment(v, context);
continue; // skip comment
} else
if (ch == '[') {
if (array == null) {
context.incrementIndex();
array = new JSON._Array();
} else {
// array within array
JSON._Value val = JSON.parse_Value(v, context);
if (val == null) {
throw new JSONParsingException("Invalid Value", context);
}
array.add(val);
}
} else
if (ch == ',') {
// ignore item separators
// TODO: should insert a placeholder for unspecified values?
context.incrementIndex();
} else
if (ch == ']') {
// end of array
context.incrementIndex();
comp = true;
break arrayParse;
} else {
JSON._Value val = JSON.parse_Value(v, context);
if (val == null) {
throw new JSONParsingException("Invalid Value", context);
}
array.add(val);
}
}
/* array completed? */
if (!comp) {
throw new JSONParsingException("Incomplete Array", context);
}
/* return array */
return array;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// String
/**
*** Parse a JSON String
**/
public static String parse_String(String v, JSONParsingContext context)
throws JSONParsingException
{
if (context == null) { context = new JSONParsingContext(); }
int len = StringTools.length(v);
String val = null;
boolean comp = false;
stringParse:
for (;context.getIndex() < len;) {
char ch = v.charAt(context.getIndex());
if (Character.isWhitespace(ch)) {
context.incrementIndex(); // consume space
if (ch == '\n') { context.incrementLine(); }
continue; // skip space
} else
if (ch == '/') {
String comment = JSON.parse_Comment(v, context);
continue; // skip comment
} else
if (ch == '\"') {
// parse String
context.incrementIndex(); // consume initial quote
StringBuffer sb = new StringBuffer();
quoteParse:
for (;context.getIndex() < len;) {
ch = v.charAt(context.getIndex());
if (ch == '\\') {
context.incrementIndex(); // skip '\'
if (context.getIndex() >= len) {
throw new JSONParsingException("Overflow", context);
}
ch = v.charAt(context.getIndex());
context.incrementIndex(); // skip char
switch (ch) {
case '"' : sb.append('"' ); break;
case '\\': sb.append('\\'); break;
case '/' : sb.append('/' ); break;
case 'b' : sb.append('\b'); break;
case 'f' : sb.append('\f'); break;
case 'n' : sb.append('\n'); break;
case 'r' : sb.append('\r'); break;
case 't' : sb.append('\t'); break;
case 'u' : {
int ndx = context.getIndex();
if ((ndx + 4) >= len) {
throw new JSONParsingException("Overflow", context);
}
String hex = v.substring(ndx,ndx+4);
context.incrementIndex(4);
break;
}
default : sb.append(ch); break;
}
} else
if (ch == '\"') {
context.incrementIndex(); // consume final quote
comp = true;
break quoteParse; // we're done
} else {
sb.append(ch);
context.incrementIndex();
if (context.getIndex() >= len) {
throw new JSONParsingException("Overflow", context);
}
}
} // quoteParse
val = sb.toString();
break stringParse;
} else {
throw new JSONParsingException("Missing initial String quote", context);
}
} // stringParse
/* String completed? */
if (!comp) {
throw new JSONParsingException("Incomplete String", context);
}
/* return String */
return val; // may be null
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// Number
/**
*** Parse a JSON Number
**/
public static Number parse_Number(String v, JSONParsingContext context)
throws JSONParsingException
{
if (context == null) { context = new JSONParsingContext(); }
int len = StringTools.length(v);
Number val = null;
boolean comp = false;
numberParse:
for (;context.getIndex() < len;) {
char ch = v.charAt(context.getIndex());
if (Character.isWhitespace(ch)) {
context.incrementIndex(); // consume space
if (ch == '\n') { context.incrementLine(); }
continue; // skip space
} else
if (ch == '/') {
String comment = JSON.parse_Comment(v, context);
continue; // skip comment
} else
if ((ch == '-') || (ch == '+') || Character.isDigit(ch)) {
StringBuffer num = new StringBuffer();
num.append(ch);
context.incrementIndex();
int intDig = Character.isDigit(ch)? 1 : 0;
int frcDig = 0;
int expDig = 0;
boolean frcCh = false; // '.'
boolean esnCh = false; // '+'/'-'
boolean expCh = false; // 'e'/'E'
digitParse:
for (;context.getIndex() < len;) {
char d = v.charAt(context.getIndex());
if (Character.isDigit(d)) {
if (expCh) {
expDig++;
} else
if (frcCh) {
frcDig++;
} else {
intDig++;
}
num.append(d);
context.incrementIndex();
} else
if (d == '.') {
if (frcCh) {
// more than one '.'
throw new JSONParsingException("Invalid numeric value (multiple '.')", context);
} else
if (intDig == 0) {
// no digits before decimal
throw new JSONParsingException("Invalid numeric value (no digits before '.')", context);
}
frcCh = true;
num.append(d);
context.incrementIndex();
} else
if ((d == 'e') || (d == 'E')) {
if (frcCh && (frcDig == 0)) {
// no digits after decimal
throw new JSONParsingException("Invalid numeric value (no digits after '.')", context);
} else
if (expCh) {
// more than one 'E'
throw new JSONParsingException("Invalid numeric value (multiple 'E')", context);
}
expCh = true;
num.append(d);
context.incrementIndex();
} else
if ((d == '-') || (d == '+')) {
if (!expCh) {
// no 'E'
throw new JSONParsingException("Invalid numeric value (no 'E')", context);
} else
if (esnCh) {
// more than one '-/+'
throw new JSONParsingException("Invalid numeric value (more than one '+/-')", context);
}
esnCh = true;
num.append(d);
context.incrementIndex();
} else {
comp = true;
break digitParse; // first non-numeric character
}
} // digitParse
if (context.getIndex() >= len) {
throw new JSONParsingException("Overflow", context);
}
String numStr = num.toString();
if (frcCh || expCh) {
val = (Number)(new Double(StringTools.parseDouble(numStr,0.0)));
} else {
val = (Number)(new Long(StringTools.parseLong(numStr,0L)));
}
break numberParse;
} else {
throw new JSONParsingException("Missing initial Numeric +/-/0", context);
}
} // numberParse
/* number completed? */
if (!comp) {
throw new JSONParsingException("Incomplete Number", context);
}
/* return number */
return val; // may be null
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
private JSON._Object object = null;
/**
*** Constructor
**/
public JSON()
{
super();
}
/**
*** Constructor
**/
public JSON(JSON._Object obj)
{
this.object = obj;
}
/**
*** Constructor
**/
public JSON(String json)
throws JSONParsingException
{
this.object = JSON.parse_Object(json);
}
/**
*** Constructor
**/
public JSON(InputStream input)
throws JSONParsingException, IOException
{
String json = StringTools.toStringValue(FileTools.readStream(input));
this.object = JSON.parse_Object(json);
}
// ------------------------------------------------------------------------
/**
*** Returns true if an object is defined
**/
public boolean hasObject()
{
return (this.object != null);
}
/**
*** Gets the main JSON._Object
**/
public JSON._Object getObject()
{
return this.object;
}
/**
*** Sets the main JSON._Object
**/
public void setObject(JSON._Object obj)
{
this.object = obj;
}
// ------------------------------------------------------------------------
/**
*** Return a String representation of this instance
**/
public String toString() // JSON
{
if (this.object != null) {
return this.object.toString();
} else {
return "";
}
}
/**
*** Return a String representation of this instance
**/
public String toString(boolean inclPrefix) // JSON
{
if (this.object != null) {
return this.object.toString(inclPrefix);
} else {
return "";
}
}
/**
*** Print object contents (debug purposes only)
**/
public void debugDisplayObject()
{
if (this.object != null) {
this.object.debugDisplayObject(0);
} else {
Print.sysPrintln("n/a");
}
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
}
| {
"content_hash": "f6a7694c1b78e535e9255ace1af5757a",
"timestamp": "",
"source": "github",
"line_count": 2226,
"max_line_length": 118,
"avg_line_length": 31.96271338724169,
"alnum_prop": 0.42394130627275156,
"repo_name": "shafqatali404/OpenGTS_2.6.0",
"id": "16fba3fafa68d3e8e5707c665994540681bd20fc",
"size": "71149",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/org/opengts/util/JSON.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "17573"
},
{
"name": "CSS",
"bytes": "125062"
},
{
"name": "Java",
"bytes": "11912232"
},
{
"name": "JavaScript",
"bytes": "1642398"
},
{
"name": "Perl",
"bytes": "65030"
},
{
"name": "Shell",
"bytes": "69213"
}
],
"symlink_target": ""
} |
package listeners;
import commands.chat.WarframeAlerts;
import core.SSSS;
import core.StartArgumentHandler;
import core.UpdateClient;
import core.UpdateClient;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.hooks.ListenerAdapter;
import utils.Logger;
import utils.STATICS;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class ReadyListener extends ListenerAdapter {
static ReadyEvent readyEvent;
private static void handleStartArgs() {
String[] args = StartArgumentHandler.args;
if (args.length > 0) {
switch (args[0]) {
case "-restart":
for (Guild g : readyEvent.getJDA().getGuilds()) {
g.getDefaultChannel().sendMessage(
":ok_hand: Bot successfully restarted!"
).queue();
}
break;
case "-update":
for (Guild g : readyEvent.getJDA().getGuilds()) {
g.getDefaultChannel().sendMessage(
":ok_hand: Bot successfully updated to version v." + STATICS.VERSION + "!\n\n" +
"**Changelogs:** http://github.zekro.de/DiscordBot/blob/master/README.md#latest-changelogs\n" +
"Github Repository: http://github.zekro.de/DiscordBot"
).queue();
}
break;
}
}
}
@Override
public void onReady(ReadyEvent event) {
StringBuilder sb = new StringBuilder();
event.getJDA().getGuilds().forEach(guild -> sb.append("| - \"" + guild.getName() + "\" - {@" + guild.getOwner().getUser().getName() + "#" + guild.getOwner().getUser().getDiscriminator() + "} - [" + guild.getId() + "] \n"));
System.out.println(String.format(
"\n\n" +
"#------------------------------------------------------------------------- - - - - - - -\n" +
"| %s - v.%s (JDA: v.%s)\n" +
"#------------------------------------------------------------------------- - - - - - - -\n" +
"| Running on %s guilds: \n" +
"%s" +
"#------------------------------------------------------------------------- - - - - - - -\n\n",
Logger.Cyan + Logger.Bold + "zekroBot" + Logger.Reset, STATICS.VERSION, "3.3.1_276", event.getJDA().getGuilds().size(), sb.toString()));
if (STATICS.BOT_OWNER_ID == 0) {
Logger.ERROR(
"#######################################################\n" +
"# PLEASE INSERT YOUR DISCORD USER ID IN SETTINGS.TXT #\n" +
"# AS ENTRY 'BOT_OWNER_ID' TO SPECIFY THAT YOU ARE THE #\n" +
"# BOTS OWNER! #\n" +
"#######################################################"
);
}
commands.settings.Botmessage.setSupplyingMessage(event.getJDA());
WarframeAlerts.startTimer(event.getJDA());
readyEvent = event;
STATICS.lastRestart = new Date();
handleStartArgs();
if (!STATICS.enableWarframeAlerts && !System.getProperty("os.name").contains("Windows")) {
System.out.println("[INFO] System: " + System.getProperty("os.name") + " detected - enabled warframe alerts.");
STATICS.enableWarframeAlerts = true;
}
if (STATICS.autoUpdate)
new Timer().schedule(new TimerTask() {
@Override
public void run() {
UpdateClient.checkIfUpdate(event.getJDA());
}
}, 0, 60000);
commands.chat.Vote3.loadPolls(event.getJDA());
commands.chat.Counter.loadAll(event.getJDA());
commands.guildAdministration.Autochannel.load(event.getJDA());
commands.guildAdministration.Mute.load();
// commands.chat.Vote2.loadPolls(event.getJDA());
}
}
| {
"content_hash": "e38823fe4cdc1c6bdef8176870b3a415",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 232,
"avg_line_length": 37.49107142857143,
"alnum_prop": 0.4724934508216242,
"repo_name": "zekroTJA/DiscordBot",
"id": "1e55bc42517af9b099aace0e7107fa9109e7392a",
"size": "4199",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/listeners/ReadyListener.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "4302"
},
{
"name": "Java",
"bytes": "326009"
},
{
"name": "Python",
"bytes": "1085"
}
],
"symlink_target": ""
} |
<!-- HTML header for doxygen 1.8.8-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- For Mobile Devices -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<title>CubbyFlow: API/Python/Array Directory Reference</title>
<!--<link href="tabs.css" rel="stylesheet" type="text/css"/>-->
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="customdoxygen.css" rel="stylesheet" type="text/css"/>
<link href='https://fonts.googleapis.com/css?family=Roboto+Slab' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="jquery.smartmenus.bootstrap.css" rel="stylesheet">
<script type="text/javascript" src="jquery.smartmenus.js"></script>
<!-- SmartMenus jQuery Bootstrap Addon -->
<script type="text/javascript" src="jquery.smartmenus.bootstrap.js"></script>
<!-- SmartMenus jQuery plugin -->
</head>
<body>
<nav class="navbar navbar-default" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand">CubbyFlow v0.71</a>
</div>
</div>
</nav>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div class="content" id="content">
<div class="container">
<div class="row">
<div class="col-sm-12 panel " style="padding-bottom: 15px;">
<div style="margin-bottom: 15px;">
<!-- end header part --><!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_19ea4dbfe8f0e4681f60b9b97f7b5d11.html">API</a></li><li class="navelem"><a class="el" href="dir_64f1ee62b3de5469433693db05eb8ed9.html">Python</a></li><li class="navelem"><a class="el" href="dir_12d73286b28dd0b33381c604d4b33f4c.html">Array</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">Array Directory Reference</div> </div>
</div><!--header-->
<div class="contents">
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a>
Files</h2></td></tr>
<tr class="memitem:_a_p_i_2_python_2_array_2_array_view_8hpp"><td class="memItemLeft" align="right" valign="top">file  </td><td class="memItemRight" valign="bottom"><a class="el" href="_a_p_i_2_python_2_array_2_array_view_8hpp.html">ArrayView.hpp</a> <a href="_a_p_i_2_python_2_array_2_array_view_8hpp_source.html">[code]</a></td></tr>
<tr class="separator:"><td class="memSeparator" colspan="2"> </td></tr>
</table>
</div><!-- contents -->
<!-- HTML footer for doxygen 1.8.8-->
<!-- start footer part -->
</div>
</div>
</div>
</div>
</div>
<hr class="footer"/><address class="footer"><small>
Generated on Thu Jul 15 2021 02:18:16 for CubbyFlow by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
</body>
<script type="text/javascript" src="doxy-boot.js"></script>
</html>
| {
"content_hash": "baa29e9dcb6190958d158354de29d00b",
"timestamp": "",
"source": "github",
"line_count": 100,
"max_line_length": 340,
"avg_line_length": 49.29,
"alnum_prop": 0.6402921485088253,
"repo_name": "utilForever/CubbyFlow",
"id": "5689f69f648b8f3fa2664b94d5a63f0690083605",
"size": "4929",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "dir_12d73286b28dd0b33381c604d4b33f4c.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "474045"
},
{
"name": "C++",
"bytes": "5480071"
},
{
"name": "CMake",
"bytes": "30365"
},
{
"name": "CSS",
"bytes": "12372"
},
{
"name": "Dockerfile",
"bytes": "947"
},
{
"name": "HTML",
"bytes": "3296"
},
{
"name": "JavaScript",
"bytes": "70575"
},
{
"name": "Objective-C",
"bytes": "13594"
},
{
"name": "Python",
"bytes": "24346"
},
{
"name": "Shell",
"bytes": "2532"
}
],
"symlink_target": ""
} |
// o2zcdisc -- zeroconf/bonjour discovery for O2
//
// Roger B. Dannenberg
// Feb 2021
// This file is divided into sections:
// 0. Heading: #include's
// 1. Bonjour API implementation
// 2. avahi-client API implementation
// 3. Common functions
#ifndef O2_NO_ZEROCONF
/****************************/
/* SECTION 0: include files */
/****************************/
#include <ctype.h>
#include "o2internal.h"
#include "discovery.h"
#include "hostip.h"
#include "pathtree.h"
#include "o2zcdisc.h"
// check for len-char hex string
static bool check_hex(const char *addr, int len)
{
for (int i = 0; i < len; i++) {
char c = addr[i];
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) {
return false;
}
}
return true;
}
// check for valid name since we will try to use name as IP addresses
// returns true if format is valid. Also returns the udp_port number
// extracted from the end of name, and modifies name by padding with
// zeros after the tcp_port (erasing most of the field with udp_port)
// so that name, on return, is an O2string suitable for service lookup.
static bool is_valid_proc_name(char *name, int port,
char *internal_ip, int *udp_port)
{
if (!name) return false;
if (strlen(name) != 28) return false;
if (name[0] != '@') return false;
// must have 8 lower case hex chars starting at name[1] followed by ':'
if (!check_hex(name + 1, 8)) return false;
if (name[9] != ':') return false;
if (!check_hex(name + 10, 8)) return false;
if (name[18] != ':') return false;
// internal IP is copied to internal_ip
o2_strcpy(internal_ip, name + 10, 9);
// must have 4-digit hex tcp port number matching port
if (!check_hex(name + 19, 4)) return false;
int top = o2_hex_to_byte(name + 19);
int bot = o2_hex_to_byte(name + 21);
int tcp_port = (top << 8) + bot;
if (tcp_port != port) return false; // name must be consistent
if (name[23] != ':') return false;
// must find 4-digit hex udp port number
if (!check_hex(name + 24, 4)) return false;
top = o2_hex_to_byte(name + 24);
bot = o2_hex_to_byte(name + 26);
*udp_port = (top << 8) + bot;
// pad O2 name with zeros to a word boundary (only one zero needed)
name[23] = 0;
return true;
}
#ifdef USE_BONJOUR
/*****************************************/
/* SECTION 1: Bonjour API implementation */
/*****************************************/
// DNSServiceBrowse sets up a callback zc_browse_callback that gets
// names, but then we need to call DNSServiceResolve to get more
// information. Unfortunately, this is not synchronous and there's yet
// another callback, so we have to manage multiple DNSServiceResolve
// actions where we have an outstanding request, we hope to get
// a response, but there are multiple outcomes.
//
// To "harden" this discovery process, we need to worry about error codes
// and failure to receive callbacks.
// - DNSServiceRegister and DNSServiceBrowse errors, since they happen
// early, will simply shut down discovery. No real recovery here.
// - zc_register_callback and zc_browse_callback errors are reported, but
// since this is a callback that stays active, there is nothing to do
// but wait for the next callback.
// - DNSServiceResolve errors mean we will not be able to look up a name.
// We could try again every 1s.
// - zc_resolve_callback may never be called or may be called with an error,
// in which case it is ignored. If it fails, we should consider the
// DNSServiceResolve to have failed, shut down resolve_info, and call
// resolve() for the next pending name. If it succeeds, we should remove
// the name from resolve_pending, so let's just do a linear search to find
// the name.
// The logic is tricky: We keep all un-resolved names in resolve_pending.
// We want to resolve the list quickly, but sequentially to avoid opening
// a pile of TCP connections to the Bonjour/ZeroConf server. But if there
// is a failure, we want to retry every 1s. So we keep a marker with each
// name to indicate we have not yet tried to resolve.
// In addition, we keep a watchdog timer running that is scheduled for 1s
// after each DNSServiceResolve call (whether it fails or not). We use a
// sequence number so only the last scheduled watchdog event will do
// anything.
// If DNSServiceResolve fails, we move the failing name to the beginning
// of resolve_pending (so it will not be revisited until every other name
// has been revisited). Then we return after setting timer for 1s.
// If the watchdog with the current serial number wakes up, it means
// DNSServiceResolve was called 1s ago, and either it failed and we need to
// retry, or it succeeded but we never got a callback. If we did not get
// a callback, resolve_info is non-null and we should call close_socket().
// Then, we are ready for another attept at DNSServiceResolve.
// When the callback is called, we need to remove the name from
// resolve_pending, close the connection, and set resolve_info to NULL.
// Set to a new Bonjour_info instance to listen to a socket from
// DNSServiceResolve. Serves as a lock on resolving names: if non-null, then
// a resolve request is being processed, so do not start another one.
// Set to NULL when Bonjour_info socket is marked for closure. (It may take time
// to actually close the socket by later calling delete on Bonjour_info.)
static Bonjour_info *resolve_info = NULL;
static int watchdog_seq = 0; // sequence number to cancel watchdog callback
static int rtcount = 0;
typedef struct {
int seqno;
const char *name;
bool unresolved; // does resolve need to be called on this?
bool asap; // process as soon as possible (first time)
} resolve_type;
Vec<resolve_type> resolve_pending;
static void resolve();
Bonjour_info::Bonjour_info(DNSServiceRef sr) {
sd_ref = sr;
// install socket
info = new Fds_info(DNSServiceRefSockFD(sd_ref),
NET_TCP_CLIENT, 0, this);
info->read_type = READ_CUSTOM; // we handle everything
}
Bonjour_info::~Bonjour_info() {
// do some garbage collection: we use resolve_info to keep
// track of Zc_info created by DNSServiceResolve so that when
// we get the data we need from a callback, we can close the
// connection. But if the connection closes without the
// callback, we have a dangling pointer blocking further calls
// to discover processes indicated by resolve_pending.
// (Probably, Zc_info should be in the context pointer passed
// to DNSServiceResolve, but it's easier to call
// DNSServiceResolve first, then create Zc_info, which uses
// the socket returned by DNSServiceResolve.)
if (this == resolve_info) {
resolve_info = NULL;
}
DNSServiceRefDeallocate(sd_ref);
sd_ref = NULL;
}
O2err Bonjour_info::deliver(O2netmsg_ptr msg) {
// this is called when there is data from the Bonjour/Zeroconf server
// to be processed by the library: pass it on...
DNSServiceErrorType err;
err = DNSServiceProcessResult(sd_ref);
if (err) {
fprintf(stderr, "DNSServiceProcessResult returns %d, "
"ending O2 discovery\n", err);
return O2_FAIL;
}
return O2_SUCCESS;
}
void zc_resolve_callback(DNSServiceRef sd_ref, DNSServiceFlags flags,
uint32_t interface_index, DNSServiceErrorType err,
const char *fullname, const char *hosttarget,
uint16_t port, uint16_t txt_len,
const unsigned char *txt_record, void *context)
{
port = ntohs(port);
O2_DBz(printf("zc_resolve_callback err %d name %s hosttarget %s port %d"
" len %d context %p\n",
err, fullname, hosttarget, port, txt_len, context));
uint8_t proc_name_len;
const char *proc_name = (const char *) TXTRecordGetValuePtr(txt_len,
txt_record, "name", &proc_name_len);
char name[32];
char internal_ip[O2N_IP_LEN];
int udp_port = 0;
// names are fixed length -- reject if invalid:
if (!proc_name || proc_name_len != 28) {
goto no_discovery;
}
o2_strcpy(name, proc_name, proc_name_len + 1); // extra 1 for EOS
O2_DBz(printf("%s got a TXT field: name=%s\n", o2_debug_prefix, name));
{ // remove name from resolve_pending
int i;
bool found_it = false;
for (i = 0; i < resolve_pending.size(); i++) {
if (streql((const char *) context, resolve_pending[i].name)) {
if (resolve_pending[i].unresolved) {
// we must have tried to resolve, but then got a browse
// callback for the same name; maybe something changed,
// so we have to keep the name and resolve again later.
resolve_type rt = resolve_pending[i];
resolve_pending.erase(i); // move to first location
resolve_pending.insert(0, rt);
} else { // we got the info we need, so remove this name
// from the pending list.
O2_DBz(printf("%s zc_resolve_callback resolve_pending name"
"%s@%p freed seqno %d\n", o2_debug_prefix,
resolve_pending[i].name, resolve_pending[i].name,
resolve_pending[i].seqno));
O2_FREE((void *) resolve_pending[i].name);
resolve_pending.erase(i);
}
found_it = true;
break;
}
}
if (!found_it) {
O2_DBz(printf("zc_resolve_callback could not find this name %s\n"
" proc name: %s\n",
(char *) context, name));
}
}
if (!is_valid_proc_name(name, port, internal_ip, &udp_port)) {
goto no_discovery;
}
{ // check for compatible version number
int version;
uint8_t vers_num_len;
const char *vers_num = (const char *) TXTRecordGetValuePtr(txt_len,
txt_record, "vers", &vers_num_len);
O2_DBz(if (vers_num) {
printf("%s got a TXT field: vers=", o2_debug_prefix);
for (int i = 0; i < vers_num_len; i++) {
printf("%c", vers_num[i]); }
printf("\n"); });
if (!vers_num ||
(version = o2_parse_version(vers_num, vers_num_len)) == 0) {
goto no_discovery;
}
o2_discovered_a_remote_process_name(name, version, internal_ip,
port, udp_port, O2_DY_INFO);
} // fall through to clean up resolve_info...
no_discovery:
if (resolve_info) {
resolve_info->info->close_socket(true);
resolve_info = NULL;
} else {
O2_DBz(printf("zc_resolve_callback with null resolve_info\n"));
}
resolve(); // no-op if empty
}
void set_watchdog_timer()
{
o2_send_start();
o2_add_int32(++watchdog_seq);
O2message_ptr m = o2_message_finish(o2_local_time() + 1, "!_o2/dydog", true);
o2_schedule_msg(&o2_ltsched, m);
}
void resolve()
{
DNSServiceRef sd_ref;
DNSServiceErrorType err;
while (!resolve_info && resolve_pending.size() > 0) {
resolve_type rt = resolve_pending.last();
rt.unresolved = false; // since we are calling resolve on this name
const char *name = rt.name;
O2_DBz(printf("%s Setting up DNSServiceResolve name %s@%p at %g "
"seqno %d\n", o2_debug_prefix, name, name,
o2_local_time(), rt.seqno));
assert(name);
err = DNSServiceResolve(&sd_ref, 0, kDNSServiceInterfaceIndexAny, name,
"_o2proc._tcp.", "local", zc_resolve_callback,
(void *) name);
if (err) {
fprintf(stderr, "DNSServiceResolve returned %d for %s\n",
err, name);
} else { // create resolve_info
resolve_info = new Bonjour_info(sd_ref);
}
// move name to the beginning of the list
// (to be revisited after all others)
resolve_pending.pop_back(); // we've already copied to rt
resolve_pending.insert(0, rt);
set_watchdog_timer();
}
}
void zc_register_callback(DNSServiceRef sd_ref, DNSServiceFlags flags,
DNSServiceErrorType err, const char *name,
const char *regtype, const char *domain,
void *context)
{
O2_DBz(printf("%s zc_register_callback err %d registered %s as %s domain "
"%s\n", o2_debug_prefix, err, name, regtype, domain));
}
void resolve_watchdog(O2msg_data_ptr msg, const char *types,
O2arg_ptr *argv, int argc, const void *user_data)
{
if (argv[0]->i != watchdog_seq) {
return; // a newer timer is set; ignore this one
}
if (resolve_info) { // connection is still open, no response for 1s
resolve_info->info->close_socket(true); // this will clean up
resolve_info = NULL;
}
resolve(); // try again
}
static void rr_callback(DNSServiceRef sd_ref, DNSRecordRef record_ref,
DNSServiceFlags flags, DNSServiceErrorType err,
void *context)
{
O2_DBz(printf("rr_callback sd_ref %p record_ref %p flags %d err %d\n",
sd_ref, record_ref, flags, err));
}
static Bonjour_info *zc_register(const char *type_domain, const char *host,
int port, int text_end, const char *text)
{
DNSServiceRef sd_ref;
DNSServiceErrorType err =
DNSServiceRegister(&sd_ref, kDNSServiceInterfaceIndexAny, 0,
o2_ensemble_name, type_domain, NULL, host,
htons(port), text_end, text,
zc_register_callback, NULL);
if (err) {
fprintf(stderr, "DNSServiceRegister returned %d, "
"O2 discovery is not possible.\n", err);
return NULL;
}
O2_DBz(printf("%s Registered port %d with text:\n", o2_debug_prefix, port);
for (int i = 0; i < text_end; ) {
printf(" ");
for (int j = 0; j < text[i]; j++) printf("%c", text[i + 1 + j]);
printf("\n"); i += 1 + text[i]; });
// make a handler for the socket that was returned
return new Bonjour_info(sd_ref);
}
#ifdef WIN32
typedef unsigned long in_addr_t;
#endif
void o2_zc_register_record(int port)
{
char ipdot[O2N_IP_LEN];
o2_hex_to_dot(o2n_internal_ip, ipdot);
in_addr_t addr = inet_addr(ipdot);
char fullname[64];
o2_strcpy(fullname, o2_ensemble_name, 64);
int len = (int) strlen(fullname);
if (len > 63 - 6) {
return;
}
strcpy(fullname + len, ".local");
DNSServiceRef sd_ref;
DNSServiceErrorType err;
err = DNSServiceCreateConnection(&sd_ref);
if (err) {
return;
}
DNSRecordRef record_ref;
err = DNSServiceRegisterRecord(sd_ref, &record_ref,
kDNSServiceFlagsUnique, 0 /*kDNSServiceFlagsIncludeP2P*/, fullname,
kDNSServiceType_A, kDNSServiceClass_IN, sizeof(addr), &addr,
240, rr_callback, NULL);
if (err != kDNSServiceErr_NoError) {
fprintf(stderr, "Error: DNSServiceRegisterRecord failed.\n");
DNSServiceRefDeallocate(sd_ref);
}
Bonjour_info *zcr_info = zc_register("_http._tcp.", fullname,
port, 0, NULL);
if (zcr_info) {
new Bonjour_info(sd_ref);
} else {
DNSServiceRefDeallocate(sd_ref);
}
}
static void zc_browse_callback(DNSServiceRef sd_ref, DNSServiceFlags flags,
uint32_t interfaceIndex, DNSServiceErrorType err,
const char *name, const char *regtype,
const char *domain, void *context)
{
O2_DBz(printf("%s zc_browse_callback err %d flags %d name %s as %s domain "
"%s\n", o2_debug_prefix, err, flags, name, regtype, domain));
// match if ensemble name is a prefix of name, e.g. "ensname (2)"
if (!(flags & kDNSServiceFlagsAdd) ||
(strncmp(o2_ensemble_name, name, strlen(o2_ensemble_name)) != 0)) {
return; // do not resolve this name
}
resolve_type *rt;
for (int i = 0; i < resolve_pending.size(); i++) {
rt = &resolve_pending[i];
if (strcmp(name, rt->name) == 0) {
rt->unresolved = true; // resolve is already in progress; do it
O2_DBz(printf("%s zc_browse_callback name %s@%p already pending"
" seqno %d\n",
o2_debug_prefix, rt->name, rt->name, rt->seqno));
return; // again later -- maybe there's new info
}
} // we did not find the name in the pending list, so add it...
rt = resolve_pending.append_space(1);
rt->name = o2_heapify(name);
rt->seqno = ++rtcount;
O2_DBz(printf("%s zc_browse_callback rt->name gets %s@%p seqno %d\n",
o2_debug_prefix, rt->name, rt->name, rt->seqno));
rt->unresolved = true; // we need to resolve it
rt->asap = true;
resolve();
}
// Start discovery with zeroconf/bonjour ...
// Assumes we have an ensemble name and proc name with public IP
//
O2err o2_zcdisc_initialize()
{
// Publish a service with type _o2proc._tcp, name ensemblename
// and text record name=@xxxxxxxx:yyyyyyyy:zzzz
char text[80];
strcpy(text + 1, "name=");
int text_end = 6 + (int) strlen(o2_ctx->proc->key);
strcpy(text + 6, o2_ctx->proc->key); // proc->key is (currently) 24 bytes
// for discovery, we need udp port too, so append it after ':'
text[text_end++] = ':';
sprintf(text + text_end, "%04x", o2_ctx->proc->udp_address.get_port());
text_end += 4;
text[0] = text_end - 1; // text[0] (length) does not include itself
// now add vers=2.0.0
int vers_loc = text_end + 1;
strcpy(text + vers_loc, "vers=");
char *vers_num = text + vers_loc + 5;
o2_version(vers_num);
text_end = vers_loc + 5 + (int) strlen(vers_num);
text[vers_loc - 1] = text_end - vers_loc;
O2_DBz(printf("Setting up DNSServiceRegister\n"));
int port = o2_ctx->proc->fds_info->port;
Bonjour_info *zcreg =
zc_register("_o2proc._tcp.", NULL, port, text_end, text);
if (zcreg == NULL) {
return O2_FAIL;
}
O2_DBz(printf("%s Registered port %d with text:\n", o2_debug_prefix, port);
for (int i = 0; i < text_end; ) {
printf(" ");
for (int j = 0; j < text[i]; j++) printf("%c", text[i + 1 + j]);
printf("\n"); i += 1 + text[i]; });
// create a browser
DNSServiceRef sd_ref;
O2_DBz(printf("Setting up DNSServiceBrowse\n"));
DNSServiceErrorType err = DNSServiceBrowse(&sd_ref, 0,
kDNSServiceInterfaceIndexAny, "_o2proc._tcp.",
NULL, zc_browse_callback, NULL);
if (err) {
fprintf(stderr, "DNSServiceBrowse returned %d, "
"O2 discovery is not possible.\n", err);
delete zcreg;
return O2_FAIL;
}
// make a handler for the socket that was returned
new Bonjour_info(sd_ref);
o2_method_new_internal("/_o2/dydog", "i", &resolve_watchdog,
NULL, false, true);
return O2_SUCCESS;
}
void o2_zcdisc_finish()
{
for (int i = 0; i < resolve_pending.size(); i++) {
O2_DBz(printf("%s o2_zcdisc_finish resolve_pending name %s@%p seqno %d "
"freed\n",
o2_debug_prefix, resolve_pending[i].name,
resolve_pending[i].name, resolve_pending[i].seqno));
O2_FREE((void *) resolve_pending[i].name);
}
resolve_pending.finish();
}
#elif USE_AVAHI
/**********************************************/
/* SECTION 2: avahi-client API implementation */
/**********************************************/
#include <avahi-client/client.h>
#include <avahi-client/lookup.h>
#include <avahi-client/publish.h>
#include <avahi-common/alternative.h>
#include <avahi-common/simple-watch.h>
#include <avahi-common/malloc.h>
#include <avahi-common/error.h>
// note on naming: Avahi uses "avahi" prefix, so all of our
// avahi-related names in O2 use "zc".
static AvahiServiceBrowser *zc_sb = NULL;
static AvahiClient *zc_client = NULL; // global access to avahi-client API
// AvahiPoll structure so Avahi can watch sockets:
static AvahiSimplePoll *zc_poll = NULL;
// These globals keep everything we are allocating -- it's not stated
// in Avahi docs what happens to objects passed into it, so we'll
// free them ourselves if we are not explicitly told to free them by
// Avahi. If Avahi takes ownership and frees either _name or _text
// objects, we may end up freeing dangling pointers. Hopefully, this
// will be detected in testing and not released. Yikes... why isn't
// Avahi documented sufficiently for reliable use?
static AvahiEntryGroup *zc_group = NULL;
static AvahiEntryGroup *zc_http_group = NULL;
static char *zc_name = NULL;
static char *zc_http_name = NULL;
static int zc_http_port = 0;
static bool zc_running = false;
static O2err zc_create_services(AvahiClient *c);
// helper to deal with multiple free functions:
#define FREE_WITH(variable, free_function) \
if (variable) { \
free_function(variable); \
variable = NULL; \
}
void o2_zcdisc_finish()
{
O2_DBz(printf("%s o2_zcdisc_finish\n", o2_debug_prefix));
// (I think) these are freed by avahi_client_free later, so
// we remove the dangling pointers:
zc_group = NULL;
zc_http_group = NULL;
zc_http_port = 0;
FREE_WITH(zc_sb, avahi_service_browser_free);
FREE_WITH(zc_client, avahi_client_free);
FREE_WITH(zc_poll, avahi_simple_poll_free);
FREE_WITH(zc_name, avahi_free);
FREE_WITH(zc_http_name, avahi_free);
zc_running = false;
}
static void zc_resolve_callback(AvahiServiceResolver *r,
AVAHI_GCC_UNUSED AvahiIfIndex interface,
AVAHI_GCC_UNUSED AvahiProtocol protocol,
AvahiResolverEvent event,
const char *name, const char *type,
const char *domain, const char *host_name,
const AvahiAddress *address,
uint16_t port, AvahiStringList *txt,
AvahiLookupResultFlags flags,
AVAHI_GCC_UNUSED void* userdata)
{
assert(r);
/* Called whenever a service has been resolved successfully or timed out */
switch (event) {
case AVAHI_RESOLVER_FAILURE:
fprintf(stderr, "(Resolver) Failed to resolve service '%s' of "
"type '%s' in domain '%s': %s\n", name, type, domain,
avahi_strerror(avahi_client_errno(
avahi_service_resolver_get_client(r))));
break;
case AVAHI_RESOLVER_FOUND: {
char a[AVAHI_ADDRESS_STR_MAX], *t;
O2_DBz(printf("%s Avahi resolve service '%s' of type '%s' in "
"domain '%s':\n", o2_debug_prefix, name, type, domain));
avahi_address_snprint(a, sizeof(a), address);
char name[32];
char internal_ip[O2N_IP_LEN];
int udp_port = 0;
int version = 0;
name[0] = 0;
for (AvahiStringList *asl = txt; asl; asl = asl->next) {
O2_DBz(printf("resolve callback text: %s\n", asl->text));
if (strncmp((char *) asl->text, "name=", 5) == 0 &&
asl->size == 33) { // found "name="; proc name len is 28
o2_strcpy(name, (char *) asl->text + 5, 29); // includes EOS
O2_DBz(printf("%s got a TXT field name=%s\n",
o2_debug_prefix, name));
}
if (strncmp((char *) asl->text, "vers=", 5) == 0) {
O2_DBz(printf("%s got a TXT field: ", o2_debug_prefix);
for (int i = 0; i < asl->size; i++) {
printf("%c", asl->text[i]); }
printf("\n"));
version = o2_parse_version((char *) asl->text + 5,
asl->size - 5);
}
}
if (name[0] && version &&
is_valid_proc_name(name, port, internal_ip, &udp_port)) {
o2_discovered_a_remote_process_name(name, version, internal_ip,
port, udp_port, O2_DY_INFO);
}
}
}
avahi_service_resolver_free(r);
}
static void zc_browse_callback(AvahiServiceBrowser *b,
AvahiIfIndex interface,
AvahiProtocol protocol,
AvahiBrowserEvent event,
const char *name,
const char *type,
const char *domain,
AVAHI_GCC_UNUSED AvahiLookupResultFlags flags,
void* userdata)
{
AvahiClient *c = (AvahiClient *) userdata;
assert(b);
/* Called whenever a new services becomes available on the LAN or
is removed from the LAN */
switch (event) {
case AVAHI_BROWSER_FAILURE:
fprintf(stderr, "(Browser) %s\n", avahi_strerror(
avahi_client_errno(avahi_service_browser_get_client(b))));
o2_zcdisc_finish();
return;
case AVAHI_BROWSER_NEW:
O2_DBz(printf("%s (Avahi Browser) NEW: service '%s' of type '%s' "
"in domain '%s'\n", o2_debug_prefix, name, type, domain));
/* We ignore the returned resolver object. In the callback
function we free it. If the server is terminated before
the callback function is called the server will free
the resolver for us. */
if (!(avahi_service_resolver_new(c, interface, protocol, name,
type, domain, AVAHI_PROTO_UNSPEC, (AvahiLookupFlags) 0,
zc_resolve_callback, c)))
fprintf(stderr, "Failed to resolve service '%s': %s\n",
name, avahi_strerror(avahi_client_errno(c)));
break;
case AVAHI_BROWSER_REMOVE:
O2_DBz(printf("%s (Avahi Browser) REMOVE: service '%s' of type '%s'"
" in domain '%s'\n", o2_debug_prefix, name, type, domain));
break;
case AVAHI_BROWSER_ALL_FOR_NOW:
case AVAHI_BROWSER_CACHE_EXHAUSTED:
O2_DBz(printf("%s (Avahi Browser) %s\n", o2_debug_prefix,
event == AVAHI_BROWSER_CACHE_EXHAUSTED ?
"CACHE_EXHAUSTED" : "ALL_FOR_NOW"));
break;
}
}
static void entry_group_callback(AvahiEntryGroup *g,
AvahiEntryGroupState state,
AVAHI_GCC_UNUSED void *userdata)
{
//TODO remove: zc_group = g;
/* Called whenever the entry group state changes */
switch (state) {
case AVAHI_ENTRY_GROUP_ESTABLISHED :
/* The entry group has been established successfully */
O2_DBz(printf("%s (Avahi) Service '%s' successfully established.\n",
o2_debug_prefix, zc_name));
break;
case AVAHI_ENTRY_GROUP_COLLISION : {
char *n;
/* A service name collision with a remote service
* happened. Let's pick a new name */
n = avahi_alternative_service_name(zc_name);
avahi_free(zc_name);
zc_name = n;
O2_DBz(printf("%s (Avahi) Service name collision, renaming "
"service to '%s'\n", o2_debug_prefix, zc_name));
/* And recreate the services */
zc_create_services(avahi_entry_group_get_client(g));
break;
}
case AVAHI_ENTRY_GROUP_FAILURE :
fprintf(stderr, "Entry group failure: %s\n",
avahi_strerror(avahi_client_errno(
avahi_entry_group_get_client(g))));
/* Some kind of failure happened while we were registering
our services */
o2_zcdisc_finish();
break;
case AVAHI_ENTRY_GROUP_UNCOMMITED:
case AVAHI_ENTRY_GROUP_REGISTERING:
;
}
}
O2err zc_commit_group(AvahiClient *c, char **name,
AvahiEntryGroup **group, const char *type, int port,
const char *text1, const char *text2)
{
char *n;
int ret;
if (!*group) {
if (!(*group =
avahi_entry_group_new(c, entry_group_callback, NULL))) {
fprintf(stderr, "avahi_entry_group_new() failed: %s\n",
avahi_strerror(avahi_client_errno(c)));
goto fail;
}
}
/* If the group is empty (either because it was just created, or
* because it was reset previously, add our entries. */
if (avahi_entry_group_is_empty(*group)) {
// Publish a service with type, name, and text. Note that text1
// and/or text2 might be NULL. avahi_entry_group_add_service will
// ignore anything after NULL:
O2_DBz(printf("%s (Avahi) Adding service to group, name '%s' "
"type '%s'\n",
o2_debug_prefix, *name, type));
if ((ret = avahi_entry_group_add_service(*group, AVAHI_IF_UNSPEC,
AVAHI_PROTO_UNSPEC, (AvahiPublishFlags) 0,
*name, type, NULL, NULL, port, text1, text2, NULL)) < 0) {
if (ret == AVAHI_ERR_COLLISION)
goto collision;
fprintf(stderr, "Failed to add _o2proc._tcp service %s: %s\n",
*name, avahi_strerror(ret));
goto fail;
}
/* Tell the server to register the service */
if ((ret = avahi_entry_group_commit(*group)) < 0) {
fprintf(stderr, "Failed to commit entry group: %s\n",
avahi_strerror(ret));
goto fail;
}
} else {
O2_DBz(printf("Debug: avahi_entry_group_is_empty() returned false\n"));
}
return O2_SUCCESS;
collision:
/* A service name collision with a local service happened. Let's
* pick a new name */
n = avahi_alternative_service_name(*name);
avahi_free(*name);
*name = n;
O2_DBz(printf("%s (Avahi) Service name collision, renaming service to "
"'%s'\n", o2_debug_prefix, *name));
avahi_entry_group_reset(*group);
return zc_commit_group(c, name, group, type, port, text1, text2);
fail:
return O2_FAIL;
}
static O2err zc_create_services(AvahiClient *c)
{
int ret;
assert(c);
// and text record name=@xxxxxxxx:yyyyyyyy:zzzz
char name[64];
strcpy(name, "name=");
int name_end = 5 + strlen(o2_ctx->proc->key);
strcpy(name + 5, o2_ctx->proc->key); // proc->key is 24 bytes
O2_DBz(printf("zc_create_services proc->key %s\n", o2_ctx->proc->key));
// for discovery, we need udp port too, so append it after ':'
name[name_end++] = ':';
sprintf(name + name_end, "%04x", o2_ctx->proc->udp_address.get_port());
name_end += 4;
name[name_end] = 0;
char vers[64];
strcpy(vers, "vers=");
char *vers_num = vers + 5;
o2_version(vers_num);
return zc_commit_group(c, &zc_name, &zc_group, "_o2proc._tcp",
o2_ctx->proc->fds_info->port, name, vers);
}
static void zc_client_callback(AvahiClient *c, AvahiClientState state,
AVAHI_GCC_UNUSED void * userdata)
{
assert(c);
/* Called whenever the client or server state changes */
switch (state) {
case AVAHI_CLIENT_S_RUNNING:
/* The server has startup successfully and registered its host
* name on the network, so it's time to create our services */
zc_create_services(c);
break;
case AVAHI_CLIENT_FAILURE:
fprintf(stderr, "Avahi client failure: %s\n",
avahi_strerror(avahi_client_errno(c)));
o2_zcdisc_finish();
break;
case AVAHI_CLIENT_S_COLLISION:
/* Let's drop our registered services. When the server is back
* in AVAHI_SERVER_RUNNING state we will register them
* again with the new host name. */
case AVAHI_CLIENT_S_REGISTERING:
/* The server records are now being established. This
* might be caused by a host name change. We need to wait
* for our own records to register until the host name is
* properly established. */
if (zc_group)
avahi_entry_group_reset(zc_group);
break;
case AVAHI_CLIENT_CONNECTING:
;
}
}
#include <avahi-common/simple-watch.h>
// Start discovery with avahi-client API
// Assumes we have an ensemble name and proc name with public IP
//
O2err o2_zcdisc_initialize()
{
int error;
if (zc_running) {
return O2_ALREADY_RUNNING;
}
O2_DBz(printf("%s o2_zcdisc_initialize\n", o2_debug_prefix));
zc_running = true;
// need a copy because if there is a collision, zc_name is freed
zc_name = avahi_strdup(o2_ensemble_name);
// create poll object
if (!(zc_poll = avahi_simple_poll_new())) {
fprintf(stderr, "Avahi failed to create simple poll object.\n");
goto fail;
}
// create client
zc_client = avahi_client_new(avahi_simple_poll_get(zc_poll),
(AvahiClientFlags) 0,
&zc_client_callback, NULL, &error);
if (!zc_client) {
fprintf(stderr, "Avahi failed to create client: %s\n",
avahi_strerror(error));
goto fail;
}
// Create the service browser
if (!(zc_sb = avahi_service_browser_new(zc_client, AVAHI_IF_UNSPEC,
AVAHI_PROTO_UNSPEC, "_o2proc._tcp", NULL,
(AvahiLookupFlags) 0, zc_browse_callback, zc_client))) {
fprintf(stderr, "Avahi failed to create service browser: %s\n",
avahi_strerror(avahi_client_errno(zc_client)));
goto fail;
}
// register web server port
if (zc_http_port) {
o2_zc_register_record(zc_http_port);
}
return O2_SUCCESS;
fail:
o2_zcdisc_finish();
return O2_FAIL;
}
void o2_poll_avahi()
{
if (zc_poll && zc_running) {
int ret = avahi_simple_poll_iterate(zc_poll, 0);
if (ret == 1) {
zc_running = false;
O2_DBz(printf("o2_poll_avahi got quit from "
"avahi_simple_poll_iterate\n"));
} else if (ret < 0) {
zc_running = false;
fprintf(stderr, "Error: avahi_simple_poll_iterate returned %d\n",
ret);
}
}
}
void o2_zc_register_record(int port)
{
zc_http_port = port;
if (zc_running) {
char ipdot[O2N_IP_LEN];
o2_hex_to_dot(o2n_internal_ip, ipdot);
in_addr_t addr = inet_addr(ipdot);
char fullname[64];
o2_strcpy(fullname, o2_ensemble_name, 64);
int len = strlen(fullname);
if (len > 63 - 6) {
return;
}
strcpy(fullname + len, ".local");
if (zc_http_name) avahi_free(zc_http_name);
zc_http_name = avahi_strdup(o2_ensemble_name);
assert(zc_client);
zc_commit_group(zc_client, &zc_http_name, &zc_http_group,
"_http._tcp", port, NULL, NULL);
}
}
#endif
/*******************************/
/* SECTION 3: Common functions */
/*******************************/
#endif
| {
"content_hash": "958b2ef2820dcf07b73eb980e123e2be",
"timestamp": "",
"source": "github",
"line_count": 952,
"max_line_length": 81,
"avg_line_length": 38.24894957983193,
"alnum_prop": 0.5657320187845001,
"repo_name": "rbdannenberg/o2",
"id": "b2389e5d3a80da0f42bb4fe57655378feaaf70d5",
"size": "36413",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/o2zcdisc.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "310166"
},
{
"name": "C++",
"bytes": "1118891"
},
{
"name": "CMake",
"bytes": "17412"
},
{
"name": "HTML",
"bytes": "63817"
},
{
"name": "JavaScript",
"bytes": "24954"
},
{
"name": "Makefile",
"bytes": "2748"
},
{
"name": "Python",
"bytes": "31298"
},
{
"name": "Shell",
"bytes": "19344"
}
],
"symlink_target": ""
} |
package org.springframework.xd.demo.gemfire;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Resource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.xd.demo.gemfire.function.HashTagAnalyzerFunction;
import com.gemstone.gemfire.cache.Region;
/**
* A Driver to test the HashTagAnalyzer. This requires some set up
* The XD Gemfire Cache Server is configured and initialized, e.g., run ./install in this project's
* root directory. And start the XD cache server
*
* >cd $XD_HOME/gemfire
* >bin/gemfire-server config/twitter-demo.xml
*
* start xd_singlenode
* Create Deploy the test streams
*
* From the project root directory:
* >./tweetsetup
*
* If this has already been done, you can start the XD shell and
*
* >stream undeploy tweets
* >stream deploy tweets
*
* to repopulate the cache
*
* @author David Turansk
*
*/
@Component
public class HashTagAnalyzerDriver {
@Resource(name = "hashtags")
Region<?,?> hashtags;
//@Autowired
//HashTagAnalyzerExecutor hashTagAnalyzerExecutor;
/**
* @param args
*/
@SuppressWarnings("resource")
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/client-cache.xml");
HashTagAnalyzerDriver driver = context.getBean(HashTagAnalyzerDriver.class);
driver.run();
}
public void run() {
for (Object key: hashtags.keySetOnServer()) {
hashtags.get(key);
}
HashTagAnalyzerFunction fn =new HashTagAnalyzerFunction();
Map<String,Integer> map = fn.aggregateAssociatedHashTags(hashtags, "jobs");
for (Entry<String,Integer>entry: map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
System.out.println("\n============ raw counts:");
map = fn.getHashTagCounts(hashtags);
for (Entry<String,Integer>entry: map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
}
}
| {
"content_hash": "9f1f0501e680abb00722dbe7bd431bf3",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 102,
"avg_line_length": 27.12987012987013,
"alnum_prop": 0.7290569650550502,
"repo_name": "dturanski/SpringOne2013",
"id": "451784ea3b7bec640aff445815188ab596000069",
"size": "2695",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gemfire-demo/hashtag-analyzer/src/main/java/org/springframework/xd/demo/gemfire/HashTagAnalyzerDriver.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "97379"
},
{
"name": "Groovy",
"bytes": "4474"
},
{
"name": "Java",
"bytes": "27118"
},
{
"name": "JavaScript",
"bytes": "183425"
},
{
"name": "Shell",
"bytes": "7898"
}
],
"symlink_target": ""
} |
using Microsoft.Extensions.Hosting;
using System;
using Microsoft.AspNetCore.Builder;
namespace LionFire.Hosting
{
public static class WebApplicationBuilderExtensions
{
public static IHostBuilder LionFire(this WebApplicationBuilder webApplicationBuilder, Action<LionFireHostBuilder>? action = null, bool useDefaults = true)
=> webApplicationBuilder.Host.LionFire(action, useDefaults);
}
}
| {
"content_hash": "3692e77114fdb0b3b7f0723c6382385e",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 163,
"avg_line_length": 35.333333333333336,
"alnum_prop": 0.7712264150943396,
"repo_name": "lionfire/Core",
"id": "a69dd318fcbcf53cf531f95cef867fa34c1d2305",
"size": "426",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/LionFire.AspNetCore/Hosting/WebApplicationBuilderExtensions.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "25092"
},
{
"name": "C#",
"bytes": "6313364"
},
{
"name": "CSS",
"bytes": "279549"
},
{
"name": "Dockerfile",
"bytes": "156"
},
{
"name": "HTML",
"bytes": "56450"
},
{
"name": "JavaScript",
"bytes": "8816"
},
{
"name": "Smalltalk",
"bytes": "12"
},
{
"name": "Stylus",
"bytes": "1566"
},
{
"name": "Vue",
"bytes": "3053"
}
],
"symlink_target": ""
} |
module JacintheManagement
module Core
# command : interface between scripts and GUI
class Command
RLD_HELP = <<END_RLD_HELP
Cette commande permet de restaurer le schéma
de la base et toutes ses données, en les
reconstruisant à partir du dernier dump.
END_RLD_HELP
# @return [Command] total reset command
def self.jtr
new('jtr', 'Reset total de la base',
['Restaurer le schéma de la base',
'et toutes ses données',
'à partir du dernier dump total'],
-> { ResetDb.reset_and_load_data },
RLD_HELP)
end
RWD_HELP = <<END_RWD_HELP
Cette commande permet de restaurer le schéma
de la base et les données de configuration.
END_RWD_HELP
# @return [Command] partial reset command
def self.jpr
new('jpr', 'Reset structurel de la base',
['Restaurer le schéma de la base',
'et ses données de configuration',
'à partir du dernier dump partiel'],
-> { ResetDb.reset_without_data },
RWD_HELP)
end
CLONE_HELP = <<END_CLONE_HELP
Cette commande permet de créer un clone
de la bse Jacinthe, à partir du dernier dump.
END_CLONE_HELP
# @return [Command] total reset command
def self.clone
new('clone', 'Cloner la base',
['Créer un clone de la base',
'à partir du dernier dump total'],
-> { ResetDb.clone_db },
CLONE_HELP)
end
CRON_HELP = <<END_CRON_HELP
Cette commande permet de lancer le cron dans
la base.
END_CRON_HELP
# @return [Command] start the database cron
def self.cron
new('cron', 'Lancement du cron de JacintheD',
['Lancement du cron de JacintheD'],
-> { ResetDb.start_cron },
CRON_HELP)
end
CATA_HELP = <<END_CATA_HELP
Cette commande permet de restaurer le schéma
de la base catalogue et ses données de configuration.
END_CATA_HELP
# @return [Command] partial reset command
def self.crb
new('crb', 'Reset structurel du catalogue',
['Recréer de zéro',
'la base catalogue vide'],
-> { ResetCatalog.build_base },
CATA_HELP)
end
end
end
end
| {
"content_hash": "a3b7ca2cd617369ee0566b9c6bb30010",
"timestamp": "",
"source": "github",
"line_count": 78,
"max_line_length": 53,
"avg_line_length": 29.102564102564102,
"alnum_prop": 0.5973568281938326,
"repo_name": "badal/jacman-core",
"id": "62b85a7568da2172776e4a49dcefa0421f8fcab1",
"size": "2424",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/jacman/core/commands/commands_reset_db.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "76842"
},
{
"name": "SQLPL",
"bytes": "4333"
}
],
"symlink_target": ""
} |
"""
WSGI config for InStoKiloGram project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "InStoKiloGram.settings")
application = get_wsgi_application()
| {
"content_hash": "758396cf6b68a29f99cd57972491a9dd",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 78,
"avg_line_length": 25.25,
"alnum_prop": 0.7772277227722773,
"repo_name": "neewy/InStoKiloGram",
"id": "0bfbdf4ca17fe0221917e81a91e5443613da690f",
"size": "404",
"binary": false,
"copies": "1",
"ref": "refs/heads/development",
"path": "InStoKiloGram/wsgi.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "9448"
},
{
"name": "HTML",
"bytes": "45626"
},
{
"name": "Python",
"bytes": "71792"
},
{
"name": "Shell",
"bytes": "103"
}
],
"symlink_target": ""
} |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/metric_service.proto
package com.google.monitoring.v3;
public interface CreateMetricDescriptorRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.monitoring.v3.CreateMetricDescriptorRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* The project on which to execute the request. The format is
* `"projects/{project_id_or_number}"`.
* </pre>
*
* <code>optional string name = 3;</code>
*/
java.lang.String getName();
/**
* <pre>
* The project on which to execute the request. The format is
* `"projects/{project_id_or_number}"`.
* </pre>
*
* <code>optional string name = 3;</code>
*/
com.google.protobuf.ByteString
getNameBytes();
/**
* <pre>
* The new [custom metric](/monitoring/custom-metrics)
* descriptor.
* </pre>
*
* <code>optional .google.api.MetricDescriptor metric_descriptor = 2;</code>
*/
boolean hasMetricDescriptor();
/**
* <pre>
* The new [custom metric](/monitoring/custom-metrics)
* descriptor.
* </pre>
*
* <code>optional .google.api.MetricDescriptor metric_descriptor = 2;</code>
*/
com.google.api.MetricDescriptor getMetricDescriptor();
/**
* <pre>
* The new [custom metric](/monitoring/custom-metrics)
* descriptor.
* </pre>
*
* <code>optional .google.api.MetricDescriptor metric_descriptor = 2;</code>
*/
com.google.api.MetricDescriptorOrBuilder getMetricDescriptorOrBuilder();
}
| {
"content_hash": "5b6dd20885b8c5faeddda1b3f186d5f0",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 101,
"avg_line_length": 27.56140350877193,
"alnum_prop": 0.6645448758752387,
"repo_name": "landrito/api-client-staging",
"id": "9726fb34faf58b65e782c08dd75234fe2c7f5079",
"size": "1571",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "generated/java/proto-google-cloud-monitoring-v3/src/main/java/com/google/monitoring/v3/CreateMetricDescriptorRequestOrBuilder.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "2323502"
},
{
"name": "JavaScript",
"bytes": "755724"
},
{
"name": "PHP",
"bytes": "554950"
},
{
"name": "Protocol Buffer",
"bytes": "573244"
},
{
"name": "Python",
"bytes": "1395644"
},
{
"name": "Ruby",
"bytes": "580681"
},
{
"name": "Shell",
"bytes": "592"
}
],
"symlink_target": ""
} |
using System;
using UnityEngine;
using UnityEditor;
namespace UnityToolbag
{
[CustomEditor(typeof(SortingLayerExposed))]
public class SortingLayerExposedEditor : Editor
{
public override void OnInspectorGUI()
{
// Get the renderer from the target object
var renderer = (target as SortingLayerExposed).gameObject.GetComponent<Renderer>();
// If there is no renderer, we can't do anything
if (!renderer) {
EditorGUILayout.HelpBox("SortingLayerExposed must be added to a game object that has a renderer.", MessageType.Error);
return;
}
var sortingLayerNames = SortingLayerHelper.sortingLayerNames;
// If we have the sorting layers array, we can make a nice dropdown. For stability's sake, if the array is null
// we just use our old logic. This makes sure the script works in some fashion even if Unity changes the name of
// that internal field we reflected.
if (sortingLayerNames != null) {
// Look up the layer name using the current layer ID
string oldName = SortingLayerHelper.GetSortingLayerNameFromID(renderer.sortingLayerID);
// Use the name to look up our array index into the names list
int oldLayerIndex = Array.IndexOf(sortingLayerNames, oldName);
// Show the popup for the names
int newLayerIndex = EditorGUILayout.Popup("Sorting Layer", oldLayerIndex, sortingLayerNames);
// If the index changes, look up the ID for the new index to store as the new ID
if (newLayerIndex != oldLayerIndex) {
Undo.RecordObject(renderer, "Edit Sorting Layer");
renderer.sortingLayerID = SortingLayerHelper.GetSortingLayerIDForIndex(newLayerIndex);
EditorUtility.SetDirty(renderer);
}
}
else {
// Expose the sorting layer name
string newSortingLayerName = EditorGUILayout.TextField("Sorting Layer Name", renderer.sortingLayerName);
if (newSortingLayerName != renderer.sortingLayerName) {
Undo.RecordObject(renderer, "Edit Sorting Layer Name");
renderer.sortingLayerName = newSortingLayerName;
EditorUtility.SetDirty(renderer);
}
// Expose the sorting layer ID
int newSortingLayerId = EditorGUILayout.IntField("Sorting Layer ID", renderer.sortingLayerID);
if (newSortingLayerId != renderer.sortingLayerID) {
Undo.RecordObject(renderer, "Edit Sorting Layer ID");
renderer.sortingLayerID = newSortingLayerId;
EditorUtility.SetDirty(renderer);
}
}
// Expose the manual sorting order
int newSortingLayerOrder = EditorGUILayout.IntField("Sorting Layer Order", renderer.sortingOrder);
if (newSortingLayerOrder != renderer.sortingOrder) {
Undo.RecordObject(renderer, "Edit Sorting Order");
renderer.sortingOrder = newSortingLayerOrder;
EditorUtility.SetDirty(renderer);
}
}
}
}
| {
"content_hash": "36f5df5b2436a40db744e633f480e0e9",
"timestamp": "",
"source": "github",
"line_count": 73,
"max_line_length": 134,
"avg_line_length": 45.87671232876713,
"alnum_prop": 0.6109286354135562,
"repo_name": "Banbury/UnitySpritesAndBones",
"id": "725b89d2af24ef4e7b50ead3503ad7c507481af2",
"size": "4278",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Assets/SpritesAndBones/Scripts/Editor/SortLayerExposedEditor.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1337856"
},
{
"name": "ShaderLab",
"bytes": "2988"
}
],
"symlink_target": ""
} |
var Student = Object.create({
init: function (firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.fullname = function () {
return this.firstName + ' ' + this.lastName;
};
return this;
}
});
var students = [
Object.create(Student).init('Doncho', 'Minkov'),
Object.create(Student).init('Nikolay', 'Kostov'),
Object.create(Student).init('Aneliya', 'Kostov'),
Object.create(Student).init('Aneliya', 'Stoyanova'),
Object.create(Student).init('Ivaylo', 'Kenov'),
Object.create(Student).init('Todor', 'Stoyanov')
];
var students = [{
firstName: 'Doncho',
lastName: 'Minkov'
}, {
firstName: 'Nikolay',
lastName: 'Kostov'
}, {
firstName: 'Ivaylo',
lastName: 'Kenov'
}];
function solve() {
return function (students) {
//var _ = require('./lib/underscore-min.js');
_.chain(students)
.each(function (student, index, collection) {
student.fullname = function () {
return this.firstName + ' ' + this.lastName;
}
})
.filter(function (student) {
return student.firstName.toLowerCase() < student.lastName.toLowerCase();
})
.sortBy(function (student, index, collection) {
return student.fullname().toLowerCase();
})
.reverse()
.each(function (student, index, collection) {
console.log(student.fullname());
});
};
}
module.exports = solve; | {
"content_hash": "43ae5f1daa2ac6a452b2eb83307cfc2b",
"timestamp": "",
"source": "github",
"line_count": 57,
"max_line_length": 88,
"avg_line_length": 28.05263157894737,
"alnum_prop": 0.5472170106316447,
"repo_name": "kaizer04/Telerik-Academy-2013-2014",
"id": "d5ad5bd9c4df902bb9f6444c31955a0b17b3c040",
"size": "1601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "JS Applications/JS-Apps-Dive-into-Underscore-Homework/JS-Apps-Dive-into-Underscore-Homework/task1 - Copy.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "120044"
},
{
"name": "Batchfile",
"bytes": "4176"
},
{
"name": "C#",
"bytes": "4193228"
},
{
"name": "CSS",
"bytes": "238134"
},
{
"name": "CoffeeScript",
"bytes": "11643"
},
{
"name": "HTML",
"bytes": "371739"
},
{
"name": "Harbour",
"bytes": "724"
},
{
"name": "JavaScript",
"bytes": "2993743"
},
{
"name": "Smalltalk",
"bytes": "2556"
},
{
"name": "Visual Basic",
"bytes": "9387"
}
],
"symlink_target": ""
} |
package ivansteklow.vanillaex.client.gui;
import java.util.ArrayList;
import java.util.List;
import ivansteklow.vanillaex.client.gui.ProgressBar.ProgressBarDirection;
import ivansteklow.vanillaex.container.ContainerBlockBreaker;
import ivansteklow.vanillaex.init.Refs;
import ivansteklow.vanillaex.network.PacketGetWorker;
import ivansteklow.vanillaex.network.PacketHandler;
import ivansteklow.vanillaex.tileentities.TileEntityBlockBreaker;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextFormatting;
import net.minecraftforge.items.CapabilityItemHandler;
/**
* Gui class for Block Breaker (Well)
*
* @author IvanSteklow
*
*/
public class GuiBlockBreaker extends GuiContainer {
public static final ResourceLocation TEXTURE = new ResourceLocation(Refs.MOD_ID,
"textures/gui/container/blockbreaker.png");
private TileEntityBlockBreaker te;
private IInventory playerInv;
private int chiptype;
public static int cooldown, maxCooldown = 0;
public static int sync = 0;
private ProgressBar progressBar;
public GuiBlockBreaker(IInventory playerInv, TileEntityBlockBreaker te, int Chiptype) {
super(new ContainerBlockBreaker(playerInv, te));
this.xSize = 176;
this.ySize = 166;
this.te = te;
this.playerInv = playerInv;
this.chiptype = Chiptype;
this.progressBar = new ProgressBar(TEXTURE, ProgressBarDirection.LEFT_TO_RIGHT, 14, 14, 135, 36, 176, 0);
}
@Override
protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) {
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.getTextureManager().bindTexture(TEXTURE);
this.drawTexturedModalRect(this.guiLeft, this.guiTop, 0, 0, this.xSize, this.ySize);
}
@Override
protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) {
String s;
if (chiptype == 0) {
s = I18n.format("container.blockbreaker_basic");
} else if (chiptype == 1) {
s = I18n.format("container.blockbreaker_advanced");
} else {
s = I18n.format("container.blockbreaker");
}
this.mc.fontRendererObj.drawString(s, this.xSize / 2 - this.mc.fontRendererObj.getStringWidth(s) / 2, 6,
4210752);
this.mc.fontRendererObj.drawString(this.playerInv.getDisplayName().getFormattedText(), 8, 72, 4210752);
this.progressBar.setMin(cooldown).setMax(maxCooldown);
this.progressBar.draw(this.mc);
int actualMouseX = mouseX - ((this.width - this.xSize) / 2);
int actualMouseY = mouseY - ((this.height - this.ySize) / 2);
if (actualMouseX >= 134 && actualMouseX <= 149 && actualMouseY >= 17 && actualMouseY <= 32
&& te.getCapability(CapabilityItemHandler.ITEM_HANDLER_CAPABILITY, null)
.getStackInSlot(9) == ItemStack.EMPTY) {
List<String> text = new ArrayList<String>();
text.add(TextFormatting.GRAY + I18n.format("gui.blockbreaker.enchantedbook.tooltip"));
this.drawHoveringText(text, actualMouseX, actualMouseY);
}
sync++;
sync %= 10;
if (sync == 0)
PacketHandler.NETWORKINSTANCE
.sendToServer(new PacketGetWorker(this.te.getPos(), this.mc.player.getAdjustedHorizontalFacing(),
"ivansteklow.vanillaex.client.gui.GuiBlockBreaker", "cooldown", "maxCooldown"));
}
}
| {
"content_hash": "b9ca03765016186e5d18c67fe5965288",
"timestamp": "",
"source": "github",
"line_count": 99,
"max_line_length": 107,
"avg_line_length": 34.42424242424242,
"alnum_prop": 0.7588028169014085,
"repo_name": "IvanSteklow/VanillaExtras",
"id": "a8f272e83c11ce132b91255bda449c615f130b4f",
"size": "3498",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/ivansteklow/vanillaex/client/gui/GuiBlockBreaker.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "75963"
}
],
"symlink_target": ""
} |
<html>
<head>
<title>Demo</title>
<link rel="stylesheet" href="portfoliobox.css">
<head>
<body>
<div id="portfoliobox" style="width:400px;height:400px;">
<div class="row">
<div id="tile1" class="tile tile-dark anim anim1">
<div class="tile-logo">
<img src="demo/Github.png" />
</div>
<div class="tile-body">
<h3>Github</h3>
<img src="demo/minus.png" class="tile-exit"/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut</p>
</div>
</div>
<div id="tile2" class="tile tile-medium anim anim2">
<div class="tile-logo">
<img src="demo/Github.png" />
</div>
<div class="tile-body">
<h3>Github</h3>
<img src="demo/minus.png" class="tile-exit"/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut</p>
</div>
</div>
<div id="tile3" class="tile tile-light anim anim3">
<div class="tile-logo">
<img src="demo/Github.png" />
</div>
<div class="tile-body">
<h3>Github</h3>
<img src="demo/minus.png" class="tile-exit"/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut</p>
</div>
</div>
</div>
<div class="row">
<div id="tile4" class="tile tile-light anim anim3">
<div class="tile-logo">
<img src="demo/Github.png" />
</div>
<div class="tile-body">
<h3>Github</h3>
<img src="demo/minus.png" class="tile-exit"/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut</p>
</div>
</div>
<div id="tile5" class="tile tile-dark anim anim1">
<div class="tile-logo">
<img src="demo/Github.png" />
</div>
<div class="tile-body">
<h3>Github</h3>
<img src="demo/minus.png" class="tile-exit"/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut</p>
</div>
</div>
<div id="tile6" class="tile tile-medium anim anim2">
<div class="tile-logo">
<img src="demo/Github.png" />
</div>
<div class="tile-body">
<h3>Github</h3>
<img src="demo/minus.png" class="tile-exit"/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut</p>
</div>
</div>
</div>
<div class="row">
<div id="tile7" class="tile tile-medium anim anim2">
<div class="tile-logo">
<img src="demo/Github.png" />
</div>
<div class="tile-body">
<h3>Github</h3>
<img src="demo/minus.png" class="tile-exit"/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut</p>
</div>
</div>
<div id="tile8" class="tile tile-light anim anim3">
<div class="tile-logo">
<img src="demo/Github.png" />
</div>
<div class="tile-body">
<h3>Github</h3>
<img src="demo/minus.png" class="tile-exit"/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut</p>
</div>
</div>
<div id="tile9" class="tile tile-dark anim anim1">
<div class="tile-logo">
<img src="demo/Github.png" />
</div>
<div class="tile-body">
<h3>Github</h3>
<img src="demo/minus.png" class="tile-exit"/>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut</p>
</div>
</div>
</div>
</div>
<script src="../bower_components/jquery/dist/jquery.min.js"></script>
<script src="portfoliobox.js"></script>
<script>
$("portfoliobox").portfoliobox();
</script>
</body>
</html> | {
"content_hash": "d39bf558a0df2f32e1e0bde4893c043f",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 147,
"avg_line_length": 46.95575221238938,
"alnum_prop": 0.42046739540143235,
"repo_name": "nikrich/infobox",
"id": "765fa207d4edb0f08b05e925b157fc5931eea786",
"size": "5306",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/demo.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3565"
},
{
"name": "JavaScript",
"bytes": "7032"
}
],
"symlink_target": ""
} |
import java.util.LinkedList;
// Only 10 instances of stocks should be here. Each stock has an arraylist of StockNodes that is an instance of time for that stock
class Stock {
public String ticker;
private int maxLinkedListSize;
public LinkedList<StockNode> stockTimes = new LinkedList<StockNode>();
public Stock (String ticker, double netWorth, double dividend, double volatility, double maxBid, double minAsk) {
this.ticker = ticker;
this.maxLinkedListSize = 100;//(VisualizationBase.STOCK_HISTORY_TIME * (1000 / VisualizationBase.STOCK_CHECK_INTERVAL)) / 1000;
StockNode initialStockNode = new StockNode(netWorth, dividend, volatility, maxBid, minAsk, 0, System.currentTimeMillis());
addNode(initialStockNode);
}
// This method pushes elements to the LinkedList and removes them from the end if they are larger than
// the max size based on the number of polls per second, and the time history we want to keep.
// The first element is the oldest, the last is the newest.
private boolean addNode(StockNode stockNode) {
if (stockTimes.size() > maxLinkedListSize) {
stockTimes.removeFirst();
}
return stockTimes.add(stockNode);
}
boolean addNode(double netWorth, double dividend, double volatility, double maxBid, double minAsk) {
if (stockTimes.size() > maxLinkedListSize) {
stockTimes.removeFirst();
}
long currentTime = System.currentTimeMillis();
double velocity = (netWorth - stockTimes.getLast().netWorth) / (currentTime - stockTimes.getLast().currentTime);
//System.out.println(currentTime - stockTimes.getLast().currentTime);
StockNode newStockNode = new StockNode(netWorth, dividend, volatility, maxBid, minAsk, velocity, currentTime);
return stockTimes.add(newStockNode);
}
double getCurrentNetWorth() {
if (stockTimes.isEmpty()) {
return 0;
}
return stockTimes.getLast().netWorth;
}
double getCurrentMaxBid() {
if (stockTimes.isEmpty()) {
return 0;
}
return stockTimes.getLast().maxBid;
}
double getCurrentMinAsk() {
if (stockTimes.isEmpty()) {
return 0;
}
return stockTimes.getLast().minAsk;
}
double getCurrentDividend() {
if (stockTimes.isEmpty()) {
return 0;
}
return stockTimes.getLast().dividend;
}
double getCurrentVelocity() {
if (stockTimes.isEmpty()) {
return 0;
}
return stockTimes.getLast().velocity;
}
double getCurrentVolatility() {
if (stockTimes.isEmpty()) {
return 0;
}
return stockTimes.getLast().volatility;
}
// Need methods for the
void updateMaxLinkedListSize() {
this.maxLinkedListSize = VisualizationBase.STOCK_HISTORY_TIME * (1000 / VisualizationBase.STOCK_CHECK_INTERVAL) / 1000;
}
} | {
"content_hash": "b02056eb1f701133a02a68d1ecfc5ef7",
"timestamp": "",
"source": "github",
"line_count": 101,
"max_line_length": 135,
"avg_line_length": 29.633663366336634,
"alnum_prop": 0.6501837621115937,
"repo_name": "aseber/TradingVisualization",
"id": "80f33867517863df7f585569e34f4426f7967be6",
"size": "3018",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Stock.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "28986"
}
],
"symlink_target": ""
} |
'use strict';
const url = require('url');
const Path = require('path');
const retry = require('retry-as-promised');
const clsBluebird = require('cls-bluebird');
const Utils = require('./utils');
const Model = require('./model');
const DataTypes = require('./data-types');
const Deferrable = require('./deferrable');
const ModelManager = require('./model-manager');
const QueryInterface = require('./query-interface');
const Transaction = require('./transaction');
const QueryTypes = require('./query-types');
const sequelizeErrors = require('./errors');
const Promise = require('./promise');
const Hooks = require('./hooks');
const Association = require('./associations/index');
const Validator = require('./utils/validator-extras').validator;
const _ = require('lodash');
const Op = require('./operators');
/**
* This is the main class, the entry point to sequelize. To use it, you just need to import sequelize:
*
* ```js
* const Sequelize = require('sequelize');
* ```
*
* In addition to sequelize, the connection library for the dialect you want to use should also be installed in your project. You don't need to import it however, as sequelize will take care of that.
*/
class Sequelize {
/**
* Instantiate sequelize with name of database, username and password
*
* #### Example usage
*
* ```javascript
* // without password and options
* const sequelize = new Sequelize('database', 'username')
*
* // without options
* const sequelize = new Sequelize('database', 'username', 'password')
*
* // without password / with blank password
* const sequelize = new Sequelize('database', 'username', null, {})
*
* // with password and options
* const sequelize = new Sequelize('my_database', 'john', 'doe', {})
*
* // with database, username, and password in the options object
* const sequelize = new Sequelize({ database, username, password });
*
* // with uri
* const sequelize = new Sequelize('mysql://localhost:3306/database', {})
* ```
*
* @param {String} [database] The name of the database
* @param {String} [username=null] The username which is used to authenticate against the database.
* @param {String} [password=null] The password which is used to authenticate against the database. Supports SQLCipher encryption for SQLite.
* @param {Object} [options={}] An object with options.
* @param {String} [options.host='localhost'] The host of the relational database.
* @param {Integer} [options.port=] The port of the relational database.
* @param {String} [options.username=null] The username which is used to authenticate against the database.
* @param {String} [options.password=null] The password which is used to authenticate against the database.
* @param {String} [options.database=null] The name of the database
* @param {String} [options.dialect] The dialect of the database you are connecting to. One of mysql, postgres, sqlite and mssql.
* @param {String} [options.dialectModulePath=null] If specified, load the dialect library from this path. For example, if you want to use pg.js instead of pg when connecting to a pg database, you should specify 'pg.js' here
* @param {Object} [options.dialectOptions] An object of additional options, which are passed directly to the connection library
* @param {String} [options.storage] Only used by sqlite. Defaults to ':memory:'
* @param {String} [options.protocol='tcp'] The protocol of the relational database.
* @param {Object} [options.define={}] Default options for model definitions. See sequelize.define for options
* @param {Object} [options.query={}] Default options for sequelize.query
* @param {Object} [options.set={}] Default options for sequelize.set
* @param {Object} [options.sync={}] Default options for sequelize.sync
* @param {String} [options.timezone='+00:00'] The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes.
* @param {Function} [options.logging=console.log] A function that gets executed every time Sequelize would log something.
* @param {Boolean} [options.benchmark=false] Pass query execution time in milliseconds as second argument to logging function (options.logging).
* @param {Boolean} [options.omitNull=false] A flag that defines if null values should be passed to SQL queries or not.
* @param {Boolean} [options.native=false] A flag that defines if native library shall be used or not. Currently only has an effect for postgres
* @param {Boolean} [options.replication=false] Use read / write replication. To enable replication, pass an object, with two properties, read and write. Write should be an object (a single server for handling writes), and read an array of object (several servers to handle reads). Each read/write server can have the following properties: `host`, `port`, `username`, `password`, `database`
* @param {Object} [options.pool] sequelize connection pool configuration
* @param {Integer} [options.pool.max=5] Maximum number of connection in pool
* @param {Integer} [options.pool.min=0] Minimum number of connection in pool
* @param {Integer} [options.pool.idle=10000] The maximum time, in milliseconds, that a connection can be idle before being released. Use with combination of evict for proper working, for more details read https://github.com/coopernurse/node-pool/issues/178#issuecomment-327110870
* @param {Integer} [options.pool.acquire=10000] The maximum time, in milliseconds, that pool will try to get connection before throwing error
* @param {Integer} [options.pool.evict=10000] The time interval, in milliseconds, for evicting stale connections. Set it to 0 to disable this feature.
* @param {Boolean} [options.pool.handleDisconnects=true] Controls if pool should handle connection disconnect automatically without throwing errors
* @param {Function} [options.pool.validate] A function that validates a connection. Called with client. The default function checks that client is an object, and that its state is not disconnected
* @param {Boolean} [options.quoteIdentifiers=true] Set to `false` to make table names and attributes case-insensitive on Postgres and skip double quoting of them. WARNING: Setting this to false may expose vulnerabilities and is not recommended!
* @param {String} [options.transactionType='DEFERRED'] Set the default transaction type. See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
* @param {String} [options.isolationLevel] Set the default transaction isolation level. See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options.
* @param {Object} [options.retry] Set of flags that control when a query is automatically retried.
* @param {Array} [options.retry.match] Only retry a query if the error matches one of these strings.
* @param {Integer} [options.retry.max] How many times a failing query is automatically retried. Set to 0 to disable retrying on SQL_BUSY error.
* @param {Boolean} [options.typeValidation=false] Run built in type validators on insert and update, e.g. validate that arguments passed to integer fields are integer-like.
* @param {Object|Boolean} [options.operatorsAliases=true] String based operator alias, default value is true which will enable all operators alias. Pass object to limit set of aliased operators or false to disable completely.
*
*/
constructor(database, username, password, options) {
let config;
if (arguments.length === 1 && typeof database === 'object') {
// new Sequelize({ ... options })
options = database;
config = _.pick(options, 'host', 'port', 'database', 'username', 'password');
} else if (arguments.length === 1 && typeof database === 'string' || arguments.length === 2 && typeof username === 'object') {
// new Sequelize(URI, { ... options })
config = {};
options = username || {};
const urlParts = url.parse(arguments[0]);
options.dialect = urlParts.protocol.replace(/:$/, '');
options.host = urlParts.hostname;
if (options.dialect === 'sqlite' && urlParts.pathname && urlParts.pathname.indexOf('/:memory') !== 0) {
const path = Path.join(options.host, urlParts.pathname);
options.storage = options.storage || path;
}
if (urlParts.pathname) {
config.database = urlParts.pathname.replace(/^\//, '');
}
if (urlParts.port) {
options.port = urlParts.port;
}
if (urlParts.auth) {
const authParts = urlParts.auth.split(':');
config.username = authParts[0];
if (authParts.length > 1)
config.password = authParts.slice(1).join(':');
}
} else {
// new Sequelize(database, username, password, { ... options })
options = options || {};
config = {database, username, password};
}
Sequelize.runHooks('beforeInit', config, options);
this.options = _.extend({
dialect: null,
dialectModulePath: null,
host: 'localhost',
protocol: 'tcp',
define: {},
query: {},
sync: {},
timezone:'+00:00',
logging: console.log,
omitNull: false,
native: false,
replication: false,
ssl: undefined,
pool: {},
quoteIdentifiers: true,
hooks: {},
retry: {max: 5, match: ['SQLITE_BUSY: database is locked']},
transactionType: Transaction.TYPES.DEFERRED,
isolationLevel: null,
databaseVersion: 0,
typeValidation: false,
benchmark: false,
operatorsAliases: true
}, options || {});
if (!this.options.dialect) {
throw new Error('Dialect needs to be explicitly supplied as of v4.0.0');
}
if (this.options.dialect === 'postgresql') {
this.options.dialect = 'postgres';
}
if (this.options.dialect === 'sqlite' && this.options.timezone !== '+00:00') {
throw new Error('Setting a custom timezone is not supported by SQLite, dates are always returned as UTC. Please remove the custom timezone parameter.');
}
if (this.options.logging === true) {
Utils.deprecate('The logging-option should be either a function or false. Default: console.log');
this.options.logging = console.log;
}
this.options.hooks = this.replaceHookAliases(this.options.hooks);
if (['', null, false].indexOf(config.password) > -1 || typeof config.password === 'undefined') {
config.password = null;
}
this.config = {
database: config.database,
username: config.username,
password: config.password,
host: config.host || this.options.host,
port: config.port || this.options.port,
pool: this.options.pool,
protocol: this.options.protocol,
native: this.options.native,
ssl: this.options.ssl,
replication: this.options.replication,
dialectModulePath: this.options.dialectModulePath,
keepDefaultTimezone: this.options.keepDefaultTimezone,
dialectOptions: this.options.dialectOptions
};
let Dialect;
// Requiring the dialect in a switch-case to keep the
// require calls static. (Browserify fix)
switch (this.getDialect()) {
case 'mssql':
Dialect = require('./dialects/mssql');
break;
case 'mysql':
Dialect = require('./dialects/mysql');
break;
case 'postgres':
Dialect = require('./dialects/postgres');
break;
case 'sqlite':
Dialect = require('./dialects/sqlite');
break;
default:
throw new Error('The dialect ' + this.getDialect() + ' is not supported. Supported dialects: mssql, mysql, postgres, and sqlite.');
}
this.dialect = new Dialect(this);
this.dialect.QueryGenerator.typeValidation = options.typeValidation;
if (this.options.operatorsAliases === true) {
Utils.deprecate('String based operators are now deprecated. Please use Symbol based operators for better security, read more at http://docs.sequelizejs.com/manual/tutorial/querying.html#operators');
this.dialect.QueryGenerator.setOperatorsAliases(Op.LegacyAliases); //Op.LegacyAliases should be removed and replaced by Op.Aliases by v5.0 use
} else {
this.dialect.QueryGenerator.setOperatorsAliases(this.options.operatorsAliases);
}
this.queryInterface = new QueryInterface(this);
/**
* Models are stored here under the name given to `sequelize.define`
*/
this.models = {};
this.modelManager = new ModelManager(this);
this.connectionManager = this.dialect.connectionManager;
this.importCache = {};
this.test = {
_trackRunningQueries: false,
_runningQueries: 0,
trackRunningQueries() {
this._trackRunningQueries = true;
},
verifyNoRunningQueries() {
if (this._runningQueries > 0) throw new Error('Expected 0 running queries. '+this._runningQueries+' queries still running');
}
};
Sequelize.runHooks('afterInit', this);
}
refreshTypes() {
this.connectionManager.refreshTypeParser(DataTypes);
}
/**
* Returns the specified dialect.
*
* @return {String} The specified dialect.
*/
getDialect() {
return this.options.dialect;
}
/**
* Returns an instance of QueryInterface.
* @method getQueryInterface
* @memberOf Sequelize
* @return {QueryInterface} An instance (singleton) of QueryInterface.
*/
getQueryInterface() {
this.queryInterface = this.queryInterface || new QueryInterface(this);
return this.queryInterface;
}
/**
* Define a new model, representing a table in the DB.
*
* The table columns are defined by the object that is given as the second argument. Each key of the object represents a column
*
* @param {String} modelName The name of the model. The model will be stored in `sequelize.models` under this name
* @param {Object} attributes An object, where each attribute is a column of the table. See {@link Model.init}
* @param {Object} [options] These options are merged with the default define options provided to the Sequelize constructor and passed to Model.init()
*
* @see {@link Model.init} for a more comprehensive specification of the `options` and `attributes` objects.
* @see <a href="../manual/tutorial/models-definition.html">The manual section about defining models</a>
* @see {@link DataTypes} For a list of possible data types
*
* @return {Model}
*
* @example
* sequelize.define('modelName', {
* columnA: {
* type: Sequelize.BOOLEAN,
* validate: {
* is: ["[a-z]",'i'], // will only allow letters
* max: 23, // only allow values <= 23
* isIn: {
* args: [['en', 'zh']],
* msg: "Must be English or Chinese"
* }
* },
* field: 'column_a'
* // Other attributes here
* },
* columnB: Sequelize.STRING,
* columnC: 'MY VERY OWN COLUMN TYPE'
* })
*
* sequelize.models.modelName // The model will now be available in models under the name given to define
*/
define(modelName, attributes, options) {
options = options || {};
options.modelName = modelName;
options.sequelize = this;
const model = class extends Model {};
model.init(attributes, options);
return model;
}
/**
* Fetch a Model which is already defined
*
* @param {String} modelName The name of a model defined with Sequelize.define
* @throws Will throw an error if the model is not defined (that is, if sequelize#isDefined returns false)
* @return {Model}
*/
model(modelName) {
if (!this.isDefined(modelName)) {
throw new Error(modelName + ' has not been defined');
}
return this.modelManager.getModel(modelName);
}
/**
* Checks whether a model with the given name is defined
*
* @param {String} modelName The name of a model defined with Sequelize.define
* @return {Boolean}
*/
isDefined(modelName) {
const models = this.modelManager.models;
return models.filter(model => model.name === modelName).length !== 0;
}
/**
* Imports a model defined in another file
*
* Imported models are cached, so multiple calls to import with the same path will not load the file multiple times
*
* See https://github.com/sequelize/express-example for a short example of how to define your models in separate files so that they can be imported by sequelize.import
* @param {String} path The path to the file that holds the model you want to import. If the part is relative, it will be resolved relatively to the calling file
* @return {Model}
*/
import(path) {
// is it a relative path?
if (Path.normalize(path) !== Path.resolve(path)) {
// make path relative to the caller
const callerFilename = Utils.stack()[1].getFileName();
const callerPath = Path.dirname(callerFilename);
path = Path.resolve(callerPath, path);
}
if (!this.importCache[path]) {
let defineCall = arguments.length > 1 ? arguments[1] : require(path);
if (typeof defineCall === 'object') {
// ES6 module compatibility
defineCall = defineCall.default;
}
this.importCache[path] = defineCall(this, DataTypes);
}
return this.importCache[path];
}
/**
* Execute a query on the DB, with the possibility to bypass all the sequelize goodness.
*
* By default, the function will return two arguments: an array of results, and a metadata object, containing number of affected rows etc. Use `.spread` to access the results.
*
* If you are running a type of query where you don't need the metadata, for example a `SELECT` query, you can pass in a query type to make sequelize format the results:
*
* ```js
* sequelize.query('SELECT...').spread((results, metadata) => {
* // Raw query - use spread
* });
*
* sequelize.query('SELECT...', { type: sequelize.QueryTypes.SELECT }).then(results => {
* // SELECT query - use then
* })
* ```
*
* @method query
* @param {String} sql
* @param {Object} [options={}] Query options.
* @param {Boolean} [options.raw] If true, sequelize will not try to format the results of the query, or build an instance of a model from the result
* @param {Transaction} [options.transaction=null] The transaction that the query should be executed under
* @param {QueryTypes} [options.type='RAW'] The type of query you are executing. The query type affects how results are formatted before they are passed back. The type is a string, but `Sequelize.QueryTypes` is provided as convenience shortcuts.
* @param {Boolean} [options.nest=false] If true, transforms objects with `.` separated property names into nested objects using [dottie.js](https://github.com/mickhansen/dottie.js). For example { 'user.username': 'john' } becomes { user: { username: 'john' }}. When `nest` is true, the query type is assumed to be `'SELECT'`, unless otherwise specified
* @param {Boolean} [options.plain=false] Sets the query type to `SELECT` and return a single row
* @param {Object|Array} [options.replacements] Either an object of named parameter replacements in the format `:param` or an array of unnamed replacements to replace `?` in your SQL.
* @param {Object|Array} [options.bind] Either an object of named bind parameter in the format `_param` or an array of unnamed bind parameter to replace `$1, $2, ...` in your SQL.
* @param {Boolean} [options.useMaster=false] Force the query to use the write pool, regardless of the query type.
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {new Model()} [options.instance] A sequelize instance used to build the return instance
* @param {Model} [options.model] A sequelize model used to build the returned model instances (used to be called callee)
* @param {Object} [options.retry] Set of flags that control when a query is automatically retried.
* @param {Array} [options.retry.match] Only retry a query if the error matches one of these strings.
* @param {Integer} [options.retry.max] How many times a failing query is automatically retried.
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {Boolean} [options.supportsSearchPath] If false do not prepend the query with the search_path (Postgres only)
* @param {Boolean} [options.mapToModel=false] Map returned fields to model's fields if `options.model` or `options.instance` is present. Mapping will occur before building the model instance.
* @param {Object} [options.fieldMap] Map returned fields to arbitrary names for `SELECT` query type.
*
* @return {Promise}
*
* @see {@link Model.build} for more information about instance option.
*/
query(sql, options) {
let bindParameters;
return Promise.try(() => {
options = _.assign({}, this.options.query, options);
if (options.instance && !options.model) {
options.model = options.instance.constructor;
}
// map raw fields to model attributes
if (options.mapToModel) {
options.fieldMap = _.get(options, 'model.fieldAttributeMap', {});
}
if (typeof sql === 'object') {
if (sql.values !== undefined) {
if (options.replacements !== undefined) {
throw new Error('Both `sql.values` and `options.replacements` cannot be set at the same time');
}
options.replacements = sql.values;
}
if (sql.bind !== undefined) {
if (options.bind !== undefined) {
throw new Error('Both `sql.bind` and `options.bind` cannot be set at the same time');
}
options.bind = sql.bind;
}
if (sql.query !== undefined) {
sql = sql.query;
}
}
sql = sql.trim();
if (!options.instance && !options.model) {
options.raw = true;
}
if (options.replacements && options.bind) {
throw new Error('Both `replacements` and `bind` cannot be set at the same time');
}
if (options.replacements) {
if (Array.isArray(options.replacements)) {
sql = Utils.format([sql].concat(options.replacements), this.options.dialect);
} else {
sql = Utils.formatNamedParameters(sql, options.replacements, this.options.dialect);
}
}
if (options.bind) {
const bindSql = this.dialect.Query.formatBindParameters(sql, options.bind, this.options.dialect);
sql = bindSql[0];
bindParameters = bindSql[1];
}
options = _.defaults(options, {
logging: this.options.hasOwnProperty('logging') ? this.options.logging : console.log,
searchPath: this.options.hasOwnProperty('searchPath') ? this.options.searchPath : 'DEFAULT'
});
if (options.transaction === undefined && Sequelize._cls) {
options.transaction = Sequelize._cls.get('transaction');
}
if (!options.type) {
if (options.model || options.nest || options.plain) {
options.type = QueryTypes.SELECT;
} else {
options.type = QueryTypes.RAW;
}
}
if (options.transaction && options.transaction.finished) {
const error = new Error(options.transaction.finished+' has been called on this transaction('+options.transaction.id+'), you can no longer use it. (The rejected query is attached as the \'sql\' property of this error)');
error.sql = sql;
return Promise.reject(error);
}
if (this.test._trackRunningQueries) {
this.test._runningQueries++;
}
//if dialect doesn't support search_path or dialect option
//to prepend searchPath is not true delete the searchPath option
if (!this.dialect.supports.searchPath || !this.options.dialectOptions || !this.options.dialectOptions.prependSearchPath ||
options.supportsSearchPath === false) {
delete options.searchPath;
} else if (!options.searchPath) {
//if user wants to always prepend searchPath (dialectOptions.preprendSearchPath = true)
//then set to DEFAULT if none is provided
options.searchPath = 'DEFAULT';
}
return options.transaction ? options.transaction.connection : this.connectionManager.getConnection(options);
}).then(connection => {
const query = new this.dialect.Query(connection, this, options);
const retryOptions = _.extend(this.options.retry, options.retry || {});
return retry(() => query.run(sql, bindParameters), retryOptions)
.finally(() => {
if (!options.transaction) {
return this.connectionManager.releaseConnection(connection);
}
});
}).finally(() => {
if (this.test._trackRunningQueries) {
this.test._runningQueries--;
}
});
}
/**
* Execute a query which would set an environment or user variable. The variables are set per connection, so this function needs a transaction.
* Only works for MySQL.
*
* @method set
* @param {Object} variables Object with multiple variables.
* @param {Object} options Query options.
* @param {Transaction} options.transaction The transaction that the query should be executed under
*
* @memberof Sequelize
* @return {Promise}
*/
set(variables, options) {
// Prepare options
options = _.extend({}, this.options.set, typeof options === 'object' && options || {});
if (this.options.dialect !== 'mysql') {
throw new Error('sequelize.set is only supported for mysql');
}
if (!options.transaction || !(options.transaction instanceof Transaction) ) {
throw new TypeError('options.transaction is required');
}
// Override some options, since this isn't a SELECT
options.raw = true;
options.plain = true;
options.type = 'SET';
// Generate SQL Query
const query =
'SET '+
_.map(variables, (v, k) => '@'+k +' := '+ (typeof v === 'string' ? '"'+v+'"' : v)).join(', ');
return this.query(query, options);
}
/**
* Escape value.
*
* @param {String} value
* @return {String}
*/
escape(value) {
return this.getQueryInterface().escape(value);
}
/**
* Create a new database schema.
*
* Note, that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this command will do nothing.
*
* @see {@link Model.schema}
* @param {String} schema Name of the schema
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*/
createSchema(schema, options) {
return this.getQueryInterface().createSchema(schema, options);
}
/**
* Show all defined schemas
*
* Note, that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this will show all tables.
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*/
showAllSchemas(options) {
return this.getQueryInterface().showAllSchemas(options);
}
/**
* Drop a single schema
*
* Note, that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this drop a table matching the schema name
* @param {String} schema Name of the schema
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*/
dropSchema(schema, options) {
return this.getQueryInterface().dropSchema(schema, options);
}
/**
* Drop all schemas
*
* Note,that this is a schema in the [postgres sense of the word](http://www.postgresql.org/docs/9.1/static/ddl-schemas.html),
* not a database table. In mysql and sqlite, this is the equivalent of drop all tables.
* @param {Object} options={}
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*/
dropAllSchemas(options) {
return this.getQueryInterface().dropAllSchemas(options);
}
/**
* Sync all defined models to the DB.
*
* @param {Object} [options={}]
* @param {Boolean} [options.force=false] If force is true, each Model will run `DROP TABLE IF EXISTS`, before it tries to create its own table
* @param {RegExp} [options.match] Match a regex against the database name before syncing, a safety check for cases where force: true is used in tests but not live code
* @param {Boolean|function} [options.logging=console.log] A function that logs sql queries, or false for no logging
* @param {String} [options.schema='public'] The schema that the tables should be created in. This can be overriden for each table in sequelize.define
* @param {String} [options.searchPath=DEFAULT] An optional parameter to specify the schema search_path (Postgres only)
* @param {Boolean} [options.hooks=true] If hooks is true then beforeSync, afterSync, beforeBulkSync, afterBulkSync hooks will be called
* @param {Boolean} [options.alter=false] Alters tables to fit models. Not recommended for production use. Deletes data in columns that were removed or had their type changed in the model.
* @return {Promise}
*/
sync(options) {
options = _.clone(options) || {};
options.hooks = options.hooks === undefined ? true : !!options.hooks;
options = _.defaults(options, this.options.sync, this.options);
if (options.match) {
if (!options.match.test(this.config.database)) {
return Promise.reject(new Error('Database does not match sync match parameter'));
}
}
return Promise.try(() => {
if (options.hooks) {
return this.runHooks('beforeBulkSync', options);
}
}).then(() => {
if (options.force) {
return this.drop(options);
}
}).then(() => {
const models = [];
// Topologically sort by foreign key constraints to give us an appropriate
// creation order
this.modelManager.forEachModel(model => {
if (model) {
models.push(model);
} else {
// DB should throw an SQL error if referencing inexistant table
}
});
return Promise.each(models, model => model.sync(options));
}).then(() => {
if (options.hooks) {
return this.runHooks('afterBulkSync', options);
}
}).return(this);
}
/**
* Truncate all tables defined through the sequelize models. This is done
* by calling Model.truncate() on each model.
*
* @param {object} [options] The options passed to Model.destroy in addition to truncate
* @param {Boolean|function} [options.transaction]
* @param {Boolean|function} [options.logging] A function that logs sql queries, or false for no logging
* @return {Promise}
*
* @see {@link Model.truncate} for more information
*/
truncate(options) {
const models = [];
this.modelManager.forEachModel(model => {
if (model) {
models.push(model);
}
}, { reverse: false });
const truncateModel = model => model.truncate(options);
if (options && options.cascade) {
return Promise.each(models, truncateModel);
} else {
return Promise.map(models, truncateModel);
}
}
/**
* Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model
* @see {@link Model.drop} for options
*
* @param {object} options The options passed to each call to Model.drop
* @param {Boolean|function} options.logging A function that logs sql queries, or false for no logging
* @return {Promise}
*/
drop(options) {
const models = [];
this.modelManager.forEachModel(model => {
if (model) {
models.push(model);
}
}, { reverse: false });
return Promise.each(models, model => model.drop(options));
}
/**
* Test the connection by trying to authenticate
*
* @error 'Invalid credentials' if the authentication failed (even if the database did not respond at all...)
* @return {Promise}
*/
authenticate(options) {
return this.query('SELECT 1+1 AS result', _.assign({ raw: true, plain: true }, options)).return();
}
databaseVersion(options) {
return this.getQueryInterface().databaseVersion(options);
}
/**
* Creates an object representing a database function. This can be used in search queries, both in where and order parts, and as default values in column definitions.
* If you want to refer to columns in your function, you should use `sequelize.col`, so that the columns are properly interpreted as columns and not a strings.
*
* Convert a user's username to upper case
* ```js
* instance.updateAttributes({
* username: self.sequelize.fn('upper', self.sequelize.col('username'))
* })
* ```
*
* @see {@link Model.findAll}
* @see {@link Sequelize.define}
* @see {@link Sequelize.col}
* @method fn
*
* @param {String} fn The function you want to call
* @param {any} args All further arguments will be passed as arguments to the function
*
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.fn}
* @example <caption>Convert a user's username to upper case</caption>
* instance.updateAttributes({
* username: self.sequelize.fn('upper', self.sequelize.col('username'))
* })
*/
static fn(fn) {
return new Utils.Fn(fn, Utils.sliceArgs(arguments, 1));
}
/**
* Creates an object which represents a column in the DB, this allows referencing another column in your query. This is often useful in conjunction with `sequelize.fn`, since raw string arguments to fn will be escaped.
* @see {@link Sequelize#fn}
*
* @method col
* @param {String} col The name of the column
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.col}
*/
static col(col) {
return new Utils.Col(col);
}
/**
* Creates an object representing a call to the cast function.
*
* @method cast
* @param {any} val The value to cast
* @param {String} type The type to cast it to
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.cast}
*/
static cast(val, type) {
return new Utils.Cast(val, type);
}
/**
* Creates an object representing a literal, i.e. something that will not be escaped.
*
* @method literal
* @param {any} val
* @alias asIs
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.literal}
*/
static literal(val) {
return new Utils.Literal(val);
}
/**
* An AND query
* @see {@link Model.findAll}
*
* @method and
* @param {String|Object} args Each argument will be joined by AND
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.and}
*/
static and() {
return { [Op.and]: Utils.sliceArgs(arguments) };
}
/**
* An OR query
* @see {@link Model.findAll}
*
* @method or
* @param {String|Object} args Each argument will be joined by OR
* @since v2.0.0-dev3
* @memberof Sequelize
* @return {Sequelize.or}
*/
static or() {
return { [Op.or]: Utils.sliceArgs(arguments) };
}
/**
* Creates an object representing nested where conditions for postgres's json data-type.
* @see {@link Model.findAll}
*
* @method json
* @param {String|Object} conditions A hash containing strings/numbers or other nested hash, a string using dot notation or a string using postgres json syntax.
* @param {String|Number|Boolean} [value] An optional value to compare against. Produces a string of the form "<json path> = '<value>'".
* @memberof Sequelize
* @return {Sequelize.json}
*/
static json(conditionsOrPath, value) {
return new Utils.Json(conditionsOrPath, value);
}
/**
* A way of specifying attr = condition.
*
* The attr can either be an object taken from `Model.rawAttributes` (for example `Model.rawAttributes.id` or `Model.rawAttributes.name`). The
* attribute should be defined in your model definition. The attribute can also be an object from one of the sequelize utility functions (`sequelize.fn`, `sequelize.col` etc.)
*
* For string attributes, use the regular `{ where: { attr: something }}` syntax. If you don't want your string to be escaped, use `sequelize.literal`.
*
* @see {@link Model.findAll}
*
* @param {Object} attr The attribute, which can be either an attribute object from `Model.rawAttributes` or a sequelize object, for example an instance of `sequelize.fn`. For simple string attributes, use the POJO syntax
* @param {string} [comparator='=']
* @param {String|Object} logic The condition. Can be both a simply type, or a further condition (`or`, `and`, `.literal` etc.)
* @alias condition
* @since v2.0.0-dev3
*/
static where(attr, comparator, logic) {
return new Utils.Where(attr, comparator, logic);
}
/**
* Start a transaction. When using transactions, you should pass the transaction in the options argument in order for the query to happen under that transaction
*
* ```js
* sequelize.transaction().then(transaction => {
* return User.find(..., {transaction})
* .then(user => user.updateAttributes(..., {transaction}))
* .then(() => transaction.commit())
* .catch(() => transaction.rollback());
* })
* ```
*
* A syntax for automatically committing or rolling back based on the promise chain resolution is also supported:
*
* ```js
* sequelize.transaction(transaction => { // Note that we use a callback rather than a promise.then()
* return User.find(..., {transaction})
* .then(user => user.updateAttributes(..., {transaction}))
* }).then(() => {
* // Committed
* }).catch(err => {
* // Rolled back
* console.error(err);
* });
* ```
*
* If you have [CLS](https://github.com/othiym23/node-continuation-local-storage) enabled, the transaction will automatically be passed to any query that runs within the callback.
* To enable CLS, add it do your project, create a namespace and set it on the sequelize constructor:
*
* ```js
* const cls = require('continuation-local-storage');
* const ns = cls.createNamespace('....');
* const Sequelize = require('sequelize');
* Sequelize.useCLS(ns);
* ```
* Note, that CLS is enabled for all sequelize instances, and all instances will share the same namespace
*
* @see {@link Transaction}
* @param {Object} [options={}]
* @param {Boolean} [options.autocommit]
* @param {String} [options.type='DEFERRED'] See `Sequelize.Transaction.TYPES` for possible options. Sqlite only.
* @param {String} [options.isolationLevel] See `Sequelize.Transaction.ISOLATION_LEVELS` for possible options
* @param {Function} [options.logging=false] A function that gets executed while running the query to log the sql.
* @param {Function} [autoCallback] The callback is called with the transaction object, and should return a promise. If the promise is resolved, the transaction commits; if the promise rejects, the transaction rolls back
* @return {Promise}
*/
transaction(options, autoCallback) {
if (typeof options === 'function') {
autoCallback = options;
options = undefined;
}
const transaction = new Transaction(this, options);
if (!autoCallback) return transaction.prepareEnvironment().return(transaction);
// autoCallback provided
return Sequelize._clsRun(() => {
return transaction.prepareEnvironment()
.then(() => autoCallback(transaction))
.tap(() => transaction.commit())
.catch(err => {
// Rollback transaction if not already finished (commit, rollback, etc)
// and reject with original error (ignore any error in rollback)
return Promise.try(() => {
if (!transaction.finished) return transaction.rollback().catch(() => {});
}).throw(err);
});
});
}
/**
* Use CLS with Sequelize.
* CLS namespace provided is stored as `Sequelize._cls`
* and bluebird Promise is patched to use the namespace, using `cls-bluebird` module.
*
* @param {Object} ns CLS namespace
* @returns {Object} Sequelize constructor
*/
static useCLS(ns) {
// check `ns` is valid CLS namespace
if (!ns || typeof ns !== 'object' || typeof ns.bind !== 'function' || typeof ns.run !== 'function') throw new Error('Must provide CLS namespace');
// save namespace as `Sequelize._cls`
this._cls = ns;
// patch bluebird to bind all promise callbacks to CLS namespace
clsBluebird(ns, Promise);
// return Sequelize for chaining
return this;
}
/**
* Run function in CLS context.
* If no CLS context in use, just runs the function normally
*
* @private
* @param {Function} fn Function to run
* @returns {*} Return value of function
*/
static _clsRun(fn) {
const ns = Sequelize._cls;
if (!ns) return fn();
let res;
ns.run(context => res = fn(context));
return res;
}
/*
* Getter/setter for `Sequelize.cls`
* To maintain backward compatibility with Sequelize v3.x
* Calling the
*/
static get cls() {
Utils.deprecate('Sequelize.cls is deprecated and will be removed in a future version. Keep track of the CLS namespace you use in your own code.');
return this._cls;
}
static set cls(ns) {
Utils.deprecate('Sequelize.cls should not be set directly. Use Sequelize.useCLS().');
this.useCLS(ns);
}
log() {
let options;
let args = Utils.sliceArgs(arguments);
const last = _.last(args);
if (last && _.isPlainObject(last) && last.hasOwnProperty('logging')) {
options = last;
// remove options from set of logged arguments if options.logging is equal to console.log
if (options.logging === console.log) {
args.splice(args.length-1, 1);
}
} else {
options = this.options;
}
if (options.logging) {
if (options.logging === true) {
Utils.deprecate('The logging-option should be either a function or false. Default: console.log');
options.logging = console.log;
}
// second argument is sql-timings, when benchmarking option enabled
if ((this.options.benchmark || options.benchmark) && options.logging === console.log) {
args = [args[0] + ' Elapsed time: ' + args[1] + 'ms'];
}
options.logging.apply(null, args);
}
}
/**
* Close all connections used by this sequelize instance, and free all references so the instance can be garbage collected.
*
* Normally this is done on process exit, so you only need to call this method if you are creating multiple instances, and want
* to garbage collect some of them.
*
* @return {Promise}
*/
close() {
return this.connectionManager.close();
}
normalizeDataType(Type) {
let type = typeof Type === 'function' ? new Type() : Type;
const dialectTypes = this.dialect.DataTypes || {};
if (dialectTypes[type.key]) {
type = dialectTypes[type.key].extend(type);
}
if (type instanceof DataTypes.ARRAY && dialectTypes[type.type.key]) {
type.type = dialectTypes[type.type.key].extend(type.type);
}
return type;
}
normalizeAttribute(attribute) {
if (!_.isPlainObject(attribute)) {
attribute = { type: attribute };
}
if (!attribute.type) return attribute;
attribute.type = this.normalizeDataType(attribute.type);
if (attribute.hasOwnProperty('defaultValue')) {
if (typeof attribute.defaultValue === 'function' && (
attribute.defaultValue === DataTypes.NOW ||
attribute.defaultValue === DataTypes.UUIDV1 ||
attribute.defaultValue === DataTypes.UUIDV4
)) {
attribute.defaultValue = new attribute.defaultValue();
}
}
if (attribute.type instanceof DataTypes.ENUM) {
// The ENUM is a special case where the type is an object containing the values
if (attribute.values) {
attribute.type.values = attribute.type.options.values = attribute.values;
} else {
attribute.values = attribute.type.values;
}
if (!attribute.values.length) {
throw new Error('Values for ENUM have not been defined.');
}
}
return attribute;
}
}
// Aliases
Sequelize.prototype.fn = Sequelize.fn;
Sequelize.prototype.col = Sequelize.col;
Sequelize.prototype.cast = Sequelize.cast;
Sequelize.prototype.literal = Sequelize.asIs = Sequelize.prototype.asIs = Sequelize.literal;
Sequelize.prototype.and = Sequelize.and;
Sequelize.prototype.or = Sequelize.or;
Sequelize.prototype.json = Sequelize.json;
Sequelize.prototype.where = Sequelize.condition = Sequelize.prototype.condition = Sequelize.where;
Sequelize.prototype.validate = Sequelize.prototype.authenticate;
/**
* Sequelize version number.
*/
Sequelize.version = require('../package.json').version;
Sequelize.options = {hooks: {}};
/**
* A reference to Sequelize constructor from sequelize. Useful for accessing DataTypes, Errors etc.
* @see {@link Sequelize}
*/
Sequelize.prototype.Sequelize = Sequelize;
/**
* @private
*/
Sequelize.prototype.Utils = Sequelize.Utils = Utils;
/**
* A handy reference to the bluebird Promise class
*/
Sequelize.prototype.Promise = Sequelize.Promise = Promise;
/**
* Available query types for use with `sequelize.query`
* @see {@link QueryTypes}
*/
Sequelize.prototype.QueryTypes = Sequelize.QueryTypes = QueryTypes;
/**
* Operators symbols to be used for querying data
* @see {@link Operators}
*/
Sequelize.prototype.Op = Sequelize.Op = Op;
/**
* Exposes the validator.js object, so you can extend it with custom validation functions. The validator is exposed both on the instance, and on the constructor.
* @see https://github.com/chriso/validator.js
*/
Sequelize.prototype.Validator = Sequelize.Validator = Validator;
Sequelize.prototype.Model = Sequelize.Model = Model;
Sequelize.DataTypes = DataTypes;
for (const dataType in DataTypes) {
Sequelize[dataType] = DataTypes[dataType];
}
/**
* A reference to the sequelize transaction class. Use this to access isolationLevels and types when creating a transaction
* @see {@link Transaction}
* @see {@link Sequelize.transaction}
*/
Sequelize.prototype.Transaction = Sequelize.Transaction = Transaction;
/**
* A reference to the deferrable collection. Use this to access the different deferrable options.
* @see {@link Transaction.Deferrable}
* @see {@link Sequelize#transaction}
*/
Sequelize.prototype.Deferrable = Sequelize.Deferrable = Deferrable;
/**
* A reference to the sequelize association class.
* @see {@link Association}
*/
Sequelize.prototype.Association = Sequelize.Association = Association;
/**
* Provide alternative version of `inflection` module to be used by `Utils.pluralize` etc.
* @param {Object} _inflection - `inflection` module
*/
Sequelize.useInflection = Utils.useInflection;
/**
* Allow hooks to be defined on Sequelize + on sequelize instance as universal hooks to run on all models
* and on Sequelize/sequelize methods e.g. Sequelize(), Sequelize#define()
*/
Hooks.applyTo(Sequelize);
Hooks.applyTo(Sequelize.prototype);
/**
* Expose various errors available
*/
for (const error of Object.keys(sequelizeErrors)) {
if (sequelizeErrors[error] === sequelizeErrors.BaseError) {
Sequelize.prototype.Error = Sequelize.Error = sequelizeErrors.BaseError;
} else {
Sequelize.prototype[error] = Sequelize[error] = sequelizeErrors[error];
}
}
module.exports = Sequelize;
module.exports.Sequelize = Sequelize;
module.exports.default = Sequelize;
| {
"content_hash": "8c5a520542caf24aec8f9cf2e331b85a",
"timestamp": "",
"source": "github",
"line_count": 1234,
"max_line_length": 531,
"avg_line_length": 39.60940032414911,
"alnum_prop": 0.6653709235238757,
"repo_name": "nemisj/sequelize",
"id": "662d599dfcc83d7f2916eced255eaabb44aa5410",
"size": "48878",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/sequelize.js",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2701518"
},
{
"name": "PowerShell",
"bytes": "1468"
}
],
"symlink_target": ""
} |
/**
* This code was auto-generated by a Codezu.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.contracts.paymentservice;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
/**
* Field value information for the payment gateway.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class GatewayCredentialFieldValue implements Serializable
{
// Default Serial Version UID
private static final long serialVersionUID = 1L;
/**
* The display name of the source product property. For a product field it will be the display name of the field. For a product attribute it will be the Attribute Name.
*/
protected String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
/**
* The value of a property, used by numerous objects within Mozu including facets, attributes, products, localized content, metadata, capabilities (Mozu and third-party), location inventory adjustment, and more. The value may be a string, integer, or double. Validation may be run against the entered and saved values depending on the object type.
*/
protected String value;
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
}
| {
"content_hash": "654714e8696282f2ddb1bb291f71b194",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 348,
"avg_line_length": 30.291666666666668,
"alnum_prop": 0.7248968363136176,
"repo_name": "sanjaymandadi/mozu-java",
"id": "8bc116f026d3d2ba610eecdf6f4dcfb5a7269e0e",
"size": "1454",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mozu-javaasync-core/src/main/java/com/mozu/api/contracts/paymentservice/GatewayCredentialFieldValue.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "102"
},
{
"name": "Java",
"bytes": "10956049"
}
],
"symlink_target": ""
} |
"""Tests the bob.ip.base.Wiener filter
"""
import os
import numpy
import tempfile
import nose.tools
import bob.sp
import bob.io.base
import bob.ip.base
def test_initialization():
# Getters/Setters
m = bob.ip.base.Wiener((5,4),0.5)
nose.tools.eq_(m.size, (5,4))
m.size = (5,6)
nose.tools.eq_(m.size, (5,6))
ps1 = 0.2 + numpy.fabs(numpy.random.randn(5,6))
ps2 = 0.2 + numpy.fabs(numpy.random.randn(5,6))
m.Ps = ps1
assert numpy.allclose(m.Ps, ps1)
m.Ps = ps2
assert numpy.allclose(m.Ps, ps2)
pn1 = 0.5
m.Pn = pn1
assert abs(m.Pn - pn1) < 1e-5
var_thd = 1e-5
m.variance_threshold = var_thd
assert abs(m.variance_threshold - var_thd) < 1e-5
# Comparison operators
m2 = bob.ip.base.Wiener(m)
assert m == m2
assert (m != m2) is False
m3 = bob.ip.base.Wiener(ps2, pn1)
m3.variance_threshold = var_thd
assert m == m3
assert (m != m3 ) is False
# Computation of the Wiener filter W
w_py = 1 / (1. + m.Pn / m.Ps)
assert numpy.allclose(m.w, w_py)
def test_load_save():
m = bob.ip.base.Wiener((5,4),0.5)
# Save and read from file
filename = str(tempfile.mkstemp(".hdf5")[1])
m.save(bob.io.base.HDF5File(filename, 'w'))
m_loaded = bob.ip.base.Wiener(bob.io.base.HDF5File(filename))
assert m == m_loaded
assert (m != m_loaded) is False
assert m.is_similar_to(m_loaded)
# Make them different
m_loaded.variance_threshold = 0.001
assert (m == m_loaded) is False
assert m != m_loaded
# Clean-up
os.unlink(filename)
def test_filter():
ps = 0.2 + numpy.fabs(numpy.random.randn(5,6))
pn = 0.5
m = bob.ip.base.Wiener(ps,pn)
# Python way
sample = numpy.random.randn(5,6)
sample_fft = bob.sp.fft(sample.astype(numpy.complex128))
w = m.w
sample_fft_filtered = sample_fft * m.w
sample_filtered_py = numpy.absolute(bob.sp.ifft(sample_fft_filtered))
# Bob c++ way
sample_filtered0 = m.filter(sample)
sample_filtered1 = m(sample)
sample_filtered2 = numpy.zeros((5,6),numpy.float64)
m.filter(sample, sample_filtered2)
sample_filtered3 = numpy.zeros((5,6),numpy.float64)
m.filter(sample, sample_filtered3)
sample_filtered4 = numpy.zeros((5,6),numpy.float64)
m(sample, sample_filtered4)
assert numpy.allclose(sample_filtered0, sample_filtered_py)
assert numpy.allclose(sample_filtered1, sample_filtered_py)
assert numpy.allclose(sample_filtered2, sample_filtered_py)
assert numpy.allclose(sample_filtered3, sample_filtered_py)
assert numpy.allclose(sample_filtered4, sample_filtered_py)
def test_train():
def train_wiener_ps(training_set):
# Python implementation
n_samples = training_set.shape[0]
height = training_set.shape[1]
width = training_set.shape[2]
training_fftabs = numpy.zeros((n_samples, height, width), dtype=numpy.float64)
for n in range(n_samples):
sample = (training_set[n,:,:]).astype(numpy.complex128)
training_fftabs[n,:,:] = numpy.absolute(bob.sp.fft(sample))
mean = numpy.mean(training_fftabs, axis=0)
for n in range(n_samples):
training_fftabs[n,:,:] -= mean
training_fftabs = training_fftabs * training_fftabs
var_ps = numpy.mean(training_fftabs, axis=0)
return var_ps
n_samples = 20
height = 5
width = 6
training_set = 0.2 + numpy.fabs(numpy.random.randn(n_samples, height, width))
# Python implementation
var_ps = train_wiener_ps(training_set)
# Bob C++ implementation (variant 1) + comparison against python one
m1 = bob.ip.base.Wiener(training_set)
assert numpy.allclose(var_ps, m1.Ps)
# Bob C++ implementation (variant 2) + comparison against python one
m2 = bob.ip.base.Wiener(training_set, 0.)
assert numpy.allclose(var_ps, m2.Ps)
| {
"content_hash": "29e504ab5e718d40ebf4656c02d731c9",
"timestamp": "",
"source": "github",
"line_count": 134,
"max_line_length": 82,
"avg_line_length": 27.440298507462686,
"alnum_prop": 0.6769105248844166,
"repo_name": "tiagofrepereira2012/bob.ip.base",
"id": "082525057318188a1af452543eae4a4bcc57924b",
"size": "3857",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bob/ip/base/test/test_wiener.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "5269"
},
{
"name": "C++",
"bytes": "798081"
},
{
"name": "Python",
"bytes": "131858"
}
],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Moq;
using Azure.Storage.Queues.Models;
using Microsoft.Azure.WebJobs.Extensions.Storage.Common;
using NUnit.Framework;
using Azure.Storage.Queues;
using Azure.WebJobs.Extensions.Storage.Common.Tests;
using Azure.WebJobs.Extensions.Storage.Queues.Tests;
namespace Microsoft.Azure.WebJobs.Host.FunctionalTests
{
public class InstanceTests
{
private const string QueueName = "input-instancetests";
private QueueServiceClient queueServiceClient;
[SetUp]
public void SetUp()
{
queueServiceClient = AzuriteNUnitFixture.Instance.GetQueueServiceClient();
queueServiceClient.GetQueueClient(QueueName).DeleteIfExists();
}
[Test]
public async Task Trigger_CanBeInstanceMethod()
{
// Arrange
string expectedGuid = Guid.NewGuid().ToString();
await AddQueueMessageAsync(queueServiceClient, expectedGuid, QueueName);
var prog = new InstanceProgram();
IHost host = new HostBuilder()
.ConfigureDefaultTestHost<InstanceProgram>(prog, builder =>
{
builder.AddAzureStorageQueues()
.UseQueueService(queueServiceClient);
})
.Build();
// Act
var jobHost = host.GetJobHost<InstanceProgram>();
var result = await jobHost.RunTriggerAsync<QueueMessage>();
// Assert
Assert.AreEqual(expectedGuid, result.MessageText);
}
private class InstanceProgram : IProgramWithResult<QueueMessage>
{
public TaskCompletionSource<QueueMessage> TaskSource { get; set; }
public void Run([QueueTrigger(QueueName)] QueueMessage message)
{
this.TaskSource.TrySetResult(message);
}
}
[Test]
public async Task Trigger_CanBeAsyncInstanceMethod()
{
// Arrange
string expectedGuid = Guid.NewGuid().ToString();
await AddQueueMessageAsync(queueServiceClient, expectedGuid, QueueName);
var prog = new InstanceAsyncProgram();
IHost host = new HostBuilder()
.ConfigureDefaultTestHost<InstanceAsyncProgram>(prog, builder =>
{
builder.AddAzureStorageQueues()
.UseQueueService(queueServiceClient);
})
.Build();
// Act
var jobHost = host.GetJobHost<InstanceAsyncProgram>();
var result = await jobHost.RunTriggerAsync<QueueMessage>();
// Assert
Assert.AreEqual(expectedGuid, result.MessageText);
}
private class InstanceAsyncProgram : IProgramWithResult<QueueMessage>
{
public TaskCompletionSource<QueueMessage> TaskSource { get; set; }
public Task RunAsync([QueueTrigger(QueueName)] QueueMessage message)
{
this.TaskSource.TrySetResult(message);
return Task.FromResult(0);
}
}
// $$$ this test should apply to any trigger and be in the Unit tests.
[Test]
public async Task Trigger_IfClassIsDisposable_Disposes()
{
// Arrange
await AddQueueMessageAsync(queueServiceClient, "ignore", QueueName);
IHost host = new HostBuilder()
.ConfigureDefaultTestHost<DisposeInstanceProgram>(builder =>
{
builder.AddAzureStorageQueues();
builder.UseQueueService(queueServiceClient);
})
.Build();
// Act & Assert
var jobHost = host.GetJobHost<DisposeInstanceProgram>();
var result = await jobHost.RunTriggerAsync<object>(DisposeInstanceProgram.TaskSource);
}
private sealed class DisposeInstanceProgram : IDisposable
{
public static TaskCompletionSource<object> TaskSource = new TaskCompletionSource<object>();
public void Run([QueueTrigger(QueueName)] QueueMessage message)
{
}
public void Dispose()
{
TaskSource.TrySetResult(null);
}
}
// $$$ Not really a queue test
[Test]
public async Task Trigger_IfClassConstructorHasDependencies_CanUseCustomJobActivator()
{
// Arrange
const string expectedResult = "abc";
Mock<IFactory<string>> resultFactoryMock = new Mock<IFactory<string>>(MockBehavior.Strict);
resultFactoryMock.Setup(f => f.Create()).Returns(expectedResult);
IFactory<string> resultFactory = resultFactoryMock.Object;
Mock<IJobActivator> activatorMock = new Mock<IJobActivator>(MockBehavior.Strict);
activatorMock.Setup(a => a.CreateInstance<InstanceCustomActivatorProgram>())
.Returns(() => new InstanceCustomActivatorProgram(resultFactory));
IJobActivator activator = activatorMock.Object;
await AddQueueMessageAsync(queueServiceClient, "ignore", QueueName);
IHost host = new HostBuilder()
.ConfigureDefaultTestHost<InstanceCustomActivatorProgram>(builder =>
{
builder.AddAzureStorageQueues();
builder.UseQueueService(queueServiceClient);
}, null, activator)
.Build();
// Act
var jobHost = host.GetJobHost<InstanceCustomActivatorProgram>();
Assert.NotNull(jobHost);
var result = await jobHost.RunTriggerAsync<string>(InstanceCustomActivatorProgram.TaskSource);
// Assert
Assert.AreSame(expectedResult, result);
}
private static async Task AddQueueMessageAsync(QueueServiceClient client, string message, string queueName)
{
var queue = client.GetQueueClient(queueName);
await queue.CreateIfNotExistsAsync();
await queue.ClearMessagesAsync();
await queue.SendMessageAsync(message);
}
private class InstanceCustomActivatorProgram
{
private readonly IFactory<string> _resultFactory;
public InstanceCustomActivatorProgram(IFactory<string> resultFactory)
{
_resultFactory = resultFactory ?? throw new ArgumentNullException(nameof(resultFactory));
}
public static TaskCompletionSource<string> TaskSource { get; set; } = new TaskCompletionSource<string>();
public void Run([QueueTrigger(QueueName)] QueueMessage ignore)
{
string result = _resultFactory.Create();
TaskSource.TrySetResult(result);
}
}
}
}
| {
"content_hash": "5c2eb60c32509c175b00f18691f56a14",
"timestamp": "",
"source": "github",
"line_count": 195,
"max_line_length": 117,
"avg_line_length": 36.14358974358974,
"alnum_prop": 0.608683314415437,
"repo_name": "markcowl/azure-sdk-for-net",
"id": "07f970ae811867045b31d8962eaab44f8eaee90a",
"size": "7050",
"binary": false,
"copies": "1",
"ref": "refs/heads/ext-resource",
"path": "sdk/storage/Azure.Storage.Webjobs.Extensions.Queues/tests/InstanceTests.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "13482080"
},
{
"name": "PowerShell",
"bytes": "3408"
}
],
"symlink_target": ""
} |
.class Lcom/nineoldandroids/animation/AnimatorSet$1;
.super Lcom/nineoldandroids/animation/AnimatorListenerAdapter;
.source "AnimatorSet.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
value = Lcom/nineoldandroids/animation/AnimatorSet;->start()V
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field canceled:Z
.field final synthetic this$0:Lcom/nineoldandroids/animation/AnimatorSet;
.field final synthetic val$nodesToStart:Ljava/util/ArrayList;
# direct methods
.method constructor <init>(Lcom/nineoldandroids/animation/AnimatorSet;Ljava/util/ArrayList;)V
.locals 1
.prologue
.line 508
iput-object p1, p0, Lcom/nineoldandroids/animation/AnimatorSet$1;->this$0:Lcom/nineoldandroids/animation/AnimatorSet;
iput-object p2, p0, Lcom/nineoldandroids/animation/AnimatorSet$1;->val$nodesToStart:Ljava/util/ArrayList;
invoke-direct {p0}, Lcom/nineoldandroids/animation/AnimatorListenerAdapter;-><init>()V
.line 509
const/4 v0, 0x0
iput-boolean v0, p0, Lcom/nineoldandroids/animation/AnimatorSet$1;->canceled:Z
return-void
.end method
# virtual methods
.method public onAnimationCancel(Lcom/nineoldandroids/animation/Animator;)V
.locals 1
.param p1, "anim" # Lcom/nineoldandroids/animation/Animator;
.prologue
.line 511
const/4 v0, 0x1
iput-boolean v0, p0, Lcom/nineoldandroids/animation/AnimatorSet$1;->canceled:Z
.line 512
return-void
.end method
.method public onAnimationEnd(Lcom/nineoldandroids/animation/Animator;)V
.locals 5
.param p1, "anim" # Lcom/nineoldandroids/animation/Animator;
.prologue
.line 514
iget-boolean v3, p0, Lcom/nineoldandroids/animation/AnimatorSet$1;->canceled:Z
if-nez v3, :cond_0
.line 515
iget-object v3, p0, Lcom/nineoldandroids/animation/AnimatorSet$1;->val$nodesToStart:Ljava/util/ArrayList;
invoke-virtual {v3}, Ljava/util/ArrayList;->size()I
move-result v2
.line 516
.local v2, "numNodes":I
const/4 v0, 0x0
.local v0, "i":I
:goto_0
if-ge v0, v2, :cond_0
.line 517
iget-object v3, p0, Lcom/nineoldandroids/animation/AnimatorSet$1;->val$nodesToStart:Ljava/util/ArrayList;
invoke-virtual {v3, v0}, Ljava/util/ArrayList;->get(I)Ljava/lang/Object;
move-result-object v1
check-cast v1, Lcom/nineoldandroids/animation/AnimatorSet$Node;
.line 518
.local v1, "node":Lcom/nineoldandroids/animation/AnimatorSet$Node;
iget-object v3, v1, Lcom/nineoldandroids/animation/AnimatorSet$Node;->animation:Lcom/nineoldandroids/animation/Animator;
invoke-virtual {v3}, Lcom/nineoldandroids/animation/Animator;->start()V
.line 519
iget-object v3, p0, Lcom/nineoldandroids/animation/AnimatorSet$1;->this$0:Lcom/nineoldandroids/animation/AnimatorSet;
# getter for: Lcom/nineoldandroids/animation/AnimatorSet;->mPlayingSet:Ljava/util/ArrayList;
invoke-static {v3}, Lcom/nineoldandroids/animation/AnimatorSet;->access$000(Lcom/nineoldandroids/animation/AnimatorSet;)Ljava/util/ArrayList;
move-result-object v3
iget-object v4, v1, Lcom/nineoldandroids/animation/AnimatorSet$Node;->animation:Lcom/nineoldandroids/animation/Animator;
invoke-virtual {v3, v4}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
.line 516
add-int/lit8 v0, v0, 0x1
goto :goto_0
.line 522
.end local v0 # "i":I
.end local v1 # "node":Lcom/nineoldandroids/animation/AnimatorSet$Node;
.end local v2 # "numNodes":I
:cond_0
return-void
.end method
| {
"content_hash": "859d3fc1b981c70e8fde10a0b76f0ea5",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 145,
"avg_line_length": 30.330645161290324,
"alnum_prop": 0.7085881414517415,
"repo_name": "x5y/SparkNZ-Xposed",
"id": "4dea22fb30ffdc1be8a7355af46dafa959eef3ab",
"size": "3761",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TelecomApp_Decompiled/smali/com/nineoldandroids/animation/AnimatorSet$1.smali",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2972"
}
],
"symlink_target": ""
} |
'''
Hartree-Fock for periodic systems at a single k-point
See Also:
pyscf.pbc.scf.khf.py : Hartree-Fock for periodic systems with k-point sampling
'''
import sys
import numpy as np
import h5py
from pyscf.scf import hf as mol_hf
from pyscf import lib
from pyscf.lib import logger
from pyscf.data import nist
from pyscf.pbc import gto
from pyscf.pbc import tools
from pyscf.pbc.gto import ecp
from pyscf.pbc.gto.pseudo import get_pp
from pyscf.pbc.scf import chkfile # noqa
from pyscf.pbc.scf import addons
from pyscf.pbc import df
from pyscf.pbc.scf.rsjk import RangeSeparatedJKBuilder
from pyscf.pbc.lib.kpts_helper import gamma_point
from pyscf import __config__
def get_ovlp(cell, kpt=np.zeros(3)):
'''Get the overlap AO matrix.
'''
# Avoid pbcopt's prescreening in the lattice sum, for better accuracy
s = cell.pbc_intor('int1e_ovlp', hermi=0, kpts=kpt,
pbcopt=lib.c_null_ptr())
s = lib.asarray(s)
hermi_error = abs(s - np.rollaxis(s.conj(), -1, -2)).max()
if hermi_error > cell.precision and hermi_error > 1e-12:
logger.warn(cell, '%.4g error found in overlap integrals. '
'cell.precision or cell.rcut can be adjusted to '
'improve accuracy.', hermi_error)
cond = np.max(lib.cond(s))
if cond * cell.precision > 1e2:
prec = 1e2 / cond
rmin = max([cell.bas_rcut(ib, prec) for ib in range(cell.nbas)])
if cell.rcut < rmin:
logger.warn(cell, 'Singularity detected in overlap matrix. '
'Integral accuracy may be not enough.\n '
'You can adjust cell.precision or cell.rcut to '
'improve accuracy. Recommended values are\n '
'cell.precision = %.2g or smaller.\n '
'cell.rcut = %.4g or larger.', prec, rmin)
return s
def get_hcore(cell, kpt=np.zeros(3)):
'''Get the core Hamiltonian AO matrix.
'''
hcore = get_t(cell, kpt)
if cell.pseudo:
hcore += get_pp(cell, kpt)
else:
hcore += get_nuc(cell, kpt)
if len(cell._ecpbas) > 0:
hcore += ecp.ecp_int(cell, kpt)
return hcore
def get_t(cell, kpt=np.zeros(3)):
'''Get the kinetic energy AO matrix.
'''
return cell.pbc_intor('int1e_kin', hermi=1, kpts=kpt)
def get_nuc(cell, kpt=np.zeros(3)):
'''Get the bare periodic nuc-el AO matrix, with G=0 removed.
See Martin (12.16)-(12.21).
'''
return df.FFTDF(cell).get_nuc(kpt)
def get_j(cell, dm, hermi=1, vhfopt=None, kpt=np.zeros(3), kpts_band=None):
'''Get the Coulomb (J) AO matrix for the given density matrix.
Args:
dm : ndarray or list of ndarrays
A density matrix or a list of density matrices
Kwargs:
hermi : int
Whether J, K matrix is hermitian
| 0 : no hermitian or symmetric
| 1 : hermitian
| 2 : anti-hermitian
vhfopt :
A class which holds precomputed quantities to optimize the
computation of J, K matrices
kpt : (3,) ndarray
The "inner" dummy k-point at which the DM was evaluated (or
sampled).
kpts_band : (3,) ndarray or (*,3) ndarray
An arbitrary "band" k-point at which J is evaluated.
Returns:
The function returns one J matrix, corresponding to the input
density matrix (both order and shape).
'''
return df.FFTDF(cell).get_jk(dm, hermi, kpt, kpts_band, with_k=False)[0]
def get_jk(mf, cell, dm, hermi=1, vhfopt=None, kpt=np.zeros(3),
kpts_band=None, with_j=True, with_k=True, omega=None, **kwargs):
'''Get the Coulomb (J) and exchange (K) AO matrices for the given density matrix.
Args:
dm : ndarray or list of ndarrays
A density matrix or a list of density matrices
Kwargs:
hermi : int
Whether J, K matrix is hermitian
| 0 : no hermitian or symmetric
| 1 : hermitian
| 2 : anti-hermitian
vhfopt :
A class which holds precomputed quantities to optimize the
computation of J, K matrices
kpt : (3,) ndarray
The "inner" dummy k-point at which the DM was evaluated (or
sampled).
kpts_band : (3,) ndarray or (*,3) ndarray
An arbitrary "band" k-point at which J and K are evaluated.
Returns:
The function returns one J and one K matrix, corresponding to the input
density matrix (both order and shape).
'''
return df.FFTDF(cell).get_jk(dm, hermi, kpt, kpts_band, with_j, with_k,
omega, exxdiv=mf.exxdiv)
def get_bands(mf, kpts_band, cell=None, dm=None, kpt=None):
'''Get energy bands at the given (arbitrary) 'band' k-points.
Returns:
mo_energy : (nmo,) ndarray or a list of (nmo,) ndarray
Bands energies E_n(k)
mo_coeff : (nao, nmo) ndarray or a list of (nao,nmo) ndarray
Band orbitals psi_n(k)
'''
if cell is None: cell = mf.cell
if dm is None: dm = mf.make_rdm1()
if kpt is None: kpt = mf.kpt
kpts_band = np.asarray(kpts_band)
single_kpt_band = (getattr(kpts_band, 'ndim', None) == 1)
kpts_band = kpts_band.reshape(-1,3)
fock = mf.get_hcore(cell, kpts_band)
fock = fock + mf.get_veff(cell, dm, kpt=kpt, kpts_band=kpts_band)
s1e = mf.get_ovlp(cell, kpts_band)
nkpts = len(kpts_band)
mo_energy = []
mo_coeff = []
for k in range(nkpts):
e, c = mf.eig(fock[k], s1e[k])
mo_energy.append(e)
mo_coeff.append(c)
if single_kpt_band:
mo_energy = mo_energy[0]
mo_coeff = mo_coeff[0]
return mo_energy, mo_coeff
def init_guess_by_chkfile(cell, chkfile_name, project=None, kpt=None):
'''Read the HF results from checkpoint file, then project it to the
basis defined by ``cell``
Returns:
Density matrix, (nao,nao) ndarray
'''
from pyscf.pbc.scf import uhf
dm = uhf.init_guess_by_chkfile(cell, chkfile_name, project, kpt)
return dm[0] + dm[1]
get_fock = mol_hf.get_fock
get_occ = mol_hf.get_occ
get_grad = mol_hf.get_grad
make_rdm1 = mol_hf.make_rdm1
energy_elec = mol_hf.energy_elec
def dip_moment(cell, dm, unit='Debye', verbose=logger.NOTE,
grids=None, rho=None, kpt=np.zeros(3), origin=None):
''' Dipole moment in the cell (is it well defined)?
Args:
cell : an instance of :class:`Cell`
dm (ndarray) : density matrix
Return:
A list: the dipole moment on x, y and z components
'''
from pyscf.pbc import tools
from pyscf.pbc.dft import gen_grid
from pyscf.pbc.dft import numint
if cell.dimension != 3:
# raise NotImplementedError
logger.warn(cell, 'Dipole moment for low-dimension system is not supported.')
return np.zeros(3)
log = logger.new_logger(cell, verbose)
a = cell.lattice_vectors()
b = np.linalg.inv(a).T
if grids is None:
grids = gen_grid.UniformGrids(cell)
#? FIXME: Less requirements on the density accuracy.
#ke_cutoff = gto.estimate_ke_cutoff(cell, 1e-5)
#grids.mesh = tools.cutoff_to_mesh(a, ke_cutoff)
if rho is None:
rho = numint.NumInt().get_rho(cell, dm, grids, kpt, cell.max_memory)
if origin is None:
origin = _search_dipole_gauge_origin(cell, grids, rho, log)
# Move the cell to the position around the origin.
def shift_grids(r):
r_frac = lib.dot(r - origin, b.T)
# Grids on the boundary (r_frac == +/-0.5) of the new cell may lead to
# unbalanced contributions to the dipole moment. Exclude them from the
# dipole and quadrupole
r_frac[r_frac== 0.5] = 0
r_frac[r_frac==-0.5] = 0
r_frac[r_frac > 0.5] -= 1
r_frac[r_frac <-0.5] += 1
r = lib.dot(r_frac, a)
return r
r = shift_grids(grids.coords)
e_dip = np.einsum('g,g,gx->x', rho, grids.weights, r)
charges = cell.atom_charges()
r = shift_grids(cell.atom_coords())
nuc_dip = np.einsum('g,gx->x', charges, r)
dip = nuc_dip - e_dip
if unit.upper() == 'DEBYE':
dip *= nist.AU2DEBYE
log.note('Dipole moment(X, Y, Z, Debye): %8.5f, %8.5f, %8.5f', *dip)
else:
log.note('Dipole moment(X, Y, Z, A.U.): %8.5f, %8.5f, %8.5f', *dip)
return dip
def _search_dipole_gauge_origin(cell, grids, rho, log):
'''Optimize the position of the unit cell in crystal. With a proper unit
cell, the nuclear charge center and the electron density center are at the
same point. This function returns the origin of such unit cell.
'''
from pyscf.pbc.dft import gen_grid
a = cell.lattice_vectors()
b = np.linalg.inv(a).T
charges = cell.atom_charges()
coords = cell.atom_coords()
origin = np.einsum('i,ix->x', charges, coords) / charges.sum()
log.debug1('Initial guess of origin center %s', origin)
nelec = np.dot(rho, grids.weights)
# The dipole moment in the crystal is not uniquely defined. Depending on
# the position and the shape of the unit cell, the value of dipole moment
# can be very different. The optimization below searches the boundary of
# cell inside which the nuclear charge center and electron density charge
# center locate at the same point. The gauge origin will be chosen at the
# center of unit cell.
if (cell.dimension == 3 and
# For orthogonal lattice only
abs(np.diag(a.diagonal())).max() and
isinstance(grids, gen_grid.UniformGrids)):
gridxyz = grids.coords.T.reshape(3, *grids.mesh)
gridbase = (gridxyz[0,:,0,0], gridxyz[1,0,:,0], gridxyz[2,0,0,:])
wxyz = grids.weights.reshape(grids.mesh)
rhoxyz = rho.reshape(grids.mesh)
def search_orig(ix, origin):
nx = grids.mesh[ix]
Lx = a[ix,ix]
g = gridbase[ix] - origin
g_frac = (g * b[ix,ix]).round(6)
g[g_frac == .5] = 0
g[g_frac ==-.5] = 0
g[g_frac > .5] -= Lx
g[g_frac < -.5] += Lx
meanx = np.einsum('xyz,xyz->'+('xyz'[ix]), rhoxyz, wxyz) / nelec
ex = meanx * g
r_nuc = coords[:,ix] - origin
r_frac = (r_nuc * b[ix,ix]).round(6)
r_nuc[r_frac == .5] = 0
r_nuc[r_frac ==-.5] = 0
r_nuc[r_frac > .5] -= Lx
r_nuc[r_frac < -.5] += Lx
nuc_dip = np.dot(charges, r_nuc) / charges.sum()
# ex.sum() ~ electron dipole wrt the given origin
dipx = nuc_dip - ex.sum()
g = gridbase[ix] - origin
sorted_meanx = np.hstack((meanx[g >= Lx/2],
meanx[(g < Lx/2) & (g >= -Lx/2)],
meanx[g < -Lx/2]))
if abs(dipx) < 1e-3:
offx = 0
elif dipx > 0:
# To cancel the positive dipole, move electrons to the right side
rcum_dip = np.append(0, np.cumsum(sorted_meanx * Lx))
idx = np.where(rcum_dip > dipx)[0][0]
dx = (rcum_dip[idx] - dipx) / (rcum_dip[idx] - rcum_dip[idx-1])
offx = (idx - dx) * Lx/nx
else:
# To cancel the negative dipole, move electrons to the left side
lcum_dip = np.append(0, np.cumsum(sorted_meanx[::-1] * Lx))
idx = np.where(lcum_dip > -dipx)[0][0]
dx = (lcum_dip[idx] - -dipx) / (lcum_dip[idx] - lcum_dip[idx-1])
offx = -(idx - dx) * Lx/nx
return origin + offx
wbar = grids.weights[0]**(1./3)
for i in range(4):
orig_last = origin
origin[0] = search_orig(0, origin[0])
origin[1] = search_orig(1, origin[1])
origin[2] = search_orig(2, origin[2])
if abs(origin - orig_last).max() < wbar:
break
log.debug1('iter %d: origin %s', i, origin)
else:
# If the grids are non-cubic grids, regenerating the grids is expensive if
# the position or the shape of the unit cell is changed. The position of
# the unit cell is not optimized. The gauge origin is set to the nuclear
# charge center of the original unit cell.
pass
return origin
def get_rho(mf, dm=None, grids=None, kpt=None):
'''Compute density in real space
'''
from pyscf.pbc.dft import gen_grid
from pyscf.pbc.dft import numint
if dm is None:
dm = mf.make_rdm1()
if getattr(dm, 'ndim', None) != 2: # UHF
dm = dm[0] + dm[1]
if grids is None:
grids = gen_grid.UniformGrids(mf.cell)
if kpt is None:
kpt = mf.kpt
ni = numint.NumInt()
return ni.get_rho(mf.cell, dm, grids, kpt, mf.max_memory)
def _dip_correction(mf):
'''Makov-Payne corrections for charged systems.'''
from pyscf.pbc import tools
from pyscf.pbc.dft import gen_grid
log = logger.new_logger(mf)
cell = mf.cell
a = cell.lattice_vectors()
b = np.linalg.inv(a).T
grids = gen_grid.UniformGrids(cell)
ke_cutoff = gto.estimate_ke_cutoff(cell, 1e-5)
grids.mesh = tools.cutoff_to_mesh(a, ke_cutoff)
dm = mf.make_rdm1()
rho = mf.get_rho(dm, grids, mf.kpt)
origin = _search_dipole_gauge_origin(cell, grids, rho, log)
def shift_grids(r):
r_frac = lib.dot(r - origin, b.T)
# Grids on the boundary (r_frac == +/-0.5) of the new cell may lead to
# unbalanced contributions to the dipole moment. Exclude them from the
# dipole and quadrupole
r_frac[r_frac== 0.5] = 0
r_frac[r_frac==-0.5] = 0
r_frac[r_frac > 0.5] -= 1
r_frac[r_frac <-0.5] += 1
r = lib.dot(r_frac, a)
return r
# SC BCC FCC
madelung = (-2.83729747948, -3.63923344951, -4.58486207411)
vol = cell.vol
L = vol ** (1./3)
chg = cell.charge
# epsilon is the dielectric constant of the system. For systems
# surrounded by vacuum, epsilon = 1.
epsilon = 1
# Energy correction of point charges of a simple cubic lattice.
de_mono = - chg**2 * np.array(madelung) / (2 * L * epsilon)
# dipole energy correction
r_e = shift_grids(grids.coords)
r_nuc = shift_grids(cell.atom_coords())
charges = cell.atom_charges()
e_dip = np.einsum('g,g,gx->x', rho, grids.weights, r_e)
nuc_dip = np.einsum('g,gx->x', charges, r_nuc)
dip = nuc_dip - e_dip
de_dip = -2.*np.pi/(3*cell.vol) * np.linalg.norm(dip)**2
# quadrupole energy correction
if abs(a - np.eye(3)*L).max() > 1e-5:
logger.warn(mf, 'System is not cubic cell. Quadrupole energy '
'correction is inaccurate since it is developed based on '
'cubic cell.')
e_quad = np.einsum('g,g,gx,gx->', rho, grids.weights, r_e, r_e)
nuc_quad = np.einsum('g,gx,gx->', charges, r_nuc, r_nuc)
quad = nuc_quad - e_quad
de_quad = 2.*np.pi/(3*cell.vol) * quad
de = de_mono + de_dip + de_quad
return de_mono, de_dip, de_quad, de
def makov_payne_correction(mf):
'''Makov-Payne correction (Phys. Rev. B, 51, 4014)
'''
cell = mf.cell
logger.note(mf, 'Makov-Payne correction for charged 3D PBC systems')
# PRB 51 (1995), 4014
# PRB 77 (2008), 115139
if cell.dimension != 3:
logger.warn(mf, 'Correction for low-dimension PBC systems'
'is not available.')
return 0
de_mono, de_dip, de_quad, de = _dip_correction(mf)
if mf.verbose >= logger.NOTE:
write = mf.stdout.write
write('Corrections (AU)\n')
write(' Monopole Dipole Quadrupole total\n')
write('SC %12.8f %12.8f %12.8f %12.8f\n' %
(de_mono[0], de_dip , de_quad , de[0]))
write('BCC %12.8f %12.8f %12.8f %12.8f\n' %
(de_mono[1], de_dip , de_quad , de[1]))
write('FCC %12.8f %12.8f %12.8f %12.8f\n' %
(de_mono[2], de_dip , de_quad , de[2]))
return de
class SCF(mol_hf.SCF):
'''SCF base class adapted for PBCs.
Attributes:
kpt : (3,) ndarray
The AO k-point in Cartesian coordinates, in units of 1/Bohr.
exxdiv : str
Exchange divergence treatment, can be one of
| None : ignore G=0 contribution in exchange
| 'ewald' : Ewald probe charge correction [JCP 122, 234102 (2005); DOI:10.1063/1.1926272]
with_df : density fitting object
Default is the FFT based DF model. For all-electron calculation,
MDF model is favored for better accuracy. See also :mod:`pyscf.pbc.df`.
direct_scf : bool
When this flag is set to true, the J/K matrices will be computed
directly through the underlying with_df methods. Otherwise,
depending the available memory, the 4-index integrals may be cached
and J/K matrices are computed based on the 4-index integrals.
'''
direct_scf = getattr(__config__, 'pbc_scf_SCF_direct_scf', False)
def __init__(self, cell, kpt=np.zeros(3),
exxdiv=getattr(__config__, 'pbc_scf_SCF_exxdiv', 'ewald')):
if not cell._built:
sys.stderr.write('Warning: cell.build() is not called in input\n')
cell.build()
self.cell = cell
mol_hf.SCF.__init__(self, cell)
self.with_df = df.FFTDF(cell)
# Range separation JK builder
self.rsjk = None
self.exxdiv = exxdiv
self.kpt = kpt
self.conv_tol = cell.precision * 10
self._keys = self._keys.union(['cell', 'exxdiv', 'with_df', 'rsjk'])
@property
def kpt(self):
if 'kpt' in self.__dict__:
# To handle the attribute kpt loaded from chkfile
self.kpt = self.__dict__.pop('kpt')
return self.with_df.kpts.reshape(3)
@kpt.setter
def kpt(self, x):
self.with_df.kpts = np.reshape(x, (-1, 3))
if self.rsjk:
self.rsjk.kpts = self.with_df.kpts
def build(self, cell=None):
if 'kpt' in self.__dict__:
# To handle the attribute kpt loaded from chkfile
self.kpt = self.__dict__.pop('kpt')
if self.rsjk:
if not np.all(self.rsjk.kpts == self.kpt):
self.rsjk = self.rsjk.__class__(cell, self.kpt.reshape(1,3))
self.rsjk.build(direct_scf_tol=self.direct_scf_tol)
if self.verbose >= logger.WARN:
self.check_sanity()
return self
def reset(self, cell=None):
'''Reset cell and relevant attributes associated to the old cell object'''
if cell is not None:
self.cell = cell
self.mol = cell # used by hf kernel
self.with_df.reset(cell)
return self
def dump_flags(self, verbose=None):
mol_hf.SCF.dump_flags(self, verbose)
logger.info(self, '******** PBC SCF flags ********')
logger.info(self, 'kpt = %s', self.kpt)
logger.info(self, 'Exchange divergence treatment (exxdiv) = %s', self.exxdiv)
cell = self.cell
if ((cell.dimension >= 2 and cell.low_dim_ft_type != 'inf_vacuum') and
isinstance(self.exxdiv, str) and self.exxdiv.lower() == 'ewald'):
madelung = tools.pbc.madelung(cell, [self.kpt])
logger.info(self, ' madelung (= occupied orbital energy shift) = %s', madelung)
logger.info(self, ' Total energy shift due to Ewald probe charge'
' = -1/2 * Nelec*madelung = %.12g',
madelung*cell.nelectron * -.5)
if getattr(self, 'smearing_method', None) is not None:
logger.info(self, 'Smearing method = %s', self.smearing_method)
logger.info(self, 'DF object = %s', self.with_df)
if not getattr(self.with_df, 'build', None):
# .dump_flags() is called in pbc.df.build function
self.with_df.dump_flags(verbose)
return self
def check_sanity(self):
mol_hf.SCF.check_sanity(self)
self.with_df.check_sanity()
if (isinstance(self.exxdiv, str) and self.exxdiv.lower() != 'ewald' and
isinstance(self.with_df, df.df.DF)):
logger.warn(self, 'exxdiv %s is not supported in DF or MDF',
self.exxdiv)
return self
def get_hcore(self, cell=None, kpt=None):
if cell is None: cell = self.cell
if kpt is None: kpt = self.kpt
if cell.pseudo:
nuc = self.with_df.get_pp(kpt)
else:
nuc = self.with_df.get_nuc(kpt)
if len(cell._ecpbas) > 0:
nuc += ecp.ecp_int(cell, kpt)
return nuc + cell.pbc_intor('int1e_kin', 1, 1, kpt)
def get_ovlp(self, cell=None, kpt=None):
if cell is None: cell = self.cell
if kpt is None: kpt = self.kpt
return get_ovlp(cell, kpt)
def get_jk(self, cell=None, dm=None, hermi=1, kpt=None, kpts_band=None,
with_j=True, with_k=True, omega=None, **kwargs):
r'''Get Coulomb (J) and exchange (K) following :func:`scf.hf.RHF.get_jk_`.
for particular k-point (kpt).
When kpts_band is given, the J, K matrices on kpts_band are evaluated.
J_{pq} = \sum_{rs} (pq|rs) dm[s,r]
K_{pq} = \sum_{rs} (pr|sq) dm[r,s]
where r,s are orbitals on kpt. p and q are orbitals on kpts_band
if kpts_band is given otherwise p and q are orbitals on kpt.
'''
if cell is None: cell = self.cell
if dm is None: dm = self.make_rdm1()
if kpt is None: kpt = self.kpt
cpu0 = (logger.process_clock(), logger.perf_counter())
dm = np.asarray(dm)
nao = dm.shape[-1]
if (not omega and kpts_band is None and
# TODO: generate AO integrals with rsjk algorithm
not self.rsjk and
(self.exxdiv == 'ewald' or not self.exxdiv) and
(self._eri is not None or cell.incore_anyway or
(not self.direct_scf and self._is_mem_enough()))):
if self._eri is None:
logger.debug(self, 'Building PBC AO integrals incore')
self._eri = self.with_df.get_ao_eri(kpt, compact=True)
vj, vk = mol_hf.dot_eri_dm(self._eri, dm, hermi, with_j, with_k)
if with_k and self.exxdiv == 'ewald':
from pyscf.pbc.df.df_jk import _ewald_exxdiv_for_G0
# G=0 is not inculded in the ._eri integrals
_ewald_exxdiv_for_G0(self.cell, kpt, dm.reshape(-1,nao,nao),
vk.reshape(-1,nao,nao))
elif self.rsjk:
vj, vk = self.rsjk.get_jk(dm.reshape(-1,nao,nao), hermi, kpt, kpts_band,
with_j, with_k, omega, exxdiv=self.exxdiv)
else:
vj, vk = self.with_df.get_jk(dm.reshape(-1,nao,nao), hermi, kpt, kpts_band,
with_j, with_k, omega, exxdiv=self.exxdiv)
if with_j:
vj = _format_jks(vj, dm, kpts_band)
if with_k:
vk = _format_jks(vk, dm, kpts_band)
logger.timer(self, 'vj and vk', *cpu0)
return vj, vk
def get_j(self, cell=None, dm=None, hermi=1, kpt=None, kpts_band=None,
omega=None):
r'''Compute J matrix for the given density matrix and k-point (kpt).
When kpts_band is given, the J matrices on kpts_band are evaluated.
J_{pq} = \sum_{rs} (pq|rs) dm[s,r]
where r,s are orbitals on kpt. p and q are orbitals on kpts_band
if kpts_band is given otherwise p and q are orbitals on kpt.
'''
return self.get_jk(cell, dm, hermi, kpt, kpts_band, with_k=False,
omega=omega)[0]
def get_k(self, cell=None, dm=None, hermi=1, kpt=None, kpts_band=None,
omega=None):
'''Compute K matrix for the given density matrix.
'''
return self.get_jk(cell, dm, hermi, kpt, kpts_band, with_j=False,
omega=omega)[1]
def get_veff(self, cell=None, dm=None, dm_last=0, vhf_last=0, hermi=1,
kpt=None, kpts_band=None):
'''Hartree-Fock potential matrix for the given density matrix.
See :func:`scf.hf.get_veff` and :func:`scf.hf.RHF.get_veff`
'''
if cell is None: cell = self.cell
if dm is None: dm = self.make_rdm1()
if kpt is None: kpt = self.kpt
if self.rsjk and self.direct_scf:
# Enable direct-SCF for real space JK builder
ddm = dm - dm_last
vj, vk = self.get_jk(cell, ddm, hermi, kpt, kpts_band)
vhf = vj - vk * .5
vhf += vhf_last
else:
vj, vk = self.get_jk(cell, dm, hermi, kpt, kpts_band)
vhf = vj - vk * .5
return vhf
def get_jk_incore(self, cell=None, dm=None, hermi=1, kpt=None, omega=None,
**kwargs):
'''Get Coulomb (J) and exchange (K) following :func:`scf.hf.RHF.get_jk_`.
*Incore* version of Coulomb and exchange build only.
Currently RHF always uses PBC AO integrals (unlike RKS), since
exchange is currently computed by building PBC AO integrals.
'''
if omega:
raise NotImplementedError
if cell is None: cell = self.cell
if kpt is None: kpt = self.kpt
if self._eri is None:
self._eri = self.with_df.get_ao_eri(kpt, compact=True)
return self.get_jk(cell, dm, hermi, kpt)
def energy_nuc(self):
return self.cell.energy_nuc()
get_bands = get_bands
get_rho = get_rho
@lib.with_doc(dip_moment.__doc__)
def dip_moment(self, cell=None, dm=None, unit='Debye', verbose=logger.NOTE,
**kwargs):
rho = kwargs.pop('rho', None)
if rho is None:
rho = self.get_rho(dm)
if cell is None:
cell = self.cell
return dip_moment(cell, dm, unit, verbose, rho=rho, kpt=self.kpt, **kwargs)
def _finalize(self):
'''Hook for dumping results and clearing up the object.'''
mol_hf.SCF._finalize(self)
if self.cell.charge != 0:
makov_payne_correction(self)
return self
def get_init_guess(self, cell=None, key='minao'):
if cell is None: cell = self.cell
dm = mol_hf.SCF.get_init_guess(self, cell, key)
dm = normalize_dm_(self, dm)
return dm
def init_guess_by_1e(self, cell=None):
if cell is None: cell = self.cell
if cell.dimension < 3:
logger.warn(self, 'Hcore initial guess is not recommended in '
'the SCF of low-dimensional systems.')
return mol_hf.SCF.init_guess_by_1e(self, cell)
def init_guess_by_chkfile(self, chk=None, project=None, kpt=None):
if chk is None: chk = self.chkfile
if kpt is None: kpt = self.kpt
return init_guess_by_chkfile(self.cell, chk, project, kpt)
def from_chk(self, chk=None, project=None, kpt=None):
return self.init_guess_by_chkfile(chk, project, kpt)
def dump_chk(self, envs):
if self.chkfile:
mol_hf.SCF.dump_chk(self, envs)
with h5py.File(self.chkfile, 'a') as fh5:
fh5['scf/kpt'] = self.kpt
return self
def _is_mem_enough(self):
nao = self.cell.nao_nr()
if abs(self.kpt).sum() < 1e-9:
mem_need = nao**4*8/4/1e6
else:
mem_need = nao**4*16/1e6
return mem_need + lib.current_memory()[0] < self.max_memory*.95
def density_fit(self, auxbasis=None, with_df=None):
from pyscf.pbc.df import df_jk
return df_jk.density_fit(self, auxbasis, with_df=with_df)
def rs_density_fit(self, auxbasis=None, with_df=None):
from pyscf.pbc.df import rsdf_jk
return rsdf_jk.density_fit(self, auxbasis, with_df=with_df)
def mix_density_fit(self, auxbasis=None, with_df=None):
from pyscf.pbc.df import mdf_jk
return mdf_jk.density_fit(self, auxbasis, with_df=with_df)
def sfx2c1e(self):
from pyscf.pbc.x2c import sfx2c1e
return sfx2c1e.sfx2c1e(self)
x2c = x2c1e = sfx2c1e
def to_rhf(self, mf):
'''Convert the input mean-field object to a RHF/ROHF/RKS/ROKS object'''
return addons.convert_to_rhf(mf)
def to_uhf(self, mf):
'''Convert the input mean-field object to a UHF/UKS object'''
return addons.convert_to_uhf(mf)
def to_ghf(self, mf):
'''Convert the input mean-field object to a GHF/GKS object'''
return addons.convert_to_ghf(mf)
def nuc_grad_method(self, *args, **kwargs):
raise NotImplementedError
def jk_method(self, J='FFTDF', K=None):
'''
Set up the schemes to evaluate Coulomb and exchange matrix
FFTDF: planewave density fitting using Fast Fourier Transform
AFTDF: planewave density fitting using analytic Fourier Transform
GDF: Gaussian density fitting
MDF: Gaussian and planewave mix density fitting
RS: range-separation JK builder
RSDF: range-separation density fitting
'''
if K is None:
K = J
if J != K:
raise NotImplementedError('J != K')
if 'DF' in J or 'DF' in K:
if 'DF' in J and 'DF' in K:
assert J == K
else:
df_method = J if 'DF' in J else K
self.with_df = getattr(df, df_method)(self.cell, self.kpt)
# For nuclear attraction
if ('RS' in J or 'RS' in K) and not self.with_df:
self.with_df = df.GDF(self.cell, self.kpt)
if J == 'RS' or K == 'RS':
if not gamma_point(self.kpt):
raise NotImplementedError('Single k-point must be gamma point')
self.rsjk = RangeSeparatedJKBuilder(self.cell, self.kpt)
self.rsjk.verbose = self.verbose
# For nuclear attraction
if J == 'RS' and K == 'RS' and not isinstance(self.with_df, df.GDF):
self.with_df = df.GDF(self.cell, self.kpt)
nuc = self.with_df.__class__.__name__
logger.debug1(self, 'Apply %s for J, %s for K, %s for nuc', J, K, nuc)
return self
class KohnShamDFT:
'''A mock DFT base class
The base class is defined in the pbc.dft.rks module. This class can
be used to verify if an SCF object is an pbc-Hartree-Fock method or an
pbc-DFT method. It should be overwritten by the actual KohnShamDFT class
when loading dft module.
'''
class RHF(SCF, mol_hf.RHF):
stability = mol_hf.RHF.stability
def convert_from_(self, mf):
'''Convert given mean-field object to RHF'''
addons.convert_to_rhf(mf, self)
return self
def _format_jks(vj, dm, kpts_band):
if kpts_band is None:
vj = vj.reshape(dm.shape)
elif kpts_band.ndim == 1: # a single k-point on bands
vj = vj.reshape(dm.shape)
elif getattr(dm, "ndim", 0) == 2:
vj = vj[0]
return vj
def normalize_dm_(mf, dm):
'''
Scale density matrix to make it produce the correct number of electrons.
'''
cell = mf.cell
if isinstance(dm, np.ndarray) and dm.ndim == 2:
ne = np.einsum('ij,ji->', dm, mf.get_ovlp(cell)).real
else:
ne = np.einsum('xij,ji->', dm, mf.get_ovlp(cell)).real
if abs(ne - cell.nelectron).sum() > 1e-7:
logger.debug(mf, 'Big error detected in the electron number '
'of initial guess density matrix (Ne/cell = %g)!\n'
' This can cause huge error in Fock matrix and '
'lead to instability in SCF for low-dimensional '
'systems.\n DM is normalized wrt the number '
'of electrons %s', ne, cell.nelectron)
dm *= cell.nelectron / ne
return dm
| {
"content_hash": "e7779d7963dad2dec75f17ccdd97e7de",
"timestamp": "",
"source": "github",
"line_count": 865,
"max_line_length": 101,
"avg_line_length": 37.15491329479769,
"alnum_prop": 0.5701795326550297,
"repo_name": "sunqm/pyscf",
"id": "e18a753a76826bc697a12e76e25b7d8dee531c53",
"size": "32922",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pyscf/pbc/scf/hf.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2805171"
},
{
"name": "CMake",
"bytes": "19597"
},
{
"name": "Common Lisp",
"bytes": "40515"
},
{
"name": "Dockerfile",
"bytes": "447"
},
{
"name": "Makefile",
"bytes": "6797"
},
{
"name": "Python",
"bytes": "19630497"
},
{
"name": "Roff",
"bytes": "429"
},
{
"name": "Shell",
"bytes": "6564"
}
],
"symlink_target": ""
} |
from unittest import TestCase
from sworkflow.tasks import Task, PythonTask
from sworkflow.tasks.workflow import Workflow, walk, ExitWorkflow
class TaskTestCase(TestCase):
def test_required_attributes(self):
task = Task()
self.assertEqual(task.deps, ())
class WalkTestCase(TestCase):
def test_class_declaration(self):
class T1(Task):
taskname = 'T1'
class T2(Task):
taskname = 'T2'
deps = [T1]
class T3(Task):
taskname = 'T3'
deps = [T2]
class T4(Task):
taskname = 'T4'
deps = [T3, T1]
self.assertEqual(map(type, walk(T4)), [T1, T2, T3, T4])
def test_instance_declaration(self):
t1 = Task(taskname='T1')
t2 = Task(taskname='T2', deps=[t1])
t3 = Task(taskname='T3', deps=[t2])
t4 = Task(taskname='T4', deps=[t3, t1])
self.assertEqual(list(walk(t4)), [t1, t2, t3, t4])
def test_mixed_declaration(self):
t1 = Task(taskname='T1')
class T(Task):
taskname = 'T'
deps = [t1]
t2 = Task(taskname='T2', deps=[T])
t3 = Task(taskname='T3', deps=[t1, t2])
class S(Task):
taskname = 'S'
deps = [T, t1, t3, T]
self.assertEqual([t.taskname for t in walk(S)],
['T1', 'T', 'T2', 'T3', 'S'])
def test_cyclic_reference(self):
t1 = Task(taskname='T1')
t2 = Task(taskname='T2', deps=[t1])
t1.deps = [t2]
self.assertRaises(AssertionError, list, walk(t1))
def test_invalid_task(self):
t1 = Task()
t2 = Task(deps=[t1, None])
self.assertRaises(AssertionError, list, walk(t2))
class WorkflowTestCase(TestCase):
def setUp(self):
self.executed = executed = []
class MockTask(Task):
def execute(self):
executed.append(self)
self.MockTask = MockTask
def test_simple_workflow(self):
t1 = self.MockTask()
st = self.MockTask(deps=[t1])
wf = Workflow(starttask=st)
self.assertEqual(wf.tasks, [(0, t1, False), (1, st, False)])
wf.execute()
self.assertEqual(self.executed, [t1, st])
def test_exclude_tasks_passing_none(self):
t1 = self.MockTask()
st = self.MockTask(deps=[t1])
wf = Workflow(taskname='w1', starttask=st, exclude_tasks=None)
self.assertEqual(wf.tasks, [(0, t1, False), (1, st, False)])
wf.execute()
self.assertEqual(self.executed, [t1, st])
def test_exclude_tasks_by_position(self):
t1 = self.MockTask()
st = self.MockTask(deps=[t1])
wf = Workflow(taskname='w1', starttask=st, exclude_tasks=['1'])
self.assertEqual(wf.tasks, [(0, t1, False), (1, st, True)])
wf.execute()
self.assertEqual(self.executed, [t1])
def test_exclude_tasks_by_classname(self):
class Skipme(self.MockTask):
pass
t1 = self.MockTask()
st = Skipme(deps=[t1])
wf = Workflow(starttask=st, exclude_tasks=['Skipme'])
self.assertEqual(wf.tasks, [(0, t1, False), (1, st, True)])
wf.execute()
self.assertEqual(self.executed, [t1])
def test_include_tasks_passing_none(self):
t1 = self.MockTask()
st = self.MockTask(deps=[t1])
wf = Workflow(taskname='w1', starttask=st, include_tasks=None)
self.assertEqual(wf.tasks, [(0, t1, False), (1, st, False)])
wf.execute()
self.assertEqual(self.executed, [t1, st])
def test_include_tasks_by_position(self):
t1 = self.MockTask()
st = self.MockTask(deps=[t1])
wf = Workflow(taskname='w1', starttask=st, include_tasks=['1'])
self.assertEqual(wf.tasks, [(0, t1, True), (1, st, False)])
wf.execute()
self.assertEqual(self.executed, [st])
def test_include_tasks_by_classname(self):
class IncludeMe(self.MockTask):
pass
t1 = self.MockTask()
st = IncludeMe(deps=[t1])
wf = Workflow(starttask=st, include_tasks=['IncludeMe'])
self.assertEqual(wf.tasks, [(0, t1, True), (1, st, False)])
wf.execute()
self.assertEqual(self.executed, [st])
def test_workflow_used_as_task(self):
t0 = self.MockTask()
t1 = self.MockTask(deps=[t0])
w1 = Workflow(starttask=t1)
t2 = self.MockTask(deps=[w1])
w2 = Workflow(starttask=t2)
self.assertEqual(w2.tasks, [(0, w1, False), (1, t2, False)])
w2.execute()
self.assertEqual(self.executed, [t0, t1, t2])
def test_propagate_task_failure_as_is(self):
class TaskFailed(Exception):
pass
class FailTask(self.MockTask):
def execute(self):
raise TaskFailed
wf = Workflow(starttask=FailTask())
self.assertRaises(TaskFailed, wf.execute)
# fail even across sub workflows
wf = Workflow(starttask=Workflow(starttask=FailTask()))
self.assertRaises(TaskFailed, wf.execute)
def test_exitworkflow(self):
class FailTask(Task):
def execute(self):
raise ExitWorkflow('FailTask', ExitWorkflow.EXIT_CANCELLED)
wf = Workflow(starttask=FailTask())
wf.execute()
# doesn't fail even across sub workflows
wf = Workflow(starttask=Workflow(starttask=FailTask()))
wf.execute()
def create_mock(status):
class MockExitTask(Task):
def execute(self):
raise ExitWorkflow('MockExitTask', status)
return MockExitTask
# doesn't fail, and finish OK
wf = Workflow(starttask=create_mock(ExitWorkflow.EXIT_STOPPED))
wf.execute()
# will fail throwing ExitWorkflow exception
wf = Workflow(starttask=create_mock(ExitWorkflow.EXIT_FAILED))
self.assertRaises(ExitWorkflow, wf.execute)
def test_exitworkflow_pythontask(self):
from subprocess import check_call, CalledProcessError
def create_mock(status):
class MockPyTask(PythonTask):
execargs = []
def _run(self):
check_call(['sh', '-c', 'exit %s' % str(status)])
return MockPyTask()
# Raises EXIT_STOPPED
self.assertRaises(ExitWorkflow, create_mock(ExitWorkflow.EXIT_STOPPED).execute)
# Raises ExitWorkflow with EXIT_CANCELLED status
self.assertRaises(ExitWorkflow, create_mock(ExitWorkflow.EXIT_CANCELLED).execute)
# Raises a ExitWorkflow with EXIT_FAILED status
self.assertRaises(ExitWorkflow, create_mock(ExitWorkflow.EXIT_FAILED).execute)
# Other not registered error, will raise CalledProcessError
self.assertRaises(CalledProcessError, create_mock(255).execute)
def test_template_expansion(self):
# settings and task attributes must be expanded on execute
class MyTask(Task):
foo = 'foo'
bar = 'bar'
@property
def execargs(self):
return [self.foo, self.bar]
task = MyTask(foo='$foo-$xta', bar='$bar')
class MyWorkflow(Workflow):
starttask = task
settings = dict(xta='xta$foo')
# Instanciate workflow with custom params that will be merged with settings
wf = MyWorkflow(params=dict(foo='cof'))
# Add settings after workflow was instanciated
wf.settings['bar'] = 'bar$foo'
# check that tasks weren't expanded til executed
self.assertEqual(task.foo, '$foo-$xta')
self.assertEqual(task.bar, '$bar')
# run workflow and check expanded task attributes
wf.execute()
self.assertEqual(wf.settings, {'foo': 'cof', 'bar': 'bar$foo', 'xta': 'xta$foo'})
self.assertEqual(task.foo, 'cof-xtacof')
self.assertEqual(task.bar, 'barcof')
self.assertEqual(task.execargs, ['cof-xtacof', 'barcof'])
| {
"content_hash": "bb0059aed8204f2ab3e6e6e1003f9ab5",
"timestamp": "",
"source": "github",
"line_count": 239,
"max_line_length": 89,
"avg_line_length": 33.55230125523013,
"alnum_prop": 0.5827409901483975,
"repo_name": "mydeco-dev-team/sworkflow",
"id": "7328da760217158e359853a527b794389ba6c0ad",
"size": "8019",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sworkflow/tests/test_workflow.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Python",
"bytes": "39850"
}
],
"symlink_target": ""
} |
'use strict';
describe('battlrApp.version module', function() {
beforeEach(module('battlrApp.version'));
describe('interpolate filter', function() {
beforeEach(module(function($provide) {
$provide.value('version', 'TEST_VER');
}));
it('should replace VERSION', inject(function(interpolateFilter) {
expect(interpolateFilter('before %VERSION% after')).toEqual('before TEST_VER after');
}));
});
});
| {
"content_hash": "c7f08ccf84d2dfa646852e678459685b",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 91,
"avg_line_length": 28.933333333333334,
"alnum_prop": 0.663594470046083,
"repo_name": "JorgeRuiz/angular-template",
"id": "c00b9a308d3dbe9f954c358ac26f955d0f60cb3d",
"size": "434",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/interpolate-filter.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "366"
},
{
"name": "HTML",
"bytes": "5297"
},
{
"name": "JavaScript",
"bytes": "2740032"
}
],
"symlink_target": ""
} |
<?php
namespace empire\framework\storage;
use empire\framework\storageengine\StorageEngine;
use empire\framework\util\Result;
use empire\framework\util\ArrayResult;
/**
* Provides a simple key value storage.
*
* Depending on the <code>$useTimestamps</code> argument to the constructor, timestamps will be
* stored with each entry. This is required for deleting old values.
*
* @author Tobias Hornberger [tobias.hornberger@falsemirror.de]
*/
class DefaultStorage implements Storage {
/**
* The storage engine instance
*
* @var StorageEngine
*/
private $engine;
/**
* Constructs a new default storage.
*
* @param StorageEngine the storage engine
*/
public function __construct(StorageEngine $engine) {
$this->engine = $engine;
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::getEngine()
*/
public function getEngine() {
return $this->engine;
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::store()
*/
public function store($key, $data, $overwrite = false) {
if($this->engine->exists($key)) {
if($overwrite) {
$this->engine->update($key, $data, true);
return true;
}
return false;
}
else {
$this->engine->store($key, $data);
return true;
}
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::storeAll()
*/
public function storeAll($array) {
$this->engine->storeAll($array);
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::update()
*/
public function update($key, $data, $updateTimestamp = true) {
if($this->engine->exists($key)) {
$this->engine->update($key, $data, $updateTimestamp);
return true;
}
return false;
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::fetch()
*/
public function fetch($key) {
$data = $this->engine->fetch($key);
if($data === null) {
return null;
}
return $data;
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::fetchAll()
*/
public function fetchAll() {
return $this->engine->fetchAll();
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::fetchResult()
*/
public function fetchResult() {
$result = $this->engine->fetchResult();
return $result;
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::exists()
*/
public function exists($key) {
return $this->engine->exists($key);
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::getDate()
*/
public function getDate($key) {
return $this->engine->getDate($key);
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::delete()
*/
public function delete($key) {
return $this->engine->delete($key);
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::deleteOld()
*/
public function deleteOld($limit) {
return $this->engine->deleteOld($limit);
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::flush()
*/
public function flush() {
return $this->engine->flush();
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::remove()
*/
public function remove() {
$this->engine->remove();
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::size()
*/
public function size() {
return $this->engine->size();
}
/*
* (non-PHPdoc) @see \empire\framework\storage\Storage::isEmpty()
*/
public function isEmpty() {
return (boolean) ($this->size() === 0);
}
} | {
"content_hash": "f996dd9a34824fe587312aefa07679fc",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 95,
"avg_line_length": 21.436708860759495,
"alnum_prop": 0.6465899025686448,
"repo_name": "thornberger/empire",
"id": "406cf4fc40eb54b67f5655f468f7a43679e2689e",
"size": "3387",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "framework/storage/DefaultStorage.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "1083569"
},
{
"name": "Smarty",
"bytes": "837"
}
],
"symlink_target": ""
} |
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
| {
"content_hash": "1a1d102d56e3753e6ecd248f34dae5a7",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 90,
"avg_line_length": 31.6,
"alnum_prop": 0.6582278481012658,
"repo_name": "wangzhong1986/wangzhong",
"id": "1abce9c6e8dd45c69b15c8946e21b1823dfc57d2",
"size": "347",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "firstProjectOnGitHub/firstProjectOnGitHub/main.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "5967"
}
],
"symlink_target": ""
} |
import sys
import PyQt4
from PyQt4 import QtCore, QtGui
import argparse
import decimal
from decimal import Decimal
import traderthread
import mainwindow
import tradeapi
app = QtGui.QApplication(sys.argv)
tradeApi = None
exchangeName = ''
parser = argparse.ArgumentParser()
parser.add_argument("--exchange", choices=['btce', 'bitfinex', 'dummy'], default='btce')
parser.add_argument("--arb-coin", choices=['ltc', 'nmc', 'ppc', 'nvc'], default='ltc', dest='arb_coin')
parser.add_argument("--refresh-timeout", type=int, default=100, dest='refresh_timeout')
parser.add_argument("--trade-interval", type=int, default=10000, dest='trade_interval')
parser.add_argument("--usd-to-spend", type=Decimal, default=Decimal('20'), dest='usd_to_spend')
parser.add_argument("--btc-to-spend", type=Decimal, default=Decimal('0.02'), dest='btc_to_spend')
parser.add_argument("--arb-coin-to-spend", type=Decimal, default=Decimal('1'), dest='arb_coin_to_spend')
parser.add_argument("--min-profit", type=Decimal, default=Decimal('0.01'), dest='min_profit')
parser.add_argument("--max-lag", type=int, default=1000, dest='max_lag')
parser.add_argument("--greedy-percent", type=Decimal, default=0, dest='greedy_percent')
args = parser.parse_args()
exchangeName = args.exchange
coin = args.arb_coin
timeout = args.refresh_timeout
with tradeapi.CreateTradeApi(exchangeName, ['keyfile.txt', 'keyfile2.txt', 'keyfile3.txt']) as tradeApi:
mainWindow = mainwindow.MainWindow(tradeApi.Name())
mainWindow.show()
traderThread = traderthread.TraderThread(app, tradeApi, 'btcusd', coin+'btc', coin+'usd', timeout, args.trade_interval,
args.usd_to_spend, args.btc_to_spend, args.arb_coin_to_spend, args.min_profit, args.max_lag, args.greedy_percent)
mainWindow.ui.label_sec1.setText(traderThread.p1)
mainWindow.ui.label_sec2.setText(traderThread.p2)
mainWindow.ui.label_sec3.setText(traderThread.p3)
traderThread.updateData.connect(mainWindow.receiveUpdate, QtCore.Qt.QueuedConnection)
traderThread.updateLag.connect(mainWindow.receiveLag, QtCore.Qt.QueuedConnection)
app.aboutToQuit.connect(traderThread.quit)
traderThread.start()
sys.exit(app.exec_()) | {
"content_hash": "4f23ea0f9ab46eaa3278ad947802c34f",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 121,
"avg_line_length": 42.1764705882353,
"alnum_prop": 0.7503486750348675,
"repo_name": "victorshch/pytrader",
"id": "2833072fa80e7ddfc300cbf42c0815577d250cdd",
"size": "2151",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pyarb.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "85853"
}
],
"symlink_target": ""
} |
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::fstream;
using std::max;
using std::string;
using std::vector;
// map reads so we can access reads with mapped[read_id]
void map_reads(vector<Read*>* mapped, vector<Read*>& reads) {
int max_id = -1;
for (auto r: reads) {
max_id = max(max_id, r->getId());
}
mapped->resize(max_id + 1, nullptr);
for (auto r: reads) {
(*mapped)[r->getId()] = r;
}
}
int main(int argc, char **argv) {
cmdline::parser args;
args.add<string>("reads", 'r', "reads file", true);
args.add<string>("overlaps", 'x', "overlaps file", true);
args.add<string>("overlaps_format", 'f', "overlaps file format; supported: afg, mhap", false, "afg");
args.parse_check(argc, argv);
const string format = args.get<string>("overlaps_format");
const string reads_filename = args.get<string>("reads");
const string overlaps_filename = args.get<string>("overlaps");
vector<Overlap*> overlaps, filtered;
vector<Read*> reads;
vector<Read*> reads_mapped;
readAfgReads(reads, reads_filename.c_str());
map_reads(&reads_mapped, reads);
std::cerr << "Read " << reads.size() << " reads" << std::endl;
if (format == "afg") {
readAfgOverlaps(overlaps, overlaps_filename.c_str());
} else if (format == "mhap") {
fstream overlaps_file(overlaps_filename);
MHAP::read_overlaps(overlaps_file, &overlaps);
overlaps_file.close();
}
for (auto o: overlaps) {
const auto a = o->getA();
const auto b = o->getB();
assert(reads_mapped[a] != nullptr);
assert(reads_mapped[b] != nullptr);
}
filterContainedOverlaps(filtered, overlaps, reads_mapped, true);
for (const auto o : filtered) {
cout << *o;
}
for (auto r: reads) {
delete r;
}
for (auto o: overlaps) {
delete o;
}
cerr << "Written " << filtered.size() << " overlaps. Ratio: " << filtered.size() / (1.0 * overlaps.size()) << endl;
return 0;
}
| {
"content_hash": "78deb076210170da4d3e6fa0a6b55b64",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 117,
"avg_line_length": 25.96,
"alnum_prop": 0.6255778120184899,
"repo_name": "mariokostelac/assembly-tools",
"id": "834c723cf3389ab53fa5e09fdb9481a4b01b2067",
"size": "2139",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/filter-contained/main.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "27940"
},
{
"name": "Makefile",
"bytes": "2219"
},
{
"name": "Python",
"bytes": "2503"
},
{
"name": "Shell",
"bytes": "1401"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.