code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
package domain
import (
"flag"
)
type Config struct {
DockerAPIEndpoint string
VulcandAPIEndpoint string
HostIP string
}
func (config *Config) InstallFlags() {
flag.StringVar(&config.DockerAPIEndpoint, "d", "/var/run/docker.sock", "Docker API endpoint")
flag.StringVar(&config.VulcandAPIEndpoint, "v", "172.17.8.101:8182", "Vulcand API endpoint")
flag.StringVar(&config.HostIP, "h", "172.17.8.101", "Host's external facing ip")
}
|
acazau/dvs
|
domain/common.go
|
GO
|
mit
| 453
|
FROM alpine:3.9
ARG BUILD_DATE
ARG VCS_REF
LABEL org.label-schema.build-date=$BUILD_DATE \
org.label-schema.vcs-url="https://github.com/phpearth/docker-php.git" \
org.label-schema.vcs-ref=$VCS_REF \
org.label-schema.schema-version="1.0" \
org.label-schema.vendor="PHP.earth" \
org.label-schema.name="docker-php" \
org.label-schema.description="Docker For PHP Developers - Docker image with PHP 7.3, OpenLiteSpeed, and Alpine" \
org.label-schema.url="https://github.com/phpearth/docker-php"
# PHP_INI_DIR to be symmetrical with official php docker image
ENV PHP_INI_DIR /etc/php/7.3
# When using Composer, disable the warning about running commands as root/super user
ENV COMPOSER_ALLOW_SUPERUSER=1
# Persistent runtime dependencies
ARG DEPS="\
curl \
ca-certificates \
runit \
php7.3 \
php7.3-phar \
php7.3-bcmath \
php7.3-calendar \
php7.3-mbstring \
php7.3-exif \
php7.3-ftp \
php7.3-openssl \
php7.3-zip \
php7.3-sysvsem \
php7.3-sysvshm \
php7.3-sysvmsg \
php7.3-shmop \
php7.3-sockets \
php7.3-zlib \
php7.3-bz2 \
php7.3-curl \
php7.3-simplexml \
php7.3-xml \
php7.3-opcache \
php7.3-dom \
php7.3-xmlreader \
php7.3-xmlwriter \
php7.3-tokenizer \
php7.3-ctype \
php7.3-session \
php7.3-fileinfo \
php7.3-iconv \
php7.3-json \
php7.3-posix \
php7.3-litespeed \
litespeed \
"
# PHP.earth Alpine repository for better developer experience
ADD https://repos.php.earth/alpine/phpearth.rsa.pub /etc/apk/keys/phpearth.rsa.pub
RUN set -x \
&& echo "https://repos.php.earth/alpine/v3.9" >> /etc/apk/repositories \
&& apk add --no-cache $DEPS \
&& ln -sf /dev/stdout /var/lib/litespeed/logs/access.log \
&& ln -sf /dev/stderr /var/lib/litespeed/logs/error.log
COPY tags/litespeed /
EXPOSE 8088 7080
CMD ["/sbin/runit-wrapper"]
|
php-earth/docker-php
|
docker/7.3-litespeed.Dockerfile
|
Dockerfile
|
mit
| 2,070
|
<?php
namespace rock\sanitize\rules;
class RemoveTags extends Rule
{
/**
* @inheritdoc
*/
public function sanitize($input)
{
return is_string($input) ? filter_var($input, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES) : $input;
}
}
|
romeOz/rock-sanitize
|
src/rules/RemoveTags.php
|
PHP
|
mit
| 276
|
/*
* This file is part of the UnTech Editor Suite.
* Copyright (c) 2016 - 2021, Marcus Rowe <undisbeliever@gmail.com>.
* Distributed under The MIT License: https://opensource.org/licenses/MIT
*/
#pragma once
#include "imgui.h"
namespace UnTech::Gui {
class AnimationTimer {
private:
float _time;
static_assert(std::is_same_v<decltype(_time), decltype(ImGuiIO::DeltaTime)>);
public:
bool active;
bool ntscRegion;
public:
AnimationTimer()
: _time(0)
, active(false)
, ntscRegion(true)
{
}
void reset()
{
active = false;
_time = 0;
}
void start()
{
reset();
active = true;
}
void stop() { active = false; }
void playPause() { active = !active; }
template <typename Function>
void process(Function onNextFrame)
{
if (!active) {
return;
}
_time += ImGui::GetIO().DeltaTime;
if (_time > 1.0f) {
_time = 0;
active = false;
}
const float _frameTime = ntscRegion ? 1.0f / 60 : 1.0f / 50;
while (_time > _frameTime) {
_time -= _frameTime;
onNextFrame();
}
}
};
class SingleAnimationTimer {
private:
static constexpr unsigned TICKS_PER_SECOND = 300;
static constexpr unsigned TICKS_PER_NTSC_FRAME = TICKS_PER_SECOND / 60;
static constexpr unsigned TICKS_PER_PAL_FRAME = TICKS_PER_SECOND / 50;
private:
AnimationTimer _frameTimer;
unsigned _frameCounter;
unsigned _tickCounter;
public:
SingleAnimationTimer()
: _frameTimer()
, _frameCounter(0)
, _tickCounter(0)
{
}
bool isActive() const { return _frameTimer.active; }
void reset()
{
_frameTimer.reset();
_frameCounter = 0;
_tickCounter = 0;
}
void start()
{
reset();
_frameTimer.start();
}
void stop() { _frameTimer.stop(); }
void playPause() { _frameTimer.playPause(); }
template <typename Function>
void process(unsigned animationDelay, Function onNextFrame)
{
_frameTimer.process([&] {
_frameCounter++;
const unsigned nTicks = _frameTimer.ntscRegion ? TICKS_PER_NTSC_FRAME : TICKS_PER_PAL_FRAME;
_tickCounter += nTicks;
if (_tickCounter >= animationDelay) {
_tickCounter = 0;
onNextFrame();
}
});
}
};
class DualAnimationTimer {
private:
static constexpr unsigned TICKS_PER_SECOND = 300;
static constexpr unsigned TICKS_PER_NTSC_FRAME = TICKS_PER_SECOND / 60;
static constexpr unsigned TICKS_PER_PAL_FRAME = TICKS_PER_SECOND / 50;
private:
AnimationTimer _frameTimer;
unsigned _frameCounter;
unsigned _firstCounter;
unsigned _secondCounter;
public:
DualAnimationTimer()
: _frameTimer()
, _frameCounter(0)
, _firstCounter(0)
, _secondCounter(0)
{
}
bool isActive() const { return _frameTimer.active; }
void reset()
{
_frameTimer.reset();
_frameCounter = 0;
_firstCounter = 0;
_secondCounter = 0;
}
void start()
{
reset();
_frameTimer.start();
}
void stop() { _frameTimer.stop(); }
void playPause() { _frameTimer.playPause(); }
template <typename FirstFunction, typename SecondFunction>
void process(unsigned firstAnimationDelay, FirstFunction firstFunction,
unsigned secondAnimationDelay, SecondFunction secondFunction)
{
_frameTimer.process([&] {
_frameCounter++;
const unsigned nTicks = _frameTimer.ntscRegion ? TICKS_PER_NTSC_FRAME : TICKS_PER_PAL_FRAME;
_firstCounter += nTicks;
if (_firstCounter >= firstAnimationDelay) {
_firstCounter = 0;
firstFunction();
}
_secondCounter += nTicks;
if (_secondCounter >= secondAnimationDelay) {
_secondCounter = 0;
secondFunction();
}
});
}
};
}
|
undisbeliever/untech-editor
|
src/gui/animation-timer.h
|
C
|
mit
| 4,153
|
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import Collapse from '../Collapse';
import withStyles from '../styles/withStyles';
export const styles = theme => ({
/* Styles applied to the root element. */
root: {
marginTop: 8,
marginLeft: 12, // half icon
paddingLeft: 8 + 12, // margin + half icon
paddingRight: 8,
borderLeft: `1px solid ${
theme.palette.type === 'light' ? theme.palette.grey[400] : theme.palette.grey[600]
}`,
},
/* Styles applied to the root element if `last={true}` (controlled by `Step`). */
last: {
borderLeft: 'none',
},
/* Styles applied to the Transition component. */
transition: {},
});
const StepContent = React.forwardRef(function StepContent(props, ref) {
const {
active,
alternativeLabel,
children,
classes,
className,
completed,
last,
optional,
orientation,
TransitionComponent = Collapse,
transitionDuration: transitionDurationProp = 'auto',
TransitionProps,
...other
} = props;
if (process.env.NODE_ENV !== 'production') {
if (orientation !== 'vertical') {
console.error(
'Material-UI: <StepContent /> is only designed for use with the vertical stepper.',
);
}
}
let transitionDuration = transitionDurationProp;
if (transitionDurationProp === 'auto' && !TransitionComponent.muiSupportAuto) {
transitionDuration = undefined;
}
return (
<div className={clsx(classes.root, { [classes.last]: last }, className)} ref={ref} {...other}>
<TransitionComponent
in={active}
className={classes.transition}
timeout={transitionDuration}
unmountOnExit
{...TransitionProps}
>
{children}
</TransitionComponent>
</div>
);
});
StepContent.propTypes = {
/**
* @ignore
* Expands the content.
*/
active: PropTypes.bool,
/**
* @ignore
* Set internally by Step when it's supplied with the alternativeLabel prop.
*/
alternativeLabel: PropTypes.bool,
/**
* Step content.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* @ignore
*/
completed: PropTypes.bool,
/**
* @ignore
*/
last: PropTypes.bool,
/**
* @ignore
* Set internally by Step when it's supplied with the optional prop.
*/
optional: PropTypes.bool,
/**
* @ignore
*/
orientation: PropTypes.oneOf(['horizontal', 'vertical']),
/**
* The component used for the transition.
*/
TransitionComponent: PropTypes.elementType,
/**
* Adjust the duration of the content expand transition.
* Passed as a prop to the transition component.
*
* Set to 'auto' to automatically calculate transition time based on height.
*/
transitionDuration: PropTypes.oneOfType([
PropTypes.number,
PropTypes.shape({ enter: PropTypes.number, exit: PropTypes.number }),
PropTypes.oneOf(['auto']),
]),
/**
* Props applied to the `Transition` element.
*/
TransitionProps: PropTypes.object,
};
export default withStyles(styles, { name: 'MuiStepContent' })(StepContent);
|
kybarg/material-ui
|
packages/material-ui/src/StepContent/StepContent.js
|
JavaScript
|
mit
| 3,312
|
/*
HTS221.cpp - HTS221 library for Aistin ATMega
This program is free software under the MIT License (MIT)
Copyright 2015 iProtoXi Oy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <HTS221.h>
#include <Arduino.h>
uint8_t HTS221::sensorAddress = 0x5F;
uint8_t HTS221::init(void)
{
uint8_t ctrl_reg_values[3] = {0x87, 0x00, 0x00};
return writeReg(0xA0, ctrl_reg_values, sizeof(ctrl_reg_values));
}
void HTS221::readCalibration(void)
{
int16_t C0;
int16_t C1;
int16_t T0;
int16_t T1;
int16_t RH0;
int16_t RH1;
int16_t H0;
int16_t H1;
uint8_t calibrationRegs[16];
readReg(0xB0, calibrationRegs, 16);
RH0 = calibrationRegs[0]; // e.g. 35.5
RH1 = calibrationRegs[1]; // e.g. 70.5
C0 = ((((uint16_t)(calibrationRegs[5] & 3))<<8) | ((uint16_t)calibrationRegs[2]));
C1 = ((((uint16_t)(calibrationRegs[5] & 12))<<6) | ((uint16_t)calibrationRegs[3]));
T0 = ((((uint16_t)calibrationRegs[13])<<8) | ((uint16_t)calibrationRegs[12]));
T1 = ((((uint16_t)calibrationRegs[15])<<8) | ((uint16_t)calibrationRegs[14]));
H0 = ((((uint16_t)calibrationRegs[7])<<8) | ((uint16_t)calibrationRegs[6])); // e.g. 4085
H1 = ((((uint16_t)calibrationRegs[11])<<8) | ((uint16_t)calibrationRegs[10])); // e.g. 203.5
CTf = ((float)C1 - (float)C0) / ((float)T1 - (float)T0) / 8.0;
CTc = ((-1*(float)CTf * (float)T0) + (float)C0 )/ 8.0;
RHf = ((float)RH1 - (float)RH0) / ((float)H1 - (float)H0) / 2.0;
RHc = ((-1*(float)RHf * (float)H0) + (float)RH0 )/ 2.0;
}
int16_t HTS221::readHumidityRaw(void)
{
uint8_t sensorData[2];
readReg(0xA8, sensorData, 2);
return ((int8_t)sensorData[1])*256+sensorData[0];
}
float HTS221::readHumidity(void)
{
int16_t raw = readHumidityRaw();
return (raw * RHf) + RHc;
}
uint16_t HTS221::readTemperatureRaw(void)
{
uint8_t sensorData[2];
readReg(0xAA, sensorData, 2);
return ((int8_t)sensorData[1])*256+sensorData[0];
}
float HTS221::readTemperature(void)
{
int16_t raw = readTemperatureRaw();
return (CTf * raw) + CTc;
}
uint8_t HTS221::readReg(uint8_t regAddress)
{
return aistin::readReg(sensorAddress, regAddress);
}
void HTS221::readReg(uint8_t regAddress, uint8_t *regValue, uint8_t quanity)
{
regAddress = 0x80 | regAddress; //set MSB to 1 to auto increment
aistin::readReg(sensorAddress, regAddress, regValue, quanity);
}
uint8_t HTS221::writeReg(uint8_t regAddress, uint8_t regValue)
{
return aistin::writeReg(sensorAddress, regAddress, regValue);
}
uint8_t HTS221::writeReg(uint8_t regAddress, uint8_t *regValue, size_t quanity)
{
regAddress = 0x80 | regAddress; //set MSB to 1 to auto increment
return aistin::writeReg(sensorAddress, regAddress, regValue, quanity);
}
|
iProtoXi/Aistin-arduino-examples
|
libraries/aistin/HTS221.cpp
|
C++
|
mit
| 3,699
|
version https://git-lfs.github.com/spec/v1
oid sha256:d5cc128e23de4db1491cefafea31b5214603d86c06f1a6748cde6e53907b6a95
size 4880
|
xiangzhuyuan/cron-jlpt
|
jlpt/288807773129079274432992910168785584342.html
|
HTML
|
mit
| 129
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_65) on Sun Jun 29 05:13:55 IDT 2014 -->
<TITLE>
casimir.cryptoAPI
</TITLE>
<META NAME="date" CONTENT="2014-06-29">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameTitleFont">
<A HREF="../../casimir/cryptoAPI/package-summary.html" target="classFrame">casimir.cryptoAPI</A></FONT>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont">
Classes</FONT>
<FONT CLASS="FrameItemFont">
<BR>
<A HREF="BitcoinAPI.html" title="class in casimir.cryptoAPI" target="classFrame">BitcoinAPI</A>
<BR>
<A HREF="MastercoinAPI.html" title="class in casimir.cryptoAPI" target="classFrame">MastercoinAPI</A></FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML>
|
thehobbit85/coinpowers
|
javadoc/casimir/cryptoAPI/package-frame.html
|
HTML
|
mit
| 953
|
package org.vitrivr.cineast.api.websocket.handlers.queries;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import org.eclipse.jetty.websocket.api.Session;
import org.vitrivr.cineast.api.messages.query.SegmentQuery;
import org.vitrivr.cineast.api.messages.result.MediaObjectQueryResult;
import org.vitrivr.cineast.api.messages.result.MediaSegmentQueryResult;
import org.vitrivr.cineast.core.config.QueryConfig;
import org.vitrivr.cineast.core.data.entities.MediaObjectDescriptor;
import org.vitrivr.cineast.core.data.entities.MediaSegmentDescriptor;
/**
* This class extends the {@link AbstractQueryMessageHandler} abstract class and handles messages of type {@link SegmentQuery}.
*/
public class SegmentQueryMessageHandler extends AbstractQueryMessageHandler<SegmentQuery> {
/**
* Executes a {@link SegmentQuery} message. Performs a lookup for the segment ID specified in the {@link SegmentQuery} object.
*
* @param session WebSocket session the invocation is associated with.
* @param qconf The {@link QueryConfig} that contains additional specifications.
* @param message Instance of {@link SegmentQuery}
* @param segmentIdsForWhichMetadataIsFetched Segment IDs for which metadata is fetched
* @param objectIdsForWhichMetadataIsFetched Object IDs for which metadata is fetched
*/
@Override
public void execute(Session session, QueryConfig qconf, SegmentQuery message, Set<String> segmentIdsForWhichMetadataIsFetched, Set<String> objectIdsForWhichMetadataIsFetched) throws Exception {
/* Prepare QueryConfig (so as to obtain a QueryId). */
final String uuid = qconf.getQueryId().toString();
/* Retrieve segments; if empty, abort query. */
final List<String> segmentId = new ArrayList<>(0);
segmentId.add(message.getSegmentId());
final List<MediaSegmentDescriptor> segment = this.loadSegments(segmentId);
if (segment.isEmpty()) {
return;
}
/* Retrieve media objects; if empty, abort query. */
final List<String> objectId = segment.stream().map(MediaSegmentDescriptor::getObjectId).collect(Collectors.toList());
final List<MediaObjectDescriptor> object = this.loadObjects(objectId);
if (object.isEmpty()) {
return;
}
List<CompletableFuture<Void>> futures = new ArrayList<>();
List<Thread> threads = new ArrayList<>();
/* Write segments and objects to results stream. */
futures.add(this.write(session, new MediaSegmentQueryResult(uuid, segment)));
futures.add(this.write(session, new MediaObjectQueryResult(uuid, object)));
/* Load and transmit segment & object metadata. */
threads.addAll(this.loadAndWriteSegmentMetadata(session, uuid, segmentId, segmentIdsForWhichMetadataIsFetched, message.getMetadataAccessSpec()));
threads.addAll(this.loadAndWriteObjectMetadata(session, uuid, objectId, objectIdsForWhichMetadataIsFetched, message.getMetadataAccessSpec()));
for (Thread thread : threads) {
thread.join();
}
futures.forEach(CompletableFuture::join);
}
}
|
vitrivr/cineast
|
cineast-api/src/main/java/org/vitrivr/cineast/api/websocket/handlers/queries/SegmentQueryMessageHandler.java
|
Java
|
mit
| 3,210
|
FROM nginx
MAINTAINER Octoblu <docker@octoblu.com>
EXPOSE 80
COPY . /usr/share/nginx/html
|
octoblu/vote-octoblu-com
|
Dockerfile
|
Dockerfile
|
mit
| 91
|
#home {
border: 2px solid #CCCCCC;
background-color: #DDDDDD;
margin: 42px auto;
padding: 21px;
width: 42%;
}
|
francoiscolas/vane
|
template/public/css/home/index.css
|
CSS
|
mit
| 130
|
package keyapi
import (
"bytes"
"crypto/tls"
"crypto/x509"
"errors"
"io/ioutil"
"log"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/sipb/homeworld/platform/keysystem/keyserver/account"
"github.com/sipb/homeworld/platform/keysystem/keyserver/authorities"
"github.com/sipb/homeworld/platform/keysystem/keyserver/config"
"github.com/sipb/homeworld/platform/keysystem/keyserver/verifier"
"github.com/sipb/homeworld/platform/util/testkeyutil"
"github.com/sipb/homeworld/platform/util/wraputil"
)
func TestVerifyAccountIP_NoLimit(t *testing.T) {
acnt := &account.Account{
LimitIP: nil,
}
request := httptest.NewRequest("GET", "/test", nil)
request.RemoteAddr = "192.168.0.1:1234"
err := verifyAccountIP(acnt, request)
if err != nil {
t.Error(err)
}
}
func TestVerifyAccountIP_Valid(t *testing.T) {
acnt := &account.Account{
LimitIP: net.IPv4(192, 168, 0, 3),
}
request := httptest.NewRequest("GET", "/test", nil)
request.RemoteAddr = "192.168.0.3:1234"
err := verifyAccountIP(acnt, request)
if err != nil {
t.Error(err)
}
}
func TestVerifyAccountIP_Invalid(t *testing.T) {
acnt := &account.Account{
LimitIP: net.IPv4(192, 168, 0, 3),
}
request := httptest.NewRequest("GET", "/test", nil)
request.RemoteAddr = "172.16.0.1:1234"
err := verifyAccountIP(acnt, request)
if err == nil {
t.Error("Expected error")
} else if !strings.Contains(err.Error(), "wrong IP address") {
t.Error("Wrong error.")
}
}
func TestVerifyAccountIP_BadRequest(t *testing.T) {
acnt := &account.Account{
LimitIP: net.IPv4(192, 168, 0, 3),
}
request := httptest.NewRequest("GET", "/test", nil)
request.RemoteAddr = "invalid"
err := verifyAccountIP(acnt, request)
if err == nil {
t.Error("Expected error")
} else if !strings.Contains(err.Error(), "invalid request address") {
t.Errorf("Wrong error: %s", err)
}
}
func TestAttemptAuthentication_NoAuthentication(t *testing.T) {
request := httptest.NewRequest("GET", "/test", nil)
keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, certdata)
if err != nil {
t.Fatal(err)
}
gctx := config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
AuthenticationAuthority: authority.(*authorities.TLSAuthority),
}
_, err = attemptAuthentication(&gctx, request)
if err == nil {
t.Error("Expected error")
} else if !strings.Contains(err.Error(), "No authentication method") {
t.Error("Wrong error.")
}
}
func TestAttemptAuthentication_TokenAuth(t *testing.T) {
keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, certdata)
if err != nil {
t.Fatal(err)
}
gctx := config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
AuthenticationAuthority: authority.(*authorities.TLSAuthority),
Accounts: map[string]*account.Account{
"test-user": {Principal: "test-user"},
},
}
request := httptest.NewRequest("GET", "/test", nil)
request.Header.Set(verifier.TokenHeader, gctx.TokenVerifier.Registry.GrantToken("test-user", time.Minute))
acnt, err := attemptAuthentication(&gctx, request)
if err != nil {
t.Error(err)
} else if acnt.Principal != "test-user" {
t.Error("Wrong account.")
}
}
func TestAttemptAuthentication_TokenAuth_Fail(t *testing.T) {
keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, certdata)
if err != nil {
t.Fatal(err)
}
gctx := config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
AuthenticationAuthority: authority.(*authorities.TLSAuthority),
Accounts: map[string]*account.Account{
"test-user": {Principal: "test-user"},
},
}
request := httptest.NewRequest("GET", "/test", nil)
request.Header.Set(verifier.TokenHeader, "this-is-not-a-valid-token")
_, err = attemptAuthentication(&gctx, request)
if err == nil {
t.Error("Expected error.")
} else if !strings.Contains(err.Error(), "Unrecognized token") {
t.Errorf("Wrong error: %s", err.Error())
}
}
func TestAttemptAuthentication_MissingAccount_Token(t *testing.T) {
keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, certdata)
if err != nil {
t.Fatal(err)
}
gctx := config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
AuthenticationAuthority: authority.(*authorities.TLSAuthority),
Accounts: map[string]*account.Account{},
}
request := httptest.NewRequest("GET", "/test", nil)
request.Header.Set(verifier.TokenHeader, gctx.TokenVerifier.Registry.GrantToken("test-user", time.Minute))
_, err = attemptAuthentication(&gctx, request)
if err == nil {
t.Error("Expected error.")
} else if !strings.Contains(err.Error(), "Cannot find account") {
t.Errorf("Wrong error: %s", err)
}
}
func TestAttemptAuthentication_NoDirectAuth_Token(t *testing.T) {
keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, certdata)
if err != nil {
t.Fatal(err)
}
gctx := config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
AuthenticationAuthority: authority.(*authorities.TLSAuthority),
Accounts: map[string]*account.Account{
"test-user": {Principal: "test-user", DisableDirectAuth: true},
},
}
request := httptest.NewRequest("GET", "/test", nil)
request.Header.Set(verifier.TokenHeader, gctx.TokenVerifier.Registry.GrantToken("test-user", time.Minute))
_, err = attemptAuthentication(&gctx, request)
if err == nil {
t.Error("Expected error.")
} else if !strings.Contains(err.Error(), "disabled direct authentication") {
t.Errorf("Wrong error: %s", err)
}
}
func TestAttemptAuthentication_InvalidIP_Token(t *testing.T) {
keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, certdata)
if err != nil {
t.Fatal(err)
}
gctx := config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
AuthenticationAuthority: authority.(*authorities.TLSAuthority),
Accounts: map[string]*account.Account{
"test-user": {Principal: "test-user", LimitIP: net.IPv4(192, 168, 0, 16)},
},
}
request := httptest.NewRequest("GET", "/test", nil)
request.Header.Set(verifier.TokenHeader, gctx.TokenVerifier.Registry.GrantToken("test-user", time.Minute))
request.RemoteAddr = "192.168.0.17:50000"
_, err = attemptAuthentication(&gctx, request)
if err == nil {
t.Error("Expected error.")
} else if !strings.Contains(err.Error(), "from wrong IP address") {
t.Errorf("Wrong error: %s", err)
}
}
const (
TLS_CLIENT_CSR = "-----BEGIN CERTIFICATE REQUEST-----\nMIIBVTCBvwIBADAWMRQwEgYDVQQDDAtjbGllbnQtdGVzdDCBnzANBgkqhkiG9w0B\nAQEFAAOBjQAwgYkCgYEAtKukT2LT/PJ/i1pbqfe4Vm9iN2yMFoiKj0em7FFOrAeU\n/5onq8fZEXhUruN+OhjMr+K1c2qy7noqbzD3Fz/vi2frB9DUFMA9rkj3teRIEXKB\nBDzb1cbDSTL0HxH47/tURxzxzGCVfTCc1xUY+dqMsd8SvowxuEptU4SO9H8CR2MC\nAwEAAaAAMA0GCSqGSIb3DQEBCwUAA4GBALCOKX+QHmNLGrrSCWB8p2iMuS+aPOcW\nYI9c1VaaTSQ43HOjF1smvGIa1iicM2L5zTBOEG36kI+sKFDOF2cXclhQF1WfLcxC\nIi/JSV+W7hbS6zWvJOnmoi15hzvVa1MRk8HZH+TpiMxO5uqQdDiEkV1sJ50v0ZtR\nTMuSBjdmmJ1t\n-----END CERTIFICATE REQUEST-----"
)
func prepCertAuth(t *testing.T, gctx *config.Context) *http.Request {
certstr, err := gctx.AuthenticationAuthority.Sign(TLS_CLIENT_CSR, false, time.Minute, "test-user", []string{})
if err != nil {
t.Fatal(err)
}
cert, err := wraputil.LoadX509CertFromPEM([]byte(certstr))
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest("GET", "/test", nil)
request.TLS = &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{cert}}}
return request
}
func TestAttemptAuthentication_CertAuth(t *testing.T) {
keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, certdata)
if err != nil {
t.Fatal(err)
}
gctx := config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
AuthenticationAuthority: authority.(*authorities.TLSAuthority),
Accounts: map[string]*account.Account{
"test-user": {Principal: "test-user"},
},
}
acnt, err := attemptAuthentication(&gctx, prepCertAuth(t, &gctx))
if err != nil {
t.Error(err)
} else if acnt.Principal != "test-user" {
t.Error("Wrong account.")
}
}
func TestAttemptAuthentication_MissingAccount_Cert(t *testing.T) {
keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, certdata)
if err != nil {
t.Fatal(err)
}
gctx := config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
AuthenticationAuthority: authority.(*authorities.TLSAuthority),
Accounts: map[string]*account.Account{},
}
_, err = attemptAuthentication(&gctx, prepCertAuth(t, &gctx))
if err == nil {
t.Error("Expected error.")
} else if !strings.Contains(err.Error(), "Cannot find account") {
t.Errorf("Wrong error: %s", err)
}
}
func TestAttemptAuthentication_NoDirectAuth_Cert(t *testing.T) {
keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, certdata)
if err != nil {
t.Fatal(err)
}
gctx := config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
AuthenticationAuthority: authority.(*authorities.TLSAuthority),
Accounts: map[string]*account.Account{
"test-user": {Principal: "test-user", DisableDirectAuth: true},
},
}
_, err = attemptAuthentication(&gctx, prepCertAuth(t, &gctx))
if err == nil {
t.Error("Expected error.")
} else if !strings.Contains(err.Error(), "disabled direct authentication") {
t.Errorf("Wrong error: %s", err)
}
}
func TestAttemptAuthentication_InvalidIP_Cert(t *testing.T) {
keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, certdata)
if err != nil {
t.Fatal(err)
}
gctx := config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
AuthenticationAuthority: authority.(*authorities.TLSAuthority),
Accounts: map[string]*account.Account{
"test-user": {Principal: "test-user", LimitIP: net.IPv4(192, 168, 0, 16)},
},
}
request := prepCertAuth(t, &gctx)
request.RemoteAddr = "192.168.0.17:50000"
_, err = attemptAuthentication(&gctx, request)
if err == nil {
t.Error("Expected error.")
} else if !strings.Contains(err.Error(), "from wrong IP address") {
t.Errorf("Wrong error: %s", err)
}
}
func TestConfiguredKeyserver_GetClientCAs(t *testing.T) {
keydata, _, certdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, certdata)
if err != nil {
t.Fatal(err)
}
ks := &ConfiguredKeyserver{Context: &config.Context{AuthenticationAuthority: authority.(*authorities.TLSAuthority)}}
subjects := ks.GetClientCAs().Subjects()
cert, err := x509.ParseCertificate(ks.Context.AuthenticationAuthority.ToHTTPSCert().Certificate[0])
if err != nil {
t.Fatal(err)
}
if len(subjects) != 1 {
t.Error("Wrong number of subjects.")
} else if !bytes.Equal(subjects[0], cert.RawSubject) {
t.Error("Mismatched raw subject bytes.")
}
}
func TestConfiguredKeyserver_GetServerCert(t *testing.T) {
keydata, _, cdata := testkeyutil.GenerateTLSRootPEMsForTests(t, "test-ca", nil, nil)
authority, err := authorities.LoadTLSAuthority(keydata, cdata)
if err != nil {
t.Fatal(err)
}
ks := &ConfiguredKeyserver{ServerCert: authority.(*authorities.TLSAuthority).ToHTTPSCert()}
if len(ks.GetServerCert().Certificate) != 1 {
t.Fatal("Wrong number of certs")
}
certdata := ks.GetServerCert().Certificate[0]
refdata, err := wraputil.LoadSinglePEMBlock(cdata, []string{"CERTIFICATE"})
if err != nil {
t.Error(err)
} else if !bytes.Equal(certdata, refdata) {
t.Error("Cert mismatch")
}
}
func TestConfiguredKeyserver_HandleStaticRequest(t *testing.T) {
ks := &ConfiguredKeyserver{Context: &config.Context{StaticFiles: map[string]config.StaticFile{
"testa.txt": {Filename: "testa.txt", Filepath: "../config/testdir/testa.txt"},
}}}
recorder := httptest.NewRecorder()
err := ks.HandleStaticRequest(recorder, "testa.txt")
if err != nil {
t.Error(err)
}
result := recorder.Result()
if result.Body == nil {
t.Fatal("Nil body.")
}
response, err := ioutil.ReadAll(result.Body)
if err != nil {
t.Fatal(err)
}
ref, err := ioutil.ReadFile("../config/testdir/testa.txt")
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(response, ref) {
t.Error("Mismatched file data.")
}
}
func TestConfiguredKeyserver_HandleStaticRequest_NonexistentEntry(t *testing.T) {
ks := &ConfiguredKeyserver{Context: &config.Context{}}
err := ks.HandleStaticRequest(nil, "testa.txt")
if err == nil {
t.Error("Expected error.")
} else if !strings.Contains(err.Error(), "No such static file") {
t.Error("Wrong error.")
}
}
func TestConfiguredKeyserver_HandleStaticRequest_NonexistentFile(t *testing.T) {
ks := &ConfiguredKeyserver{Context: &config.Context{StaticFiles: map[string]config.StaticFile{
"testa.txt": {Filename: "testa.txt", Filepath: "../config/testdir/nonexistent.txt"},
}}}
err := ks.HandleStaticRequest(nil, "testa.txt")
if err == nil {
t.Error("Expected error.")
} else if !strings.Contains(err.Error(), "no such file") {
t.Errorf("Wrong error: %s", err)
}
}
func TestConfiguredKeyserver_HandlePubRequest_NoAuthority(t *testing.T) {
ks := &ConfiguredKeyserver{Context: &config.Context{}}
err := ks.HandlePubRequest(nil, "grant")
if err == nil {
t.Error("Expected error.")
} else if !strings.Contains(err.Error(), "No such authority") {
t.Errorf("Wrong error: %s", err)
}
}
type BrokenConnection struct {
}
func (BrokenConnection) Read(p []byte) (n int, err error) {
return 0, errors.New("connection cut by a squirrel with scissors")
}
func TestConfiguredKeyserver_HandleAPIRequest_ConnError(t *testing.T) {
logrecord := bytes.NewBuffer(nil)
logger := log.New(logrecord, "", 0)
ks := &ConfiguredKeyserver{
Context: &config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
},
Logger: logger,
}
recorder := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/api", BrokenConnection{})
request.Header.Set(verifier.TokenHeader, ks.Context.TokenVerifier.Registry.GrantToken("test-account", time.Minute))
err := ks.HandleAPIRequest(recorder, request)
if err == nil {
t.Error("Expected error")
} else if !strings.Contains(err.Error(), "connection cut by a squirrel with scissors") {
t.Errorf("Wrong error: %s", err)
}
if logrecord.String() != "" {
t.Error("Unexpected logging.")
}
}
func TestConfiguredKeyserver_HandleAPIRequest_Unauthed(t *testing.T) {
logrecord := bytes.NewBuffer(nil)
logger := log.New(logrecord, "", 0)
ks := &ConfiguredKeyserver{
Context: &config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
},
Logger: logger,
}
recorder := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/api", nil)
err := ks.HandleAPIRequest(recorder, request)
if err == nil {
t.Error("Expected error")
} else if !strings.Contains(err.Error(), "No authentication method found in request") {
t.Errorf("Wrong error: %s", err)
}
if logrecord.String() != "" {
t.Error("Unexpected logging.")
}
}
func TestConfiguredKeyserver_HandleAPIRequest_NoSuchGrant(t *testing.T) {
logrecord := bytes.NewBuffer(nil)
logger := log.New(logrecord, "", 0)
ks := &ConfiguredKeyserver{
Context: &config.Context{
TokenVerifier: verifier.NewTokenVerifier(),
Accounts: map[string]*account.Account{
"test-account": {
Principal: "test-account",
},
},
},
Logger: logger,
}
request_data := []byte("[{\"api\": \"test-api\", \"body\": \"\"}]")
recorder := httptest.NewRecorder()
request := httptest.NewRequest("GET", "/api", bytes.NewReader(request_data))
request.Header.Set(verifier.TokenHeader, ks.Context.TokenVerifier.Registry.GrantToken("test-account", time.Minute))
err := ks.HandleAPIRequest(recorder, request)
if err == nil {
t.Error("Expected error")
} else if !strings.Contains(err.Error(), "could not find API request") {
t.Errorf("Wrong error: %s", err)
}
if logrecord.String() != "" {
t.Error("Unexpected logging.")
}
}
|
sipb/homeworld
|
platform/keysystem/keyserver/keyapi/api_test.go
|
GO
|
mit
| 16,533
|
<?php
declare(strict_types=1);
namespace BEAR\Resource\Annotation;
use Attribute;
use Doctrine\Common\Annotations\Annotation\NamedArgumentConstructor;
use Ray\Di\Di\Qualifier;
/**
* @Annotation
* @Target("METHOD")
* @Qualifier
* @NamedArgumentConstructor
*/
#[Attribute(Attribute::TARGET_METHOD), Qualifier]
final class ContextScheme
{
/** @var string */
public $value;
public function __construct(string $value = '')
{
$this->value = $value;
}
}
|
bearsunday/BEAR.Resource
|
src/Annotation/ContextScheme.php
|
PHP
|
mit
| 485
|
var fs = require("fs");
var http = require("http");
var fileName = __dirname + "/ipsum.txt";
var server = http.createServer(function (req, res) {
fs.exists(fileName, function(exists) {
if (exists) {
fs.stat(fileName, function(error, stats) {
if (error) {
throw error;
}
if (stats.isFile()) {
var stream = fs.createReadStream(fileName);
stream.pipe(res);
}
});
}
});
}).listen(process.env.PORT || 8000, process.env.HOST || "0.0.0.0", function() {
console.log("HTTP Server Started. Listening on " + server.address().address + " : Port " + server.address().port);
});
|
itkoren/Lets-Node-exp-streams-pipe
|
fileAsync2.js
|
JavaScript
|
mit
| 642
|
---
---
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>StateMatcher | @uirouter/core</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
<link rel="stylesheet" href="../assets/css/uirouter.css">
<script src="../assets/js/modernizr.js"></script>
<script src="../assets/js/reset.js"></script>
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">@uirouter/core</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<!--
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
-->
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Internal UI-Router API</label>
<!--
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
-->
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../index.html">@uirouter/core</a>
</li>
<li>
<a href="../modules/state.html">state</a>
</li>
<li>
<a href="state.statematcher.html">StateMatcher</a>
</li>
</ul>
<h1>Class StateMatcher</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<span class="target">StateMatcher</span>
</li>
</ul>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section ">
<h3>Constructors</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-constructor tsd-parent-kind-class"><a href="state.statematcher.html#constructor" class="tsd-kind-icon">constructor</a></li>
</ul>
</section>
<section class="tsd-index-section tsd-is-private tsd-is-private-protected">
<h3>Properties</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><a href="state.statematcher.html#_states" class="tsd-kind-icon">_states</a></li>
</ul>
</section>
<section class="tsd-index-section ">
<h3>Methods</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-method tsd-parent-kind-class"><a href="state.statematcher.html#find" class="tsd-kind-icon">find</a></li>
<li class="tsd-kind-method tsd-parent-kind-class"><a href="state.statematcher.html#isrelative" class="tsd-kind-icon">is<wbr>Relative</a></li>
<li class="tsd-kind-method tsd-parent-kind-class"><a href="state.statematcher.html#resolvepath" class="tsd-kind-icon">resolve<wbr>Path</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group ">
<h2>Constructors</h2>
<section class="tsd-panel tsd-member tsd-kind-constructor tsd-parent-kind-class">
<a name="constructor" class="tsd-anchor"></a>
<!--
<h3>constructor</h3>
-->
<ul class="tsd-signatures tsd-kind-constructor tsd-parent-kind-class">
<li class="tsd-signature tsd-kind-icon">new <wbr>State<wbr>Matcher<span class="tsd-signature-symbol">(</span>_states<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">object</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="state.statematcher.html" class="tsd-signature-type">StateMatcher</a></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<h4 class="tsd-parameters-title">Parameters</h4>
<ul class="tsd-parameters">
<li>
<h5>_states <span class="tsd-signature-type">object</span></h5>
<ul class="tsd-parameters">
<li class="tsd-parameter-index-signature">
<h5><span class="tsd-signature-symbol">[</span>key: <span class="tsd-signature-type">string</span><span class="tsd-signature-symbol">]: </span><a href="state.stateobject.html" class="tsd-signature-type">StateObject</a></h5>
</li>
</ul>
</li>
</ul>
<div class="tsd-returns">
<h4 class="tsd-returns-title">Returns <a href="state.statematcher.html" class="tsd-signature-type">StateMatcher</a></h4>
</div>
<hr>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/8ed691b/src/state/stateMatcher.ts#L7">state/stateMatcher.ts:7</a></li>
</ul>
</aside> </li>
</ul>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-private tsd-is-private-protected">
<h2>Properties</h2>
<section class="tsd-panel tsd-member tsd-kind-property tsd-parent-kind-class tsd-is-private">
<a name="_states" class="tsd-anchor"></a>
<!--
<h3><span class="tsd-flag ts-flagPrivate">Private</span> _states</h3>
-->
<div class="tsd-signature tsd-kind-icon">_states<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-type">object</span></div>
<div class="tsd-declaration">
</div>
<div class="tsd-type-declaration">
<h4>Type declaration</h4>
<ul class="tsd-parameters">
<li class="tsd-parameter-index-signature">
<h5><span class="tsd-signature-symbol">[</span>key: <span class="tsd-signature-type">string</span><span class="tsd-signature-symbol">]: </span><a href="state.stateobject.html" class="tsd-signature-type">StateObject</a></h5>
</li>
</ul>
</div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/8ed691b/src/state/stateMatcher.ts#L8">state/stateMatcher.ts:8</a></li>
</ul>
</aside>
</section>
</section>
<section class="tsd-panel-group tsd-member-group ">
<h2>Methods</h2>
<section class="tsd-panel tsd-member tsd-kind-method tsd-parent-kind-class">
<a name="find" class="tsd-anchor"></a>
<!--
<h3>find</h3>
-->
<ul class="tsd-signatures tsd-kind-method tsd-parent-kind-class">
<li class="tsd-signature tsd-kind-icon">find<span class="tsd-signature-symbol">(</span>stateOrName<span class="tsd-signature-symbol">: </span><a href="../modules/state.html#stateorname" class="tsd-signature-type">StateOrName</a>, base<span class="tsd-signature-symbol">?: </span><a href="../modules/state.html#stateorname" class="tsd-signature-type">StateOrName</a>, matchGlob<span class="tsd-signature-symbol">?: </span><span class="tsd-signature-type">boolean</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="state.stateobject.html" class="tsd-signature-type">StateObject</a></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<h4 class="tsd-parameters-title">Parameters</h4>
<ul class="tsd-parameters">
<li>
<h5>stateOrName <a href="../modules/state.html#stateorname" class="tsd-signature-type">StateOrName</a></h5>
</li>
<li>
<h5>base: <span class="tsd-flag ts-flagOptional">Optional</span> <a href="../modules/state.html#stateorname" class="tsd-signature-type">StateOrName</a></h5>
</li>
<li>
<h5>matchGlob: <span class="tsd-flag ts-flagDefault value">Default value</span> <span class="tsd-signature-type">boolean</span><span class="tsd-signature-symbol"> = true</span></h5>
</li>
</ul>
<div class="tsd-returns">
<h4 class="tsd-returns-title">Returns <a href="state.stateobject.html" class="tsd-signature-type">StateObject</a></h4>
</div>
<hr>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/8ed691b/src/state/stateMatcher.ts#L15">state/stateMatcher.ts:15</a></li>
</ul>
</aside> </li>
</ul>
</section>
<section class="tsd-panel tsd-member tsd-kind-method tsd-parent-kind-class">
<a name="isrelative" class="tsd-anchor"></a>
<!--
<h3>is<wbr>Relative</h3>
-->
<ul class="tsd-signatures tsd-kind-method tsd-parent-kind-class">
<li class="tsd-signature tsd-kind-icon">is<wbr>Relative<span class="tsd-signature-symbol">(</span>stateName<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">string</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">boolean</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<h4 class="tsd-parameters-title">Parameters</h4>
<ul class="tsd-parameters">
<li>
<h5>stateName <span class="tsd-signature-type">string</span></h5>
</li>
</ul>
<div class="tsd-returns">
<h4 class="tsd-returns-title">Returns <span class="tsd-signature-type">boolean</span></h4>
</div>
<hr>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/8ed691b/src/state/stateMatcher.ts#L10">state/stateMatcher.ts:10</a></li>
</ul>
</aside> </li>
</ul>
</section>
<section class="tsd-panel tsd-member tsd-kind-method tsd-parent-kind-class">
<a name="resolvepath" class="tsd-anchor"></a>
<!--
<h3>resolve<wbr>Path</h3>
-->
<ul class="tsd-signatures tsd-kind-method tsd-parent-kind-class">
<li class="tsd-signature tsd-kind-icon">resolve<wbr>Path<span class="tsd-signature-symbol">(</span>name<span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">string</span>, base<span class="tsd-signature-symbol">: </span><a href="../modules/state.html#stateorname" class="tsd-signature-type">StateOrName</a><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">string</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<h4 class="tsd-parameters-title">Parameters</h4>
<ul class="tsd-parameters">
<li>
<h5>name <span class="tsd-signature-type">string</span></h5>
</li>
<li>
<h5>base <a href="../modules/state.html#stateorname" class="tsd-signature-type">StateOrName</a></h5>
</li>
</ul>
<div class="tsd-returns">
<h4 class="tsd-returns-title">Returns <span class="tsd-signature-type">string</span></h4>
</div>
<hr>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/8ed691b/src/state/stateMatcher.ts#L43">state/stateMatcher.ts:43</a></li>
</ul>
</aside> </li>
</ul>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../index.html"><em>@uirouter/core</em></a>
</li>
<li class="label tsd-is-external">
<span>Public API</span>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/common.html">common</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/core.html">core</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/params.html">params</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/resolve.html">resolve</a>
</li>
<li class="current tsd-kind-external-module">
<a href="../modules/state.html">state</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/transition.html">transition</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/url.html">url</a>
</li>
<li class=" tsd-kind-external-module">
<a href="../modules/view.html">view</a>
</li>
<li class="label tsd-is-external">
<span>Internal UI-<wbr><wbr>Router API</span>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/common_hof.html">common_<wbr>hof</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/common_predicates.html">common_<wbr>predicates</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/common_strings.html">common_<wbr>strings</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/hooks.html">hooks</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/path.html">path</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/trace.html">trace</a>
</li>
<li class=" tsd-kind-external-module tsd-is-external">
<a href="../modules/vanilla.html">vanilla</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
<li class=" tsd-kind-class tsd-parent-kind-external-module tsd-is-external">
<a href="state.statebuilder.html" class="tsd-kind-icon">State<wbr>Builder</a>
</li>
</ul>
<ul class="current">
<li class="current tsd-kind-class tsd-parent-kind-external-module">
<a href="state.statematcher.html" class="tsd-kind-icon">State<wbr>Matcher</a>
<ul>
<li class=" tsd-kind-constructor tsd-parent-kind-class">
<a href="state.statematcher.html#constructor" class="tsd-kind-icon">constructor</a>
</li>
<li class=" tsd-kind-property tsd-parent-kind-class tsd-is-private">
<a href="state.statematcher.html#_states" class="tsd-kind-icon">_states</a>
</li>
<li class=" tsd-kind-method tsd-parent-kind-class">
<a href="state.statematcher.html#find" class="tsd-kind-icon">find</a>
</li>
<li class=" tsd-kind-method tsd-parent-kind-class">
<a href="state.statematcher.html#isrelative" class="tsd-kind-icon">is<wbr>Relative</a>
</li>
<li class=" tsd-kind-method tsd-parent-kind-class">
<a href="state.statematcher.html#resolvepath" class="tsd-kind-icon">resolve<wbr>Path</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="state.stateobject.html" class="tsd-kind-icon">State<wbr>Object</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module tsd-is-external">
<a href="state.statequeuemanager.html" class="tsd-kind-icon">State<wbr>Queue<wbr>Manager</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="state.stateregistry.html" class="tsd-kind-icon">State<wbr>Registry</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="state.stateservice.html" class="tsd-kind-icon">State<wbr>Service</a>
</li>
<li class=" tsd-kind-class tsd-parent-kind-external-module">
<a href="state.targetstate.html" class="tsd-kind-icon">Target<wbr>State</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../interfaces/state.builders.html" class="tsd-kind-icon">Builders</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="../interfaces/state.hrefoptions.html" class="tsd-kind-icon">Href<wbr>Options</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="../interfaces/state.lazyloadresult.html" class="tsd-kind-icon">Lazy<wbr>Load<wbr>Result</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="../interfaces/state.statedeclaration.html" class="tsd-kind-icon">State<wbr>Declaration</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module">
<a href="../interfaces/state.targetstatedef.html" class="tsd-kind-icon">Target<wbr>State<wbr>Def</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module tsd-is-external">
<a href="../interfaces/state.transitionpromise.html" class="tsd-kind-icon">Transition<wbr>Promise</a>
</li>
<li class=" tsd-kind-interface tsd-parent-kind-external-module tsd-is-external">
<a href="../interfaces/state._viewdeclaration.html" class="tsd-kind-icon">_<wbr>View<wbr>Declaration</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#builderfunction" class="tsd-kind-icon">Builder<wbr>Function</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#oninvalidcallback" class="tsd-kind-icon">On<wbr>Invalid<wbr>Callback</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#redirecttoresult" class="tsd-kind-icon">Redirect<wbr>ToResult</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#resolvetypes" class="tsd-kind-icon">Resolve<wbr>Types</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#stateorname" class="tsd-kind-icon">State<wbr>OrName</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#stateregistrylistener" class="tsd-kind-icon">State<wbr>Registry<wbr>Listener</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-external-module">
<a href="../modules/state.html#_statedeclaration" class="tsd-kind-icon">_<wbr>State<wbr>Declaration</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../modules/state.html#databuilder" class="tsd-kind-icon">data<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../modules/state.html#getnavigablebuilder" class="tsd-kind-icon">get<wbr>Navigable<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../modules/state.html#getparamsbuilder" class="tsd-kind-icon">get<wbr>Params<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../modules/state.html#geturlbuilder" class="tsd-kind-icon">get<wbr>Url<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../modules/state.html#includesbuilder" class="tsd-kind-icon">includes<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../modules/state.html#namebuilder" class="tsd-kind-icon">name<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../modules/state.html#parseurl" class="tsd-kind-icon">parse<wbr>Url</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../modules/state.html#pathbuilder" class="tsd-kind-icon">path<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module">
<a href="../modules/state.html#resolvablesbuilder" class="tsd-kind-icon">resolvables<wbr>Builder</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-external-module tsd-is-not-exported">
<a href="../modules/state.html#selfbuilder" class="tsd-kind-icon">self<wbr>Builder</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="http://typedoc.io" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html>
|
ui-router/ui-router.github.io
|
_core_docs/5.0.21/classes/state.statematcher.html
|
HTML
|
mit
| 26,523
|
angular
.module('ScheduleModule')
.controller('DialogController',
function($scope, $rootScope, $mdDialog, scheduleHourService, orientation, users, user, newScheduleHour,
saveEnum, serverService, authorityEnum, userService) {
var self = this;
var workplaces = $rootScope.properties.workplaces;
var tempAddedScheduleHours = $scope.sch.tempAddedScheduleHours;
var tempRemovedScheduleHours = $scope.sch.tempRemovedScheduleHours;
var index, existsInTemp, scheduleHours;
var ordered = userService.getArrayOfIdsOrderedBy(users, 'name');
var nonordered = userService.getArrayOfIds(users);
serverService.getScheduleDataFromServerByCurrentWeek($scope.sch.currentWeek).then(function(answer) {
scheduleHours = answer.concat($scope.sch.tempAddedScheduleHours);
scheduleHours = scheduleHourService.scheduleHoursWithoutTemp(scheduleHours, $scope.sch.tempRemovedScheduleHours);
self.prefs = scheduleHourService
.checkScheduleForOpenMenu(newScheduleHour, scheduleHours, tempAddedScheduleHours, orientation, users, workplaces);
});
self.isAdmin = user.authority === authorityEnum.ADMIN;
self.saveEnum = saveEnum;
self.save = function(saveState, data) {
if (saveState === saveEnum.PLACE) newScheduleHour.place = data;
if (saveState === saveEnum.PERSONID) newScheduleHour.peopleId = nonordered[ordered.indexOf(data)];
if (saveState === saveEnum.DISABLED) newScheduleHour.peopleId = 0;
if(!self.isAdmin) {
tempAddedScheduleHours.push(newScheduleHour);
scheduleHours.push(newScheduleHour);
$scope.sch.scheduleHours = scheduleHours;
}
if(self.isAdmin)
serverService.addScheduleHour(newScheduleHour, scheduleHours).then(function(answer) {
$scope.sch.scheduleHours = answer;
});
$mdDialog.hide();
};
self.replace = function(targetScheduleHour, data, saveState) {
if(!self.isAdmin) {
index = tempAddedScheduleHours.indexOf(targetScheduleHour);
existsInTemp = index !== -1;
if(existsInTemp)
tempAddedScheduleHours.splice(index, 1);
else
tempRemovedScheduleHours.push(newScheduleHour);
index = scheduleHours.indexOf(targetScheduleHour);
scheduleHours.splice(index, 1);
targetScheduleHour = angular.copy(targetScheduleHour);
if (saveState === saveEnum.PLACE) targetScheduleHour.place = data;
if (saveState === saveEnum.PERSONID) targetScheduleHour.peopleId = nonordered[ordered.indexOf(data)];
tempAddedScheduleHours.push(targetScheduleHour);
scheduleHours.push(targetScheduleHour);
$scope.sch.scheduleHours = scheduleHours;
}
if(self.isAdmin)
serverService.replaceScheduleHour(targetScheduleHour, scheduleHours, saveState, data).then(function(answer) {
$scope.sch.scheduleHours = answer;
});
$mdDialog.hide();
};
self.remove = function(targetScheduleHour) {
if(!self.isAdmin) {
index = tempAddedScheduleHours.indexOf(targetScheduleHour);
existsInTemp = index !== -1;
if(existsInTemp)
tempAddedScheduleHours.splice(index, 1);
else
tempRemovedScheduleHours.push(targetScheduleHour);
index = scheduleHours.indexOf(targetScheduleHour);
scheduleHours.splice(index, 1);
$scope.sch.scheduleHours = scheduleHours;
}
if(self.isAdmin)
serverService.removeScheduleHour(targetScheduleHour, scheduleHours).then(function(answer) {
$scope.sch.scheduleHours = answer;
});
$mdDialog.hide();
};
self.extend = function(targetScheduleHour) {
var activeRange = moment.duration(5, 'hours')
.afterMoment(moment(newScheduleHour.dateHourStart).minute(0).second(0));
var shRange = moment.duration(targetScheduleHour.hours, 'hours')
.afterMoment(moment(targetScheduleHour.dateHourStart).minute(0).second(0));
var unionRange = activeRange.union(shRange);
var unionScheduleHour = {
dateHourStart: unionRange.start().format('YYYY-MM-DD HH:mm:ss'),
hours: unionRange.length("hours"),
peopleId: targetScheduleHour.peopleId,
place: targetScheduleHour.place
};
if(!self.isAdmin) {
index = tempAddedScheduleHours.indexOf(targetScheduleHour);
existsInTemp = index !== -1;
if(existsInTemp)
tempAddedScheduleHours.splice(index, 1);
else
tempRemovedScheduleHours.push(targetScheduleHour);
index = scheduleHours.indexOf(targetScheduleHour);
scheduleHours.splice(index, 1);
tempAddedScheduleHours.push(unionScheduleHour);
scheduleHours.push(unionScheduleHour);
$scope.sch.scheduleHours = scheduleHours;
}
if(self.isAdmin)
serverService.extendScheduleHour(targetScheduleHour, unionScheduleHour, scheduleHours).then(function(answer) {
$scope.sch.scheduleHours = answer;
});
$mdDialog.hide();
};
self.hide = function() {
$mdDialog.hide();
};
}
);
|
Nandtel/ScheduleService
|
src/main/webapp/js/app/controller/dialogController.js
|
JavaScript
|
mit
| 6,328
|
create function uac.check_group_parents() returns trigger as $$
begin
perform 1 from uac.groups
where array[group_id]<@(new.group_id || "group".parents(new.group_id))
and user_name=new.user_name;
if found then
return null;
end if;
return new;
end $$ language plpgsql stable;
create function uac.role_id(name) returns oid as $$
declare
i oid;
begin
select oid into i from pg_roles where rolname=$1;
return i;
end $$ language plpgsql stable;
create function uac.roles(name) returns name[] as $$
begin
return $1 || array(select b.rolname
from pg_catalog.pg_auth_members m
join pg_catalog.pg_roles b on (m.roleid = b.oid)
where m.member = uac.role_id($1)
);
end $$ language plpgsql stable;
create function uac.can_read_group(_group_id bigint) returns boolean as $$
begin
return uac.can_read_group(current_user, $1);
end $$ language plpgsql stable;
create function uac.can_read_group(_user name, _group_id bigint, _root bool=true)
returns boolean
as $$
begin
perform true from uac.groups
where array[user_name]<@uac.roles($1)
and (
($3 and group_id is null)
or group_id=$2
or array[group_id]<@"group".parents($2)
)
limit 1;
return found;
end $$ language plpgsql stable security definer;
|
skuapso/psql
|
sql/functions/07.uac.sql
|
SQL
|
mit
| 1,298
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<head>
<title>Reference</title>
<link rel="stylesheet" href="../ldoc.css" type="text/css" />
</head>
<body>
<div id="container">
<div id="product">
<div id="product_logo"></div>
<div id="product_name"><big><b></b></big></div>
<div id="product_description"></div>
</div> <!-- id="product" -->
<div id="main">
<!-- Menu -->
<div id="navigation">
<br/>
<h1>LUIGI</h1>
<ul>
<li><a href="../index.html">Index</a></li>
</ul>
<h2>Widget Types</h2>
<ul class="$(kind=='Topics' and '' or 'nowrap'">
<li><a href="../widget types/button.html">button</a></li>
<li><a href="../widget types/check.html">check</a></li>
<li><a href="../widget types/menu.html">menu</a></li>
<li><a href="../widget types/menu.item.html">menu.item</a></li>
<li><a href="../widget types/progress.html">progress</a></li>
<li><a href="../widget types/radio.html">radio</a></li>
<li><a href="../widget types/sash.html">sash</a></li>
<li><a href="../widget types/slider.html">slider</a></li>
<li><a href="../widget types/status.html">status</a></li>
<li><strong>stepper</strong></li>
<li><a href="../widget types/text.html">text</a></li>
</ul>
<h2>Modules</h2>
<ul class="$(kind=='Topics' and '' or 'nowrap'">
<li><a href="../modules/attribute.html">attribute</a></li>
</ul>
<h2>Classes</h2>
<ul class="$(kind=='Topics' and '' or 'nowrap'">
<li><a href="../classes/Event.html">Event</a></li>
<li><a href="../classes/Layout.html">Layout</a></li>
<li><a href="../classes/Widget.html">Widget</a></li>
</ul>
</div>
<div id="content">
<h1>Widget <code>stepper</code></h1>
<p>A stepper.</p>
<p>This widget is composed of two buttons and a content area.
Upon creation, this widget's children are moved into an
<code>items</code> property. The items are displayed one at a time in
the content area. Pressing the buttons cycles through the
item displayed in the content area.</p>
<br/>
<br/>
</div> <!-- id="content" -->
</div> <!-- id="main" -->
<div id="about">
<i>generated by <a href="http://github.com/stevedonovan/LDoc">LDoc 1.4.3</a></i>
<i style="float:right;">Last updated 2015-12-05 16:15:11 </i>
</div> <!-- id="about" -->
</div> <!-- id="container" -->
</body>
</html>
|
airstruck/luigi
|
doc/widget types/stepper.html
|
HTML
|
mit
| 2,385
|
<?php
/**
* Created by PhpStorm.
* User: jonasse
* Date: 05.03.2015
* Time: 14:55
*/
namespace Tixi\ApiBundle\Interfaces\Dispo;
/**
* Class DrivingAssertionEditDTO
* @package Tixi\ApiBundle\Interfaces\Dispo
*/
class DrivingAssertionEditDTO {
public $driverId; // integer
public $driverName; // string firstname lastname
public $id; // integer
public $sortOrderString; // string date and time (local)
public $day; // string
public $shift; // string
public $assertionStatus; // integer
public $frequency; // string
public $parentSubject; // string
public $parentMemo; // multiline
}
|
Martin-Jonasse/sfitixi
|
src/Tixi/ApiBundle/Interfaces/Dispo/DrivingAssertionEditDTO.php
|
PHP
|
mit
| 745
|
\hypertarget{namespacegft_1_1Image32}{\section{gft\-:\-:Image32 Namespace Reference}
\label{namespacegft_1_1Image32}\index{gft\-::\-Image32@{gft\-::\-Image32}}
}
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
struct \hyperlink{structgft_1_1Image32_1_1__image32}{\-\_\-image32}
\end{DoxyCompactItemize}
\subsection*{Typedefs}
\begin{DoxyCompactItemize}
\item
typedef struct \\*
\hyperlink{structgft_1_1Image32_1_1__image32}{gft\-::\-Image32\-::\-\_\-image32} \hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32}
\end{DoxyCompactItemize}
\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$ \hyperlink{namespacegft_1_1Image32_aa1dc6b37e4b078f6a7957e1f4599fec6}{Sobel\-Filter} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img)
\item
\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$ \hyperlink{namespacegft_1_1Image32_a2d12581cb7829426c3a3401c0a45e7ef}{Linear\-Filter} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img, \hyperlink{namespacegft_1_1Kernel_a88f2f8f5778d1d17a52a77e1f2518ab3}{Kernel\-::\-Kernel} $\ast$K)
\item
\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$ \hyperlink{namespacegft_1_1Image32_a673f7fb9c237e0897132e35fd02d00d7}{Image\-Magnitude} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$imgx, \hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$imgy)
\item
\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$ \hyperlink{namespacegft_1_1Image32_aafef8dafc4fe11b3ad9384bc88f9282d}{Create} (int ncols, int nrows)
\begin{DoxyCompactList}\small\item\em A constructor. \end{DoxyCompactList}\item
void \hyperlink{namespacegft_1_1Image32_a8af9ff5a2bd012ec196a0c1a2ee70d8c}{Destroy} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$$\ast$img)
\begin{DoxyCompactList}\small\item\em A destructor. \end{DoxyCompactList}\item
\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$ \hyperlink{namespacegft_1_1Image32_a39385351619f9249e1178a86bdc7d641}{Clone} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img)
\begin{DoxyCompactList}\small\item\em A copy constructor. \end{DoxyCompactList}\item
\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$ \hyperlink{namespacegft_1_1Image32_a9a6ebcc61becc0cf51d7f5e2b00a2b13}{Read} (char $\ast$filename)
\item
void \hyperlink{namespacegft_1_1Image32_a505d58287ec93993f052b3790a474368}{Write} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img, char $\ast$filename)
\item
\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$ \hyperlink{namespacegft_1_1Image32_a2e5383b2fbe8ce694817ab91fd3782ba}{Convert\-To\-Nbits} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img, int N)
\item
int \hyperlink{namespacegft_1_1Image32_a636e6a116ad8d8ed2d165fe6c418abd9}{Get\-Minimum\-Value} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img)
\item
int \hyperlink{namespacegft_1_1Image32_a750d825c8a367d711b92b5fd517b0c95}{Get\-Maximum\-Value} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img)
\item
void \hyperlink{namespacegft_1_1Image32_a438912502a65d8184ca8281f54732b04}{Set} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img, int value)
\item
\hyperlink{namespacegft_a033dba4822661600b08d2bbf16879252}{bool} \hyperlink{namespacegft_1_1Image32_a4d4f4345c1fcd3f53f7cdb2bbcd5f5df}{Is\-Valid\-Pixel} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img, int x, int y)
\item
\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$ \hyperlink{namespacegft_1_1Image32_a5de6c6d8b8af8c7231719f7fd368c34c}{Threshold} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img, int L, int H)
\item
void \hyperlink{namespacegft_1_1Image32_a2f2526c9e47451a20ad5a0ef5af4283e}{Draw\-Rectangle} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img, int x1, int y1, int x2, int y2, int val)
\item
void \hyperlink{namespacegft_1_1Image32_a4f0d74d9624a853cfc4ad98dd89ba1f9}{Draw\-Line\-D\-D\-A} (\hyperlink{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{Image32} $\ast$img, int x1, int y1, int xn, int yn, int val)
\end{DoxyCompactItemize}
\subsection{Typedef Documentation}
\hypertarget{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Image32@{Image32}}
\index{Image32@{Image32}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Image32}]{\setlength{\rightskip}{0pt plus 5cm}typedef struct {\bf gft\-::\-Image32\-::\-\_\-image32} {\bf gft\-::\-Image32\-::\-Image32}}}\label{namespacegft_1_1Image32_a6c5a03566b593bb406f1fe33266a0382}
It supports both linear and two-\/dimensional access (i.\-e., img-\/$>$data\mbox{[}p\mbox{]} or img-\/$>$array\mbox{[}y\mbox{]}\mbox{[}x\mbox{]} for a pixel (x,y) at address p=x+y$\ast$xsize).
\subsection{Function Documentation}
\hypertarget{namespacegft_1_1Image32_a39385351619f9249e1178a86bdc7d641}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Clone@{Clone}}
\index{Clone@{Clone}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Clone}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Image32} $\ast$ gft\-::\-Image32\-::\-Clone (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a39385351619f9249e1178a86bdc7d641}
A copy constructor.
\hypertarget{namespacegft_1_1Image32_a2e5383b2fbe8ce694817ab91fd3782ba}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Convert\-To\-Nbits@{Convert\-To\-Nbits}}
\index{Convert\-To\-Nbits@{Convert\-To\-Nbits}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Convert\-To\-Nbits}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Image32} $\ast$ gft\-::\-Image32\-::\-Convert\-To\-Nbits (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img, }
\item[{int}]{N}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a2e5383b2fbe8ce694817ab91fd3782ba}
\hypertarget{namespacegft_1_1Image32_aafef8dafc4fe11b3ad9384bc88f9282d}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Create@{Create}}
\index{Create@{Create}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Create}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Image32} $\ast$ gft\-::\-Image32\-::\-Create (
\begin{DoxyParamCaption}
\item[{int}]{ncols, }
\item[{int}]{nrows}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_aafef8dafc4fe11b3ad9384bc88f9282d}
A constructor.
\hypertarget{namespacegft_1_1Image32_a8af9ff5a2bd012ec196a0c1a2ee70d8c}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Destroy@{Destroy}}
\index{Destroy@{Destroy}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Destroy}]{\setlength{\rightskip}{0pt plus 5cm}void gft\-::\-Image32\-::\-Destroy (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$$\ast$}]{img}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a8af9ff5a2bd012ec196a0c1a2ee70d8c}
A destructor.
\hypertarget{namespacegft_1_1Image32_a4f0d74d9624a853cfc4ad98dd89ba1f9}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Draw\-Line\-D\-D\-A@{Draw\-Line\-D\-D\-A}}
\index{Draw\-Line\-D\-D\-A@{Draw\-Line\-D\-D\-A}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Draw\-Line\-D\-D\-A}]{\setlength{\rightskip}{0pt plus 5cm}void gft\-::\-Image32\-::\-Draw\-Line\-D\-D\-A (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img, }
\item[{int}]{x1, }
\item[{int}]{y1, }
\item[{int}]{xn, }
\item[{int}]{yn, }
\item[{int}]{val}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a4f0d74d9624a853cfc4ad98dd89ba1f9}
\hypertarget{namespacegft_1_1Image32_a2f2526c9e47451a20ad5a0ef5af4283e}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Draw\-Rectangle@{Draw\-Rectangle}}
\index{Draw\-Rectangle@{Draw\-Rectangle}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Draw\-Rectangle}]{\setlength{\rightskip}{0pt plus 5cm}void gft\-::\-Image32\-::\-Draw\-Rectangle (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img, }
\item[{int}]{x1, }
\item[{int}]{y1, }
\item[{int}]{x2, }
\item[{int}]{y2, }
\item[{int}]{val}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a2f2526c9e47451a20ad5a0ef5af4283e}
\hypertarget{namespacegft_1_1Image32_a750d825c8a367d711b92b5fd517b0c95}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Get\-Maximum\-Value@{Get\-Maximum\-Value}}
\index{Get\-Maximum\-Value@{Get\-Maximum\-Value}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Get\-Maximum\-Value}]{\setlength{\rightskip}{0pt plus 5cm}int gft\-::\-Image32\-::\-Get\-Maximum\-Value (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a750d825c8a367d711b92b5fd517b0c95}
\hypertarget{namespacegft_1_1Image32_a636e6a116ad8d8ed2d165fe6c418abd9}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Get\-Minimum\-Value@{Get\-Minimum\-Value}}
\index{Get\-Minimum\-Value@{Get\-Minimum\-Value}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Get\-Minimum\-Value}]{\setlength{\rightskip}{0pt plus 5cm}int gft\-::\-Image32\-::\-Get\-Minimum\-Value (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a636e6a116ad8d8ed2d165fe6c418abd9}
\hypertarget{namespacegft_1_1Image32_a673f7fb9c237e0897132e35fd02d00d7}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Image\-Magnitude@{Image\-Magnitude}}
\index{Image\-Magnitude@{Image\-Magnitude}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Image\-Magnitude}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Image32} $\ast$ gft\-::\-Image32\-::\-Image\-Magnitude (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{imgx, }
\item[{Image32 $\ast$}]{imgy}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a673f7fb9c237e0897132e35fd02d00d7}
\hypertarget{namespacegft_1_1Image32_a4d4f4345c1fcd3f53f7cdb2bbcd5f5df}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Is\-Valid\-Pixel@{Is\-Valid\-Pixel}}
\index{Is\-Valid\-Pixel@{Is\-Valid\-Pixel}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Is\-Valid\-Pixel}]{\setlength{\rightskip}{0pt plus 5cm}{\bf bool} gft\-::\-Image32\-::\-Is\-Valid\-Pixel (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img, }
\item[{int}]{x, }
\item[{int}]{y}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a4d4f4345c1fcd3f53f7cdb2bbcd5f5df}
\hypertarget{namespacegft_1_1Image32_a2d12581cb7829426c3a3401c0a45e7ef}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Linear\-Filter@{Linear\-Filter}}
\index{Linear\-Filter@{Linear\-Filter}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Linear\-Filter}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Image32} $\ast$ gft\-::\-Image32\-::\-Linear\-Filter (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img, }
\item[{Kernel\-::\-Kernel $\ast$}]{K}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a2d12581cb7829426c3a3401c0a45e7ef}
\hypertarget{namespacegft_1_1Image32_a9a6ebcc61becc0cf51d7f5e2b00a2b13}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Read@{Read}}
\index{Read@{Read}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Read}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Image32} $\ast$ gft\-::\-Image32\-::\-Read (
\begin{DoxyParamCaption}
\item[{char $\ast$}]{filename}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a9a6ebcc61becc0cf51d7f5e2b00a2b13}
\hypertarget{namespacegft_1_1Image32_a438912502a65d8184ca8281f54732b04}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Set@{Set}}
\index{Set@{Set}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Set}]{\setlength{\rightskip}{0pt plus 5cm}void gft\-::\-Image32\-::\-Set (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img, }
\item[{int}]{value}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a438912502a65d8184ca8281f54732b04}
\hypertarget{namespacegft_1_1Image32_aa1dc6b37e4b078f6a7957e1f4599fec6}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Sobel\-Filter@{Sobel\-Filter}}
\index{Sobel\-Filter@{Sobel\-Filter}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Sobel\-Filter}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Image32} $\ast$ gft\-::\-Image32\-::\-Sobel\-Filter (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_aa1dc6b37e4b078f6a7957e1f4599fec6}
\hypertarget{namespacegft_1_1Image32_a5de6c6d8b8af8c7231719f7fd368c34c}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Threshold@{Threshold}}
\index{Threshold@{Threshold}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Threshold}]{\setlength{\rightskip}{0pt plus 5cm}{\bf Image32} $\ast$ gft\-::\-Image32\-::\-Threshold (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img, }
\item[{int}]{L, }
\item[{int}]{H}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a5de6c6d8b8af8c7231719f7fd368c34c}
\hypertarget{namespacegft_1_1Image32_a505d58287ec93993f052b3790a474368}{\index{gft\-::\-Image32@{gft\-::\-Image32}!Write@{Write}}
\index{Write@{Write}!gft::Image32@{gft\-::\-Image32}}
\subsubsection[{Write}]{\setlength{\rightskip}{0pt plus 5cm}void gft\-::\-Image32\-::\-Write (
\begin{DoxyParamCaption}
\item[{Image32 $\ast$}]{img, }
\item[{char $\ast$}]{filename}
\end{DoxyParamCaption}
)}}\label{namespacegft_1_1Image32_a505d58287ec93993f052b3790a474368}
|
ademirtc/bandeirantes
|
lib/gft/doc/latex/namespacegft_1_1Image32.tex
|
TeX
|
mit
| 13,529
|
+++
date = "2016-10-26T10:49:04+11:00"
title = "Bag Data Structure in Golang"
+++
A bag is a container of non-unique items. Bags are defined by the following
operations *Length*, *Add*, *Delete* and *Find*. Bags often also need to support
*FindAll*.
Bags can be ordered or un-ordered. This post will be discussing un-ordered
bags.
<!--more-->
Bags are useful when one needs to store a bunch of things and later check
if a certain thing is present. For example, storing the characters of a string
(and perhaps, the frequency count).
A bag can be easily implemented in Go using a map.
## bag of integers
For the sake of simplicity, we will first cover a bag of integers, then move
onto a bag of characters (including some useful functions on such a bag).
```
package bag
type count int
type Bag map[int]count
func (b *Bag) Len() int {
sum := 0
for _, v := range *b {
sum += int(v)
}
return sum
}
func (b *Bag) Add(x int) {
(*b)[x]++
}
func (b *Bag) Delete(x int) {
_, ok := (*b)[x]
if ok {
(*b)[x]--
}
}
func (b *Bag) Find(x int) (int, bool) {
count, ok := (*b)[x]
return int(count), ok
}
func (b *Bag) FindAll(x int) (int, bool) {
return b.Find(x) // not useful for this implementation
}
```
We can then use our bag of integers like this
```
func fn() {
bag := make(Bag)
// add some values to bag
for i := 0; i < 5; i++ {
bag.Add(i)
}
// check if we have a '2'
x, ok := bag.Find(2) // x = 1 (one '2' in bag), ok = true
// check if we have a '10'
x, ok = bag.Find(10) // ok = false (no '10' in bag)
// add a second '2' and check we now have two of them in bag
bag.Add(2)
x, ok := bag.Find(2) // x = 2 (two 2's in bag), ok = true
}
```
## bag of bytes
A bag of bytes can be used to store such things as byte values for characters
encoded using ASCII. This bag would not be very useful for storing text written
in Greek but would be useful for some cryptography tasks.
The basic operations are similar to the above, except of course we replace
occurences of `int` with `byte`. Also we add a helper function to create a bag
from a string (ASCII values only remember).
```
type Bag map[byte]int
func makeBag(s string) Bag {
bag := make(Bag)
for i := 0; i < len(s); i++ {
bag.Add(s[i])
}
return bag
}
```
We can then write some other functions to operate on this bag
```
func (b *Bag) difference(c Bag) Bag {
bag := make(Bag)
for k, vb := range *b {
vc, ok := c[k]
if ok {
if vb > vc {
bag[k] = vb - vc
}
} else {
bag[k] = vb
}
}
return bag
}
```
Similarly, one can implement union, and intersection in the above manner. See
Github for complete
[source code](https://github.com/tcharding/types/tree/master/bags) and tests.
---
#### Bibliography:
[Ski08] - **The Algorithm Design Manual**, Steven S. Skiena
[CLRS09] - **Introduction to Algorithms**, Thomas H.Cormen, Charles E. Leiserson,
Ronald L. Rivest, Clifford Stein
[Mor] - **Open Data Structures**, Pat Morin, Edition 0.1
|
tcharding/tobin.cc
|
content/blog/bag.md
|
Markdown
|
mit
| 2,997
|
import unittest
import unittest.mock as mock
import dice
import dice_config as dcfg
import dice_exceptions as dexc
class DiceInputVerificationTest(unittest.TestCase):
def test_dice_roll_input_wod(self):
examples = {'!r 5':[5, 10, None, 10, 8, 'wod', None],
'!r 2000':[2000, 10, None, 10, 8, 'wod', None],
'!r 2d8':[2, 8, None, None, None, 'wod', None],
'!r 7d6x4':[7, 6, None, 4, None, 'wod', None],
'!r 5000d700x700':[5000, 700, None, 700, None, 'wod', None],
'!r 15d20?20':[15, 20, None, None, 20, 'wod', None],
'!r 39d10x5?8':[39, 10, None, 5, 8, 'wod', None],
'!r 1d4x4?4':[1, 4, None, 4, 4, 'wod', None],
'!r 6d6+':[6, 6, 0, None, None, 'wod', None],
'!r 5d32+5':[5, 32, 5, None, None, 'wod', None],
'!r 17d4-12':[17, 4, -12, None, None, 'wod', None],
'!r 3d12+x12':[3, 12, 0, 12, None, 'wod', None],
'!r 10d20-7?15':[10, 20, -7, None, 15, 'wod', None],
'!r 768d37+33x5?23':[768, 37, 33, 5, 23, 'wod', None]}
for example, value in examples.items():
n, d, m, x, s, mode, cmd_msg = dice.dice_input_verification(example)
self.assertEqual([n, d, m, x, s, mode, cmd_msg], value)
def test_dice_roll_input_simple(self):
examples = {'!r 7':[7, 6, 0, None, None, 'simple', None],
'!r 2000':[2000, 6, 0, None, None, 'simple', None],
'!r 2d8':[2, 8, None, None, None, 'simple', None],
'!r 7d6x4':[7, 6, None, 4, None, 'simple', None],
'!r 8000d899x899':[8000, 899, None, 899, None, 'simple', None],
'!r 15d20?20':[15, 20, None, None, 20, 'simple', None],
'!r 39d10x5?8':[39, 10, None, 5, 8, 'simple', None],
'!r 1d4x4?4':[1, 4, None, 4, 4, 'simple', None],
'!r 6d6+':[6, 6, 0, None, None, 'simple', None],
'!r 5d32+5':[5, 32, 5, None, None, 'simple', None],
'!r 17d4-12':[17, 4, -12, None, None, 'simple', None],
'!r 3d12+x12':[3, 12, 0, 12, None, 'simple', None],
'!r 10d20-7?15':[10, 20, -7, None, 15, 'simple', None],
'!r 768d37+33x5?23':[768, 37, 33, 5, 23, 'simple', None]}
for example, value in examples.items():
n, d, m, x, s, mode, cmd_msg = dice.dice_input_verification(example, 'simple')
self.assertEqual([n, d, m, x, s, mode, cmd_msg], value)
def test_dice_options_help(self):
examples = {'!r help': [None, None, None, None, None, dcfg.mode, 'Find all available commands at:'
'\nhttps://github.com/brmedeiros/dicey9000/blob/master/README.md']}
for example, value in examples.items():
n, d, m, x, s, mode, cmd_msg = dice.dice_input_verification(example, dcfg.mode)
self.assertEqual([n, d, m, x, s, mode, cmd_msg], value)
def test_dice_options_mode(self):
examples = {'!r set wod': [None, None, None, None, None,
'wod', 'Default mode (!r n) set to World of Darksness (WoD)'],
'!r set simple': [None, None, None, None, None,
'simple', 'Default mode (!r n) set to simple (nd6)']}
for dmode in ['wod', 'simple']:
for example, value in examples.items():
n, d, m, x, s, mode, cmd_msg = dice.dice_input_verification(example, dmode)
self.assertEqual([n, d, m, x, s, mode, cmd_msg], value)
def test_dice_input_exception(self):
examples = ['!r ', '!r dmeoamdef', '!r kelf laij', '!r 2 3', '!r 6dz','!r 30dx', '!r 5d7x7?', '!r 9d10?',
'!r -10', '!r -6d8', '!r 6d8x?10', '!r 12d12x18?', '!r set ', '!r set help', '!r set akneoi',
'!r 3d6 help', '!r set 6d8?4 wod', '!r 6d12-', '!r 8d4-45?+', '!r 12d6+8-9', '!r 8d20-923+1x10?15',
'!r 6+','!r 5+2', '!r 7-', '!r 12-3', '!r 20x4', '!r 25?12', '!r 2+7x4?4', '!r 5-12x15?20']
for mode in ['wod', 'simple']:
for example in examples:
self.assertRaises(dexc.RollInputError, dice.dice_input_verification, example, mode)
def test_exploding_dice_exception(self):
examples = ['!r 5d8x9', '!r 12d60x100', '!r 1d6x9?4', '!r 78d5+x43', '!r 6d12-10x15', '!r 8d20+1x22?20']
for mode in ['wod', 'simple']:
for example in examples:
self.assertRaises(dexc.ExplodingDiceError, dice.dice_input_verification, example, mode)
def test_exploding_dice_too_small_exception(self):
examples = ['!r 5d8x1', '!r 8d6x2', '!r 3d70x1?10', '!r 10d2x2?2', '!r 78d5+x2', '!r 6d12-10x1',
'!r 8d20+1x2?20']
for mode in ['wod', 'simple']:
for example in examples:
self.assertRaises(dexc.ExplodingDiceTooSmallError, dice.dice_input_verification, example, mode)
def test_success_condition_exception(self):
examples = ['!r 2d8?9', '!r 2d15?55', '!r 65d10x6?11', '!r 32d5x5?100', '!r 78d5+?6', '!r 6d12-10?45',
'!r 8d20+1x18?200']
for mode in ['wod', 'simple']:
for example in examples:
self.assertRaises(dexc.SuccessConditionError, dice.dice_input_verification, example, mode)
def test_dice_type_exception(self):
examples = ['!r 2d0', '!r 50d0?55', '!r 6d0x6?11', '!r 32d0x5?100', '!r 78d0+?6', '!r 6d0-10?45',
'!r 8d0+1x18?200']
for mode in ['wod', 'simple']:
for example in examples:
self.assertRaises(dexc.DiceTypeError, dice.dice_input_verification, example, mode)
class DiceRollTest(unittest.TestCase):
@mock.patch('random.randint')
def test_roll_dice(self, random_call):
results = [1, 4, 6, 6, 2, 3, 5]
random_call.side_effect = results
target = dice.DiceRoll(7, 6, None, None, None)
target.roll_dice()
self.assertEqual(7, target.number_of_dice)
self.assertEqual(7, len(target.results))
for i, result in enumerate(results):
self.assertEqual(result, target.results[i])
self.assertEqual(str(result), target.formated_results[i])
@mock.patch('random.randint')
def test_total(self, random_call):
results = [1, 10, 5, 4, 10]
random_call.side_effect = results
examples = [0, 5, -10, 22, -50]
for example in examples:
target = dice.DiceRoll(5, 10, example, None, None)
target.roll_dice()
self.assertEqual(example, target.roll_modifier)
self.assertEqual(sum(results) + example, target.total)
@mock.patch('random.randint')
def test_explode(self, random_call):
results = [1, 12, 5, 4, 7, 6]
random_call.side_effect = results
target = dice.DiceRoll(6, 12, None, 12, None)
target.roll_dice()
self.assertEqual(12, target.explode_value)
self.assertEqual(len(results)+1, len(target.results))
|
brmedeiros/dicey9000
|
tests.py
|
Python
|
mit
| 7,240
|
//
// CompanyViewHelper.h
// TLChat
//
// Created by 戴王炯 on 4/26/16.
// Copyright © 2016 李伯坤. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface CompanyViewHelper : NSObject
@property (nonatomic, strong) NSMutableArray *companyData;
@property (nonatomic, strong) NSMutableArray *funData;
@end
|
dwjdwj1216/xiaoYouBang
|
TLChat/Business/CompanyViewHelper.h
|
C
|
mit
| 333
|
package org.icechamps.lava;
/**
* User: Robert.Diaz
* Date: 3/22/13
* Time: 11:12 AM
*/
public class PetOwner implements Comparable<PetOwner> {
public Person person;
public Pet pet;
public PetOwner(Person person, Pet pet) {
this.person = person;
this.pet = pet;
}
@Override
public int compareTo(PetOwner o) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == o) return EQUAL;
int comparison = this.person.compareTo(o.person);
if (comparison != EQUAL) return comparison;
comparison = this.pet.compareTo(o.pet);
if (comparison != EQUAL) return comparison;
assert this.equals(o) : "compareTo inconsistent with equals.";
return EQUAL;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PetOwner petOwner = (PetOwner) o;
if (!person.equals(petOwner.person)) return false;
if (!pet.equals(petOwner.pet)) return false;
return true;
}
@Override
public int hashCode() {
int result = person.hashCode();
result = 31 * result + pet.hashCode();
return result;
}
@Override
public String toString() {
return "PetOwner{" +
"person.name=" + person.name +
", pet.name=" + pet.name +
'}';
}
}
|
metaldrummer610/Lava
|
src/test/java/org/icechamps/lava/PetOwner.java
|
Java
|
mit
| 1,489
|
<?php
/**
* Export database and sanitise emails and other sensitive information
*/
if(php_sapi_name() !== 'cli') {
die('CLI only');
}
date_default_timezone_set('Europe/London');
require dirname(__FILE__) . '/../bootstrap.php';
$config = require dirname(__FILE__) . '/../inc/config.inc.php';
class FelixExporter extends \FelixOnline\Exporter\MySQLExporter
{
protected $count = 1;
function processTable($table)
{
echo "Working on: $table\n";
if ($table == 'akismet_log') {
return false;
}
if ($table == 'advert') {
return false;
}
if ($table == 'advert_category') {
return false;
}
if ($table == 'article_visit') {
return false;
}
if ($table == 'api_keys') {
return false;
}
if ($table == 'api_log') {
return false;
}
if ($table == 'archive_file') {
return false;
}
if ($table == 'archive_issue') {
return false;
}
if ($table == 'archive_publication') {
return false;
}
if ($table == 'email_validation') {
return false;
}
if ($table == 'cookies') {
return false;
}
if ($table == 'login') {
return false;
}
if ($table == 'audit_log') {
return false;
}
return $table;
}
function processRow($row, $table)
{
if ($row['deleted'] == 1) {
return false;
}
if ($table == 'category') {
if ($row['secret'] == 1) {
return false;
}
}
if ($table == 'article') {
// Check if in a secret category
$res = $this->db->query(
"SELECT
secret
FROM `category`
WHERE category='".$row['category']."'");
if($res) {
$secret = $res->fetch_row()[0];
} else {
$secret = 0;
}
if($secret == 1) {
return false;
}
if ($row['hidden'] == 1) {
return false;
}
if ($row['published'] == 0) {
return false;
}
}
if ($table == 'link') {
if ($row['active'] == 0) {
return false;
}
}
if ($table == 'comment') {
if ($row['spam'] == 1) {
return false;
}
$row['email'] = 'test-'.$this->count.'@example.com';
$row['ip'] = '0.0.0.0';
$row['referer'] = 'Anonymised';
$row['useragent'] = 'Anonymised';
$this->count++;
}
if ($table == 'user') {
// Check if user has any articles
$res = $this->db->query(
"SELECT
COUNT(article.id)
FROM `article`
INNER JOIN `article_author`
ON (article.id=article_author.article)
INNER JOIN `article_publication`
ON (article.id=article_publication.article)
AND article_publication.republished = 0
WHERE article_author.author='".$row['user']."'");
if($res) {
$count = $res->fetch_row()[0];
} else {
$count = 0;
}
if ($count > 0) {
$row['ip'] = '0.0.0.0';
$row['facebook'] = NULL;
$row['twitter'] = NULL;
$row['websitename'] = NULL;
$row['websiteurl'] = NULL;
$row['info'] = "[]";
$row['visits'] = 0;
if ($row['email'] ) {
$row['email'] = "test-".$this->count."@example.com";
$this->count++;
}
} else {
return false;
}
}
if ($table == 'comment_like') {
$row['ip'] = '0.0.0.0';
$row['user_agent'] = 'Anonymised';
}
if ($table == 'polls_response') {
$row['ip'] = '0.0.0.0';
$row['useragent'] = 'Anonymised';
}
return $row;
}
}
$orig_directory = getcwd();
// change to backup directory
$backup_directory = realpath(dirname(__FILE__) . '/../backups');
chdir($backup_directory);
// Remove old backups
$files = glob("*.sql.zip");
$time = time();
foreach ($files as $file) {
if (is_file($file) && !is_link($file)) {
if ($time - filemtime($file) >= 60 * 60 * 24 * 2) { // 2 days - get older stuff from ICU backup
unlink($file);
}
}
}
// Start export
$db_file = $config['db_name'] . '-' . date("Y-m-d") . '.sql';
$exporter = new FelixExporter(array(
'db_name' => $config['db_name'],
'db_user' => $config['db_user'],
'db_pass' => $config['db_pass'],
'file' => $db_file,
));
$exporter->run();
echo "Compressing...\n";
// Zip file
exec(sprintf("zip %s %s", $db_file . '.zip', $db_file), $output, $return);
if ($return !== 0) {
throw new Exception(implode("\n", $output));
}
// Remove original sql file
unlink($db_file);
// create symlink
$symlink = 'latest.sql.zip';
if (file_exists($symlink)) {
unlink($symlink);
}
symlink($db_file . '.zip', $symlink);
// Move back to original directory
chdir($orig_directory);
echo "Completed: ".realpath(dirname(__FILE__)) . '/../backups/'.$db_file.".zip\n";
exit(0);
|
FelixOnline/FelixOnline
|
scripts/export-db.php
|
PHP
|
mit
| 4,434
|
/* ヘッダファイルのインクルード */
#include <stdio.h> /* C標準入出力 */
#include <string.h> /* C文字列処理 */
#include <unistd.h> /* UNIX標準 */
#include <X11/Xlib.h> /* Xlib */
#include <X11/Xutil.h> /* Xユーティリティ */
#include <X11/Xatom.h> /* アトム */
/* main関数 */
int main(int argc, char **argv){
/* 変数の宣言と初期化. */
Display *d; /* Display構造体へのポインタd. */
Window wr; /* ウィンドウ生成の結果を表す値wr.(Window == XID == unsigned long) */
int result; /* マップの結果result. */
unsigned long white; /* 白のRGB値white. */
XEvent event; /* XEvent構造体(共用体)のevent. */
int i; /* ループ用変数i. */
XTextProperty text_property; /* テキストプロパティtext_property. */
char title[] = "ABCDE"; /* タイトルtitleを"ABCDE"で初期化. */
Atom atom_wm_delete_window; /* WM_DELETE_WINDOWのアトムatom_wm_delete_window. */
Atom atom_wm_protocols; /* WM_PROTOCOLSのアトムatom_wm_protocols. */
int default_screen; /* デフォルトスクリーン番号default_screen. */
Colormap default_colormap; /* デフォルトカラーマップdefault_colormap. */
XColor color1; /* 色情報color1 */
XColor color2; /* 色情報color2 */
GC graphics_context; /* グラフィックスコンテキストgraphics_context. */
/* Xサーバとの接続. */
d = XOpenDisplay(NULL); /* XOpenDisplayでXサーバに接続し, 戻り値のアドレスをdに格納. */
/* dを出力. */
printf("d = %08x\n", d); /* dの値を16進数で出力. */
/* デフォルトスクリーン番号の取得. */
default_screen = DefaultScreen(d); /* DefaultScreenでデフォルトスクリーン番号を取得し, default_screenに格納. */
printf("default_screen = %d\n", default_screen); /* default_screenを出力. */
/* デフォルトカラーマップの取得. */
default_colormap = DefaultColormap(d, default_screen); /* DefaultColormapでdefault_screenのdefault_colormapを取得. */
printf("default_colormap = %08x\n", default_colormap); /* default_colormapを出力. */
/* 青のピクセル値を取得. */
color1.red = 0x0; /* redは0x0. */
color1.green = 0x0; /* greenは0x0. */
color1.blue = 0xffff; /* blueは0xffff. */
XAllocColor(d, default_colormap, &color1); /* XAllocColorにRGB値を設定したcolor1を指定するとピクセル値が格納される. */
/* 赤のピクセル値を取得. */
color2.red = 0xffff; /* redは0xffff. */
color2.green = 0x0; /* greenは0x0. */
color2.blue = 0x0; /* blueは0x0. */
XAllocColor(d, default_colormap, &color2); /* XAllocColorにRGB値を設定したcolor2を指定するとピクセル値が格納される. */
/* 白のピクセル値を取得. */
white = XWhitePixel(d, 0); /* XWhitePixelでスクリーン0における白のピクセル値を取得し, whiteに格納. */
/* ウィンドウの生成. */
wr = XCreateSimpleWindow(d, DefaultRootWindow(d), 100, 100, 640, 480, 1, white, white); /* XCreateSimpleWindowでウィンドウ生成し, 結果はwrに格納. */
/* ウィンドウ生成の結果を出力. */
printf("wr = %08x\n", wr); /* wrを出力. */
/* グラフィックスコンテキストの生成. */
graphics_context = XCreateGC(d, wr, 0, NULL); /* XCreateGCでグラフィックスコンテキストを生成し, ポインタgraphics_contextを返す. */
printf("graphics_context = %08x\n", graphics_context); /* ポインタgraphics_contextを出力. */
/* ウィンドウのマッピング(表示要求) */
result = XMapWindow(d, wr); /* XMapWindowでマッピング. */
/* マッピング結果を出力. */
printf("result = %d\n", result); /* resultの値を出力. */
/* テキストプロパティのセット. */
text_property.value = (unsigned char *)title; /* タイトル文字列を指定. */
text_property.encoding = XA_STRING; /* XA_STRINGを指定. */
text_property.format = 8; /* 半角英数の場合8ビットなので8を指定. */
text_property.nitems = strlen(title); /* titleの文字数を指定. */
XSetWMProperties(d, wr, &text_property, NULL, argv, argc, NULL, NULL, NULL); /* XSetWMPropertiesでウィンドウマネージャにtext_propertyをセット. */
/* WM_PROTOCOLSにWM_DELETE_WINDOWをセット. */
atom_wm_delete_window = XInternAtom(d, "WM_DELETE_WINDOW", False); /* XInternAtomで"WM_DELETE_WINDOW"のアトムを取得. */
XSetWMProtocols(d, wr, &atom_wm_delete_window, 1); /* XSetWMProtocolsでatom_wm_delete_windowをセット. */
/* WM_PROTOCOLSのアトムを取得. */
atom_wm_protocols = XInternAtom(d, "WM_PROTOCOLS", False); /* XInternAtomでWM_PROTOCOLSのアトムを取得. */
/* イベントマスクのセット. */
XSelectInput(d, wr, ButtonPressMask | ButtonReleaseMask | StructureNotifyMask | ExposureMask); /* XSelectInputでマスクをセット.(ExposureMaskを追加.) */
/* 表示要求イベントをフラッシュ. */
XFlush(d); /* XFlushでフラッシュ. */
/* iの初期化. */
i = 0; /* iを0にしておく. */
/* イベントループ. */
while (1){
/* イベントの取得. */
XNextEvent(d, &event); /* XNextEventでeventを取得. */
/* イベントタイプごとに処理. */
switch (event.type){ /* event.typeの値で分岐. */
/* ButtonPress */
case ButtonPress: /* マウスボタンが押された時. */
/* ButtonPressブロック. */
{
/* マウス位置の出力. */
printf("(%d, %d)\n", event.xbutton.x, event.xbutton.y); /* event.xbutton.xとevent.xbutton.yを出力. */
i++; /* iをインクリメント. */
if (i == 10){ /* iが10の時. */
/* Xサーバとの接続を終了する. */
XCloseDisplay(d); /* XCloseDisplayで切断する. */
/* プログラムの終了 */
return 0; /* 0を返して正常終了. */
}
}
/* break. */
break; /* breakで終わる. */
/* ButtonRelease */
case ButtonRelease: /* マウスボタンが離された時. */
/* ButtonReleaseブロック. */
{
/* "ButtonRelease!!". */
printf("ButtonRelease!!\n"); /* "ButtonRelease!!"と出力. */
}
/* break. */
break; /* breakで終わる. */
/* ClientMessage */
case ClientMessage: /* クライアントメッセージ */
/* ClientMessageブロック. */
{
/* WM_PROTOCOLSの場合. */
if (event.xclient.message_type == atom_wm_protocols){ /* atom_wm_protocolsなら. */
/* "WM_PROTOCOLS!" */
printf("WM_PROTOCOLS!\n"); /* "WM_PROTOCOLS!"と出力. */
/* WM_DELETE_WINDOWなら終了. */
if (event.xclient.data.l[0] == atom_wm_delete_window){ /* atom_wm_delete_windowなら. */
/* "WM_DELETE_WINDOW!!" */
printf("WM_DELETE_WINDOW!!\n"); /* "WM_DELETE_WINDOW!!"と出力. */
/* ウィンドウを破棄. */
XDestroyWindow(d, wr); /* XDestroyWindowでウィンドウを破棄. */
}
}
}
/* break. */
break; /* breakで終わる. */
/* DestroyNotify */
case DestroyNotify: /* ウィンドウ破棄通知. */
/* DestroyNotifyブロック. */
{
/* graphics_contextの解放. */
XFreeGC(d, graphics_context); /* XFreeGCでgraphics_contextの解放. */
/* "DestroyNotify!" */
printf("DestroyNotify!\n"); /* "DestroyNotify!"と出力. */
/* 切断したら全てのリソースを破棄. */
XSetCloseDownMode(d, DestroyAll); /* XSetCloseDownModeでDestroyAllをセット. */
/* Xサーバとの接続を終了する. */
XCloseDisplay(d); /* XCloseDisplayで切断する. */
/* プログラムの終了 */
return 0; /* 0を返して正常終了. */
}
/* break. */
break; /* breakで終わる. */
/* Expose */
case Expose: /* 描画要求. */
/* Exposeブロック */
{
/* 描画色を青に設定. */
XSetForeground(d, graphics_context, color1.pixel); /* XSetForegroundでcolor1.pixelをセット. */
/* 点の描画 */
XDrawPoint(d, wr, graphics_context, 50, 50); /* (50, 50)の位置に点を描画. */
XDrawPoint(d, wr, graphics_context, 60, 60); /* (60, 60)の位置に点を描画. */
XDrawPoint(d, wr, graphics_context, 70, 70); /* (70, 70)の位置に点を描画. */
XDrawPoint(d, wr, graphics_context, 80, 80); /* (80, 80)の位置に点を描画. */
XDrawPoint(d, wr, graphics_context, 90, 90); /* (90, 90)の位置に点を描画. */
/* 描画色を赤に設定. */
XSetForeground(d, graphics_context, color2.pixel); /* XSetForegroundでcolor2.pixelをセット. */
/* 点の描画 */
XDrawPoint(d, wr, graphics_context, 100, 50); /* (100, 50)の位置に点を描画. */
XDrawPoint(d, wr, graphics_context, 90, 60); /* (90, 60)の位置に点を描画. */
XDrawPoint(d, wr, graphics_context, 80, 70); /* (80, 70)の位置に点を描画. */
XDrawPoint(d, wr, graphics_context, 70, 80); /* (70, 80)の位置に点を描画. */
XDrawPoint(d, wr, graphics_context, 60, 90); /* (60, 90)の位置に点を描画. */
}
/* break. */
break; /* breakで終わる. */
/* default */
default: /* それ以外. */
/* break. */
break; /* breakで終わる. */
}
}
}
|
bg1bgst333/Sample
|
xlib/XSetForeground/XSetForeground/src/XSetForeground/XSetForeground.c
|
C
|
mit
| 9,740
|
'use strict';
module.exports = function (t, a) {
a(t(), false, "Undefined");
a(t(1), false, "Primitive");
a(t({}), false, "Objectt");
a(t({
toString: function () {
return '[object Error]';
}
}), false,
"Fake error");
a(t(new Error()), true, "Error");
a(t(new EvalError()), true, "EvalError");
a(t(new RangeError()), true, "RangeError");
a(t(new ReferenceError()), true, "ReferenceError");
a(t(new SyntaxError()), true, "SyntaxError");
a(t(new TypeError()), true, "TypeError");
a(t(new URIError()), true, "URIError");
};
|
runningfun/angular_project
|
node_modules/bower/node_modules/inquirer/node_modules/cli-color/node_modules/es5-ext/test/error/is-error.js
|
JavaScript
|
mit
| 621
|
namespace LaptopListingSystem.Services.Administration.Contracts
{
using System.Linq;
using LaptopListingSystem.Services.Common;
public interface IAdministrationService<TEntity>
where TEntity : class
{
IQueryable<TEntity> Read();
TEntity Get(params object[] id);
void Create(TEntity entity);
void Update(TEntity entity);
void Delete(params object[] id);
void Delete(TEntity entity);
}
}
|
KristianMariyanov/LaptopListingSystem
|
Services/LaptopListingSystem.Services.Administration/Contracts/IAdministrationService.cs
|
C#
|
mit
| 472
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>newest</title>
<link rel="stylesheet" media="screen" href="css/index.css">
<link rel="stylesheet" type="text/css" href="font/font.css">
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/GlobalValue.js"></script>
<style>
.review{
float: left;
font-size: 13px;
height: 30px;
line-height: 30px;
}
ul img{
height: 20px;
margin: 5px;
float: left;
}
#right-container .review{
height: 20px;
font-size: 14px;
line-height: 20px;
margin-left: 10px;
}
</style>
<!--
作者:731275785@qq.com
时间:2017-07-22
描述:验证登录与加载用户数据
-->
<script>
if($.cookie('newestUserId')==null || $.cookie('newestUserName')==null){
window.location.href = "login-register.html";
}
</script>
</head>
<body>
<div id="index-container">
<div id="index-head">
<div id="index-head-inner">
<a href="index.html"><img style="height: 50px; float: left;" src="pic/title.png"></a>
<ul id="index-head-nav">
<li><a href="index.html">新鲜事</a>
<ul>
<li><a href="publish-post.html">发布</a></li>
<li><a href="mypost.html">我的</a></li>
</ul>
</li>
<li><a>新闻</a>
<ul>
<li><a id="new-tech">要闻</a></li>
<li><a id="new-science">科学</a></li>
<li><a id="new-soft">软件</a></li>
<li><a id="new-game">游戏</a></li>
<li><a id="new-movie">影视</a></li>
<li><a id="new-comic">动漫</a></li>
<li><a id="new-funny">趣闻</a></li>
</ul>
</li>
</ul>
<div class="search-bar">
<div id="popver">
<div id="search-bar-container">
<input id="search-bar-input" type="text" placeholder="搜索你感兴趣的内容">
<button id="search-bar-button"></button>
</div>
</div>
</div>
<button class="search-button" id="search">搜索</button>
</div>
</div>
<div style="padding: 0 16px;margin: 65px auto auto auto">
<div id="new-content">
<div id="mylike">
<div style="padding-left: 20px;">我的喜欢</div>
</div>
<div id="new-container">
<div id="content-main">
<ul id="ul-for-new">
</ul>
<div id="none">没有更多啦</div>
</div>
</div>
</div>
<div id="index-right">
<div id="right-container">
<div class="person-head" id="myHeadPic"></div>
<div class="person-name" id="myName"></div>
<div class="person-piece">
<img height="20px" style="float: left;" src="pic/review.png">
<div class="review" id="myReview">@我的</div>
</div>
<div class="person-piece">
<img height="20px" style="float: left;" src="pic/like.png">
<div class="review" id="myLike">我的喜欢</div>
</div>
<div class="person-piece">
<img height="20px" style="float: left;" src="pic/setup.png">
<div class="review" id="mySetting">我的设置</div>
</div>
<button id="log-out">注 销</button>
</div>
</div>
</div>
</div>
<!--
作者:731275785@qq.com
时间:2017-07-21
描述:全局变量
-->
<script>
var u1 = u + "my-like";
var u3 = u + "like";
var u4 = "news.html?postId=";
var ajaxobj;
var list =
'<li class="list-news">' +
'<div class="list-news-top">' +
'<div class="media-head"></div>' +
'<div class="media-name"></div>' +
'<div class="news-classify">'+
'<div class="review" style="margin-right:4px;"></div>' +
'</div>' +
'</div>' +
'<div class="new-item-content">' +
'<h3><a></a></h3>' +
'<div class="new-item-content-inner"></div>' +
'</div>' +
'<div class="list-news-action">' +
'<div class="list-news-action-review">' +
'<img src="pic/review.png">' +
'<a class="review" style="padding: 0;">评论</a>' +
'</div>' +
'<div class="list-news-action-like">' +
'<img>' +
'<div class="review"></div>' +
'<div class="review">喜欢</div>' +
'</div>' +
'<div class="list-news-action-time"></div>' +
'</div>' +
'</li>';
</script>
<!--
作者:731275785@qq.com
时间:2017-07-21
描述:喜欢的切换
-->
<script>
function sendAddLike(dataId){
$.ajax({
type:"post",
url:u3,
async:true,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data:{
post_id: dataId,
user_id: $.cookie('newestUserId'),
liked: +1
}
});
}
function sendSubLike(dataId){
$.ajax({
type:"post",
url:u3,
async:true,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data:{
post_id: dataId,
user_id: $.cookie('newestUserId'),
liked: -1
}
});
}
$("body").on("click","img", function(){
if($(this).attr("src") == "pic/like.png" && $(this).attr("id") == null){
$(this).attr("src","pic/like-click.png");
var likeNum = $(this).next().html();
$(this).next().html(Number(likeNum)+1);
sendAddLike($(this).parent().parent().parent().data("postId"));
}
else if($(this).attr("src") == "pic/like-click.png" && $(this).attr("id") == null){
$(this).attr("src","pic/like.png");
var likeNum = $(this).next().html();
$(this).next().html(Number(likeNum)-1);
sendSubLike($(this).parent().parent().parent().data("postId"));
$(this).parent().parent().parent().remove();
}
else{
//do nothing
}
});
</script>
<!--
作者:731275785@qq.com
时间:2017-07-22
描述:点击查看详情
-->
<script>
$("body").on("click","h3 a:first-child", function(){
window.location.href = u4 +
$(this).parent().parent().parent().data("postId") + "=category=" +
$(this).parent().parent().parent().data("category");
});
$("body").on("click",".new-item-content-inner", function(){
window.location.href = u4 +
$(this).parent().parent().data("postId") + "=category=" +
$(this).parent().parent().parent().data("category");
});
$("body").on("click",".list-news-action-review", function(){
window.location.href = u4 +
$(this).parent().parent().data("postId") + "=category=" +
$(this).parent().parent().data("category") + "=reviews";
});
</script>
<!--
作者:731275785@qq.com
时间:2017-07-22
描述:验证登录与加载用户数据
-->
<script>
function sendMyLike(){
$.ajax({
type:"post",
url:u1,
async:true,
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data:{
user_id: $.cookie('newestUserId')
},
success:function(data){
ajaxobj = JSON.parse(data);
if(ajaxobj.isOk == true){
if(ajaxobj.posts.length > 0){
for(var i=0; i<ajaxobj.posts.length; i++){
appendList(ajaxobj.posts[i].post_id,ajaxobj.posts[i].author_name,
ajaxobj.posts[i].author_id,ajaxobj.posts[i].title,
ajaxobj.posts[i].content,ajaxobj.posts[i].time,
ajaxobj.posts[i].author_pic,
ajaxobj.posts[i].category,
ajaxobj.posts[i].isLiked,ajaxobj.posts[i].liked);
}
}
}
}
});
}
if($.cookie('newestUserId') && $.cookie('newestUserName')){
$("#myName").html($.cookie('newestUserName'));
$("#myHeadPic").css("background-image","url("+$.cookie('newestUserPic')+")");
$("#myHeadPic").css("background-size","100px 100px");
sendMyLike();
}
</script>
<!--
作者:731275785@qq.com
时间:2017-07-22
描述:注销
-->
<script>
function logOut(){
// $.cookie('newestUserId', null, {
// expires : -1,
// });
$.cookie('newestUserPassword', null, {
expires : -1,
});
$.cookie('newestUserName',null, {
expires : -1,
});
$.cookie('newestUserPic',null, {
expires : -1,
});
}
$("#log-out").click(function(){
logOut();
window.location.reload();
})
</script>
<!--
作者:731275785@qq.com
时间:2017-07-21
描述:动态添加
-->
<script>
function appendList(postId,authorName,authorId,title,content,time,author_pic,category,isLiked,liked){
$("#ul-for-new").append(list);
$("#ul-for-new li:last-child").data("postId",postId);
$("#ul-for-new li:last-child").data("category",category);
$("#ul-for-new li:last-child").children(".list-news-top").children(".media-head").css("background-image","url("+author_pic+")");
$("#ul-for-new li:last-child").children(".list-news-top").children(".media-head").css("background-size","26px 26px");
$("#ul-for-new li:last-child").children(".list-news-top").children(".media-name").html(authorName);
if(category == "game"){
$("#ul-for-new li:last-child").children(".list-news-top").children(".news-classify").children(".review").html("游戏");
}
else if(category == "science"){
$("#ul-for-new li:last-child").children(".list-news-top").children(".news-classify").children(".review").html("科学");
}
else if(category == "tech"){
$("#ul-for-new li:last-child").children(".list-news-top").children(".news-classify").children(".review").html("要闻");
}
else if(category == "soft"){
$("#ul-for-new li:last-child").children(".list-news-top").children(".news-classify").children(".review").html("软件");
}
else if(category == "funny"){
$("#ul-for-new li:last-child").children(".list-news-top").children(".news-classify").children(".review").html("趣闻");
}
else if(category == "comic"){
$("#ul-for-new li:last-child").children(".list-news-top").children(".news-classify").children(".review").html("动漫");
}
else if(category == "新鲜事"){
$("#ul-for-new li:last-child").children(".list-news-top").children(".news-classify").children(".review").html("新鲜事");
}
else{
$("#ul-for-new li:last-child").children(".list-news-top").children(".news-classify").children(".review").html("影视");
}
$("#ul-for-new li:last-child").children(".new-item-content").children("h3").children("a").html(title);
$("#ul-for-new li:last-child").children(".new-item-content").children(".new-item-content-inner").html(content);
$("#ul-for-new li:last-child").children(".list-news-action").children(".list-news-action-like").children(".review").first().html(liked);
if(isLiked){
$("#ul-for-new li:last-child").children(".list-news-action").children(".list-news-action-like").children("img").attr("src","pic/like-click.png");
}
else{
$("#ul-for-new li:last-child").children(".list-news-action").children(".list-news-action-like").children("img").attr("src","pic/like.png");
}
$("#ul-for-new li:last-child").children(".list-news-action").children(".list-news-action-time").html(time);
}
</script>
<!--
作者:731275785@qq.com
时间:2017-07-24
描述:选择新闻种类
-->
<script>
$("#new-funny").click(function(){
window.location.href = "subnew.html?category=funny";
});
$("#new-game").click(function(){
window.location.href = "subnew.html?category=game";
});
$("#new-movie").click(function(){
window.location.href = "subnew.html?category=movie";
});
$("#new-comic").click(function(){
window.location.href = "subnew.html?category=comic";
});
$("#new-soft").click(function(){
window.location.href = "subnew.html?category=soft";
});
$("#new-tech").click(function(){
window.location.href = "subnew.html?category=tech";
});
$("#new-science").click(function(){
window.location.href = "subnew.html?category=science";
})
</script>
<!--
作者:731275785@qq.com
时间:2017-07-25
描述:@我的
-->
<script>
$("#myReview").click(function(){
window.location.href = "review-list.html";
});
</script>
<!--
作者:731275785@qq.com
时间:2017-07-25
描述:我的设置
-->
<script>
$("#mySetting").click(function(){
window.location.href = "setup.html";
});
$("#myLike").click(function(){
window.location.href = "mylike.html";
});
</script>
<!--
作者:731275785@qq.com
时间:2017-07-26
描述:搜索
-->
<script>
$("#search").click(function(){
if($("#search-bar-input").val() != ""){
window.location.href = "search-user.html?keyword=" + $("#search-bar-input").val();
}
});
</script>
</body>
</html>
|
SCU-Newest/Newest
|
mylike.html
|
HTML
|
mit
| 13,057
|
Kivy_SMS_service
================
Example code to make a service in kivy that intercepts incoming sms messages.
|
LISTERINE/Kivy_SMS_service
|
README.md
|
Markdown
|
mit
| 113
|
@extends('vendor.installer.layouts.master')
@section('title', 'Installation Complete')
@section('container')
<p class="paragraph">Access to this installer is now disabled.</p>
<div class="buttons">
<a href="{{ url('/') }}" class="button">{{ trans('messages.final.exit') }}</a>
</div>
@stop
|
scci/security-employee-tracker
|
resources/views/vendor/installer/finished.blade.php
|
PHP
|
mit
| 310
|
import tensorflow as tf
import numpy as np
from baselines.ppo2.model import Model
class MicrobatchedModel(Model):
"""
Model that does training one microbatch at a time - when gradient computation
on the entire minibatch causes some overflow
"""
def __init__(self, *, policy, ob_space, ac_space, nbatch_act, nbatch_train,
nsteps, ent_coef, vf_coef, max_grad_norm, mpi_rank_weight, comm, microbatch_size):
self.nmicrobatches = nbatch_train // microbatch_size
self.microbatch_size = microbatch_size
assert nbatch_train % microbatch_size == 0, 'microbatch_size ({}) should divide nbatch_train ({}) evenly'.format(microbatch_size, nbatch_train)
super().__init__(
policy=policy,
ob_space=ob_space,
ac_space=ac_space,
nbatch_act=nbatch_act,
nbatch_train=microbatch_size,
nsteps=nsteps,
ent_coef=ent_coef,
vf_coef=vf_coef,
max_grad_norm=max_grad_norm,
mpi_rank_weight=mpi_rank_weight,
comm=comm)
self.grads_ph = [tf.placeholder(dtype=g.dtype, shape=g.shape) for g in self.grads]
grads_ph_and_vars = list(zip(self.grads_ph, self.var))
self._apply_gradients_op = self.trainer.apply_gradients(grads_ph_and_vars)
def train(self, lr, cliprange, obs, returns, masks, actions, values, neglogpacs, states=None):
assert states is None, "microbatches with recurrent models are not supported yet"
# Here we calculate advantage A(s,a) = R + yV(s') - V(s)
# Returns = R + yV(s')
advs = returns - values
# Normalize the advantages
advs = (advs - advs.mean()) / (advs.std() + 1e-8)
# Initialize empty list for per-microbatch stats like pg_loss, vf_loss, entropy, approxkl (whatever is in self.stats_list)
stats_vs = []
for microbatch_idx in range(self.nmicrobatches):
_sli = range(microbatch_idx * self.microbatch_size, (microbatch_idx+1) * self.microbatch_size)
td_map = {
self.train_model.X: obs[_sli],
self.A:actions[_sli],
self.ADV:advs[_sli],
self.R:returns[_sli],
self.CLIPRANGE:cliprange,
self.OLDNEGLOGPAC:neglogpacs[_sli],
self.OLDVPRED:values[_sli]
}
# Compute gradient on a microbatch (note that variables do not change here) ...
grad_v, stats_v = self.sess.run([self.grads, self.stats_list], td_map)
if microbatch_idx == 0:
sum_grad_v = grad_v
else:
# .. and add to the total of the gradients
for i, g in enumerate(grad_v):
sum_grad_v[i] += g
stats_vs.append(stats_v)
feed_dict = {ph: sum_g / self.nmicrobatches for ph, sum_g in zip(self.grads_ph, sum_grad_v)}
feed_dict[self.LR] = lr
# Update variables using average of the gradients
self.sess.run(self._apply_gradients_op, feed_dict)
# Return average of the stats
return np.mean(np.array(stats_vs), axis=0).tolist()
|
openai/baselines
|
baselines/ppo2/microbatched_model.py
|
Python
|
mit
| 3,241
|
var config = require('./config'),
db;
function warn() {
console.warn('[WARN] MongoDB:', [].join.call(arguments, ' '));
}
function getDB(done) {
if (db) return done(db);
if (!config.mongoURI) return warn('No DB configured!');
require('mongodb').MongoClient.connect(config.mongoURI, function(err, _db) {
if (err) return warn('Failed to connect ->', err.message);
db = _db;
done(db);
});
}
function store(coll, data) {
data.now = new Date().toISOString();
getDB(function(db) {
db.collection(coll).insert(data, function(err) {
if (err) warn('Failed to insert to', coll, '->', err.message);
// Do nothing
});
});
}
exports.getEmailsByTo = function(to, done) {
getDB(function(db) {
db.collection(config.emailsCollection).find({to:to}).toArray(done);
});
};
exports.storeEmail = function(data) {
store(config.emailsCollection, data);
};
exports.storeError = function(data) {
store(config.errorsCollection, data);
};
|
flesler/EaaS
|
lib/db.js
|
JavaScript
|
mit
| 946
|
export default class TeamScoreModel {
constructor(props) {
this.id = props.id
this.teamId = props.team_id
this.defencePoints = props.defence_points
this.attackPoints = props.attack_points
}
get totalPoints() {
return this.defencePoints + this.attackPoints
}
}
|
aspyatkin/themis-finals
|
www/src/scripts/models/team-score-model.js
|
JavaScript
|
mit
| 317
|
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="HTTrack is an easy-to-use website mirror utility. It allows you to download a World Wide website from the Internet to a local directory,building recursively all structures, getting html, images, and other files from the server to your computer. Links are rebuiltrelatively so that you can freely browse to the local site (works with any browser). You can mirror several sites together so that you can jump from one toanother. You can, also, update an existing mirror site, or resume an interrupted download. The robot is fully configurable, with an integrated help" />
<meta name="keywords" content="httrack, HTTRACK, HTTrack, winhttrack, WINHTTRACK, WinHTTrack, offline browser, web mirror utility, aspirateur web, surf offline, web capture, www mirror utility, browse offline, local site builder, website mirroring, aspirateur www, internet grabber, capture de site web, internet tool, hors connexion, unix, dos, windows 95, windows 98, solaris, ibm580, AIX 4.0, HTS, HTGet, web aspirator, web aspirateur, libre, GPL, GNU, free software" />
<title>List of available projects - HTTrack Website Copier</title>
<!-- Mirror and index made by HTTrack Website Copier/3.47-21 [XR&CO'2013] -->
<style type="text/css">
<!--
body {
margin: 0; padding: 0; margin-bottom: 15px; margin-top: 8px;
background: #77b;
}
body, td {
font: 14px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
}
#subTitle {
background: #000; color: #fff; padding: 4px; font-weight: bold;
}
#siteNavigation a, #siteNavigation .current {
font-weight: bold; color: #448;
}
#siteNavigation a:link { text-decoration: none; }
#siteNavigation a:visited { text-decoration: none; }
#siteNavigation .current { background-color: #ccd; }
#siteNavigation a:hover { text-decoration: none; background-color: #fff; color: #000; }
#siteNavigation a:active { text-decoration: none; background-color: #ccc; }
a:link { text-decoration: underline; color: #00f; }
a:visited { text-decoration: underline; color: #000; }
a:hover { text-decoration: underline; color: #c00; }
a:active { text-decoration: underline; }
#pageContent {
clear: both;
border-bottom: 6px solid #000;
padding: 10px; padding-top: 20px;
line-height: 1.65em;
background-image: url(backblue.gif);
background-repeat: no-repeat;
background-position: top right;
}
#pageContent, #siteNavigation {
background-color: #ccd;
}
.imgLeft { float: left; margin-right: 10px; margin-bottom: 10px; }
.imgRight { float: right; margin-left: 10px; margin-bottom: 10px; }
hr { height: 1px; color: #000; background-color: #000; margin-bottom: 15px; }
h1 { margin: 0; font-weight: bold; font-size: 2em; }
h2 { margin: 0; font-weight: bold; font-size: 1.6em; }
h3 { margin: 0; font-weight: bold; font-size: 1.3em; }
h4 { margin: 0; font-weight: bold; font-size: 1.18em; }
.blak { background-color: #000; }
.hide { display: none; }
.tableWidth { min-width: 400px; }
.tblRegular { border-collapse: collapse; }
.tblRegular td { padding: 6px; background-image: url(fade.gif); border: 2px solid #99c; }
.tblHeaderColor, .tblHeaderColor td { background: #99c; }
.tblNoBorder td { border: 0; }
// -->
</style>
</head>
<body>
<table width="76%" border="0" align="center" cellspacing="0" cellpadding="3" class="tableWidth">
<tr>
<td id="subTitle">HTTrack Website Copier - Open Source offline browser</td>
</tr>
</table>
<table width="76%" border="0" align="center" cellspacing="0" cellpadding="0" class="tableWidth">
<tr class="blak">
<td>
<table width="100%" border="0" align="center" cellspacing="1" cellpadding="0">
<tr>
<td colspan="6">
<table width="100%" border="0" align="center" cellspacing="0" cellpadding="10">
<tr>
<td id="pageContent">
<!-- ==================== End prologue ==================== -->
<h1 ALIGN=Center>Index of locally available projects:</H1>
<table border="0" width="100%" cellspacing="1" cellpadding="0">
<TH>
<BR/>
No categories
</TH>
<TR>
<TD BACKGROUND="fade.gif">
· <A HREF="CodeIgniter%202.1.4/index.html">CodeIgniter 2.1.4</A>
</TD>
</TR>
</TABLE>
<BR>
<H6 ALIGN="RIGHT">
<I>Mirror and index made by HTTrack Website Copier [XR&CO'2008]</I>
</H6>
<!-- Mirror and index made by HTTrack Website Copier/3.47-21 [XR&CO'2013] -->
<!-- Thanks for using HTTrack Website Copier! -->
<!-- ==================== Start epilogue ==================== -->
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<table width="76%" border="0" align="center" valign="bottom" cellspacing="0" cellpadding="0">
<tr>
<td id="footer"><small>© 2008 Xavier Roche & other contributors - Web Design: Leto Kauler.</small></td>
</tr>
</table>
</body>
</html>
|
pulipulichen/php-file-converter
|
user_guide_zh_tw/index.html
|
HTML
|
mit
| 5,078
|
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " docker-build build the docker-image with image name 'redisco-grokzen'"
@echo " docker-run run the docker-image named 'redisco-grokzen'"
@echo " docker-build-run first build and then run docker image."
@echo " test run nosetest suite with all doctests. Requires a running redis server (Use the docker image)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Redisco.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Redisco.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Redisco"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Redisco"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
docker-build:
sudo docker build -t redisco-grokzen .
docker-run:
sudo docker run -p 6379:6379 -i -t redisco-grokzen
docker-build-run: docker-build docker-run
test:
nosetests --with-doctest
|
Grokzen/redisco
|
Makefile
|
Makefile
|
mit
| 6,271
|
Topic summary...
## Symptoms
## Causes
## Diagnose
### Scenario Title
## Advice
## Resolve
|
rotorz/unity3d-tile-system
|
docs/templates/Troubleshooting-Topic.md
|
Markdown
|
mit
| 106
|
// Multiform extraction
|
luishendrix92/utilboxjs
|
src/String/extract.js
|
JavaScript
|
mit
| 23
|
<?php
namespace SixtyNine\ClassGrapher\Model;
interface ItemInterface
{
const TYPE_CLASS = 'class';
const TYPE_INTERFACE = 'interface';
const TYPE_METHOD = 'method';
function getFile();
function getType();
function getLine();
function getName();
function setName($name);
}
|
sixty-nine/ClassGrapher
|
src/SixtyNine/ClassGrapher/Model/ItemInterface.php
|
PHP
|
mit
| 308
|
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <author name="Daniel Grunwald"/>
// <version>$Revision: 3090 $</version>
// </file>
using System;
using System.Collections.Generic;
using System.Threading;
namespace WorldBankBBS.ICSharpCode.TextEditor.Src.Util
{
/// <summary>
/// A IList{T} that checks that it is only accessed on the thread that created it, and that
/// it is not modified while an enumerator is running.
/// </summary>
sealed class CheckedList<T> : IList<T>
{
readonly int threadID;
readonly IList<T> baseList;
int enumeratorCount;
public CheckedList() : this(new List<T>()) {}
public CheckedList(IList<T> baseList)
{
if (baseList == null)
throw new ArgumentNullException("baseList");
this.baseList = baseList;
this.threadID = Thread.CurrentThread.ManagedThreadId;
}
void CheckRead()
{
if (Thread.CurrentThread.ManagedThreadId != threadID)
throw new InvalidOperationException("CheckList cannot be accessed from this thread!");
}
void CheckWrite()
{
if (Thread.CurrentThread.ManagedThreadId != threadID)
throw new InvalidOperationException("CheckList cannot be accessed from this thread!");
if (enumeratorCount != 0)
throw new InvalidOperationException("CheckList cannot be written to while enumerators are active!");
}
public T this[int index] {
get {
CheckRead();
return baseList[index];
}
set {
CheckWrite();
baseList[index] = value;
}
}
public int Count {
get {
CheckRead();
return baseList.Count;
}
}
public bool IsReadOnly {
get {
CheckRead();
return baseList.IsReadOnly;
}
}
public int IndexOf(T item)
{
CheckRead();
return baseList.IndexOf(item);
}
public void Insert(int index, T item)
{
CheckWrite();
baseList.Insert(index, item);
}
public void RemoveAt(int index)
{
CheckWrite();
baseList.RemoveAt(index);
}
public void Add(T item)
{
CheckWrite();
baseList.Add(item);
}
public void Clear()
{
CheckWrite();
baseList.Clear();
}
public bool Contains(T item)
{
CheckRead();
return baseList.Contains(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
CheckRead();
baseList.CopyTo(array, arrayIndex);
}
public bool Remove(T item)
{
CheckWrite();
return baseList.Remove(item);
}
public IEnumerator<T> GetEnumerator()
{
CheckRead();
return Enumerate();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
CheckRead();
return Enumerate();
}
IEnumerator<T> Enumerate()
{
CheckRead();
try {
enumeratorCount++;
foreach (T val in baseList) {
yield return val;
CheckRead();
}
} finally {
enumeratorCount--;
CheckRead();
}
}
}
}
|
sharpninja/WorldBankBBS
|
WorldBankBBS.ICSharpCode.TextEditor/Src/Util/CheckedList.cs
|
C#
|
mit
| 2,908
|
#ifndef __ModuleSceneIntro_H__
#define __ModuleSceneIntro_H__
#include "Module.h"
#include "Globals.h"
#include "Primitive.h"
#include "Geometry.h"
#include "Mesh.h"
#include <list>
//#include "PhysBody3D.h"
struct PhysBody3D;
class ModuleSceneIntro : public Module
{
public:
ModuleSceneIntro(Application* app, const char* name, bool start_enabled = true);
~ModuleSceneIntro();
bool Init(cJSON* node);
bool Start();
update_status Update(float dt);
bool Draw();
bool CleanUp();
//void OnCollision(PhysBody3D* body1, PhysBody3D* body2);
public:
//Mesh* m;
//list<Geometry*> geometries;
InCube* b;
//PhysBody3D* b;
};
#endif // __ModuleSceneIntro_H__
|
laura-96/GameEngine
|
GameEngine/ModuleSceneIntro.h
|
C
|
mit
| 671
|
(function (global, factory) {
if (typeof define === 'function' && define.amd) {
define(['exports', 'module', '../util/data'], factory);
} else if (typeof exports !== 'undefined' && typeof module !== 'undefined') {
factory(exports, module, require('../util/data'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, mod, global.data);
global.attached = mod.exports;
}
})(this, function (exports, module, _utilData) {
'use strict';
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _data = _interopRequireDefault(_utilData);
module.exports = function (opts) {
return function () {
var info = (0, _data['default'])(this, 'lifecycle/' + opts.id);
if (info.attached) return;
info.attached = true;
info.detached = false;
opts.attached(this);
};
};
});
|
antitoxic/skatejs
|
lib/lifecycle/attached.js
|
JavaScript
|
mit
| 893
|
import django
# Django 1.5 add support for custom auth user model
from django.conf import settings
if django.VERSION >= (1, 5):
AUTH_USER_MODEL = settings.AUTH_USER_MODEL
else:
try:
from django.contrib.auth.models import User
AUTH_USER_MODEL = 'auth.User'
except ImportError:
raise ImportError(u"User model is not to be found.")
# location of patterns, url, include changes in 1.4 onwards
try:
from django.conf.urls import patterns, url, include
except:
from django.conf.urls.defaults import patterns, url, include
|
maroux/django-relationships
|
relationships/compat.py
|
Python
|
mit
| 563
|
from PyQt4.QtGui import *
import pypipe.formats
import pypipe.basefile
from pypipe.core import pipeline
from widgets.combobox import ComboBox
class AddFileDialog(QDialog):
def __init__(self, parent=None):
super(AddFileDialog, self).__init__(parent)
self.formats_combo = ComboBox()
self.filename_edit = QLineEdit()
self.open_button = QPushButton('Open')
self.ok_button = QPushButton('&OK')
self.cancel_button = QPushButton('&Cancel')
self.setWindowTitle('Add file')
top_layout = QVBoxLayout()
top_layout.addWidget(QLabel('<b>File format:</b>'))
top_layout.addWidget(self.formats_combo)
top_layout.addWidget(QLabel('<b>File Name:</b>'))
center_layout = QHBoxLayout()
center_layout.addWidget(self.filename_edit)
center_layout.addWidget(self.open_button)
bottom_layout = QHBoxLayout()
bottom_layout.addWidget(self.ok_button)
bottom_layout.addWidget(self.cancel_button)
layout = QVBoxLayout()
layout.addLayout(top_layout)
layout.addLayout(center_layout)
layout.addLayout(bottom_layout)
self.setLayout(layout)
self.formats_combo.add_classes_from_module(pypipe.formats)
self.connect_all()
def connect_all(self):
self.cancel_button.clicked.connect(self.reject)
self.filename_edit.textChanged.connect(self.turn_ok_button)
self.formats_combo.currentIndexChanged.connect(self.turn_ok_button)
self.ok_button.clicked.connect(self.accept)
self.open_button.clicked.connect(self.open_file)
def turn_ok_button(self):
try:
f = self.get_file()
self.ok_button.setEnabled(True)
except pypipe.basefile.FileNotExistsError:
self.ok_button.setEnabled(False)
return
if pypipe.core.pipeline.can_add_file(f):
self.ok_button.setEnabled(True)
else:
self.ok_button.setEnabled(False)
def open_file(self):
file_name = QFileDialog.getOpenFileName(self, 'Open file')
self.filename_edit.setText(file_name)
def get_file(self):
init = self.formats_combo.get_current_item()
path = str(self.filename_edit.text())
return init(path)
def exec_(self):
self.turn_ok_button()
super(AddFileDialog, self).exec_()
|
ctlab/pypipe
|
pypipe-gui/windows/addfiledialog.py
|
Python
|
mit
| 2,392
|
# 智能指针
> [ch15-00-smart-pointers.md](https://github.com/rust-lang/book/blob/main/src/ch15-00-smart-pointers.md)
> <br>
> commit 1fedfc4b96c2017f64ecfcf41a0a07e2e815f24f
**指针** (*pointer*)是一个包含内存地址的变量的通用概念。这个地址引用,或 “指向”(points at)一些其他数据。Rust 中最常见的指针是第四章介绍的 **引用**(*reference*)。引用以 `&` 符号为标志并借用了他们所指向的值。除了引用数据没有任何其他特殊功能。它们也没有任何额外开销,所以应用得最多。
另一方面,**智能指针**(*smart pointers*)是一类数据结构,他们的表现类似指针,但是也拥有额外的元数据和功能。智能指针的概念并不为 Rust 所独有;其起源于 C++ 并存在于其他语言中。Rust 标准库中不同的智能指针提供了多于引用的额外功能。本章将会探索的一个例子便是 **引用计数** (*reference counting*)智能指针类型,其允许数据有多个所有者。引用计数智能指针记录总共有多少个所有者,并当没有任何所有者时负责清理数据。
在 Rust 中,普通引用和智能指针的一个额外的区别是引用是一类只借用数据的指针;相反,在大部分情况下,智能指针 **拥有** 他们指向的数据。
实际上本书中已经出现过一些智能指针,比如第八章的 `String` 和 `Vec<T>`,虽然当时我们并不这么称呼它们。这些类型都属于智能指针因为它们拥有一些数据并允许你修改它们。它们也带有元数据(比如他们的容量)和额外的功能或保证(`String` 的数据总是有效的 UTF-8 编码)。
智能指针通常使用结构体实现。智能指针区别于常规结构体的显著特性在于其实现了 `Deref` 和 `Drop` trait。`Deref` trait 允许智能指针结构体实例表现的像引用一样,这样就可以编写既用于引用、又用于智能指针的代码。`Drop` trait 允许我们自定义当智能指针离开作用域时运行的代码。本章会讨论这些 trait 以及为什么对于智能指针来说他们很重要。
考虑到智能指针是一个在 Rust 经常被使用的通用设计模式,本章并不会覆盖所有现存的智能指针。很多库都有自己的智能指针而你也可以编写属于你自己的智能指针。这里将会讲到的是来自标准库中最常用的一些:
* `Box<T>`,用于在堆上分配值
* `Rc<T>`,一个引用计数类型,其数据可以有多个所有者
* `Ref<T>` 和 `RefMut<T>`,通过 `RefCell<T>` 访问。( `RefCell<T>` 是一个在运行时而不是在编译时执行借用规则的类型)。
另外我们会涉及 **内部可变性**(*interior mutability*)模式,这是不可变类型暴露出改变其内部值的 API。我们也会讨论 **引用循环**(*reference cycles*)会如何泄漏内存,以及如何避免。
让我们开始吧!
|
KaiserY/trpl-zh-cn
|
src/ch15-00-smart-pointers.md
|
Markdown
|
mit
| 2,993
|
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at okaanagac@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
|
CynicalApe/Dijkstra-Graph
|
CODE_OF_CONDUCT.md
|
Markdown
|
mit
| 3,216
|
@import "n.css";
* {
box-sizing: border-box;
}
body{
padding-left: 30px;
}
.sidebar-place{
flex-grow: 1;
flex-shrink: 0;
}
.main-flex{
flex-grow: 5;
flex-shrink: 3;
}
.big-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 70%;
}
.list-container {
width:80%;
display: flex;
/* border-bottom: 1px solid orange;
border-top: 1px solid orange; */
}
.inside-container {
display: flex;
flex-direction: column;
width: 100%;
}
.sidebar-p {
margin: 0;
font-size: 20px;
color: #ff8732;
letter-spacing: 2px;
font-weight: bold;
display: flex;
font-family: 'Roboto', sans-serif;
}
.p-container {
display: flex;
width: 100%;
}
.sidebar-items{
margin: 0 auto;
width: 100%;
height: 100%;
padding: 3px 0;
padding-left: 8px;
font-size: 17px;
letter-spacing: 0.8px;
text-decoration: none;
color: black;
}
.sidebar-items:hover{
color: #ff8732;
}
.sidebar-section{
margin-bottom: 10px;
width: 100%;
}
.sidebar-hr {
border-color: #ff8732;
width: 75%;
float: left;
margin: 10px 0 7px 0!important;
}
|
LetsnetHungary/sinalisal
|
_assets/css/sidebar.css
|
CSS
|
mit
| 1,126
|
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { GlobalService } from '../service/global.service';
@Injectable()
export class ReportService {
constructor (private http: HttpClient, private global: GlobalService) {
}
public postReport (data: FormData): Observable<any> {
return this.http.post(this.global.url + `/report`, data).map((res: any) => {
if ( res.status === 'success' ) {
return res.result;
} else {
alert('[ERROR]: ' + res.result);
}
});
}
public getReportList (): Observable<any> {
return this.http.get(this.global.url + `/report`).map((res: any) => {
if ( res.status === 'success' ) {
return res.result;
} else {
alert('[ERROR]: ' + res.result);
}
})
}
public getReportById (id: number): Observable<any> {
return this.http.get(this.global.url + `/report/${id}`).map((res: any) => {
if ( res.status === 'success' ) {
return res.result;
} else {
alert('[ERROR]: ' + res.result);
}
})
}
}
|
kit-se/SE_Booking_System_front
|
src/app/shared/http/report.service.ts
|
TypeScript
|
mit
| 1,288
|
<h1>Book Detail</h1>
{% if book %}
Title: {{ book.name }}
{% else % }
Book not found: {{ error }}
{% endif %}
|
oliverroick/django-tests
|
books/templates/book_detail.html
|
HTML
|
mit
| 111
|
#include <gtest/gtest.h>
#include <cpuinfo.h>
#include <cpuinfo-mock.h>
TEST(PROCESSORS, count) {
ASSERT_EQ(8, cpuinfo_get_processors_count());
}
TEST(PROCESSORS, non_null) {
ASSERT_TRUE(cpuinfo_get_processors());
}
TEST(PROCESSORS, smt_id) {
for (uint32_t i = 0; i < cpuinfo_get_processors_count(); i++) {
ASSERT_EQ(0, cpuinfo_get_processor(i)->smt_id);
}
}
TEST(PROCESSORS, core) {
for (uint32_t i = 0; i < cpuinfo_get_processors_count(); i++) {
ASSERT_EQ(cpuinfo_get_core(i), cpuinfo_get_processor(i)->core);
}
}
TEST(PROCESSORS, cluster) {
for (uint32_t i = 0; i < cpuinfo_get_processors_count(); i++) {
switch (i) {
case 0:
case 1:
case 2:
case 3:
ASSERT_EQ(cpuinfo_get_cluster(0), cpuinfo_get_processor(i)->cluster);
break;
case 4:
case 5:
case 6:
case 7:
ASSERT_EQ(cpuinfo_get_cluster(1), cpuinfo_get_processor(i)->cluster);
break;
}
}
}
TEST(PROCESSORS, package) {
for (uint32_t i = 0; i < cpuinfo_get_processors_count(); i++) {
ASSERT_EQ(cpuinfo_get_package(0), cpuinfo_get_processor(i)->package);
}
}
TEST(PROCESSORS, linux_id) {
for (uint32_t i = 0; i < cpuinfo_get_processors_count(); i++) {
switch (i) {
case 0:
case 1:
case 2:
case 3:
ASSERT_EQ(i + 4, cpuinfo_get_processor(i)->linux_id);
break;
case 4:
case 5:
case 6:
case 7:
ASSERT_EQ(i - 4, cpuinfo_get_processor(i)->linux_id);
break;
}
}
}
TEST(PROCESSORS, l1i) {
for (uint32_t i = 0; i < cpuinfo_get_processors_count(); i++) {
ASSERT_EQ(cpuinfo_get_l1i_cache(i), cpuinfo_get_processor(i)->cache.l1i);
}
}
TEST(PROCESSORS, l1d) {
for (uint32_t i = 0; i < cpuinfo_get_processors_count(); i++) {
ASSERT_EQ(cpuinfo_get_l1d_cache(i), cpuinfo_get_processor(i)->cache.l1d);
}
}
TEST(PROCESSORS, l2) {
for (uint32_t i = 0; i < cpuinfo_get_processors_count(); i++) {
switch (i) {
case 0:
case 1:
case 2:
case 3:
ASSERT_EQ(cpuinfo_get_l2_cache(0), cpuinfo_get_processor(i)->cache.l2);
break;
case 4:
case 5:
case 6:
case 7:
ASSERT_EQ(cpuinfo_get_l2_cache(1), cpuinfo_get_processor(i)->cache.l2);
break;
}
}
}
TEST(PROCESSORS, l3) {
for (uint32_t i = 0; i < cpuinfo_get_processors_count(); i++) {
ASSERT_FALSE(cpuinfo_get_processor(i)->cache.l3);
}
}
TEST(PROCESSORS, l4) {
for (uint32_t i = 0; i < cpuinfo_get_processors_count(); i++) {
ASSERT_FALSE(cpuinfo_get_processor(i)->cache.l4);
}
}
TEST(CORES, count) {
ASSERT_EQ(8, cpuinfo_get_cores_count());
}
TEST(CORES, non_null) {
ASSERT_TRUE(cpuinfo_get_cores());
}
TEST(CORES, processor_start) {
for (uint32_t i = 0; i < cpuinfo_get_cores_count(); i++) {
ASSERT_EQ(i, cpuinfo_get_core(i)->processor_start);
}
}
TEST(CORES, processor_count) {
for (uint32_t i = 0; i < cpuinfo_get_cores_count(); i++) {
ASSERT_EQ(1, cpuinfo_get_core(i)->processor_count);
}
}
TEST(CORES, core_id) {
for (uint32_t i = 0; i < cpuinfo_get_cores_count(); i++) {
ASSERT_EQ(i, cpuinfo_get_core(i)->core_id);
}
}
TEST(CORES, cluster) {
for (uint32_t i = 0; i < cpuinfo_get_cores_count(); i++) {
switch (i) {
case 0:
case 1:
case 2:
case 3:
ASSERT_EQ(cpuinfo_get_cluster(0), cpuinfo_get_core(i)->cluster);
break;
case 4:
case 5:
case 6:
case 7:
ASSERT_EQ(cpuinfo_get_cluster(1), cpuinfo_get_core(i)->cluster);
break;
}
}
}
TEST(CORES, package) {
for (uint32_t i = 0; i < cpuinfo_get_cores_count(); i++) {
ASSERT_EQ(cpuinfo_get_package(0), cpuinfo_get_core(i)->package);
}
}
TEST(CORES, vendor) {
for (uint32_t i = 0; i < cpuinfo_get_cores_count(); i++) {
ASSERT_EQ(cpuinfo_vendor_arm, cpuinfo_get_core(i)->vendor);
}
}
TEST(CORES, uarch) {
for (uint32_t i = 0; i < cpuinfo_get_cores_count(); i++) {
ASSERT_EQ(cpuinfo_uarch_cortex_a53, cpuinfo_get_core(i)->uarch);
}
}
TEST(CORES, midr) {
for (uint32_t i = 0; i < cpuinfo_get_cores_count(); i++) {
ASSERT_EQ(UINT32_C(0x410FD034), cpuinfo_get_core(i)->midr);
}
}
TEST(CORES, DISABLED_frequency) {
for (uint32_t i = 0; i < cpuinfo_get_cores_count(); i++) {
ASSERT_EQ(UINT64_C(1586000000), cpuinfo_get_core(i)->frequency);
}
}
TEST(CLUSTERS, count) {
ASSERT_EQ(2, cpuinfo_get_clusters_count());
}
TEST(CLUSTERS, non_null) {
ASSERT_TRUE(cpuinfo_get_clusters());
}
TEST(CLUSTERS, processor_start) {
for (uint32_t i = 0; i < cpuinfo_get_clusters_count(); i++) {
switch (i) {
case 0:
ASSERT_EQ(0, cpuinfo_get_cluster(i)->processor_start);
break;
case 1:
ASSERT_EQ(4, cpuinfo_get_cluster(i)->processor_start);
break;
}
}
}
TEST(CLUSTERS, processor_count) {
for (uint32_t i = 0; i < cpuinfo_get_clusters_count(); i++) {
ASSERT_EQ(4, cpuinfo_get_cluster(i)->processor_count);
}
}
TEST(CLUSTERS, core_start) {
for (uint32_t i = 0; i < cpuinfo_get_clusters_count(); i++) {
switch (i) {
case 0:
ASSERT_EQ(0, cpuinfo_get_cluster(i)->core_start);
break;
case 1:
ASSERT_EQ(4, cpuinfo_get_cluster(i)->core_start);
break;
}
}
}
TEST(CLUSTERS, core_count) {
for (uint32_t i = 0; i < cpuinfo_get_clusters_count(); i++) {
ASSERT_EQ(4, cpuinfo_get_cluster(i)->core_count);
}
}
TEST(CLUSTERS, cluster_id) {
for (uint32_t i = 0; i < cpuinfo_get_clusters_count(); i++) {
ASSERT_EQ(i, cpuinfo_get_cluster(i)->cluster_id);
}
}
TEST(CLUSTERS, package) {
for (uint32_t i = 0; i < cpuinfo_get_clusters_count(); i++) {
ASSERT_EQ(cpuinfo_get_package(0), cpuinfo_get_cluster(i)->package);
}
}
TEST(CLUSTERS, vendor) {
for (uint32_t i = 0; i < cpuinfo_get_clusters_count(); i++) {
ASSERT_EQ(cpuinfo_vendor_arm, cpuinfo_get_cluster(i)->vendor);
}
}
TEST(CLUSTERS, uarch) {
for (uint32_t i = 0; i < cpuinfo_get_clusters_count(); i++) {
ASSERT_EQ(cpuinfo_uarch_cortex_a53, cpuinfo_get_cluster(i)->uarch);
}
}
TEST(CLUSTERS, midr) {
for (uint32_t i = 0; i < cpuinfo_get_clusters_count(); i++) {
ASSERT_EQ(UINT32_C(0x410FD034), cpuinfo_get_cluster(i)->midr);
}
}
TEST(CLUSTERS, DISABLED_frequency) {
for (uint32_t i = 0; i < cpuinfo_get_clusters_count(); i++) {
ASSERT_EQ(UINT64_C(1586000000), cpuinfo_get_cluster(i)->frequency);
}
}
TEST(PACKAGES, count) {
ASSERT_EQ(1, cpuinfo_get_packages_count());
}
TEST(PACKAGES, name) {
for (uint32_t i = 0; i < cpuinfo_get_packages_count(); i++) {
ASSERT_EQ("Samsung Exynos 7870",
std::string(cpuinfo_get_package(i)->name,
strnlen(cpuinfo_get_package(i)->name, CPUINFO_PACKAGE_NAME_MAX)));
}
}
TEST(PACKAGES, gpu_name) {
for (uint32_t i = 0; i < cpuinfo_get_packages_count(); i++) {
ASSERT_EQ("ARM Mali-T830",
std::string(cpuinfo_get_package(i)->gpu_name,
strnlen(cpuinfo_get_package(i)->gpu_name, CPUINFO_GPU_NAME_MAX)));
}
}
TEST(PACKAGES, processor_start) {
for (uint32_t i = 0; i < cpuinfo_get_packages_count(); i++) {
ASSERT_EQ(0, cpuinfo_get_package(i)->processor_start);
}
}
TEST(PACKAGES, processor_count) {
for (uint32_t i = 0; i < cpuinfo_get_packages_count(); i++) {
ASSERT_EQ(8, cpuinfo_get_package(i)->processor_count);
}
}
TEST(PACKAGES, core_start) {
for (uint32_t i = 0; i < cpuinfo_get_packages_count(); i++) {
ASSERT_EQ(0, cpuinfo_get_package(i)->core_start);
}
}
TEST(PACKAGES, core_count) {
for (uint32_t i = 0; i < cpuinfo_get_packages_count(); i++) {
ASSERT_EQ(8, cpuinfo_get_package(i)->core_count);
}
}
TEST(PACKAGES, cluster_start) {
for (uint32_t i = 0; i < cpuinfo_get_packages_count(); i++) {
ASSERT_EQ(0, cpuinfo_get_package(i)->cluster_start);
}
}
TEST(PACKAGES, cluster_count) {
for (uint32_t i = 0; i < cpuinfo_get_packages_count(); i++) {
ASSERT_EQ(2, cpuinfo_get_package(i)->cluster_count);
}
}
TEST(ISA, thumb) {
#if CPUINFO_ARCH_ARM
ASSERT_TRUE(cpuinfo_has_arm_thumb());
#elif CPUINFO_ARCH_ARM64
ASSERT_FALSE(cpuinfo_has_arm_thumb());
#endif
}
TEST(ISA, thumb2) {
#if CPUINFO_ARCH_ARM
ASSERT_TRUE(cpuinfo_has_arm_thumb2());
#elif CPUINFO_ARCH_ARM64
ASSERT_FALSE(cpuinfo_has_arm_thumb2());
#endif
}
TEST(ISA, armv5e) {
#if CPUINFO_ARCH_ARM
ASSERT_TRUE(cpuinfo_has_arm_v5e());
#elif CPUINFO_ARCH_ARM64
ASSERT_FALSE(cpuinfo_has_arm_v5e());
#endif
}
TEST(ISA, armv6) {
#if CPUINFO_ARCH_ARM
ASSERT_TRUE(cpuinfo_has_arm_v6());
#elif CPUINFO_ARCH_ARM64
ASSERT_FALSE(cpuinfo_has_arm_v6());
#endif
}
TEST(ISA, armv6k) {
#if CPUINFO_ARCH_ARM
ASSERT_TRUE(cpuinfo_has_arm_v6k());
#elif CPUINFO_ARCH_ARM64
ASSERT_FALSE(cpuinfo_has_arm_v6k());
#endif
}
TEST(ISA, armv7) {
#if CPUINFO_ARCH_ARM
ASSERT_TRUE(cpuinfo_has_arm_v7());
#elif CPUINFO_ARCH_ARM64
ASSERT_FALSE(cpuinfo_has_arm_v7());
#endif
}
TEST(ISA, armv7mp) {
#if CPUINFO_ARCH_ARM
ASSERT_TRUE(cpuinfo_has_arm_v7mp());
#elif CPUINFO_ARCH_ARM64
ASSERT_FALSE(cpuinfo_has_arm_v7mp());
#endif
}
TEST(ISA, idiv) {
ASSERT_TRUE(cpuinfo_has_arm_idiv());
}
TEST(ISA, vfpv2) {
ASSERT_FALSE(cpuinfo_has_arm_vfpv2());
}
TEST(ISA, vfpv3) {
ASSERT_TRUE(cpuinfo_has_arm_vfpv3());
}
TEST(ISA, vfpv3_d32) {
ASSERT_TRUE(cpuinfo_has_arm_vfpv3_d32());
}
TEST(ISA, vfpv3_fp16) {
ASSERT_TRUE(cpuinfo_has_arm_vfpv3_fp16());
}
TEST(ISA, vfpv3_fp16_d32) {
ASSERT_TRUE(cpuinfo_has_arm_vfpv3_fp16_d32());
}
TEST(ISA, vfpv4) {
ASSERT_TRUE(cpuinfo_has_arm_vfpv4());
}
TEST(ISA, vfpv4_d32) {
ASSERT_TRUE(cpuinfo_has_arm_vfpv4_d32());
}
TEST(ISA, wmmx) {
ASSERT_FALSE(cpuinfo_has_arm_wmmx());
}
TEST(ISA, wmmx2) {
ASSERT_FALSE(cpuinfo_has_arm_wmmx2());
}
TEST(ISA, neon) {
ASSERT_TRUE(cpuinfo_has_arm_neon());
}
TEST(ISA, neon_fp16) {
ASSERT_TRUE(cpuinfo_has_arm_neon_fp16());
}
TEST(ISA, neon_fma) {
ASSERT_TRUE(cpuinfo_has_arm_neon_fma());
}
TEST(ISA, atomics) {
ASSERT_FALSE(cpuinfo_has_arm_atomics());
}
TEST(ISA, neon_rdm) {
ASSERT_FALSE(cpuinfo_has_arm_neon_rdm());
}
TEST(ISA, fp16_arith) {
ASSERT_FALSE(cpuinfo_has_arm_fp16_arith());
}
TEST(ISA, jscvt) {
ASSERT_FALSE(cpuinfo_has_arm_jscvt());
}
TEST(ISA, fcma) {
ASSERT_FALSE(cpuinfo_has_arm_fcma());
}
TEST(ISA, aes) {
ASSERT_TRUE(cpuinfo_has_arm_aes());
}
TEST(ISA, sha1) {
ASSERT_TRUE(cpuinfo_has_arm_sha1());
}
TEST(ISA, sha2) {
ASSERT_TRUE(cpuinfo_has_arm_sha2());
}
TEST(ISA, pmull) {
ASSERT_TRUE(cpuinfo_has_arm_pmull());
}
TEST(ISA, crc32) {
ASSERT_TRUE(cpuinfo_has_arm_crc32());
}
TEST(L1I, count) {
ASSERT_EQ(8, cpuinfo_get_l1i_caches_count());
}
TEST(L1I, non_null) {
ASSERT_TRUE(cpuinfo_get_l1i_caches());
}
TEST(L1I, size) {
for (uint32_t i = 0; i < cpuinfo_get_l1i_caches_count(); i++) {
ASSERT_EQ(32 * 1024, cpuinfo_get_l1i_cache(i)->size);
}
}
TEST(L1I, associativity) {
for (uint32_t i = 0; i < cpuinfo_get_l1i_caches_count(); i++) {
ASSERT_EQ(2, cpuinfo_get_l1i_cache(i)->associativity);
}
}
TEST(L1I, sets) {
for (uint32_t i = 0; i < cpuinfo_get_l1i_caches_count(); i++) {
ASSERT_EQ(cpuinfo_get_l1i_cache(i)->size,
cpuinfo_get_l1i_cache(i)->sets * cpuinfo_get_l1i_cache(i)->line_size * cpuinfo_get_l1i_cache(i)->partitions * cpuinfo_get_l1i_cache(i)->associativity);
}
}
TEST(L1I, partitions) {
for (uint32_t i = 0; i < cpuinfo_get_l1i_caches_count(); i++) {
ASSERT_EQ(1, cpuinfo_get_l1i_cache(i)->partitions);
}
}
TEST(L1I, line_size) {
for (uint32_t i = 0; i < cpuinfo_get_l1i_caches_count(); i++) {
ASSERT_EQ(64, cpuinfo_get_l1i_cache(i)->line_size);
}
}
TEST(L1I, flags) {
for (uint32_t i = 0; i < cpuinfo_get_l1i_caches_count(); i++) {
ASSERT_EQ(0, cpuinfo_get_l1i_cache(i)->flags);
}
}
TEST(L1I, processors) {
for (uint32_t i = 0; i < cpuinfo_get_l1i_caches_count(); i++) {
ASSERT_EQ(i, cpuinfo_get_l1i_cache(i)->processor_start);
ASSERT_EQ(1, cpuinfo_get_l1i_cache(i)->processor_count);
}
}
TEST(L1D, count) {
ASSERT_EQ(8, cpuinfo_get_l1d_caches_count());
}
TEST(L1D, non_null) {
ASSERT_TRUE(cpuinfo_get_l1d_caches());
}
TEST(L1D, size) {
for (uint32_t i = 0; i < cpuinfo_get_l1d_caches_count(); i++) {
ASSERT_EQ(32 * 1024, cpuinfo_get_l1d_cache(i)->size);
}
}
TEST(L1D, associativity) {
for (uint32_t i = 0; i < cpuinfo_get_l1d_caches_count(); i++) {
ASSERT_EQ(4, cpuinfo_get_l1d_cache(i)->associativity);
}
}
TEST(L1D, sets) {
for (uint32_t i = 0; i < cpuinfo_get_l1d_caches_count(); i++) {
ASSERT_EQ(cpuinfo_get_l1d_cache(i)->size,
cpuinfo_get_l1d_cache(i)->sets * cpuinfo_get_l1d_cache(i)->line_size * cpuinfo_get_l1d_cache(i)->partitions * cpuinfo_get_l1d_cache(i)->associativity);
}
}
TEST(L1D, partitions) {
for (uint32_t i = 0; i < cpuinfo_get_l1d_caches_count(); i++) {
ASSERT_EQ(1, cpuinfo_get_l1d_cache(i)->partitions);
}
}
TEST(L1D, line_size) {
for (uint32_t i = 0; i < cpuinfo_get_l1d_caches_count(); i++) {
ASSERT_EQ(64, cpuinfo_get_l1d_cache(i)->line_size);
}
}
TEST(L1D, flags) {
for (uint32_t i = 0; i < cpuinfo_get_l1d_caches_count(); i++) {
ASSERT_EQ(0, cpuinfo_get_l1d_cache(i)->flags);
}
}
TEST(L1D, processors) {
for (uint32_t i = 0; i < cpuinfo_get_l1d_caches_count(); i++) {
ASSERT_EQ(i, cpuinfo_get_l1d_cache(i)->processor_start);
ASSERT_EQ(1, cpuinfo_get_l1d_cache(i)->processor_count);
}
}
TEST(L2, count) {
ASSERT_EQ(2, cpuinfo_get_l2_caches_count());
}
TEST(L2, non_null) {
ASSERT_TRUE(cpuinfo_get_l2_caches());
}
TEST(L2, size) {
for (uint32_t i = 0; i < cpuinfo_get_l2_caches_count(); i++) {
ASSERT_EQ(256 * 1024, cpuinfo_get_l2_cache(i)->size);
}
}
TEST(L2, associativity) {
for (uint32_t i = 0; i < cpuinfo_get_l2_caches_count(); i++) {
ASSERT_EQ(16, cpuinfo_get_l2_cache(i)->associativity);
}
}
TEST(L2, sets) {
for (uint32_t i = 0; i < cpuinfo_get_l2_caches_count(); i++) {
ASSERT_EQ(cpuinfo_get_l2_cache(i)->size,
cpuinfo_get_l2_cache(i)->sets * cpuinfo_get_l2_cache(i)->line_size * cpuinfo_get_l2_cache(i)->partitions * cpuinfo_get_l2_cache(i)->associativity);
}
}
TEST(L2, partitions) {
for (uint32_t i = 0; i < cpuinfo_get_l2_caches_count(); i++) {
ASSERT_EQ(1, cpuinfo_get_l2_cache(i)->partitions);
}
}
TEST(L2, line_size) {
for (uint32_t i = 0; i < cpuinfo_get_l2_caches_count(); i++) {
ASSERT_EQ(64, cpuinfo_get_l2_cache(i)->line_size);
}
}
TEST(L2, flags) {
for (uint32_t i = 0; i < cpuinfo_get_l2_caches_count(); i++) {
ASSERT_EQ(0, cpuinfo_get_l2_cache(i)->flags);
}
}
TEST(L2, processors) {
for (uint32_t i = 0; i < cpuinfo_get_l2_caches_count(); i++) {
switch (i) {
case 0:
ASSERT_EQ(0, cpuinfo_get_l2_cache(i)->processor_start);
ASSERT_EQ(4, cpuinfo_get_l2_cache(i)->processor_count);
break;
case 1:
ASSERT_EQ(4, cpuinfo_get_l2_cache(i)->processor_start);
ASSERT_EQ(4, cpuinfo_get_l2_cache(i)->processor_count);
break;
}
}
}
TEST(L3, none) {
ASSERT_EQ(0, cpuinfo_get_l3_caches_count());
ASSERT_FALSE(cpuinfo_get_l3_caches());
}
TEST(L4, none) {
ASSERT_EQ(0, cpuinfo_get_l4_caches_count());
ASSERT_FALSE(cpuinfo_get_l4_caches());
}
#include <galaxy-j7-prime.h>
int main(int argc, char* argv[]) {
#if CPUINFO_ARCH_ARM
cpuinfo_set_hwcap(UINT32_C(0x0037B0D6));
cpuinfo_set_hwcap2(UINT32_C(0x0000001F));
#endif
cpuinfo_mock_filesystem(filesystem);
#ifdef __ANDROID__
cpuinfo_mock_android_properties(properties);
cpuinfo_mock_gl_renderer("Mali-T830");
#endif
cpuinfo_initialize();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Teaonly/easyLearning.js
|
TensorExpress/aten/src/ATen/cpu/cpuinfo/test/mock/galaxy-j7-prime.cc
|
C++
|
mit
| 15,069
|
\documentclass{beamer}
% !TeX spellcheck = es_CL
\mode<presentation>
{
\usetheme{Berkeley}
% or ...
\setbeamercovered{transparent}
% or whatever (possibly just delete it)
}
\usepackage{tikz}
\usepackage{graphicx}
\usepackage[english]{babel}
% or whatever
\usepackage[utf8]{inputenc}
% or whatever
\usepackage{tikz}
\usetikzlibrary{decorations.pathreplacing,angles,quotes}
\usetikzlibrary{shapes, shadows, arrows, positioning}
\usepackage{times}
%\usepackage[T1]{fontenc}
% Or whatever. Note that the encoding and the font should match. If T1
% does not look nice, try deleting the line with the fontenc.
\AtBeginSection[]
{
\begin{frame}<beamer>[noframenumbering]{Outline}
\tableofcontents[currentsection]
\end{frame}
}
\title[Transparencia en Investigación en las Ciencias Sociales] % (optional, use only with long paper titles)
{Nuevos desafíos para la investigación y las políticas públicas: reproducibilidad, transparencia y credibilidad}
\subtitle
{}
\author[] % (optional, use only with lots of authors)
{Garret~Christensen\inst{1}\inst{2}\\
Fernando~Hoces de la Guardia\inst{1}}
% - Give the names in the same order as the appear in the paper.
% - Use the \inst{?} command only if the authors have different
% affiliation.
\institute[Universities of Somewhere and Elsewhere] % (optional, but mostly needed)
{
\inst{1}%
UC Berkeley:\\
Berkeley Initiative for Transparency in the Social Sciences\\
\inst{2}%
Berkeley Institute for Data Sciences\\
}
% - Use the \inst command only if there are several affiliations.
% - Keep it simple, no one is interested in your street address.
\date[BITSS2017] % (optional, should be abbreviation of conference name)
{Pontificia Universidad Católica, Octubre 2017\\
Slides disponibles en \\ \url{https://goo.gl/wU81GA}}
% - Either use conference name or its abbreviation.
% - Not really informative to the audience, more for people (including
% yourself) who are reading the slides online
\subject{Transparencia en Investigación}
% This is only inserted into the PDF information catalog. Can be left
% out.
\pgfdeclareimage[height=2cm]{university-logo}{../Images/BITSSlogo.png}
\logo{\pgfuseimage{university-logo}}
% If you have a file called "university-logo-filename.xxx", where xxx
% is a graphic format that can be processed by latex or pdflatex,
% resp., then you can add a logo as follows:
% \pgfdeclareimage[height=0.5cm]{university-logo}{university-logo-filename}
% \logo{\pgfuseimage{university-logo}}
% Delete this, if you do not want the table of contents to pop up at
% the beginning of each subsection:
%\AtBeginSubsection[]
%{
% \begin{frame}<beamer>{Outline}
% \tableofcontents[currentsection,currentsubsection]
% \end{frame}
%}
% If you wish to uncover everything in a step-wise fashion, uncomment
% the following command:
\beamerdefaultoverlayspecification{<.->}
\begin{document}
\begin{frame}
\titlepage
\end{frame}
% Structuring a talk is a difficult task and the following structure
% may not be suitable. Here are some rules that apply for this
% solution:
% - Exactly two or three sections (other than the summary).
% - At *most* three subsections per section.
% - Talk about 30s to 2min per frame. So there should be between about
% 15 and 30 frames, all told.
% - A conference audience is likely to know very little of what you
% are going to talk about. So *simplify*!
% - In a 20min talk, getting the main ideas across is hard
% enough. Leave out details, even if it means being less precise than
% you think necessary.
% - If you omit details that are vital to the proof/implementation,
% just say so once. Everybody will be happy with that.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}
Primero, un favor: ¿Podrían completar esta breve encuesta?
\huge{\url{https://goo.gl/dxfJRb}}
\end{frame}
\begin{frame}{Estructura de la Presentación}
\tableofcontents
% You might wish to add the option [pausesections]
\end{frame}
\section {Introducción}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\href{https://www.bitss.org/}{\includegraphics[width=\paperwidth]{../Images/BITSSlogo.png}}
};
\end{tikzpicture}
\end{frame}
}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\href{https://www.bitss.org/}{\includegraphics[width=\paperwidth]{../Images/ecosystem.PNG}}
};
\end{tikzpicture}
\end{frame}
}
% Ideas clave:
% Que es BITSS
% Creciente reconocimiento de problemas relacionados con como hacemos ciencia: sesgo de publicacion, p-hacking, dificl replicacion (repetir experimento, mismo resultado) e incluso reproduccion computacinal de resultados (mismos datos, mismo código, distinto resultado!)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Ética en la Investigación Científica}
\begin{frame}{Ética en la Investigación Científica}
\begin{itemize}
\item Transparencia es un elemento central de la ética del investigador.
\item Valores científicos acuñados por Robert Merton (Merton 1942):
\begin{itemize}[<.->]
\item \textbf{Universalismo}: cualquier persona puede presentar un argumento, independiente de su estatus.
\item \textbf{Comunismo}: el conocimiento es compartido de manera abierta.
\item \textbf{Desinterés}: la verdad como motivación, y no los beneficios monetarios.
\item \textbf{Escepticismo Organizado}: revisión a través de pares (peer review), replicación.
\end{itemize}
\end{itemize}
\end{frame}
\begin{frame}{Ética en la Investigación Científica}
\begin{itemize}
\item
Casos de fraude existen \href{http://pss.sagepub.com/content/24/10/1875}{(Simonsohn 2013)}, pero más importante como investigadores tenemos que admitir nuestra condición humana, sujeto as sesgos y razonamiento motivado, transparencia puede ayudar con esto \href{http://pps.sagepub.com/content/7/6/615.short}{(Nosek, Spies, Motyl 2012)}.
\item
Quienes llevamos a cabo experimentos o usamos datos con información identificable a nivel individual, tenemos que tomar con seriedad los Comités de Ética Institucionales (IRBs) (Ch. 11--13 Morton \& Williams 2010, \href{http://desposato.org/ethicsfieldexperiments.pdf}{Desposato 2014}).
\end{itemize}
\end{frame}
%{ % all template changes are local to this group.
% \setbeamertemplate{navigation symbols}{}
% \begin{frame}[plain]
% \begin{tikzpicture}[remember picture,overlay]
% \node[at=(current page.center)] {
% \includegraphics[height=\paperheight]{../Images/motivatedreasoning.PNG}
% };
% \end{tikzpicture}
% \end{frame}
%}
%{ % all template changes are local to this group.
% \setbeamertemplate{navigation symbols}{}
% \begin{frame}[plain]
% \begin{tikzpicture}[remember picture,overlay]
% \node[at=(current page.center)] {
% \href{http://www.nytimes.com/2014/10/29/upshot/professors-research-project-%stirs-political-outrage-in-montana.html}{\includegraphics[width=\paperwidth]{../Images/Montana1.PNG}}
% };
% \end{tikzpicture}
% \end{frame}
%}
%{ % all template changes are local to this group.
% \setbeamertemplate{navigation symbols}{}
% \begin{frame}[plain]
% \begin{tikzpicture}[remember picture,overlay]
% \node[at=(current page.center)] {
% \href{https://www.washingtonpost.com/news/monkey-cage/wp/2015/05/13/campaign-experiment-found-to-be-in-violation-of-montana-law/}{\includegraphics[width=\paperwidth]{../Images/Montana2.PNG}}
% };
% \end{tikzpicture}
% \end{frame}
%}
%HERE'S THE BASIC SYNTAX TO SHOW FIGURE AND IMAGE ON SAME SLIDE
%\begin{frame}
%Why we worry: \href{http://pss.sagepub.com/content/23/5/524}{(John, Loewenstein, Prelec 2011)}
%\frame{\includegraphics[scale=0.375]{../Images/PrelecFig1.PNG}}
%\end{frame}
\begin{frame}{Ética en la Investigación Científica}
Por qué nos preocupamos:
\begin{itemize}[<.->]
\item \href{http://www.jstor.org/stable/pdf/10.1525/jer.2007.2.4.3.pdf}{(Anderson, Martinson, De Vries 2007)}
\item \href{http://pss.sagepub.com/content/23/5/524}{(John, Loewenstein, Prelec 2011)}
\end{itemize}
\end{frame}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[width=\paperwidth]{../Images/AMdV2007.PNG}
};
\end{tikzpicture}
\end{frame}
}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[height=\paperheight]{../Images/PrelecFig1.PNG}
};
\end{tikzpicture}
\end{frame}
}
%\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\section{Study Design and Power}
%\begin{frame}{Study Design and Power}
%\begin{itemize}[<.->]
%\item
%Adequately power trials to help prevent spurious significant results.
%\item
%Practical suggestions:
%\begin{itemize}
%\item
%Collaborate with other labs to mutually run each others' experiments (Open Science Collaboration 2014, 2015).
%\begin{itemize}[<.->]
%\item \href{http://science.sciencemag.org/content/349/6251/aac4716.full}{Replication Project: Psychology}
%\item \href{http://econtent.hogrefe.com/doi/full/10.1027/1864-9335/a000178}{Many Labs 1}, \href{https://osf.io/8cd4r/}{2}, 3
%\item Crowdsourcing Analysis \href{http://www.nature.com/news/crowdsourced-research-many-hands-make-tight-work-1.18508}{(Silberzahn and Uhlmann 2016)}
%\item \href{http://science.sciencemag.org/content/early/2016/03/02/science.aaf0918}{Experimental economics replications (Camerer et al. 2016)}
%\end{itemize}
%\item
%Maximize power subject to budget constraint by adjusting expensive treatment arm (relative) size \href{http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.650.9734&rep=rep1&type=pdf}{(Duflo, Glennerster, Kremer 2007)}.
%\end{itemize}
%\end{itemize}
%\end{frame}
%{ % all template changes are local to this group.
% \setbeamertemplate{navigation symbols}{}
% \begin{frame}[plain]
% \begin{tikzpicture}[remember picture,overlay]
% \node[at=(current page.center)] {
% \includegraphics[width=\paperwidth]{../Images/Crowdsourcing2.PNG}
% };
% \end{tikzpicture}
% \end{frame}
%}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Registros}
\subsection*{Sesgo de Publicación}
\begin{frame}{Sesgo de Publicación}%{Subtitles are optional.}
% - A title should summarize the slide in an understandable fashion
% for anyone how does not follow everything on the slide itself.
Existencia del problema:
\begin{itemize}
\item
El tamaño de los efectos disminuye con el tamaño muestral (\href{http://pan.oxfordjournals.org/content/9/4/385.short}{Gerber, Green, Nickerson 2001})
\item
Las Ciencias Sociales muestran una tasa de rechazo de la hipótesis nula mayor que las ciencias duras (\href{http://journals.plos.org/plosone/article?id=10.1371/journal.pone.0010068}{Fanelli 2010}).
\item
La publicación de efectos nulos esta desapareciendo en el tiempo, en todas las disciplinas. (\href{http://link.springer.com/article/10.1007/s11192-011-0494-7}{Fanelli 2011}).
\item
Estudio que siguió a experimentos completados muestra que aquellos experimentos con fuertes resultados son 40pp más probable de ser publicados, y 60pp más probable de ser escritos. Alto ``file drawer problem''. (\href{http://science.sciencemag.org/content/345/6203/1502}{Franco, Malhotra, Simonovits 2014})
\end{itemize}
\end{frame}
%Go through the fields
\begin{frame}{Problema en todas las disciplinas}
\begin{itemize}[<.->]
\item Medicina: \href{http://www.nejm.org/doi/full/10.1056/nejmsa065779}{(Turner et al. 2008)}
\item Ciencias Sociales: \href{http://science.sciencemag.org/content/345/6203/1502.short}{(Franco, Malhotra, Simonovits 2014)}
\item Economía: \href{https://www.aeaweb.org/articles.php?doi=10.1257/app.20150044}{(Brodeur et al. 2016)}
\item Sociología: \href{http://smr.sagepub.com/content/37/1/3.short}{(Gerber and Malhotra 2008)}
\item Ciencias Políticas: \href{http://nowpublishers.com/article/Details/QJPS-8024}{(Gerber and Malhotra 2008)}
\end{itemize}
\end{frame}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[height=\paperheight]{../Images/TurnerFigure1.PNG}
};
\end{tikzpicture}
\end{frame}
}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[height=\paperheight]{../Images/Tess.PNG}
};
\end{tikzpicture}
\end{frame}
}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[height=\paperheight]{../Images/Brodeur.PNG}
};
\end{tikzpicture}
\end{frame}
}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[height=\paperheight]{../Images/GerberSoc.PNG}
};
\end{tikzpicture}
\end{frame}
}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[height=\paperheight]{../Images/GerberPS.PNG}
};
\end{tikzpicture}
\end{frame}
}
\begin {frame}{Sesgo de Publicación}
Si solo escribimos/publicamos resultados significativos, y no dejamos registro de los no significativos, no tenemos forma de distinguir si nuestros resultados ``significativos'' son reales, o si son el 5\% que deberíamos esperar debido a error estadístico.
%If we only write up/publish significant results, and we have no record of all the insignificant results, we have no way to tell if our `significant' results are real, or if they're the 5\% we should expect due to noise.
\end{frame}
\subsection* {Registros}
\begin{frame}{Registros}
Pre-Registros como una solución al sesgo de publicación:
\begin{itemize}
\item
Hacer pública la investigación a ejecutar, publicando por adelantado las hipótesis a testear.
%\item If we know every hypothesis test that is run on a given subject, we have a better idea of how seriously to take the significant results.
\item
Adopción casi universal en RCTs en medicina. Journals top (ICMJE) no publican estudios si no están registrados. \url{http://clinicaltrials.gov}
% \item
% Even better if registry requires outcomes from after study. Currently limited, but NIH is moving on this.
\end{itemize}
\end{frame}
\begin{frame}{Registros}
Nuevos en ciencias sociales, pero:
\begin{itemize}[<.->]
\item
Registro de AEA, actualmente solo para RCTs. \url{http://socialscienceregistry.org}
\item
Registro de EGAP \url{http://egap.org/design-registration}
\item
Registro de 3ie, para evaluaciones en países en desarrollo. \url{http://ridie.3ieimpact.org}
\item
Open Science Framework\\ \url{http://osf.io}
\begin{itemize}
\item
Formato abierto
\item
Pronto va a estar sincronizado con los de más arriba
\end{itemize}
\item Simple: \url{http://aspredicted.org}
\end{itemize}
\end{frame}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain, label=AEAreg]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[height=\paperheight]{../Images/combinedAEARegGraphs.png}
};
\end{tikzpicture}
\end{frame}
}
\begin{frame}{Publicaciones Basadas en Diseño de la Investigación}
AKA Reportes Registrados, cambia momento de peer review hacia antes del la recolección de dates, análisis y resultados.
\begin{enumerate}[<.->]
\item Diseñar un estudio
\item Enviar a un journal
\item Revisión basada en la importancia de la pregunta y calidad del diseño
\item Obtener aceptación en principio
\item Ejecutar el estudio, y publicar incluso con resultados nulos
\end{enumerate}
\href{https://osf.io/8mpji/wiki/home/}{20 Journals, 5 más con con ediciones especiales \beamergotobutton{Link}}
\end{frame}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain, label=AEAreg]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[height=\paperheight]{../Images/results_blind_review.png}
};
\end{tikzpicture}
\end{frame}
}
\begin{frame}{Meta-Análisis}
Síntesis sistemático de los resultados
\vspace{.2in}
Organizaciones:
\begin{itemize}[<.->]
\item Cochrane Collaboration (Medicina)
\item Campbell Collaboration (Políticas públicas)
\item \href{http://ies.ed.gov/ncee/wwc/}{What Works Clearinghouse (Educación, Gob. US)}
\item \href{http://clear.dol.gov/}{CLEAR (Empleo, Gob. US)}
\item \href{https://www.hendrix.edu/maer-network/}{MAER-NET} (Economía)
\end{itemize}
\end{frame}
\begin{frame}{Meta-Análisis}
Herramientas:
\begin{itemize}[<.->]
\item Funnel plots del tamaño de la muestra vs. tamaño del efecto \href{http://www.jstor.org/stable/2117925}{(Card \& Krueger 1995)}
\item Funnel Asymmetry Test \href{https://books.google.com/books?id=jSQEdEsL7VoC}{(Stanley \& Doucouliagos 2012)}
\item P-curve \href{http://p-curve.com/}{(Simonsohn et al. 2014)} \href{http://p-curve.com/}{\beamergotobutton{Online App}}
\begin{itemize}
\item Un p-checker para todos \href{http://shinyapps.org/apps/p-checker/}{\beamergotobutton{Shiny App}}
\end{itemize}
\end{itemize}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Planes de Pre-Análisis}
\subsection*{P-Hacking}
\begin{frame}[<.->]{P-Hacking}
Definición del problema:
\begin{itemize}
\item
Otros nombres: ``data-fishing'', grados de libertad del investigador, o ``data-mining''.
\item
Definición: flexibilidad en el análisis de datos permite presentar \textit{casi cualquier resultado} bajo un umbral arbitrario; significancia estadística pierde sentido.
\item
No es algo único de investigadores con malas intenciones. Es subconsciente, o simplemente una practica estándar del análisis estadístico (\href{http://www.stat.columbia.edu/~gelman/research/unpublished/p_hacking.pdf}{Gelman, Loken 2013}).
\end{itemize}
\end{frame}
\begin{frame}{P-Hacking: hágalo usted mismo!}
\begin{itemize}
\item
``Science isn't Broken'' ---538 reportaje periodístico con modulo interactivo \href{http://fivethirtyeight.com/features/science-isnt-broken}{\beamerbutton{Link}}
\item
Practique p-hacking en R/Shiny App. \href{http://www.nicebread.de/introducing-p-hacker/}{\beamerbutton{Link}}
\item
El Exact Fishy Test \href{https://macartan.shinyapps.io/fish/}{\beamerbutton{Link}}
\end{itemize}
\end{frame}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[width=\paperwidth]{../Images/Crowdsourcing2.PNG}
};
\end{tikzpicture}
\end{frame}
}
\subsection*{Planes de Pre-Análisis}
\begin{frame}{Planes de Pre-Análisis}
\textbf{Explicación de la solución, de 3ie:}
``Un plan de pre-análisis (PAPs) es una descripción detallada de los análisis a ser conducidos. Esta descripción es escrita antes de ver los datos que contienen los impactos del programa bajo evaluación. Puede especificar las hipótesis a testear, como se construirán las variables, ecuaciones a estimar, controles a utilizar, y otros aspectos del análisis. Una función clave de los PAPs es incrementar la transparencia en investigación. Al especificar los detalles por adelantado antes de ver los resultados, el plan es un resguardo contra data mining y búsqueda de especificaciones. Se les recomienda a los investigadores que desarrollen y suban dichos planes junto con el registro de sus estudios. Sin embargo, esto no es requisito para el registro de un estudio.''
\end{frame}
\begin{frame}{Origenes: Regulación Farmaceutica en USA}
``E9 Statistical Principles for Clinical Trials'' (1998)
\href{http://www.fda.gov/downloads/drugs/guidancecomplianceregulatoryinformation/guidances/ucm073137.pdf}{\beamergotobutton{Link}}
\S V Consideraciones en el Análisis de Datos
\begin{enumerate}[<.->]
\item Pre-especificación del análisis
\item Grupos de análisis
\item Tratamiento de NAs y valores extremos
\item Transformaciones a los datos
\item Estimación, intervalos de confianza, y testeo de hipótesis
\item Ajuste de significancia y niveles de confianza
\item Subgrupos, interacciones, y variables de control
\item Integridad de los datos y validez del software computacional
\end{enumerate}
\end{frame}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{Sugerencias de Glennerster, Takavarasha}
\textit{Running Randomized Evaluations}
\begin{enumerate}[<.->]
\def\labelenumi{\arabic{enumi}.}
\item
Como se van a medir los principales variables de resultado,
\item
Dentro de las variables de resultado: cuales son primarias, cuales secundarias?
\item
Composición exacta de toda la familia de tests utilizados en análisis de effectos promedios
\begin{itemize}
\item Explicación de efectos promedio, FWER, FDR en Anderson (\href{https://are.berkeley.edu/~mlanderson/pdf/Anderson\%202008a.pdf}{JASA 2008}).
\end{itemize}
\item
Los subgrupos a ser analizados,
\item
La dirección esperada de los impactos si queremos usar test de una cola, y
\item
La especificación primaria a ser utilizada en el análisis.
\end{enumerate}
\end{frame}
\begin{frame}{Sugerencias de McKenzie}
\href{http://blogs.worldbank.org/impactevaluations/a-pre-analysis-plan-checklist}{World Bank Development Impact Blog}
\begin{enumerate}[<.->]
\item
Descripción de la muestra a ser utilizada en el estudio
\item
Fuentes de datos fundamentales
\item
Hipótesis a testear a través de la cadena causal
\item
Especificar como se van a construir la variables
\item
Especificar la ecuación donde se estimará el efecto del tratamiento
\item
Cúal es la estrategia para analizar multiples variables de resultados y múltiples test de hipótesis?
\item
Procedimiento a utilizar para enfrentar atrición en la muestra
\item
Qué hará el estudio en caso de limitada variación en las variables de resultados?
\item
Si hay un modelo a testear, este debe ser incluido
\item
No olvidar archivarlo (con una fecha estampada digitalmente)
\end{enumerate}
\end{frame}
%\begin{frame}{Simmons, Nelson, Simonsohn (2011)}
%\begin{enumerate}[<.->]
%\def\labelenumi{\arabic{enumi}.}
%\item
% Authors must decide the rule for terminating data collection before data collection begins and report this rule in the article.
%\item
% Authors must collect at least 20 observations per cell or else provide
% a compelling cost-of-data-collection justification.
%\item
% Authors must list all variables collected in a study.
%\item
% Authors must report all experimental conditions, including failed
% manipulations.
%\item
% If observations are eliminated, authors must also report what the
% statistical results are if those observations are included.
%\item
% If an analysis includes a covariate, authors must report the
% statistical results of the analysis without the covariate.
%\end{enumerate}
%\end{frame}
\begin{frame}{Ejemplos}
\begin{itemize}[<.->]
\item
J-PAL Registro de Hipótesis , ver \url{http://www.povertyactionlab.org/Hypothesis-Registry}
6 ejemplos de papers publicados:
\begin{itemize}
\item
Sierra Leone CDD, Oregon Medicare, Turkey Job Training, El Salvador TOMS, dos en Indonesia (Olken et al.)
\end{itemize}
\item Psicología: \href{http://pss.sagepub.com/content/26/2/249}{Hawkins, Fitzgerald, Nosek---Riesgos de Concepción y Prejuicios}
\end{itemize}
\vspace{0.25in}
Amplio rango de que es lo que se debe escribir exactamente y cuanto detalle incorporar en el PAP. En un nivel extremo el código estaría listo para ejecutar en cuanto lleguen los datos.
\end{frame}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[width=\paperwidth]{../Images/GoBifo1.PNG}
};
\end{tikzpicture}
\end{frame}
}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[width=\paperwidth]{../Images/preregchallenge.png}
};
\end{tikzpicture}
\end{frame}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}{PAP--Estudios Observacionales}
\begin{itemize}[<.->]
\item Actual debate en salud pública/epidemiologia.
\item Pre-especificar de manera verificable: difícil. pero no imposible.
\item Ejemplo: Datos generados periódicamente por el gobierno.
\item Ejemplo: Salario Mínimo (\href{http://onlinelibrary.wiley.com/doi/10.1111/0019-8676.00199/full}{Neumark 2001})
\end{itemize}
\end{frame}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[width=\paperwidth]{../Images/Neumark.PNG}
};
\end{tikzpicture}
\end{frame}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Replicaciones}
\begin{frame}{Replicaciones}
\begin{enumerate}[<.->]
\item El problema \href{http://www.jstor.org/stable/1806061}{(JMCB Project)}
\item Protocolo del proyecto, Estándares de publicación
\item Organización del flujo de trabajo
\item Compartir código y datos
\end{enumerate}
\end{frame}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain, label=AEAreg]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[width=\paperwidth]{../Images/JMCB1.PNG}
};
\end{tikzpicture}
\end{frame}
}
\subsection*{Protocolo del Proyecto, Estándares de Información (Reporting Guidelines)}
\begin{frame}[<.->]{Protocolo del Proyecto, Estándares de Información}
Asegurar disponibilidad de todo lo necesario para que otro investigador replique su investigación.
\begin{itemize}
\item Encuentre el estándar de información apropiado para su disciplina y sígalo: \url{http://www.equator-network.org}
\item Informe todos los detalles sobre la implementación de un proyecto en un protocolo detallado: \url{http://www.spirit-statement.org}
\item Pautas Transparency and Openness Promotion (TOP): \url{http://cos.io/top}
\end{itemize}
\end{frame}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain, label=AEAreg]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[width=\paperwidth]{../Images/TOPGuidelines.PNG}
};
\end{tikzpicture}
\end{frame}
}
\subsection*{Flujo de trabajo}
\begin{frame}{Flujo de trabajo}
``Reproducibilidad es simplemente una colaboración con personas que aun no conoces, incluido tu mismo en una semana más'
---Philip Stark, UC Berkeley Statistics
\end{frame}
\begin{frame}{Flujo de trabajo}
\begin{itemize}
\item Sugerencias practicas sobre organización y programación
\begin{itemize}[<.->]
\item Al realizar cambios a archivos que han sido compartidos/publicados, implica que debe renombrar el archivo.
\item Haga referencia a la versión necesaria para ejecutar funciones.
\item Long (2008) \textit{The Workflow of Data Analysis Using Stata}
\end{itemize}
\item Programación Literaria: comentario extensivo en el código, apuntando a que sea legible por humanos
\item Control de Versiones
\item Documentos Dinámicos
\end{itemize}
\end{frame}
\subsection*{Control de Versiones}
\begin{frame}{Control de Versiones}
\begin{itemize}[<.->]
\item
Utilizar control de versiones puede ayudar a hacer su trabajo más reproducible.
\item
Qué es Control de Versiones?
\begin{quote}
Control de versiones es un sistema que registra cambios a uno o varios archivos en el tiempo, de forma tal que versiones especifica pueden ser recuperados más adelante.
\end{quote}
--Git, \href{https://git-scm.com/book/en/v2/Getting-Started-About-Version-Control}{About Version Control}
%\item Distributed Version Control Systems (DCVS) let multiple users control the same files in this manner.
\end{itemize}
\end{frame}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain, label=AEAreg]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[height=\paperheight]{../Images/github-logo-transparent.JPG}
};
\end{tikzpicture}
\end{frame}
% all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[width=\paperwidth]{../Images/OSFnow.PNG}
};
\end{tikzpicture}
\end{frame}
% all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[width=\paperwidth]{../Images/OSFsoon.PNG}
};
\end{tikzpicture}
\end{frame}
}
\begin{frame}{Documentos Dinámicos}
Meta aspiracional: Escriba su código y su paper en el mismo archivo. De esta forma se minimiza la perdida de información y se eliminan errores de copiar/pegar.
\medskip
Establecido en R/Python y comenzando en Stata.
\begin{itemize}[<.->]
\item Incluye tablas dentro del archivo, en lugar de copiar-pegar-formatear elementos estáticos
\item Todas las cifras dentro del texto también son calculadas de manera dinámica, eliminando la necesidad de tipeo de cifras manualmente.
\item Cifras y tablas se actualizan automáticamente.
\item El paper completo es (re)producido con uno o dos clicks
\end{itemize}
\end{frame}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain, label=AEAreg]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[height=\paperheight]{../Images/jupyter.png}
};
\end{tikzpicture}
\end{frame}
}
{ % all template changes are local to this group.
\setbeamertemplate{navigation symbols}{}
\begin{frame}[plain, label=AEAreg]
\begin{tikzpicture}[remember picture,overlay]
\node[at=(current page.center)] {
\includegraphics[width=\paperwidth]{../Images/RStudio-Logo-Blue-Gradient.png}
};
\end{tikzpicture}
\end{frame}
}
\subsection*{Compartiendo lo Datos}
\begin{frame}{Compartiendo lo Datos}
Publique su código y sus datos en un repositorio publico de confianza.\begin{itemize}[<.->]
\item
Encuentre el repositorio apropiado: \url{http://www.re3data.org/}
\item
Los repositorios están diseñados para durar más que su website.
\item
También están diseñados para facilitar la búsqueda por parte de otros investigadores.
\item
Los repositorios guardan sus datos en formatos públicos que evitan obsolescencia en el tiempo.
\end{itemize}
\end{frame}
\section{Lecciones Para el Análisis de Políticas Públicas}
\begin{frame}{Lecciones Para el Análisis de Políticas Públicas}
\begin{itemize}
\item Link Evidencia-PP con \textbf{alta} transparencia.
\item Link Evidencia-PP con \textbf{baja} transparencia.
\item Nuestra propuesta en BITSS.
\end{itemize}
\end{frame}
\begin{frame}{Una forma en la cual la evidencia afecta las políticas públicas}
\
\tikzstyle{agent} = [diamond, draw, node distance= 7em, minimum height=5em, minimum width=5em]
\tikzstyle{line} = [draw, -stealth]
\tikzstyle{line_enph} = [draw, red, ultra thick]
\tikzstyle{inp} = [draw, circle, text centered, minimum height=2em, text width=2em, node distance= 10em]
\tikzstyle{outp} = [draw, circle, text centered, minimum height=2em, text width=2em, node distance= 10em]
\tikzstyle{block1} = [draw, circle, text width=5em, text centered, minimum height=7em, node distance= 5em]
\tikzstyle{block2} = [draw, circle, text width=7em, text centered, minimum height=2em, node distance= 5em]
\tikzstyle{block3} = [draw, rounded rectangle, text width=5em, text centered, minimum height=2em, node distance= 5em]
\begin{figure}[h!]\centering
\vspace{-2.0em}
\begin{tikzpicture}[thick,scale=0.55, every node/.style={scale=0.55}]
%% The oddly shaped truth
\node[regular polygon, regular polygon sides=3,
draw, fill=white,
inner sep=.1em,
shape border rotate=70](tru){Truth};
%%%%%Researcher 1 and Inputs: depends on R_1%%%%%%%
\node [block1, right = 2em of tru](R_1){Research\linebreak $(R)$};
\node [block1,inner sep=0em, right = 2em of R_1](PA_1){Policy \linebreak Analysis: ($PA$) \linebreak Gains \& \linebreak losses};
\node [block1, above right = 0em and 8em of R_1](PM_1){Policy\linebreak Maker 1};
\node [block1, below right = 0em and 8em of R_1](PM_2){Policy\linebreak Maker 2};
\node [block3, right = 2em of PM_1](PC_1){Support};
\node [block3, right = 2em of PM_2](PC_2){Oppose};
%%%%% Draw edges col 2%%%%%%%%%%%%%%%%%
%Research to PA
\draw [line](tru) -- (R_1);
\draw [line](R_1) -- (PA_1);
%PA to PM
\draw [line](PA_1) -- (PM_1);
\draw [line](PA_1) -- (PM_2);
%PM to PC
\draw [line](PM_1) -- (PC_1);
\draw [line](PM_2) -- (PC_2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\draw[decoration={brace}, decorate] (7,3.4) -- node[above=6pt](lab4){{\Large Observed by citizens} }(16,3.4);
\end{tikzpicture}
\caption{Simplified Model of Connection Between Evidence and Policy}
\vspace{-.8em}
\end{figure}
\end{frame}
\begin{frame}[shrink=30,label=lack_cred]{Link Evidencia-políticas públicas con Baja Transparencia y Reproducibilidad}
\tikzstyle{agent} = [diamond, draw, node distance= 7em, minimum height=5em, minimum width=5em]
\tikzstyle{line} = [draw, -stealth]
\tikzstyle{line_d} = [draw, dashed, -stealth]
\tikzstyle{inp} = [draw, circle, text centered, minimum height=2em, text width=2em, node distance= 10em]
\tikzstyle{outp} = [draw, circle, text centered, minimum height=2em, text width=2em, node distance= 10em]
\tikzstyle{block1} = [draw, circle, text width=3em, text centered, minimum height=2em, node distance= 5em]
\tikzstyle{block2} = [draw, circle, text width=4em, text centered, minimum height=2em, node distance= 5em]
\tikzstyle{block3} = [draw, rounded rectangle, text width=5em, text centered, minimum height=2em, node distance= 5em]
\begin{figure}[h!]
\centering
\hspace*{0.2\linewidth}
\begin{tikzpicture}[thick,scale=0.2, every node/.style={scale=0.8}]
%% The oddly shaped truth
\node[regular polygon, regular polygon sides=3,
draw, fill=white,
inner sep=.1em,
shape border rotate=70](tru){Truth};
%%%%%Researcher 1 and Inputs: depends on R_1%%%%%%%
\node [block1, right = 5em of tru](R_2){$R_2$};
\node [block1, above = 8em of R_2](R_1){$R_1$} node [left = -0.1em of R_1, text width = 5em]{Large Treatment Effect};
\node [block1, below = 8em of R_2](R_3){$R_3$} node [left = -0.1em of R_3, text width = 5em]{Small Treatment Effect};
\draw[decoration={brace,mirror}, decorate] (13,-33) -- node[below=6pt, text width = 4.8em](lab1){Researchers Degrees of
Freedom}(18,-33);
\draw[decoration={brace,mirror}, decorate] (29,-33) -- node[below=6pt, text width = 4.8em](lab2){P. Analyst Degrees of
Freedom}(34,-33);
\draw[decoration={brace}, decorate] (31,33) -- node[below=2pt]{Observed by citizens}(70,33);
%\node [agent](Researcher_1){$R_1$} node [left = 0.6em of Researcher_1, text width = 8em]{Large Treatment Effect};
\node [block1, right = 5em of R_1](PA_12){$PA_{1,2}$};
\node [block1, above = .5em of PA_12](PA_11){$PA_{1,1}$} node [right = -0.1em of PA_11, text width = 5em]{Large gains only};
\node [block1, below = .5em of PA_12](PA_13){$PA_{1,3}$};
\node [block1, right = 5em of R_2](PA_22){$PA_{22,}$};
\node [block1, above = .5em of PA_22](PA_21){$PA_{2,1}$};
\node [block1, below = .5em of PA_22](PA_23){$PA_{2,3}$};
\node [block1, right = 5em of R_3](PA_32){$PA_{3,2}$};
\node [block1, above = .5em of PA_32](PA_31){$PA_{3,1}$};
\node [block1, below = .5em of PA_32](PA_33){$PA_{3,3}$} node [right = -0.1em of PA_33, text width = 5em]{Large losses only};
\node [block2, above right = 3em and 15em of R_2](PM_1){Policy\linebreak Maker 1};
\node [block2, below right = 3em and 15em of R_2](PM_2){Policy\linebreak Maker 2};
\node [block3, right = 3em of PM_1](PC_1){Support};
\node [block3, right = 3em of PM_2](PC_2){Oppose};
%%%%% Draw edges col 2%%%%%%%%%%%%%%%%%
%Truth to research
\draw [line](tru) -- (R_1);
\draw [line_d](tru) -- (R_2);
\draw [line_d](tru) -- (R_3);
%Research to PA
\draw [line_d](R_1) -- (PA_13);
\draw [line_d](R_1) -- (PA_11);
\draw [line](R_1) -- (PA_12);
\draw [line_d](R_2) -- (PA_23);
\draw [line_d](R_2) -- (PA_21);
\draw [line_d](R_2) -- (PA_22);
\draw [line_d](R_3) -- (PA_33);
\draw [line_d](R_3) -- (PA_31);
\draw [line_d](R_3) -- (PA_32);
%PA to PM
\draw [line](PA_11) -- (PM_1);
\draw [line](PA_33) -- (PM_2);
%PM to PC
\draw [line](PM_1) -- (PC_1);
\draw [line](PM_2) -- (PC_2);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\end{tikzpicture}
\caption{Policy-making with low TR in research and policy analysis}\label{low_cred}
\end{figure}
\hyperlink{problems}{\beamerbutton{}}
%\end{comment}
\end{frame}
\begin{frame}{Nuestra Propuesta Para el Análisis de Políticas Públicas}
\begin{enumerate}
\item Publicar pautas de transparencia y reproducibildad para el analisis de políticas públicas (similar a Pautas TOP, descritas antes).
\item Colaborar con agencias/centro interesados en implementar estas ideas.
\texttt{\href{https://rpubs.com/fhoces/dd_cbo_mw}{\underline{Ejemplo aquí.}}}
\item Iterar.
\end{enumerate}
\end{frame}
\section{Conclusión}
\begin{frame}{Conclusión}
OK, estoy convencido. Como puedo implementar esto en mi propia investigación?
\begin{itemize}[<.->]
\item Tomen nuestro MOOC (E. Miguel).\href{https://www.futurelearn.com/courses/open-social-science-research}{\beamergotobutton{Link}}
\item Suscribance al blog \& E-mail de BITSS \href{https://bitss.org/blog}{\beamergotobutton{Link}}
\item Apliquen a nuestro Instituto de Verano: RT2. \href{http://www.bitss.org/events/summer-institute/}{\beamergotobutton{Link}}
\item Apliquen a nuestros fondos de investigacion SSMART (fondos adicionales para investigadores de paises en desarrollo). \href{http://www.bitss.org/ssmart-grants/}{\beamergotobutton{Link}}
\item Apliquen al premio Leamer-Rosenthal. \href{http://www.bitss.org/lr-prizes/}{\beamergotobutton{Link}}
\item Revisen nuestra pagina de recursos. \href{http://www.bitss.org/resource-tag/education/}{\beamergotobutton{Link}}
\item Interesado en incluir parte de estas practicas en el análisis de políticas públicas? Hablen conmigo! \href{mailto:fhoces@berkeley.edu}{fhoces@berkeley.edu}
\end{itemize}
\end{frame}
\begin{frame}{RT2}
Tres días de entrenamiento. Evento anual que alterna entre Berkeley y fuera de USA (Londres fue hace dos semanas)
'\includegraphics[width=4in]{../Images/bitss-2014-cohort2.jpg}
\end{frame}
\begin{frame}{Fondos SSMART}
Fondos de hasta \$30,000 para financiar investigación en transparencia:
\begin{itemize}[<.->]
\item Desarrollo de nuevas metodologías
\item Nuevas herramientas y usos de meta-análisis
\item Investigación sobre comportamiento de investigadores y adopción de nuevas normas
\end{itemize}
Financiamiento extra para investigadores de paises en desarrollo.
\includegraphics[width=2.5in]{../Images/LRwinners.jpg}
\end{frame}
\begin{frame}{Premio Leamer-Rosenthal}
Reconocimiento a investigadores que han completado estudios en/sobre transparencia y reproducibilidad en ciencias sociales.
Ejemplos:
\begin{itemize}[<.->]
\item Psicología
\item Ciencias Políticas
\item Economía
\end{itemize}
\includegraphics[width=2.5in]{../Images/leamer1-zoomed33.jpg}
\end{frame}
\begin{frame}
\begin{center}
Preguntas?
\vspace{0.5in}
\Huge{Muchas Gracias}
\end{center}
\end{frame}
\end{document}
|
fhoces/BITSS_PUC_CHILE_2017
|
1-Presentacion/BITSS-Intro-Slides.tex
|
TeX
|
mit
| 42,452
|
module Pohoda
module Builders
module Lst
class ListNumericSeriesType < Rdc::ListVersionType
include ParserCore::BaseBuilder
def builder
root = Ox::Element.new(name)
root = add_attributes_and_namespaces(root)
super.nodes.each do |n|
root << n
end
root << build_element('lst:itemNumericSeries', data[:item_numeric_series], data[:item_numeric_series_attributes]) if data.key? :item_numeric_series
root
end
end
end
end
end
|
Masa331/pohoda
|
lib/pohoda/builders/lst/list_numeric_series_type.rb
|
Ruby
|
mit
| 542
|
package com.zimbra.qa.selenium.projects.octopus.tests.history;
import org.testng.annotations.*;
import com.zimbra.qa.selenium.framework.util.*;
import com.zimbra.qa.selenium.projects.octopus.ui.PageHistory.*;
public class RefineComment extends HistoryCommonTest {
public RefineComment() {
super();
logger.info("New " + RefineComment.class.getCanonicalName());
}
@BeforeMethod(groups= ("always"))
public void setup()
throws HarnessException {
super.setup();
}
@Test(description = "Verify check 'comment' checkbox", groups = { "functional" })
public void RefineCheckComment() throws HarnessException {
// verify check action for 'comment'
verifyCheckAction(Locators.zHistoryFilterComment.locator,
GetText.comment(fileName));
}
@Test(description = "Verify uncheck 'comment' checkbox", groups = { "smoke" })
public void RefineUnCheckComment() throws HarnessException {
// verify uncheck action for 'comment'
verifyCheckUnCheckAction(Locators.zHistoryFilterComment.locator,
GetText.comment(fileName));
}
//TODO add test case for delete comment (bug #70800)
}
|
nico01f/z-pec
|
ZimbraSelenium/src/java/com/zimbra/qa/selenium/projects/octopus/tests/history/RefineComment.java
|
Java
|
mit
| 1,153
|
var Col = require('./Col')
module.exports = Col
// export { default } from './Col'
|
constelation/monorepo
|
packagesOld/Col/index.js
|
JavaScript
|
mit
| 84
|
/*
* Configuration for Amlogic Meson GXBB SoCs
* (C) Copyright 2016 Beniamino Galvani <b.galvani@gmail.com>
*
* SPDX-License-Identifier: GPL-2.0+
*/
#ifndef __MESON_GXBB_COMMON_CONFIG_H
#define __MESON_GXBB_COMMON_CONFIG_H
#define CONFIG_CPU_ARMV8
#define CONFIG_REMAKE_ELF
#define CONFIG_NR_DRAM_BANKS 1
#define CONFIG_ENV_SIZE 0x2000
#define CONFIG_SYS_MAXARGS 32
#define CONFIG_SYS_MALLOC_LEN (32 << 20)
#define CONFIG_SYS_CBSIZE 1024
#define CONFIG_SYS_SDRAM_BASE 0
#define CONFIG_SYS_TEXT_BASE 0x01000000
#define CONFIG_SYS_INIT_SP_ADDR 0x20000000
#define CONFIG_SYS_LOAD_ADDR CONFIG_SYS_TEXT_BASE
/* Generic Interrupt Controller Definitions */
#define GICD_BASE 0xc4301000
#define GICC_BASE 0xc4302000
#define CONFIG_SYS_LONGHELP
#define CONFIG_CMDLINE_EDITING
#include <config_distro_defaults.h>
#define BOOT_TARGET_DEVICES(func) \
func(MMC, mmc, 0) \
func(MMC, mmc, 1) \
func(MMC, mmc, 2) \
func(PXE, pxe, na) \
func(DHCP, dhcp, na)
#include <config_distro_bootcmd.h>
#define CONFIG_EXTRA_ENV_SETTINGS \
"fdt_addr_r=0x01000000\0" \
"scriptaddr=0x1f000000\0" \
"kernel_addr_r=0x01080000\0" \
"pxefile_addr_r=0x01080000\0" \
"ramdisk_addr_r=0x13000000\0" \
MESON_FDTFILE_SETTING \
BOOTENV
#define CONFIG_SYS_BOOTM_LEN (64 << 20) /* 64 MiB */
#endif /* __MESON_GXBB_COMMON_CONFIG_H */
|
guileschool/beagleboard
|
u-boot/include/configs/meson-gxbb-common.h
|
C
|
mit
| 1,340
|
package org.robolectric.shadows;
import static android.os.Build.VERSION_CODES.M;
import static android.os.Build.VERSION_CODES.N;
import static android.os.Build.VERSION_CODES.N_MR1;
import static android.os.Build.VERSION_CODES.P;
import static com.google.common.truth.Truth.assertThat;
import static org.mockito.Mockito.when;
import static org.robolectric.Shadows.shadowOf;
import static org.robolectric.util.ReflectionHelpers.getStaticField;
import static org.robolectric.util.reflector.Reflector.reflector;
import android.content.Context;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbPort;
import android.hardware.usb.UsbPortStatus;
import android.os.Build;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowUsbManager._UsbManager_;
/** Unit tests for {@link ShadowUsbManager}. */
@RunWith(AndroidJUnit4.class)
public class ShadowUsbManagerTest {
private static final String DEVICE_NAME_1 = "usb1";
private static final String DEVICE_NAME_2 = "usb2";
private UsbManager usbManager;
@Mock UsbDevice usbDevice1;
@Mock UsbDevice usbDevice2;
@Mock UsbAccessory usbAccessory;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
usbManager =
(UsbManager)
ApplicationProvider.getApplicationContext().getSystemService(Context.USB_SERVICE);
when(usbDevice1.getDeviceName()).thenReturn(DEVICE_NAME_1);
when(usbDevice2.getDeviceName()).thenReturn(DEVICE_NAME_2);
}
@Test
public void getDeviceList() {
assertThat(usbManager.getDeviceList()).isEmpty();
shadowOf(usbManager).addOrUpdateUsbDevice(usbDevice1, true);
shadowOf(usbManager).addOrUpdateUsbDevice(usbDevice2, true);
assertThat(usbManager.getDeviceList().values())
.containsExactly(usbDevice1, usbDevice2);
}
@Test
public void hasPermission() {
assertThat(usbManager.hasPermission(usbDevice1)).isFalse();
shadowOf(usbManager).addOrUpdateUsbDevice(usbDevice1, false);
shadowOf(usbManager).addOrUpdateUsbDevice(usbDevice2, false);
assertThat(usbManager.hasPermission(usbDevice1)).isFalse();
assertThat(usbManager.hasPermission(usbDevice2)).isFalse();
shadowOf(usbManager).addOrUpdateUsbDevice(usbDevice1, true);
assertThat(usbManager.hasPermission(usbDevice1)).isTrue();
assertThat(usbManager.hasPermission(usbDevice2)).isFalse();
}
@Test
@Config(minSdk = N)
public void grantPermission_selfPackage_shouldHavePermission() {
usbManager.grantPermission(usbDevice1);
assertThat(usbManager.hasPermission(usbDevice1)).isTrue();
}
@Test
@Config(minSdk = N_MR1)
public void grantPermission_differentPackage_shouldHavePermission() {
usbManager.grantPermission(usbDevice1, "foo.bar");
assertThat(shadowOf(usbManager).hasPermissionForPackage(usbDevice1, "foo.bar")).isTrue();
}
@Test
@Config(minSdk = N_MR1)
public void revokePermission_shouldNotHavePermission() {
usbManager.grantPermission(usbDevice1, "foo.bar");
assertThat(shadowOf(usbManager).hasPermissionForPackage(usbDevice1, "foo.bar")).isTrue();
shadowOf(usbManager).revokePermission(usbDevice1, "foo.bar");
assertThat(shadowOf(usbManager).hasPermissionForPackage(usbDevice1, "foo.bar")).isFalse();
}
@Test
@Config(minSdk = M, maxSdk = P)
public void getPorts_shouldReturnAddedPorts() {
shadowOf(usbManager).addPort("port1");
shadowOf(usbManager).addPort("port2");
shadowOf(usbManager).addPort("port3");
List<UsbPort> usbPorts = getUsbPorts();
assertThat(usbPorts).hasSize(3);
assertThat(usbPorts.stream().map(UsbPort::getId).collect(Collectors.toList()))
.containsExactly("port1", "port2", "port3");
}
@Test
@Config(minSdk = M)
public void clearPorts_shouldRemoveAllPorts() {
shadowOf(usbManager).addPort("port1");
shadowOf(usbManager).clearPorts();
List<UsbPort> usbPorts = getUsbPorts();
assertThat(usbPorts).isEmpty();
}
@Test
@Config(minSdk = M, maxSdk = P)
public void setPortRoles_sinkHost_shouldSetPortStatus() {
final int powerRoleSink = getStaticField(UsbPort.class, "POWER_ROLE_SINK");
final int dataRoleHost = getStaticField(UsbPort.class, "DATA_ROLE_HOST");
shadowOf(usbManager).addPort("port1");
List<UsbPort> usbPorts = getUsbPorts();
_usbManager_().setPortRoles(usbPorts.get(0), powerRoleSink, dataRoleHost);
UsbPortStatus usbPortStatus = _usbManager_().getPortStatus(usbPorts.get(0));
assertThat(usbPortStatus.getCurrentPowerRole()).isEqualTo(powerRoleSink);
assertThat(usbPortStatus.getCurrentDataRole()).isEqualTo(dataRoleHost);
}
@Test
public void removeDevice() {
assertThat(usbManager.getDeviceList()).isEmpty();
shadowOf(usbManager).addOrUpdateUsbDevice(usbDevice1, false);
shadowOf(usbManager).addOrUpdateUsbDevice(usbDevice2, false);
assertThat(usbManager.getDeviceList().values())
.containsExactly(usbDevice1, usbDevice2);
shadowOf(usbManager).removeUsbDevice(usbDevice1);
assertThat(usbManager.getDeviceList().values()).containsExactly(usbDevice2);
}
@Test
public void openAccessory() {
assertThat(usbManager.openAccessory(usbAccessory)).isNotNull();
}
@Test
public void setAccessory() {
assertThat(usbManager.getAccessoryList()).isNull();
shadowOf(usbManager).setAttachedUsbAccessory(usbAccessory);
assertThat(usbManager.getAccessoryList()).hasLength(1);
assertThat(usbManager.getAccessoryList()[0]).isEqualTo(usbAccessory);
}
/////////////////////////
private List<UsbPort> getUsbPorts() {
return Arrays.asList(_usbManager_().getPorts());
}
private _UsbManager_ _usbManager_() {
return reflector(_UsbManager_.class, usbManager);
}
}
|
spotify/robolectric
|
robolectric/src/test/java/org/robolectric/shadows/ShadowUsbManagerTest.java
|
Java
|
mit
| 6,191
|
---
layout: post
title: 皮囊
category: 书单
---
* 那一刻才明白啊太曾经对我说过的一句话,才明白啊太的生活观:我们的生命本来多轻盈,都是被这肉体和各种欲望的污浊给拖住。啊太,我记住了。“肉体是拿来用的,不是拿来伺候的”.请一定要来看望我。
* 明天晚上,你记得挑起你父亲各种愿望,让他想下来,越多愿望越好。一个人的求生的欲望越强,活下来的机会就越大。
* 文明人才怕东怕西,必要的时候我可以不文明,我比你底线低。
* 我们一定要活出自己想要的样子~!只有一次青春啊
* 厚朴,或许能真实的抵达这个世界的,能确切地抵达梦想的,不是不顾一切投入想象的狂热,而是务实、谦卑的,甚至你自己都看不起的可怜的隐忍。
* 海藏不住,也圈不住。对待海最好的办法,就是让每个人自己去找寻与他相处的办法。每片海,沉浮着不同的景致,也翻滚着
* 各自的危险。
* **我,或许许多人,都在不知道如何生活的情况下,往往采用最容易掩饰或最常用的借口——理想或者责任。**
* 本书中写了阿太,一个教会他用皮囊而非伺候的人;父亲,一个客观上造就了他的人;母亲,顽固的执着,爱着父亲的女人;文展,一个失去家乡又到不了远方的人;厚朴,一个不知道自己是谁,虚活着的人;我的亲人,我的朋友,我自己。
|
czero1995/czero1995.github.io
|
_posts/bookLife/2016-10-14-皮囊-.md
|
Markdown
|
mit
| 1,524
|
#!/usr/bin/env lua
-- FizzBuzz in Lua
for i = 1, 100 do
if i % 15 == 0 then
print("fizzbuzz")
elseif i % 3 == 0 then
print("fizz")
elseif i % 5 == 0 then
print("buzz")
else
print(i)
end
end
|
qjcg/CO2Aldrin
|
app/bin/fizzbuzz.lua
|
Lua
|
mit
| 204
|
// ___ ____ __ __
// / _ `/ _ \\ \ /
// \_,_/ .__/_\_\
// /_/
//
// 過去は未来によって変えられる。
//
// Copyright (c) 2014 Kenan Sulayman aka apx
//
// Based on third-party code:
//
// Copyright (c) 2010 Tom Hughes-Croucher
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
var dgram = require("dgram"),
util = require("util");
var host = "localhost",
port = process.env.port || 53;
const rev = 13;
var server = dgram.createSocket("udp4");
var dnx = Object.create({
records: {},
addRecord: function (domain) {
this.records[domain] = {
in: {
a: []//,
// not implemented
}
};
var qname = this.toolchain.utils.domainToQname(domain);
return {
delegate: function (r) {
if ( typeof r.rdata === "string" ) {
r.rdata = this.toolchain.utils.ip2dec(r.rdata);
}
if ( !r["qname"] ) {
r["qname"] = qname;
}
r["zname"] = domain;
if ( !this.records[domain] )
this.records[domain] = {};
if ( !this.records[domain]["in"] )
this.records[domain]["in"] = {};
if ( !this.records[domain]["in"][r.type || "a"] )
this.records[domain]["in"][r.type || "a"] = [];
return this.records[domain]["in"][r.type || "a"].push(r), r;
}.bind(this)
};
},
server: server,
toolchain: require("./lib/toolchain")
});
server.on("message", function(msg, rinfo) {
// parse query
var q = dnx.toolchain.processRequest(msg);
// build response
var buf = dnx.toolchain.createResponse(q, dnx.records);
dnx.server.send(buf, 0, buf.length, rinfo.port, rinfo.address);
});
server.addListener("error", function(e) {
throw e;
});
var config = require("./config.json");
Object.keys(config).forEach(function (e) {
var r = dnx.addRecord(e)
config[e].forEach(function (rx) {
r.delegate(rx);
})
})
server.bind(port, host);
console.log([
" __ ",
" ___/ /__ __ __",
"/ _ / _ \\\\ \\ /",
"\\_,_/_//_/_\\_\\",
" \t",
"[dnx r" + rev + "]",
""
].join("\n"))
require("dns").resolve(host, function (err, data) {
var revlookup = data ? " (" + data.join(", ") + ")" : "";
console.log("Delegation:");
Object.keys(dnx.records).forEach(function (d) {
console.log("\t=> ", d);
Object.keys(dnx.records[d]).forEach(function (c) {
Object.keys(dnx.records[d][c]).forEach(function (r) {
console.log("\t\t" + c + ": " + r + ":");
dnx.records[d][c][r].forEach(function (rx) {
console.log("\t\t\t", rx.qname, " (" + rx["zname"] + "): ", util.inspect(rx, {depth: null}).split("{ ").join("{\n ").split("\n").join("\n\t\t\t\t").split(" }").join("\n\t\t\t }"))
})
})
});
})
process.stdout.write("\nStarted server: " + host + revlookup + ", using port " + port + ".");
});
|
KenanSulayman/dnx
|
dns.js
|
JavaScript
|
mit
| 3,768
|
#ifndef BITCOIN_CHAINPARAMSSEEDS_H
#define BITCOIN_CHAINPARAMSSEEDS_H
/**
* List of fixed seed nodes for the bitcoin network
* AUTOGENERATED by contrib/seeds/generate-seeds.py
*
* Each line contains a 16-byte IPv6 address and a port.
* IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.
*/
static SeedSpec6 pnSeed6_main[] = {
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x68,0xec,0x25,0xb4}, 11533},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x2e,0x65,0x52,0xc0}, 11533},
};
static SeedSpec6 pnSeed6_test[] = {
};
#endif // BITCOIN_CHAINPARAMSSEEDS_H
|
mitocoinorg/mitocoin
|
src/chainparamsseeds.h
|
C
|
mit
| 639
|
//-----------------------------------------------------------------------
// <copyright file="WebApiToSwaggerGeneratorSettings.cs" company="NSwag">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/NSwag/NSwag/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using NJsonSchema;
using NJsonSchema.Annotations;
using NJsonSchema.Generation;
using NJsonSchema.Infrastructure;
using NSwag.SwaggerGeneration.Processors;
using NSwag.SwaggerGeneration.Processors.Contexts;
namespace NSwag.SwaggerGeneration.AspNetCore.Processors
{
internal class OperationParameterProcessor : IOperationProcessor
{
private readonly AspNetCoreToSwaggerGeneratorSettings _settings;
public OperationParameterProcessor(AspNetCoreToSwaggerGeneratorSettings settings)
{
_settings = settings;
}
/// <summary>Processes the specified method information.</summary>
/// <param name="operationProcessorContext"></param>
/// <returns>true if the operation should be added to the Swagger specification.</returns>
public async Task<bool> ProcessAsync(OperationProcessorContext operationProcessorContext)
{
if (!(operationProcessorContext is AspNetCoreOperationProcessorContext context))
{
return false;
}
var httpPath = context.OperationDescription.Path;
var parameters = context.ApiDescription.ParameterDescriptions;
var methodParameters = context.MethodInfo.GetParameters();
var position = 1;
foreach (var apiParameter in parameters.Where(p => p.Source != null))
{
// TODO: Provide extension point so that this can be implemented in the ApiVersionProcessor class
var versionProcessor = _settings.OperationProcessors.TryGet<ApiVersionProcessor>();
if (versionProcessor != null &&
versionProcessor.IgnoreParameter &&
apiParameter.ModelMetadata?.DataTypeName == "ApiVersion")
{
continue;
}
// In Mvc < 2.0, there isn't a good way to infer the attributes of a parameter with a IModelNameProvider.Name
// value that's different than the parameter name. Additionally, ApiExplorer will recurse in to complex model bound types
// and expose properties as top level parameters. Consequently, determining the property or parameter of an Api is best
// effort attempt.
var extendedApiParameter = new ExtendedApiParameterDescription
{
ApiParameter = apiParameter,
Attributes = Enumerable.Empty<Attribute>(),
ParameterType = apiParameter.Type
};
ParameterInfo parameter = null;
var propertyName = apiParameter.ModelMetadata?.PropertyName;
var property = !string.IsNullOrEmpty(propertyName) ?
apiParameter.ModelMetadata.ContainerType?.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance) :
null;
if (property != null)
{
extendedApiParameter.PropertyInfo = property;
extendedApiParameter.Attributes = property.GetCustomAttributes();
}
else
{
var parameterDescriptor = apiParameter.TryGetPropertyValue<ParameterDescriptor>("ParameterDescriptor");
var parameterName = parameterDescriptor?.Name ?? apiParameter.Name;
parameter = methodParameters.FirstOrDefault(m => m.Name.ToLowerInvariant() == parameterName.ToLowerInvariant());
if (parameter != null)
{
extendedApiParameter.ParameterInfo = parameter;
extendedApiParameter.Attributes = parameter.GetCustomAttributes();
}
else
{
parameterName = apiParameter.Name;
property = operationProcessorContext.ControllerType.GetProperty(parameterName, BindingFlags.Public | BindingFlags.Instance);
if (property != null)
{
extendedApiParameter.PropertyInfo = property;
extendedApiParameter.Attributes = property.GetCustomAttributes();
}
}
}
if (apiParameter.Type == null)
{
extendedApiParameter.ParameterType = typeof(string);
if (apiParameter.Source == BindingSource.Path)
{
// ignore unused implicit path parameters
if (!httpPath.ToLowerInvariant().Contains("{" + apiParameter.Name.ToLowerInvariant() + ":") &&
!httpPath.ToLowerInvariant().Contains("{" + apiParameter.Name.ToLowerInvariant() + "}"))
{
continue;
}
extendedApiParameter.Attributes = extendedApiParameter.Attributes.Concat(new[] { new NotNullAttribute() });
}
}
if (extendedApiParameter.Attributes.Any(a => a.GetType().Name == "SwaggerIgnoreAttribute"))
{
continue;
}
SwaggerParameter operationParameter = null;
if (apiParameter.Source == BindingSource.Path ||
(apiParameter.Source == BindingSource.Custom &&
httpPath.Contains($"{{{apiParameter.Name}}}")))
{
operationParameter = await CreatePrimitiveParameterAsync(context, extendedApiParameter).ConfigureAwait(false);
operationParameter.Kind = SwaggerParameterKind.Path;
operationParameter.IsRequired = true; // apiParameter.RouteInfo?.IsOptional == false;
context.OperationDescription.Operation.Parameters.Add(operationParameter);
}
else if (apiParameter.Source == BindingSource.Header)
{
operationParameter = await CreatePrimitiveParameterAsync(context, extendedApiParameter).ConfigureAwait(false);
operationParameter.Kind = SwaggerParameterKind.Header;
context.OperationDescription.Operation.Parameters.Add(operationParameter);
}
else if (apiParameter.Source == BindingSource.Query)
{
operationParameter = await CreatePrimitiveParameterAsync(context, extendedApiParameter).ConfigureAwait(false);
operationParameter.Kind = SwaggerParameterKind.Query;
context.OperationDescription.Operation.Parameters.Add(operationParameter);
}
else if (apiParameter.Source == BindingSource.Body)
{
operationParameter = await AddBodyParameterAsync(context, extendedApiParameter).ConfigureAwait(false);
}
else if (apiParameter.Source == BindingSource.Form)
{
operationParameter = await CreatePrimitiveParameterAsync(context, extendedApiParameter).ConfigureAwait(false);
operationParameter.Kind = SwaggerParameterKind.FormData;
context.OperationDescription.Operation.Parameters.Add(operationParameter);
}
else
{
if (await TryAddFileParameterAsync(context, extendedApiParameter).ConfigureAwait(false) == false)
{
operationParameter = await CreatePrimitiveParameterAsync(context, extendedApiParameter).ConfigureAwait(false);
operationParameter.Kind = SwaggerParameterKind.Query;
context.OperationDescription.Operation.Parameters.Add(operationParameter);
}
}
if (operationParameter != null)
{
operationParameter.Position = position;
position++;
if (_settings.SchemaType == SchemaType.OpenApi3)
{
operationParameter.IsNullableRaw = null;
}
if (parameter != null)
{
((Dictionary<ParameterInfo, SwaggerParameter>)operationProcessorContext.Parameters)[parameter] = operationParameter;
}
}
}
RemoveUnusedPathParameters(context.OperationDescription, httpPath);
UpdateConsumedTypes(context.OperationDescription);
EnsureSingleBodyParameter(context.OperationDescription);
return true;
}
private void EnsureSingleBodyParameter(SwaggerOperationDescription operationDescription)
{
if (operationDescription.Operation.ActualParameters.Count(p => p.Kind == SwaggerParameterKind.Body) > 1)
throw new InvalidOperationException($"The operation '{operationDescription.Operation.OperationId}' has more than one body parameter.");
}
private void UpdateConsumedTypes(SwaggerOperationDescription operationDescription)
{
if (operationDescription.Operation.ActualParameters.Any(p => p.Type == JsonObjectType.File))
operationDescription.Operation.Consumes = new List<string> { "multipart/form-data" };
}
private void RemoveUnusedPathParameters(SwaggerOperationDescription operationDescription, string httpPath)
{
operationDescription.Path = "/" + Regex.Replace(httpPath, "{(.*?)(:(([^/]*)?))?}", match =>
{
var parameterName = match.Groups[1].Value.TrimEnd('?');
if (operationDescription.Operation.ActualParameters.Any(p => p.Kind == SwaggerParameterKind.Path && string.Equals(p.Name, parameterName, StringComparison.OrdinalIgnoreCase)))
return "{" + parameterName + "}";
return string.Empty;
}).Trim('/');
}
private bool IsNullable(ParameterInfo parameter)
{
var isNullable = Nullable.GetUnderlyingType(parameter.ParameterType) != null;
if (isNullable)
return false;
return parameter.ParameterType.GetTypeInfo().IsValueType;
}
private async Task<bool> TryAddFileParameterAsync(
OperationProcessorContext context, ExtendedApiParameterDescription extendedApiParameter)
{
var info = _settings.ReflectionService.GetDescription(extendedApiParameter.ParameterType, extendedApiParameter.Attributes, _settings);
var isFileArray = IsFileArray(extendedApiParameter.ApiParameter.Type, info);
var attributes = extendedApiParameter.Attributes
.Union(extendedApiParameter.ParameterType.GetTypeInfo().GetCustomAttributes());
var hasSwaggerFileAttribute = attributes.Any(a =>
a.GetType().IsAssignableTo("SwaggerFileAttribute", TypeNameStyle.Name));
if (info.Type == JsonObjectType.File || hasSwaggerFileAttribute || isFileArray)
{
await AddFileParameterAsync(context, extendedApiParameter, isFileArray).ConfigureAwait(false);
return true;
}
return false;
}
private async Task AddFileParameterAsync(OperationProcessorContext context, ExtendedApiParameterDescription extendedApiParameter, bool isFileArray)
{
var operationParameter = await CreatePrimitiveParameterAsync(context, extendedApiParameter).ConfigureAwait(false);
InitializeFileParameter(operationParameter, isFileArray);
context.OperationDescription.Operation.Parameters.Add(operationParameter);
}
private bool IsFileArray(Type type, JsonTypeDescription typeInfo)
{
var isFormFileCollection = type.Name == "IFormFileCollection";
var isFileArray = typeInfo.Type == JsonObjectType.Array && type.GenericTypeArguments.Any() &&
_settings.ReflectionService.GetDescription(type.GenericTypeArguments[0], null, _settings).Type == JsonObjectType.File;
return isFormFileCollection || isFileArray;
}
private async Task<SwaggerParameter> AddBodyParameterAsync(OperationProcessorContext context, ExtendedApiParameterDescription extendedApiParameter)
{
SwaggerParameter operationParameter;
var typeDescription = _settings.ReflectionService.GetDescription(
extendedApiParameter.ParameterType, extendedApiParameter.Attributes, _settings);
var isNullable = _settings.AllowNullableBodyParameters && typeDescription.IsNullable;
var operation = context.OperationDescription.Operation;
var parameterType = extendedApiParameter.ParameterType;
if (parameterType.Name == "XmlDocument" || parameterType.InheritsFrom("XmlDocument", TypeNameStyle.Name))
{
operation.Consumes = new List<string> { "application/xml" };
operationParameter = new SwaggerParameter
{
Name = extendedApiParameter.ApiParameter.Name,
Kind = SwaggerParameterKind.Body,
Schema = new JsonSchema4
{
Type = JsonObjectType.String,
IsNullableRaw = isNullable
},
IsNullableRaw = isNullable,
IsRequired = extendedApiParameter.IsRequired(_settings.RequireParametersWithoutDefault),
Description = await extendedApiParameter.GetDocumentationAsync().ConfigureAwait(false)
};
}
else if (parameterType.IsAssignableTo("System.IO.Stream", TypeNameStyle.FullName))
{
operation.Consumes = new List<string> { "application/octet-stream" };
operationParameter = new SwaggerParameter
{
Name = extendedApiParameter.ApiParameter.Name,
Kind = SwaggerParameterKind.Body,
Schema = new JsonSchema4
{
Type = JsonObjectType.String,
Format = JsonFormatStrings.Byte,
IsNullableRaw = isNullable
},
IsNullableRaw = isNullable,
IsRequired = extendedApiParameter.IsRequired(_settings.RequireParametersWithoutDefault),
Description = await extendedApiParameter.GetDocumentationAsync().ConfigureAwait(false)
};
}
else // body from type
{
operationParameter = new SwaggerParameter
{
Name = extendedApiParameter.ApiParameter.Name,
Kind = SwaggerParameterKind.Body,
IsRequired = extendedApiParameter.IsRequired(_settings.RequireParametersWithoutDefault),
IsNullableRaw = isNullable,
Description = await extendedApiParameter.GetDocumentationAsync().ConfigureAwait(false),
Schema = await context.SchemaGenerator.GenerateWithReferenceAndNullabilityAsync<JsonSchema4>(
extendedApiParameter.ParameterType, extendedApiParameter.Attributes, isNullable, schemaResolver: context.SchemaResolver).ConfigureAwait(false)
};
}
operation.Parameters.Add(operationParameter);
return operationParameter;
}
private async Task<SwaggerParameter> CreatePrimitiveParameterAsync(
OperationProcessorContext context,
ExtendedApiParameterDescription extendedApiParameter)
{
var operationParameter = await context.SwaggerGenerator.CreatePrimitiveParameterAsync(
extendedApiParameter.ApiParameter.Name,
await extendedApiParameter.GetDocumentationAsync().ConfigureAwait(false),
extendedApiParameter.ParameterType,
extendedApiParameter.Attributes).ConfigureAwait(false);
if (extendedApiParameter.ParameterInfo?.HasDefaultValue == true)
{
operationParameter.Default = extendedApiParameter.ParameterInfo.DefaultValue;
}
operationParameter.IsRequired = extendedApiParameter.IsRequired(_settings.RequireParametersWithoutDefault);
return operationParameter;
}
private void InitializeFileParameter(SwaggerParameter operationParameter, bool isFileArray)
{
operationParameter.Type = JsonObjectType.File;
operationParameter.Kind = SwaggerParameterKind.FormData;
if (isFileArray)
operationParameter.CollectionFormat = SwaggerParameterCollectionFormat.Multi;
}
private class ExtendedApiParameterDescription
{
public ApiParameterDescription ApiParameter { get; set; }
public ParameterInfo ParameterInfo { get; set; }
public PropertyInfo PropertyInfo { get; set; }
public Type ParameterType { get; set; }
public IEnumerable<Attribute> Attributes { get; set; }
public bool IsRequired(bool requireParametersWithoutDefault)
{
var isRequired = false;
// available in asp.net core >= 2.2
if (ApiParameter.HasProperty("IsRequired"))
{
isRequired = ApiParameter.TryGetPropertyValue("IsRequired", false);
}
else
{
// fallback for asp.net core <= 2.1
if (ApiParameter.Source == BindingSource.Body)
{
isRequired = true;
}
else if (ApiParameter.ModelMetadata != null &&
ApiParameter.ModelMetadata.IsBindingRequired)
{
isRequired = true;
}
else if (ApiParameter.Source == BindingSource.Path &&
ApiParameter.RouteInfo != null &&
ApiParameter.RouteInfo.IsOptional == false)
{
isRequired = true;
}
}
return isRequired || (requireParametersWithoutDefault && ParameterInfo?.HasDefaultValue != true);
}
public async Task<string> GetDocumentationAsync()
{
var parameterDocumentation = string.Empty;
if (ParameterInfo != null)
{
parameterDocumentation = await ParameterInfo.GetDescriptionAsync(Attributes).ConfigureAwait(false);
}
else if (PropertyInfo != null)
{
parameterDocumentation = await PropertyInfo.GetDescriptionAsync(Attributes).ConfigureAwait(false);
}
return parameterDocumentation;
}
}
}
}
|
NSwag/NSwag
|
src/NSwag.SwaggerGeneration.AspNetCore/Processors/OperationParameterProcessor.cs
|
C#
|
mit
| 20,145
|
//==========================================================
// CasaEngine - Free C++ 3D engine
//
// Copyright (C) 2004-2005 Laurent Gomila
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// 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.
//
// E-mail : laurent.gom@gmail.com
//==========================================================
#ifndef DX9BUFFER_H
#define DX9BUFFER_H
//==========================================================
// En-têtes
//==========================================================
#include "DX9Enum.h"
#include "Graphics/Vertices/BufferBase.h"
#include "CA_Assert.h"
struct IDirect3DVertexBuffer9;
struct IDirect3DIndexBuffer9;
namespace CasaEngine
{
/////////////////////////////////////////////////////////////
// Spécialisation DirectX9 des vertex / index buffers
/////////////////////////////////////////////////////////////
template <class T>
class DX9Buffer : public IBufferBase
{
public :
//----------------------------------------------------------
// Constructeur
//----------------------------------------------------------
DX9Buffer(unsigned long Count, T* Buffer);
//----------------------------------------------------------
// Renvoie un pointeur sur le buffer
//----------------------------------------------------------
T* GetBuffer() const;
private :
/**
*
*/
void Fill(const void* Data, unsigned long size_, unsigned long flags_);
//----------------------------------------------------------
// Verrouille le buffer
//----------------------------------------------------------
void* Lock(unsigned long Offset, unsigned long Size, unsigned long Flags);
//----------------------------------------------------------
// Déverouille le buffer
//----------------------------------------------------------
void Unlock();
//----------------------------------------------------------
// Données membres
//----------------------------------------------------------
SmartPtr<T, CResourceCOM> m_Buffer; ///< Pointeur sur le buffer Dx9
};
//==========================================================
// Définition des vertex / index buffers à partir du template DX9Buffer
//==========================================================
typedef DX9Buffer<IDirect3DVertexBuffer9> DX9VertexBuffer;
typedef DX9Buffer<IDirect3DIndexBuffer9> DX9IndexBuffer;
#include "DX9Buffer.inl"
} // namespace CasaEngine
#endif // DX9BUFFER_H
|
xcasadio/casaengine
|
src/Engine/Graphics/Renderer/DX9/DX9Buffer.h
|
C
|
mit
| 3,234
|
package net.anotheria.moskito.webui.dashboards.action;
import net.anotheria.maf.action.ActionCommand;
import net.anotheria.maf.action.ActionMapping;
import net.anotheria.maf.bean.FormBean;
import net.anotheria.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This action creates a new accumulator.
* @author lrosenberg
*/
public class DashboardAddGaugeAction extends BaseDashboardAction {
@Override
public ActionCommand execute(ActionMapping mapping, FormBean formBean, HttpServletRequest request, HttpServletResponse response) throws Exception {
String gaugeName = request.getParameter("pName");
String[] dashboardsName = request.getParameterValues("pDashboards");
if (dashboardsName == null || dashboardsName.length == 0) {
setInfoMessage("Nothing selected!");
return mapping.redirect();
}
for(String dashboard : dashboardsName) {
getDashboardAPI().addGaugeToDashboard(dashboard, gaugeName);
}
setInfoMessage(createInfoMessage(gaugeName, dashboardsName));
return mapping.redirect().addParameter("dashboard", dashboardsName[0]);
}
private String createInfoMessage(String gaugeName, String[] dashboardsName) {
if (dashboardsName.length > 1)
return "Gauge \'"+gaugeName+"\' has been added to following dashboards: "+ StringUtils.concatenateTokens(", ", dashboardsName);
else
return "Gauge \'"+gaugeName+"\' has been added to dashboard \'"+ dashboardsName[0] + "\'";
}
}
|
anotheria/moskito
|
moskito-webui/src/main/java/net/anotheria/moskito/webui/dashboards/action/DashboardAddGaugeAction.java
|
Java
|
mit
| 1,488
|
'use strict'
import trumpet from 'trumpet'
import { trumpetInnerText } from './index'
import JsonStream from 'JSONStream'
// Myfox page not found is a code 200... must fix it!
const notFound200 = function () {
const parser = trumpet()
parser.select('head title', trumpetInnerText((data) => {
parser.status = 200
if (data.indexOf('Page not found') !== -1) {
parser.status = 404
const error = new Error('Page not found case returned by Myfox.')
error.status = 404
return parser.emit('error', error)
}
}))
return parser
}
// Myfox code KO is a code 200... must fix it and return error messages.
const codeKo200 = function () {
const parser = JsonStream.parse('code')
parser.on('data', (data) => {
if (data === 'KO') {
const error = new Error('Code KO returned by Myfox.')
error.status = 400
return parser.emit('error', error)
}
})
return parser
}
export { notFound200 as notFound200 }
export { codeKo200 as codeKo200 }
|
gxapplications/myfox-wrapper-api
|
lib/html-parsers/false-error-codes.js
|
JavaScript
|
mit
| 998
|
/**
*/
package CIM.IEC61968.PaymentMetering;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.eclipse.emf.common.util.Enumerator;
/**
* <!-- begin-user-doc -->
* A representation of the literals of the enumeration '<em><b>Charge Kind</b></em>',
* and utility methods for working with them.
* <!-- end-user-doc -->
* @see CIM.IEC61968.PaymentMetering.PaymentMeteringPackage#getChargeKind()
* @model
* @generated
*/
public enum ChargeKind implements Enumerator {
/**
* The '<em><b>Auxiliary Charge</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #AUXILIARY_CHARGE_VALUE
* @generated
* @ordered
*/
AUXILIARY_CHARGE(0, "auxiliaryCharge", "auxiliaryCharge"),
/**
* The '<em><b>Consumption Charge</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #CONSUMPTION_CHARGE_VALUE
* @generated
* @ordered
*/
CONSUMPTION_CHARGE(1, "consumptionCharge", "consumptionCharge"),
/**
* The '<em><b>Other</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #OTHER_VALUE
* @generated
* @ordered
*/
OTHER(2, "other", "other"),
/**
* The '<em><b>Demand Charge</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #DEMAND_CHARGE_VALUE
* @generated
* @ordered
*/
DEMAND_CHARGE(3, "demandCharge", "demandCharge"),
/**
* The '<em><b>Tax Charge</b></em>' literal object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #TAX_CHARGE_VALUE
* @generated
* @ordered
*/
TAX_CHARGE(4, "taxCharge", "taxCharge");
/**
* The '<em><b>Auxiliary Charge</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Auxiliary Charge</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #AUXILIARY_CHARGE
* @model name="auxiliaryCharge"
* @generated
* @ordered
*/
public static final int AUXILIARY_CHARGE_VALUE = 0;
/**
* The '<em><b>Consumption Charge</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Consumption Charge</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #CONSUMPTION_CHARGE
* @model name="consumptionCharge"
* @generated
* @ordered
*/
public static final int CONSUMPTION_CHARGE_VALUE = 1;
/**
* The '<em><b>Other</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Other</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #OTHER
* @model name="other"
* @generated
* @ordered
*/
public static final int OTHER_VALUE = 2;
/**
* The '<em><b>Demand Charge</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Demand Charge</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #DEMAND_CHARGE
* @model name="demandCharge"
* @generated
* @ordered
*/
public static final int DEMAND_CHARGE_VALUE = 3;
/**
* The '<em><b>Tax Charge</b></em>' literal value.
* <!-- begin-user-doc -->
* <p>
* If the meaning of '<em><b>Tax Charge</b></em>' literal object isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @see #TAX_CHARGE
* @model name="taxCharge"
* @generated
* @ordered
*/
public static final int TAX_CHARGE_VALUE = 4;
/**
* An array of all the '<em><b>Charge Kind</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private static final ChargeKind[] VALUES_ARRAY =
new ChargeKind[] {
AUXILIARY_CHARGE,
CONSUMPTION_CHARGE,
OTHER,
DEMAND_CHARGE,
TAX_CHARGE,
};
/**
* A public read-only list of all the '<em><b>Charge Kind</b></em>' enumerators.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static final List<ChargeKind> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY));
/**
* Returns the '<em><b>Charge Kind</b></em>' literal with the specified literal value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param literal the literal.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static ChargeKind get(String literal) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
ChargeKind result = VALUES_ARRAY[i];
if (result.toString().equals(literal)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Charge Kind</b></em>' literal with the specified name.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param name the name.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static ChargeKind getByName(String name) {
for (int i = 0; i < VALUES_ARRAY.length; ++i) {
ChargeKind result = VALUES_ARRAY[i];
if (result.getName().equals(name)) {
return result;
}
}
return null;
}
/**
* Returns the '<em><b>Charge Kind</b></em>' literal with the specified integer value.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the integer value.
* @return the matching enumerator or <code>null</code>.
* @generated
*/
public static ChargeKind get(int value) {
switch (value) {
case AUXILIARY_CHARGE_VALUE: return AUXILIARY_CHARGE;
case CONSUMPTION_CHARGE_VALUE: return CONSUMPTION_CHARGE;
case OTHER_VALUE: return OTHER;
case DEMAND_CHARGE_VALUE: return DEMAND_CHARGE;
case TAX_CHARGE_VALUE: return TAX_CHARGE;
}
return null;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final int value;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String name;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private final String literal;
/**
* Only this class can construct instances.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
private ChargeKind(int value, String name, String literal) {
this.value = value;
this.name = name;
this.literal = literal;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getValue() {
return value;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getName() {
return name;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getLiteral() {
return literal;
}
/**
* Returns the literal value of the enumerator, which is its string representation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
return literal;
}
} //ChargeKind
|
georghinkel/ttc2017smartGrids
|
solutions/ModelJoin/src/main/java/CIM/IEC61968/PaymentMetering/ChargeKind.java
|
Java
|
mit
| 7,017
|
import {IconDefinition, IconLookup, IconName, IconPrefix, IconPathData, IconPack } from '@fortawesome/fontawesome-common-types';
export {IconDefinition, IconLookup, IconName, IconPrefix, IconPathData, IconPack } from '@fortawesome/fontawesome-common-types';
export const dom: DOM;
export const library: Library;
export const parse: { transform(transformString: string): Transform };
export const config: Config;
export function noAuto():void;
export function findIconDefinition(iconLookup: IconLookup): IconDefinition;
export function text(content: string, params?: TextParams): Text;
export function counter(content: string | number, params?: CounterParams): Counter;
export function toHtml(content: any): string;
export function toHtml(abstractNodes: AbstractElement): string;
export function layer(
assembler: (
addLayerCallback: (layerToAdd: IconOrText | IconOrText[]) => void
) => void,
params?: LayerParams
): Layer;
export function icon(icon: IconName | IconLookup, params?: IconParams): Icon;
export type IconProp = IconName | [IconPrefix, IconName] | IconLookup;
export type FlipProp = "horizontal" | "vertical" | "both";
export type SizeProp =
| "xs"
| "lg"
| "sm"
| "1x"
| "2x"
| "3x"
| "4x"
| "5x"
| "6x"
| "7x"
| "8x"
| "9x"
| "10x";
export type PullProp = "left" | "right";
export type RotateProp = 90 | 180 | 270;
export type FaSymbol = string | boolean;
export interface Config {
familyPrefix: IconPrefix;
replacementClass: string;
autoReplaceSvg: boolean | 'nest';
autoAddCss: boolean;
autoA11y: boolean;
searchPseudoElements: boolean;
observeMutations: boolean;
keepOriginalSource: boolean;
measurePerformance: boolean;
showMissingIcons: boolean;
}
export interface AbstractElement {
tag: string;
attributes: any;
children?: AbstractElement[];
}
export interface FontawesomeObject {
readonly abstract: AbstractElement[];
readonly html: string[];
readonly node: HTMLCollection;
}
export interface Icon extends FontawesomeObject, IconDefinition {
readonly type: "icon";
}
export interface Text extends FontawesomeObject {
readonly type: "text";
}
export interface Counter extends FontawesomeObject {
readonly type: "counter";
}
export interface Layer extends FontawesomeObject {
readonly type: "layer";
}
type IconOrText = Icon | Text;
export interface Attributes {
[key: string]: number | string;
}
export interface Styles {
[key: string]: string;
}
export interface Transform {
size?: number;
x?: number;
y?: number;
rotate?: number;
flipX?: boolean;
flipY?: boolean;
}
export interface Params {
title?: string;
classes?: string | string[];
attributes?: Attributes;
styles?: Styles;
}
export interface CounterParams extends Params {
}
export interface LayerParams {
classes?: string | string[];
}
export interface TextParams extends Params {
transform?: Transform;
}
export interface IconParams extends Params {
transform?: Transform;
symbol?: FaSymbol;
mask?: IconLookup;
}
export interface DOM {
i2svg(params?: { node: Node; callback: () => void }): Promise<void>;
css(): string;
insertCss(): string;
watch(): void;
}
type IconDefinitionOrPack = IconDefinition | IconPack;
export interface Library {
add(...definitions: IconDefinitionOrPack[]): void;
reset(): void;
}
|
Hendrik44/pi-weather-app
|
Carthage/Checkouts/FontAwesome.swift/FortAwesome/Font-Awesome/js-packages/@fortawesome/fontawesome-svg-core/index.d.ts
|
TypeScript
|
mit
| 3,310
|
/*
* The Plaid API
*
* The Plaid REST API. Please see https://plaid.com/docs/api for more details.
*
* API version: 2020-09-14_1.78.0
*/
// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT.
package plaid
import (
"encoding/json"
)
// LinkTokenCreateRequestUpdate Specifies options for initializing Link for [update mode](https://plaid.com/docs/link/update-mode).
type LinkTokenCreateRequestUpdate struct {
// If `true`, enables [update mode with Account Select](https://plaid.com/docs/link/update-mode/#using-update-mode-to-request-new-accounts).
AccountSelectionEnabled *bool `json:"account_selection_enabled,omitempty"`
}
// NewLinkTokenCreateRequestUpdate instantiates a new LinkTokenCreateRequestUpdate object
// This constructor will assign default values to properties that have it defined,
// and makes sure properties required by API are set, but the set of arguments
// will change when the set of required properties is changed
func NewLinkTokenCreateRequestUpdate() *LinkTokenCreateRequestUpdate {
this := LinkTokenCreateRequestUpdate{}
var accountSelectionEnabled bool = false
this.AccountSelectionEnabled = &accountSelectionEnabled
return &this
}
// NewLinkTokenCreateRequestUpdateWithDefaults instantiates a new LinkTokenCreateRequestUpdate object
// This constructor will only assign default values to properties that have it defined,
// but it doesn't guarantee that properties required by API are set
func NewLinkTokenCreateRequestUpdateWithDefaults() *LinkTokenCreateRequestUpdate {
this := LinkTokenCreateRequestUpdate{}
var accountSelectionEnabled bool = false
this.AccountSelectionEnabled = &accountSelectionEnabled
return &this
}
// GetAccountSelectionEnabled returns the AccountSelectionEnabled field value if set, zero value otherwise.
func (o *LinkTokenCreateRequestUpdate) GetAccountSelectionEnabled() bool {
if o == nil || o.AccountSelectionEnabled == nil {
var ret bool
return ret
}
return *o.AccountSelectionEnabled
}
// GetAccountSelectionEnabledOk returns a tuple with the AccountSelectionEnabled field value if set, nil otherwise
// and a boolean to check if the value has been set.
func (o *LinkTokenCreateRequestUpdate) GetAccountSelectionEnabledOk() (*bool, bool) {
if o == nil || o.AccountSelectionEnabled == nil {
return nil, false
}
return o.AccountSelectionEnabled, true
}
// HasAccountSelectionEnabled returns a boolean if a field has been set.
func (o *LinkTokenCreateRequestUpdate) HasAccountSelectionEnabled() bool {
if o != nil && o.AccountSelectionEnabled != nil {
return true
}
return false
}
// SetAccountSelectionEnabled gets a reference to the given bool and assigns it to the AccountSelectionEnabled field.
func (o *LinkTokenCreateRequestUpdate) SetAccountSelectionEnabled(v bool) {
o.AccountSelectionEnabled = &v
}
func (o LinkTokenCreateRequestUpdate) MarshalJSON() ([]byte, error) {
toSerialize := map[string]interface{}{}
if o.AccountSelectionEnabled != nil {
toSerialize["account_selection_enabled"] = o.AccountSelectionEnabled
}
return json.Marshal(toSerialize)
}
type NullableLinkTokenCreateRequestUpdate struct {
value *LinkTokenCreateRequestUpdate
isSet bool
}
func (v NullableLinkTokenCreateRequestUpdate) Get() *LinkTokenCreateRequestUpdate {
return v.value
}
func (v *NullableLinkTokenCreateRequestUpdate) Set(val *LinkTokenCreateRequestUpdate) {
v.value = val
v.isSet = true
}
func (v NullableLinkTokenCreateRequestUpdate) IsSet() bool {
return v.isSet
}
func (v *NullableLinkTokenCreateRequestUpdate) Unset() {
v.value = nil
v.isSet = false
}
func NewNullableLinkTokenCreateRequestUpdate(val *LinkTokenCreateRequestUpdate) *NullableLinkTokenCreateRequestUpdate {
return &NullableLinkTokenCreateRequestUpdate{value: val, isSet: true}
}
func (v NullableLinkTokenCreateRequestUpdate) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value)
}
func (v *NullableLinkTokenCreateRequestUpdate) UnmarshalJSON(src []byte) error {
v.isSet = true
return json.Unmarshal(src, &v.value)
}
|
plaid/plaid-go
|
plaid/model_link_token_create_request_update.go
|
GO
|
mit
| 4,051
|
/**
* Created by sasakiumi on 3/2/14.
*/
public class DigitObserver implements Observer {
@Override
public void update(NumberGenerator generator) {
System.out.println("DigitObserver" + generator.getNumber());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
|
Lewuathe/java-GoF
|
Observer/src/DigitObserver.java
|
Java
|
mit
| 335
|
package controller.experiment.thermocouple;
import java.awt.Component;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.swing.JFileChooser;
import model.thermocouple.graduate.Graduate;
import model.thermocouple.graduate.GraduateFactory;
/**
* Преобразователь градуировки из термоЭДС в температуру с помощью файла
* градуировки. Используется GUI. <b>Внимание</b>, нет проверки на наличие
* графической среды, так что могут быть сбои
*
* @author Mikey
*
*/
public class GraduateConverter implements Runnable {
JFileChooser fileChooser;
Component parent;
public GraduateConverter(Component parent) {
this.parent = parent;
}
@Override
public void run() {
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setDialogTitle("Выберите файл с градуировкой");
int status = fileChooser.showOpenDialog(parent);
if (status != JFileChooser.APPROVE_OPTION)
return;
if (fileChooser.getSelectedFile() == null)
return;
Path graduateFilePath = fileChooser.getSelectedFile().toPath();
Graduate graduate = null;
graduate = GraduateFactory.forBinary(graduateFilePath.toFile());
if (graduate == null) {
graduate = GraduateFactory.forTextFile(graduateFilePath);
}
if (graduate == null)
return;
fileChooser.setDialogTitle("Какой файл преобразовать?");
status = fileChooser.showOpenDialog(parent);
if (status != JFileChooser.APPROVE_OPTION)
return;
if (fileChooser.getSelectedFile() == null)
return;
List<String> tVtgLines = null;
try {
tVtgLines = Files.readAllLines(fileChooser.getSelectedFile().toPath());
} catch (IOException e) {
e.printStackTrace();
return;
}
if (tVtgLines == null)
return;
List<Double> values = new ArrayList<>();
NumberFormat numberFormat = NumberFormat.getInstance(Locale.getDefault());
for (String line : tVtgLines) {
Double voltage = 0d;
try {
Number n = numberFormat.parse(line);
voltage = n.doubleValue();
} catch (ParseException e1) {
e1.printStackTrace();
} finally {
values.add(graduate.getTemperature(voltage, 22 + 273));
}
}
try (PrintStream ps = new PrintStream(fileChooser.getSelectedFile())) {
for (Double value : values) {
ps.println(String.format(Locale.getDefault(), "%.3f", value));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
MikhailChe/TemperatureWaveMethod
|
src/controller/experiment/thermocouple/GraduateConverter.java
|
Java
|
mit
| 2,883
|
const chalk = require('chalk');
const { curry } = require('ramda');
const log = curry((color, string) => console.info(color(string)));
const good = log(chalk.green);
const info = log(chalk.cyan);
const warn = log(chalk.magenta);
const bad = log(chalk.red.bold);
module.exports = (server, port) => {
const resolve = (signal) => {
info('\n');
info(`Signal ${signal} received`);
info(`Express is shutting down on http://localhost:${port}`);
server.close();
good('\nThe server shutdown gracefully');
};
const reject = (signal, error) => {
warn('\nThe server did NOT shutdown gracefully\n');
bad(error);
};
const shutdown = (signal) => {
try {
resolve(signal);
process.exit(0);
} catch (error) {
reject(signal, error);
process.exit(-1);
}
};
const signals = ['SIGTERM', 'SIGHUP', 'SIGINT'];
signals.forEach(signal => process.on(signal, () => shutdown(signal)));
};
|
halis/cocoapuff
|
src/server/shutdown.js
|
JavaScript
|
mit
| 947
|
---
date: 2017-01-15
layout: log
location: Dallas, TX (fly) Atlanta, GA
coffee:
office:
restaurants: Au Rendez-Vous
bars:
beers:
hikes:
movies: Singin' in the Rain
games:
climbing: Stone Summit
books:
links:
achievements:
personal_growth:
highlight:
description:
private_notes:
---
Picked up Blue from airport parking, everything started fine! Walked around Piedmont Park for awhile, then met up with Meredith again later in the day for climbing at the _huge_ Stone Summit climbing gym, amazing french food at a restaurant owned by a Vietnamese lady, and watching Singin' in the Rain at a special 65th anniversary showing.
|
jhanstra/jh-gatsby
|
pages/jot/2017/01/2017-01-15/index.md
|
Markdown
|
mit
| 624
|
#if UNITY_ANDROID && ! UNITY_EDITOR
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.11
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
using System;
using System.Runtime.InteropServices;
public class AkThreadProperties : IDisposable {
private IntPtr swigCPtr;
protected bool swigCMemOwn;
internal AkThreadProperties(IntPtr cPtr, bool cMemoryOwn) {
swigCMemOwn = cMemoryOwn;
swigCPtr = cPtr;
}
internal static IntPtr getCPtr(AkThreadProperties obj) {
return (obj == null) ? IntPtr.Zero : obj.swigCPtr;
}
~AkThreadProperties() {
Dispose();
}
public virtual void Dispose() {
lock(this) {
if (swigCPtr != IntPtr.Zero) {
if (swigCMemOwn) {
swigCMemOwn = false;
AkSoundEnginePINVOKE.CSharp_delete_AkThreadProperties(swigCPtr);
}
swigCPtr = IntPtr.Zero;
}
GC.SuppressFinalize(this);
}
}
public int nPriority {
set {
AkSoundEnginePINVOKE.CSharp_AkThreadProperties_nPriority_set(swigCPtr, value);
}
get {
int ret = AkSoundEnginePINVOKE.CSharp_AkThreadProperties_nPriority_get(swigCPtr);
return ret;
}
}
public uint uStackSize {
set {
AkSoundEnginePINVOKE.CSharp_AkThreadProperties_uStackSize_set(swigCPtr, value);
}
get {
uint ret = AkSoundEnginePINVOKE.CSharp_AkThreadProperties_uStackSize_get(swigCPtr);
return ret;
}
}
public int uSchedPolicy {
set {
AkSoundEnginePINVOKE.CSharp_AkThreadProperties_uSchedPolicy_set(swigCPtr, value);
}
get {
int ret = AkSoundEnginePINVOKE.CSharp_AkThreadProperties_uSchedPolicy_get(swigCPtr);
return ret;
}
}
public uint dwAffinityMask {
set {
AkSoundEnginePINVOKE.CSharp_AkThreadProperties_dwAffinityMask_set(swigCPtr, value);
}
get {
uint ret = AkSoundEnginePINVOKE.CSharp_AkThreadProperties_dwAffinityMask_get(swigCPtr);
return ret;
}
}
public AkThreadProperties() : this(AkSoundEnginePINVOKE.CSharp_new_AkThreadProperties(), true) {
}
}
#endif // #if UNITY_ANDROID && ! UNITY_EDITOR
|
TeamTorchBear/Guzzlesaurus
|
Assets/Wwise/Deployment/API/Generated/Android/AkThreadProperties_Android.cs
|
C#
|
mit
| 2,378
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
using System.Text;
using Cadenza;
namespace Awareness.Agnostic
{
public abstract class AbstractPlatform
{
public abstract IClock Clock { get; }
public abstract DateTime LastActivity { get; }
protected abstract String ResourcesDirectory { get; }
public readonly AbstractPreferences Preferences;
public abstract event EventHandler ApplicationLaunched, ApplicationWillQuit, SystemResumed;
public AbstractPlatform(AbstractPreferences preferences)
{
Preferences = preferences;
}
public abstract void ThreadSleep(TimeSpan duration);
public abstract void RunOnMainThread(Action act);
public string ResourceNamed(string name)
{
var path = Path.Combine(ResourcesDirectory, name);
if (!File.Exists(path))
throw new FileNotFoundException("Resource not found: " + path);
return path;
}
public abstract Thread CreateWorkerThread (Action act);
public abstract IThreadEvent GetThreadEvent();
public abstract AbstractBowlSound CreateBowlSound(string soundPath);
public abstract void OpenUrl (string url);
}
}
|
dvdsgl/awareness
|
Awareness.Agnostic/AbstractPlatform.cs
|
C#
|
mit
| 1,322
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bitcamp.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
jerrrytan/bitcamp
|
bitcamp/manage.py
|
Python
|
mit
| 250
|
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const WebpackShellPlugin = require('webpack-shell-plugin');
const { join, resolve } = require('path');
var BUILD_DIR = resolve(__dirname, '../../priv/static');
var APP_DIR = __dirname;
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var config = {
entry:{
'app.bundle': [resolve(__dirname, 'js/App.jsx')],
'store.bundle': [resolve(__dirname, 'js/app/store.js')],
'dependencies.bundle': [
"react",
"react-dom",
"react-redux",
"redux-thunk",
"redux-logger",
"react-router-redux",
"react-router-dom",
"history",
"react-apollo",
"qrcode.react",
"graphql-tag",
"react-select",
"apollo-phoenix-websocket",
"jquery",
"phoenix",
"bootstrap",
]
},
output: {
path: BUILD_DIR,
publicPath: '/js',
filename: 'js/[name].js'
},
plugins: [
new WebpackShellPlugin({onBuildStart:['cp -R ../shared .']}),
new webpack.SourceMapDevToolPlugin(),
new ExtractTextPlugin('css/app.css', { allChunks: true }),
new webpack.EnvironmentPlugin({
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
DEBUG: process.env.NODE_ENV == 'development'
}),
new webpack.optimize.CommonsChunkPlugin({ name: "dependencies.bundle", filename: 'js/[name].js', minChunks: Infinity }),
// new webpack.ProvidePlugin({
// Promise: 'babel-polyfill'
// }),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery"
}),
new CopyWebpackPlugin([{ from: resolve(join(__dirname, "./assets")) }], { ignore: [resolve(join(__dirname, '.gitkeep'))] })
],
resolve: {
extensions: ['.json', '.jsx', '.js']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
include: __dirname,
use: {
loader: 'babel-loader',
options: {
presets: ['es2015', 'react', 'stage-0'],
plugins: ['transform-decorators-legacy', 'transform-class-properties', ["resolver", { "resolveDirs": [resolve(join(__dirname, 'js'))] }]]
}
}
},
{
test: /\.css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" }
]
},
{
test: /\.scss$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
//resolve-url-loader may be chained before sass-loader if necessary
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.(graphql|gql)$/,
exclude: /node_modules/,
loader: 'graphql-tag/loader',
}
// { test: /\.png$/, loader: "url-loader?limit=100000" },
// { test: /\.jpg$/, loader: "file-loader" },
// { test: /\.(woff2?|svg)$/, loader: 'url?limit=10000' },
// { test: /\.(ttf|eot)$/, loader: 'file' },
// { test: /\.json$/, loader: "json-loader" }
]
}
};
module.exports = config;
|
mgwidmann/slack_coder
|
client/web/webpack.config.js
|
JavaScript
|
mit
| 3,128
|
<?php
namespace App\Model\Repository;
use App\Model\Entity\Solution;
use Doctrine\ORM\EntityManagerInterface;
/**
* @extends BaseRepository<Solution>
*/
class Solutions extends BaseRepository
{
public function __construct(EntityManagerInterface $em)
{
parent::__construct($em, Solution::class);
}
}
|
ReCodEx/api
|
app/model/repository/Solutions.php
|
PHP
|
mit
| 324
|
package gloomyfolken.hooklib.disk;
import gloomyfolken.hooklib.asm.HookClassTransformer;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DiskHookLib {
public static void main(String[] args) throws IOException {
new DiskHookLib().process();
}
File untransformedDir = new File("untransformed");
File transformedDir = new File("transformed");
File hooksDir = new File("hooks");
void process() throws IOException {
HookClassTransformer transformer = new HookClassTransformer();
for (File file : getFiles(".class", hooksDir)) {
transformer.registerHookContainer(FileUtils.readFileToByteArray(file));
// теперь file надо скопировать в transformedDir, сохранив путь
}
for (File file : getFiles(".class", untransformedDir)) {
byte[] bytes = IOUtils.toByteArray(new FileInputStream(file));
String className = ""; //нужно из пути получить название класса через точки вроде ru.lol.DatClass
byte[] newBytes = transformer.transform(className, bytes);
// надо закинуть файл, состоящий из newBytes в transformedDir, сохранив путь
}
}
private static List<File> getFiles(String postfix, File dir) throws IOException {
ArrayList<File> files = new ArrayList<File>();
File[] filesArray = dir.listFiles();
if (filesArray != null) {
for (File file : dir.listFiles()) {
if (file.isDirectory()) {
files.addAll(getFiles(postfix, file));
} else if (file.getName().toLowerCase().endsWith(postfix)) {
files.add(file);
}
}
}
return files;
}
}
|
GloomyFolken/HookLib
|
src/gloomyfolken/hooklib/disk/DiskHookLib.java
|
Java
|
mit
| 2,028
|
var classNames = require('classnames');
var React = require('react/addons');
var Tappable = require('react-tappable');
var Transition = React.addons.CSSTransitionGroup;
var defaultControllerState = {
direction: 0,
fade: false,
leftArrow: false,
leftButtonDisabled: false,
leftIcon: '',
leftLabel: '',
leftAction: null,
rightArrow: false,
rightButtonDisabled: false,
rightIcon: '',
rightLabel: '',
rightAction: null,
title: ''
};
function newState (from) {
var ns = Object.assign({}, defaultControllerState);
if (from) Object.assign(ns, from);
delete ns.name; // may leak from props
return ns;
}
var NavigationBar = React.createClass({
contextTypes: {
app: React.PropTypes.object
},
propTypes: {
name: React.PropTypes.string
},
getInitialState () {
return newState(this.props);
},
componentDidMount () {
if (this.props.name) {
this.context.app.navigationBars[this.props.name] = this;
}
},
componentWillUnmount () {
if (this.props.name) {
delete this.context.app.navigationBars[this.props.name];
}
},
componentWillReceiveProps (nextProps) {
this.setState(newState(nextProps));
if (nextProps.name !== this.props.name) {
if (nextProps.name) {
this.context.app.navigationBars[nextProps.name] = this;
}
if (this.props.name) {
delete this.context.app.navigationBars[this.props.name];
}
}
},
update (state) {
state = newState(state);
// console.info('Updating NavigationBar ' + this.props.name, state);
this.setState(newState(state));
},
updateWithTransition (state, transition) {
state = newState(state);
if (transition === ('show-from-right' || 'reveal-from-left')) {
state.direction = 1;
} else if (transition === ('reveal-from-right' || 'show-from-left')) {
state.direction = -1;
} else if (transition === 'fade') {
state.fade = true;
}
// console.info('Updating NavigationBar ' + this.props.name + ' with transition ' + transition, state);
this.setState(state);
},
renderLeftButton () {
var className = classNames('NavigationBarLeftButton', {
'has-icon': this.state.leftArrow || this.state.leftIcon
});
return (
<Tappable onTap={this.state.leftAction} className={className} disabled={this.state.leftButtonDisabled} component="button">
{this.renderLeftArrow()}
{this.renderLeftIcon()}
{this.renderLeftLabel()}
</Tappable>
);
},
renderLeftArrow () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade || this.state.direction) {
transitionName = 'NavigationBarTransition-Fade';
}
var arrow = this.state.leftArrow ? <span className="NavigationBarLeftArrow" /> : null;
return (
<Transition transitionName={transitionName}>
{arrow}
</Transition>
);
},
renderLeftIcon () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade || this.state.direction) {
transitionName = 'NavigationBarTransition-Fade';
}
var className = classNames('NavigationBarLeftIcon', this.state.leftIcon);
var icon = this.state.leftIcon ? <span className={className} /> : null;
return (
<Transition transitionName={transitionName}>
{icon}
</Transition>
);
},
renderLeftLabel () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade) {
transitionName = 'NavigationBarTransition-Fade';
} else if (this.state.direction > 0) {
transitionName = 'NavigationBarTransition-Forwards';
} else if (this.state.direction < 0) {
transitionName = 'NavigationBarTransition-Backwards';
}
return (
<Transition transitionName={transitionName}>
<span key={Date.now()} className="NavigationBarLeftLabel">{this.state.leftLabel}</span>
</Transition>
);
},
renderTitle () {
var title = this.state.title ? <span key={Date.now()} className="NavigationBarTitle">{this.state.title}</span> : null;
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade) {
transitionName = 'NavigationBarTransition-Fade';
} else if (this.state.direction > 0) {
transitionName = 'NavigationBarTransition-Forwards';
} else if (this.state.direction < 0) {
transitionName = 'NavigationBarTransition-Backwards';
}
return (
<Transition transitionName={transitionName}>
<Tappable onTap={this.state.titleAction}>
{title}
</Tappable>
</Transition>
);
},
renderRightButton () {
var transitionName = 'NavigationBarTransition-Instant';
if (this.state.fade || this.state.direction) {
transitionName = 'NavigationBarTransition-Fade';
}
var button = (this.state.rightIcon || this.state.rightLabel) ? (
<Tappable key={Date.now()} onTap={this.state.rightAction} className="NavigationBarRightButton" disabled={this.state.rightButtonDisabled} component="button">
{this.renderRightLabel()}
{this.renderRightIcon()}
</Tappable>
) : null;
return (
<Transition transitionName={transitionName}>
{button}
</Transition>
);
},
renderRightIcon () {
if (!this.state.rightIcon) return null;
var className = classNames('NavigationBarRightIcon', this.state.rightIcon);
return <span className={className} />;
},
renderRightLabel () {
return this.state.rightLabel ? <span key={Date.now()} className="NavigationBarRightLabel">{this.state.rightLabel}</span> : null;
},
render () {
var className = classNames('NavigationBar', {
'has-left-arrow': this.state.leftArrow,
'has-left-icon': this.state.leftIcon,
'has-left-label': this.state.leftLabel,
'has-right-icon': this.state.rightIcon,
'has-right-label': this.state.rightLabel
});
return (
<div className={className}>
{this.renderLeftButton()}
{this.renderTitle()}
{this.renderRightButton()}
</div>
);
}
});
/*
function createController () {
var state = newState();
var listeners = [];
return {
update (ns) {
state = newState(ns);
listeners.forEach(fn => fn());
},
getState () {
return state;
},
addListener (fn) {
listeners.push(fn);
},
removeListener (fn) {
listeners = listeners.filter(i => fn !== i);
}
};
}
*/
export default NavigationBar;
|
npirotte/catchapp
|
src/js/touchstone/NavigationBar.js
|
JavaScript
|
mit
| 6,090
|
from .lattice import default_optics_mode
from .lattice import energy
from .accelerator import default_vchamber_on
from .accelerator import default_radiation_on
from .accelerator import accelerator_data
from .accelerator import create_accelerator
from .families import get_family_data
from .families import family_mapping
from .families import get_section_name_mapping
# -- default accelerator values for TS_V03 --
lattice_version = accelerator_data['lattice_version']
|
lnls-fac/sirius
|
pymodels/TS_V03_03/__init__.py
|
Python
|
mit
| 474
|
<?php
declare(strict_types = 1);
namespace BrowscapPHP\Parser\Helper;
use BrowscapPHP\Cache\BrowscapCacheInterface;
use BrowscapPHP\Helper\QuoterInterface;
use Psr\Log\LoggerInterface;
/**
* interface for the parser dataHelper
*/
interface GetDataInterface
{
/**
* class contsructor
*
* @param \BrowscapPHP\Cache\BrowscapCacheInterface $cache
* @param \Psr\Log\LoggerInterface $logger
* @param \BrowscapPHP\Helper\QuoterInterface $quoter
*/
public function __construct(BrowscapCacheInterface $cache, LoggerInterface $logger, QuoterInterface $quoter);
/**
* Gets the settings for a given pattern (method calls itself to
* get the data from the parent patterns)
*
* @param string $pattern
* @param array $settings
*
* @throws \UnexpectedValueException
*
* @return array
*/
public function getSettings(string $pattern, array $settings = []) : array;
}
|
mimmi20/browscap-php
|
src/Parser/Helper/GetDataInterface.php
|
PHP
|
mit
| 977
|
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more informations
# Copyright (C) Santiago Hernandez Ramos <shramos@protonmail.com>
# This program is published under GPLv2 license
from scapy.packet import Packet, bind_layers
from scapy.fields import FieldLenField, BitEnumField, StrLenField, \
ShortField, ConditionalField, ByteEnumField, ByteField, StrNullField
from scapy.layers.inet import TCP
from scapy.error import Scapy_Exception
# CUSTOM FIELDS
# source: http://stackoverflow.com/a/43717630
class VariableFieldLenField(FieldLenField):
def addfield(self, pkt, s, val):
val = self.i2m(pkt, val)
data = []
while val:
if val > 127:
data.append(val & 127)
val /= 127
else:
data.append(val)
lastoffset = len(data) - 1
data = "".join(chr(val | (0 if i == lastoffset else 128))
for i, val in enumerate(data))
return s + data
if len(data) > 3:
raise Scapy_Exception("%s: malformed length field" %
self.__class__.__name__)
def getfield(self, pkt, s):
value = 0
for offset, curbyte in enumerate(s):
curbyte = ord(curbyte)
value += (curbyte & 127) * (128 ** offset)
if curbyte & 128 == 0:
return s[offset + 1:], value
if offset > 2:
raise Scapy_Exception("%s: malformed length field" %
self.__class__.__name__)
# LAYERS
CONTROL_PACKET_TYPE = {1: 'CONNECT',
2: 'CONNACK',
3: 'PUBLISH',
4: 'PUBACK',
5: 'PUBREC',
6: 'PUBREL',
7: 'PUBCOMP',
8: 'SUBSCRIBE',
9: 'SUBACK',
10: 'UNSUBSCRIBE',
11: 'UNSUBACK',
12: 'PINGREQ',
13: 'PINGRESP',
14: 'DISCONNECT'}
QOS_LEVEL = {0: 'At most once delivery',
1: 'At least once delivery',
2: 'Exactly once delivery'}
# source: http://stackoverflow.com/a/43722441
class MQTT(Packet):
name = "MQTT fixed header"
fields_desc = [
BitEnumField("type", 1, 4, CONTROL_PACKET_TYPE),
BitEnumField("DUP", 0, 1, {0: 'Disabled',
1: 'Enabled'}),
BitEnumField("QOS", 0, 2, QOS_LEVEL),
BitEnumField("RETAIN", 0, 1, {0: 'Disabled',
1: 'Enabled'}),
# Since the size of the len field depends on the next layer, we need
# to "cheat" with the length_of parameter and use adjust parameter to
# calculate the value.
VariableFieldLenField("len", None, length_of="len",
adjust=lambda pkt, x: len(pkt.payload),),
]
class MQTTConnect(Packet):
name = "MQTT connect"
fields_desc = [
FieldLenField("length", None, length_of="protoname"),
StrLenField("protoname", "",
length_from=lambda pkt: pkt.length),
ByteField("protolevel", 0),
BitEnumField("usernameflag", 0, 1, {0: 'Disabled',
1: 'Enabled'}),
BitEnumField("passwordflag", 0, 1, {0: 'Disabled',
1: 'Enabled'}),
BitEnumField("willretainflag", 0, 1, {0: 'Disabled',
1: 'Enabled'}),
BitEnumField("willQOSflag", 0, 2, QOS_LEVEL),
BitEnumField("willflag", 0, 1, {0: 'Disabled',
1: 'Enabled'}),
BitEnumField("cleansess", 0, 1, {0: 'Disabled',
1: 'Enabled'}),
BitEnumField("reserved", 0, 1, {0: 'Disabled',
1: 'Enabled'}),
ShortField("klive", 0),
FieldLenField("clientIdlen", None, length_of="clientId"),
StrLenField("clientId", "",
length_from=lambda pkt: pkt.clientIdlen),
# Payload with optional fields depending on the flags
ConditionalField(FieldLenField("wtoplen", None, length_of="willtopic"),
lambda pkt: pkt.willflag == 1),
ConditionalField(StrLenField("willtopic", "",
length_from=lambda pkt: pkt.wtoplen),
lambda pkt: pkt.willflag == 1),
ConditionalField(FieldLenField("wmsglen", None, length_of="willmsg"),
lambda pkt: pkt.willflag == 1),
ConditionalField(StrLenField("willmsg", "",
length_from=lambda pkt: pkt.wmsglen),
lambda pkt: pkt.willflag == 1),
ConditionalField(FieldLenField("userlen", None, length_of="username"),
lambda pkt: pkt.usernameflag == 1),
ConditionalField(StrLenField("username", "",
length_from=lambda pkt: pkt.userlen),
lambda pkt: pkt.usernameflag == 1),
ConditionalField(FieldLenField("passlen", None, length_of="password"),
lambda pkt: pkt.passwordflag == 1),
ConditionalField(StrLenField("password", "",
length_from=lambda pkt: pkt.passlen),
lambda pkt: pkt.passwordflag == 1),
]
RETURN_CODE = {0: 'Connection Accepted',
1: 'Unacceptable protocol version',
2: 'Identifier rejected',
3: 'Server unavailable',
4: 'Bad username/password',
5: 'Not authorized'}
class MQTTConnack(Packet):
name = "MQTT connack"
fields_desc = [
ByteField("sessPresentFlag", 0),
ByteEnumField("retcode", 0, RETURN_CODE),
# this package has not payload
]
class MQTTPublish(Packet):
name = "MQTT publish"
fields_desc = [
FieldLenField("length", None, length_of="topic"),
StrLenField("topic", "",
length_from=lambda pkt: pkt.length),
ConditionalField(ShortField("msgid", None),
lambda pkt: (pkt.underlayer.QOS == 1
or pkt.underlayer.QOS == 2)),
StrLenField("value", "",
length_from=lambda pkt: (pkt.underlayer.len -
pkt.length - 2)),
]
class MQTTPuback(Packet):
name = "MQTT puback"
fields_desc = [
ShortField("msgid", None),
]
class MQTTPubrec(Packet):
name = "MQTT pubrec"
fields_desc = [
ShortField("msgid", None),
]
class MQTTPubrel(Packet):
name = "MQTT pubrel"
fields_desc = [
ShortField("msgid", None),
]
class MQTTPubcomp(Packet):
name = "MQTT pubcomp"
fields_desc = [
ShortField("msgid", None),
]
class MQTTSubscribe(Packet):
name = "MQTT subscribe"
fields_desc = [
ShortField("msgid", None),
FieldLenField("length", None, length_of="topic"),
StrLenField("topic", "",
length_from=lambda pkt: pkt.length),
ByteEnumField("QOS", 0, QOS_LEVEL),
]
ALLOWED_RETURN_CODE = {0: 'Success',
1: 'Success',
2: 'Success',
128: 'Failure'}
class MQTTSuback(Packet):
name = "MQTT suback"
fields_desc = [
ShortField("msgid", None),
ByteEnumField("retcode", None, ALLOWED_RETURN_CODE)
]
class MQTTUnsubscribe(Packet):
name = "MQTT unsubscribe"
fields_desc = [
ShortField("msgid", None),
StrNullField("payload", "")
]
class MQTTUnsuback(Packet):
name = "MQTT unsuback"
fields_desc = [
ShortField("msgid", None)
]
# LAYERS BINDINGS
bind_layers(TCP, MQTT, sport=1883)
bind_layers(TCP, MQTT, dport=1883)
bind_layers(MQTT, MQTTConnect, type=1)
bind_layers(MQTT, MQTTConnack, type=2)
bind_layers(MQTT, MQTTPublish, type=3)
bind_layers(MQTT, MQTTPuback, type=4)
bind_layers(MQTT, MQTTPubrec, type=5)
bind_layers(MQTT, MQTTPubrel, type=6)
bind_layers(MQTT, MQTTPubcomp, type=7)
bind_layers(MQTT, MQTTSubscribe, type=8)
bind_layers(MQTT, MQTTSuback, type=9)
bind_layers(MQTT, MQTTUnsubscribe, type=10)
bind_layers(MQTT, MQTTUnsuback, type=11)
bind_layers(MQTTConnect, MQTT)
bind_layers(MQTTConnack, MQTT)
bind_layers(MQTTPublish, MQTT)
bind_layers(MQTTPuback, MQTT)
bind_layers(MQTTPubrec, MQTT)
bind_layers(MQTTPubrel, MQTT)
bind_layers(MQTTPubcomp, MQTT)
bind_layers(MQTTSubscribe, MQTT)
bind_layers(MQTTSuback, MQTT)
bind_layers(MQTTUnsubscribe, MQTT)
bind_layers(MQTTUnsuback, MQTT)
|
CodeNameGhost/shiva
|
thirdparty/scapy/contrib/mqtt.py
|
Python
|
mit
| 8,943
|
/*
MIT License
Copyright (c) 2017 Hamdi Kavak
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.hamdikavak.humanmobility.modeling.spatial;
/**
* A class to handle distance that requires units.
* @author Hamdi Kavak
* @version 0.3.0
*/
public class DistanceWithUnit {
private SpatialDistanceUnit unit;
private double value;
public SpatialDistanceUnit getUnit() {
return unit;
}
public void setUnit(SpatialDistanceUnit unit) {
this.unit = unit;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
public DistanceWithUnit(){
}
public DistanceWithUnit(double value, SpatialDistanceUnit unit){
this.value = value;
this.unit = unit;
}
/**
* Compares this distance with the one given as a parameter.
*
* @param distanceToCompare distance object to compare
* @return true if this distance is than the one given as a parameter
*/
public boolean isShortherThan(DistanceWithUnit distanceToCompare){
DistanceWithUnit currentDistance = this.toDifferentUnit(SpatialDistanceUnit.Meter);
DistanceWithUnit compareDistance = distanceToCompare.toDifferentUnit(SpatialDistanceUnit.Meter);
return currentDistance.getValue() < compareDistance.getValue();
}
/**
* Converts current distance object to a new one based in given unit.
* @param unit new unit
* @return a new {@code DistanceWithUnit} object in given unit.
*/
public DistanceWithUnit toDifferentUnit(SpatialDistanceUnit unit){
double ratio = getUnitConversionRatios( this.getUnit(), unit);
return new DistanceWithUnit(this.value * ratio, unit);
}
private static double getUnitConversionRatios(SpatialDistanceUnit fromUnit, SpatialDistanceUnit toUnit) {
if (fromUnit == SpatialDistanceUnit.Meter){
if (toUnit == SpatialDistanceUnit.Meter){
return 1d;
}
else if (toUnit == SpatialDistanceUnit.Foot){
return 3.28084;
}
else if (toUnit == SpatialDistanceUnit.Yard){
return 1.09361;
}
else if (toUnit == SpatialDistanceUnit.Kilometer){
return 0.001;
}
else if (toUnit == SpatialDistanceUnit.Mile){
return 0.000621371;
}
else if (toUnit == SpatialDistanceUnit.NauticalMile){
return 0.000539957;
}
}
else if (fromUnit == SpatialDistanceUnit.Foot){
if (toUnit == SpatialDistanceUnit.Meter){
return 0.3048;
}
else if (toUnit == SpatialDistanceUnit.Foot){
return 1d;
}
else if (toUnit == SpatialDistanceUnit.Yard){
return 0.333333;
}
else if (toUnit == SpatialDistanceUnit.Kilometer){
return 0.0003048;
}
else if (toUnit == SpatialDistanceUnit.Mile){
return 0.000189394;
}
else if (toUnit == SpatialDistanceUnit.NauticalMile){
return 0.000164579;
}
}
else if (fromUnit == SpatialDistanceUnit.Yard){
if (toUnit == SpatialDistanceUnit.Meter){
return 0.9144;
}
else if (toUnit == SpatialDistanceUnit.Foot){
return 3d;
}
else if (toUnit == SpatialDistanceUnit.Yard){
return 1d;
}
else if (toUnit == SpatialDistanceUnit.Kilometer){
return 0.0009144;
}
else if (toUnit == SpatialDistanceUnit.Mile){
return 0.000568182;
}
else if (toUnit == SpatialDistanceUnit.NauticalMile){
return 0.000493737;
}
}
else if (fromUnit == SpatialDistanceUnit.Kilometer){
if (toUnit == SpatialDistanceUnit.Meter){
return 1000d;
}
else if (toUnit == SpatialDistanceUnit.Foot){
return 3280.84;
}
else if (toUnit == SpatialDistanceUnit.Yard){
return 1093.61;
}
else if (toUnit == SpatialDistanceUnit.Kilometer){
return 1d;
}
else if (toUnit == SpatialDistanceUnit.Mile){
return 0.621371;
}
else if (toUnit == SpatialDistanceUnit.NauticalMile){
return 0.539957;
}
}
else if (fromUnit == SpatialDistanceUnit.Mile){
if (toUnit == SpatialDistanceUnit.Meter){
return 1609.34;
}
else if (toUnit == SpatialDistanceUnit.Foot){
return 5280;
}
else if (toUnit == SpatialDistanceUnit.Yard){
return 1760;
}
else if (toUnit == SpatialDistanceUnit.Kilometer){
return 1.60934;
}
else if (toUnit == SpatialDistanceUnit.Mile){
return 1d;
}
else if (toUnit == SpatialDistanceUnit.NauticalMile){
return 0.868976;
}
}
else if (fromUnit == SpatialDistanceUnit.NauticalMile){
if (toUnit == SpatialDistanceUnit.Meter){
return 1852d;
}
else if (toUnit == SpatialDistanceUnit.Foot){
return 6076.12;
}
else if (toUnit == SpatialDistanceUnit.Yard){
return 2025.37;
}
else if (toUnit == SpatialDistanceUnit.Kilometer){
return 1.852;
}
else if (toUnit == SpatialDistanceUnit.Mile){
return 1.15078;
}
else if (toUnit == SpatialDistanceUnit.NauticalMile){
return 1d;
}
}
return 0d;
}
}
|
hamdikavak/human-mobility-modeling-utilities
|
src/main/java/com/hamdikavak/humanmobility/modeling/spatial/DistanceWithUnit.java
|
Java
|
mit
| 5,812
|
dotfiles
========
My configuration files(.zshrc .vimrc ... etc)
|
CrossClover/dotfiles
|
README.md
|
Markdown
|
mit
| 69
|
/* This is a default that will override the browser pages, and then your page will style from there */
/*
Theme Name:
Theme URI:
Description:
Version: 1.0
Author:
Author URI:
*/
/* reset styles */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var, b, u, i, center,
dl, dt, dd, ol, ul, li, fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%;
vertical-align: baseline; background: transparent;
}
body { line-height: 1; }
ol, ul { list-style: none; }
blockquote, q { quotes: none; }
blockquote:before, blockquote:after, q:before, q:after { content: ''; }
:focus { outline: 0; }
ins { text-decoration: none; }
del { text-decoration: line-through; }
table { border-collapse: collapse; border-spacing: 0; }
body {
font-size: 62.5%;
text-align: left;
color: #000000;
}
/* container - place inside each section or around the entire page depending on your layout */
.container {
width: 960px;
margin: 0 auto;
text-align: left;
position: relative;
}
/* for clearing any floats <br class="clearfloat" /> */
.clearfloat {
clear:both;
height:0;
font-size: 1px;
line-height: 0px;
}
|
ninamutty/ninamutty.github.io
|
styles/reset.css
|
CSS
|
mit
| 1,374
|
/*
* This file is part of EasyExchange.
*
* (c) 2014 - Machiel Molenaar <machiel@machiel.me>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
package com.mtech.easyexchange.mvc.user;
import com.mtech.easyexchange.annotation.ActiveUser;
import com.mtech.easyexchange.model.User;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpSession;
@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String index(ModelMap map) {
return "user/login";
}
@RequestMapping(value = "/login/failed", method = RequestMethod.GET)
public String loginFailed(ModelMap model, HttpSession session) {
model.addAttribute("error", true);
model.addAttribute("session", session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION"));
return "user/login";
}
@RequestMapping(value = "/welcome", method = RequestMethod.GET)
public String welcome(@ActiveUser User user, ModelMap map) {
map.addAttribute("user", user);
return "user/welcome";
}
}
|
Machiel/EasyExchange
|
Web/src/main/java/com/mtech/easyexchange/mvc/user/LoginController.java
|
Java
|
mit
| 1,418
|
# frozen_string_literal: true
module PGExaminer
class Result
class Language < Item
def diffable_attrs
{
"name" => "name"
}
end
end
end
end
|
chanks/pg_examiner
|
lib/pg_examiner/result/language.rb
|
Ruby
|
mit
| 190
|
#!/bin/bash
SERVER_NAME=pressure_test_server
OPERATOR_LIST=(
)
|
jiabinruan/gowithcool
|
example/pressure_test_server/build/comm.sh
|
Shell
|
mit
| 65
|
define(['../../game', 'collectableItem', 'states/levels/LevelState'], function (game, CollectableItem, Parent) {
var map,
levelThreeFirstLayerBackground,
levelThreeSecondLayerPlatforms,
shampoosGroup,
shampoosCoordinates;
function Level3State() {
};
Level3State.prototype = new Parent();
Level3State.prototype.constructor = Level3State;
Level3State.prototype.preload = function () {
this.load.tilemap('LevelThreeMap', 'levels/LevelThreeMap.json', null, Phaser.Tilemap.TILED_JSON);
this.load.image('background', 'images/L3-CosmeticShop/wallpapers/golden-sands-beach-13840-1920x1200.jpg');
this.load.image('platforms', 'images/L3-CosmeticShop/bamboo-platform(32x32).ss.png');
this.load.image('shampoo', 'images/L3-CosmeticShop/shampoo.png');
};
Level3State.prototype.update = function () {
Parent.prototype.update.call(this, levelThreeSecondLayerPlatforms, shampoosGroup);
if (this.player.points === 410) {
this.player.level = 4;
game.state.start('level4', true, false, this.player, this.engine);
}
};
Level3State.prototype.createMap = function () {
// Load level one map
map = game.add.tilemap('LevelThreeMap');
map.addTilesetImage('background', 'background');
map.addTilesetImage('platforms', 'platforms');
levelThreeFirstLayerBackground = map.createLayer('LevelThree - background');
levelThreeFirstLayerBackground.resizeWorld();
levelThreeFirstLayerBackground.wrap = true;
levelThreeSecondLayerPlatforms = map.createLayer('LevelThree - platforms');
levelThreeSecondLayerPlatforms.resizeWorld();
levelThreeSecondLayerPlatforms.wrap = true;
// Set collision between player and platforms
map.setCollisionByExclusion([0], true, levelThreeSecondLayerPlatforms);
showLevelPrehistory();
};
Level3State.prototype.initializePlayer = function () {
//Place player graphics at the map
this.player.placeAtMap(50, 120);
Parent.prototype.initializePlayer.call(this);
};
Level3State.prototype.initializeCollectableItems = function () {
//Create shampoos
shampoosGroup = this.add.group();
shampoosGroup.enableBody = true;
shampoosCoordinates = [
{x: 50, y: 420},
{x: 185, y: 65},
{x: 215, y: 65},
{x: 195, y: 350},
{x: 315, y: 320},
{x: 350, y: 450},
{x: 510, y: 160},
{x: 415, y: 65},
{x: 595, y: 320},
{x: 700, y: 64},
{x: 670, y: 450},
{x: 990, y: 350},
{x: 1020, y: 350},
{x: 900, y: 65},
{x: 940, y: 65},
{x: 980, y: 65},
{x: 1130, y: 255},
{x: 1275, y: 195},
{x: 1400, y: 290},
{x: 1370, y: 290}
];
for (var i = 0; i < shampoosCoordinates.length; i += 1) {
var currentShampoo = shampoosCoordinates[i];
var x = currentShampoo.x;
var y = currentShampoo.y;
new CollectableItem(x, y, shampoosGroup, 'shampoo');
}
};
function showLevelPrehistory() {
var body = document.getElementsByTagName('body')[0],
div = document.createElement('div'),
span,
spanText,
divPrehistory,
spanInDivPrehistory,
spanInDivPrehistoryText,
continueGameButton,
continueGameButtonText,
playButton;
div.id = 'prehistory-main-background';
span = document.createElement('span');
span.id = 'current-level';
spanText = document.createTextNode('Level 3');
span.textContent = spanText.textContent;
divPrehistory = document.createElement('div');
divPrehistory.id = 'divPrehistory';
divPrehistory.style.backgroundImage = "url('images/Prehistory/paper-roll.png')";
spanInDivPrehistory = document.createElement('span');
spanInDivPrehistory.id = 'prehistory-span-text';
spanInDivPrehistoryText = document.createTextNode('Enough with these silly games – StarCraft, MarCraft...! Let’s do ' +
'something for the girls! We need to create a cosmetics shop! Wait a minute! A cosmetics shop! ' +
'What the hell!?!?!Yeah, that right! Everyone can learn S# only a few are those who can master the OOP that goes with it. ' +
'Saddy Kopper is one of them. But in that crazy girl dimension (somewhere in Waka waka eh eh) the young Kopper must ' +
'create a cosmestics shop. In order to complete this task, he needs to collect all shampoos. If the Amazons are merciful ' +
'(they will be - Saddy is very charming), they will reveal the secret of mastering OOP.');
spanInDivPrehistory.textContent = spanInDivPrehistoryText.textContent;
divPrehistory.appendChild(spanInDivPrehistory);
continueGameButton = document.createElement('button');
continueGameButton.className = 'hvr-border-fade';
continueGameButton.id = 'continue';
continueGameButtonText = document.createTextNode('Continue');
continueGameButton.textContent = continueGameButtonText.textContent;
div.appendChild(span);
div.appendChild(divPrehistory);
div.appendChild(continueGameButton);
div.style.backgroundImage = "url('images/Game Over - messages background/L3-beach.jpg')";
body.appendChild(div);
playButton = document.getElementById('continue');
playButton.onclick = function () {
div.removeChild(span);
div.removeChild(divPrehistory);
div.removeChild(continueGameButton);
body.removeChild(div);
};
}
return Level3State;
});
|
DimitarSD/Teamwork-Porto-Flip
|
Game/scripts/states/levels/Level3State.js
|
JavaScript
|
mit
| 5,947
|
# Visual Studio Team Services queries
A webpage where you can run pre-defined vsts querys that are too complex to make in the [vsts query editor](https://www.visualstudio.com/en-us/docs/work/track/using-queries).
## Queries
So far there is only one query in the project.
### Pullrequests and related work items
Use this query to get a list of completed pull requests and their associated work-items.
You can use this query as a poor man’s release management tool:
Set your master branch to protected and set it to "block pull requests unless they have a linked work item".
[https://www.visualstudio.com/en-us/docs/git/branch-policies](https://www.visualstudio.com/en-us/docs/git/branch-policies)
Let your continuous integration system note the commit idwhen you make a release build or incorporate the commit id in the version number of the build.
Use this query to find the completed pull requests since the last time you made a release build and get a list of the associated work-items.
Then you can use the vsts query editor to create a release mail, change the state or add a tag on the associated work-items.
[https://www.visualstudio.com/en-us/docs/work/track/using-queries](https://www.visualstudio.com/en-us/docs/work/track/using-queries)
## About the code
The code is written in typescript and the project is based on the ts-vscode-boilerplate.
Please visit [blog.wolksoftware.com](http://blog.wolksoftware.com/setting-up-your-typescript-vs-code-development-environment) to learn more about this template.
|
niclas-awalt/vsts-queries
|
README.md
|
Markdown
|
mit
| 1,528
|
<div class="notifications">
<!-- _ASSIGN_ MSN -->
<div class="notifications-inner" ng-repeat="notification in notifications track by notification.id">
<comp-notification notification=notification></comp-notification>
</div>
</div>
|
Chillybyte/GlobalComments
|
web/app/components/comp-notifications/template.html
|
HTML
|
mit
| 246
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MEF.TheTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MEF.TheTests")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6aa4dd0f-54cb-4fa1-8670-d3e69cc07aa7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
chadmichel/MEF_UnitTest
|
MEF.TheTests/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,400
|
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_demo-app_session'
|
davidargylethacker/rails-demo-app
|
demo-app/config/initializers/session_store.rb
|
Ruby
|
mit
| 140
|
// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ( $, window, document, undefined ) {
"use strict";
// undefined is used here as the undefined global variable in ECMAScript 3 is
// mutable (ie. it can be changed by someone else). undefined isn"t really being
// passed in so we can ensure the value of it is truly undefined. In ES5, undefined
// can no longer be modified.
// window and document are passed through as local variable rather than global
// as this (slightly) quickens the resolution process and can be more efficiently
// minified (especially when both are regularly referenced in your plugin).
// Create the defaults once
var pluginName = "niceCharCounter",
defaults = {
limit: 100,
descending: true,
warningPercent: 70,
clearLimitColor: "#29b664",
warningColor: "#c0392b",
overColor: "#e74c3c",
counter: "#counter",
hardLimit: false,
text: "{{counter}}",
onType: function(){
//console.log("On Type");
},
clearLimitTrigger: function(){
//console.log("Clear Limit Trigger");
},
onClearLimit: function(){
//console.log("On Clear Limit");
},
warningTrigger: function(){
//console.log("Warning Trigger");
},
onWarning: function(){
//console.log("On Warning");
},
overTrigger: function(){
//console.log("Over Trigger");
},
onOver: function(){
//console.log("On Over");
}
};
// The actual plugin constructor
function Plugin (element, options) {
this.element = element;
// jQuery has an extend method which merges the contents of two or
// more objects, storing the result in the first object. The first object
// is generally empty as we don"t want to alter the default options for
// future instances of the plugin
this.settings = $.extend( {}, defaults, options );
this._defaults = defaults;
this._name = pluginName;
this.currentState = "";
var warningFactor = Math.round((this.settings.limit * this.settings.warningPercent) / 100);
this.warningFactor = this.settings.limit - warningFactor;
this.init();
var _this = this;
$(this.element).keyup(function(){
var $this= $(this);
var total = $this.val().length;
_this.doAction(total);
});
}
// Avoid Plugin.prototype conflicts
$.extend(Plugin.prototype, {
tey: function(){
console.log("tey");
},
init: function () {
if (this.settings.hardLimit) {
$(this.element).attr("maxlength", this.settings.limit);
}
var text = this.settings.text.replace("{{counter}}", "<span class=\"nice-remaining\"></span>");
text = text.replace("{{limit}}", "<span class=\"nice-limit\">" + this.settings.limit + "</span>");
/**
* Verifica se tem alguma coisa com o padrao [singular, plural] e marca os spans
* devidos
*/
var pattern = /\[\w+\,\s?\w+\]/g; // [singular, plural]
var result = text.match(pattern); // Pega todas as ocorrencias
console.log(result);
if (result) {
$.each(result, function(index, val) {
var words = val.replace(/\[/g, "").replace(/\]/g, "").split(",");
var singular = words[0];
var plural = words[1];
text = text.replace(val, "<span class=\"nice-inflector\" data-singular="+singular+" data-plural="+plural+"></span>");
});
}
if ($(this.settings.counter).length < 1) {
console.error("You have to set the counter");
return false;
}
$(this.settings.counter).html(text);
$(this.settings.counter).children("span.charsValue").css("color", this.settings.clearLimitColor);
this.doAction($(this.element).val().length);
},
doAction: function (total) {
var $span = $(this.settings.counter).children("span.nice-remaining");
var remaining = this.settings.limit - total;
var remainingPercent = Math.round((total * 100) / this.settings.limit);
remainingPercent = (remainingPercent < 100) ? remainingPercent : 100;
var ui = {tota: total, remaining: remaining, remainingPercent: remainingPercent};
if (this.settings.warningPercent > 0 && remaining <= this.warningFactor && remaining >= 0) {
$span.css("color", this.settings.warningColor); // quase
this.settings.onWarning(ui);
this.setStateAndTrigger("warning", ui);
} else if (remaining < 0) {
$span.css("color", this.settings.overColor); // estourou
this.settings.onOver(ui);
this.setStateAndTrigger("over", ui);
} else{
$span.css("color", this.settings.clearLimitColor); // acima do warning
this.settings.onClearLimit(ui);
this.setStateAndTrigger("clearLimit", ui);
}
var descending = this.settings.descending;
$("span.nice-inflector").each(function(){
var $this = $(this);
var factor = (descending) ? remaining : total;
var word = (factor === 1 || factor === 0) ? $this.data("singular") : $this.data("plural");
$this.text(word);
});
this.settings.onType(ui, this.currentState, this.settings);
if (this.settings.descending) {
$span.html(remaining);
} else {
$span.html(total);
}
},
setStateAndTrigger: function (state, ui){
if (state !== this.currentState) {
this.settings[state + "Trigger"](ui, this.setting);
}
this.currentState = state;
}
});
// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[ pluginName ] = function ( options ) {
return this.each(function() {
if ( !$.data( this, "plugin_" + pluginName ) ) {
$.data( this, "plugin_" + pluginName, new Plugin( this, options ) );
}
});
};
})( jQuery, window, document );
|
danielfpedro/nice-char-counter
|
src/nice-char-counter.js
|
JavaScript
|
mit
| 7,582
|
/*
Copyright (c) 2017 The swc Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
use anyhow::{Context, Error};
use napi::{CallContext, JsBuffer, Status};
use serde::de::DeserializeOwned;
use std::any::type_name;
pub trait MapErr<T>: Into<Result<T, anyhow::Error>> {
fn convert_err(self) -> napi::Result<T> {
self.into()
.map_err(|err| napi::Error::new(Status::GenericFailure, format!("{:?}", err)))
}
}
impl<T> MapErr<T> for Result<T, anyhow::Error> {}
pub trait CtxtExt {
fn get_buffer_as_string(&self, index: usize) -> napi::Result<String>;
/// Currently this uses JsBuffer
fn get_deserialized<T>(&self, index: usize) -> napi::Result<T>
where
T: DeserializeOwned;
}
impl CtxtExt for CallContext<'_> {
fn get_buffer_as_string(&self, index: usize) -> napi::Result<String> {
let buffer = self.get::<JsBuffer>(index)?.into_value()?;
Ok(String::from_utf8_lossy(buffer.as_ref()).to_string())
}
fn get_deserialized<T>(&self, index: usize) -> napi::Result<T>
where
T: DeserializeOwned,
{
let buffer = self.get::<JsBuffer>(index)?.into_value()?;
let v = serde_json::from_slice(&buffer)
.with_context(|| {
format!(
"Failed to deserialize argument at `{}` as {}\nJSON: {}",
index,
type_name::<T>(),
String::from_utf8_lossy(&buffer)
)
})
.convert_err()?;
Ok(v)
}
}
pub(crate) fn deserialize_json<T>(s: &str) -> Result<T, Error>
where
T: DeserializeOwned,
{
serde_json::from_str(s)
.with_context(|| format!("failed to deserialize as {}\nJSON: {}", type_name::<T>(), s))
}
|
azukaru/next.js
|
packages/next-swc/crates/napi/src/util.rs
|
Rust
|
mit
| 2,753
|
---
layout: layout
title: "Jared Wright"
---
<br>
<title>Jared Wright</title>
<section class="content">
<p>Hi, I'm <b>Jared</b>
<span style="font-style:italic"><br><br>
Developer, Student, and (aspiring) Entrepreneur
<br><br></span>
All of my open source projects are hosted on Github <a href='http://github.com/jawerty'>@jawerty</a>
</p>
<br><br>
<h2>* Articles</h2>
{% for post in site.posts %}
<a href="{{ post.url }}">{{ post.title }}</a><span> - {{ post.date | date: "%B %e, %Y" }}</span>
<br>
<br>
{% endfor %}
</section>
|
jawerty/mygithubpage
|
index.html
|
HTML
|
mit
| 615
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <ctype.h>
#define PATHLEN 256
#define CMDLEN 512
#define MAXARGS 500
#define ALIASALLOC 20
#define STDIN 0
#define STDOUT 1
#define MAXSOURCE 10
#ifndef isblank
#define isblank(ch) (((ch) == ' ') || ((ch) == '\t'))
#endif
#define isquote(ch) (((ch) == '"') || ((ch) == '\''))
#define isdecimal(ch) (((ch) >= '0') && ((ch) <= '9'))
#define isoctal(ch) (((ch) >= '0') && ((ch) <= '7'))
typedef int BOOL;
#define FALSE ((BOOL) 0)
#define TRUE ((BOOL) 1)
extern void do_alias(), do_cd(), do_exec(), do_exit(), do_prompt();
extern void do_source(), do_umask(), do_unalias(), do_help(), do_ln();
extern void do_cp(), do_mv(), do_rm(), do_chmod(), do_mkdir(), do_rmdir();
extern void do_mknod(), do_chown(), do_chgrp(), do_sync(), do_printenv();
extern void do_more(), do_cmp(), do_touch(), do_ls(), do_dd(), do_tar();
extern void do_mount(), do_umount(), do_setenv(), do_pwd(), do_echo();
extern void do_kill(), do_grep(), do_ed();
extern char *buildname();
extern char *modestring();
extern char *timestring();
extern BOOL isadir();
extern BOOL copyfile();
extern BOOL match();
extern BOOL makestring();
extern BOOL makeargs();
extern int expandwildcards();
extern int namesort();
extern char *getchunk();
extern void freechunks();
extern BOOL intflag;
/* END CODE */
struct group { short gr_gid; };
struct group *getgrnam(char *name) { return nullptr; }
struct passwd { short pw_uid; };
struct passwd *getpwnam(char *name) { return nullptr; }
int chown(char *name, short uid, int gid) { return 0; }
int chmod(char *name, int mode) { return 0; }
|
BclEx/GpuEx
|
src.fileutils/futils.h
|
C
|
mit
| 1,651
|
/**
* Copyright (c) 2014 Virtue Studios
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.virtue.engine.service;
import java.util.ArrayDeque;
import java.util.Queue;
import org.virtue.network.session.impl.OnDemandSession;
/**
*
* @author Im Frizzy <skype:kfriz1998>
* @since Sep 4, 2014
*/
public class OnDemandService implements Runnable {
/**
* The {@link ArrayDeque} of {@link Session}
*/
private final Queue<OnDemandSession> pendingSessions = new ArrayDeque<>();
/**
* Adds a {@link Session} to the pendingSessions array
* @param session
*/
public void addPendingSession(OnDemandSession session) {
synchronized (pendingSessions) {
pendingSessions.add(session);
pendingSessions.notifyAll();
}
}
@Override
public void run() {
for (;;) {
OnDemandSession session;
synchronized (pendingSessions) {
while ((session = pendingSessions.poll()) == null) {
try {
pendingSessions.wait();
} catch (InterruptedException e) {
/* ignore */
}
}
}
session.processFileQueue();
}
}
}
|
Sundays211/VirtueRS3
|
src/main/java/org/virtue/engine/service/OnDemandService.java
|
Java
|
mit
| 2,105
|
/*
* This file is part of SpongeAPI, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.api.data.manipulators.items;
import org.spongepowered.api.data.manipulators.IntData;
/**
* Represents an item that can be cloned or copied.
*
* <p>Some items can be cloned or copied with crafting.</p>
*
* <p>Some items may prevent further cloning after a specified generation.</p>
*/
public interface CloneableData extends IntData<CloneableData> {
/**
* Gets the generation of this cloneable item.
*
* <p>The original always starts as generation 0.</p>
*
* @return The generation of the cloneable item
*/
int getGeneration();
/**
* Sets the generation of this cloneable item.
*
* <p>The original always starts as generation 0.</p>
*
* @param generation The generation of this item
* @return This instance, for chaining
*/
CloneableData setGeneration(int generation);
/**
* Gets the generational limit to which the item would no longer
* be cloneable by normal means.
*
* @return The generational limit
*/
int getGenerationLimit();
}
|
frogocomics/SpongeAPI
|
src/main/java/org/spongepowered/api/data/manipulators/items/CloneableData.java
|
Java
|
mit
| 2,336
|
export * from './site.component';
|
tsuberi/kid-watch-app
|
src/app/Site/index.ts
|
TypeScript
|
mit
| 34
|
<?php
include_once "connect.php";
$link = db_connect();
// Delete user where email
$sql_settings_user_remove = "DELETE FROM users WHERE email = '".$_POST['email']."' ";
if ($link->query($sql_settings_user_remove) === TRUE) {
echo "<div class='row'> <div class='col-lg-12'> <div class='alert alert-success alert-dismissable'> <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button> <i class='fa fa-info-circle'></i> Pomyślnie usunięto użytkownika o adresie email : <strong>".$_POST['email']."</strong> Odśwież stronę.</div> </div> </div>";
} else {
echo "Error: " . $sql_settings_user_remove . "<br>" . $link->error;
}
|
Lukaszm328/Knoocker
|
web/ajax_php/settings_user_remove.php
|
PHP
|
mit
| 698
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.