identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/gateway7/CsvHelper/blob/master/src/CsvHelper/Configuration/IFieldPreprocessorSettings.cs
|
Github Open Source
|
Open Source
|
MS-PL, Apache-2.0
| 2,017
|
CsvHelper
|
gateway7
|
C#
|
Code
| 339
| 698
|
namespace CsvHelper.Configuration
{
using System.Text.RegularExpressions;
/// <summary>
/// Provides information on preprocessing to be performed on the CSV field after extraction.
/// </summary>
public interface IFieldPreprocessorSettings
{
/// <summary>
/// An optional prefix expected to appear in the field. Set <see cref="IsPrefixMandatory"/> to true, is the prefix is mandatory.
/// </summary>
string Prefix { get; set; }
/// <summary>
/// If true, the value of <see cref="Prefix"/> must be defined. Absence
/// of the latter in the field value will result in an exception.
/// Defaults to false.
/// </summary>
bool IsPrefixMandatory { get; set; }
/// <summary>
/// If true, trims the prefix value defined in <see cref="Prefix" />.
/// </summary>
bool TrimPrefix { get; set; }
/// <summary>
/// An optional suffix expected to appear in the field. Set <see cref="IsPrefixMandatory"/> to true, is the prefix is mandatory.
/// </summary>
string Suffix { get; set; }
/// <summary>
/// If true, the value of <see cref="Suffix"/> must be defined. Absence
/// of the latter in the field value will result in an exception.
/// Defaults to false.
/// </summary>
bool IsSuffixMandatory { get; set; }
/// <summary>
/// If true, trims the suffix value defined in <see cref="Suffix" />.
/// </summary>
bool TrimSuffix { get; set; }
/// <summary>
/// The amount of characters to trim from the beginning of the firld. Cannot be specified together with <see cref="TrimPrefix"/>.
/// </summary>
int TrimStart { get; set; }
/// <summary>
/// The amount of characters to trim from the end of the field. Cannot be specified together with <see cref="TrimSuffix"/>.
/// </summary>
int TrimEnd { get; set; }
/// <summary>
/// Return the [pattern] (second) argument in <see cref="Regex.Replace(string, string, string)"/>.
/// Requires <see cref="RegexReplacementPattern"/> and cannot be used in conjunction with other, non-regex settings.
/// </summary>
string RegexMatchPattern { get; }
/// <summary>
/// Returns the [replacement] (third) argument in <see cref="Regex.Replace(string, string, string)"/>
/// Requires <see cref="RegexMatchPattern"/> and cannot be used in conjunction with other, non-regex settings.
/// </summary>
string RegexReplacementPattern { get; }
}
}
| 48,540
|
https://github.com/hanjietao/ops-pro/blob/master/src/main/java/com/pepper/framework/shiro/web/filter/online/OnlineSessionFilter.java
|
Github Open Source
|
Open Source
|
MIT
| null |
ops-pro
|
hanjietao
|
Java
|
Code
| 313
| 1,583
|
package com.pepper.framework.shiro.web.filter.online;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.pepper.common.constant.ShiroConstants;
import com.pepper.common.utils.security.ShiroUtils;
import com.pepper.framework.shiro.session.OnlineSessionDAO;
import com.pepper.project.monitor.online.domain.OnlineSession;
import com.pepper.project.system.user.domain.User;
/**
* 自定义访问控制
*
* @author pepper
*/
public class OnlineSessionFilter extends AccessControlFilter
{
Logger logger = LoggerFactory.getLogger(OnlineSessionFilter.class);
/**
* 强制退出后重定向的地址
*/
@Value("${shiro.user.loginUrl}")
private String loginUrl;
@Value("${pepper.clientLoginType}")
private String clientLoginType;
@Autowired
private OnlineSessionDAO onlineSessionDAO;
/**
* 表示是否允许访问;mappedValue就是[urls]配置中拦截器参数部分,如果允许访问返回true,否则false;
*/
@Override
protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
throws Exception
{
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
logger.info("content-type= "+httpServletRequest.getHeader("Content-Type"));
logger.info("RequestURL= "+httpServletRequest.getRequestURL());
logger.info("QueryString= "+httpServletRequest.getQueryString());
logger.info("RequestURI= "+httpServletRequest.getRequestURI());
logger.info("RequestHeader[LOGIN_TYPE]= "+httpServletRequest.getHeader(ShiroConstants.LOGIN_TYPE));
InputStream is = request.getInputStream();
StringBuilder sb = new StringBuilder();
byte[] b = new byte[4096];
for (int n; (n = is.read(b)) != -1;) {
sb.append(new String(b, 0, n));
}
logger.info("RequestBody ",sb.toString());
//JSONObject jsonObject = JSONObject.parseObject(sb.toString());
Subject subject = getSubject(request, response);
if (subject == null || subject.getSession() == null)
{
return true;
}
Session session = onlineSessionDAO.readSession(subject.getSession().getId());
if (session != null && session instanceof OnlineSession)
{
OnlineSession onlineSession = (OnlineSession) session;
request.setAttribute(ShiroConstants.ONLINE_SESSION, onlineSession);
// 把user对象设置进去
boolean isGuest = onlineSession.getUserId() == null || onlineSession.getUserId() == 0L;
if (isGuest == true)
{
User user = ShiroUtils.getSysUser();
if (user != null)
{
onlineSession.setUserId(user.getUserId());
onlineSession.setLoginName(user.getLoginName());
onlineSession.setAvatar(user.getAvatar());
onlineSession.setDeptName(user.getDept().getDeptName());
onlineSession.markAttributeChanged();
}
}
if (onlineSession.getStatus() == OnlineSession.OnlineStatus.off_line)
{
return false;
}
String loginType = httpServletRequest.getHeader(ShiroConstants.LOGIN_TYPE);
if(clientLoginType.equals(loginType) && (ShiroUtils.getSysUser() == null
|| ShiroUtils.getSysUser().getClientUser() == null
|| ShiroUtils.getSysUser().getClientUser().getUserId() == null
|| ShiroUtils.getSysUser().getClientUser().getUserId() == 0L)){
logger.info("loginType={}, shiroUtils: sysUser={} , clientUser={}, clientUserId={},special condition"
,loginType
,ShiroUtils.getSysUser().toString(),ShiroUtils.getSysUser().getClientUser()
,ShiroUtils.getSysUser().getClientUser().getUserId());
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().write("{\"code\":\"101\",\"msg\":\"未登录或登录超时。请重新登录\"}");
return false;
}
}
return true;
}
/**
* 表示当访问拒绝时是否已经处理了;如果返回true表示需要继续处理;如果返回false表示该拦截器实例已经处理了,将直接返回即可。
*/
@Override
protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception
{
Subject subject = getSubject(request, response);
if (subject != null)
{
subject.logout();
}
saveRequestAndRedirectToLogin(request, response);
return false;
}
// 跳转到登录页
@Override
protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException
{
WebUtils.issueRedirect(request, response, loginUrl);
}
}
| 34,332
|
https://github.com/jonasbn/perl-critic-policy-regularexpressions-requiredefault/blob/master/t/implementation.t
|
Github Open Source
|
Open Source
|
Artistic-2.0
| null |
perl-critic-policy-regularexpressions-requiredefault
|
jonasbn
|
Perl
|
Code
| 18
| 107
|
use strict;
use warnings;
use Test::More tests => 4;
use_ok('Perl::Critic::Policy::RegularExpressions::RequireDefault');
ok(my $policy = Perl::Critic::Policy::RegularExpressions::RequireDefault->new());
isa_ok($policy, 'Perl::Critic::Policy::RegularExpressions::RequireDefault');
can_ok($policy, qw(violates));
| 22,851
|
https://github.com/yoyonel/pyWarpGrid/blob/master/src/warp_grid/warp_map.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
pyWarpGrid
|
yoyonel
|
Python
|
Code
| 525
| 2,026
|
"""
"""
from dataclasses import dataclass, field
import itertools
from OpenGL.GL.shaders import compileProgram, compileShader
from OpenGL.raw.GL.VERSION.GL_1_0 import glColor3f, glPointSize
from OpenGL.raw.GL.VERSION.GL_1_1 import GL_POINTS, GL_LINES
from OpenGL.raw.GL.VERSION.GL_2_0 import (
GL_VERTEX_SHADER, GL_FRAGMENT_SHADER,
glUseProgram
)
import pathlib
import pyglet
import pymunk
from pymunk import Vec2d, Space
from warp_grid.flag import Flag3D
@dataclass
class WarpMapPyMunk(object):
space: Space
h: int = 13
w: int = 11
size: int = 32
bs: list = field(default_factory=list)
static_bs: list = field(default_factory=list)
def __post_init__(self):
web_group = 1
for y in range(self.h):
for x in range(self.w):
b = pymunk.Body(1, 1)
b.position = Vec2d(x, y) * self.size
b.velocity_func = self.constant_velocity
s = pymunk.Circle(b, 15)
s.filter = pymunk.ShapeFilter(group=web_group)
s.ignore_draw = True
self.space.add(b, s)
self.bs.append(b)
stiffness = 5000. * 0.1
damping = 100 * 0.1
def add_joint(a, b):
rl = a.position.get_distance(b.position) * 0.9
j = pymunk.DampedSpring(a, b, (0, 0), (0, 0),
rl, stiffness, damping)
j.max_bias = 1000
self.space.add(j)
for y in range(1, self.h - 1):
for x in range(1, self.w - 1):
bs_xy = self.bs[x + y * self.w]
for yi in range(y - 1, y + 2):
for xi in range(x - 1, x + 2):
if (xi, yi) != (x, y) and ((x - xi) * (y - yi) == 0):
add_joint(bs_xy, self.bs[xi + yi * self.w])
print("len(self.space.constraints): {}".format(
len(self.space.constraints)))
# ATTACH POINTS
def _static_point(b):
static_body = pymunk.Body(body_type=pymunk.Body.STATIC)
static_body.position = b.position
self.static_bs.append(static_body)
j = pymunk.PivotJoint(static_body, b, static_body.position)
j.damping = 100
j.stiffness = 20000
self.space.add(j)
self.static_bs = []
# fisrt and last rows
for x in range(self.w):
_static_point(self.bs[x])
_static_point(self.bs[x + (self.h - 1) * self.w])
# first and last cols
for y in range(self.h):
_static_point(self.bs[y * self.w])
_static_point(self.bs[(self.w - 1) + y * self.w])
cooling_map_img = pyglet.image.load(
pathlib.Path('datas/cooling_map.png'))
# self.cooling_map_sprite = pyglet.sprite.Sprite(img=cooling_map_img)
self.cooling_map_tex = cooling_map_img.get_texture()
x = (self.w * 4) * 2.0
y = (self.h * 4) * 2.0
vlist_arr = [
0, 0, 1.0, 1.0, 1.0, 0, 0,
x, 0, 1.0, 1.0, 1.0, 1, 0,
0, y, 1.0, 1.0, 1.0, 0, 1,
x, y, 1.0, 1.0, 1.0, 1, 1,
]
self.vlist = pyglet.graphics.vertex_list(
4,
('v2f',
list(itertools.chain(*zip(vlist_arr[::7], vlist_arr[1::7])))),
('t2f',
list(itertools.chain(*zip(vlist_arr[5::7], vlist_arr[6::7]))))
)
# http://io7m.com/documents/fso-tta/
self.vertex_shader_source = """
#version 130
out vec2 vTexCoord;
void
main() {
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
vTexCoord = vec2(gl_MultiTexCoord0);
}
"""
self.fragment_shader_source = """
#version 130
uniform sampler2D tex0;
in vec2 vTexCoord;
out vec4 fragColor;
void main() {
fragColor = texture(tex0, vTexCoord) * 8;
}
"""
self.shader = compileProgram(
compileShader(self.vertex_shader_source, GL_VERTEX_SHADER),
compileShader(self.fragment_shader_source, GL_FRAGMENT_SHADER),
)
self.flag = Flag3D()
@staticmethod
def constant_velocity(body: pymunk.Body, _gravity, _damping, _dt):
body_velocity_normalized = body.velocity.normalized()
#
body.velocity = body_velocity_normalized * 75
def get_web_crossings(self):
return [
[b.position.x, b.position.y]
for b in self.bs
]
def draw_debug(self,
draw_flag=False,
draw_static_attach_points=False,
draw_web_crossings=True,
draw_web_constraints=False, ):
if draw_flag:
# self.vao._draw_frame()
self.flag.update(self.bs)
glUseProgram(self.shader)
self.flag.draw()
glUseProgram(0)
# static attach points
if draw_static_attach_points:
glColor3f(1, 0, 1)
glPointSize(6)
a = []
for b in self.static_bs:
a += [b.position.x, b.position.y]
pyglet.graphics.draw(len(a) // 2, GL_POINTS, ('v2f', a))
# web crossings / bodies
if draw_web_crossings:
glColor3f(.1, .8, .05)
a = []
for b in self.bs:
a += [b.position.x, b.position.y]
glPointSize(4)
pyglet.graphics.draw(len(a) // 2, GL_POINTS, ('v2f', a))
# web net / constraints
if draw_web_constraints:
a = []
for j in self.space.constraints:
a += [j.a.position.x, j.a.position.y, j.b.position.x,
j.b.position.y]
pyglet.graphics.draw(len(a) // 2, GL_LINES, ('v2f', a))
def relax(self, dt):
self.space.step(dt)
| 11,482
|
https://github.com/davidmallasen/AceptaElReto/blob/master/0250-DesgasteBombines/0250.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
AceptaElReto
|
davidmallasen
|
C++
|
Code
| 202
| 449
|
/**
* Problema 0250: El desgaste de los bombines
*
* Ada Byron 2015. Equipo Infinite loop:
* David Mallasén Quintana
* Ivan Prada Cazalla
*/
#include <cstdio>
#define gc getchar_unlocked
inline int readIntNeg();
int dias[1000000];
int main() {
int casos, suma, suma1, suma2, min, dia_min;
casos = readIntNeg();
while (casos > 0) {
suma1 = 0;
suma2 = 0;
min = 2000000000;
dia_min = casos + 1;
for (int i = 0; i < casos; i++)
dias[i] = readIntNeg();
for (int i = 0; i < casos; i++)
suma2 += dias[i];
for (int i = 0; i < casos; i++) {
suma = suma1 - suma2;
if (suma < 0) suma = -suma;
if (suma < min) {
min = suma;
dia_min = i;
}
suma1 += dias[i];
suma2 -= dias[i];
}
printf("%i\n", dia_min);
casos = readIntNeg();
}
return 0;
}
int readIntNeg() {
int num = 0, neg = 1;
char ch = gc();
while (ch < '0' && ch != '-') ch = gc();
if (ch == '-') {
neg = -1;
ch = gc();
}
while (ch >= '0') {
num = 10 * num + ch - 48;
ch = gc();
}
return num * neg;
}
| 38,548
|
https://github.com/Nullpo1nt/neu-csu540-raytracer/blob/master/src/main/java/raytracer/surfaces/Box.java
|
Github Open Source
|
Open Source
|
MIT
| null |
neu-csu540-raytracer
|
Nullpo1nt
|
Java
|
Code
| 227
| 596
|
package raytracer.surfaces;
import javax.vecmath.Vector3d;
import raytracer.Ray;
/**
* Used for bounding box, but since the bounding volume hierarchy isn't complete
* it is not used.
*
* @author Bryant Martin
*
*/
public class Box {
public Vector3d min,
max;
public Box(Vector3d min, Vector3d max) {
this.min = min;
this.max = max;
}
public boolean intersects(Ray r) {
//return true;
double txmin, txmax, tymin, tymax, tzmin, tzmax;
double a;
a = 1 / r.p1.x;
if (a >= 0) {
txmin = a * (min.x - r.p0.x);
txmax = a * (max.x - r.p0.x);
} else {
txmin = a * (max.x - r.p0.x);
txmax = a * (min.x - r.p0.x);
}
a = 1 / r.p1.y;
if (a >= 0) {
tymin = a * (min.y - r.p0.y);
tymax = a * (max.y - r.p0.y);
} else {
tymin = a * (max.y - r.p0.y);
tymax = a * (min.y - r.p0.y);
}
a = 1 / r.p1.z;
if (a >= 0) {
tzmin = a * (min.z - r.p0.z);
tzmax = a * (max.z - r.p0.z);
} else {
tzmin = a * (max.z - r.p0.z);
tzmax = a * (min.z - r.p0.z);
}
if ((txmin > tymax || tymin > txmax) ||
(tzmin > tymax || tymin > tzmax) ||
(txmin > tzmax || tzmin > txmax)) {
return true;
}
return true;
}
}
| 36,510
|
https://github.com/noamhammer/salto/blob/master/packages/netsuite-adapter/src/transformer.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
salto
|
noamhammer
|
TypeScript
|
Code
| 670
| 2,018
|
/*
* Copyright 2020 Salto Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
ElemID, Field, InstanceElement, isListType, isObjectType, isPrimitiveType, ObjectType,
PrimitiveType, PrimitiveTypes, PrimitiveValue, TypeElement, Value, Values,
} from '@salto-io/adapter-api'
import { naclCase } from '@salto-io/adapter-utils'
import { logger } from '@salto-io/logging'
import { Attributes, Element as XmlElement } from 'xml-js'
import _ from 'lodash'
import { IS_ATTRIBUTE, IS_NAME, NETSUITE, RECORDS_PATH } from './constants'
const log = logger(module)
const XML_TRUE_VALUE = 'T'
const XML_FALSE_VALUE = 'F'
const transformXmlElements = (elements: XmlElement[], type: ObjectType, attributes?: Attributes):
Values | undefined => {
const transformPrimitive = (val?: PrimitiveValue, primitiveType?: PrimitiveType): Value => {
if (_.isUndefined(primitiveType) || _.isUndefined(val)) {
return undefined
}
switch (primitiveType.primitive) {
case PrimitiveTypes.NUMBER:
return Number(val)
case PrimitiveTypes.BOOLEAN:
return val === XML_TRUE_VALUE
default:
return val
}
}
const transformXmlElement = (element: XmlElement, field: Field): Values | undefined => {
if (field === undefined) {
log.warn('Unknown field with name=%. Skipping its transformation', element.name)
return undefined
}
const fieldType = field.type
if (isObjectType(fieldType)) {
if (!_.isArray(element.elements)) {
log.warn('Expected to have inner xml elements for object type %s. Skipping its transformation',
fieldType.elemID.name)
return undefined
}
const transformed = _.omitBy(
transformXmlElements(element.elements, fieldType, element.attributes),
_.isUndefined
)
return _.isEmpty(transformed) ? undefined : transformed
}
if (isListType(fieldType)) {
if (!_.isArray(element.elements)) {
log.warn('Expected to have inner xml elements for list type %s. Skipping its transformation',
fieldType.elemID.name)
return undefined
}
const transformed = element.elements
.map(e => transformXmlElement(e,
new Field(new ElemID(''), fieldType.innerType.elemID.name, fieldType.innerType)))
.filter((val: Value) => !_.isUndefined(val))
return transformed.length === 0 ? undefined : { [field.name]: transformed }
}
if (isPrimitiveType(fieldType)) {
return { [field.name]:
_.isArray(element.elements)
? transformPrimitive(element.elements[0].text, fieldType)
: undefined }
}
return undefined
}
const loweredFieldMap = _.mapKeys(type.fields, (_field, name) => name.toLowerCase())
const transformAttributes = (): Values =>
_(attributes)
.entries()
.map(([lowerAttrName, val]) =>
[loweredFieldMap[lowerAttrName]?.name,
transformPrimitive(val, loweredFieldMap[lowerAttrName]?.type as PrimitiveType)])
.filter(([name, val]) => !_.isUndefined(name) && !_.isUndefined(val))
.fromPairs()
.value()
const result = _(Object.assign(
transformAttributes(),
...elements.map(e => transformXmlElement(e, loweredFieldMap[e.name as string]))
)).omitBy(_.isUndefined).value()
return _.isEmpty(result) ? undefined : result
}
export const createInstanceElement = (rootXmlElement: XmlElement, type: ObjectType):
InstanceElement => {
const findInnerElement = (name: string): XmlElement =>
rootXmlElement.elements?.find(e => e.name === name) as XmlElement
const getInstanceName = (): string => {
const nameField = Object.values(type.fields)
.find(f => f.annotations[IS_NAME]) as Field
return naclCase((findInnerElement(nameField.name.toLowerCase()).elements)?.[0].text as string)
}
const instanceName = getInstanceName()
return new InstanceElement(instanceName, type,
transformXmlElements(rootXmlElement.elements as XmlElement[], type, rootXmlElement.attributes),
[NETSUITE, RECORDS_PATH, type.elemID.name, instanceName])
}
const isXmlElement = (element: XmlElement | undefined): element is XmlElement =>
element !== undefined
const isAttribute = (field: Field): boolean => field.annotations[IS_ATTRIBUTE]
const transformValues = (values: Values, type: ObjectType): XmlElement[] =>
Object.entries(values)
.map(([key, val]) => {
const field = type.fields[key]
if (_.isUndefined(field) || isAttribute(field)) {
return undefined
}
// eslint-disable-next-line @typescript-eslint/no-use-before-define
return transformValue(val, field.type, field.name.toLowerCase())
})
.filter(isXmlElement)
const transformValue = (value: Value, type: TypeElement, elementName: string):
XmlElement | undefined => {
const transformPrimitive = (primitiveValue: PrimitiveValue, primitiveType: PrimitiveType):
string => {
if (primitiveType.primitive === PrimitiveTypes.BOOLEAN) {
return primitiveValue ? XML_TRUE_VALUE : XML_FALSE_VALUE
}
return String(primitiveValue)
}
const transformAttributes = (values: Values, objType: ObjectType): Attributes =>
_(Object.values(objType.fields)
.filter(isAttribute)
.map(f => f.name)
.map(name => [name.toLowerCase(), values[name]]))
.fromPairs()
.omitBy(_.isUndefined)
.value()
if (isObjectType(type)) {
if (!_.isPlainObject(value)) {
return undefined
}
return {
type: 'element',
name: elementName,
elements: transformValues(value, type),
attributes: transformAttributes(value, type),
}
}
if (isListType(type)) {
if (!_.isArray(value)) {
return undefined
}
return {
type: 'element',
name: elementName,
elements: value.map(listValue =>
transformValue(listValue, type.innerType, type.innerType.elemID.name.toLowerCase()))
.filter(isXmlElement),
}
}
if (isPrimitiveType(type)) {
return {
type: 'element',
name: elementName,
elements: [{
type: 'text',
text: transformPrimitive(value, type),
}],
}
}
return undefined
}
export const createXmlElement = (instance: InstanceElement): XmlElement =>
({
elements: [
transformValue(instance.value, instance.type, instance.type.elemID.name.toLowerCase()),
] as XmlElement[],
})
| 145
|
https://github.com/jaredh123/furniture-store/blob/master/js/scripts.js
|
Github Open Source
|
Open Source
|
MIT
| null |
furniture-store
|
jaredh123
|
JavaScript
|
Code
| 218
| 1,064
|
$(document).ready(function() {
var request = new XMLHttpRequest();
request.open('GET', "https://it771mq5n2.execute-api.us-west-2.amazonaws.com/production/furniture/", true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
let body = JSON.parse(this.response);
let types = [];
//Reset ID's and list types
for (let i = 0; i < body.body.data.length; i++) {
body.body.data[i].id = i;
if (!types.includes(body.body.data[i].type)) {
types.push(body.body.data[i].type);
}
}
//List types on page
for (let i = 0; i < types.length; i++) {
$("#furnitureTypes").append(`<li class="type" id="${types[i]}">${types[i]}</li>`);
}
function displayFurnitureItems(type) {
for (let i = 0; i < body.body.data.length; i++) {
if (body.body.data[i].type === type) {
$("#itemsLocation").append(`<li class=furnitureItem id="${body.body.data[i].id}">${body.body.data[i].name}</li>`);
}
}
$(".furnitureItem").click(function(event) {
event.preventDefault();
$("#detailsLocation, #imageLocation").empty();
let id = this.getAttribute("id");
displayItemDetails(id);
});
}
function displayItemDetails(id) {
id = parseInt(id);
for (let i = 0; i < body.body.data.length; i++) {
if (body.body.data[i].id === id) {
let colors = body.body.data[i].colors.join(", ");
let deliverable = "";
if (body.body.data[i].deliverable === true) {
deliverable = "Delivery available.";
}
else {
deliverable = "Delivery unavailable.";
}
//Display furniture item details
$("#detailsLocation").append(`<p> <span id=name><strong>${body.body.data[i].name}</strong></span> -- $${body.body.data[i].cost}</p>`);
$("#detailsLocation").append(`<p>${body.body.data[i].description}</p>`);
$("#detailsLocation").append(`<p>Colors: ${colors}.</p>`);
if (body.body.data[i].dimensions) {
$("#detailsLocation").append(`<p>Dimensions: ${body.body.data[i].dimensions.length}" L x ${body.body.data[i].dimensions.width}" W</p>`);
}
$("#detailsLocation").append(`<p>Stock: ${body.body.data[i].stock}</p>`);
$("#detailsLocation").append(`<p><em>${deliverable}</em></p>`);
//Display image
$("#imageLocation").append(`<img src=${body.body.data[i].imageUrl} alt="${body.body.data[i].name} photo">`);
console.log(`id: ${body.body.data[i].id}`);
console.log(`name: ${body.body.data[i].name}`);
console.log(`$${body.body.data[i].cost}`);
console.log(body.body.data[i].description);
console.log(`${body.body.data[i].dimensions.length}" L x ${body.body.data[i].dimensions.width}" W`);
console.log(`Stock: ${body.body.data[i].stock}`);
console.log(deliverable);
}
}
}
console.log(types);
$(".type").click(function(event) {
event.preventDefault();
$("#itemsLocation").empty();
let id = this.getAttribute("id");
displayFurnitureItems(id);
});
}
}
request.send()
});
| 5,580
|
https://github.com/lgh990/open-platform/blob/master/bytedance/src/main/java/scw/integration/bytedance/poi/PoiExtHotelOrderCancelResponse.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
open-platform
|
lgh990
|
Java
|
Code
| 46
| 173
|
package scw.integration.bytedance.poi;
import io.swagger.v3.oas.annotations.media.Schema;
import scw.integration.bytedance.Response;
import scw.integration.bytedance.ResponseCode;
public class PoiExtHotelOrderCancelResponse extends Response<ResponseCode> {
private static final long serialVersionUID = 1L;
@Schema(description = "取消订单确认状态码;0 - 接受取消")
private Long status;
public Long getStatus() {
return status;
}
public void setStatus(Long status) {
this.status = status;
}
}
| 2,713
|
https://github.com/eurekaclinical/protempa/blob/master/protempa-dsb-relationaldb/src/main/java/org/protempa/backend/dsb/relationaldb/AbstractCaseClause.java
|
Github Open Source
|
Open Source
|
GPL-2.0-only, Apache-2.0, BSD-3-Clause, EPL-1.0, CDDL-1.0, Classpath-exception-2.0, CDDL-1.1, MPL-1.0, MPL-2.0
| 2,021
|
protempa
|
eurekaclinical
|
Java
|
Code
| 216
| 571
|
/*
* #%L
* Protempa Commons Backend Provider
* %%
* Copyright (C) 2012 - 2013 Emory University
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.protempa.backend.dsb.relationaldb;
import static org.protempa.backend.dsb.relationaldb.SqlGeneratorUtil.prepareValue;
import org.protempa.backend.dsb.relationaldb.mappings.Mappings;
abstract class AbstractCaseClause implements CaseClause {
private final Object[] sqlCodes;
private final TableAliaser referenceIndices;
private final ColumnSpec columnSpec;
private final Mappings mappings;
AbstractCaseClause(Object[] sqlCodes, TableAliaser referenceIndices,
ColumnSpec columnSpec, Mappings mappings) {
this.sqlCodes = sqlCodes;
this.referenceIndices = referenceIndices;
this.columnSpec = columnSpec;
this.mappings = mappings;
}
@Override
public String generateClause() {
StringBuilder selectPart = new StringBuilder();
selectPart.append(", case ");
for (int k = 0; k < sqlCodes.length; k++) {
selectPart.append("when ");
selectPart.append(referenceIndices
.generateColumnReferenceWithOp(columnSpec));
selectPart.append(" like ");
selectPart.append(prepareValue(sqlCodes[k]));
selectPart.append(" then ");
selectPart.append(prepareValue(this.mappings.getTarget(sqlCodes[k])));
if (k < sqlCodes.length - 1) {
selectPart.append(" ");
}
}
selectPart.append(" end ");
return selectPart.toString();
}
}
| 44,655
|
https://github.com/weihao996/Quarantine-Boys/blob/master/src/wider/mtcnn_rnet_test.py
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
Quarantine-Boys
|
weihao996
|
Python
|
Code
| 82
| 539
|
"""The code to test training process for rnet"""
import tensorflow as tf
from mtcnn import train_net, RNet
def train_Rnet(training_data, base_lr, loss_weight,
train_mode, num_epochs,
load_model=False, load_filename=None,
save_model=False, save_filename=None,
num_iter_to_save=10000,
device='/cpu:0', gpu_memory_fraction=1):
pnet = tf.Graph()
with pnet.as_default():
with tf.device(device):
train_net(Net=RNet,
training_data=training_data,
base_lr=base_lr,
loss_weight=loss_weight,
train_mode=train_mode,
num_epochs=num_epochs,
load_model=load_model,
load_filename=load_filename,
save_model=save_model,
save_filename=save_filename,
num_iter_to_save=num_iter_to_save,
gpu_memory_fraction=gpu_memory_fraction)
if __name__ == '__main__':
load_filename = './pretrained/initial_weight_rnet.npy'
save_filename = './save_model/new_saver/rnet/rnet'
training_data = ['./prepare_data/rnet_data_for_cls.tfrecords',
'./prepare_data/rnet_data_for_bbx.tfrecords']
device = '/gpu:0'
train_Rnet(training_data=training_data,
base_lr=0.0001,
loss_weight=[1.0, 0.5, 0.5],
train_mode=2,
num_epochs=[300, None, None],
load_model=False,
load_filename=load_filename,
save_model=True,
save_filename=save_filename,
num_iter_to_save=50000,
device=device,
gpu_memory_fraction=0.4)
| 32,718
|
https://github.com/dvallin/tlb-js/blob/master/test/spatial/space.spec.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
tlb-js
|
dvallin
|
TypeScript
|
Code
| 103
| 298
|
import { DiscreteSpace, Space } from '../../src/spatial/space'
import { Vector } from '../../src/spatial/vector'
describe('DiscreteSpace', () => {
testSpace(new Vector([0, 2]), () => new DiscreteSpace(10))
})
function testSpace(position: Vector, spaceBuilder: () => Space<string>): void {
let space: Space<string>
beforeEach(() => {
space = spaceBuilder()
})
describe('get and set', () => {
it('sets and gets cells', () => {
space.set(position, 'a')
expect(space.get(position)).toEqual('a')
})
it('works for empty cells', () => {
expect(space.get(position)).toBeUndefined()
})
})
describe('remove', () => {
it('retains values', () => {
space.set(position, 'a')
const value = space.remove(position)
expect(value).toEqual('a')
})
it('works for empty cells', () => {
const value = space.remove(position)
expect(value).toBeUndefined()
})
})
}
| 8,761
|
https://github.com/meliorence/react-native-render-html/blob/master/doc-tools/doc-pages/src/pages/cards/preformattedConfig.tsx
|
Github Open Source
|
Open Source
|
BSD-2-Clause
| 2,023
|
react-native-render-html
|
meliorence
|
TSX
|
Code
| 90
| 240
|
import { UIRenderHtmlCardProps } from '../../toolkit/toolkit-types';
const html = `
<figure>
<pre> ___________________________
< I'm an expert in my field. >
---------------------------
\\ ^__^
\\ (oo)\\_______
(__)\\ )\\/\\
||----w |
|| ||
</pre>
<figcaption>
A cow saying, "I'm an expert in my field." The cow is illustrated using preformatted text characters.
</figcaption>
</figure>`;
const preformattedConfig: UIRenderHtmlCardProps = {
title: 'Preformatted Text',
caption:
'Notice that every white-space inside the <pre> tag is preserved while white-spaces outside are collapsed.',
props: {
source: {
html
}
},
preferHtmlSrc: true
};
export default preformattedConfig;
| 39,884
|
https://github.com/kokonstya/egal-framework-npm-package/blob/master/src/Actions/ActionResponses/ActionResult.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
egal-framework-npm-package
|
kokonstya
|
TypeScript
|
Code
| 53
| 159
|
/**
* Класс возвращает ответ, полученный сервером
*/
export class ActionResult {
private readonly data: object;
actionName?: string;
modelName?: string;
actionMessage?: Object;
constructor(data: object, actionName?: string, modelName?: string, actionMessage?:Object) {
this.data = data;
this.actionName = actionName;
this.modelName = modelName;
this.actionMessage = actionMessage
}
getData(): object {
return [this.data, this.actionName, this.modelName, this.actionMessage];
}
}
| 16,959
|
https://github.com/donaldboulton/bibwoe/blob/master/_sass/minimal-mistakes/_footnotes.scss
|
Github Open Source
|
Open Source
|
BSD-3-Clause, MIT
| 2,022
|
bibwoe
|
donaldboulton
|
SCSS
|
Code
| 111
| 392
|
$color_1: black;
$color_2: #888;
$font_family_1: Arial, sans-serif;
$background_color_13: #fcf4dd;
#footnotediv {
position: absolute;
width: 400px;
overflow: visible;
background-color: $background_color_13;
font-size: 1.0em;
color: $color_1;
padding: 5px 12px;
border: 1px solid #aaa;
box-shadow: 0 0 10px #333;
-webkit-box-shadow: #333 0 0 10px;
-moz-box-shadow: 0 0 10px #333;
p {
margin: 0;
padding: 5px 0;
}
}
a.footnotebacklink {
border-bottom: none;
img {
margin: 0;
padding: 0;
border: 0;
}
}
#footnotecloselink {
color: $color_2;
text-decoration: none;
text-align: right;
margin: 0;
padding: 0 5px;
font-size: 1.0em;
position: absolute;
float: right;
top: 0;
right: 0;
font-family: $font_family_1;
font-weight: bold;
}
sup {
a {
margin: 0;
padding: 0 4px 5px 4px;
}
padding: 0;
}
| 40,481
|
https://github.com/gelicia/projektor/blob/master/server/server-app/src/test/kotlin/projektor/notification/github/GitHubPullRequestCommentApplicationTest.kt
|
Github Open Source
|
Open Source
|
MIT
| null |
projektor
|
gelicia
|
Kotlin
|
Code
| 689
| 3,156
|
package projektor.notification.github
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig
import io.ktor.http.*
import io.ktor.server.testing.*
import io.ktor.util.*
import org.awaitility.kotlin.await
import org.awaitility.kotlin.until
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import projektor.ApplicationTestCase
import projektor.notification.github.auth.PrivateKeyEncoder
import projektor.parser.GroupedResultsXmlLoader
import projektor.parser.grouped.model.CoverageFile
import projektor.parser.grouped.model.GitMetadata
import projektor.parser.grouped.model.ResultsMetadata
import projektor.server.example.coverage.JacocoXmlLoader
import projektor.server.example.coverage.JacocoXmlLoader.Companion.jacocoXmlParserLineCoveragePercentage
import strikt.api.expectThat
import strikt.assertions.contains
import strikt.assertions.hasSize
@KtorExperimentalAPI
class GitHubPullRequestCommentApplicationTest : ApplicationTestCase() {
private val wireMockServer = WireMockServer(wireMockConfig().dynamicPort())
private val gitHubWireMockStubber = GitHubWireMockStubber(wireMockServer)
@BeforeEach
fun startWireMock() {
wireMockServer.start()
wireMockServer.resetAll()
}
@AfterEach
fun stopWireMock() {
wireMockServer.stop()
}
@Test
fun `when all GitHub notification properties set should publish comment to pull request`() {
val privateKeyContents = loadTextFromFile("fake_private_key.pem")
serverBaseUrl = "http://localhost:8080"
gitHubApiUrl = "http://localhost:${wireMockServer.port()}"
gitHubAppId = "12345"
gitHubPrivateKeyEncoded = PrivateKeyEncoder.base64Encode(privateKeyContents)
val orgName = "craigatk"
val repoName = "projektor"
val branchName = "main"
val pullRequestNumber = 2
gitHubWireMockStubber.stubRepositoryRequests(orgName, repoName)
gitHubWireMockStubber.stubListPullRequests(orgName, repoName, listOf("another-branch", branchName))
gitHubWireMockStubber.stubGetIssue(orgName, repoName, pullRequestNumber)
gitHubWireMockStubber.stubListComments(orgName, repoName, pullRequestNumber, listOf("Some other comment"))
gitHubWireMockStubber.stubAddComment(orgName, repoName, pullRequestNumber)
val gitMetadata = GitMetadata()
gitMetadata.repoName = "$orgName/$repoName"
gitMetadata.branchName = branchName
gitMetadata.isMainBranch = true
val metadata = ResultsMetadata()
metadata.git = gitMetadata
val requestBody = GroupedResultsXmlLoader().passingGroupedResults(metadata)
withTestApplication(::createTestApplication) {
handleRequest(HttpMethod.Post, "/groupedResults") {
addHeader(HttpHeaders.ContentType, "application/json")
setBody(requestBody)
}.apply {
val (publicId, _) = waitForTestRunSaveToComplete(response)
await until { gitHubWireMockStubber.findAddCommentRequestBodies(orgName, repoName, pullRequestNumber).size == 1 }
val addCommentRequestBodies = gitHubWireMockStubber.findAddCommentRequestBodies(orgName, repoName, pullRequestNumber)
expectThat(addCommentRequestBodies).hasSize(1)
expectThat(addCommentRequestBodies[0]).contains(publicId.id)
}
}
}
@Test
fun `when creating a comment on the GitHub PR fails should still save test run`() {
serverBaseUrl = "http://localhost:8080"
gitHubApiUrl = "http://localhost:${wireMockServer.port()}"
gitHubAppId = "12345"
gitHubPrivateKeyEncoded = PrivateKeyEncoder.base64Encode("invalid-private-key")
val orgName = "craigatk"
val repoName = "projektor"
val branchName = "main"
val pullRequestNumber = 2
gitHubWireMockStubber.stubRepositoryRequests(orgName, repoName)
gitHubWireMockStubber.stubListPullRequests(orgName, repoName, listOf("another-branch", branchName))
gitHubWireMockStubber.stubGetIssue(orgName, repoName, pullRequestNumber)
gitHubWireMockStubber.stubListComments(orgName, repoName, pullRequestNumber, listOf("Some other comment"))
gitHubWireMockStubber.stubAddComment(orgName, repoName, pullRequestNumber)
val gitMetadata = GitMetadata()
gitMetadata.repoName = "$orgName/$repoName"
gitMetadata.branchName = branchName
gitMetadata.isMainBranch = true
val metadata = ResultsMetadata()
metadata.git = gitMetadata
val requestBody = GroupedResultsXmlLoader().passingGroupedResults(metadata)
withTestApplication(::createTestApplication) {
handleRequest(HttpMethod.Post, "/groupedResults") {
addHeader(HttpHeaders.ContentType, "application/json")
setBody(requestBody)
}.apply {
waitForTestRunSaveToComplete(response)
await until { gitHubWireMockStubber.findAddCommentRequestBodies(orgName, repoName, pullRequestNumber).size == 0 }
}
}
}
@Test
fun `when report includes coverage data should include it in PR comment`() {
val privateKeyContents = loadTextFromFile("fake_private_key.pem")
serverBaseUrl = "http://localhost:8080"
gitHubApiUrl = "http://localhost:${wireMockServer.port()}"
gitHubAppId = "12345"
gitHubPrivateKeyEncoded = PrivateKeyEncoder.base64Encode(privateKeyContents)
val orgName = "craigatk"
val repoName = "projektor"
val branchName = "main"
val pullRequestNumber = 2
gitHubWireMockStubber.stubRepositoryRequests(orgName, repoName)
gitHubWireMockStubber.stubListPullRequests(orgName, repoName, listOf("another-branch", branchName))
gitHubWireMockStubber.stubGetIssue(orgName, repoName, pullRequestNumber)
gitHubWireMockStubber.stubListComments(orgName, repoName, pullRequestNumber, listOf("Some other comment"))
gitHubWireMockStubber.stubAddComment(orgName, repoName, pullRequestNumber)
val coverageFile = CoverageFile()
coverageFile.reportContents = JacocoXmlLoader().jacocoXmlParser()
val gitMetadata = GitMetadata()
gitMetadata.repoName = "$orgName/$repoName"
gitMetadata.branchName = branchName
gitMetadata.isMainBranch = true
val metadata = ResultsMetadata()
metadata.git = gitMetadata
val requestBody = GroupedResultsXmlLoader().passingResultsWithCoverage(listOf(coverageFile), metadata)
withTestApplication(::createTestApplication) {
handleRequest(HttpMethod.Post, "/groupedResults") {
addHeader(HttpHeaders.ContentType, "application/json")
setBody(requestBody)
}.apply {
val (publicId, _) = waitForTestRunSaveToComplete(response)
await until { gitHubWireMockStubber.findAddCommentRequestBodies(orgName, repoName, pullRequestNumber).size == 1 }
val addCommentRequestBodies = gitHubWireMockStubber.findAddCommentRequestBodies(orgName, repoName, pullRequestNumber)
expectThat(addCommentRequestBodies).hasSize(1)
expectThat(addCommentRequestBodies[0]).contains(jacocoXmlParserLineCoveragePercentage.toString())
}
}
}
@Test
fun `should find pull request by commit SHA and add comment to it`() {
val privateKeyContents = loadTextFromFile("fake_private_key.pem")
serverBaseUrl = "http://localhost:8080"
gitHubApiUrl = "http://localhost:${wireMockServer.port()}"
gitHubAppId = "12345"
gitHubPrivateKeyEncoded = PrivateKeyEncoder.base64Encode(privateKeyContents)
val orgName = "craigatk"
val repoName = "projektor"
val branchName = "main"
val commitSha = "123456789"
val pullRequestNumber = 2
gitHubWireMockStubber.stubRepositoryRequests(orgName, repoName)
gitHubWireMockStubber.stubListPullRequests(orgName, repoName, listOf("branch-1", "branch-2"), listOf("sha-1", commitSha))
gitHubWireMockStubber.stubGetIssue(orgName, repoName, pullRequestNumber)
gitHubWireMockStubber.stubListComments(orgName, repoName, pullRequestNumber, listOf("Some other comment"))
gitHubWireMockStubber.stubAddComment(orgName, repoName, pullRequestNumber)
val gitMetadata = GitMetadata()
gitMetadata.repoName = "$orgName/$repoName"
gitMetadata.branchName = branchName
gitMetadata.isMainBranch = true
gitMetadata.commitSha = commitSha
val metadata = ResultsMetadata()
metadata.git = gitMetadata
val requestBody = GroupedResultsXmlLoader().passingGroupedResults(metadata)
withTestApplication(::createTestApplication) {
handleRequest(HttpMethod.Post, "/groupedResults") {
addHeader(HttpHeaders.ContentType, "application/json")
setBody(requestBody)
}.apply {
val (publicId, _) = waitForTestRunSaveToComplete(response)
await until { gitHubWireMockStubber.findAddCommentRequestBodies(orgName, repoName, pullRequestNumber).size == 1 }
val addCommentRequestBodies = gitHubWireMockStubber.findAddCommentRequestBodies(orgName, repoName, pullRequestNumber)
expectThat(addCommentRequestBodies).hasSize(1)
expectThat(addCommentRequestBodies[0]).contains(publicId.id)
}
}
}
@Test
fun `should find pull request by pull request number and add comment to it`() {
val privateKeyContents = loadTextFromFile("fake_private_key.pem")
serverBaseUrl = "http://localhost:8080"
gitHubApiUrl = "http://localhost:${wireMockServer.port()}"
gitHubAppId = "12345"
gitHubPrivateKeyEncoded = PrivateKeyEncoder.base64Encode(privateKeyContents)
val orgName = "craigatk"
val repoName = "projektor"
val pullRequestNumber = 2
gitHubWireMockStubber.stubRepositoryRequests(orgName, repoName)
gitHubWireMockStubber.stubGetIssue(orgName, repoName, pullRequestNumber)
gitHubWireMockStubber.stubListComments(orgName, repoName, pullRequestNumber, listOf("Some other comment"))
gitHubWireMockStubber.stubAddComment(orgName, repoName, pullRequestNumber)
val gitMetadata = GitMetadata()
gitMetadata.repoName = "$orgName/$repoName"
gitMetadata.isMainBranch = false
gitMetadata.pullRequestNumber = pullRequestNumber
val metadata = ResultsMetadata()
metadata.git = gitMetadata
val requestBody = GroupedResultsXmlLoader().passingGroupedResults(metadata)
withTestApplication(::createTestApplication) {
handleRequest(HttpMethod.Post, "/groupedResults") {
addHeader(HttpHeaders.ContentType, "application/json")
setBody(requestBody)
}.apply {
val (publicId, _) = waitForTestRunSaveToComplete(response)
await until { gitHubWireMockStubber.findAddCommentRequestBodies(orgName, repoName, pullRequestNumber).size == 1 }
val addCommentRequestBodies = gitHubWireMockStubber.findAddCommentRequestBodies(orgName, repoName, pullRequestNumber)
expectThat(addCommentRequestBodies).hasSize(1)
expectThat(addCommentRequestBodies[0]).contains(publicId.id)
}
}
}
}
| 11,296
|
https://github.com/ualibraries/ual-payments/blob/master/templates/partials/title.html.twig
|
Github Open Source
|
Open Source
|
MIT
| null |
ual-payments
|
ualibraries
|
Twig
|
Code
| 9
| 46
|
<div class="title__wrapper">
<div class="title__inner">
<h1 class="title__title">Library payments</h1>
</div>
</div>
| 20,197
|
https://github.com/yunguangwang891017/Familia/blob/master/python/cpp/topical_word_embeddings_wrapper.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,017
|
Familia
|
yunguangwang891017
|
C++
|
Code
| 424
| 1,623
|
// Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Author: lianrongzhong@baidu.com
#include <python2.7/Python.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include "familia/semantic_matching.h"
#include "familia/util.h"
using std::string;
using std::vector;
using std::cin;
using std::cout;
using std::endl;
using namespace familia;
#ifdef Py_RETURN_NONE
#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None
#endif
// 使用UNUSED宏对不使用的参数进行处理
#define UNUSED(x) (void)(x)
// 创建Topical Word Embeddings对象
static PyObject* init_twe(PyObject* self, PyObject* args) {
UNUSED(self);
char* model_dir = NULL;
char* emb_file = NULL;
if (!PyArg_ParseTuple(args, "ss", &model_dir, &emb_file)) {
LOG(ERROR) << "Failed to parse twe parameters.";
return NULL;
}
TopicalWordEmbedding* twe = new TopicalWordEmbedding(model_dir, emb_file);
if (twe == NULL) {
LOG(ERROR) << "Failed to new TopicalWordEmbedding.";
return NULL;
}
return PyLong_FromUnsignedLong((unsigned long)twe);
}
// 销毁Topical Word Embedding对象
static PyObject* destroy_twe(PyObject* self, PyObject* args) {
UNUSED(self);
unsigned long twe_ptr = 0;
if (!PyArg_ParseTuple(args, "k", &twe_ptr)) {
LOG(ERROR) << "Failed to parse TopicalWordEmbedding pointer.";
return NULL;
}
TopicalWordEmbedding* twe = (TopicalWordEmbedding*)(twe_ptr);
delete(twe);
Py_RETURN_NONE;
}
// 返回与目标词最相关的K个词
static PyObject* nearest_words(PyObject* self, PyObject* args) {
UNUSED(self);
unsigned long twe_ptr = 0;
char* word = NULL;
int k = 0;
if (!PyArg_ParseTuple(args, "ksi", &twe_ptr, &word, &k)) {
LOG(ERROR) << "Failed to parse find_nearest_words parameters.";
return NULL;
}
// 检查词典是否包含目标词
TopicalWordEmbedding* twe = (TopicalWordEmbedding*)(twe_ptr);
if (!twe->contains_word(word)) {
LOG(INFO) << word << " is out of vocabulary.";
Py_RETURN_NONE;
}
// 查询最邻近的词
vector<WordAndDis> items(k);
twe->nearest_words(word, items);
// 将结果封装成list返回
PyObject* py_list = PyList_New(0);
if (py_list != NULL) {
for (size_t i = 0; i < items.size(); ++i) {
PyObject* item = Py_BuildValue("(sf)", items[i].word.c_str(), items[i].distance);
PyList_Append(py_list, item);
Py_CLEAR(item);
}
}
return py_list;
}
// 返回对应主题下最邻近的词
static PyObject* nearest_words_around_topic(PyObject* self, PyObject* args) {
UNUSED(self);
unsigned long twe_ptr = 0;
int topic_id = 0;
int k = 0;
if (!PyArg_ParseTuple(args, "kii", &twe_ptr, &topic_id, &k)) {
LOG(ERROR) << "Failed to parse nearest_words_around_topic parameters.";
return NULL;
}
// 判断主题ID是否在合法范围内
TopicalWordEmbedding* twe = (TopicalWordEmbedding*)(twe_ptr);
if (0 > topic_id || topic_id >= twe->num_topics()) {
LOG(INFO) << "Topic_id " << topic_id << " is iilegal.";
Py_RETURN_NONE;
}
// 查询该主题下最邻近的词
vector<WordAndDis> items(k);
twe->nearest_words_around_topic(topic_id, items);
// 将结果封装成list返回
PyObject* py_list = PyList_New(0);
if (py_list != NULL) {
for (size_t i = 0; i < items.size(); ++i) {
PyObject* item = Py_BuildValue("(sf)", items[i].word.c_str(), items[i].distance);
PyList_Append(py_list, item);
Py_CLEAR(item);
}
}
return py_list;
}
// 定义各个函数
static PyMethodDef Methods[] = {
{"init_twe", (PyCFunction)init_twe, METH_VARARGS, "init_twe"},
{"destroy_twe", (PyCFunction)destroy_twe, METH_VARARGS, "destroy_twe"},
{"nearest_words", (PyCFunction)nearest_words, METH_VARARGS, "nearest_words"},
{"nearest_words_around_topic", (PyCFunction)nearest_words_around_topic,
METH_VARARGS, "nearest_words_around_topic"},
{NULL, NULL, 0, NULL}
};
// 模块初始化化
PyMODINIT_FUNC inittopical_word_embeddings(void) {
Py_InitModule("topical_word_embeddings", Methods);
}
/* vim: set ts=4 sw=4 sts=4 tw=100 */
| 13,384
|
https://github.com/suddenlyGiovanni/core/blob/master/packages/system/src/FreeAssociative/index.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
core
|
suddenlyGiovanni
|
TypeScript
|
Code
| 266
| 726
|
// tracing: off
import "../Operator"
import { Stack } from "../Stack"
export class IEmpty {
readonly _tag = "Empty"
}
export class IElement<A> {
readonly _tag = "Element"
constructor(readonly element: A) {}
}
export class IConcat<A> {
readonly _tag = "Concat"
constructor(readonly left: FreeAssociative<A>, readonly right: FreeAssociative<A>) {}
}
export type FreeAssociative<A> = IEmpty | IElement<A> | IConcat<A>
export function init<A>(): FreeAssociative<A> {
return new IEmpty()
}
export function of<A>(a: A): FreeAssociative<A> {
return new IElement(a)
}
export function concat<A>(
r: FreeAssociative<A>
): (l: FreeAssociative<A>) => FreeAssociative<A> {
return (l) => new IConcat(l, r)
}
export function concat_<A>(
l: FreeAssociative<A>,
r: FreeAssociative<A>
): FreeAssociative<A> {
return new IConcat(l, r)
}
export function append<A>(a: A): (_: FreeAssociative<A>) => FreeAssociative<A> {
return (_) => new IConcat(_, new IElement(a))
}
export function append_<A>(_: FreeAssociative<A>, a: A): FreeAssociative<A> {
return new IConcat(_, new IElement(a))
}
export function prepend<A>(a: A): (_: FreeAssociative<A>) => FreeAssociative<A> {
return (_) => new IConcat(new IElement(a), _)
}
export function prepend_<A>(_: FreeAssociative<A>, a: A): FreeAssociative<A> {
return new IConcat(new IElement(a), _)
}
export function toArray<A>(_: FreeAssociative<A>): readonly A[] {
const as = <A[]>[]
let current: FreeAssociative<A> | undefined = _
let stack: Stack<FreeAssociative<A>> | undefined = undefined
while (typeof current !== "undefined") {
switch (current._tag) {
case "Empty": {
current = undefined
break
}
case "Element": {
as.push(current.element)
current = undefined
break
}
case "Concat": {
const p: any = stack
stack = new Stack(current.right, p)
current = current.left
break
}
}
if (typeof current === "undefined") {
if (typeof stack !== "undefined") {
current = stack.value
stack = stack.previous
}
}
}
return as
}
| 24,465
|
https://github.com/knoldus/play-internationalization-example/blob/master/target/scala-2.12/twirl/main/views/html/welcome.template.scala
|
Github Open Source
|
Open Source
|
CC0-1.0
| null |
play-internationalization-example
|
knoldus
|
Scala
|
Code
| 134
| 1,241
|
package views.html
import _root_.play.twirl.api.TwirlFeatureImports._
import _root_.play.twirl.api.TwirlHelperImports._
import _root_.play.twirl.api.Html
import _root_.play.twirl.api.JavaScript
import _root_.play.twirl.api.Txt
import _root_.play.twirl.api.Xml
import models._
import controllers._
import play.api.i18n._
import views.html._
import play.api.templates.PlayMagic._
import play.api.mvc._
import play.api.data._
object welcome extends _root_.play.twirl.api.BaseScalaTemplate[play.twirl.api.HtmlFormat.Appendable,_root_.play.twirl.api.Format[play.twirl.api.HtmlFormat.Appendable]](play.twirl.api.HtmlFormat) with _root_.play.twirl.api.Template3[String,String,MessagesProvider,play.twirl.api.HtmlFormat.Appendable] {
/**/
def apply/*1.2*/(message: String, style: String = "scala")(implicit messages: MessagesProvider):play.twirl.api.HtmlFormat.Appendable = {
_display_ {
{
Seq[Any](format.raw/*1.81*/("""
"""),_display_(/*3.2*/defining(play.core.PlayVersion.current)/*3.41*/ { version =>_display_(Seq[Any](format.raw/*3.54*/("""
"""),format.raw/*4.5*/("""<section>
<div class="wrapper">
"""),_display_(/*6.14*/if(messages.messages.lang.language.equals("en"))/*6.62*/ {_display_(Seq[Any](format.raw/*6.64*/("""
"""),format.raw/*7.17*/("""<a class = "button" href=""""),_display_(/*7.44*/routes/*7.50*/.MySupportController.homePageInFrench()),format.raw/*7.89*/("""">fr</a>
""")))}/*8.15*/else/*8.20*/{_display_(Seq[Any](format.raw/*8.21*/("""
"""),format.raw/*9.17*/("""<a class = "button" href=""""),_display_(/*9.44*/routes/*9.50*/.MySupportController.homePageWithDefaultLang()),format.raw/*9.96*/("""">en</a>
""")))}),format.raw/*10.14*/("""
"""),format.raw/*11.9*/("""</div>
</section>
<div id="content" class="wrapper doc">
<article>
<h1>"""),_display_(/*16.18*/message),format.raw/*16.25*/("""</h1>
<h2>"""),_display_(/*17.18*/messages/*17.26*/.messages("home.title")),format.raw/*17.49*/("""</h2>
</article>
</div>
""")))}),format.raw/*20.2*/("""
"""))
}
}
}
def render(message:String,style:String,messages:MessagesProvider): play.twirl.api.HtmlFormat.Appendable = apply(message,style)(messages)
def f:((String,String) => (MessagesProvider) => play.twirl.api.HtmlFormat.Appendable) = (message,style) => (messages) => apply(message,style)(messages)
def ref: this.type = this
}
/*
-- GENERATED --
DATE: Fri Jul 14 15:50:38 IST 2017
SOURCE: /home/teena/play-internationalization-example/app/views/welcome.scala.html
HASH: d9eb89c0cadf9427f10ab90eed1278909fb9a821
MATRIX: 755->1|929->80|957->83|1004->122|1054->135|1085->140|1164->193|1220->241|1259->243|1303->260|1356->287|1370->293|1429->332|1469->355|1481->360|1519->361|1563->378|1616->405|1630->411|1696->457|1749->479|1785->488|1913->589|1941->596|1991->619|2008->627|2052->650|2119->687
LINES: 21->1|26->1|28->3|28->3|28->3|29->4|31->6|31->6|31->6|32->7|32->7|32->7|32->7|33->8|33->8|33->8|34->9|34->9|34->9|34->9|35->10|36->11|41->16|41->16|42->17|42->17|42->17|45->20
-- GENERATED --
*/
| 41,690
|
https://github.com/vlrusu/ads112c04/blob/master/ads112c04/__init__.py
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ads112c04
|
vlrusu
|
Python
|
Code
| 14
| 59
|
"""Top-level package for ADS112C04."""
__author__ = """Vadim Rusu"""
__email__ = 'vadim.l.rusu@gmail.com'
__version__ = '0.1.0'
| 48,466
|
https://github.com/Shresht7/File-Control-System/blob/master/src/components/explorer.tsx
|
Github Open Source
|
Open Source
|
MIT
| null |
File-Control-System
|
Shresht7
|
TypeScript
|
Code
| 414
| 1,048
|
// Library
import fs, { Dirent } from 'fs'
import path from 'path'
import { useState, useEffect } from 'react'
import { render, Box, Text, useInput } from 'ink'
import open from 'open'
// ==================
// EXPLORER COMPONENT
// ==================
const Explorer = ({ source }: { source: string }) => {
const [currentDir, setCurrentDir] = useState<string>(source) // The Current Working Directory
const [dirEntries, setDirEntries] = useState<Dirent[]>([]) // The List of Children Directory Entries
const [search, setSearch] = useState('') // Search Field to filter down the results
const [cursor, setCursor] = useState<number>(0)
// Set Directory Entries whenever Current Directory changes
useEffect(() => {
setCursor(0)
setSearch('')
setDirEntries(
[
{
name: "..",
isFile: () => false,
isDirectory: () => true,
isBlockDevice: () => false,
isCharacterDevice: () => false,
isFIFO: () => false,
isSocket: () => false,
isSymbolicLink: () => false
},
...fs.readdirSync(currentDir, { withFileTypes: true })
]
)
}, [currentDir])
// Input Handler
useInput((input, key) => {
// Down Key
if (key.downArrow) {
if (cursor < dirEntries.length - 1) { // If cursor is not the last entry ...
setCursor(prevCursor => prevCursor + 1) // ... move it down
} else { // Otherwise ...
setCursor(0) // ... loop back to first entry
}
// Up Key
} else if (key.upArrow) {
if (cursor > 0) { // If cursor is not the first entry ...
setCursor(prevCursor => prevCursor - 1) // ... move it up
} else { // Otherwise ...
setCursor(dirEntries.length - 1) // ... loop down to the last entry
}
// Enter Key
} else if (key.return) {
const selectedEntry = dirEntries.filter(dir => dir.name.match(search)).sort()[cursor] // Select Filtered Directory Entry
if (selectedEntry.isDirectory()) {
setCurrentDir(path.join(currentDir, selectedEntry.name)) // Set Selected Entry as Current Working Directory
} else {
open(path.join(currentDir, selectedEntry.name)) // Otherwise open the entry if it is not a directory
}
// Backspace Key - Reset Search Filter
} else if (key.backspace) {
setCursor(0)
setSearch(prevSearch => prevSearch.substring(0, -1))
// Any Other Key - Update Search Term
} else {
setCursor(0)
setSearch(prevSearch => `${prevSearch}${input}`)
}
})
return (
<Box margin={1} flexDirection='column'>
<Box paddingLeft={2} borderStyle='round' borderColor='yellow'>
<Text>{`${currentDir}\\${search}`}</Text>
</Box>
<Box marginTop={1} flexDirection='column'>
{dirEntries && dirEntries
.filter(dir => search ? dir.name.match(search) : true)
.sort()
.map((dir, idx) => (
<Text
key={idx}
inverse={idx === cursor}
>
{(dir.isDirectory() ? ' 📂 ' : ' 📄 ') + dir.name}
</Text>
))
.slice(Math.max(0, cursor - 7), Math.min(dirEntries.length, cursor + 7))
}
</Box>
</Box>
)
}
const explore = async () => {
render(<Explorer source={process.cwd()} />)
}
// ==================
export default explore
// ==================
| 34,362
|
https://github.com/hassan31120/eunoia/blob/master/app/Http/Resources/UserResource.php
|
Github Open Source
|
Open Source
|
MIT
| null |
eunoia
|
hassan31120
|
PHP
|
Code
| 69
| 283
|
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request)
{
// return parent::toArray($request);
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'age' => $this->age,
'phone_no' => $this->phone_no,
'gender' => $this->gender,
'disease_id' => $this->disease_id,
'survey_score' => $this->survey_score,
'created_at' => $this->created_at->diffForHumans(),
'updated_at' => $this->updated_at->diffForHumans()
];
}
}
| 21,114
|
https://github.com/tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective/blob/master/vcf/VCFBuilder2/MainWindow.h
|
Github Open Source
|
Open Source
|
Apache-1.1
| 2,022
|
sourcecodes-of-CodeReadingTheOpenSourcePerspective
|
tharindusathis
|
C
|
Code
| 238
| 839
|
//MainWindow.h
#ifndef _MAINWINDOW_H__
#define _MAINWINDOW_H__
#include "VCFBuilderUIConfig.h"
#include "Window.h"
#include "StatusBar.h"
#define MAINWINDOW_CLASSID "be07f0a1-35c1-41a3-bdc5-9f97db8edb93"
#define PALETTE_BUTTON_HANDLER "PaletteButtonHandler"
#define PROJECT_HANDLER "CurrentProjectHandler"
class VCF::MenuItemEvent;
using namespace VCF;
namespace VCFBuilder {
class Form;
class VCFBuilderAppEvent;
class ProjectEvent;
class Project;
class ObjectExplorer;
class MainUIPanel;
class FormView;
/**
*Class MainWindow documentation
*/
class VCFBUILDER_API MainWindow : public VCF::Window {
public:
BEGIN_CLASSINFO(MainWindow, "VCFBuilder::MainWindow", "VCF::Window", MAINWINDOW_CLASSID)
END_CLASSINFO(MainWindow)
MainWindow();
virtual ~MainWindow();
void onFileNewProject( VCF::MenuItemEvent* e );
void onFileOpenProject( VCF::MenuItemEvent* e );
void onFileSaveProject( VCF::MenuItemEvent* e );
void onFileSaveProjectAs( VCF::MenuItemEvent* e );
void onFileCloseProject( VCF::MenuItemEvent* e );
void onFileNewForm( VCF::MenuItemEvent* e );
void onFileSaveForm( VCF::MenuItemEvent* e );
void onFileSaveFormAs( VCF::MenuItemEvent* e );
void onFileExit( VCF::MenuItemEvent* e );
void onEditUndo( VCF::MenuItemEvent* e );
void onEditUndoUpdate( VCF::MenuItemEvent* e );
void onEditRedo( VCF::MenuItemEvent* e );
void onEditRedoUpdate( VCF::MenuItemEvent* e );
void onEditCut( VCF::MenuItemEvent* e );
void onEditCopy( VCF::MenuItemEvent* e );
void onEditPaste( VCF::MenuItemEvent* e );
void onEditSelectAll( VCF::MenuItemEvent* e );
void onEditDelete( VCF::MenuItemEvent* e );
void onEditPreferences( VCF::MenuItemEvent* e );
void onEditProjectSettings( VCF::MenuItemEvent* e );
void onMenuItemSelectionChanged( ItemEvent* e );
virtual void afterCreate( ComponentEvent* event );
/**
sets the current active form object. This causes a new
Frame to be displayed within the FormView's form grid.
The new Frame is loaded from the VFF file name specified
in the Form's getVFFFileName() method.
*/
void setActiveForm( Form* activeForm );
Form* getActiveForm();
Frame* getActiveFrameControl();
FormView* getFormViewer();
ObjectExplorer* getObjectExplorer();
protected:
MainUIPanel* m_mainUI;
StatusBar* m_statusBar;
private:
};
}; //end of namespace VCFBuilder
#endif //_MAINWINDOW_H__
| 41,994
|
https://github.com/antonmedv/year/blob/master/packages/2015/04/14/index.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
year
|
antonmedv
|
JavaScript
|
Code
| 6
| 15
|
module.exports = new Date(2015, 3, 14)
| 30,270
|
https://github.com/CodingSaroj/ShroonPrism/blob/master/example/shader.frag
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ShroonPrism
|
CodingSaroj
|
GLSL
|
Code
| 124
| 360
|
#version 450 core
layout (location = 0) in vec2 f_UV;
layout (location = 1) in vec3 f_Normal;
layout (location = 2) in vec3 f_FragPos;
layout (location = 0) out vec4 o_Color;
layout (binding = 0) uniform RendererData
{
vec3 u_LightDir;
vec3 u_LightCol;
};
layout (binding = 1) uniform ObjectData
{
mat4 u_Model;
mat4 u_Projection;
float u_Roughness;
float u_Specular;
};
layout (location = 0) uniform sampler2D u_Albedo;
void main()
{
float ndotl = max(dot(f_Normal, u_LightDir), 0.2);
vec3 diffuse = u_LightCol * ndotl;
vec3 viewDir = normalize(-f_FragPos);
vec3 reflectDir = reflect(-u_LightDir, f_Normal);
float vdotr = max(dot(viewDir, reflectDir), 0.0);
vec3 specular = u_Specular * u_LightCol * vec3(pow(vdotr, max((1.0 - u_Roughness) * 256.0, 1.0)));
vec3 light = diffuse + specular;
o_Color = vec4(light, 1.0) * texture(u_Albedo, f_UV);
}
| 28,044
|
https://github.com/MarkusMokler/photomsmsk-by/blob/master/PhotoMSK/PhotoMSK/Properties/Themes/Landing/empty-project/Views/_ViewStart.cshtml
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
photomsmsk-by
|
MarkusMokler
|
C#
|
Code
| 5
| 31
|
@{
Layout = "~/Themes/empty-project/Views/Shared/_Layout.cshtml";
}
| 729
|
https://github.com/yuanzaiyuanfang/AndroidBaseModule/blob/master/basemodule/src/main/java/com/basemodule/baserx/RxSubscriber.java
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
AndroidBaseModule
|
yuanzaiyuanfang
|
Java
|
Code
| 246
| 870
|
package com.basemodule.baserx;
import android.app.Dialog;
import android.content.Context;
import com.basemodule.R;
import com.basemodule.base.IBaseApplication;
import com.basemodule.utils.NetWorkUtils;
import com.orhanobut.logger.Logger;
import rx.Subscriber;
/**
* des:订阅封装
* Created by xsf
* on 2016.09.10:16
*/
/********************
* 使用例子
********************/
/*_apiService.login(mobile, verifyCode)
.//省略
.subscribe(new RxSubscriber<User user>(mContext,false) {
@Override
public void _onNext(User user) {
// 处理user
}
@Override
public void _onError(String msg) {
ToastUtil.showShort(mActivity, msg);
});*/
public abstract class RxSubscriber<T> extends Subscriber<T> {
private static final String TAG = "RxSubscriber_ONERROR";
private Context mContext;
private boolean showDialog = true;
private Dialog dialog;
/**
* 是否显示浮动dialog
*/
public void showDialog() {
this.showDialog = true;
}
public void hideDialog() {
this.showDialog = true;
}
public RxSubscriber(Context context, boolean showDialog) {
this.mContext = context;
this.showDialog = showDialog;
}
@Override
public void onCompleted() {
if (showDialog) stopProgressDialog();
_onAfter();
}
@Override
public void onStart() {
super.onStart();
if (showDialog) startProgressDialog();
_onStart();
}
/**
*/
private void startProgressDialog() {
if (dialog == null) {
dialog = IBaseApplication.getProgressDialog();
}
dialog.show();
}
/**
*
*/
private void stopProgressDialog() {
if (dialog != null) {
dialog.dismiss();
}
}
@Override
public void onNext(T t) {
_onNext(t);
}
@Override
public void onError(Throwable e) {
_onAfter();
Logger.d(TAG, "onError: " + e.getMessage());
if (showDialog)
stopProgressDialog();
e.printStackTrace();
//网络
if (!NetWorkUtils.isNetConnected(IBaseApplication.getAppInstance())) {
_onError(IBaseApplication.getAppInstance().getString(R.string.no_net));
}
//服务器
else if (e instanceof ServerException) {
_onError(e.getMessage());
}
//手动抛出
else if (e instanceof IllegalStateException) {
_onError(e.getMessage());
}
// //其它
// else {
// _onError(IBaseApplication.getAppContext().getString(R.string.net_error));
// }
}
protected void _onStart() {
}
protected abstract void _onNext(T t);
protected abstract void _onError(String message);
protected void _onAfter() {
}
}
| 30,852
|
https://github.com/shiehinms/vminspector/blob/master/ui/newconnectdlg.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
vminspector
|
shiehinms
|
Python
|
Code
| 144
| 293
|
#!/usr/bin/env python
# Copyright (c) 2007-8 Qtrac Ltd. All rights reserved.
# This program or module 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
# version 3 of the License, or (at your option) any later version. It is
# provided for educational purposes and 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.
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import ui_newconnectdlg
class NewConnectDlg(QDialog, ui_newconnectdlg.Ui_NewConnectDlg):
def __init__(self, parent=None):
super(NewConnectDlg, self).__init__(parent)
self.setupUi(self)
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
form = NewConnectDlg()
form.show()
app.exec_()
| 49,154
|
https://github.com/davidokun/Angular-js/blob/master/http/src/app/server.service.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Angular-js
|
davidokun
|
TypeScript
|
Code
| 113
| 423
|
import {Injectable} from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class ServerService {
constructor(private http: Http) {}
storeServers(servers: any[]) {
const myHeaders = new Headers({
'Content-Type' : 'application/json'
});
// return this.http.post('https://angular-http-module.firebaseio.com/data.json',
// servers,
// {headers: myHeaders});
return this.http.put('https://angular-http-module.firebaseio.com/data.json',
servers,
{headers: myHeaders});
}
getServers() {
return this.http.get('https://angular-http-module.firebaseio.com/data.json')
.map(
(response: Response) => {
const data = response.json();
for (const server of data) {
server.name = 'FETCHED_' + server.name;
}
return data;
}
).catch(
(error: Response) => {
console.log('Error retrieving the servers from backend ' + error);
return Observable.throw(error);
}
);
}
getAppName() {
return this.http.get('https://angular-http-module.firebaseio.com/data/appName.json')
.map(
(response: Response) => {
return response.json();
}
);
}
}
| 50,400
|
https://github.com/sridharlovevirus/KEC-Placement-Assistant/blob/master/studentprofile/index.php
|
Github Open Source
|
Open Source
|
MIT
| null |
KEC-Placement-Assistant
|
sridharlovevirus
|
PHP
|
Code
| 157
| 903
|
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Kongu Engineering college</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<form action="" method="post">
<div class="container">
<br />
<h2 align="center">Request For Edit Acadamic Details</h2>
<br />
<div class="form-group">
<label>Enter the reason for Editing data:</label>
<textarea name="d" id="d" rows="6" class="form-control"></textarea>
</div>
<div class="form-group">
<center> <button type="submit" name="r" class="btn btn-info">Request</button>
<a href="../index.php"> <button type="button" name="c" class="btn btn-warning">Cancel</button></a>
</div>
<div class="form-group">
<input type="hidden" name="post_id" id="post_id" />
<div id="autoSave"></div>
</div>
</div>
</form>
</body>
</html>
<?php
session_start();
if(isset($_POST['r']))
{
$sub="Request For Change Personal Details";
$roll=$_SESSION['user'];
$d=$_POST['d'];
$t=date("d/m/y h:i:sa");
mysql_connect('localhost','root','');
mysql_select_db('kongu');
$rq="select rollno from request where rollno='$roll'";
$u=mysql_query($rq);
$count=mysql_num_rows($u);
if($count==0)
{
$ro="insert into request values('$roll','$d','$t')";
}
else
{
$ro="update request set reason='$d',time='$t' where rollno='$roll'";
}
mysql_query($ro);
$dep=$_SESSION['dep'];
$t1="select mailid from login where additionalrole='placement'";
$ry=mysql_query($t1);
$row1=mysql_fetch_array($ry);
$mail=$row1['mailid'];
$d="Reason for change data is:".$d;
$t=date("d/m/y h:i:sa");
$id=rand(11111,99999);
$att="http://localhost/admin/requestedit.php?request=1";
$mailr="insert into mail values('$roll','$sub','$mail','$d','$att','$t','$id',0)";
mysql_query($mailr);
echo "<script>alert('request submited')</script>";
echo "<b><h1><center>Thank you for your request</center></h1></b>";
header('Refresh:1; url=../index.php');
}
?>
| 42,926
|
https://github.com/KongBOy/final_project/blob/master/web_homework/w11_bomber/key.js
|
Github Open Source
|
Open Source
|
MIT
| null |
final_project
|
KongBOy
|
JavaScript
|
Code
| 202
| 692
|
var max_num = 99;
var min_num = 1;
var counter = 0;
var guess_num = 0;
var answer = Math.floor(Math.random() * 99 + 1);
console.log("answer = " + answer);
function Guess_button() {
guess_num = input_num.value;
//console.log("guess_num = " + guess_num);
if(guess_num == ""){
guess_num = 1;
}
counter++;
//console.log("counter = " + counter);
Set_smoke_img(counter);
if (guess_num == answer) {
alert("恭喜答對了!" + " 總共猜了" + (counter) + "次\n再試一次!");
Restart();
}
else {
if (answer < guess_num) {
max_num = guess_num;
}
else {
min_num = guess_num;
}
if(counter <=5)
{
alert(min_num + " ~ " + max_num);
input_num.value = "";
}
else{
alert("次數已經達到上限\n" + "總共猜了" + (counter) + "次\n再試一次!");
Restart();
}
}
}
function Restart() {
answer = Math.floor(Math.random() * 99) + 1;
console.log("answer = " + answer);
counter = 0; //宣告計數器 紀錄玩家猜測次數
max_num = 99;
min_num = 1;
input_num.value = "";
var bombs = document.querySelectorAll("#bombs img");
for(var i=0;i<bombs.length;i++){
bombs[i].src = "img/bomber.png";
}
}
function Set_smoke_img(counter) {
//console.log("counter = " + counter);
switch (counter) {
case 1:
document.img1.src = "img/smoke.png";
break;
case 2:
document.img2.src = "img/smoke.png";
break;
case 3:
document.img3.src = "img/smoke.png";
break;
case 4:
document.img4.src = "img/smoke.png";
break;
case 5:
document.img5.src = "img/smoke.png";
break;
case 6:
document.img6.src = "img/smoke.png";
break;
}
}
| 39,733
|
https://github.com/jkiddo/opentele-client-android/blob/master/questionnaire-mainapp/src/dk/silverbullet/telemed/rest/tasks/RetrieveEntityTask.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,015
|
opentele-client-android
|
jkiddo
|
Java
|
Code
| 120
| 461
|
package dk.silverbullet.telemed.rest.tasks;
import android.os.AsyncTask;
import android.util.Log;
import dk.silverbullet.telemed.OpenTeleApplication;
import dk.silverbullet.telemed.questionnaire.Questionnaire;
import dk.silverbullet.telemed.rest.client.RestClient;
import dk.silverbullet.telemed.rest.client.RestException;
import dk.silverbullet.telemed.rest.listener.RetrieveEntityListener;
import dk.silverbullet.telemed.utils.Util;
public class RetrieveEntityTask<T> extends AsyncTask<String, String, T> {
private static final String TAG = Util.getTag(RetrieveEntityTask.class);
private final String path;
private final Questionnaire questionnaire;
private final RetrieveEntityListener<T> listener;
private final Class<T> clazz;
public RetrieveEntityTask(String path, Questionnaire questionnaire, RetrieveEntityListener<T> listener, Class<T> clazz) {
this.path = path;
this.questionnaire = questionnaire;
this.listener = listener;
this.clazz = clazz;
}
@Override
protected T doInBackground(String... params) {
try {
return RestClient.getJson(questionnaire, path, clazz);
} catch (RestException e) {
OpenTeleApplication.instance().logException(e);
Log.w(TAG, "Could not retrieve acknowledgement list", e);
}
return null;
}
@Override
protected void onPostExecute(T result) {
if (result != null) {
listener.retrieved(result);
} else {
listener.retrieveError();
}
}
}
| 18,114
|
https://github.com/zzh-wisdom/hashmap/blob/master/quartz/src/lib/dev.h
|
Github Open Source
|
Open Source
|
MIT
| null |
hashmap
|
zzh-wisdom
|
C
|
Code
| 197
| 412
|
/***************************************************************************
Copyright 2016 Hewlett Packard Enterprise Development LP.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
***************************************************************************/
#ifndef __DEVICE_DRIVER_API_H
#define __DEVICE_DRIVER_API_H
#include <stdint.h>
#define MAX_NUM_MC_PCI_BUS 16
#define MAX_NUM_MC_CHANNELS 16
typedef struct {
unsigned int bus_id;
unsigned int dev_id;
unsigned int funct;
} pci_addr;
typedef struct {
pci_addr addr[MAX_NUM_MC_CHANNELS];
unsigned int channels;
} pci_regs_t;
int set_counter(unsigned int counter_id, unsigned int event_id);
int set_pci(unsigned bus_id, unsigned int device_id, unsigned int function_id, unsigned int offset, uint16_t val);
int get_pci(unsigned bus_id, unsigned int device_id, unsigned int function_id, unsigned int offset, uint16_t* val);
#endif /* __DEVICE_DRIVER_API_H */
| 11,573
|
https://github.com/FrankHeijden/cloud/blob/master/cloud-core/src/main/java/cloud/commandframework/CommandManager.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
cloud
|
FrankHeijden
|
Java
|
Code
| 5,119
| 11,210
|
//
// MIT License
//
// Copyright (c) 2021 Alexander Söderberg & 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 cloud.commandframework;
import cloud.commandframework.annotations.injection.ParameterInjectorRegistry;
import cloud.commandframework.arguments.CommandArgument;
import cloud.commandframework.arguments.CommandSuggestionEngine;
import cloud.commandframework.arguments.CommandSyntaxFormatter;
import cloud.commandframework.arguments.DelegatingCommandSuggestionEngineFactory;
import cloud.commandframework.arguments.StandardCommandSyntaxFormatter;
import cloud.commandframework.arguments.flags.CommandFlag;
import cloud.commandframework.arguments.parser.ArgumentParser;
import cloud.commandframework.arguments.parser.ParserParameter;
import cloud.commandframework.arguments.parser.ParserRegistry;
import cloud.commandframework.arguments.parser.StandardParserRegistry;
import cloud.commandframework.captions.CaptionRegistry;
import cloud.commandframework.captions.SimpleCaptionRegistryFactory;
import cloud.commandframework.context.CommandContext;
import cloud.commandframework.context.CommandContextFactory;
import cloud.commandframework.context.StandardCommandContextFactory;
import cloud.commandframework.execution.CommandExecutionCoordinator;
import cloud.commandframework.execution.CommandResult;
import cloud.commandframework.execution.CommandSuggestionProcessor;
import cloud.commandframework.execution.FilteringCommandSuggestionProcessor;
import cloud.commandframework.execution.postprocessor.AcceptingCommandPostprocessor;
import cloud.commandframework.execution.postprocessor.CommandPostprocessingContext;
import cloud.commandframework.execution.postprocessor.CommandPostprocessor;
import cloud.commandframework.execution.preprocessor.AcceptingCommandPreprocessor;
import cloud.commandframework.execution.preprocessor.CommandPreprocessingContext;
import cloud.commandframework.execution.preprocessor.CommandPreprocessor;
import cloud.commandframework.internal.CommandInputTokenizer;
import cloud.commandframework.internal.CommandRegistrationHandler;
import cloud.commandframework.meta.CommandMeta;
import cloud.commandframework.permission.AndPermission;
import cloud.commandframework.permission.CommandPermission;
import cloud.commandframework.permission.OrPermission;
import cloud.commandframework.permission.Permission;
import cloud.commandframework.permission.PredicatePermission;
import cloud.commandframework.services.ServicePipeline;
import cloud.commandframework.services.State;
import io.leangen.geantyref.TypeToken;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Predicate;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* The manager is responsible for command registration, parsing delegation, etc.
*
* @param <C> Command sender type
*/
public abstract class CommandManager<C> {
private final Map<Class<? extends Exception>, BiConsumer<C, ? extends Exception>> exceptionHandlers = new HashMap<>();
private final EnumSet<ManagerSettings> managerSettings = EnumSet.of(
ManagerSettings.ENFORCE_INTERMEDIARY_PERMISSIONS);
private final CommandContextFactory<C> commandContextFactory = new StandardCommandContextFactory<>();
private final ServicePipeline servicePipeline = ServicePipeline.builder().build();
private final ParserRegistry<C> parserRegistry = new StandardParserRegistry<>();
private final Collection<Command<C>> commands = new LinkedList<>();
private final ParameterInjectorRegistry<C> parameterInjectorRegistry = new ParameterInjectorRegistry<>();
private final CommandExecutionCoordinator<C> commandExecutionCoordinator;
private final CommandTree<C> commandTree;
private final CommandSuggestionEngine<C> commandSuggestionEngine;
private CommandSyntaxFormatter<C> commandSyntaxFormatter = new StandardCommandSyntaxFormatter<>();
private CommandSuggestionProcessor<C> commandSuggestionProcessor = new FilteringCommandSuggestionProcessor<>();
private CommandRegistrationHandler commandRegistrationHandler;
private CaptionRegistry<C> captionRegistry;
private final AtomicReference<RegistrationState> state = new AtomicReference<>(RegistrationState.BEFORE_REGISTRATION);
/**
* Create a new command manager instance
*
* @param commandExecutionCoordinator Execution coordinator instance. The coordinator is in charge of executing incoming
* commands. Some considerations must be made when picking a suitable execution coordinator
* for your platform. For example, an entirely asynchronous coordinator is not suitable
* when the parsers used in that particular platform are not thread safe. If you have
* commands that perform blocking operations, however, it might not be a good idea to
* use a synchronous execution coordinator. In most cases you will want to pick between
* {@link CommandExecutionCoordinator#simpleCoordinator()} and
* {@link cloud.commandframework.execution.AsynchronousCommandExecutionCoordinator}
* @param commandRegistrationHandler Command registration handler. This will get called every time a new command is
* registered to the command manager. This may be used to forward command registration
* to the platform.
*/
protected CommandManager(
final @NonNull Function<@NonNull CommandTree<C>, @NonNull CommandExecutionCoordinator<C>> commandExecutionCoordinator,
final @NonNull CommandRegistrationHandler commandRegistrationHandler
) {
this.commandTree = CommandTree.newTree(this);
this.commandExecutionCoordinator = commandExecutionCoordinator.apply(this.commandTree);
this.commandRegistrationHandler = commandRegistrationHandler;
this.commandSuggestionEngine = new DelegatingCommandSuggestionEngineFactory<>(this).create();
/* Register service types */
this.servicePipeline.registerServiceType(new TypeToken<CommandPreprocessor<C>>() {
}, new AcceptingCommandPreprocessor<>());
this.servicePipeline.registerServiceType(new TypeToken<CommandPostprocessor<C>>() {
}, new AcceptingCommandPostprocessor<>());
/* Create the caption registry */
this.captionRegistry = new SimpleCaptionRegistryFactory<C>().create();
/* Register default injectors */
this.parameterInjectorRegistry().registerInjector(
CommandContext.class,
(context, annotationAccessor) -> context
);
}
/**
* Execute a command and get a future that completes with the result. The command may be executed immediately
* or at some point in the future, depending on the {@link CommandExecutionCoordinator} used in the command manager.
* <p>
* The command may also be filtered out by preprocessors (see {@link CommandPreprocessor}) before they are parsed,
* or by the {@link CommandArgument} command arguments during parsing. The execution may also be filtered out
* after parsing by a {@link CommandPostprocessor}. In the case that a command was filtered out at any of the
* execution stages, the future will complete with {@code null}.
* <p>
* The future may also complete exceptionally. The command manager contains some utilities that allow users to
* register exception handlers ({@link #registerExceptionHandler(Class, BiConsumer)} and these can be retrieved using
* {@link #getExceptionHandler(Class)}, or used with {@link #handleException(Object, Class, Exception, BiConsumer)}. It
* is highly recommended that these methods are used in the command manager, as it allows users of the command manager
* to override the exception handling as they wish.
*
* @param commandSender Sender of the command
* @param input Input provided by the sender. Prefixes should be removed before the method is being called, and
* the input here will be passed directly to the command parsing pipeline, after having been tokenized.
* @return future that completes with the command result, or {@code null} if the execution was cancelled at any of the
* processing stages.
*/
public @NonNull CompletableFuture<CommandResult<C>> executeCommand(
final @NonNull C commandSender,
final @NonNull String input
) {
final CommandContext<C> context = this.commandContextFactory.create(
false,
commandSender,
this
);
final LinkedList<String> inputQueue = new CommandInputTokenizer(input).tokenize();
/* Store a copy of the input queue in the context */
context.store("__raw_input__", new LinkedList<>(inputQueue));
try {
if (this.preprocessContext(context, inputQueue) == State.ACCEPTED) {
return this.commandExecutionCoordinator.coordinateExecution(context, inputQueue);
}
} catch (final Exception e) {
final CompletableFuture<CommandResult<C>> future = new CompletableFuture<>();
future.completeExceptionally(e);
return future;
}
/* Wasn't allowed to execute the command */
return CompletableFuture.completedFuture(null);
}
/**
* Get command suggestions for the "next" argument that would yield a correctly parsing command input. The command
* suggestions provided by the command argument parsers will be filtered using the {@link CommandSuggestionProcessor}
* before being returned.
*
* @param commandSender Sender of the command
* @param input Input provided by the sender. Prefixes should be removed before the method is being called, and
* the input here will be passed directly to the command parsing pipeline, after having been tokenized.
* @return List of suggestions
*/
public @NonNull List<@NonNull String> suggest(
final @NonNull C commandSender,
final @NonNull String input
) {
final CommandContext<C> context = this.commandContextFactory.create(
true,
commandSender,
this
);
return this.commandSuggestionEngine.getSuggestions(context, input);
}
/**
* Register a new command to the command manager and insert it into the underlying command tree. The command will be
* forwarded to the {@link CommandRegistrationHandler} and will, depending on the platform, be forwarded to the platform.
* <p>
* Different command manager implementations have different requirements for the command registration. It is possible
* that a command manager may only allow registration during certain stages of the application lifetime. Read the platform
* command manager documentation to find out more about your particular platform
*
* @param command Command to register
* @return The command manager instance. This is returned so that these method calls may be chained. This will always
* return {@code this}.
*/
public @NonNull CommandManager<C> command(final @NonNull Command<C> command) {
if (!(this.transitionIfPossible(RegistrationState.BEFORE_REGISTRATION, RegistrationState.REGISTERING)
|| this.isCommandRegistrationAllowed())) {
throw new IllegalStateException("Unable to register commands because the manager is no longer in a registration "
+ "state. Your platform may allow unsafe registrations by enabling the appropriate manager setting.");
}
this.commandTree.insertCommand(command);
this.commands.add(command);
return this;
}
/**
* Register a new command
*
* @param command Command to register. {@link Command.Builder#build()}} will be invoked.
* @return The command manager instance
*/
public @NonNull CommandManager<C> command(final Command.@NonNull Builder<C> command) {
return this.command(command.manager(this).build());
}
/**
* Get the command syntax formatter
*
* @return Command syntax formatter
*/
public @NonNull CommandSyntaxFormatter<C> getCommandSyntaxFormatter() {
return this.commandSyntaxFormatter;
}
/**
* Set the command syntax formatter
*
* @param commandSyntaxFormatter New formatter
*/
public void setCommandSyntaxFormatter(final @NonNull CommandSyntaxFormatter<C> commandSyntaxFormatter) {
this.commandSyntaxFormatter = commandSyntaxFormatter;
}
/**
* Get the command registration handler
*
* @return Command registration handler
*/
public @NonNull CommandRegistrationHandler getCommandRegistrationHandler() {
return this.commandRegistrationHandler;
}
protected final void setCommandRegistrationHandler(final @NonNull CommandRegistrationHandler commandRegistrationHandler) {
this.requireState(RegistrationState.BEFORE_REGISTRATION);
this.commandRegistrationHandler = commandRegistrationHandler;
}
/**
* Check if the command sender has the required permission. If the permission node is
* empty, this should return {@code true}
*
* @param sender Command sender
* @param permission Permission node
* @return {@code true} if the sender has the permission, else {@code false}
*/
@SuppressWarnings("unchecked")
public boolean hasPermission(
final @NonNull C sender,
final @NonNull CommandPermission permission
) {
if (permission instanceof Permission) {
if (permission.toString().isEmpty()) {
return true;
}
return this.hasPermission(sender, permission.toString());
} else if (permission instanceof PredicatePermission) {
return ((PredicatePermission<C>) permission).hasPermission(sender);
} else if (permission instanceof OrPermission) {
for (final CommandPermission innerPermission : permission.getPermissions()) {
if (this.hasPermission(sender, innerPermission)) {
return true;
}
}
return false;
} else if (permission instanceof AndPermission) {
for (final CommandPermission innerPermission : permission.getPermissions()) {
if (!this.hasPermission(sender, innerPermission)) {
return false;
}
}
return true;
}
throw new IllegalArgumentException("Unknown permission type " + permission.getClass());
}
/**
* Get the caption registry
*
* @return Caption registry
*/
public final @NonNull CaptionRegistry<C> getCaptionRegistry() {
return this.captionRegistry;
}
/**
* Replace the caption registry. Some platforms may inject their own captions into the default registry,
* and so you may need to insert these captions yourself if you do decide to replace the caption registry.
*
* @param captionRegistry New caption registry
*/
public final void setCaptionRegistry(final @NonNull CaptionRegistry<C> captionRegistry) {
this.captionRegistry = captionRegistry;
}
/**
* Replace the default caption registry
*
* @param captionRegistry Caption registry to use
* @deprecated Use {@link #setCaptionRegistry(CaptionRegistry)} These methods are identical.
*/
@Deprecated
public final void registerDefaultCaptions(final @NonNull CaptionRegistry<C> captionRegistry) {
this.captionRegistry = captionRegistry;
}
/**
* Check if the command sender has the required permission. If the permission node is
* empty, this should return {@code true}
*
* @param sender Command sender
* @param permission Permission node
* @return {@code true} if the sender has the permission, else {@code false}
*/
public abstract boolean hasPermission(@NonNull C sender, @NonNull String permission);
/**
* Create a new command builder. This will also register the creating manager in the command
* builder using {@link Command.Builder#manager(CommandManager)}, so that the command
* builder is associated with the creating manager. This allows for parser inference based on
* the type, with the help of the {@link ParserRegistry parser registry}
* <p>
* This method will not register the command in the manager. To do that, {@link #command(Command.Builder)}
* or {@link #command(Command)} has to be invoked with either the {@link Command.Builder} instance, or the constructed
* {@link Command command} instance
*
* @param name Command name
* @param aliases Command aliases
* @param description Description for the root literal
* @param meta Command meta
* @return Builder instance
* @deprecated for removal since 1.4.0. Use {@link #commandBuilder(String, Collection, Description, CommandMeta)} instead.
*/
@Deprecated
public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull Collection<String> aliases,
final @NonNull Description description,
final @NonNull CommandMeta meta
) {
return this.commandBuilder(name, aliases, (ArgumentDescription) description, meta);
}
/**
* Create a new command builder. This will also register the creating manager in the command
* builder using {@link Command.Builder#manager(CommandManager)}, so that the command
* builder is associated with the creating manager. This allows for parser inference based on
* the type, with the help of the {@link ParserRegistry parser registry}
* <p>
* This method will not register the command in the manager. To do that, {@link #command(Command.Builder)}
* or {@link #command(Command)} has to be invoked with either the {@link Command.Builder} instance, or the constructed
* {@link Command command} instance
*
* @param name Command name
* @param aliases Command aliases
* @param description Description for the root literal
* @param meta Command meta
* @return Builder instance
* @since 1.4.0
*/
public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull Collection<String> aliases,
final @NonNull ArgumentDescription description,
final @NonNull CommandMeta meta
) {
return Command.<C>newBuilder(
name,
meta,
description,
aliases.toArray(new String[0])
).manager(this);
}
/**
* Create a new command builder with an empty description.
* <p>
* This will also register the creating manager in the command
* builder using {@link Command.Builder#manager(CommandManager)}, so that the command
* builder is associated with the creating manager. This allows for parser inference based on
* the type, with the help of the {@link ParserRegistry parser registry}
* <p>
* This method will not register the command in the manager. To do that, {@link #command(Command.Builder)}
* or {@link #command(Command)} has to be invoked with either the {@link Command.Builder} instance, or the constructed
* {@link Command command} instance
*
* @param name Command name
* @param aliases Command aliases
* @param meta Command meta
* @return Builder instance
*/
public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull Collection<String> aliases,
final @NonNull CommandMeta meta
) {
return Command.<C>newBuilder(
name,
meta,
ArgumentDescription.empty(),
aliases.toArray(new String[0])
).manager(this);
}
/**
* Create a new command builder. This will also register the creating manager in the command
* builder using {@link Command.Builder#manager(CommandManager)}, so that the command
* builder is associated with the creating manager. This allows for parser inference based on
* the type, with the help of the {@link ParserRegistry parser registry}
* <p>
* This method will not register the command in the manager. To do that, {@link #command(Command.Builder)}
* or {@link #command(Command)} has to be invoked with either the {@link Command.Builder} instance, or the constructed
* {@link Command command} instance
*
* @param name Command name
* @param meta Command meta
* @param description Description for the root literal
* @param aliases Command aliases
* @return Builder instance
* @deprecated for removal since 1.4.0. Use {@link #commandBuilder(String, CommandMeta, ArgumentDescription, String...)}
* instead.
*/
@Deprecated
public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull CommandMeta meta,
final @NonNull Description description,
final @NonNull String... aliases
) {
return this.commandBuilder(name, meta, (ArgumentDescription) description, aliases);
}
/**
* Create a new command builder. This will also register the creating manager in the command
* builder using {@link Command.Builder#manager(CommandManager)}, so that the command
* builder is associated with the creating manager. This allows for parser inference based on
* the type, with the help of the {@link ParserRegistry parser registry}
* <p>
* This method will not register the command in the manager. To do that, {@link #command(Command.Builder)}
* or {@link #command(Command)} has to be invoked with either the {@link Command.Builder} instance, or the constructed
* {@link Command command} instance
*
* @param name Command name
* @param meta Command meta
* @param description Description for the root literal
* @param aliases Command aliases
* @return Builder instance
* @since 1.4.0
*/
public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull CommandMeta meta,
final @NonNull ArgumentDescription description,
final @NonNull String... aliases
) {
return Command.<C>newBuilder(
name,
meta,
description,
aliases
).manager(this);
}
/**
* Create a new command builder with an empty description.
* <p>
* This will also register the creating manager in the command
* builder using {@link Command.Builder#manager(CommandManager)}, so that the command
* builder is associated with the creating manager. This allows for parser inference based on
* the type, with the help of the {@link ParserRegistry parser registry}
* <p>
* This method will not register the command in the manager. To do that, {@link #command(Command.Builder)}
* or {@link #command(Command)} has to be invoked with either the {@link Command.Builder} instance, or the constructed
* {@link Command command} instance
*
* @param name Command name
* @param meta Command meta
* @param aliases Command aliases
* @return Builder instance
*/
public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull CommandMeta meta,
final @NonNull String... aliases
) {
return Command.<C>newBuilder(
name,
meta,
ArgumentDescription.empty(),
aliases
).manager(this);
}
/**
* Create a new command builder using default command meta created by {@link #createDefaultCommandMeta()}.
* <p>
* This will also register the creating manager in the command
* builder using {@link Command.Builder#manager(CommandManager)}, so that the command
* builder is associated with the creating manager. This allows for parser inference based on
* the type, with the help of the {@link ParserRegistry parser registry}
* <p>
* This method will not register the command in the manager. To do that, {@link #command(Command.Builder)}
* or {@link #command(Command)} has to be invoked with either the {@link Command.Builder} instance, or the constructed
* {@link Command command} instance
*
* @param name Command name
* @param description Description for the root literal
* @param aliases Command aliases
* @return Builder instance
* @throws UnsupportedOperationException If the command manager does not support default command meta creation
* @see #createDefaultCommandMeta() Default command meta creation
* @deprecated for removal since 1.4.0. Use {@link #commandBuilder(String, ArgumentDescription, String...)} instead.
*/
@Deprecated
public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull Description description,
final @NonNull String... aliases
) {
return this.commandBuilder(name, (ArgumentDescription) description, aliases);
}
/**
* Create a new command builder using default command meta created by {@link #createDefaultCommandMeta()}.
* <p>
* This will also register the creating manager in the command
* builder using {@link Command.Builder#manager(CommandManager)}, so that the command
* builder is associated with the creating manager. This allows for parser inference based on
* the type, with the help of the {@link ParserRegistry parser registry}
* <p>
* This method will not register the command in the manager. To do that, {@link #command(Command.Builder)}
* or {@link #command(Command)} has to be invoked with either the {@link Command.Builder} instance, or the constructed
* {@link Command command} instance
*
* @param name Command name
* @param description Description for the root literal
* @param aliases Command aliases
* @return Builder instance
* @throws UnsupportedOperationException If the command manager does not support default command meta creation
* @see #createDefaultCommandMeta() Default command meta creation
* @since 1.4.0
*/
public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull ArgumentDescription description,
final @NonNull String... aliases
) {
return Command.<C>newBuilder(
name,
this.createDefaultCommandMeta(),
description,
aliases
).manager(this);
}
/**
* Create a new command builder using default command meta created by {@link #createDefaultCommandMeta()}, and
* an empty description.
* <p>
* This will also register the creating manager in the command
* builder using {@link Command.Builder#manager(CommandManager)}, so that the command
* builder is associated with the creating manager. This allows for parser inference based on
* the type, with the help of the {@link ParserRegistry parser registry}
* <p>
* This method will not register the command in the manager. To do that, {@link #command(Command.Builder)}
* or {@link #command(Command)} has to be invoked with either the {@link Command.Builder} instance, or the constructed
* {@link Command command} instance
*
* @param name Command name
* @param aliases Command aliases
* @return Builder instance
* @throws UnsupportedOperationException If the command manager does not support default command meta creation
* @see #createDefaultCommandMeta() Default command meta creation
*/
public Command.@NonNull Builder<C> commandBuilder(
final @NonNull String name,
final @NonNull String... aliases
) {
return Command.<C>newBuilder(
name,
this.createDefaultCommandMeta(),
ArgumentDescription.empty(),
aliases
).manager(this);
}
/**
* Create a new command argument builder.
* <p>
* This will also invoke {@link CommandArgument.Builder#manager(CommandManager)}
* so that the argument is associated with the calling command manager. This allows for parser inference based on
* the type, with the help of the {@link ParserRegistry parser registry}.
*
* @param type Argument type
* @param name Argument name
* @param <T> Generic argument name
* @return Argument builder
*/
public <T> CommandArgument.@NonNull Builder<C, T> argumentBuilder(
final @NonNull Class<T> type,
final @NonNull String name
) {
return CommandArgument.<C, T>ofType(type, name).manager(this);
}
/**
* Create a new command flag builder
*
* @param name Flag name
* @return Flag builder
*/
public CommandFlag.@NonNull Builder<Void> flagBuilder(final @NonNull String name) {
return CommandFlag.newBuilder(name);
}
/**
* Get the internal command tree. This should not be accessed unless you know what you
* are doing
*
* @return Command tree
*/
public @NonNull CommandTree<C> getCommandTree() {
return this.commandTree;
}
/**
* Construct a default command meta instance
*
* @return Default command meta
* @throws UnsupportedOperationException If the command manager does not support this operation
*/
public abstract @NonNull CommandMeta createDefaultCommandMeta();
/**
* Register a new command preprocessor. The order they are registered in is respected, and they
* are called in LIFO order
*
* @param processor Processor to register
* @see #preprocessContext(CommandContext, LinkedList) Preprocess a context
*/
public void registerCommandPreProcessor(final @NonNull CommandPreprocessor<C> processor) {
this.servicePipeline.registerServiceImplementation(
new TypeToken<CommandPreprocessor<C>>() {
},
processor,
Collections.emptyList()
);
}
/**
* Register a new command postprocessor. The order they are registered in is respected, and they
* are called in LIFO order
*
* @param processor Processor to register
* @see #preprocessContext(CommandContext, LinkedList) Preprocess a context
*/
public void registerCommandPostProcessor(final @NonNull CommandPostprocessor<C> processor) {
this.servicePipeline.registerServiceImplementation(new TypeToken<CommandPostprocessor<C>>() {
}, processor,
Collections.emptyList()
);
}
/**
* Preprocess a command context instance
*
* @param context Command context
* @param inputQueue Command input as supplied by sender
* @return {@link State#ACCEPTED} if the command should be parsed and executed, else {@link State#REJECTED}
* @see #registerCommandPreProcessor(CommandPreprocessor) Register a command preprocessor
*/
public State preprocessContext(
final @NonNull CommandContext<C> context,
final @NonNull LinkedList<@NonNull String> inputQueue
) {
this.servicePipeline.pump(new CommandPreprocessingContext<>(context, inputQueue))
.through(new TypeToken<CommandPreprocessor<C>>() {
})
.getResult();
return context.<String>getOptional(AcceptingCommandPreprocessor.PROCESSED_INDICATOR_KEY).orElse("").isEmpty()
? State.REJECTED
: State.ACCEPTED;
}
/**
* Postprocess a command context instance
*
* @param context Command context
* @param command Command instance
* @return {@link State#ACCEPTED} if the command should be parsed and executed, else {@link State#REJECTED}
* @see #registerCommandPostProcessor(CommandPostprocessor) Register a command postprocessor
*/
public State postprocessContext(
final @NonNull CommandContext<C> context,
final @NonNull Command<C> command
) {
this.servicePipeline.pump(new CommandPostprocessingContext<>(context, command))
.through(new TypeToken<CommandPostprocessor<C>>() {
})
.getResult();
return context.<String>getOptional(AcceptingCommandPostprocessor.PROCESSED_INDICATOR_KEY).orElse("").isEmpty()
? State.REJECTED
: State.ACCEPTED;
}
/**
* Get the command suggestions processor instance currently used in this command manager
*
* @return Command suggestions processor
* @see #setCommandSuggestionProcessor(CommandSuggestionProcessor) Setting the suggestion processor
*/
public @NonNull CommandSuggestionProcessor<C> getCommandSuggestionProcessor() {
return this.commandSuggestionProcessor;
}
/**
* Set the command suggestions processor for this command manager. This will be called every
* time {@link #suggest(Object, String)} is called, to process the list of suggestions
* before it's returned to the caller
*
* @param commandSuggestionProcessor New command suggestions processor
*/
public void setCommandSuggestionProcessor(final @NonNull CommandSuggestionProcessor<C> commandSuggestionProcessor) {
this.commandSuggestionProcessor = commandSuggestionProcessor;
}
/**
* Get the parser registry instance. The parser registry contains default
* mappings to {@link ArgumentParser}
* and allows for the registration of custom mappings. The parser registry also
* contains mappings of annotations to {@link ParserParameter}
* which allows for annotations to be used to customize parser settings.
* <p>
* When creating a new parser type, it is recommended to register it in the parser
* registry. In particular, default parser types (shipped with cloud implementations)
* should be registered in the constructor of the platform {@link CommandManager}
*
* @return Parser registry instance
*/
public ParserRegistry<C> getParserRegistry() {
return this.parserRegistry;
}
/**
* Get the parameter injector registry instance
*
* @return Parameter injector registry
* @since 1.3.0
*/
public final @NonNull ParameterInjectorRegistry<C> parameterInjectorRegistry() {
return this.parameterInjectorRegistry;
}
/**
* Get the exception handler for an exception type, if one has been registered
*
* @param clazz Exception class
* @param <E> Exception type
* @return Exception handler, or {@code null}
* @see #registerCommandPreProcessor(CommandPreprocessor) Registering an exception handler
*/
@SuppressWarnings("unchecked")
public final <E extends Exception> @Nullable BiConsumer<@NonNull C, @NonNull E>
getExceptionHandler(final @NonNull Class<E> clazz) {
final BiConsumer<C, ? extends Exception> consumer = this.exceptionHandlers.get(clazz);
if (consumer == null) {
return null;
}
return (BiConsumer<C, E>) consumer;
}
/**
* Register an exception handler for an exception type. This will then be used
* when {@link #handleException(Object, Class, Exception, BiConsumer)} is called
* for the particular exception type
*
* @param clazz Exception class
* @param handler Exception handler
* @param <E> Exception type
*/
public final <E extends Exception> void registerExceptionHandler(
final @NonNull Class<E> clazz,
final @NonNull BiConsumer<@NonNull C, @NonNull E> handler
) {
this.exceptionHandlers.put(clazz, handler);
}
/**
* Handle an exception using the registered exception handler for the exception type, or using the
* provided default handler if no exception handler has been registered for the exception type
*
* @param sender Executing command sender
* @param clazz Exception class
* @param exception Exception instance
* @param defaultHandler Default exception handler. Will be called if there is no exception
* handler stored for the exception type
* @param <E> Exception type
*/
public final <E extends Exception> void handleException(
final @NonNull C sender,
final @NonNull Class<E> clazz,
final @NonNull E exception,
final @NonNull BiConsumer<C, E> defaultHandler
) {
Optional.ofNullable(this.getExceptionHandler(clazz)).orElse(defaultHandler).accept(sender, exception);
}
/**
* Get a collection containing all registered commands.
*
* @return Unmodifiable view of all registered commands
*/
public final @NonNull Collection<@NonNull Command<C>> getCommands() {
return Collections.unmodifiableCollection(this.commands);
}
/**
* Get a command help handler instance. This can be used to assist in the production
* of command help menus, etc. This command help handler instance will display
* all commands registered in this command manager.
*
* @return Command help handler. A new instance will be created
* each time this method is called.
*/
public final @NonNull CommandHelpHandler<C> getCommandHelpHandler() {
return new CommandHelpHandler<>(this, cmd -> true);
}
/**
* Get a command help handler instance. This can be used to assist in the production
* of command help menus, etc. A predicate can be specified to filter what commands
* registered in this command manager are visible in the help menu.
*
* @param commandPredicate Predicate that filters what commands are displayed in
* the help menu.
* @return Command help handler. A new instance will be created
* each time this method is called.
*/
public final @NonNull CommandHelpHandler<C> getCommandHelpHandler(
final @NonNull Predicate<Command<C>> commandPredicate
) {
return new CommandHelpHandler<>(this, commandPredicate);
}
/**
* Get a command manager setting
*
* @param setting Setting
* @return {@code true} if the setting is activated or {@code false} if it's not
* @see #setSetting(ManagerSettings, boolean) Update a manager setting
*/
public boolean getSetting(final @NonNull ManagerSettings setting) {
return this.managerSettings.contains(setting);
}
/**
* Update a command manager setting
*
* @param setting Setting to update
* @param value Value. In most cases {@code true} will enable a feature, whereas {@code false} will disable it.
* The value passed to the method will be reflected in {@link #getSetting(ManagerSettings)}
* @see #getSetting(ManagerSettings) Get a manager setting
*/
@SuppressWarnings("unused")
public void setSetting(
final @NonNull ManagerSettings setting,
final boolean value
) {
if (value) {
this.managerSettings.add(setting);
} else {
this.managerSettings.remove(setting);
}
}
/**
* Returns the command execution coordinator used in this manager
*
* @return Command execution coordinator
* @since 1.6.0
*/
public @NonNull CommandExecutionCoordinator<C> commandExecutionCoordinator() {
return this.commandExecutionCoordinator;
}
/**
* Transition from the {@code in} state to the {@code out} state, if the manager is not already in that state.
*
* @param in The starting state
* @param out The ending state
* @throws IllegalStateException if the manager is in any state but {@code in} or {@code out}
* @since 1.2.0
*/
protected final void transitionOrThrow(final @NonNull RegistrationState in, final @NonNull RegistrationState out) {
if (!this.transitionIfPossible(in, out)) {
throw new IllegalStateException("Command manager was in state " + this.state.get() + ", while we were expecting a state "
+ "of " + in + " or " + out + "!");
}
}
/**
* Transition from the {@code in} state to the {@code out} state, if the manager is not already in that state.
*
* @param in The starting state
* @param out The ending state
* @return {@code true} if the state transition was successful, or the manager was already in the desired state
* @since 1.2.0
*/
protected final boolean transitionIfPossible(final @NonNull RegistrationState in, final @NonNull RegistrationState out) {
return this.state.compareAndSet(in, out) || this.state.get() == out;
}
/**
* Require that the commands manager is in a certain state.
*
* @param expected The required state
* @throws IllegalStateException if the manager is not in the expected state
* @since 1.2.0
*/
protected final void requireState(final @NonNull RegistrationState expected) {
if (this.state.get() != expected) {
throw new IllegalStateException("This operation required the commands manager to be in state " + expected + ", but it "
+ "was in " + this.state.get() + " instead!");
}
}
/**
* Transition the command manager from either {@link RegistrationState#BEFORE_REGISTRATION} or
* {@link RegistrationState#REGISTERING} to {@link RegistrationState#AFTER_REGISTRATION}.
*
* @throws IllegalStateException if the manager is not in the expected state
* @since 1.4.0
*/
protected final void lockRegistration() {
if (this.getRegistrationState() == RegistrationState.BEFORE_REGISTRATION) {
this.transitionOrThrow(RegistrationState.BEFORE_REGISTRATION, RegistrationState.AFTER_REGISTRATION);
return;
}
this.transitionOrThrow(RegistrationState.REGISTERING, RegistrationState.AFTER_REGISTRATION);
}
/**
* Get the active registration state for this manager.
* <p>
* If this state is {@link RegistrationState#AFTER_REGISTRATION}, commands can no longer be registered
*
* @return The current state
* @since 1.2.0
*/
public final @NonNull RegistrationState getRegistrationState() {
return this.state.get();
}
/**
* Check if command registration is allowed.
* <p>
* On platforms where unsafe registration is possible, this can be overridden by enabling the
* {@link ManagerSettings#ALLOW_UNSAFE_REGISTRATION} setting.
*
* @return {@code true} if the registration is allowed, else {@code false}
* @since 1.2.0
*/
public boolean isCommandRegistrationAllowed() {
return this.getSetting(ManagerSettings.ALLOW_UNSAFE_REGISTRATION) || this.state.get() != RegistrationState.AFTER_REGISTRATION;
}
/**
* Configurable command related settings
*
* @see CommandManager#setSetting(ManagerSettings, boolean) Set a manager setting
* @see CommandManager#getSetting(ManagerSettings) Get a manager setting
*/
public enum ManagerSettings {
/**
* Do not create a compound permission and do not look greedily
* for child permission values, if a preceding command in the tree path
* has a command handler attached
*/
ENFORCE_INTERMEDIARY_PERMISSIONS,
/**
* Force sending of an empty suggestion (i.e. a singleton list containing an empty string)
* when no suggestions are present
*/
FORCE_SUGGESTION,
/**
* Allow registering commands even when doing so has the potential to produce inconsistent results.
* <p>
* For example, if a platform serializes the command tree and sends it to clients,
* this will allow modifying the command tree after it has been sent, as long as these modifications are not blocked by
* the underlying platform
*
* @since 1.2.0
*/
ALLOW_UNSAFE_REGISTRATION,
/**
* Enables overriding of existing commands on supported platforms.
*
* @since 1.2.0
*/
OVERRIDE_EXISTING_COMMANDS
}
/**
* The point in the registration lifecycle for this commands manager
*
* @since 1.2.0
*/
public enum RegistrationState {
/**
* The point when no commands have been registered yet.
*
* <p>At this point, all configuration options can be changed.</p>
*/
BEFORE_REGISTRATION,
/**
* When at least one command has been registered, and more commands have been registered.
*
* <p>In this state, some options that affect how commands are registered with the platform are frozen. Some platforms
* will remain in this state for their lifetime.</p>
*/
REGISTERING,
/**
* Once registration has been completed.
*
* <p>At this point, the command manager is effectively immutable. On platforms where command registration happens via
* callback, this state is achieved the first time the manager's callback is executed for registration.</p>
*/
AFTER_REGISTRATION
}
}
| 1,069
|
https://github.com/thiscouldbejd/Caerus/blob/master/_Directories/Enums/ParameterOperator.vb
|
Github Open Source
|
Open Source
|
MIT
| null |
Caerus
|
thiscouldbejd
|
Visual Basic
|
Code
| 68
| 264
|
Namespace Directories
''' <summary></summary>
''' <autogenerated>Generated from a T4 template. Modifications will be lost, if applicable use a partial class instead.</autogenerated>
''' <generator-date>08/02/2014 18:09:27</generator-date>
''' <generator-functions>1</generator-functions>
''' <generator-source>Caerus\_Directories\Enums\ParameterOperator.tt</generator-source>
''' <generator-version>1</generator-version>
<System.CodeDom.Compiler.GeneratedCode("Caerus\_Directories\Enums\ParameterOperator.tt", "1")> _
<System.Serializable()> _
Public Enum ParameterOperator As System.Int32
''' <summary>Represents an AND Operator</summary>
AndOperator = 1
''' <summary>Represents an OR Operator</summary>
OrEquality = 2
''' <summary>Represents a NOT Operator</summary>
NotEquality = 3
End Enum
End Namespace
| 10,361
|
https://github.com/h2oai/dai-deployment-templates/blob/master/local-rest-scorer/build.gradle
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
dai-deployment-templates
|
h2oai
|
Gradle
|
Code
| 302
| 987
|
plugins {
id 'com.google.cloud.tools.jib'
id 'org.springframework.boot'
}
apply from: project(":").file('gradle/java.gradle')
dependencies {
implementation project(':common:rest-spring-api')
implementation project(':common:transform')
implementation group: 'ai.h2o', name: 'h2o-genmodel'
implementation group: 'ai.h2o', name: 'h2o-genmodel-ext-xgboost'
implementation group: 'ai.h2o', name: 'mojo2-runtime-api'
implementation group: 'ai.h2o', name: 'mojo2-runtime-h2o3-impl'
implementation group: 'ai.h2o', name: 'mojo2-runtime-impl'
implementation group: 'io.springfox', name: 'springfox-boot-starter', version: springFoxVersion
implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web'
implementation group: 'org.apache.tomcat.embed', name: 'tomcat-embed-core', version: '9.0.63'
implementation group: 'com.google.guava', name: 'guava', version: guavaVersion
testImplementation group: 'org.springframework.boot', name: 'spring-boot-starter-test'
testImplementation group: 'com.google.truth.extensions', name: 'truth-java8-extension'
testImplementation group: 'org.mockito', name: 'mockito-inline'
testImplementation group: 'org.mockito', name : 'mockito-core'
testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api'
testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-params'
testImplementation group: 'org.junit-pioneer', name: 'junit-pioneer', version: jupiterPioneerVersion
testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine'
}
test {
useJUnitPlatform()
}
bootRun {
systemProperties System.properties
}
bootJar {
mainClass = 'ai.h2o.mojos.deploy.local.rest.ScorerApplication'
archiveClassifier = 'boot'
}
jar {
enabled = true
}
// Include the local rest scorer executable jar in the root package distribution zip file.
rootProject.distributionZip {
dependsOn bootJar
into(this.project.path.replace(":", "/")) {
from bootJar.archivePath
}
}
// Docker image configuration.
jib {
from {
image = javaBaseImage
}
to {
image = dockerRepositoryPrefix + 'rest-scorer'
tags = [version]
auth {
username = System.getenv('TO_DOCKER_USERNAME') ?: ''
password = System.getenv('TO_DOCKER_PASSWORD') ?: ''
}
}
container {
jvmFlags = defaultJibContainerJvmFlags.split(" ").each { it.trim() }
ports = ['8080']
volumes = [
// For storing the mojo2 file with the model to be used for scoring.
'/mojos',
// For the DAI license file.
'/secrets',
]
environment = [
// The expected path to the DAI license file.
DRIVERLESS_AI_LICENSE_FILE: '/secrets/license.sig',
]
}
}
// Make docker TAR build part of the build task to ensure the image can be built.
// No pushing anywhere (not even to local docker). To push to local docker run task `jibDockerBuild` instead.
// To push to harbor use task `jib`, credentials will be needed though.
tasks.build.dependsOn tasks.jibBuildTar
| 32,635
|
https://github.com/Deval123/rapmis/blob/master/app/Resources/views/staff/show.html.twig
|
Github Open Source
|
Open Source
|
MIT
| null |
rapmis
|
Deval123
|
Twig
|
Code
| 117
| 540
|
{% extends 'base.html.twig' %}
{% block body %}
<div class="page-content-wrapper">
<div class="page-content">
<div class="page-bar">
<div class="page-title-breadcrumb">
<div class=" pull-left">
<div class="page-title">Dashboard</div>
</div>
<ol class="breadcrumb page-breadcrumb pull-right">
<li><i class="fa fa-home"></i> <a class="parent-item" href="{{ path('homepage') }}">Home</a> <i class="fa fa-angle-right"></i>
</li>
<li class="active">Dashboard</li>
</ol>
</div>
</div>
<h1>Staff</h1>
<table>
<tbody>
<tr>
<th></th>
<td><img src="{{ asset('uploads/staff/' ~ staff.filename) }}" alt=""></td>
</tr>
<tr>
<th>Name</th>
<td>{{ staff.name }}</td>
</tr>
<tr>
<th>Fonction</th>
<td>{{ staff.fonction }}</td>
</tr>
<tr>
<th>Tel</th>
<td>{{ staff.tel }}</td>
</tr>
<tr>
<th>Mail</th>
<td>{{ staff.mail }}</td>
</tr>
</tbody>
</table>
<ul>
<li>
<a href="{{ path('staff_index') }}">Back to the list</a>
</li>
<li>
<a href="{{ path('staff_edit', { 'id': staff.id }) }}">Edit</a>
</li>
<li>
{{ form_start(delete_form) }}
<input type="submit" value="Delete">
{{ form_end(delete_form) }}
</li>
</ul>
</div>
</div>
{% endblock %}
| 14,726
|
https://github.com/zalando-stups/skrop/blob/master/filters/localfilecache_test.go
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
skrop
|
zalando-stups
|
Go
|
Code
| 366
| 1,695
|
package filters
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
"github.com/zalando-stups/skrop/cache"
"github.com/zalando-stups/skrop/filters/imagefiltertest"
"github.com/zalando/skipper/filters"
"github.com/zalando/skipper/filters/filtertest"
"github.com/stretchr/testify/assert"
)
type noopMetricHandler struct{}
var emptyMeta = make(map[string]*string)
func (f *noopMetricHandler) MeasureSince(key string, start time.Time) {}
func (f *noopMetricHandler) IncCounter(key string) {}
func (f *noopMetricHandler) IncCounterBy(key string, value int64) {}
func (f *noopMetricHandler) IncFloatCounterBy(key string, value float64) {}
func TestLocalFileCache_NewLocalFileCache(t *testing.T) {
cache := cache.NewFileSystemCache()
cacheFilter := NewLocalFileCache(cache)
assert.NotNil(t, cacheFilter)
}
func TestLocalFileCache_Name(t *testing.T) {
cache := &localFileCache{}
name := cache.Name()
assert.Equal(t, "localFileCache", name)
}
func TestLocalFileCache_CreateFilter(t *testing.T) {
cache := cache.NewFileSystemCache()
imagefiltertest.TestCreate(t, func() filters.Spec { return NewLocalFileCache(cache) },
[]imagefiltertest.CreateTestItem{{
Msg: "no args",
Args: nil,
Err: true,
}, {
Msg: "one arg",
Args: []interface{}{"/tmp"},
Err: false,
}, {
Msg: "two args",
Args: []interface{}{"/tmp", "hello"},
Err: true,
}})
}
func TestLocalFileCache_determineKey(t *testing.T) {
resourcePath := "/LT/12/1A/01/39/51/LT121A013-951@25.jpg"
requestPath := "http://www.example.org" + resourcePath
queryParams := "?a=3"
urlNoQuery := httptest.NewRequest("GET", requestPath, nil).URL
urlQuery := httptest.NewRequest("GET", requestPath+queryParams, nil).URL
cacheDir := "/images"
extensionIndex := strings.LastIndex(resourcePath, ".")
path := resourcePath[:extensionIndex]
ext := resourcePath[extensionIndex:]
keyQuery := determineKey(cacheDir, urlQuery)
keyNoQuery := determineKey(cacheDir, urlNoQuery)
assert.True(t, strings.HasPrefix(keyQuery, cacheDir+path))
assert.True(t, strings.HasSuffix(keyQuery, ext))
assert.False(t, resourcePath == keyQuery)
assert.False(t, keyQuery == keyNoQuery)
}
func TestLocalFileCache_Request_NoCache(t *testing.T) {
reqPath := "/LT/12/1A/01/39/51/LT121A013-951@25.jpg"
cache := cache.NewFileSystemCache()
cacheFilter := NewLocalFileCache(cache)
f, _ := cacheFilter.CreateFilter([]interface{}{"/images"})
req, _ := http.NewRequest("GET", "http://www.example.org"+reqPath+"?refresh=true", nil)
ctx := &filtertest.Context{FRequest: req, FMetrics: &noopMetricHandler{}}
f.Request(ctx)
assert.False(t, ctx.Served())
}
func TestLocalFileCache_Request_NotInCache(t *testing.T) {
reqPath := "/LT/12/1A/01/39/51/LT121A013-951@25.jpg"
cache := cache.NewFileSystemCache()
cacheFilter := NewLocalFileCache(cache)
f, _ := cacheFilter.CreateFilter([]interface{}{"/images"})
req, _ := http.NewRequest("GET", "http://www.example.org"+reqPath, nil)
ctx := &filtertest.Context{FRequest: req, FMetrics: &noopMetricHandler{}}
f.Request(ctx)
assert.False(t, ctx.Served())
}
func TestLocalFileCache_Request_InCache(t *testing.T) {
reqPath := "/lisbon-tram.jpg"
cache := cache.NewFileSystemCache()
cacheFilter := NewLocalFileCache(cache)
f, _ := cacheFilter.CreateFilter([]interface{}{"../images"})
req, _ := http.NewRequest("GET", "http://www.example.org"+reqPath, nil)
ctx := &filtertest.Context{FRequest: req, FMetrics: &noopMetricHandler{}}
f.Request(ctx)
assert.True(t, ctx.Served())
_, err := ioutil.ReadAll(ctx.Response().Body)
assert.Nil(t, err)
}
func TestLocalFileCache_refresh(t *testing.T) {
query := make(url.Values)
assert.False(t, refreshCache(query))
query = make(url.Values)
query[refreshCacheQueryKey] = []string{""}
assert.False(t, refreshCache(query))
query = make(url.Values)
query[refreshCacheQueryKey] = []string{"false"}
assert.False(t, refreshCache(query))
query = make(url.Values)
query[refreshCacheQueryKey] = []string{"true"}
assert.True(t, refreshCache(query))
}
func TestLocalFileCache_Response(t *testing.T) {
reqPath := "/lisbon-tram.jpg"
cache := cache.NewFileSystemCache()
cacheFilter := NewLocalFileCache(cache)
f, _ := cacheFilter.CreateFilter([]interface{}{"../tmpimages"})
req, _ := http.NewRequest("GET", "http://www.example.org"+reqPath, nil)
recorder := httptest.NewRecorder()
ctx := &filtertest.Context{FRequest: req, FMetrics: &noopMetricHandler{}, FResponse: recorder.Result()}
f.Response(ctx)
assert.Equal(t, "200 OK", ctx.Response().Status)
os.RemoveAll("../tmpimages")
}
| 44,772
|
https://github.com/hiloWang/notes/blob/master/Android/00-Code/UISystem/View/src/main/java/com/ztiany/view/drawable/DrawableBitmapFragment.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
notes
|
hiloWang
|
Java
|
Code
| 54
| 204
|
package com.ztiany.view.drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.ztiany.view.R;
/**
* @author Ztiany
* Email: ztiany3@gmail.com
* Date : 2017-12-10 23:38
*/
public class DrawableBitmapFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.drawable_fragment_bitmap, container, false);
}
}
| 2,051
|
https://github.com/neonowy/vrs/blob/master/Test/Test.VirtualRadar.Library/Presenter/ConnectionSessionLogPresenterTests.cs
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
vrs
|
neonowy
|
C#
|
Code
| 600
| 2,107
|
// Copyright © 2010 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using VirtualRadar.Interface.Presenter;
using Moq;
using VirtualRadar.Interface.View;
using InterfaceFactory;
using VirtualRadar.Interface.Database;
using Test.Framework;
using System.Threading;
using System.Globalization;
namespace Test.VirtualRadar.Library.Presenter
{
[TestClass]
public class ConnectionSessionLogPresenterTests
{
public TestContext TestContext { get; set; }
private IClassFactory _ClassFactorySnapshot;
private IConnectionSessionLogPresenter _Presenter;
private Mock<IConnectionSessionLogView> _View;
private Mock<ILogDatabase> _LogDatabase;
private List<LogClient> _LogClients;
private List<LogSession> _LogSessions;
[TestInitialize]
public void TestInitialise()
{
_ClassFactorySnapshot = Factory.TakeSnapshot();
_LogClients = new List<LogClient>();
_LogSessions = new List<LogSession>();
_LogDatabase = TestUtilities.CreateMockSingleton<ILogDatabase>();
_LogDatabase.Setup(d => d.FetchSessions(It.IsAny<IList<LogClient>>(), It.IsAny<IList<LogSession>>(), It.IsAny<DateTime>(), It.IsAny<DateTime>())).Callback((IList<LogClient> clients, IList<LogSession> sessions, DateTime startDate, DateTime endDate) => {
foreach(var client in _LogClients) clients.Add(client);
foreach(var session in _LogSessions) sessions.Add(session);
});
_Presenter = Factory.Resolve<IConnectionSessionLogPresenter>();
_View = new Mock<IConnectionSessionLogView>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties();
}
[TestCleanup]
public void TestCleanup()
{
Factory.RestoreSnapshot(_ClassFactorySnapshot);
}
[TestMethod]
public void ConnectionSessionLogPresenter_Initialise_Sets_Initial_Values_For_View_Properties()
{
_Presenter.Initialise(_View.Object);
Assert.AreEqual(DateTime.Today, _View.Object.StartDate);
Assert.AreEqual(DateTime.Today, _View.Object.EndDate);
}
[TestMethod]
public void ConnectionSessionLogPresenter_Clicking_ShowSessions_Triggers_Display_Of_Sessions()
{
_Presenter.Initialise(_View.Object);
_View.Object.StartDate = new DateTime(2010, 3, 4);
_View.Object.EndDate = new DateTime(2011, 7, 8);
var client1 = new Mock<LogClient>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object;
var client2 = new Mock<LogClient>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object;
var session1 = new Mock<LogSession>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object;
var session2 = new Mock<LogSession>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object;
_LogClients.Add(client1);
_LogClients.Add(client2);
_LogSessions.Add(session1);
_LogSessions.Add(session2);
_View.Setup(v => v.ShowSessions(It.IsAny<IEnumerable<LogClient>>(), It.IsAny<IEnumerable<LogSession>>())).Callback((IEnumerable<LogClient> clients, IEnumerable<LogSession> sessions) => {
Assert.AreEqual(2, clients.Count());
Assert.IsTrue(clients.Where(c => c == client1).Any());
Assert.IsTrue(clients.Where(c => c == client2).Any());
Assert.AreEqual(2, sessions.Count());
Assert.IsTrue(sessions.Where(s => s == session1).Any());
Assert.IsTrue(sessions.Where(s => s == session2).Any());
});
_View.Raise(v => v.ShowSessionsClicked += null, EventArgs.Empty);
_LogDatabase.Verify(d => d.FetchSessions(It.IsAny<IList<LogClient>>(), It.IsAny<IList<LogSession>>(), new DateTime(2010, 3, 4, 0, 0, 0, 0), new DateTime(2011, 7, 8, 23, 59, 59, 999)), Times.Once());
_View.Verify(v => v.ShowSessions(It.IsAny<IEnumerable<LogClient>>(), It.IsAny<IEnumerable<LogSession>>()), Times.Once());
}
[TestMethod]
[DataSource("Data Source='LibraryTests.xls';Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Extended Properties='Excel 8.0'",
"ValidateSessionLogView$")]
public void ConnectionSessionLogPresenter_Clicking_ShowSessions_Triggers_Validation()
{
var worksheet = new ExcelWorksheetData(TestContext);
_Presenter.Initialise(_View.Object);
_View.Object.StartDate = worksheet.DateTime("StartDate");
_View.Object.EndDate = worksheet.DateTime("EndDate");
ValidationResults validationResults = null;
_View.Setup(v => v.ShowValidationResults(It.IsAny<ValidationResults>())).Callback((ValidationResults results) => {
validationResults = results;
});
_View.Raise(v => v.ShowSessionsClicked += null, EventArgs.Empty);
Assert.IsNotNull(validationResults);
Assert.AreEqual(worksheet.Int("CountErrors"), validationResults.Results.Count());
if(validationResults.Results.Count() > 0) {
Assert.IsTrue(validationResults.Results.Where(r => r.Field == worksheet.ParseEnum<ValidationField>("Field") &&
r.Message == worksheet.String("Message") &&
r.IsWarning == worksheet.Bool("IsWarning")).Any());
}
}
[TestMethod]
public void ConnectionSessionLogPresenter_Clicking_ShowSessions_Does_Not_Display_Sessions_If_Validation_Failed()
{
_Presenter.Initialise(_View.Object);
_View.Object.StartDate = DateTime.Today;
_View.Object.EndDate = _View.Object.StartDate.AddDays(-1);
_View.Raise(v => v.ShowSessionsClicked += null, EventArgs.Empty);
_LogDatabase.Verify(db => db.FetchSessions(It.IsAny<IList<LogClient>>(), It.IsAny<IList<LogSession>>(), It.IsAny<DateTime>(), It.IsAny<DateTime>()), Times.Never());
_View.Verify(v => v.ShowSessions(It.IsAny<IEnumerable<LogClient>>(), It.IsAny<IEnumerable<LogSession>>()), Times.Never());
}
}
}
| 24,692
|
https://github.com/WilliamXieCrypto/gravity-bridge/blob/master/solidity/contracts/ReentrantERC20.sol
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
gravity-bridge
|
WilliamXieCrypto
|
Solidity
|
Code
| 101
| 380
|
//SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.10;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./Gravity.sol";
// Reentrant evil erc20
contract ReentrantERC20 {
address state_gravityAddress;
constructor(address _gravityAddress) {
state_gravityAddress = _gravityAddress;
}
function transfer(address, uint256) public returns (bool) {
address[] memory addresses = new address[](0);
ValSignature[] memory sigs = new ValSignature[](0);
uint256[] memory uint256s = new uint256[](0);
address blankAddress = address(0);
bytes memory bytess = new bytes(0);
uint256 zero = 0;
LogicCallArgs memory args;
ValsetArgs memory valset;
{
args = LogicCallArgs(
uint256s,
addresses,
uint256s,
addresses,
address(0),
bytess,
zero,
bytes32(0),
zero
);
}
{
valset = ValsetArgs(addresses, uint256s, zero, zero, blankAddress);
}
Gravity(state_gravityAddress).submitLogicCall(valset, sigs, args);
return true;
}
}
| 35,815
|
https://github.com/SymbiFlow/f4pga-rr-graph/blob/master/rr_graph/channel.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
f4pga-rr-graph
|
SymbiFlow
|
Python
|
Code
| 3,650
| 11,310
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020-2022 F4PGA Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
"""
This file for packing tracks into channels.
It does *not* manage channel XML nodes.
Note channels go between switchboxes. Switchboxes cannot be at the last grid
coordinate.
Therefore, you need a grid size of at least 3 rows or cols to allow any
channels to exist. With a 3 width configuration you would get a channel of
length 0, connecting the switchbox at 0 to the switchbox at 1.
With above in mind, objects here entirely omit the last row/col and placing a
channel in the first is illegal.
Specifically:
* For CHANX: X=0 is invalid, X=grid.width-1 is invalid
* For CHANY: Y=0 is invalid, Y=grid.height-1 is invalid
"""
import pprint
import enum
import io
from collections import namedtuple
import lxml.etree as ET
from . import Position
from . import Size
from . import node_pos, single_element
from .utils.asserts import assert_eq
from .utils.asserts import assert_len_eq
from .utils.asserts import assert_type
from .utils.asserts import assert_type_or_none
# FIXME: doctests and static_property are not playing nice together.
# from . import static_property
static_property = property
class ChannelNotStraight(TypeError):
pass
_Track = namedtuple(
"Track", ("start", "end", "direction", "segment_id", "idx")
)
class Track(_Track):
"""
Represents a single CHANX or CHANY (track) within a channel.
IE The tracks of a x_list or y_list entry in <channels> element.
start: start Pos
end: end Pos
idx: XML index integer
"""
class Type(enum.Enum):
"""
subset of NodeType in graph2
"""
# Horizontal routing
X = 'CHANX'
# Vertical routing
Y = 'CHANY'
def __repr__(self):
return 'Track.Type.' + self.name
class Direction(enum.Enum):
INC = 'INC_DIR'
DEC = 'DEC_DIR'
BI = 'BI_DIR'
def __repr__(self):
return 'Track.Direction.' + self.name
def __new__(
cls,
start,
end,
direction=Direction.INC,
segment_id=0,
idx=None,
name=None,
type_hint=None,
):
"""Make most but not all attributes immutable"""
if not isinstance(start, Position):
start = Position(*start)
assert_type(start, Position)
if not isinstance(end, Position):
end = Position(*end)
assert_type(end, Position)
if start.x != end.x and start.y != end.y:
raise ChannelNotStraight(
"Track not straight! {}->{}".format(start, end)
)
assert_type(direction, cls.Direction)
assert_type(segment_id, int)
assert_type_or_none(idx, int)
assert_type_or_none(name, str)
assert_type_or_none(type_hint, cls.Type)
obj = _Track.__new__(cls, start, end, direction, segment_id, idx)
obj.name = name
obj.type_hint = type_hint
return obj
@static_property
def type(self):
"""Type of the channel.
Returns: Track.Type
>>> Track((1, 0), (10, 0)).type
Track.Type.X
>>> Track((0, 1), (0, 10)).type
Track.Type.Y
>>> Track((1, 1), (1, 1)).type
Traceback (most recent call last):
...
ValueError: Ambiguous type
>>> Track((1, 1), (1, 1), type_hint=Track.Type.X).type
Track.Type.X
>>> Track((1, 1), (1, 1), type_hint=Track.Type.Y).type
Track.Type.Y
"""
if self.type_hint:
return self.type_hint
guess = self.type_guess
if guess is None:
raise ValueError("Ambiguous type")
return guess
@static_property
def type_guess(self):
"""Type of the channel.
Returns: Track.Type
>>> Track((1, 0), (10, 0)).type_guess
Track.Type.X
>>> Track((0, 1), (0, 10)).type_guess
Track.Type.Y
>>> str(Track((1, 1), (1, 1)).type_guess)
'None'
"""
if self.start.x == self.end.x and self.start.y == self.end.y:
return None
elif self.start.x == self.end.x:
return Track.Type.Y
elif self.start.y == self.end.y:
return Track.Type.X
else:
assert False, self
def positions(self):
"""Generate all positions this track occupies"""
startx, endx = sorted([self.start.x, self.end.x])
starty, endy = sorted([self.start.y, self.end.y])
for x in range(startx, endx + 1):
for y in range(starty, endy + 1):
yield Position(x, y)
@static_property
def start0(self):
"""The non-constant start coordinate.
>>> Track((1, 0), (10, 0)).start0
1
>>> Track((0, 1), (0, 10)).start0
1
>>> Track((1, 1), (1, 1)).start0
Traceback (most recent call last):
...
ValueError: Ambiguous type
>>> Track((1, 1), (1, 1), type_hint=Track.Type.X).start0
1
>>> Track((10, 0), (1, 0)).start0
10
>>> Track((0, 10), (0, 1)).start0
10
"""
if self.type == Track.Type.X:
return self.start.x
elif self.type == Track.Type.Y:
return self.start.y
else:
assert False
@static_property
def end0(self):
"""The non-constant end coordinate.
>>> Track((1, 0), (10, 0)).end0
10
>>> Track((0, 1), (0, 10)).end0
10
>>> Track((1, 1), (1, 1)).end0
Traceback (most recent call last):
...
ValueError: Ambiguous type
>>> Track((1, 1), (1, 1), type_hint=Track.Type.X).end0
1
>>> Track((10, 0), (1, 0)).end0
1
>>> Track((0, 10), (0, 1)).end0
1
"""
if self.type == Track.Type.X:
return self.end.x
elif self.type == Track.Type.Y:
return self.end.y
else:
assert False, self.type
@static_property
def common(self):
"""The common coordinate value.
>>> Track((0, 0), (10, 0)).common
0
>>> Track((0, 0), (0, 10)).common
0
>>> Track((1, 1), (1, 1)).common
Traceback (most recent call last):
...
ValueError: Ambiguous type
>>> Track((1, 1), (1, 1), type_hint=Track.Type.X).common
1
>>> Track((10, 0), (0, 0)).common
0
>>> Track((0, 10), (0, 0)).common
0
>>> Track((4, 10), (4, 0)).common
4
"""
if self.type == Track.Type.X:
assert_eq(self.start.y, self.end.y)
return self.start.y
elif self.type == Track.Type.Y:
assert_eq(self.start.x, self.end.x)
return self.start.x
else:
assert False
@static_property
def length(self):
"""Length of the track.
>>> Track((0, 0), (10, 0)).length
10
>>> Track((0, 0), (0, 10)).length
10
>>> Track((1, 1), (1, 1)).length
0
>>> Track((10, 0), (0, 0)).length
10
>>> Track((0, 10), (0, 0)).length
10
"""
try:
return abs(self.end0 - self.start0)
except ValueError:
return 0
def new_idx(self, idx):
"""Create a new channel with the same start/end but new index value.
>>> s = (1, 4)
>>> e = (1, 8)
>>> c1 = Track(s, e, idx=0)
>>> c2 = c1.new_idx(2)
>>> assert_eq(c1.start, c2.start)
>>> assert_eq(c1.end, c2.end)
>>> c1.idx
0
>>> c2.idx
2
"""
return self.__class__(
self.start,
self.end,
self.direction,
self.segment_id,
idx,
name=self.name,
type_hint=self.type_hint,
)
def __repr__(self):
"""
>>> repr(Track((0, 0), (10, 0)))
'T((0,0), (10,0))'
>>> repr(Track((0, 0), (0, 10)))
'T((0,0), (0,10))'
>>> repr(Track((1, 2), (3, 2), idx=5))
'T((1,2), (3,2), 5)'
>>> repr(Track((1, 2), (3, 2), name="ABC"))
'T(ABC)'
>>> repr(Track((1, 2), (3, 2), idx=5, name="ABC"))
'T(ABC,5)'
"""
if self.name:
idx_str = ""
if self.idx is not None:
idx_str = ",{}".format(self.idx)
return "T({}{})".format(self.name, idx_str)
idx_str = ""
if self.idx is not None:
idx_str = ", {}".format(self.idx)
return "T(({},{}), ({},{}){})".format(
self.start.x, self.start.y, self.end.x, self.end.y, idx_str
)
def __str__(self):
"""
>>> str(Track((0, 0), (10, 0)))
'CHANX 0,0->10,0'
>>> str(Track((0, 0), (0, 10)))
'CHANY 0,0->0,10'
>>> str(Track((1, 2), (3, 2), idx=5))
'CHANX 1,2->3,2 @5'
>>> str(Track((1, 2), (3, 2), name="ABC"))
'ABC'
>>> str(Track((1, 2), (3, 2), idx=5, name="ABC"))
'ABC@5'
"""
idx_str = ""
if self.idx is not None:
idx_str = " @{}".format(self.idx)
if self.name:
return "{}{}".format(self.name, idx_str[1:])
return "{} {},{}->{},{}{}".format(
self.type.value, self.start.x, self.start.y, self.end.x,
self.end.y, idx_str
)
# Short alias.
T = Track
class ChannelGrid(dict):
"""
Functionality:
* Manages single type of track (either `CHANX` or `CHANY`).
* Manages channel width along grid.
* Allocates tracks within channels.
The `ChannelGrid` is indexed by `Position` and returns a sequence width all
the `Track`s at that position.
"""
def __init__(self, size, chan_type):
"""
size: Size representing tile grid width/height
chan_type: of Channels.Type
"""
self.chan_type = chan_type
self.size = Size(*size)
self.clear()
@property
def width(self):
"""Grid width
>>> g = ChannelGrid((6, 7), Track.Type.Y)
>>> g.width
6
"""
return self.size.width
@property
def height(self):
"""Grid height
>>> g = ChannelGrid((6, 7), Track.Type.Y)
>>> g.height
7
"""
return self.size.height
def column(self, x):
"""Get a y coordinate indexed list giving tracks at that x + y position"""
column = []
for y in range(0, self.height):
column.append(self[Position(x, y)])
return column
def row(self, y):
"""Get an x coordinate indexed list giving tracks at that x + y position"""
row = []
for x in range(0, self.width):
row.append(self[Position(x, y)])
return row
"""
dim_*: CHANX/CHANY abstraction functions
These can be used to write code that is not aware of specifics related to CHANX vs CHANY
"""
def dim_rc(self):
"""Get dimension a, the number of row/col positions"""
return {
Track.Type.X: self.height,
Track.Type.Y: self.width,
}[self.chan_type]
def dim_chanl(self):
"""Get dimension b, the number of valid track positions within a specific channel"""
return {
Track.Type.X: self.width,
Track.Type.Y: self.height,
}[self.chan_type]
def foreach_position(self):
"""Generate all valid placement positions (exclude border)"""
xmin, ymin = {
Track.Type.X: (1, 0),
Track.Type.Y: (0, 1),
}[self.chan_type]
for row in range(ymin, self.height):
for col in range(xmin, self.width):
yield Position(col, row)
def foreach_track(self):
"""Generate all current legal channel positions (exclude border)"""
for pos in self.foreach_position():
for ti, t in enumerate(self[pos]):
yield (pos, ti, t)
def slicen(self):
"""Get grid width or height corresponding to chanx/chany type"""
return {
Track.Type.X: self.height,
Track.Type.Y: self.width,
}[self.chan_type]
def slice(self, i):
"""Get row or col corresponding to chanx/chany type"""
return {
Track.Type.X: self.row,
Track.Type.Y: self.column,
}[self.chan_type](
i
)
def track_slice(self, t):
"""Get the row or column the track runs along"""
return {
Track.Type.X: self.row,
Track.Type.Y: self.column,
}[t.type](
t.common
)
def tracks(self):
"""Get all channels in a set"""
ret = set()
for _pos, _ti, t in self.foreach_track():
ret.add(t)
return ret
def validate_pos(self, pos, msg=''):
"""
A channel must go between switchboxes (where channels can cross)
Channels are upper right of tile
Therefore, the first position in a channel cannot have a track because
there is no proceeding switchbox"""
if msg:
msg = msg + ': '
# Gross error out of grid
if pos.x < 0 or pos.y < 0 or pos.x >= self.width or pos.y >= self.height:
raise ValueError(
"%sGrid %s, point %s out of grid size coordinate" %
(msg, self.size, pos)
)
if self.chan_type == Track.Type.X and pos.x == 0:
raise ValueError("%sInvalid CHANX x=0 point %s" % (msg, pos))
if self.chan_type == Track.Type.Y and pos.y == 0:
raise ValueError("%sInvalid CHANY y=0 point %s" % (msg, pos))
def create_track(self, t, idx=None):
"""
Channel allocator
Finds an optimal place to put the channel, increasing the channel width if necessary
If idx is given, it must go there
Throw exception if location is already occupied
>>> g = ChannelGrid((11, 11), Track.Type.X)
>>> # Adding the first channel
>>> g.create_track(Track((1, 6), (4, 6), name="A"))
T(A,0)
>>> g[(1,6)]
[T(A,0)]
>>> g[(2,6)]
[T(A,0)]
>>> g[(4,6)]
[T(A,0)]
>>> g[(5,6)]
[None]
>>> # Adding second non-overlapping second channel
>>> g.create_track(Track((5, 6), (7, 6), name="B"))
T(B,0)
>>> g[(4,6)]
[T(A,0)]
>>> g[(5,6)]
[T(B,0)]
>>> g[(7,6)]
[T(B,0)]
>>> g[(8,6)]
[None]
>>> # Adding third channel which overlaps with second channel
>>> g.create_track(Track((5, 6), (7, 6), name="T"))
T(T,1)
>>> g[(4,6)]
[T(A,0), None]
>>> g[(5,6)]
[T(B,0), T(T,1)]
>>> g[(7,6)]
[T(B,0), T(T,1)]
>>> # Adding a channel which overlaps, but is a row over
>>> g.create_track(Track((5, 7), (7, 7), name="D"))
T(D,0)
>>> g[(5,6)]
[T(B,0), T(T,1)]
>>> g[(5,7)]
[T(D,0)]
>>> # Adding fourth channel which overlaps both the first
>>> # and second+third channel
>>> g.create_track(Track((3, 6), (6, 6), name="E"))
T(E,2)
>>> g[(2,6)]
[T(A,0), None, None]
>>> g[(3,6)]
[T(A,0), None, T(E,2)]
>>> g[(6,6)]
[T(B,0), T(T,1), T(E,2)]
>>> g[(7,6)]
[T(B,0), T(T,1), None]
>>> # This channel fits in the hole left by the last one.
>>> g.create_track(Track((1, 6), (3, 6), name="F"))
T(F,1)
>>> g[(1,6)]
[T(A,0), T(F,1), None]
>>> g[(2,6)]
[T(A,0), T(F,1), None]
>>> g[(3,6)]
[T(A,0), T(F,1), T(E,2)]
>>> g[(4,6)]
[T(A,0), None, T(E,2)]
>>> # Add another channel which causes a hole
>>> g.create_track(Track((1, 6), (7, 6), name="G"))
T(G,3)
>>> g[(1,6)]
[T(A,0), T(F,1), None, T(G,3)]
>>> g[(2,6)]
[T(A,0), T(F,1), None, T(G,3)]
>>> g[(3,6)]
[T(A,0), T(F,1), T(E,2), T(G,3)]
>>> g[(4,6)]
[T(A,0), None, T(E,2), T(G,3)]
>>> g[(5,6)]
[T(B,0), T(T,1), T(E,2), T(G,3)]
>>> g[(6,6)]
[T(B,0), T(T,1), T(E,2), T(G,3)]
>>> g[(7,6)]
[T(B,0), T(T,1), None, T(G,3)]
>>> g[(8,6)]
[None, None, None, None]
"""
assert t.idx is None
force_idx = idx
self.validate_pos(t.start, 'start')
self.validate_pos(t.end, 'end')
if t.type_guess != self.chan_type:
if t.length != 0:
raise TypeError(
"Can only add channels of type {} which {} ({}) is not.".
format(self.chan_type, t, t.type)
)
else:
t.type_hint = self.chan_type
c = self.track_slice(t)
assert_len_eq(c)
# Find start and end
s, e = min(t.start0, t.end0), max(t.start0, t.end0)
assert e >= s, (e, '>=', s)
assert s < len(c), (s, '<', len(c), c)
assert e < len(c), (e + 1, '<', len(c), c)
# Find a idx that this channel fits.
# Normally start at first channel (0) unless forcing to a specific channel
max_idx = force_idx if force_idx is not None else 0
while True:
# Check each position if the track can fit
# Expanding channel width as required index grows
for p in c[s:e + 1]:
while len(p) < max_idx + 1:
p.append(None)
# Can't place here?
if p[max_idx] is not None:
# Grow track width
if force_idx is not None:
raise IndexError(
"Can't fit channel at index %d" % force_idx
)
max_idx += 1
break
# Was able to place into all locations
else:
break
# Make sure everything has the same length.
for p in c:
while len(p) < max_idx + 1:
p.append(None)
assert_len_eq(c)
t = t.new_idx(max_idx)
assert t.idx == max_idx
for p in c[s:e + 1]:
p[t.idx] = t
return t
def pretty_print(self):
"""
If type == Track.Type.X
A--AC-C
B-----B
D--DE-E
F-----F
If type == Track.Type.Y
AB DF
|| ||
|| ||
A| D|
C| E|
|| ||
CB EF
"""
def get_str(t):
if not t:
s = ""
elif t.name:
s = t.name
else:
s = str(t)
return s
# Work out how many characters the largest label takes up.
s_maxlen = 1
for row in range(0, self.height):
for col in range(0, self.width):
for t in self[(col, row)]:
s_maxlen = max(s_maxlen, len(get_str(t)))
assert s_maxlen > 0, s_maxlen
s_maxlen += 3
if self.chan_type == Track.Type.Y:
beg_fmt = "{:^%i}" % s_maxlen
end_fmt = beg_fmt
mid_fmt = beg_fmt.format("||")
elif self.chan_type == Track.Type.X:
beg_fmt = "{:>%i}>" % (s_maxlen - 1)
end_fmt = "->{:<%i}" % (s_maxlen - 2)
mid_fmt = "-" * s_maxlen
else:
assert False
non_fmt = " " * s_maxlen
"""
rows[row][col][c]
row: global row location
col: column of output
c: character showing occupation along a track
Channel width may vary across tiles, but all columns within that region
should have the same length
"""
rows = []
for y in range(0, self.height):
cols = []
for x in range(0, self.width):
# Header
hdri = {Track.Type.X: x, Track.Type.Y: y}[self.chan_type]
channels = [("|{: ^%i}" % (s_maxlen - 1)).format(hdri)]
for t in self[(x, y)]:
if not t:
fmt = non_fmt
elif t.start == t.end:
s = get_str(t)
channels.append(
"{} ".format(
"".join(
[
beg_fmt.format(s),
mid_fmt.format(s),
end_fmt.format(s),
]
)[:s_maxlen - 1]
)
)
continue
elif t.start == (x, y):
fmt = beg_fmt
elif t.end == (x, y):
fmt = end_fmt
else:
fmt = mid_fmt
channels.append(fmt.format(get_str(t)))
cols.append(channels)
rows.append(cols)
# Dump the track state as a string
f = io.StringIO()
def p(*args, **kw):
print(*args, file=f, **kw)
if self.chan_type == Track.Type.X:
for r in range(0, len(rows)):
assert_len_eq(rows[r])
# tracks + 1 for header
track_rows = len(rows[r][0])
for tracki in range(0, track_rows):
for c in range(0, len(rows[r])):
p(rows[r][c][tracki], end="")
# Close header
if tracki == 0:
p("|", end="")
p()
p("\n")
elif self.chan_type == Track.Type.Y:
for r in range(0, len(rows)):
# tracks + 1 for header
for c in range(0, len(rows[r])):
track_cols = len(rows[r][c])
p("|*", end="")
for tracki in range(0, track_cols):
p(rows[r][c][tracki], end="")
# Close header
if tracki == 0:
p("|", end="")
p(" ", end="")
p("")
# p("|*|")
else:
assert False
return f.getvalue()
def clear(self):
"""Remove tracks from all currently occupied positions, making channel width 0"""
for x in range(0, self.width):
for y in range(0, self.height):
self[Position(x, y)] = []
def check(self):
"""Self integrity check"""
# Verify uniform track length
if self.chan_type == Track.Type.X:
for y in range(self.height):
assert_len_eq(self.row(y))
elif self.chan_type == Track.Type.Y:
for x in range(self.width):
assert_len_eq(self.column(x))
else:
assert False
def density(self):
"""Return (number occupied positions, total number positions)"""
occupied = 0
net = 0
for _pos, _ti, t in self.foreach_track():
net += 1
if t is not None:
occupied += 1
return occupied, net
def fill_empty(self, segment_id, name=None):
tracks = []
for pos, ti, t in self.foreach_track():
if t is None:
tracks.append(
self.create_track(
Track(
pos,
pos,
segment_id=segment_id,
name=name,
type_hint=self.chan_type,
direction=Track.Direction.BI
),
idx=ti
)
)
return tracks
def channel_widths(self):
"""Return (min channel width, max channel width, row/col widths)"""
cwmin = float('+inf')
cwmax = float('-inf')
xy_list = []
for i in range(self.slicen()):
# track width should be consistent along a slice
# just take the first element
loc = self.slice(i)[0]
cwmin = min(cwmin, len(loc))
cwmax = max(cwmax, len(loc))
xy_list.append(len(loc))
return (cwmin, cwmax, xy_list)
def assert_width(self, width):
"""Assert all channels have specified --route_chan_width"""
for pos in self.foreach_position():
tracks = self[pos]
assert len(
tracks
) == width, 'Bad width Position(x=%d, y=%d): expect %d, got %d' % (
pos.x, pos.y, width, len(tracks)
)
def assert_full(self):
"""Assert all allocated channels are fully occupied"""
self.check()
# occupied, net = self.density()
# print("Occupied %d / %d" % (occupied, net))
for pos, ti, t in self.foreach_track():
assert t is not None, 'Unoccupied Position(x=%d, y=%d) track=%d' % (
pos.x, pos.y, ti
)
class Channels:
"""Holds all channels for the whole grid (X + Y)"""
def __init__(self, size):
self.size = size
self.x = ChannelGrid(size, Track.Type.X)
self.y = ChannelGrid(size, Track.Type.Y)
def create_diag_track(self, start, end, segment_id, idx=None):
# Actually these can be tuple as well
# assert_type(start, Pos)
# assert_type(end, Pos)
# Create track(s)
try:
return (self.create_xy_track(start, end, segment_id, idx=idx), )
except ChannelNotStraight:
assert idx is None, idx
corner = (start.x, end.y)
ta = self.create_xy_track(start, corner, segment_id)[0]
tb = self.create_xy_track(corner, end, segment_id)[0]
return (ta, tb)
def create_xy_track(
self,
start,
end,
segment_id,
idx=None,
name=None,
typeh=None,
direction=None
):
"""
idx: None to automatically allocate
"""
# Actually these can be tuple as well
# assert_type(start, Pos)
# assert_type(end, Pos)
# Create track(s)
# Will throw exception if not straight
t = Track(
start,
end,
segment_id=segment_id,
name=name,
type_hint=typeh,
direction=direction
)
# Add the track to associated channel list
# Get the track now with the index assigned
t = {
Track.Type.X: self.x.create_track,
Track.Type.Y: self.y.create_track
}[t.type](
t, idx=idx
)
# print('create %s %s to %s idx %s' % (t.type, start, end, idx))
assert t.idx is not None
if typeh:
assert t.type == typeh, (t.type.value, typeh)
return t
def pad_channels(self, segment_id):
tracks = []
tracks.extend(self.x.fill_empty(segment_id))
tracks.extend(self.y.fill_empty(segment_id))
return tracks
def pretty_print(self):
s = ''
s += 'X\n'
s += self.x.pretty_print()
s += 'Y\n'
s += self.y.pretty_print()
return s
def clear(self):
"""Remove all channels"""
self.x.clear()
self.y.clear()
def from_xml_nodes(self, nodes_xml):
"""Add channels from <nodes> CHANX/CHANY"""
for node_xml in nodes_xml:
ntype = node_xml.get('type')
if ntype not in ('CHANX', 'CHANY'):
continue
ntype_e = Track.Type(ntype)
direction = Track.Direction(node_xml.get('direction'))
loc = single_element(node_xml, 'loc')
idx = int(loc.get('ptc'))
pos_low, pos_high = node_pos(node_xml)
# print('Importing %s @ %s:%s :: %d' % (ntype, pos_low, pos_high, idx))
segment_xml = single_element(node_xml, 'segment')
segment_id = int(segment_xml.get('segment_id'))
# idx will get assigned when adding to track
try:
self.create_xy_track(
pos_low,
pos_high,
segment_id,
idx=idx,
# XML has no name concept. Should it?
name=None,
typeh=ntype_e,
direction=direction
)
except Exception:
print("Bad XML: %s" % (ET.tostring(node_xml)))
raise
def to_xml_channels(self, channels_xml):
channels_xml.clear()
# channel entry
cw_xmin, cw_xmax, x_lists = self.x.channel_widths()
cw_ymin, cw_ymax, y_lists = self.y.channel_widths()
cw_max = max(cw_xmax, cw_ymax)
ET.SubElement(
channels_xml, 'channel', {
'chan_width_max': str(cw_max),
'x_min': str(cw_xmin),
'x_max': str(cw_xmax),
'y_min': str(cw_ymin),
'y_max': str(cw_ymax),
}
)
# x_list / y_list tries
for i, info in enumerate(x_lists):
ET.SubElement(
channels_xml, 'x_list', {
'index': str(i),
'info': str(info)
}
)
for i, info in enumerate(y_lists):
ET.SubElement(
channels_xml, 'y_list', {
'index': str(i),
'info': str(info)
}
)
def to_xml(self, xml_graph):
self.to_xml_channels(single_element(xml_graph, 'channels'))
def TX(start, end, idx=None, name=None, direction=None, segment_id=None):
if direction is None:
direction = Track.Direction.INC
if segment_id is None:
segment_id = 0
return T(
start,
end,
direction=direction,
segment_id=segment_id,
idx=idx,
name=name,
type_hint=Track.Type.X,
)
def TY(start, end, idx=None, name=None, direction=None, segment_id=None):
if direction is None:
direction = Track.Direction.INC
if segment_id is None:
segment_id = 0
return T(
start,
end,
direction=direction,
segment_id=segment_id,
idx=idx,
name=name,
type_hint=Track.Type.Y,
)
def docprint(x):
pprint.pprint(x.splitlines())
def create_test_channel_grid():
g = ChannelGrid((6, 3), Track.Type.X)
g.create_track(TX((1, 0), (5, 0), name="AA"))
g.create_track(TX((1, 0), (3, 0), name="BB"))
g.create_track(TX((2, 0), (5, 0), name="CC"))
g.create_track(TX((1, 0), (1, 0), name="DD"))
g.create_track(TX((1, 1), (3, 1), name="aa"))
g.create_track(TX((4, 1), (5, 1), name="bb"))
g.create_track(TX((1, 1), (5, 1), name="cc"))
g.check()
return g
def test_x_auto():
"""
>>> docprint(test_x_auto())
['| 0 | 1 | 2 | 3 | 4 | 5 |',
' AA>---------------->AA ',
' BB>------>BB ',
' DD CC>----------->CC ',
'',
'',
'| 0 | 1 | 2 | 3 | 4 | 5 |',
' aa>------>aa bb>->bb ',
' cc>---------------->cc ',
'',
'',
'| 0 | 1 | 2 | 3 | 4 | 5 |',
'',
'']
"""
g = create_test_channel_grid()
return g.pretty_print()
def test_pad():
"""
>>> docprint(test_pad())
['| 0 | 1 | 2 | 3 | 4 | 5 |',
' AA>---------------->AA ',
' BB>------>BB XX XX ',
' DD CC>----------->CC ',
'',
'',
'| 0 | 1 | 2 | 3 | 4 | 5 |',
' aa>------>aa bb>->bb ',
' cc>---------------->cc ',
'',
'',
'| 0 | 1 | 2 | 3 | 4 | 5 |',
'',
'']
"""
g = create_test_channel_grid()
g.fill_empty(0, name='XX')
g.check()
return g.pretty_print()
def test_x_manual():
"""
>>> pprint.pprint(test_x_manual().splitlines())
['| 0 | 1 | 2 | 3 | 4 | 5 |',
' AA>---------------->AA ',
' BB>------>BB ',
' DD CC>----------->CC ',
'',
'',
'| 0 | 1 | 2 | 3 | 4 | 5 |',
' aa>------>aa bb>->bb ',
' cc>---------------->cc ',
'',
'',
'| 0 | 1 | 2 | 3 | 4 | 5 |',
'',
'']
"""
g = ChannelGrid((6, 3), Track.Type.X)
g.create_track(TX((1, 0), (5, 0), name="AA"), idx=0)
g.create_track(TX((1, 0), (3, 0), name="BB"), idx=1)
g.create_track(TX((2, 0), (5, 0), name="CC"), idx=2)
g.create_track(TX((1, 0), (1, 0), name="DD"), idx=2)
g.create_track(TX((1, 1), (3, 1), name="aa"), idx=0)
g.create_track(TX((4, 1), (5, 1), name="bb"), idx=0)
g.create_track(TX((1, 1), (5, 1), name="cc"), idx=1)
try:
g.create_track(TX((1, 1), (5, 1), name="dd"), idx=1)
assert False, "Should have failed to place"
except IndexError:
pass
g.check()
return g.pretty_print()
def test_y_auto():
"""
>>> docprint(test_y_auto())
['|*| 0 | |*| 0 | |*| 0 | ',
'|*| 1 | AA BB DD |*| 1 | aa cc |*| 1 | ',
'|*| 2 | || || CC |*| 2 | || || |*| 2 | ',
'|*| 3 | || BB || |*| 3 | aa || |*| 3 | ',
'|*| 4 | || || |*| 4 | bb || |*| 4 | ',
'|*| 5 | AA CC |*| 5 | bb cc |*| 5 | ']
"""
g = ChannelGrid((3, 6), Track.Type.Y)
g.create_track(TY((0, 1), (0, 5), name="AA"))
g.create_track(TY((0, 1), (0, 3), name="BB"))
g.create_track(TY((0, 2), (0, 5), name="CC"))
g.create_track(TY((0, 1), (0, 1), name="DD"))
g.create_track(TY((1, 1), (1, 3), name="aa"))
g.create_track(TY((1, 4), (1, 5), name="bb"))
g.create_track(TY((1, 1), (1, 5), name="cc"))
g.check()
return g.pretty_print()
if __name__ == "__main__":
import doctest
print('doctest: begin')
failure_count, test_count = doctest.testmod()
assert test_count > 0
assert failure_count == 0, "Doctests failed!"
print('doctest: end')
| 36,623
|
https://github.com/atkins126/ByteScout-SDK-SourceCode/blob/master/Sensitive Data Suite/VB.NET/Remove Sensitive Data From Image/Module1.vb
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
ByteScout-SDK-SourceCode
|
atkins126
|
Visual Basic
|
Code
| 233
| 651
|
'*******************************************************************************************'
' '
' Download Free Evaluation Version From: https://bytescout.com/download/web-installer '
' '
' Also available as Web API! Get free API Key https://app.pdf.co/signup '
' '
' Copyright © 2017-2020 ByteScout, Inc. All rights reserved. '
' https://www.bytescout.com '
' https://www.pdf.co '
'*******************************************************************************************'
Imports System.IO
Imports System.Drawing
Imports Bytescout.PDFExtractor
Class Program
Shared Sub Main(ByVal args As String())
Dim input As String = "scanned_sample_EmailSSN.png"
Dim result As String = "result.png"
Using detector As New SensitiveDataDetector("demo", "demo")
' Enable OCR mode And provide path to data folder
detector.OCRMode = OCRMode.Auto
detector.OCRLanguageDataFolder = "c:\Program Files\Bytescout PDF Extractor SDK\ocrdata_best\"
detector.LoadDocumentFromFile(input)
' Detect sensitive data
Dim detectionResults As SensitiveDataDetectionResults = detector.PerformDetection()
If detectionResults.DetectedItems.Length > 0 Then
Using image As Image = Image.FromFile(input)
' Create new bitmap, as graphics object require indexed pixel format
Using newBitmap As New Bitmap(image.Width, image.Height)
Using g As Graphics = Graphics.FromImage(newBitmap)
g.DrawImage(image, 0, 0)
For Each detectedItem As DetectedSensitiveItem In detectionResults.DetectedItems
' Convert coordinates from Points (1/72") to display pixels
Dim rect As Rectangle = New Rectangle(
CInt(detectedItem.Rectangle.X * 96 / 72),
CInt(detectedItem.Rectangle.Y * 96 / 72),
CInt(detectedItem.Rectangle.Width * 96 / 72),
CInt(detectedItem.Rectangle.Height * 96 / 72))
' Paint over the detected item with a white Or black brush
g.FillRectangle(Brushes.Black, rect)
Next
End Using
newBitmap.Save(result)
End Using
End Using
End If
End Using
' Open output file with attached application
Dim processStartInfo As New ProcessStartInfo(result)
processStartInfo.UseShellExecute = True
Process.Start(processStartInfo)
End Sub
End Class
| 20,695
|
https://github.com/yafully/Simple-web-site/blob/master/bak/20170621/app_chat.js
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Simple-web-site
|
yafully
|
JavaScript
|
Code
| 688
| 3,770
|
'use strict'
const express = require('express');
const app = express();
const http = require('http').Server(app);
const server = require('socket.io')(http);
const chatuserModel = require('./modules/chatuserSetup');
const silly = require("silly-datetime");
const url = require("url");
const qs = require('querystring');
const cookie = require('cookie');
const cookieParser = require('cookie-parser');
const session = require('express-session');//Session
var RedisStore = require('connect-redis')(session);//载入redis session中间件
var sessionStore = new RedisStore({
host:'127.0.0.1',
port:'6379',
db:1 //此属性可选。redis可以进行分库操作。若无此参数,则不进行分库
});
server.use(function(socket, next) {
var data = socket.handshake || socket.request;
if (data.headers.cookie) {
data.cookie = cookie.parse(data.headers.cookie);
data.sessionID = cookieParser.signedCookie(data.cookie['express.sid'], 'secret');
data.sessionStore = sessionStore;
sessionStore.get(data.sessionID, function (err, session) {
if (err || !session) {
return next(new Error('session not found'))
} else {
data.session = session;
data.session.id = data.sessionID;
console.log(data.session);
console.log(99999999);
next();
}
});
} else {
return next(new Error('Missing cookie headers'));
}
});
const roomInfo = {};
const clients = [];
//staff
//socket.broadcast.emit("userIn","system@: 【"+client.name+"】-- a newer ! Let's welcome him ~");//广播(不包含当前客户端)
//server.sockets.emit('userIn', "this is a test");//广播(且包含当前客户端)
//socket.broadcast.to('game').emit('message', 'nice game');//在房间广播(不包含当前客户端)
//server.sockets.in('game').emit('message', 'cool game');//在房间广播(包含当前客户端)
//io.sockets.socket(socketid).emit('message', 'for your eyes only');//发送给指定客户端
// 获取上线的客服
function getStaff(room,ssocket){
//聚合分组客服人员和普通用户
chatuserModel.aggregate([
{
$match: {
"roomname":room
}
},
{
$project : {
roomname:1,
users : 1
}
},
{
"$unwind": "$users"
},
//{"$sort": { "users.status":1} },
{
$project:
{
myuser:{
_id:null,
email:'$users.email',
name:'$users.name',
status:'$users.status',
role:'$users.role',
staff:{
$cond: { if: {$in: ["$users.role",[ 1 ]]}, then: true, else: false }
}
}
}
},
{
$group:
{
_id: '$roomname',
staff: { $addToSet: {
$cond: { if: {$eq: [ "$myuser.staff",true ]}, then: "$myuser", else: null } }
},
staffTotal:{$sum:{
$cond: { if: {$eq: [ "$myuser.staff",true ]}, then: 1, else: 0 }
}},
staffOnline:{$sum:{
$cond: [ {$and : [ {$eq: [ "$myuser.status",true ]},{$eq: [ "$myuser.staff",true ]} ]},1,0]
}},
custom: { $addToSet: {
$cond: { if: {$eq: [ "$myuser.staff",false ]}, then: "$myuser", else: null } }
},
customTotal:{$sum:{
$cond: { if: {$eq: [ "$myuser.staff",false ]}, then: 1, else: 0 }
}},
customOnline:{$sum:{
$cond: [ {$and : [ {$eq: [ "$myuser.status",true ]},{$eq: [ "$myuser.staff",false ]} ]},1,0]
}}
}
}
]).exec(function(err, doc) {
if(err){console.log(err); return;}
let customData = doc[0].custom;
let customOline = doc[0].customOnline;
ssocket.broadcast.to(room).emit('staff_list',doc[0].staff,doc[0].staffOnline,customData,customOline); //广播更新客服人员列表
ssocket.emit('staff_list',doc[0].staff,doc[0].staffOnline,customData,customOline); //更新本机客服人员列表
});
}
//注销 下线处理
function statusSetDown(room,client,ssocket){
// let oMail = client.email;
// let oName = client.name;
let data = {};
data.email = client.email;
data.name = client.name;
chatuserModel.updateOne({"roomname":room,'users.email': data.email}, {$set: {'users.$.status': false}},function(err,doc){
if(err){
console.log(err);
}else{
console.log(data.name+ " is down");
ssocket.broadcast.to(room).emit('userOut',data);//向房间广播用户下线
getStaff(room,ssocket);
}
});
}
//存储聊天记录
function storeContent(room,oMail,chats,time,to){ // 保存聊天记录
chatuserModel.update(
{"roomname":room,'users.email': oMail},
{$push: {'users.$.content': {chatlog:chats,date:time,touser:to?to:'all'}}},
function(err,doc){
if(err){
console.log(err);
}else{
console.log("store chatlog success!");
}
});
}
server.on('connection',function(socket){ // server listening
console.log('socket.id '+socket.id+ ': connecting'); // console-- message\
let headurl = socket.request.headers.referer;
let queryUrl = url.parse(headurl).query;//获取房间名
let query = qs.parse(queryUrl);
let roomId = query.site;
let session = socket.handshake.session;//获取socket里面的session
if(typeof session.chatauth =='undefined'){//session丢失
socket.broadcast.to(roomId).emit("logout");
console.log('socket offline!');
}else{
socket.broadcast.to(roomId).emit("login");
console.log('socket online!');
}
getStaff(roomId,socket);
socket.join(roomId);//加入房间
//构造用户对象client
var client = {
Socket: socket,
id:socket.id,
email: '----',
name:'----'
};
//接收客户端聊天页面打开时发送过来的用户信息并广播
socket.on("message",function(email,name,sid){
//console.log(sid);
//console.log('778888777777');
// session_store.get("user", function(error, session){
// console.log(session);
// });
client.email = email;// 接收user name
client.name = name;
clients.push(client);//保存此client
if (!roomInfo[roomId]) {
roomInfo[roomId] = [];
}
//console.log(roomInfo[roomId]);
// let hasUser = roomInfo[roomId].some(function(item){
// return item.email == email;
// });
// if(!hasUser){
// }
roomInfo[roomId].push(client);
//console.log(roomInfo);
////socket.broadcast.emit("userIn","system@: ["+client.name+"]-- a newer ! Let's welcome him ~");//广播(不包含当前客户端)
////server.sockets.emit('userIn', "this is a test");//广播(且包含当前客户端)
////socket.broadcast.to('my room').emit('event_name', data);}//2. 向another room广播一个事件,在此房间所有客户端都会收到消息//注意:和上面对比,这里是从服务器的角度来提交事件
////io.sockets.in('another room').emit('event_name', data);//向所有客户端广播
let data = {};
data.email = client.email;
data.name = client.name;
socket.broadcast.to(roomId).emit("userIn",data);
//console.log(roomInfo);
});
//广播客户传来的数据并处理--群聊
socket.on('say',function(content){ // 群聊阶段
console.log("server: "+client.name + " say : " + content);
//置入数据库
var time = silly.format(new Date(), 'YYYY-MM-DD HH:mm');
socket.emit('user_say',client.name,client.email,time,content);
socket.broadcast.to(roomId).emit('user_say',client.name,client.email,time,content);
storeContent(roomId,client.email,content,new Date()); //保存聊天记录
});
//私聊
socket.on("say_private",function(fromuser,touser,content){ //私聊阶段
let toSocket = [];
let fromSocket =[];
let tomail = "";
let time = silly.format(new Date(), 'YYYY-MM-DD HH:mm');
for(var n in roomInfo[roomId]){
//找到对方数据
if(roomInfo[roomId][n].name === touser){ // get touser -- socket
toSocket.push(roomInfo[roomId][n].Socket);
tomail = roomInfo[roomId][n].email;
}
//找到我方数据
if(roomInfo[roomId][n].email === client.email){
fromSocket.push(roomInfo[roomId][n].Socket);
}
}
//console.log(toSocket);
// console.log(touser);
// console.log("toSocket: "+toSocket.id);
// console.log("my socket: "+socket.id);
if(typeof toSocket != "undefined"){//id不为空且不是自己
if(client.email != tomail){//这里不能用socket.id来判断,因为新开一个选项卡socket.id就不一样了
fromSocket.forEach(function(item, index) {// 数据返回给 fromuser这里用数组遍历是因为目标对象可能开了N个页面需要广播
item.emit("say_private_done",touser,content,time); //数据返回给fromuser
});
toSocket.forEach(function(item, index) {
item.emit("sayToYou",fromuser,content,time);
// 数据返回给 touser这里用数组遍历是因为目标对象可能开了N个页面需要广播
});
storeContent(roomId,client.email,content,new Date(),tomail);//保存聊天记录
}else{
console.log('不能给自己发消息');
socket.emit("erro",'不能给自己发消息.');
//server.to(roomId).socket.emit('erro', fromuser, '不能给自己发消息.');
}
//console.log(fromuser+" 给 "+touser+"发了份私信: "+content);
}else{
socket.emit("erro",'对方不在线,无法收到消息.');
}
});
//断开链接
socket.on('disconnect',function(){ // Event: disconnect
if(Object.keys(roomInfo).length>0){
for(let i=0;i<roomInfo[roomId].length;i++){//删除这个房间内email为当前email的所有信息
if(roomInfo[roomId][i].email === client.email){
roomInfo[roomId].splice(i, 1);
i--;
}
}
statusSetDown(roomId,client,socket);//用户下线状态更新
socket.leave(roomId);
console.log(client.name + ': disconnect');
}
});
});
exports.listen = function(charServer){
return server.listen(charServer); // listening
};
| 22,299
|
https://github.com/bitfieldconsulting/ftl-fundamentals-tomdoherty/blob/master/calculator.go
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
ftl-fundamentals-tomdoherty
|
bitfieldconsulting
|
Go
|
Code
| 182
| 329
|
// Package calculator provides a library for simple calculations in Go.
package calculator
import (
"fmt"
"math"
)
// Add takes two numbers and returns the result of adding them together.
func Add(a, b float64) float64 {
return a + b
}
// Subtract takes two numbers and returns the result of subtracting the second
// from the first.
func Subtract(a, b float64) float64 {
return a - b
}
// Multiply takes two numbers and returns the result of subtracting the second
// from the first.
func Multiply(a, b float64) float64 {
return a * b
}
// Divide takes two numbers and returns the result of subtracting the second
// from the first.
func Divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("invalid inputs(%f, %f): division by zero error", a, b)
}
return a / b, nil
}
// Sqrt takes one numbers and returns the square root
func Sqrt(a float64) (float64, error) {
if a < 0 {
return 0, fmt.Errorf("invalid input(%f): input must be greater than zero", a)
}
return math.Sqrt(a), nil
}
| 22,844
|
https://github.com/shaoboyan/aquarium-test/blob/master/src/aquarium-optimized/d3d12/ProgramD3D12.cpp
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
aquarium-test
|
shaoboyan
|
C++
|
Code
| 59
| 323
|
#include "ProgramD3D12.h"
#include "ContextD3D12.h"
#include <string.h>
#include <fstream>
ProgramD3D12::ProgramD3D12(ContextD3D12 *context, std::string vId, std::string fId)
: Program(vId, fId), vertexShader(nullptr), pixelShader(nullptr), context(context)
{
}
ProgramD3D12::~ProgramD3D12() {}
void ProgramD3D12::loadProgram()
{
std::ifstream VertexShaderStream(vId, std::ios::in);
std::string VertexShaderCode((std::istreambuf_iterator<char>(VertexShaderStream)),
std::istreambuf_iterator<char>());
VertexShaderStream.close();
// Read the Fragment Shader code from the file
std::ifstream FragmentShaderStream(fId, std::ios::in);
std::string FragmentShaderCode((std::istreambuf_iterator<char>(FragmentShaderStream)),
std::istreambuf_iterator<char>());
FragmentShaderStream.close();
vertexShader = context->createShaderModule("VS", VertexShaderCode);
pixelShader = context->createShaderModule("PS", FragmentShaderCode);
}
| 28,140
|
https://github.com/naniastutitriana/sp_ginjal/blob/master/application/controllers/Ruleds.php
|
Github Open Source
|
Open Source
|
MIT
| null |
sp_ginjal
|
naniastutitriana
|
PHP
|
Code
| 67
| 383
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Ruleds extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('Ruleds_model');
}
public function index(){
$data['ruleds_data'] = $this->Ruleds_model->get_ruleds();
$this->load->view('admin/ruleds', $data);
}
public function create(){
if (isset($_POST['submit'])){
$this->Ruleds_model->insert_ruleds();
redirect('ruleds/index');
}
$data['contents']='admin/tambah_ruleds';
$this->load->view('templates/index', $data);
}
public function edit(){
if (isset($_POST['submit'])){
$this->Ruleds_model->edit_ruleds();
redirect('ruleds/index');
}
$id = $this->uri->segment(3);
$data['ruleds'] = $this->Ruleds_model->getById($id);
$this->load->view('admin/ruleds_edit', $data);
}
public function hapus(){
$id = $this->uri->segment(3);
$this->Ruleds_model->hapus_ruleds($id);
redirect('ruleds/index');
}
}
?>
| 31,928
|
https://github.com/OutbackGames/KGB-Hacker/blob/master/main.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
KGB-Hacker
|
OutbackGames
|
C++
|
Code
| 28
| 94
|
#include "TripleX.h"
using namespace OutbackGames::CPP::TripleX;
TripleX game = TripleX();
TripleX* gamePtr = &game;
int main(){
srand(time(NULL));
gamePtr -> PrintIntro();
gamePtr -> GameLoop();
return 0;
}
//veni vidi vici
| 13,664
|
https://github.com/ZJNixiang/VKPreferences/blob/master/VKHDHeaders/ReportCommentMethod-Protocol.h
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
VKPreferences
|
ZJNixiang
|
Objective-C
|
Code
| 44
| 146
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "IVKRequest.h"
#import "NSObject.h"
@class NSNumber;
@protocol ReportCommentMethod <NSObject, IVKRequest>
@property(retain, nonatomic) NSNumber *reason;
@property(retain, nonatomic) NSNumber *comment_id;
@property(retain, nonatomic) NSNumber *owner_id;
@end
| 38,443
|
https://github.com/TotalJTM/PrimitierModdingFramework/blob/master/Dumps/PrimitierDumpV1.0.1/Valve/VR/InteractionSystem/Sample/RenderModelChangerUI.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
PrimitierModdingFramework
|
TotalJTM
|
C#
|
Code
| 86
| 303
|
/*
* Generated code file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty
*/
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using UnityEngine;
using Valve.VR.InteractionSystem;
// Image 50: SteamVR.dll - Assembly: SteamVR, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - Types 7133-7547
namespace Valve.VR.InteractionSystem.Sample
{
public class RenderModelChangerUI : UIElement // TypeDefIndex: 7530
{
// Fields
public GameObject leftPrefab; // 0x28
public GameObject rightPrefab; // 0x30
protected SkeletonUIOptions ui; // 0x38
// Constructors
public RenderModelChangerUI(); // 0x00000001803625E0-0x00000001803625F0
// Methods
protected override void Awake(); // 0x00000001803623F0-0x0000000180362440
protected override void OnButtonClick(); // 0x0000000180362440-0x00000001803625E0
}
}
| 44,459
|
https://github.com/rkausch/opensphere-desktop/blob/master/open-sphere-base/core/src/main/java/io/opensphere/core/util/MilitaryRankIcon.java
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-free-unknown, Apache-2.0, LicenseRef-scancode-public-domain
| 2,020
|
opensphere-desktop
|
rkausch
|
Java
|
Code
| 661
| 2,408
|
package io.opensphere.core.util;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import io.opensphere.core.util.swing.SwingUtilities;
/** Enumerable representation of Military Rank webfont. */
public enum MilitaryRankIcon implements FontIconEnum
{
/** Enumerable representation of PV2. */
RANK_03_E2("a"),
/** Enumerable representation of PFC. */
RANK_03_E3("b"),
/** Enumerable representation of CPL. */
RANK_03_E4_1("c"),
/** Enumerable representation of SPC. */
RANK_03_E4_2("d"),
/** Enumerable representation of SGT. */
RANK_03_E5("e"),
/** Enumerable representation of SSG. */
RANK_03_E6("f"),
/** Enumerable representation of SFC. */
RANK_03_E7("g"),
/** Enumerable representation of 1SG. */
RANK_03_E8_1("h"),
/** Enumerable representation of MSG. */
RANK_03_E8_2("i"),
/** Enumerable representation of SMA. */
RANK_03_E9_1("j"),
/** Enumerable representation of CSM. */
RANK_03_E9_2("k"),
/** Enumerable representation of SGM. */
RANK_03_E9_3("l"),
/** Enumerable representation of A1C. */
RANK_04_E2("m"),
/** Enumerable representation of Amn. */
RANK_04_E3("n"),
/** Enumerable representation of SrA. */
RANK_04_E4("o"),
/** Enumerable representation of SSgt. */
RANK_04_E5("p"),
/** Enumerable representation of TSgt. */
RANK_04_E6("q"),
/** Enumerable representation of MSgt. */
RANK_04_E7("r"),
/** Enumerable representation of SMSgt. */
RANK_04_E8("s"),
/** Enumerable representation of CMSgt. */
RANK_04_E9_1("t"),
/** Enumerable representation of CMSgt. */
RANK_04_E9_2("u"),
/** Enumerable representation of CCM. */
RANK_04_E9_3("v"),
/** Enumerable representation of CMSAF. */
RANK_04_E9_4("w"),
/** Enumerable representation of ?. */
RANK_02_02_E2("x"),
/** Enumerable representation of ?. */
RANK_02_02_E3("y"),
/** Enumerable representation of SO3. */
RANK_02_02_E4("z"),
/** Enumerable representation of SO2. */
RANK_02_02_E5("A"),
/** Enumerable representation of SO1. */
RANK_02_02_E6("B"),
/** Enumerable representation of SOC. */
RANK_02_02_E7("C"),
/** Enumerable representation of SOCS. */
RANK_02_02_E9("D"),
/** Enumerable representation of SOCM. */
RANK_02_02_E9_1("E"),
/** Enumerable representation of SA. */
RANK_02_00_E2("F"),
/** Enumerable representation of SN. */
RANK_02_00_E3("G"),
/** Enumerable representation of PO3. */
RANK_02_00_E4("H"),
/** Enumerable representation of PO2. */
RANK_02_00_E5("I"),
/** Enumerable representation of PO1. */
RANK_02_00_E6("J"),
/** Enumerable representation of CPO. */
RANK_02_00_E7("K"),
/** Enumerable representation of SCPO. */
RANK_02_00_E8("L"),
/** Enumerable representation of MCPO. */
RANK_02_00_E9_01("M"),
/** Enumerable representation of MCPON. */
RANK_02_00_E9_02("N"),
/** Enumerable representation of HA. */
RANK_02_01_E2("O"),
/** Enumerable representation of HN. */
RANK_02_01_E3("P"),
/** Enumerable representation of HM3. */
RANK_02_01_E4("Q"),
/** Enumerable representation of HM2. */
RANK_02_01_E5("R"),
/** Enumerable representation of HM1. */
RANK_02_01_E6("S"),
/** Enumerable representation of HMC. */
RANK_02_01_E7("T"),
/** Enumerable representation of HMCS. */
RANK_02_01_E8("U"),
/** Enumerable representation of HMCM. */
RANK_02_01_E9("V"),
/** Enumerable representation of CW2 / CW4. */
RANK_01_CW2("W"),
/** Enumerable representation of CW5. */
RANK_01_CW5("X"),
/** Enumerable representation of 2ndLt. */
RANK_01_O1("Y"),
/** Enumerable representation of 1stLt. */
RANK_01_O2("Z"),
/** Enumerable representation of Capt. */
RANK_01_O3("0"),
/** Enumerable representation of Maj. */
RANK_01_O4("1"),
/** Enumerable representation of LtCol. */
RANK_01_O5("2"),
/** Enumerable representation of Col. */
RANK_01_O6("3"),
/** Enumerable representation of BGen. */
RANK_01_O7("4"),
/** Enumerable representation of MajGen. */
RANK_01_O8("5"),
/** Enumerable representation of LtGen. */
RANK_01_O9("6"),
/** Enumerable representation of Gen. */
RANK_01_O10("7"),
/** Enumerable representation of W1 / CW3. */
RANK_01_W1("8"),
/** Enumerable representation of PFC. */
RANK_01_E2("9"),
/** Enumerable representation of LCpl. */
RANK_01_E3("!"),
/** Enumerable representation of Cpl. */
RANK_01_E4("\""),
/** Enumerable representation of Sgt. */
RANK_01_E5("#"),
/** Enumerable representation of SSgt. */
RANK_01_E6("$"),
/** Enumerable representation of GySgt. */
RANK_01_E7("%"),
/** Enumerable representation of MSgt. */
RANK_01_E8_1("&"),
/** Enumerable representation of 1stSgt. */
RANK_01_E8_2("'"),
/** Enumerable representation of MGySgt. */
RANK_01_E9_1("("),
/** Enumerable representation of SgtMaj. */
RANK_01_E9_2(")"),
/** Enumerable representation of SgtMajMarCor. */
RANK_01_E9_3("*");
static
{
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(SwingUtilities.MILITARY_RANK_FONT);
}
/**
* The font code defining the icon.
*/
private String myFontCode;
/**
* Creates a new font code enum instance.
*
* @param pFontCode the font code defining the icon.
*/
private MilitaryRankIcon(String pFontCode)
{
myFontCode = pFontCode;
}
/**
* Gets the value of the {@link #myFontCode} field.
*
* @return the value stored in the {@link #myFontCode} field.
*/
@Override
public String getFontCode()
{
return myFontCode;
}
@Override
public Font getFont()
{
return SwingUtilities.MILITARY_RANK_FONT;
}
/**
* {@inheritDoc}
*
* @see io.opensphere.core.util.FontIconEnum#getXDrawingOffset()
*/
@Override
public float getXDrawingOffset()
{
return 0;
}
/**
* {@inheritDoc}
*
* @see io.opensphere.core.util.FontIconEnum#getYDrawingOffset()
*/
@Override
public float getYDrawingOffset()
{
return 0;
}
/**
* {@inheritDoc}
*
* @see io.opensphere.core.util.FontIconEnum#getGlyphName()
*/
@Override
public String getGlyphName()
{
return name();
}
}
| 38,725
|
https://github.com/artemave/donc/blob/master/lib/getEnclosingTestName.js
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
donc
|
artemave
|
JavaScript
|
Code
| 35
| 117
|
module.exports = function getEnclosingTestName(fileContents, lineNumber) {
return fileContents.split("\n").reduce((result, line, idx) => {
let match
if (idx < Number(lineNumber) && (match = line.match(/(?:test|it) *\((?:'([^']+)'|"([^"]+)")/))) {
result = match[1] || match[2]
}
return result
}, null)
}
| 3,092
|
https://github.com/EPMatt/mvc-example/blob/master/js/app.js
|
Github Open Source
|
Open Source
|
MIT
| null |
mvc-example
|
EPMatt
|
JavaScript
|
Code
| 607
| 2,041
|
function checkPassword(emptyAccepted) {
if (emptyAccepted && document.getElementById("pwd").value.length === 0) {
document.getElementById("pwd").style.border = "1px solid rgb(206, 212, 218)";
document.getElementById("pwd-sm").innerHTML = "";
enableSubmit();
} else if (document.getElementById("pwd").value.length >= 8) {
document.getElementById("pwd").style.border = "1px solid green";
document.getElementById("pwd-sm").innerHTML = "";
enableSubmit();
} else {
document.getElementById("pwd").style.border = "1px solid red";
document.getElementById("pwd-sm").innerHTML = "Password is too short. Type in at least 8 characters.";
disableSubmit();
};
}
function checkPasswords(emptyAccepted) {
if (document.getElementById("pwd").value !== document.getElementById("pwd-renew").value) {
document.getElementById("pwd-renew").style.border = "1px solid red";
document.getElementById("password-sm").innerHTML = "Passwords are not the same";
disableSubmit();
} else if (emptyAccepted && document.getElementById("pwd-renew").value.length === 0) {
document.getElementById("pwd-renew").style.border = "1px solid rgb(206, 212, 218)";
document.getElementById("password-sm").innerHTML = "";
enableSubmit();
} else {
if (document.getElementById("pwd").style.border == "1px solid red") {
document.getElementById("pwd-renew").style.border = "1px solid red";
disableSubmit();
} else {
document.getElementById("pwd-renew").style.border = "1px solid green";
enableSubmit();
}
document.getElementById("password-sm").innerHTML = "";
}
}
function checkUsername(current) {
var input = document.getElementById("username");
if (input.value.length === 0) {
input.style.border = "1px solid red";
document.getElementById("username-sm").innerHTML = "Username cannot be empty";
disableSubmit();
} else {
$.post('./users-api-check', { usr: document.getElementById("username").value }, function (d, q, x) {
if (d == 1 || d == 0 && current === input.value) {
input.style.border = "1px solid green";
document.getElementById("username-sm").innerHTML = "";
enableSubmit();
}
else {
input.style.border = "1px solid red";
document.getElementById("username-sm").innerHTML = "The username is already in use";
disableSubmit();
}
});
}
}
/* deprecated */
function checkInput(inputId, checkCb) {
if (!checkCb()) document.getElementById(inputId).style.border = "1px solid red";
else document.getElementById(inputId).style.border = "1px solid green";
}
function disableSubmit() {
document.getElementById("submit-button").onclick = null;
}
function enableSubmit() {
document.getElementById("submit-button").onclick = submitFoo;
}
function checkDataLength(inputId, inputSmId, minLen, maxLen) {
let input = document.getElementById(inputId);
let inputSm = document.getElementById(inputSmId);
if (input.value.length > maxLen) {
input.style.border = "1px solid red";
inputSm.innerHTML = "Data too long!";
disableSubmit();
} else if (input.value.length < minLen) {
input.style.border = "1px solid red";
inputSm.innerHTML = "Data too short!";
disableSubmit();
} else {
input.style.border = "1px solid green";
inputSm.innerHTML = "";
enableSubmit();
}
}
function SHA2(uncrypted, crypted, form) {
var str = document.getElementById(uncrypted).value;
var buffer = new TextEncoder("utf-8").encode(str);
return crypto.subtle.digest("SHA-512", buffer).then(
function (hash) {
document.getElementById(crypted).value = toHex(hash);
document.getElementById(form).submit();
}
);
}
function updateSHA2(uncrypted, crypted, form) {
var str = document.getElementById(uncrypted).value;
if (str.length > 0) {
var buffer = new TextEncoder("utf-8").encode(str);
return crypto.subtle.digest("SHA-512", buffer).then(
function (hash) {
document.getElementById(crypted).value = toHex(hash);
document.getElementById(form).submit();
}
);
} else document.getElementById(form).submit();
}
function toHex(msg) {
return Array
.from(new Uint8Array(msg))
.map(b => b.toString(16).padStart(2, "0"))
.join("");
}
function updateBulkSelection() {
var c = document.getElementById("bulkCheck");
$('input:checkbox.elem-check').prop('checked', c.checked);
}
function updateSelections() {
var c = document.getElementById("bulkCheck");
if ($('input:checkbox.elem-check:checked').length == 0) {
c.checked = false;
c.indeterminate = false;
} else if ($('input:checkbox.elem-check:checked').length == $('input:checkbox.elem-check').length) {
c.checked = true;
c.indeterminate = false;
} else if (c.checked == true || c.checked == false) {
c.indeterminate = true;
}
}
function deleteUsers() {
$('#users-form').prop('action', "users-api-delete-bulk");
$('#users_table_wrapper select').prop('name', '');
$('#users-form').submit();
}
function deleteProducts() {
$('#products-form').prop('action', "products-api-delete-bulk");
$('#products_table_wrapper select').prop('name', '');
$('#products-form').submit();
}
function updateProduct(form) {
$('#' + form + ' input,textarea').trigger('input');
if (document.getElementById('submit-button').onclick != null) document.getElementById(form).submit();
}
function newProduct(form) {
$('#' + form + ' input,textarea').trigger('input');
if (document.getElementById('submit-button').onclick != null) document.getElementById(form).submit();
}
function updateUser(uncrypted, crypted, form) {
$('#' + form + ' input,textarea').trigger('input');
if (document.getElementById('submit-button').onclick != null) updateSHA2(uncrypted, crypted, form);
}
function newUser(uncrypted, crypted, form) {
$('#' + form + ' input,textarea').trigger('input');
if (document.getElementById('submit-button').onclick!=null) SHA2(uncrypted,crypted,form);
}
function checkProductCode(current) {
var input = document.getElementById("product-code");
if (input.value.length === 0) {
input.style.border = "1px solid red";
document.getElementById("product-code-sm").innerHTML = "Product code cannot be empty";
disableSubmit();
} else {
$.post('./products-api-check', { pid: input.value }, function (d, q, x) {
if (d == 1 || d == 0 && current === input.value) {
input.style.border = "1px solid green";
document.getElementById("product-code-sm").innerHTML = "";
enableSubmit();
}
else {
input.style.border = "1px solid red";
document.getElementById("product-code-sm").innerHTML = "The product code is already in use";
disableSubmit();
}
});
}
}
| 6,282
|
https://github.com/relifevn/estore/blob/master/views/checkout.ejs
|
Github Open Source
|
Open Source
|
CC-BY-3.0, CC-BY-4.0
| 2,020
|
estore
|
relifevn
|
EJS
|
Code
| 1,014
| 4,578
|
<!doctype html>
<html lang="zxx">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>eCommerce HTML-5 Template </title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="manifest" href="site.webmanifest">
<link rel="shortcut icon" type="image/x-icon" href="assets/img/favicon.ico">
<!-- CSS here -->
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/owl.carousel.min.css">
<link rel="stylesheet" href="assets/css/flaticon.css">
<link rel="stylesheet" href="assets/css/slicknav.css">
<link rel="stylesheet" href="assets/css/animate.min.css">
<link rel="stylesheet" href="assets/css/magnific-popup.css">
<link rel="stylesheet" href="assets/css/fontawesome-all.min.css">
<link rel="stylesheet" href="assets/css/themify-icons.css">
<link rel="stylesheet" href="assets/css/slick.css">
<link rel="stylesheet" href="assets/css/nice-select.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<%- include('header.ejs') %>
<!-- slider Area Start-->
<div class="slider-area ">
<!-- Mobile Menu -->
<div class="single-slider slider-height2 d-flex align-items-center" data-background="assets/img/hero/category.jpg">
<div class="container">
<div class="row">
<div class="col-xl-12">
<div class="hero-cap text-center">
<h2>Checkout</h2>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- slider Area End-->
<!--================Checkout Area =================-->
<section class="checkout_area section_padding">
<div class="container">
<div class="returning_customer">
<div class="check_title">
<h2>
Returning Customer?
<a href="#">Click here to login</a>
</h2>
</div>
<p>
If you have shopped with us before, please enter your details in the
boxes below. If you are a new customer, please proceed to the
Billing & Shipping section.
</p>
<form class="row contact_form" action="#" method="post" novalidate="novalidate">
<div class="col-md-6 form-group p_star">
<input type="text" class="form-control" id="name" name="name" value=" " />
<span class="placeholder" data-placeholder="Username or Email"></span>
</div>
<div class="col-md-6 form-group p_star">
<input type="password" class="form-control" id="password" name="password" value="" />
<span class="placeholder" data-placeholder="Password"></span>
</div>
<div class="col-md-12 form-group">
<button type="submit" value="submit" class="btn_3">
log in
</button>
<div class="creat_account">
<input type="checkbox" id="f-option" name="selector" />
<label for="f-option">Remember me</label>
</div>
<a class="lost_pass" href="#">Lost your password?</a>
</div>
</form>
</div>
<div class="cupon_area">
<div class="check_title">
<h2>
Have a coupon?
<a href="#">Click here to enter your code</a>
</h2>
</div>
<input type="text" placeholder="Enter coupon code" />
<a class="tp_btn" href="#">Apply Coupon</a>
</div>
<div class="billing_details">
<div class="row">
<div class="col-lg-8">
<h3>Billing Details</h3>
<form class="row contact_form" action="#" method="post" novalidate="novalidate">
<div class="col-md-6 form-group p_star">
<input type="text" class="form-control" id="first" name="name" />
<span class="placeholder" data-placeholder="First name"></span>
</div>
<div class="col-md-6 form-group p_star">
<input type="text" class="form-control" id="last" name="name" />
<span class="placeholder" data-placeholder="Last name"></span>
</div>
<div class="col-md-12 form-group">
<input type="text" class="form-control" id="company" name="company" placeholder="Company name" />
</div>
<div class="col-md-6 form-group p_star">
<input type="text" class="form-control" id="number" name="number" />
<span class="placeholder" data-placeholder="Phone number"></span>
</div>
<div class="col-md-6 form-group p_star">
<input type="text" class="form-control" id="email" name="compemailany" />
<span class="placeholder" data-placeholder="Email Address"></span>
</div>
<div class="col-md-12 form-group p_star">
<select class="country_select">
<option value="1">Country</option>
<option value="2">Country</option>
<option value="4">Country</option>
</select>
</div>
<div class="col-md-12 form-group p_star">
<input type="text" class="form-control" id="add1" name="add1" />
<span class="placeholder" data-placeholder="Address line 01"></span>
</div>
<div class="col-md-12 form-group p_star">
<input type="text" class="form-control" id="add2" name="add2" />
<span class="placeholder" data-placeholder="Address line 02"></span>
</div>
<div class="col-md-12 form-group p_star">
<input type="text" class="form-control" id="city" name="city" />
<span class="placeholder" data-placeholder="Town/City"></span>
</div>
<div class="col-md-12 form-group p_star">
<select class="country_select">
<option value="1">District</option>
<option value="2">District</option>
<option value="4">District</option>
</select>
</div>
<div class="col-md-12 form-group">
<input type="text" class="form-control" id="zip" name="zip" placeholder="Postcode/ZIP" />
</div>
<div class="col-md-12 form-group">
<div class="creat_account">
<input type="checkbox" id="f-option2" name="selector" />
<label for="f-option2">Create an account?</label>
</div>
</div>
<div class="col-md-12 form-group">
<div class="creat_account">
<h3>Shipping Details</h3>
<input type="checkbox" id="f-option3" name="selector" />
<label for="f-option3">Ship to a different address?</label>
</div>
<textarea class="form-control" name="message" id="message" rows="1"
placeholder="Order Notes"></textarea>
</div>
</form>
</div>
<div class="col-lg-4">
<div class="order_box">
<h2>Your Order</h2>
<ul class="list">
<li>
<a href="#">Product
<span>Total</span>
</a>
</li>
<li>
<a href="#">Fresh Blackberry
<span class="middle">x 02</span>
<span class="last">$720.00</span>
</a>
</li>
<li>
<a href="#">Fresh Tomatoes
<span class="middle">x 02</span>
<span class="last">$720.00</span>
</a>
</li>
<li>
<a href="#">Fresh Brocoli
<span class="middle">x 02</span>
<span class="last">$720.00</span>
</a>
</li>
</ul>
<ul class="list list_2">
<li>
<a href="#">Subtotal
<span>$2160.00</span>
</a>
</li>
<li>
<a href="#">Shipping
<span>Flat rate: $50.00</span>
</a>
</li>
<li>
<a href="#">Total
<span>$2210.00</span>
</a>
</li>
</ul>
<div class="payment_item">
<div class="radion_btn">
<input type="radio" id="f-option5" name="selector" />
<label for="f-option5">Check payments</label>
<div class="check"></div>
</div>
<p>
Please send a check to Store Name, Store Street, Store Town,
Store State / County, Store Postcode.
</p>
</div>
<div class="payment_item active">
<div class="radion_btn">
<input type="radio" id="f-option6" name="selector" />
<label for="f-option6">Paypal </label>
<img src="img/product/single-product/card.jpg" alt="" />
<div class="check"></div>
</div>
<p>
Please send a check to Store Name, Store Street, Store Town,
Store State / County, Store Postcode.
</p>
</div>
<div class="creat_account">
<input type="checkbox" id="f-option4" name="selector" />
<label for="f-option4">I’ve read and accept the </label>
<a href="#">terms & conditions*</a>
</div>
<a class="btn_3" href="#">Proceed to Paypal</a>
</div>
</div>
</div>
</div>
</div>
</section>
<!--================End Checkout Area =================-->
<footer>
<!-- Footer Start-->
<div class="footer-area footer-padding2">
<div class="container">
<div class="row d-flex justify-content-between">
<div class="col-xl-3 col-lg-3 col-md-5 col-sm-6">
<div class="single-footer-caption mb-50">
<div class="single-footer-caption mb-30">
<!-- logo -->
<div class="footer-logo">
<a href="index.html"><img src="assets/img/logo/logo2_footer.png" alt=""></a>
</div>
<div class="footer-tittle">
<div class="footer-pera">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit sed do eiusmod tempor incididunt ut
labore.</p>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-2 col-lg-3 col-md-3 col-sm-5">
<div class="single-footer-caption mb-50">
<div class="footer-tittle">
<h4>Quick Links</h4>
<ul>
<li><a href="#">About</a></li>
<li><a href="#"> Offers & Discounts</a></li>
<li><a href="#"> Get Coupon</a></li>
<li><a href="#"> Contact Us</a></li>
</ul>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-3 col-md-4 col-sm-7">
<div class="single-footer-caption mb-50">
<div class="footer-tittle">
<h4>New Products</h4>
<ul>
<li><a href="#">Woman Cloth</a></li>
<li><a href="#">Fashion Accessories</a></li>
<li><a href="#"> Man Accessories</a></li>
<li><a href="#"> Rubber made Toys</a></li>
</ul>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-3 col-md-5 col-sm-7">
<div class="single-footer-caption mb-50">
<div class="footer-tittle">
<h4>Support</h4>
<ul>
<li><a href="#">Frequently Asked Questions</a></li>
<li><a href="#">Terms & Conditions</a></li>
<li><a href="#">Privacy Policy</a></li>
<li><a href="#">Privacy Policy</a></li>
<li><a href="#">Report a Payment Issue</a></li>
</ul>
</div>
</div>
</div>
</div>
<!-- Footer bottom -->
<div class="row">
<div class="col-xl-7 col-lg-7 col-md-7">
<div class="footer-copy-right">
<p>
<!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. -->
Copyright ©
<script>document.write(new Date().getFullYear());</script> All rights reserved | This template is made
with <i class="ti-heart" aria-hidden="true"></i> by <a href="https://colorlib.com"
target="_blank">Colorlib</a>
<!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. -->
</p>
</div>
</div>
<div class="col-xl-5 col-lg-5 col-md-5">
<div class="footer-copy-right f-right">
<!-- social -->
<div class="footer-social">
<a href="#"><i class="fab fa-twitter"></i></a>
<a href="#"><i class="fab fa-facebook-f"></i></a>
<a href="#"><i class="fab fa-behance"></i></a>
<a href="#"><i class="fas fa-globe"></i></a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Footer End-->
</footer>
<!-- JS here -->
<!-- All JS Custom Plugins Link Here here -->
<script src="./assets/js/vendor/modernizr-3.5.0.min.js"></script>
<!-- Jquery, Popper, Bootstrap -->
<script src="./assets/js/vendor/jquery-1.12.4.min.js"></script>
<script src="./assets/js/popper.min.js"></script>
<script src="./assets/js/bootstrap.min.js"></script>
<!-- Jquery Mobile Menu -->
<script src="./assets/js/jquery.slicknav.min.js"></script>
<!-- Jquery Slick , Owl-Carousel Plugins -->
<script src="./assets/js/owl.carousel.min.js"></script>
<script src="./assets/js/slick.min.js"></script>
<!-- One Page, Animated-HeadLin -->
<script src="./assets/js/wow.min.js"></script>
<script src="./assets/js/animated.headline.js"></script>
<script src="./assets/js/jquery.magnific-popup.js"></script>
<!-- Scrollup, nice-select, sticky -->
<script src="./assets/js/jquery.scrollUp.min.js"></script>
<script src="./assets/js/jquery.nice-select.min.js"></script>
<script src="./assets/js/jquery.sticky.js"></script>
<!-- contact js -->
<script src="./assets/js/contact.js"></script>
<script src="./assets/js/jquery.form.js"></script>
<script src="./assets/js/jquery.validate.min.js"></script>
<script src="./assets/js/mail-script.js"></script>
<script src="./assets/js/jquery.ajaxchimp.min.js"></script>
<!-- Jquery Plugins, main Jquery -->
<script src="./assets/js/plugins.js"></script>
<script src="./assets/js/main.js"></script>
<script src="./assets/my-js/cookies.js"></script>
<script src="./assets/my-js/check-user-data.js"></script>
</body>
</html>
| 44,097
|
https://github.com/brave2chen/springboot-easy-web/blob/master/src/components/VInput/index.vue
|
Github Open Source
|
Open Source
|
MIT
| null |
springboot-easy-web
|
brave2chen
|
Vue
|
Code
| 668
| 2,854
|
<template>
<!-- ElRadioGroup tag会报错,单独抽出来处理 -->
<ElRadioGroup
v-if="componentType === 'ElRadioGroup'"
:style="styleObject"
:class="['v-input']"
:value="value"
v-bind="innerProps"
v-on="$listeners"
>
<el-radio v-for="(op, index) in data" :key="index" :label="getValue(op)" v-bind="op">
{{ getLabel(op) }}
</el-radio>
</ElRadioGroup>
<Component
:is="componentType"
v-else
:style="styleObject"
:class="['v-input', {'v-beautify-prepend': beautifyPrepend, 'v-input__plain': componentType === 'span'}]"
:value="value"
v-bind="innerProps"
v-on="$listeners"
>
<template v-if="componentType === 'ElCheckboxGroup'">
<el-checkbox v-for="(op,index) in data" :key="index" :label="getValue(op)" v-bind="op">
{{ getLabel(op) }}
</el-checkbox>
</template>
<template v-if="componentType === 'ElSelect'">
<el-option v-for="(op,index) in data" :key="index" :label="getLabel(op)" :value="getValue(op)" v-bind="op">
<template v-if="showValue">
<span style="float: left">{{ getLabel(op) }}</span>
<span style="float: right; color: #8492a6; font-size: 13px">{{ op[showValue]||getValue(op) }}</span>
</template>
</el-option>
</template>
<slot v-if="componentType === 'VButton'">{{ innerProps.name||value }}</slot>
<slot v-if="componentType === 'span'">{{innerProps.plaintext||value}}</slot>
<!-- input、number -->
<template v-if="getIconPath(prefix) || $slots.prefix" v-slot:prefix>
<slot v-if="$slots.prefix" name="prefix" />
<img v-if="getIconPath(prefix)" class="v-input__icon v-input__icon--prefix" :src="getIconPath(prefix)">
</template>
<template v-if="getIconPath(suffix) || $slots.suffix" v-slot:suffix>
<slot v-if="$slots.suffix" name="suffix" />
<img v-if="getIconPath(suffix)" class="v-input__icon v-input__icon--suffix" :src="getIconPath(suffix)">
</template>
<template v-if="$slots.prepend" v-slot:prepend>
<slot v-if="$slots.prepend" name="prepend" />
</template>
<template v-if="$slots.append" v-slot:append>
<slot v-if="$slots.append" name="append" />
</template>
<!-- select -->
<template v-if="$slots.empty" v-slot:empty>
<slot name="empty" />
</template>
</Component>
</template>
<script>
import VInputNumber from '@/components/VInputNumber'
import VTileSelect from '@/components/VTileSelect'
import VButton from '@/components/VButton'
const defaultProps = {
datePicker: {
rangeSeparator: '~',
placeholder: '选择日期',
startPlaceholder: '开始日期',
endPlaceholder: '结束日期'
},
timePicker: {
rangeSeparator: '~',
placeholder: '选择时间',
startPlaceholder: '开始时间',
endPlaceholder: '结束时间'
},
select: {},
textarea: {
resize: 'none'
},
radio: {},
checkbox: {},
input: {},
number: {},
switch: {}
}
export default {
name: 'VInput',
components: {VInputNumber, VTileSelect, VButton},
inheritAttrs: true,
props: {
// 控件类型: input、select、radio、checkbox、date、datetime 等
type: String,
// 当type冲突是,又需要指定相应控件的type时使用,如type=button时,指定button的type,请使用innerType
innerType: String,
// v-model属性
value: {},
// select、radio、checkbox 时的选项数据
data: Array,
// select时,显示value字段,支持传入字段prop
showValue: {
required: false,
default: false
},
width: [Number, String],
// 美化prepend
beautifyPrepend: Boolean,
// slot props
prefix: Object,
suffix: Object
},
computed: {
isDatePicker() {
return ['date', 'datetime', 'daterange', 'datetimerange'].includes(this.type)
},
isTimePicker() {
return ['time', 'timerange'].includes(this.type)
},
isDateTime() {
return ['datetime', 'datetimerange'].includes(this.type)
},
isRange() {
return ['daterange', 'datetimerange', 'timerange'].includes(this.type)
},
componentType() {
// 'date', 'datetime', 'daterange', 'datetimerange'
if (this.isDatePicker) {
return 'ElDatePicker'
}
// 'time', 'timerange'
if (this.isTimePicker) {
return 'ElTimePicker'
}
return ({
input: 'ElInput',
text: 'ElInput',
textarea: 'ElInput',
password: 'ElInput',
select: 'ElSelect',
radio: 'ElRadioGroup',
checkbox: 'ElCheckboxGroup',
number: 'VInputNumber',
switch: 'ElSwitch',
slider: 'ElSlider',
rate: 'ElRate',
color: 'ElColorPicker',
transfer: 'ElTransfer',
tileSelect: 'VTileSelect',
plaintext: 'span',
button: 'VButton'
})[this.type]
},
innerProps() {
let innerProps = defaultProps[this.type]
if (this.isDatePicker) {
innerProps = {
...defaultProps['datePicker'],
valueFormat: this.isDateTime && 'yyyy-MM-dd HH:mm:ss' || 'yyyy-MM-dd'
}
}
if (this.isTimePicker) {
innerProps = {
...defaultProps['timePicker'],
valueFormat: 'HH:mm:ss',
isRange: this.isRange
}
}
const props = {
...innerProps,
type: this.type !== 'input' ? this.innerType || this.type : undefined,
...this.$attrs
}
if (!this.isDateTime && this.isRange && props.valueFormat === 'yyyy-MM-dd HH:mm:ss') {
innerProps.defaultTime = "['00:00:00', '23:59:59']"
}
if (this.type === 'transfer') {
props.data = this.data
}
if (this.type === 'select') {
props.remote = props.remote || !!props.remoteMethod || !!props['remote-method']
props.placeholder = props.placeholder || (props.remoteMethod || !!props['remote-method']) && '请输入关键字' || '请选择'
}
return props
},
styleObject() {
if (this.width) {
return {width: typeof (this.width) === 'number' ? (this.width + 'px') : this.width}
}
return {}
}
},
methods: {
getLabel(item) {
return item.name !== undefined ? item.name : item.text !== undefined ? item.text : item.label !== undefined ? item.label : (item.value || item.id)
},
getValue(item) {
return item.value !== undefined ? item.value : item.id !== undefined ? item.id : item.label
},
getIconPath(icon) {
if (icon && (icon.startsWith('/static/') || icon.startsWith('data:image'))) {
return icon
}
}
}
}
</script>
<style lang="scss">
@import '~@/styles/variables.scss';
// 美化input的prepend样式,需要手动添加class: v-beautify-prepend
.v-beautify-prepend {
&.el-input.el-input-group--prepend,
.el-input.el-input-group--prepend {
border: 1px solid $borderColor !important;
border-radius: 2px;
.el-input-group__prepend {
background-color: $colorWhite !important;
border: none !important;
}
&.is-disabled {
.el-input-group__prepend {
background-color: $bgColor !important;
}
}
&:focus-within {
border-color: $colorPrimary !important;
}
&.el-input--small .el-input-group__prepend div.el-select .el-input__inner {
border: none !important;
border-right: 1px solid $borderColor !important;
line-height: 18px !important;
height: 18px !important;
margin: 7px 0 !important;
}
&.el-input--small .el-input__inner {
line-height: 30px !important;
height: 30px !important;
border: none !important;
}
}
.el-input .el-input-group__append{
border: none;
border-left: 1px solid $borderColor
}
}
.el-form-item.is-error .v-beautify-prepend .el-input.el-input--small.el-input-group--prepend {
border-color: $colorDanger !important;
}
.v-beautify-prepend .el-input.el-input--small.el-input-group--prepend .el-input__inner:focus,
.el-form-item.is-error .v-beautify-prepend .el-input.el-input--small.el-input-group--prepend .el-input__inner {
border: none !important;
}
.v-input .el-input__suffix .el-input__icon.fa-percent {
color: $colorTextRegular;
}
.input__plain {
}
</style>
| 40,063
|
https://github.com/DinoChiesa/Apigee-UE-Keep-Last-Three/blob/master/lib/cull-proxy-revisions.user.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
Apigee-UE-Keep-Last-Three
|
DinoChiesa
|
JavaScript
|
Code
| 592
| 1,990
|
// ==UserScript==
// @namespace Apigee
// @name cull-proxy-revisions
// @description Add a button to cull proxy revisions
// @match https://apigee.com/platform/*/proxies/*/overview/*
// @grant none
// @copyright 2016 Apigee Corporation, 2019-2020 Google LLC
// @version 0.1.2
// @run-at document-end
// @license Apache 2.0
// ==/UserScript==
/* jshint esversion: 9 */
/* global fetch */
(function (globalScope){
let timerControl = {},
orgDropDiv;
const delayAfterPageLoad = 1240,
delayAfterElements = 600;
const log = function() {
var origArguments = Array.prototype.slice.call(arguments);
origArguments[0] = "[cull-proxy-revs] " + origArguments[0];
Function.prototype.apply.apply(console.log, [console, origArguments]);
};
function waitForPredicate(predicate, action, controlKey) {
controlKey = controlKey || Math.random().toString(36).substring(2,15);
let interval = timerControl[controlKey];
let found = predicate();
if (found) {
action(found);
if (interval) {
clearInterval (interval);
delete timerControl[controlKey];
}
}
else {
if ( ! interval) {
timerControl[controlKey] = setInterval ( function () {
waitForPredicate(predicate, action, controlKey);
}, 300);
}
}
}
function getElementsByTagAndClass(root, tag, clazz) {
var nodes = root.getElementsByClassName(clazz);
if (tag) {
var tagUpper = tag.toUpperCase();
nodes = Array.prototype.filter.call(nodes,
testElement => testElement.nodeName.toUpperCase() === tagUpper );
}
return nodes;
}
function getCsrfHeader() {
let nodes = document.getElementsByTagName('csrf');
if (nodes && nodes.length == 1) {
let csrf = nodes[0];
return csrf.getAttribute('data');
}
return null;
}
function cleanRevisions(numRevisionsToKeep) {
log('cleanRevisions');
const re1 = new RegExp('^https://apigee.com/platform/([^/]+)/proxies/([^/]+)/overview/([^/]+)$');
let match = re1.exec(window.location.href);
if (match) {
let orgname = match[1],
apiname = match[2],
currentRevision = match[3],
csrfHeader = getCsrfHeader(),
baseHeaders = {
'Accept': 'application/json',
'X-Apigee-CSRF': csrfHeader,
'X-Requested-With': 'XMLHttpRequest'
//'X-Restart-URL': 'https://apigee.com' + href
};
let apiUrl = `https://apigee.com/ws/proxy/organizations/${orgname}/apis/${apiname}`;
let revisionsUrl = `${apiUrl}/revisions`;
//log('getting revisions...');
return fetch(revisionsUrl, { method:'GET', headers: baseHeaders })
.then( res =>
(res.status != 200) ? null :
res.json()
.then(revisions => {
if (revisions && revisions.length > numRevisionsToKeep) {
const reducer = (p, revision) =>
p.then( accumulator => {
let revisionUrl = `${revisionsUrl}/${revision}`;
let deploymentsUrl = `${revisionUrl}/deployments`;
return fetch(deploymentsUrl, { method:'GET', headers: baseHeaders })
.then(res =>
(res.status != 200) ? null :
res.json()
.then(r => {
//console.log(JSON.stringify(r));
if (r.environment && r.environment.length == 0) {
// not deployed, so delete
return fetch(revisionUrl, { method:'DELETE', headers: baseHeaders });
}
return null;
}))
.then( result => [ ...accumulator, {revision, result} ] );
});
revisions.sort( (a, b) => b - a );
let latestRev = revisions[0];
revisions.reverse();
let revisionsToExamine = revisions.slice(0, revisions.length - numRevisionsToKeep);
revisionsToExamine.reverse();
return revisionsToExamine
.reduce(reducer, Promise.resolve([]))
.then(r =>
window.location.href =
`https://apigee.com/platform/${orgname}/proxies/${apiname}/overview/${latestRev}`);
}
}));
}
}
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
function insertCullButton(div) {
let countSelectorContainer = document.createElement('div');
countSelectorContainer.classList.add('revisionSelectorContainer');
countSelectorContainer.innerHTML = '' +
'<div id="btn-group-cull-div" class="btn-group">'+
' <button class="btn btn-small dropdown-toggle btn-cull" data-toggle="dropdown" href="#">' +
' <span>Cull</span>\n' +
' <span class="caret"></span>' +
' </button>\n' +
' <ul class="dropdown-menu cull-selector-menu" style="min-width: 64px;">\n' +
' <li>\n' +
' <a>\n' +
' <span class="rev-count">Keep 1</span>\n' +
' </a>\n' +
' </li>\n' +
' <li>\n' +
' <a>\n' +
' <span class="rev-count">Keep 3</span>\n' +
' </a>\n' +
' </li>\n' +
' <li>\n' +
' <a>\n' +
' <span class="rev-count">Keep 5</span>\n' +
' </a>\n' +
' </li>\n' +
' </ul>\n' +
'</div>\n';
// the list will open on click; we get that for free.
insertAfter(div, countSelectorContainer);
// handlers for the list items
let items = countSelectorContainer.querySelectorAll('.cull-selector-menu li');
if (items.length > 0) {
[...items].forEach(li => {
li.addEventListener('click', () => {
let span = li.querySelector('.rev-count');
// get the integer at the end of the string
cleanRevisions(Number(span.innerText.slice(5)));
});
});
}
}
function tryFixup() {
getRevisionSelector(insertCullButton);
}
function getRevisionSelector(cb) {
let nodes = getElementsByTagAndClass(document, 'div', 'revisionSelectorContainer');
if (nodes && nodes.length == 1) {
if (cb) {
return cb(nodes[0]);
}
return nodes[0];
}
return null;
}
// ================================================================
// wait for page to load fully before adding UI elements
setTimeout(function() {
waitForPredicate(getRevisionSelector, function() {
setTimeout(tryFixup, delayAfterElements);
});
}, delayAfterPageLoad);
}(this));
| 13,156
|
https://github.com/jhh67/chapel/blob/master/test/trivial/bradc/arrinit/arrinit.notypep.typeprind2.chpl
|
Github Open Source
|
Open Source
|
ECL-2.0, Apache-2.0
| 2,022
|
chapel
|
jhh67
|
Chapel
|
Code
| 16
| 39
|
var m = 4;
var D: domain = (1..m);
var A: [i:D] real = i;
write(A);
| 40,813
|
https://github.com/beyonddream/aoc2018/blob/master/day7/part2.cpp
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
aoc2018
|
beyonddream
|
C++
|
Code
| 269
| 1,014
|
//
// Created by Arun Shanmugam Kumar on 2018-12-10.
//
#include <iostream>
#include <stack>
#include <sstream>
#include <vector>
#include <map>
#include <set>
using namespace std;
int main() {
string current_step;
vector<pair<char, char>> edges;
set<char> unique_steps;
while(getline(cin, current_step) && !current_step.empty()) {
stringstream ss(current_step);
char first;
char second;
string skip;
ss >> skip >> first >> skip >> skip >> skip >> skip >> skip >> second;
edges.push_back(make_pair(first, second));
unique_steps.insert(first);
unique_steps.insert(second);
}
sort(edges.begin(), edges.end(), [](auto a, auto b){
return get<1>(a) < get<1>(b);
});
map<char, int> incoming_edges_counter_map;
map<char, vector<char>> incoming_edges_dependencies_map;
vector<char> next_edge;
for(auto it = edges.begin(); it != edges.end(); ++it) {
pair<char, char> current_edge = *it;
char from = get<0>(current_edge);
char to = get<1>(current_edge);
incoming_edges_counter_map[to]++;
incoming_edges_dependencies_map[to].push_back(from);
}
int time_taken = INT_MIN;
map<char, int> step_to_max_time_to_finish_map;
set<char> visited;
for(auto it = unique_steps.begin(); it != unique_steps.end(); ++it) {
if(incoming_edges_counter_map.find(*it) == incoming_edges_counter_map.end() ||
incoming_edges_counter_map[*it] == 0) {
next_edge.push_back(*it);
step_to_max_time_to_finish_map[*it] = 60 + (*it - 65 + 1);
time_taken = step_to_max_time_to_finish_map[*it];
visited.insert(*it);
}
}
auto it = next_edge.begin();
while(it != next_edge.end()) {
char current_node = *it;
cout << current_node << endl;
if (visited.find(current_node) == visited.end() ) {
int max_time_taken = INT_MIN;
vector<char> dependencies = incoming_edges_dependencies_map[current_node];
for(auto dependency = dependencies.begin(); dependency != dependencies.end(); dependency++) {
max_time_taken = max(max_time_taken, step_to_max_time_to_finish_map[*dependency]);
}
step_to_max_time_to_finish_map[current_node] = max_time_taken + 60 + (current_node - 65 + 1);
time_taken = step_to_max_time_to_finish_map[current_node];
visited.insert(current_node);
}
it = next_edge.erase(it);
// opportunity for optimization by using a heap
for(auto it1 = edges.begin(); it1 != edges.end(); it1++) {
if (get<0>(*it1) == current_node) {
incoming_edges_counter_map[get<1>(*it1)]--;
if(incoming_edges_counter_map[get<1>(*it1)] <= 0) {
next_edge.push_back(get<1>(*it1));
it = next_edge.begin();
}
}
}
}
cout << "Total time taken is " << time_taken << endl;
return EXIT_SUCCESS;
}
| 23,230
|
https://github.com/SHIVJITH/Odoo_Machine_Test/blob/master/addons/l10n_mx/models/account.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
Odoo_Machine_Test
|
SHIVJITH
|
Python
|
Code
| 189
| 654
|
# coding: utf-8
# Copyright 2016 Vauxoo (https://www.vauxoo.com) <info@vauxoo.com>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
import re
from odoo import models, api, fields, _
class AccountJournal(models.Model):
_inherit = 'account.journal'
def _prepare_liquidity_account_vals(self, company, code, vals):
# OVERRIDE
account_vals = super()._prepare_liquidity_account_vals(company, code, vals)
if company.country_id.code == 'MX':
# When preparing the values to use when creating the default debit and credit accounts of a
# liquidity journal, set the correct tags for the mexican localization.
account_vals.setdefault('tag_ids', [])
account_vals['tag_ids'] += [(4, tag_id) for tag_id in self.env['account.account'].mx_search_tags(code).ids]
return account_vals
class AccountAccount(models.Model):
_inherit = 'account.account'
@api.model
def mx_search_tags(self, code):
account_tag = self.env['account.account.tag']
#search if the code is compliant with the regexp we have for tags auto-assignation
re_res = re.search(
'^(?P<first>[1-8][0-9][0-9])[,.]'
'(?P<second>[0-9][0-9])[,.]'
'(?P<third>[0-9]{2,3})$', code)
if not re_res:
return account_tag
#get the elements of that code divided with separation declared in the regexp
account = re_res.groups()
return account_tag.search([
('name', '=like', "%s.%s%%" % (account[0], account[1])),
('color', '=', 4)], limit=1)
@api.onchange('code')
def _onchange_code(self):
if self.company_id.country_id.code == "MX" and self.code:
tags = self.mx_search_tags(self.code)
self.tag_ids = tags
class AccountAccountTag(models.Model):
_inherit = 'account.account.tag'
nature = fields.Selection([
('D', 'Debitable Account'), ('A', 'Creditable Account')],
help='Used in Mexican report of electronic accounting (account nature).')
| 31,838
|
https://github.com/janschultecom/monix/blob/master/monix-streams/shared/src/main/scala/monix/streams/internal/operators/flatten.scala
|
Github Open Source
|
Open Source
|
Apache-2.0, LicenseRef-scancode-unknown-license-reference
| 2,016
|
monix
|
janschultecom
|
Scala
|
Code
| 532
| 1,514
|
/*
* Copyright (c) 2014-2016 by its authors. Some rights reserved.
* See the project homepage at: https://monix.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package monix.streams.internal.operators
import monix.execution.cancelables.{BooleanCancelable, RefCountCancelable}
import monix.streams.{OverflowStrategy, Observer, Observable, Ack}
import monix.streams.Ack.{Cancel, Continue}
import monix.streams.exceptions.CompositeException
import monix.streams.internal._
import monix.streams.observers.{BufferedSubscriber, SynchronousObserver}
import scala.collection.mutable
import scala.concurrent.Promise
private[monix] object flatten {
/**
* Implementation for [[Observable.concat]].
*/
def concat[T,U](source: Observable[T], delayErrors: Boolean)
(implicit ev: T <:< Observable[U]): Observable[U] = {
Observable.unsafeCreate[U] { observerU =>
import observerU.{scheduler => s}
source.unsafeSubscribeFn(new Observer[T] {
private[this] val errors = if (delayErrors)
mutable.ArrayBuffer.empty[Throwable] else null
private[this] val refCount = RefCountCancelable {
if (delayErrors && errors.nonEmpty)
observerU.onError(CompositeException(errors))
else
observerU.onComplete()
}
def onNext(childObservable: T) = {
val upstreamPromise = Promise[Ack]()
val refID = refCount.acquire()
childObservable.unsafeSubscribeFn(new Observer[U] {
def onNext(elem: U) = {
observerU.onNext(elem)
.ifCancelTryCanceling(upstreamPromise)
}
def onError(ex: Throwable): Unit = {
if (delayErrors) {
errors += ex
onComplete()
}
else {
// error happened, so signaling both the main thread that it should stop
// and the downstream consumer of the error
upstreamPromise.trySuccess(Cancel)
observerU.onError(ex)
}
}
def onComplete(): Unit = {
// NOTE: we aren't sending this onComplete signal downstream to our observerU
// instead we are just instructing upstream to send the next observable
upstreamPromise.trySuccess(Continue)
refID.cancel()
}
})
upstreamPromise.future
}
def onError(ex: Throwable) = {
if (delayErrors) {
errors += ex
onComplete()
}
else {
// oops, error happened on main thread, piping that
// along should cancel everything
observerU.onError(ex)
}
}
def onComplete() = {
refCount.cancel()
}
})
}
}
/**
* Implementation for [[Observable.merge]].
*/
def merge[T,U](source: Observable[T])
(overflowStrategy: OverflowStrategy, onOverflow: Long => U, delayErrors: Boolean)
(implicit ev: T <:< Observable[U]): Observable[U] = {
Observable.unsafeCreate { subscriber =>
import subscriber.{scheduler => s}
val observerU = BufferedSubscriber(subscriber, overflowStrategy, onOverflow)
source.unsafeSubscribeFn(new SynchronousObserver[T] {
private[this] val streamActivity =
BooleanCancelable()
private[this] val errors = if (delayErrors)
mutable.ArrayBuffer.empty[Throwable] else null
private[this] val refCount = RefCountCancelable {
if (delayErrors)
errors.synchronized {
if (errors.nonEmpty)
observerU.onError(CompositeException(errors))
else
observerU.onComplete()
}
else
observerU.onComplete()
}
def onNext(childObservable: T) = {
val refID = refCount.acquire()
childObservable.unsafeSubscribeFn(new Observer[U] {
def onNext(elem: U) = {
if (streamActivity.isCanceled)
Cancel
else
observerU.onNext(elem)
.ifCanceledDoCancel(streamActivity)
}
def onError(ex: Throwable): Unit = {
if (delayErrors) errors.synchronized {
errors += ex
refID.cancel()
}
else {
streamActivity.cancel()
observerU.onError(ex)
}
}
def onComplete(): Unit = {
// NOTE: we aren't sending this onComplete signal downstream to our observerU
// we will eventually do that after all of them are complete
refID.cancel()
}
})
if (streamActivity.isCanceled)
Cancel
else
Continue
}
def onError(ex: Throwable) = {
if (delayErrors) errors.synchronized {
errors += ex
refCount.cancel()
}
else {
// oops, error happened on main thread,
// piping that along should cancel everything
observerU.onError(ex)
}
}
def onComplete() = {
refCount.cancel()
}
})
}
}
}
| 2,594
|
https://github.com/maxidorov/Football-App/blob/master/FootballApp/FootballApp/CardModule/CardPresenter.swift
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Football-App
|
maxidorov
|
Swift
|
Code
| 278
| 961
|
//
// PlayerCardPresenter.swift
// FootballApp
//
// Created by Данила on 14.12.2021.
//
import UIKit
import Firebase
final class CardPresenter: CardPresenterProtocol {
var model: SearchModel
var cellsCount: Int {
return playerInfo != nil ? 10 : 3
}
var playerInfo: PlayerInfo?
var network: NetworkProtocol = Network()
weak var view: CardViewProtocol?
weak var cellUpdater: CellUpdaterProtocol?
init(model: SearchModel) {
self.model = model
self.model.subscriptonStatus = SubscriptionManager.currentSubscriptions.contains(where: { (model) -> Bool in
model.id == self.model.id
})
}
func configure(cell: CardCellProtocol, indexPath: IndexPath) {
cell.configure(with: model, playerInfo: playerInfo, indexPath: indexPath)
guard let cell = cell as? CardSubscribeCell else { return }
cell.subscribeButton.addTarget(self, action: #selector(subscribeButtonPressed(sender:)), for: .touchUpInside)
cellUpdater = cell
}
func getExtraInfo() {
if model.type == .player {
network.getPlayerInfo(by: model.id) { (info) in
self.playerInfo = info
self.view?.updateViewWithInfo()
}
}
}
@objc private func subscribeButtonPressed(sender: UIButton) {
guard let userID = Auth.auth().currentUser?.uid else { return }
if model.subscriptonStatus != true {
subscribeProcessing(model: model, userID: userID)
} else {
unsubscribeProcessing(model: model, userID: userID)
}
}
func identifier(for indexPath: IndexPath) -> String? {
switch indexPath.row {
case 0:
return CardImageCell.identifier
case 1:
return CardLabelCell.identifier
case 2:
return CardSubscribeCell.identifier
default:
return CardParameterCell.identifier
}
}
private func unsubscribeProcessing(model: SearchModel, userID: String) {
switch model.type {
case .player:
FirebaseSubscriptionService.unsubscribe(user: userID, playerId: model.id) { (isUnsubscribe) in
self.cellUpdater?.updateCell(with: !isUnsubscribe)
self.model.subscriptonStatus = !isUnsubscribe
SubscriptionManager.updateSubscriptions()
}
case .team:
FirebaseSubscriptionService.unsubscribe(user: userID, teamId: model.id) { (isUnsubscribe) in
self.cellUpdater?.updateCell(with: !isUnsubscribe)
self.model.subscriptonStatus = !isUnsubscribe
SubscriptionManager.updateSubscriptions()
}
default:
break
}
}
private func subscribeProcessing(model: SearchModel, userID: String) {
switch model.type {
case .player:
FirebaseSubscriptionService.subscribe(user: userID, playerModel: model) { (isSubscribe) in
self.cellUpdater?.updateCell(with: isSubscribe)
self.model.subscriptonStatus = isSubscribe
SubscriptionManager.updateSubscriptions()
}
case .team:
FirebaseSubscriptionService.subscribe(user: userID, teamModel: model) { (isSubscribe) in
self.cellUpdater?.updateCell(with: isSubscribe)
self.model.subscriptonStatus = isSubscribe
SubscriptionManager.updateSubscriptions()
}
default:
break
}
}
}
| 32,859
|
https://github.com/aravindprasad/freesasa/blob/master/tests/test_json.c
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
freesasa
|
aravindprasad
|
C
|
Code
| 667
| 3,335
|
#if HAVE_CONFIG_H
#include <config.h>
#endif
#include <check.h>
#include <freesasa.h>
#include <json-c/json_object.h>
#include <json-c/json_object_iterator.h>
#include "tools.h"
extern json_object *
freesasa_node2json(freesasa_node *node, int exclude_type, int options);
static int
compare_nodearea(json_object *obj, const freesasa_nodearea *ref, int is_abs)
{
struct json_object_iterator it = json_object_iter_begin(obj),
it_end = json_object_iter_end(obj);
double total, polar, apolar, bb, sc;
while (!json_object_iter_equal(&it, &it_end)) {
const char *key = json_object_iter_peek_name(&it);
json_object *val = json_object_iter_peek_value(&it);
if (!strcmp(key, "total")) {
ck_assert(json_object_is_type(val, json_type_double));
total = json_object_get_double(val);
} else if (!strcmp(key, "polar")) {
ck_assert(json_object_is_type(val, json_type_double));
polar = json_object_get_double(val);
} else if (!strcmp(key, "apolar")) {
ck_assert(json_object_is_type(val, json_type_double));
apolar = json_object_get_double(val);
} else if (!strcmp(key, "main-chain")) {
ck_assert(json_object_is_type(val, json_type_double));
bb = json_object_get_double(val);
} else if (!strcmp(key, "side-chain")) {
ck_assert(json_object_is_type(val, json_type_double));
sc = json_object_get_double(val);
} else {
ck_assert(0);
}
json_object_iter_next(&it);
}
ck_assert(total > 0);
if (is_abs) {
ck_assert(float_eq(total, polar + apolar, 1e-10));
ck_assert(float_eq(total, sc + bb, 1e-10));
ck_assert(float_eq(total, ref->total, 1e-10));
ck_assert(float_eq(polar, ref->polar, 1e-10));
ck_assert(float_eq(apolar, ref->apolar, 1e-10));
ck_assert(float_eq(sc, ref->side_chain, 1e-10));
ck_assert(float_eq(bb, ref->main_chain, 1e-10));
}
return 1;
}
int test_atom(freesasa_node *node)
{
ck_assert_ptr_ne(node, NULL);
json_object *atom = freesasa_node2json(node, FREESASA_NODE_NONE, 0);
ck_assert_ptr_ne(atom, NULL);
struct json_object_iterator it = json_object_iter_begin(atom),
it_end = json_object_iter_end(atom);
while (!json_object_iter_equal(&it, &it_end)) {
const char *key = json_object_iter_peek_name(&it);
json_object *val = json_object_iter_peek_value(&it);
if (!strcmp(key, "name")) {
ck_assert(json_object_is_type(val, json_type_string));
ck_assert_str_eq(json_object_get_string(val), "N");
} else if (!strcmp(key, "area")) {
ck_assert(json_object_is_type(val, json_type_double));
ck_assert(json_object_get_double(val) > 0);
} else if (!strcmp(key, "is-polar")) {
ck_assert(json_object_is_type(val, json_type_boolean));
ck_assert(json_object_get_boolean(val));
} else if (!strcmp(key, "is-main-chain")) {
ck_assert(json_object_is_type(val, json_type_boolean));
ck_assert(json_object_get_boolean(val));
} else if (!strcmp(key, "radius")) {
ck_assert(json_object_is_type(val, json_type_double));
ck_assert(json_object_get_double(val) > 0);
} else {
ck_assert(0);
}
json_object_iter_next(&it);
}
json_object_put(atom);
return 1;
}
int test_residue(freesasa_node *node)
{
ck_assert_ptr_ne(node, NULL);
json_object *residue = freesasa_node2json(node, FREESASA_NODE_NONE, 0);
ck_assert_ptr_ne(residue, NULL);
const freesasa_nodearea *resarea = freesasa_node_area(node);
struct json_object_iterator it = json_object_iter_begin(residue),
it_end = json_object_iter_end(residue);
while (!json_object_iter_equal(&it, &it_end)) {
const char *key = json_object_iter_peek_name(&it);
json_object *val = json_object_iter_peek_value(&it);
if (!strcmp(key, "name")) {
ck_assert(json_object_is_type(val, json_type_string));
ck_assert_str_eq(json_object_get_string(val), "MET");
} else if (!strcmp(key, "number")) {
ck_assert(json_object_is_type(val, json_type_string));
ck_assert_str_eq(json_object_get_string(val), "1");
} else if (!strcmp(key, "n-atoms")) {
ck_assert(json_object_is_type(val, json_type_int));
ck_assert_int_eq(json_object_get_int(val), 8);
} else if (!strcmp(key, "atoms")) {
ck_assert(json_object_is_type(val, json_type_array));
//this is checked further by test_atom
} else if (!strcmp(key, "area")) {
ck_assert(compare_nodearea(val, resarea, 1));
} else if (!strcmp(key, "relative-area")) {
ck_assert(compare_nodearea(val, resarea, 0));
} else {
ck_assert_str_eq(key, "unknown-key");
}
json_object_iter_next(&it);
}
json_object_put(residue);
return 1;
}
int test_chain(freesasa_node *node, const freesasa_result *result)
{
ck_assert_ptr_ne(node, NULL);
json_object *chain = freesasa_node2json(node, FREESASA_NODE_NONE, 0);
const freesasa_nodearea *chain_area = freesasa_node_area(node);
ck_assert_ptr_ne(chain, NULL);
ck_assert(float_eq(chain_area->total, result->total, 1e-10));
struct json_object_iterator it = json_object_iter_begin(chain),
it_end = json_object_iter_end(chain);
while (!json_object_iter_equal(&it, &it_end)) {
const char *key = json_object_iter_peek_name(&it);
json_object *val = json_object_iter_peek_value(&it);
if (!strcmp(key, "label")) {
ck_assert(json_object_is_type(val, json_type_string));
ck_assert_str_eq(json_object_get_string(val), "A");
} else if (!strcmp(key, "n-residues")) {
ck_assert(json_object_is_type(val, json_type_int));
ck_assert_int_eq(json_object_get_int(val), 76);
} else if (!strcmp(key, "area")) {
ck_assert(compare_nodearea(val, chain_area, 1));
} else if (!strcmp(key, "residues")) {
ck_assert(json_object_is_type(val, json_type_array));
// the rest is checked in test_residue
} else {
ck_assert_str_eq(key, "unknown-key");
}
json_object_iter_next(&it);
}
json_object_put(chain);
return 1;
}
int test_structure(freesasa_node *node)
{
ck_assert_ptr_ne(node, NULL);
freesasa_nodearea structure_area = {
.name = "1ubq",
.total = 4804.0556411417447,
.polar = 2504.2173023011442,
.apolar = 2299.838338840601,
.side_chain = 3689.8982162353718,
.main_chain = 1114.157424906374};
json_object *jstruct = freesasa_node2json(node, FREESASA_NODE_NONE, 0);
ck_assert_ptr_ne(jstruct, NULL);
struct json_object_iterator it = json_object_iter_begin(jstruct),
it_end = json_object_iter_end(jstruct);
while (!json_object_iter_equal(&it, &it_end)) {
const char *key = json_object_iter_peek_name(&it);
json_object *val = json_object_iter_peek_value(&it);
if (!strcmp(key, "input")) {
ck_assert(json_object_is_type(val, json_type_string));
ck_assert_str_eq(json_object_get_string(val), "test");
} else if (!strcmp(key, "chain-labels")) {
ck_assert(json_object_is_type(val, json_type_string));
ck_assert_str_eq(json_object_get_string(val), "A");
} else if (!strcmp(key, "area")) {
compare_nodearea(val, &structure_area, 1);
} else if (!strcmp(key, "model")) {
ck_assert(json_object_is_type(val, json_type_int));
// ck_assert_str_eq(json_object_get_string(val), "1");
// these components are tested in test_chains
} else if (!strcmp(key, "chains")) {
ck_assert(json_object_is_type(val, json_type_array));
// these components are tested in test_chains
} else {
ck_assert_str_eq(key, "unknown-key");
}
json_object_iter_next(&it);
}
json_object_put(jstruct);
return 1;
}
START_TEST(test_json)
{
FILE *pdb = fopen(DATADIR "1ubq.pdb", "r");
freesasa_structure *ubq =
freesasa_structure_from_pdb(pdb, &freesasa_default_classifier, 0);
fclose(pdb);
freesasa_result *result = freesasa_calc_structure(ubq, NULL);
freesasa_node *tree = freesasa_tree_new();
freesasa_tree_add_result(tree, result, ubq, "test");
freesasa_node *result_node = freesasa_node_children(tree);
freesasa_node *structures = freesasa_node_children(result_node);
freesasa_node *chains = freesasa_node_children(structures);
freesasa_node *residues = freesasa_node_children(chains);
freesasa_node *atoms = freesasa_node_children(residues);
ck_assert(test_atom(atoms));
ck_assert(test_residue(residues));
ck_assert(test_chain(chains, result));
ck_assert(test_structure(structures));
freesasa_structure_free(ubq);
freesasa_result_free(result);
freesasa_node_free(tree);
}
END_TEST
Suite *json_suite()
{
Suite *s = suite_create("JSON");
TCase *tc_core = tcase_create("Core");
tcase_add_test(tc_core, test_json);
suite_add_tcase(s, tc_core);
return s;
}
| 39,340
|
https://github.com/Zenexer/ModCMZ/blob/master/ModCMZ.Core/Mods/Mod.cs
|
Github Open Source
|
Open Source
|
FTL
| null |
ModCMZ
|
Zenexer
|
C#
|
Code
| 430
| 1,219
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Threading.Tasks;
using ModCMZ.Core.Game;
using ModCMZ.Core.Runtime.DNA.CastleMinerZ.GraphicsProfileSupport;
namespace ModCMZ.Core.Mods
{
public abstract class Mod : IMod
{
/// <summary>
/// CastleMiner Z is about to launch. The game's domain isn't ready yet, and the mod only exists in the main domain.
/// </summary>
/// <remarks>
/// Warning: Invoked from the main application domain, not the game's application domain. Don't store anything during this call.
/// </remarks>
public event Action Launching;
/// <summary>
/// CastleMiner Z has launched.
/// </summary>
public event Action Launched;
/// <summary>
/// First event in the new application domain.
/// </summary>
/// <remarks>
/// You can use this to add your other events, but that's probably a premature optimization.
/// </remarks>
public event Action DomainReady;
/// <summary>
/// <see cref="GameApp"/> is ready.
/// </summary>
public event Action<GameApp> GameReady;
/// <summary>
/// Inventory items are being registered.
/// </summary>
public event Action<ModContentManager> RegisteringItems;
public event Action<Action<string>> ClaimingContent;
/// <summary>
/// Components have been initialized. Called after <see cref="GameReady"/>.
/// </summary>
public event Action ComponentsReady;
private bool _checkedAttribute;
private ModAttribute _attribute;
private Version _version;
public ModAttribute Attribute
{
get
{
if (!_checkedAttribute)
{
_attribute = GetType().GetCustomAttribute<ModAttribute>();
_checkedAttribute = true;
}
return _attribute;
}
}
public string Id => Attribute.Id;
public string Name => Attribute?.Name;
public virtual string Author => Attribute?.Author;
public virtual string Description => Attribute?.Description;
public virtual Version Version
{
get
{
if (_version == null)
{
if (Attribute == null)
{
return null;
}
if (Attribute.Version == null)
{
var attribute = GetType().Assembly.GetCustomAttribute<AssemblyVersionAttribute>();
if (attribute == null)
{
return null;
}
if (Version.TryParse(attribute.Version, out var version))
{
_version = version;
}
}
else
{
_version = Attribute.Version;
}
}
return _version;
}
}
private Dictionary<string, string> _embeddedContent;
private IReadOnlyDictionary<string, string> EmbeddedContent
{
get
{
if (_embeddedContent == null)
{
var embeddedContent = new Dictionary<string, string>();
var contentPrefix = $"{Assembly.GetName().Name}.Content.";
var allResourceNames = Assembly.GetManifestResourceNames();
var contentResourceNames = allResourceNames.Where(x => x.StartsWith(contentPrefix));
foreach (var resourceName in contentResourceNames)
{
var assetKey = resourceName.Substring(contentPrefix.Length);
assetKey = assetKey.Remove(assetKey.LastIndexOf('.'));
assetKey = assetKey.ToLowerInvariant();
embeddedContent.Add(assetKey, resourceName);
}
_embeddedContent = embeddedContent;
}
return _embeddedContent;
}
}
public Assembly Assembly => GetType().Assembly;
public virtual Stream OpenContentStream(string assetName)
{
var assetKey = assetName
.Replace('\\', '.')
.Replace('/', '.')
.ToLowerInvariant();
var resourceName = EmbeddedContent[assetKey];
return Assembly.GetManifestResourceStream(resourceName);
}
public virtual void OnLaunched() => Launched?.Invoke();
public virtual void OnLaunching() => Launching?.Invoke();
public virtual void OnDomainReady() => DomainReady?.Invoke();
public virtual void OnGameReady(GameApp game) => GameReady?.Invoke(game);
public virtual void OnComponentsReady() => ComponentsReady?.Invoke();
public virtual void OnRegisteringItems(ModContentManager content) => RegisteringItems?.Invoke(content);
public virtual void OnClaimingContent(ModContentManager content) => ClaimingContent?.Invoke((assetName) => content.ClaimContent(this, assetName));
}
}
| 31,679
|
https://github.com/andor0/octopod/blob/master/examples/helm-based-control-scripts/src/bin/check.rs
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
octopod
|
andor0
|
Rust
|
Code
| 149
| 663
|
use clap::{App, Arg};
use serde_json::json;
use std::io::Write;
use std::process::{exit, Command, Stdio};
const KUBEDOG_TIMEOUT: usize = 3;
fn main() -> std::io::Result<()> {
let matches = App::new("check")
.version("0.1")
.arg(
Arg::with_name("project-name")
.long("project-name")
.short("p")
.required(true)
.takes_value(true),
)
.arg(
Arg::with_name("base-domain")
.long("base-domain")
.short("d")
.required(true)
.takes_value(true),
)
.arg(
Arg::with_name("namespace")
.long("namespace")
.short("s")
.required(true)
.takes_value(true),
)
.arg(
Arg::with_name("name")
.long("name")
.short("n")
.required(true)
.takes_value(true),
)
.get_matches();
let _project_name = matches
.value_of("project-name")
.expect("could not get project-name");
let _base_domain = matches
.value_of("base-domain")
.expect("could not get base-domain");
let namespace = matches
.value_of("namespace")
.expect("could not get namepace");
let name = matches.value_of("name").expect("could not get name");
let kubedog_stdin = json!({
"Deployments": [{"ResourceName": format!("app-{}", name), "Namespace": namespace}]
})
.to_string();
let mut child = Command::new("kubedog")
.args(&["multitrack", "-t", &KUBEDOG_TIMEOUT.to_string()])
.stdin(Stdio::piped())
.spawn()
.expect("failed to call kubedog");
{
let stdin = child.stdin.as_mut().expect("failed to open stdin");
stdin
.write_all(kubedog_stdin.as_bytes())
.expect("failed to write to stdin");
}
let output = child.wait_with_output().expect("failed to read stdout");
let success = output.status.success();
if !success {
exit(1)
}
Ok(())
}
| 12,394
|
https://github.com/djsuw88/simple-server/blob/master/simple/simple-http/src/test/java/org/simpleframework/http/ConnectionTest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
simple-server
|
djsuw88
|
Java
|
Code
| 761
| 2,235
|
package org.simpleframework.http;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URL;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.CountDownLatch;
import junit.framework.TestCase;
import org.simpleframework.common.buffer.Allocator;
import org.simpleframework.common.buffer.FileAllocator;
import org.simpleframework.common.thread.ConcurrentExecutor;
import org.simpleframework.http.Request;
import org.simpleframework.http.Response;
import org.simpleframework.http.core.Container;
import org.simpleframework.http.core.ContainerTransportProcessor;
import org.simpleframework.http.core.ThreadDumper;
import org.simpleframework.transport.TransportProcessor;
import org.simpleframework.transport.TransportSocketProcessor;
import org.simpleframework.transport.SocketProcessor;
import org.simpleframework.transport.Socket;
import org.simpleframework.transport.connect.Connection;
import org.simpleframework.transport.connect.SocketConnection;
public class ConnectionTest extends TestCase {
private static final int PING_TEST_PORT = 12366;
public void testSocketPing() throws Exception {
// for(int i = 0; i < 10; i++) {
// System.err.printf("Ping [%s]%n", i);
// testPing(PING_TEST_PORT, "Hello World!", true, 2);
// }
}
public void testURLPing() throws Exception {
for(int i = 0; i < 20; i++) {
System.err.printf("Ping [%s]%n", i);
testPing(PING_TEST_PORT, "Hello World!", false, 10);
}
}
public void testMixPing() throws Exception {
//for(int i = 0; i < 50; i+=2) {
// System.err.printf("Ping [%s]%n", i);
// testPing(PING_TEST_PORT, "Hello World!", true, 2);
// System.err.printf("Ping [%s]%n", i+1);
// testPing(PING_TEST_PORT, "Hello World!", false, 10);
//}
}
private void testPing(int port, String message, boolean socket, int count) throws Exception {
PingServer server = new PingServer(PING_TEST_PORT, message);
Pinger pinger = new Pinger(PING_TEST_PORT, socket, count);
server.start();
List<String> list = pinger.execute();
for(int i = 0; i < count; i++) { // at least 20
String result = list.get(i);
assertNotNull(result);
assertEquals(result, message);
}
server.stop();
pinger.validate();
pinger.stop(); // wait for it all to finish
}
private static class DebugServer implements SocketProcessor {
private SocketProcessor server;
public DebugServer(SocketProcessor server) {
this.server = server;
}
public void process(Socket socket) throws IOException {
System.err.println("Connect...");
server.process(socket);
}
public void stop() throws IOException {
System.err.println("Stop...");
server.stop();
}
}
private static class PingServer implements Container {
private final Connection connection;
private final SocketAddress address;
private final String message;
public PingServer(int port, String message) throws Exception {
Allocator allocator = new FileAllocator();
TransportProcessor processor = new ContainerTransportProcessor(this, allocator, 5);
SocketProcessor server = new TransportSocketProcessor(processor);
DebugServer debug = new DebugServer(server);
this.connection = new SocketConnection(debug);
this.address = new InetSocketAddress(port);
this.message = message;
}
public void start() throws Exception {
try {
System.err.println("Starting...");
connection.connect(address);
}finally {
System.err.println("Started...");
}
}
public void stop() throws Exception {
connection.close();
}
public void handle(Request req, Response resp) {
try {
System.err.println(req);
PrintStream out = resp.getPrintStream(1024);
resp.setValue("Content-Type", "text/plain");
out.print(message);
out.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
private static class Pinger implements Runnable {
private final int count;
private final int port;
private final boolean socket;
private final CountDownLatch latch;
private final CountDownLatch stop;
private final ConcurrentExecutor executor;
private final ThreadDumper dumper;
private final List<String> list;
private final List<java.net.Socket> sockets;
public Pinger(int port, boolean socket, int count) throws Exception {
this.executor = new ConcurrentExecutor(Pinger.class, count);
this.list = new Vector<String>(count);
this.sockets = new Vector<java.net.Socket>(count);
this.latch = new CountDownLatch(count);
this.stop = new CountDownLatch(count + count);
this.dumper = new ThreadDumper();
this.port = port;
this.socket = socket;
this.count = count;
}
public List<String> execute() throws Exception {
dumper.start();
for(int i = 0; i < count; i++) {
executor.execute(this);
}
latch.await();
// Overrun with pings to ensure they close
if(socket) {
for(int i = 0; i < count; i++) {
executor.execute(this);
}
}
return list;
}
public void validate() throws Exception {
if(socket) {
for(java.net.Socket socket : sockets) {
if(socket.getInputStream().read() != -1) {
throw new IOException("Connection not closed");
} else {
System.err.println("Socket is closed");
}
}
}
}
public void stop() throws Exception {
executor.stop();
if(socket) {
stop.await(); // wait for all excess pings to finish
}
dumper.kill();
}
private String ping() throws Exception {
if(socket) {
return pingWithSocket();
}
return pingWithURL();
}
public void run() {
try {
String result = ping();
list.add(result);
latch.countDown();
}catch(Throwable e){
System.err.println(e);
} finally {
stop.countDown(); // account for excess pings
}
}
/**
* This works as it opens a socket and sends the request.
* This will split using the CRLF and CRLF ending.
*
* @return the response body
*
* @throws Exception if the socket can not connect
*/
private String pingWithSocket() throws Exception {
java.net.Socket socket = new java.net.Socket("localhost", port);
OutputStream out = socket.getOutputStream();
out.write(
("GET / HTTP/1.1\r\n" +
"Host: localhost\r\n"+
"\r\n").getBytes());
out.flush();
InputStream in = socket.getInputStream();
byte[] block = new byte[1024];
int count = in.read(block);
String result = new String(block, 0, count);
String parts[] = result.split("\r\n\r\n");
if(!result.startsWith("HTTP")) {
throw new IOException("Header is not valid");
}
sockets.add(socket);
return parts[1];
}
/**
* Use the standard URL tool to get the content.
*
* @return the response body
*
* @throws Exception if a connection can not be made.
*/
private String pingWithURL() throws Exception {
URL target = new URL("http://localhost:"+ port+"/");
InputStream in = target.openStream();
byte[] block = new byte[1024];
int count = in.read(block);
String result = new String(block, 0, count);
return result;
}
}
}
| 2,856
|
https://github.com/idiotWu/let-there-be-light-c/blob/master/docs/files_dup.js
|
Github Open Source
|
Open Source
|
MIT
| null |
let-there-be-light-c
|
idiotWu
|
JavaScript
|
Code
| 45
| 332
|
var files_dup =
[
[ "maze", "dir_931ce304af081f85f63237a1d4f7bc66.html", "dir_931ce304af081f85f63237a1d4f7bc66" ],
[ "render", "dir_c30bb48f042946ebe97e62b65a0197ba.html", "dir_c30bb48f042946ebe97e62b65a0197ba" ],
[ "scene", "dir_fd40b43fc4c1e00689c4b0cc7f9f9515.html", "dir_fd40b43fc4c1e00689c4b0cc7f9f9515" ],
[ "util", "dir_23ec12649285f9fabf3a6b7380226c28.html", "dir_23ec12649285f9fabf3a6b7380226c28" ],
[ "config.h", "config_8h.html", "config_8h" ],
[ "main.c", "main_8c.html", "main_8c" ],
[ "state.c", "state_8c.html", "state_8c" ],
[ "state.h", "state_8h.html", "state_8h" ]
];
| 28,579
|
https://github.com/flackyang/streamx/blob/master/streamx-flink/streamx-flink-test/src/main/scala/com/streamxhub/streamx/test/stream/MongoSourceApp.scala
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
streamx
|
flackyang
|
Scala
|
Code
| 74
| 372
|
package com.streamxhub.streamx.test.stream
import com.mongodb.BasicDBObject
import com.streamxhub.streamx.common.util.{DateUtils, JsonUtils}
import com.streamxhub.streamx.flink.core.scala.source.MongoSource
import com.streamxhub.streamx.flink.core.scala.FlinkStreaming
import org.apache.flink.api.scala._
import scala.collection.JavaConversions._
object MongoSourceApp extends FlinkStreaming {
override def handle(): Unit = {
implicit val prop = context.parameter.getProperties
val source = MongoSource()
source.getDataStream[String](
"shop",
(a, d) => {
Thread.sleep(1000)
/**
* 从上一条记录提前offset数据,作为下一条数据查询的条件,如果offset为Null,则表明是第一次查询,需要指定默认offset
*/
val offset = if (a == null) "2019-09-27 00:00:00" else {
JsonUtils.read[Map[String, _]](a).get("updateTime").toString
}
val cond = new BasicDBObject().append("updateTime", new BasicDBObject("$gte", DateUtils.parse(offset)))
d.find(cond)
},
_.toList.map(_.toJson())
).print()
}
}
| 42,299
|
https://github.com/alexeybut/Aspose.Words-for-.NET/blob/master/ApiExamples/CSharp/ApiExamples/ExCharts.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
Aspose.Words-for-.NET
|
alexeybut
|
C#
|
Code
| 3,905
| 12,702
|
using System;
using System.IO;
using System.Collections.Generic;
using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Drawing.Charts;
using NUnit.Framework;
namespace ApiExamples
{
[TestFixture]
public class ExCharts : ApiExampleBase
{
[Test]
public void ChartTitle()
{
//ExStart
//ExFor:Charts.Chart
//ExFor:Charts.Chart.Title
//ExFor:Charts.ChartTitle
//ExFor:Charts.ChartTitle.Overlay
//ExFor:Charts.ChartTitle.Show
//ExFor:Charts.ChartTitle.Text
//ExSummary:Shows how to insert a chart and change its title.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Bar, 400, 300);
Assert.AreEqual(ShapeType.NonPrimitive, chartShape.ShapeType);
Assert.True(chartShape.HasChart);
// Get the chart object from the containing shape
Chart chart = chartShape.Chart;
// Set the title text, which appears at the top center of the chart and modify its appearance
ChartTitle title = chart.Title;
title.Text = "MyChart";
title.Overlay = true;
title.Show = true;
doc.Save(ArtifactsDir + "Charts.ChartTitle.docx");
//ExEnd
}
[Test]
public void NumberFormat()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Add chart with default data.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;
chart.Title.Text = "Data Labels With Different Number Format";
// Delete default generated series.
chart.Series.Clear();
// Add new series
ChartSeries series0 =
chart.Series.Add("AW Series 0", new[] { "AW0", "AW1", "AW2" }, new[] { 2.5, 1.5, 3.5 });
// Add DataLabel to the first point of the first series.
ChartDataLabel chartDataLabel0 = series0.DataLabels.Add(0);
chartDataLabel0.ShowValue = true;
// Set currency format code.
chartDataLabel0.NumberFormat.FormatCode = "\"$\"#,##0.00";
ChartDataLabel chartDataLabel1 = series0.DataLabels.Add(1);
chartDataLabel1.ShowValue = true;
// Set date format code.
chartDataLabel1.NumberFormat.FormatCode = "d/mm/yyyy";
ChartDataLabel chartDataLabel2 = series0.DataLabels.Add(2);
chartDataLabel2.ShowValue = true;
// Set percentage format code.
chartDataLabel2.NumberFormat.FormatCode = "0.00%";
// Or you can set format code to be linked to a source cell,
// in this case NumberFormat will be reset to general and inherited from a source cell.
chartDataLabel2.NumberFormat.IsLinkedToSource = true;
doc.Save(ArtifactsDir + "Charts.NumberFormat.docx");
Assert.IsTrue(DocumentHelper.CompareDocs(ArtifactsDir + "Charts.NumberFormat.docx", GoldsDir + "DocumentBuilder.NumberFormat Gold.docx"));
}
[Test]
public void DataArraysWrongSize()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Add chart with default data.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;
ChartSeriesCollection seriesColl = chart.Series;
seriesColl.Clear();
// Create category names array, second category will be null.
string[] categories = { "Cat1", null, "Cat3", "Cat4", "Cat5", null };
// Adding new series with empty (double.NaN) values.
seriesColl.Add("AW Series 1", categories, new double[] { 1, 2, double.NaN, 4, 5, 6 });
seriesColl.Add("AW Series 2", categories, new double[] { 2, 3, double.NaN, 5, 6, 7 });
Assert.That(
() => seriesColl.Add("AW Series 3", categories, new[] { double.NaN, 4, 5, double.NaN, double.NaN }),
Throws.TypeOf<ArgumentException>());
Assert.That(
() => seriesColl.Add("AW Series 4", categories,
new[] { double.NaN, double.NaN, double.NaN, double.NaN, double.NaN }),
Throws.TypeOf<ArgumentException>());
}
[Test]
public void EmptyValuesInChartData()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Add chart with default data.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;
ChartSeriesCollection seriesColl = chart.Series;
seriesColl.Clear();
// Create category names array, second category will be null.
string[] categories = { "Cat1", null, "Cat3", "Cat4", "Cat5", null };
// Adding new series with empty (double.NaN) values.
seriesColl.Add("AW Series 1", categories, new[] { 1, 2, double.NaN, 4, 5, 6 });
seriesColl.Add("AW Series 2", categories, new[] { 2, 3, double.NaN, 5, 6, 7 });
seriesColl.Add("AW Series 3", categories, new[] { double.NaN, 4, 5, double.NaN, 7, 8 });
seriesColl.Add("AW Series 4", categories,
new[] { double.NaN, double.NaN, double.NaN, double.NaN, double.NaN, 9 });
doc.Save(ArtifactsDir + "Charts.EmptyValuesInChartData.docx");
}
[Test]
public void ChartDefaultValues()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
builder.InsertChart(ChartType.Column3D, 432, 252);
MemoryStream dstStream = new MemoryStream();
doc.Save(dstStream, SaveFormat.Docx);
Shape shapeNode = (Shape)doc.GetChild(NodeType.Shape, 0, true);
Chart chart = shapeNode.Chart;
// Assert X axis
Assert.AreEqual(ChartAxisType.Category, chart.AxisX.Type);
Assert.AreEqual(AxisCategoryType.Automatic, chart.AxisX.CategoryType);
Assert.AreEqual(AxisCrosses.Automatic, chart.AxisX.Crosses);
Assert.AreEqual(false, chart.AxisX.ReverseOrder);
Assert.AreEqual(AxisTickMark.None, chart.AxisX.MajorTickMark);
Assert.AreEqual(AxisTickMark.None, chart.AxisX.MinorTickMark);
Assert.AreEqual(AxisTickLabelPosition.NextToAxis, chart.AxisX.TickLabelPosition);
Assert.AreEqual(1, chart.AxisX.MajorUnit);
Assert.AreEqual(true, chart.AxisX.MajorUnitIsAuto);
Assert.AreEqual(AxisTimeUnit.Automatic, chart.AxisX.MajorUnitScale);
Assert.AreEqual(0.5, chart.AxisX.MinorUnit);
Assert.AreEqual(true, chart.AxisX.MinorUnitIsAuto);
Assert.AreEqual(AxisTimeUnit.Automatic, chart.AxisX.MinorUnitScale);
Assert.AreEqual(AxisTimeUnit.Automatic, chart.AxisX.BaseTimeUnit);
Assert.AreEqual("General", chart.AxisX.NumberFormat.FormatCode);
Assert.AreEqual(100, chart.AxisX.TickLabelOffset);
Assert.AreEqual(AxisBuiltInUnit.None, chart.AxisX.DisplayUnit.Unit);
Assert.AreEqual(true, chart.AxisX.AxisBetweenCategories);
Assert.AreEqual(AxisScaleType.Linear, chart.AxisX.Scaling.Type);
Assert.AreEqual(1, chart.AxisX.TickLabelSpacing);
Assert.AreEqual(true, chart.AxisX.TickLabelSpacingIsAuto);
Assert.AreEqual(1, chart.AxisX.TickMarkSpacing);
Assert.AreEqual(false, chart.AxisX.Hidden);
// Assert Y axis
Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);
Assert.AreEqual(AxisCategoryType.Category, chart.AxisY.CategoryType);
Assert.AreEqual(AxisCrosses.Automatic, chart.AxisY.Crosses);
Assert.AreEqual(false, chart.AxisY.ReverseOrder);
Assert.AreEqual(AxisTickMark.None, chart.AxisY.MajorTickMark);
Assert.AreEqual(AxisTickMark.None, chart.AxisY.MinorTickMark);
Assert.AreEqual(AxisTickLabelPosition.NextToAxis, chart.AxisY.TickLabelPosition);
Assert.AreEqual(1, chart.AxisY.MajorUnit);
Assert.AreEqual(true, chart.AxisY.MajorUnitIsAuto);
Assert.AreEqual(AxisTimeUnit.Automatic, chart.AxisY.MajorUnitScale);
Assert.AreEqual(0.5, chart.AxisY.MinorUnit);
Assert.AreEqual(true, chart.AxisY.MinorUnitIsAuto);
Assert.AreEqual(AxisTimeUnit.Automatic, chart.AxisY.MinorUnitScale);
Assert.AreEqual(AxisTimeUnit.Automatic, chart.AxisY.BaseTimeUnit);
Assert.AreEqual("General", chart.AxisY.NumberFormat.FormatCode);
Assert.AreEqual(100, chart.AxisY.TickLabelOffset);
Assert.AreEqual(AxisBuiltInUnit.None, chart.AxisY.DisplayUnit.Unit);
Assert.AreEqual(true, chart.AxisY.AxisBetweenCategories);
Assert.AreEqual(AxisScaleType.Linear, chart.AxisY.Scaling.Type);
Assert.AreEqual(1, chart.AxisY.TickLabelSpacing);
Assert.AreEqual(true, chart.AxisY.TickLabelSpacingIsAuto);
Assert.AreEqual(1, chart.AxisY.TickMarkSpacing);
Assert.AreEqual(false, chart.AxisY.Hidden);
// Assert Z axis
Assert.AreEqual(ChartAxisType.Series, chart.AxisZ.Type);
Assert.AreEqual(AxisCategoryType.Category, chart.AxisZ.CategoryType);
Assert.AreEqual(AxisCrosses.Automatic, chart.AxisZ.Crosses);
Assert.AreEqual(false, chart.AxisZ.ReverseOrder);
Assert.AreEqual(AxisTickMark.None, chart.AxisZ.MajorTickMark);
Assert.AreEqual(AxisTickMark.None, chart.AxisZ.MinorTickMark);
Assert.AreEqual(AxisTickLabelPosition.NextToAxis, chart.AxisZ.TickLabelPosition);
Assert.AreEqual(1, chart.AxisZ.MajorUnit);
Assert.AreEqual(true, chart.AxisZ.MajorUnitIsAuto);
Assert.AreEqual(AxisTimeUnit.Automatic, chart.AxisZ.MajorUnitScale);
Assert.AreEqual(0.5, chart.AxisZ.MinorUnit);
Assert.AreEqual(true, chart.AxisZ.MinorUnitIsAuto);
Assert.AreEqual(AxisTimeUnit.Automatic, chart.AxisZ.MinorUnitScale);
Assert.AreEqual(AxisTimeUnit.Automatic, chart.AxisZ.BaseTimeUnit);
Assert.AreEqual(string.Empty, chart.AxisZ.NumberFormat.FormatCode);
Assert.AreEqual(100, chart.AxisZ.TickLabelOffset);
Assert.AreEqual(AxisBuiltInUnit.None, chart.AxisZ.DisplayUnit.Unit);
Assert.AreEqual(true, chart.AxisZ.AxisBetweenCategories);
Assert.AreEqual(AxisScaleType.Linear, chart.AxisZ.Scaling.Type);
Assert.AreEqual(1, chart.AxisZ.TickLabelSpacing);
Assert.AreEqual(true, chart.AxisZ.TickLabelSpacingIsAuto);
Assert.AreEqual(1, chart.AxisZ.TickMarkSpacing);
Assert.AreEqual(false, chart.AxisZ.Hidden);
}
[Test]
public void InsertChartUsingAxisProperties()
{
//ExStart
//ExFor:ChartAxis
//ExFor:ChartAxis.CategoryType
//ExFor:ChartAxis.Crosses
//ExFor:ChartAxis.ReverseOrder
//ExFor:ChartAxis.MajorTickMark
//ExFor:ChartAxis.MinorTickMark
//ExFor:ChartAxis.MajorUnit
//ExFor:ChartAxis.MinorUnit
//ExFor:ChartAxis.TickLabelOffset
//ExFor:ChartAxis.TickLabelPosition
//ExFor:ChartAxis.TickLabelSpacingIsAuto
//ExFor:ChartAxis.TickMarkSpacing
//ExFor:Charts.AxisCategoryType
//ExFor:Charts.AxisCrosses
//ExFor:Charts.Chart.AxisX
//ExFor:Charts.Chart.AxisY
//ExFor:Charts.Chart.AxisZ
//ExSummary:Shows how to insert chart using the axis options for detailed configuration.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
new double[] { 640, 320, 280, 120, 150 });
// Get chart axes
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;
// For 2D charts like the one we made, the Z axis is null
Assert.Null(chart.AxisZ);
// Set X-axis options
xAxis.CategoryType = AxisCategoryType.Category;
xAxis.Crosses = AxisCrosses.Minimum;
xAxis.ReverseOrder = false;
xAxis.MajorTickMark = AxisTickMark.Inside;
xAxis.MinorTickMark = AxisTickMark.Cross;
xAxis.MajorUnit = 10;
xAxis.MinorUnit = 15;
xAxis.TickLabelOffset = 50;
xAxis.TickLabelPosition = AxisTickLabelPosition.Low;
xAxis.TickLabelSpacingIsAuto = false;
xAxis.TickMarkSpacing = 1;
// Set Y-axis options
yAxis.CategoryType = AxisCategoryType.Automatic;
yAxis.Crosses = AxisCrosses.Maximum;
yAxis.ReverseOrder = true;
yAxis.MajorTickMark = AxisTickMark.Inside;
yAxis.MinorTickMark = AxisTickMark.Cross;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 20;
yAxis.TickLabelPosition = AxisTickLabelPosition.NextToAxis;
//ExEnd
doc.Save(ArtifactsDir + "Charts.InsertChartUsingAxisProperties.docx");
doc.Save(ArtifactsDir + "Charts.InsertChartUsingAxisProperties.pdf");
}
[Test]
public void InsertChartWithDateTimeValues()
{
//ExStart
//ExFor:AxisBound
//ExFor:AxisBound.#ctor(Double)
//ExFor:AxisBound.#ctor(DateTime)
//ExFor:AxisScaling.Minimum
//ExFor:AxisScaling.Maximum
//ExFor:ChartAxis.Scaling
//ExFor:Charts.AxisTickMark
//ExFor:Charts.AxisTickLabelPosition
//ExFor:Charts.AxisTimeUnit
//ExFor:Charts.ChartAxis.BaseTimeUnit
//ExSummary:Shows how to insert chart with date/time values
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
// Fill data.
chart.Series.Add("Aspose Test Series",
new[]
{
new DateTime(2017, 11, 06), new DateTime(2017, 11, 09), new DateTime(2017, 11, 15),
new DateTime(2017, 11, 21), new DateTime(2017, 11, 25), new DateTime(2017, 11, 29)
},
new[] { 1.2, 0.3, 2.1, 2.9, 4.2, 5.3 });
ChartAxis xAxis = chart.AxisX;
ChartAxis yAxis = chart.AxisY;
// Set X axis bounds.
xAxis.Scaling.Minimum = new AxisBound(new DateTime(2017, 11, 05).ToOADate());
xAxis.Scaling.Maximum = new AxisBound(new DateTime(2017, 12, 03));
// Set major units to a week and minor units to a day.
xAxis.BaseTimeUnit = AxisTimeUnit.Days;
xAxis.MajorUnit = 7;
xAxis.MinorUnit = 1;
xAxis.MajorTickMark = AxisTickMark.Cross;
xAxis.MinorTickMark = AxisTickMark.Outside;
// Define Y axis properties.
yAxis.TickLabelPosition = AxisTickLabelPosition.High;
yAxis.MajorUnit = 100;
yAxis.MinorUnit = 50;
yAxis.DisplayUnit.Unit = AxisBuiltInUnit.Hundreds;
yAxis.Scaling.Minimum = new AxisBound(100);
yAxis.Scaling.Maximum = new AxisBound(700);
doc.Save(ArtifactsDir + "Charts.ChartAxisProperties.docx");
//ExEnd
}
[Test]
public void HideChartAxis()
{
//ExStart
//ExFor:ChartAxis.Hidden
//ExSummary:Shows how to hide chart axises.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Line, 432, 252);
Chart chart = shape.Chart;
chart.AxisX.Hidden = true;
chart.AxisY.Hidden = true;
// Clear demo data.
chart.Series.Clear();
chart.Series.Add("AW Series 1",
new string[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" },
new double[] { 1.2, 0.3, 2.1, 2.9, 4.2 });
MemoryStream stream = new MemoryStream();
doc.Save(stream, SaveFormat.Docx);
shape = (Shape)doc.GetChild(NodeType.Shape, 0, true);
chart = shape.Chart;
Assert.AreEqual(true, chart.AxisX.Hidden);
Assert.AreEqual(true, chart.AxisY.Hidden);
//ExEnd
}
[Test]
public void SetNumberFormatToChartAxis()
{
//ExStart
//ExFor:ChartAxis.NumberFormat
//ExFor:Charts.ChartNumberFormat
//ExFor:ChartNumberFormat.FormatCode
//ExFor:Charts.ChartNumberFormat.IsLinkedToSource
//ExSummary:Shows how to set formatting for chart values.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Column, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
new double[] { 1900000, 850000, 2100000, 600000, 1500000 });
// Set number format.
chart.AxisY.NumberFormat.FormatCode = "#,##0";
// Set this to override the above value and draw the number format from the source cell
Assert.False(chart.AxisY.NumberFormat.IsLinkedToSource);
//ExEnd
doc.Save(ArtifactsDir + "Charts.SetNumberFormatToChartAxis.docx");
doc.Save(ArtifactsDir + "Charts.SetNumberFormatToChartAxis.pdf");
}
// Note: Tests below used for verification conversion docx to pdf and the correct display.
// For now, the results check manually.
[Test]
[TestCase(ChartType.Column)]
[TestCase(ChartType.Line)]
[TestCase(ChartType.Pie)]
[TestCase(ChartType.Bar)]
[TestCase(ChartType.Area)]
public void TestDisplayChartsWithConversion(ChartType chartType)
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(chartType, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
new double[] { 1900000, 850000, 2100000, 600000, 1500000 });
doc.Save(ArtifactsDir + "Charts.TestDisplayChartsWithConversion.docx");
doc.Save(ArtifactsDir + "Charts.TestDisplayChartsWithConversion.pdf");
}
[Test]
public void Surface3DChart()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Surface3D, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series 1",
new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
new double[] { 1900000, 850000, 2100000, 600000, 1500000 });
chart.Series.Add("Aspose Test Series 2",
new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
new double[] { 900000, 50000, 1100000, 400000, 2500000 });
chart.Series.Add("Aspose Test Series 3",
new string[] { "Word", "PDF", "Excel", "GoogleDocs", "Note" },
new double[] { 500000, 820000, 1500000, 400000, 100000 });
doc.Save(ArtifactsDir + "Charts.SurfaceChart.docx");
doc.Save(ArtifactsDir + "Charts.SurfaceChart.pdf");
}
[Test]
public void BubbleChart()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert chart.
Shape shape = builder.InsertChart(ChartType.Bubble, 432, 252);
Chart chart = shape.Chart;
// Clear demo data.
chart.Series.Clear();
chart.Series.Add("Aspose Test Series",
new double[] { 2900000, 350000, 1100000, 400000, 400000 },
new double[] { 1900000, 850000, 2100000, 600000, 1500000 },
new double[] { 900000, 450000, 2500000, 800000, 500000 });
doc.Save(ArtifactsDir + "Charts.BubbleChart.docx");
doc.Save(ArtifactsDir + "Charts.BubbleChart.pdf");
}
//ExStart
//ExFor:Charts.ChartSeries
//ExFor:Charts.ChartSeries.DataLabels
//ExFor:Charts.ChartSeries.DataPoints
//ExFor:Charts.ChartSeries.Name
//ExFor:Charts.ChartDataLabel
//ExFor:Charts.ChartDataLabel.Index
//ExFor:Charts.ChartDataLabel.IsVisible
//ExFor:Charts.ChartDataLabel.NumberFormat
//ExFor:Charts.ChartDataLabel.Separator
//ExFor:Charts.ChartDataLabel.ShowCategoryName
//ExFor:Charts.ChartDataLabel.ShowDataLabelsRange
//ExFor:Charts.ChartDataLabel.ShowLeaderLines
//ExFor:Charts.ChartDataLabel.ShowLegendKey
//ExFor:Charts.ChartDataLabel.ShowPercentage
//ExFor:Charts.ChartDataLabel.ShowSeriesName
//ExFor:Charts.ChartDataLabel.ShowValue
//ExFor:Charts.ChartDataLabelCollection
//ExFor:Charts.ChartDataLabelCollection.Add(System.Int32)
//ExFor:Charts.ChartDataLabelCollection.Clear
//ExFor:Charts.ChartDataLabelCollection.Count
//ExFor:Charts.ChartDataLabelCollection.GetEnumerator
//ExFor:Charts.ChartDataLabelCollection.Item(System.Int32)
//ExFor:Charts.ChartDataLabelCollection.RemoveAt(System.Int32)
//ExSummary:Shows how to apply labels to data points in a chart.
[Test] //ExSkip
public void ChartDataLabels()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Line, 400, 300);
// Get the chart object from the containing shape
Chart chart = chartShape.Chart;
// The chart already contains demo data comprised of 3 series each with 4 categories
Assert.AreEqual(3, chart.Series.Count);
Assert.AreEqual("Series 1", chart.Series[0].Name);
// Apply data labels to every series in the graph
foreach (ChartSeries series in chart.Series)
{
ApplyDataLabels(series, 4, "000.0", ", ");
Assert.AreEqual(4, series.DataLabels.Count);
}
// Get the enumerator for a data label collection
using (IEnumerator<ChartDataLabel> enumerator = chart.Series[0].DataLabels.GetEnumerator())
{
// And use it to go over all the data labels in one series and change their separator
while (enumerator.MoveNext())
{
Assert.AreEqual(", ", enumerator.Current.Separator);
enumerator.Current.Separator = " & ";
}
}
// If the chart looks too busy, we can remove data labels one by one
chart.Series[1].DataLabels.RemoveAt(2);
// We can also clear an entire data label collection for one whole series
chart.Series[2].DataLabels.Clear();
doc.Save(ArtifactsDir + "Charts.ChartDataLabels.docx");
}
/// <summary>
/// Apply uniform data labels with custom number format and separator to a number (determined by labelsCount) of data points in a series
/// </summary>
private void ApplyDataLabels(ChartSeries series, int labelsCount, string numberFormat, string separator)
{
for (int i = 0; i < labelsCount; i++)
{
ChartDataLabel label = series.DataLabels.Add(i);
Assert.False(label.IsVisible);
// Edit the appearance of the new data label
label.ShowCategoryName = true;
label.ShowSeriesName = true;
label.ShowValue = true;
label.ShowLeaderLines = true;
label.ShowLegendKey = true;
label.ShowPercentage = false;
Assert.False(label.ShowDataLabelsRange);
// Apply number format and separator
label.NumberFormat.FormatCode = numberFormat;
label.Separator = separator;
// The label automatically becomes visible
Assert.True(label.IsVisible);
}
}
//ExEnd
//ExStart
//ExFor:Charts.ChartSeries.Smooth
//ExFor:Charts.ChartDataPoint
//ExFor:Charts.ChartDataPoint.Index
//ExFor:Charts.ChartDataPointCollection
//ExFor:Charts.ChartDataPointCollection.Add(System.Int32)
//ExFor:Charts.ChartDataPointCollection.Clear
//ExFor:Charts.ChartDataPointCollection.Count
//ExFor:Charts.ChartDataPointCollection.GetEnumerator
//ExFor:Charts.ChartDataPointCollection.Item(System.Int32)
//ExFor:Charts.ChartDataPointCollection.RemoveAt(System.Int32)
//ExFor:Charts.ChartMarker
//ExFor:Charts.ChartMarker.Size
//ExFor:Charts.ChartMarker.Symbol
//ExFor:Charts.IChartDataPoint
//ExFor:Charts.IChartDataPoint.InvertIfNegative
//ExFor:Charts.IChartDataPoint.Marker
//ExFor:Charts.MarkerSymbol
//ExSummary:Shows how to customize chart data points.
[Test]
public void ChartDataPoint()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Add a line chart, which will have default data that we will use
Shape shape = builder.InsertChart(ChartType.Line, 500, 350);
Chart chart = shape.Chart;
// Apply diamond-shaped data points to the line of the first series
foreach (ChartSeries series in chart.Series)
{
ApplyDataPoints(series, 4, MarkerSymbol.Diamond, 15);
}
// We can further decorate a series line by smoothing it
chart.Series[0].Smooth = true;
// Get the enumerator for the data point collection from one series
using (IEnumerator<ChartDataPoint> enumerator = chart.Series[0].DataPoints.GetEnumerator())
{
// And use it to go over all the data labels in one series and change their separator
while (enumerator.MoveNext())
{
Assert.False(enumerator.Current.InvertIfNegative);
}
}
// If the chart looks too busy, we can remove data points one by one
chart.Series[1].DataPoints.RemoveAt(2);
// We can also clear an entire data point collection for one whole series
chart.Series[2].DataPoints.Clear();
doc.Save(ArtifactsDir + "Charts.ChartDataPoint.docx");
}
/// <summary>
/// Applies a number of data points to a series
/// </summary>
private void ApplyDataPoints(ChartSeries series, int dataPointsCount, MarkerSymbol markerSymbol, int dataPointSize)
{
for (int i = 0; i < dataPointsCount; i++)
{
ChartDataPoint point = series.DataPoints.Add(i);
point.Marker.Symbol = markerSymbol;
point.Marker.Size = dataPointSize;
Assert.AreEqual(i, point.Index);
}
}
//ExEnd
[Test]
public void PieChartExplosion()
{
//ExStart
//ExFor:Charts.IChartDataPoint.Explosion
//ExSummary:Shows how to manipulate the position of the portions of a pie chart.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Shape shape = builder.InsertChart(ChartType.Pie, 500, 350);
Chart chart = shape.Chart;
// In a pie chart, the portions are the data points, which cannot have markers or sizes applied to them
// However, we can set this variable to move any individual "slice" away from the center of the chart
ChartDataPoint cdp = chart.Series[0].DataPoints.Add(0);
cdp.Explosion = 10;
cdp = chart.Series[0].DataPoints.Add(1);
cdp.Explosion = 40;
doc.Save(ArtifactsDir + "Charts.PieChartExplosion.docx");
//ExEnd
}
[Test]
public void Bubble3D()
{
//ExStart
//ExFor:Charts.ChartDataLabel.ShowBubbleSize
//ExFor:Charts.IChartDataPoint.Bubble3D
//ExSummary:Demonstrates bubble chart-exclusive features.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a bubble chart with 3D effects on each bubble
Shape shape = builder.InsertChart(ChartType.Bubble3D, 500, 350);
Chart chart = shape.Chart;
Assert.True(chart.Series[0].Bubble3D);
// Apply a data label to each bubble that displays the size of its bubble
for (int i = 0; i < 3; i++)
{
ChartDataLabel cdl = chart.Series[0].DataLabels.Add(i);
cdl.ShowBubbleSize = true;
}
doc.Save(ArtifactsDir + "Charts.Bubble3D.docx");
//ExEnd
}
//ExStart
//ExFor:Charts.ChartAxis.Type
//ExFor:Charts.ChartAxisType
//ExFor:Charts.ChartType
//ExFor:Charts.Chart.Series
//ExFor:Charts.ChartSeriesCollection.Add(String,DateTime[],Double[])
//ExFor:Charts.ChartSeriesCollection.Add(String,Double[],Double[])
//ExFor:Charts.ChartSeriesCollection.Add(String,Double[],Double[],Double[])
//ExFor:Charts.ChartSeriesCollection.Add(String,String[],Double[])
//ExSummary:Shows an appropriate graph type for each chart series.
[Test] //ExSkip
public void ChartSeriesCollection()
{
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// There are 4 ways of populating a chart's series collection
// 1: Each series has a string array of categories, each with a corresponding data value
// Some of the other possible applications are bar, column, line and surface charts
Chart chart = AppendChart(builder, ChartType.Column, 300, 300);
// Create and name 3 categories with a string array
string[] categories = { "Category 1", "Category 2", "Category 3" };
// Create 2 series of data, each with one point for every category
// This will generate a column graph with 3 clusters of 2 bars
chart.Series.Add("Series 1", categories, new [] { 76.6, 82.1, 91.6 });
chart.Series.Add("Series 2", categories, new [] { 64.2, 79.5, 94.0 });
// Categories are distributed along the X-axis while values are distributed along the Y-axis
Assert.AreEqual(ChartAxisType.Category, chart.AxisX.Type);
Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);
// 2: Each series will have a collection of dates with a corresponding value for each date
// Area, radar and stock charts are some of the appropriate chart types for this
chart = AppendChart(builder, ChartType.Area, 300, 300);
// Create a collection of dates to serve as categories
DateTime[] dates = { new DateTime(2014, 3, 31),
new DateTime(2017, 1, 23),
new DateTime(2017, 6, 18),
new DateTime(2019, 11, 22),
new DateTime(2020, 9, 7)
};
// Add one series with one point for each date
// Our sporadic dates will be distributed along the X-axis in a linear fashion
chart.Series.Add("Series 1", dates, new [] { 15.8, 21.5, 22.9, 28.7, 33.1 });
// 3: Each series will take two data arrays
// Appropriate for scatter plots
chart = AppendChart(builder, ChartType.Scatter, 300, 300);
// In each series, the first array contains the X-coordinates and the second contains respective Y-coordinates of points
chart.Series.Add("Series 1", new[] { 3.1, 3.5, 6.3, 4.1, 2.2, 8.3, 1.2, 3.6 }, new[] { 3.1, 6.3, 4.6, 0.9, 8.5, 4.2, 2.3, 9.9 });
chart.Series.Add("Series 2", new[] { 2.6, 7.3, 4.5, 6.6, 2.1, 9.3, 0.7, 3.3 }, new[] { 7.1, 6.6, 3.5, 7.8, 7.7, 9.5, 1.3, 4.6 });
// Both axes are value axes in this case
Assert.AreEqual(ChartAxisType.Value, chart.AxisX.Type);
Assert.AreEqual(ChartAxisType.Value, chart.AxisY.Type);
// 4: Each series will be built from three data arrays, used for bubble charts
chart = AppendChart(builder, ChartType.Bubble, 300, 300);
// The first two arrays contain X/Y coordinates like above and the third determines the thickness of each point
chart.Series.Add("Series 1", new [] { 1.1, 5.0, 9.8 }, new [] { 1.2, 4.9, 9.9 }, new [] { 2.0, 4.0, 8.0 });
doc.Save(ArtifactsDir + "Charts.ChartSeriesCollection.docx");
}
/// <summary>
/// Get the DocumentBuilder to insert a chart of a specified ChartType, width and height and clean out its default data
/// </summary>
private Chart AppendChart(DocumentBuilder builder, ChartType chartType, double width, double height)
{
Shape chartShape = builder.InsertChart(chartType, width, height);
Chart chart = chartShape.Chart;
chart.Series.Clear();
Assert.AreEqual(0, chart.Series.Count);
return chart;
}
//ExEnd
[Test]
public void ChartSeriesCollectionModify()
{
//ExStart
//ExFor:Charts.ChartSeriesCollection
//ExFor:Charts.ChartSeriesCollection.Clear
//ExFor:Charts.ChartSeriesCollection.Count
//ExFor:Charts.ChartSeriesCollection.GetEnumerator
//ExFor:Charts.ChartSeriesCollection.Item(Int32)
//ExFor:Charts.ChartSeriesCollection.RemoveAt(Int32)
//ExSummary:Shows how to work with a chart's data collection.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Use a document builder to insert a bar chart
Shape chartShape = builder.InsertChart(ChartType.Column, 400, 300);
Chart chart = chartShape.Chart;
// All charts come with demo data
// This column chart currently has 3 series with 4 categories, which means 4 clusters, 3 columns in each
ChartSeriesCollection chartData = chart.Series;
Assert.AreEqual(3, chartData.Count);
// Iterate through the series with an enumerator and print their names
using (IEnumerator<ChartSeries> enumerator = chart.Series.GetEnumerator())
{
// And use it to go over all the data labels in one series and change their separator
while (enumerator.MoveNext())
{
Console.WriteLine(enumerator.Current.Name);
}
}
// We can add new data by adding a new series to the collection, with categories and data
// We will match the existing category/series names in the demo data and add a 4th column to each column cluster
string[] categories = { "Category 1", "Category 2", "Category 3", "Category 4" };
chart.Series.Add("Series 4", categories, new[] { 4.4, 7.0, 3.5, 2.1 });
Assert.AreEqual(4, chartData.Count);
Assert.AreEqual("Series 4", chartData[3].Name);
// We can remove series by index
chartData.RemoveAt(2);
Assert.AreEqual(3, chartData.Count);
Assert.AreEqual("Series 4", chartData[2].Name);
// We can also remove out all the series
// This leaves us with an empty graph and is a convenient way of wiping out demo data
chartData.Clear();
Assert.AreEqual(0, chartData.Count);
//ExEnd
}
[Test]
public void AxisScaling()
{
//ExStart
//ExFor:Charts.AxisScaleType
//ExFor:Charts.AxisScaling
//ExFor:Charts.AxisScaling.LogBase
//ExFor:Charts.AxisScaling.Type
//ExSummary:Shows how to set up logarithmic axis scaling.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a scatter chart and clear its default data series
Shape chartShape = builder.InsertChart(ChartType.Scatter, 450, 300);
Chart chart = chartShape.Chart;
chart.Series.Clear();
// Insert a series with X/Y coordinates for 5 points
chart.Series.Add("Series 1", new[] { 1.0, 2.0, 3.0, 4.0, 5.0 }, new[] { 1.0, 20.0, 400.0, 8000.0, 160000.0 });
// The scaling of the X axis is linear by default, which means it will display "0, 1, 2, 3..."
Assert.AreEqual(AxisScaleType.Linear, chart.AxisX.Scaling.Type);
// Linear axis scaling is suitable for our X-values, but not our erratic Y-values
// We can set the scaling of the Y-axis to Logarithmic with a base of 20
// The Y-axis will now display "1, 20, 400, 8000...", which is ideal for accurate representation of this set of Y-values
chart.AxisY.Scaling.Type = AxisScaleType.Logarithmic;
chart.AxisY.Scaling.LogBase = 20.0;
doc.Save(ArtifactsDir + "Charts.AxisScaling.docx");
//ExEnd
}
[Test]
public void AxisBound()
{
//ExStart
//ExFor:Charts.AxisBound.#ctor
//ExFor:Charts.AxisBound.IsAuto
//ExFor:Charts.AxisBound.Value
//ExFor:Charts.AxisBound.ValueAsDate
//ExSummary:Shows how to set custom axis bounds.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a scatter chart, remove default data and populate it with data from a ChartSeries
Shape chartShape = builder.InsertChart(ChartType.Scatter, 450, 300);
Chart chart = chartShape.Chart;
chart.Series.Clear();
chart.Series.Add("Series 1", new[] { 1.1, 5.4, 7.9, 3.5, 2.1, 9.7 }, new[] { 2.1, 0.3, 0.6, 3.3, 1.4, 1.9 });
// By default, the axis bounds are automatically defined so all the series data within the table is included
Assert.True(chart.AxisX.Scaling.Minimum.IsAuto);
// If we wish to set our own scale bounds, we need to replace them with new ones
// Both the axis rulers will go from 0 to 10
chart.AxisX.Scaling.Minimum = new AxisBound(0);
chart.AxisX.Scaling.Maximum = new AxisBound(10);
chart.AxisY.Scaling.Minimum = new AxisBound(0);
chart.AxisY.Scaling.Maximum = new AxisBound(10);
// These are custom and not defined automatically
Assert.False(chart.AxisX.Scaling.Minimum.IsAuto);
Assert.False(chart.AxisY.Scaling.Minimum.IsAuto);
// Create a line graph
chartShape = builder.InsertChart(ChartType.Line, 450, 300);
chart = chartShape.Chart;
chart.Series.Clear();
// Create a collection of dates, which will make up the X axis
DateTime[] dates = { new DateTime(1973, 5, 11),
new DateTime(1981, 2, 4),
new DateTime(1985, 9, 23),
new DateTime(1989, 6, 28),
new DateTime(1994, 12, 15)
};
// Assign a Y-value for each date
chart.Series.Add("Series 1", dates, new[] { 3.0, 4.7, 5.9, 7.1, 8.9 });
// These particular bounds will cut off categories from before 1980 and from 1990 and onwards
// This narrows the amount of categories and values in the viewport from 5 to 3
// Note that the graph still contains the out-of-range data because we can see the line tend towards it
chart.AxisX.Scaling.Minimum = new AxisBound(new DateTime(1980, 1, 1));
chart.AxisX.Scaling.Maximum = new AxisBound(new DateTime(1990, 1, 1));
doc.Save(ArtifactsDir + "Charts.AxisBound.docx");
//ExEnd
}
[Test]
public void ChartLegend()
{
//ExStart
//ExFor:Charts.Chart.Legend
//ExFor:Charts.ChartLegend
//ExFor:Charts.ChartLegend.Overlay
//ExFor:Charts.ChartLegend.Position
//ExFor:Charts.LegendPosition
//ExSummary:Shows how to edit the appearance of a chart's legend.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a line graph
Shape chartShape = builder.InsertChart(ChartType.Line, 450, 300);
Chart chart = chartShape.Chart;
// Get its legend
ChartLegend legend = chart.Legend;
// By default, other elements of a chart will not overlap with its legend
Assert.False(legend.Overlay);
// We can move its position by setting this attribute
legend.Position = LegendPosition.TopRight;
doc.Save(ArtifactsDir + "Charts.ChartLegend.docx");
//ExEnd
}
[Test]
public void AxisCross()
{
//ExStart
//ExFor:Charts.ChartAxis.AxisBetweenCategories
//ExFor:Charts.ChartAxis.CrossesAt
//ExSummary:Shows how to get a graph axis to cross at a custom location.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a column chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Column, 450, 250);
Chart chart = shape.Chart;
// Get the Y-axis to cross at a value of 3.0, making 3.0 the new Y-zero of our column chart
// This effectively means that all the columns with Y-values about 3.0 will be above the Y-centre and point up,
// while ones below 3.0 will point down
ChartAxis axis = chart.AxisX;
axis.AxisBetweenCategories = true;
axis.Crosses = AxisCrosses.Custom;
axis.CrossesAt = 3.0;
doc.Save(ArtifactsDir + "Charts.AxisCross.docx");
//ExEnd
}
[Test]
public void ChartAxisDisplayUnit()
{
//ExStart
//ExFor:Charts.AxisBuiltInUnit
//ExFor:Charts.ChartAxis.DisplayUnit
//ExFor:Charts.ChartAxis.MajorUnitIsAuto
//ExFor:Charts.ChartAxis.MajorUnitScale
//ExFor:Charts.ChartAxis.MinorUnitIsAuto
//ExFor:Charts.ChartAxis.MinorUnitScale
//ExFor:Charts.ChartAxis.TickLabelSpacing
//ExFor:Charts.ChartAxis.TickLabelAlignment
//ExFor:Charts.AxisDisplayUnit
//ExFor:Charts.AxisDisplayUnit.CustomUnit
//ExFor:Charts.AxisDisplayUnit.Unit
//ExSummary:Shows how to manipulate the tick marks and displayed values of a chart axis.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert a scatter chart, which is populated by default values
Shape shape = builder.InsertChart(ChartType.Scatter, 450, 250);
Chart chart = shape.Chart;
// Set they Y axis to show major ticks every at every 10 units and minor ticks at every 1 units
ChartAxis axis = chart.AxisY;
axis.MajorTickMark = AxisTickMark.Outside;
axis.MinorTickMark = AxisTickMark.Outside;
axis.MajorUnit = 10.0;
axis.MinorUnit = 1.0;
// Stretch out the bounds of the axis out to show 3 major ticks and 27 minor ticks
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(20);
// Do the same for the X-axis
axis = chart.AxisX;
axis.MajorTickMark = AxisTickMark.Inside;
axis.MinorTickMark = AxisTickMark.Inside;
axis.MajorUnit = 10.0;
axis.Scaling.Minimum = new AxisBound(-10);
axis.Scaling.Maximum = new AxisBound(30);
// We can also use this attribute to set minor tick spacing
axis.TickLabelSpacing = 2;
// We can define text alignment when axis tick labels are multi-line
// MS Word aligns them to the center by default
axis.TickLabelAlignment = ParagraphAlignment.Right;
// Get the axis to display values, but in millions
axis.DisplayUnit.Unit = AxisBuiltInUnit.Millions;
// Besides the built-in axis units we can choose from,
// we can also set the axis to display values in some custom denomination, using the following attribute
// The statement below is equivalent to the one above
axis.DisplayUnit.CustomUnit = 1000000.0;
doc.Save(ArtifactsDir + "Charts.ChartAxisDisplayUnit.docx");
//ExEnd
}
}
}
| 47,197
|
https://github.com/manh-hoang-nguyen/BIM4PM-AddinRevit/blob/master/ProjectManagement/BIM4PM.Data/Repositories/UserRepository.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
BIM4PM-AddinRevit
|
manh-hoang-nguyen
|
C#
|
Code
| 63
| 237
|
namespace BIM4PM.DataAccess
{
using BIM4PM.DataAccess.Interfaces;
using BIM4PM.DataAccess.Routes;
using BIM4PM.Model;
using RestSharp;
using System.Threading.Tasks;
public class UserRepository : IUserRepository
{
RestClient _client;
public UserRepository()
{
_client = RestSharpBase.Client;
}
public async Task<User> GetMeAsync()
{
RestSharpBase reqBase = new RestSharpBase(UserRoute.GetMe, Method.GET);
RestRequest req = reqBase.Request;
IRestResponse<User> response = await _client.ExecuteAsync<User>(req);
switch ((int)response.StatusCode)
{
case 200:
return response.Data;
default:
throw new System.Exception(response.StatusDescription);
}
}
}
}
| 36,732
|
https://github.com/cbig/japan-zsetup/blob/master/R/02_results/05_LSM_visualization.R
|
Github Open Source
|
Open Source
|
CC-BY-4.0, MIT
| 2,019
|
japan-zsetup
|
cbig
|
R
|
Code
| 182
| 755
|
library(RColorBrewer)
library(htmlwidgets)
library(leaflet)
library(raster)
library(rgdal)
library(zonator)
source("R/00_lib/utils.R")
# Load the project, creates japan_zproject. WARNING: loaded object is cached
# using memoise-package. If results have change, don't load the cached version.
zproject_japan <- .load_zproject("zsetup", cache = TRUE, debug = TRUE)
output_dir <- "zsetup/taxa_all/34_caz_wgt_con/34_caz_wgt_con_out"
dsn_geojson <- file.path(output_dir, "34_caz_wgt_con_PPA_LSM_1.geojson")
dsn_rank_tif <- file.path(output_dir, "34_caz_wgt_con.CAZ_DEA.rank.compressed.tif")
variant34_LSM <- readOGR(dsn_geojson, layer = ogrListLayers(dsn_geojson))
variant34_rank <- raster(dsn_rank_tif)
zpal <- colorBin(
palette = zlegend("spectral")$colors,
domain = c(0, 1)
)
prefecture_popup <- paste0("<strong>Prefecture: </strong>",
variant34_LSM$prefecture,
"<br><strong>Mean rank: </strong>",
variant34_LSM$Mean_rank,
"<br><strong>Spp dist. sum: </strong>",
variant34_LSM$Spp_distribution_sum,
"<br><strong>Spp dist. > 10%: </strong>",
variant34_LSM$Plus_10,
"<br><strong>Spp dist. > 1%: </strong>",
variant34_LSM$Plus_1,
"<br><strong>Spp dist. > 0.1%: </strong>",
variant34_LSM$Plus_01)
base_map <- leaflet(variant34_LSM) %>% addTiles()
poly_map <- base_map %>%
addPolygons(
stroke = FALSE, fillOpacity = 0.8, smoothFactor = 0.5,
color = ~zpal(Mean_rank), popup = prefecture_popup
) %>%
addLegend("bottomright", pal = zpal, values = c(0, 1),
title = "Mean rank",
#labFormat = labelFormat(prefix = "$"),
opacity = 1
)
html_output <- gsub(".geojson", ".html", normalizePath(dsn_geojson))
saveWidget(poly_map, file = html_output)
raster_map <- base_map %>%
addRasterImage(variant34_rank, colors = zpal, opacity = 0.8) %>%
addLegend(pal = zpal, values = c(0, 1),
title = "Rank priority")
| 10,438
|
https://github.com/cvandijck/VTKExamples/blob/master/src/Cxx/VisualizationAlgorithms/Office.cxx
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
VTKExamples
|
cvandijck
|
C++
|
Code
| 905
| 6,040
|
#include <vtkActor.h>
#include <vtkCamera.h>
#include <vtkNamedColors.h>
#include <vtkPointData.h>
#include <vtkPointSource.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkStreamTracer.h>
#include <vtkStructuredGrid.h>
#include <vtkStructuredGridGeometryFilter.h>
#include <vtkStructuredGridOutlineFilter.h>
#include <vtkStructuredGridReader.h>
#include <array>
#include <vector>
int main(int argc, char* argv[])
{
if (argc < 2)
{
std::cout << "Usage: " << argv[0] << " filename [center]" << std::endl;
std::cout
<< "Demonstrate the use of vtkPointSource to generate streamlines."
<< std::endl;
std::cout << "Where: " << std::endl;
std::cout << " filename: office.binary.vtk" << std::endl;
std::cout << " center: An optional parameter choosing the center for "
"the seeds."
<< std::endl;
std::cout
<< " 0 - Corresponds to Fig 9-47(a) in the VTK textbook."
<< std::endl;
std::cout << " 1 - A slight shift to the left." << std::endl;
std::cout << " 2 - A slight shift to the upper left. (from "
"the Original code)."
<< std::endl;
std::cout
<< " 3 - The default, a slight shift to the upper left."
<< std::endl;
std::cout << " Roughly corresponds to Fig 9-47(b) in the "
"VTK textbook."
<< std::endl;
return EXIT_FAILURE;
}
auto center = 3;
if (argc > 2)
{
center = std::abs(atoi(argv[2]));
}
// These are the centers for the streamline seed.
std::vector<std::array<double, 3>> seedCenters{
{0.0, 2.1, 0.5}, {0.1, 2.1, 0.5}, {0.1, 2.7, 0.5}, {0.08, 2.7, 0.5}};
center = (center < static_cast<int>(seedCenters.size()))
? center
: static_cast<int>(seedCenters.size()) - 1;
auto colors =
vtkSmartPointer<vtkNamedColors>::New();
std::array<double, 3> tableTopColor = {0.59, 0.427, 0.392};
std::array<double, 3> filingCabinetColor = {0.8, 0.8, 0.6};
std::array<double, 3> bookShelfColor = {0.8, 0.8, 0.6};
std::array<double, 3> windowColor = {0.3, 0.3, 0.5};
colors->SetColor("TableTop", tableTopColor.data());
colors->SetColor("FilingCabinet", filingCabinetColor.data());
colors->SetColor("BookShelf", bookShelfColor.data());
colors->SetColor("Window", windowColor.data());
// We read a data file that represents a CFD analysis of airflow in an office
// (with ventilation and a burning cigarette).
auto reader =
vtkSmartPointer<vtkStructuredGridReader>::New();
reader->SetFileName(argv[1]);
// Create the scene.
// We generate a whole bunch of planes which correspond to
// the geometry in the analysis; tables, bookshelves and so on.
auto table1 =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
table1->SetInputConnection(reader->GetOutputPort());
table1->SetExtent(11, 15, 7, 9, 8, 8);
auto mapTable1 =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapTable1->SetInputConnection(table1->GetOutputPort());
mapTable1->ScalarVisibilityOff();
auto table1Actor =
vtkSmartPointer<vtkActor>::New();
table1Actor->SetMapper(mapTable1);
table1Actor->GetProperty()->SetColor(
colors->GetColor3d("TableTop").GetData());
auto table2 =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
table2->SetInputConnection(reader->GetOutputPort());
table2->SetExtent(11, 15, 10, 12, 8, 8);
auto mapTable2 =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapTable2->SetInputConnection(table2->GetOutputPort());
mapTable2->ScalarVisibilityOff();
auto table2Actor = vtkSmartPointer<vtkActor>::New();
table2Actor->SetMapper(mapTable2);
table2Actor->GetProperty()->SetColor(
colors->GetColor3d("TableTop").GetData());
auto FilingCabinet1 =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
FilingCabinet1->SetInputConnection(reader->GetOutputPort());
FilingCabinet1->SetExtent(15, 15, 7, 9, 0, 8);
auto mapFilingCabinet1 =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapFilingCabinet1->SetInputConnection(FilingCabinet1->GetOutputPort());
mapFilingCabinet1->ScalarVisibilityOff();
auto FilingCabinet1Actor =
vtkSmartPointer<vtkActor>::New();
FilingCabinet1Actor->SetMapper(mapFilingCabinet1);
FilingCabinet1Actor->GetProperty()->SetColor(
colors->GetColor3d("FilingCabinet").GetData());
auto FilingCabinet2 =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
FilingCabinet2->SetInputConnection(reader->GetOutputPort());
FilingCabinet2->SetExtent(15, 15, 10, 12, 0, 8);
auto mapFilingCabinet2 =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapFilingCabinet2->SetInputConnection(FilingCabinet2->GetOutputPort());
mapFilingCabinet2->ScalarVisibilityOff();
auto FilingCabinet2Actor =
vtkSmartPointer<vtkActor>::New();
FilingCabinet2Actor->SetMapper(mapFilingCabinet2);
FilingCabinet2Actor->GetProperty()->SetColor(
colors->GetColor3d("FilingCabinet").GetData());
auto bookshelf1Top =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf1Top->SetInputConnection(reader->GetOutputPort());
bookshelf1Top->SetExtent(13, 13, 0, 4, 0, 11);
auto mapBookshelf1Top =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf1Top->SetInputConnection(bookshelf1Top->GetOutputPort());
mapBookshelf1Top->ScalarVisibilityOff();
auto bookshelf1TopActor =
vtkSmartPointer<vtkActor>::New();
bookshelf1TopActor->SetMapper(mapBookshelf1Top);
bookshelf1TopActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto bookshelf1Bottom =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf1Bottom->SetInputConnection(reader->GetOutputPort());
bookshelf1Bottom->SetExtent(20, 20, 0, 4, 0, 11);
auto mapBookshelf1Bottom =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf1Bottom->SetInputConnection(bookshelf1Bottom->GetOutputPort());
mapBookshelf1Bottom->ScalarVisibilityOff();
auto bookshelf1BottomActor =
vtkSmartPointer<vtkActor>::New();
bookshelf1BottomActor->SetMapper(mapBookshelf1Bottom);
bookshelf1BottomActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto bookshelf1Front =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf1Front->SetInputConnection(reader->GetOutputPort());
bookshelf1Front->SetExtent(13, 20, 0, 0, 0, 11);
auto mapBookshelf1Front =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf1Front->SetInputConnection(bookshelf1Front->GetOutputPort());
mapBookshelf1Front->ScalarVisibilityOff();
auto bookshelf1FrontActor =
vtkSmartPointer<vtkActor>::New();
bookshelf1FrontActor->SetMapper(mapBookshelf1Front);
bookshelf1FrontActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto bookshelf1Back =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf1Back->SetInputConnection(reader->GetOutputPort());
bookshelf1Back->SetExtent(13, 20, 4, 4, 0, 11);
auto mapBookshelf1Back =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf1Back->SetInputConnection(bookshelf1Back->GetOutputPort());
mapBookshelf1Back->ScalarVisibilityOff();
auto bookshelf1BackActor =
vtkSmartPointer<vtkActor>::New();
bookshelf1BackActor->SetMapper(mapBookshelf1Back);
bookshelf1BackActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto bookshelf1LHS =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf1LHS->SetInputConnection(reader->GetOutputPort());
bookshelf1LHS->SetExtent(13, 20, 0, 4, 0, 0);
auto mapBookshelf1LHS =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf1LHS->SetInputConnection(bookshelf1LHS->GetOutputPort());
mapBookshelf1LHS->ScalarVisibilityOff();
auto bookshelf1LHSActor =
vtkSmartPointer<vtkActor>::New();
bookshelf1LHSActor->SetMapper(mapBookshelf1LHS);
bookshelf1LHSActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto bookshelf1RHS =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf1RHS->SetInputConnection(reader->GetOutputPort());
bookshelf1RHS->SetExtent(13, 20, 0, 4, 11, 11);
auto mapBookshelf1RHS =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf1RHS->SetInputConnection(bookshelf1RHS->GetOutputPort());
mapBookshelf1RHS->ScalarVisibilityOff();
auto bookshelf1RHSActor =
vtkSmartPointer<vtkActor>::New();
bookshelf1RHSActor->SetMapper(mapBookshelf1RHS);
bookshelf1RHSActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto bookshelf2Top =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf2Top->SetInputConnection(reader->GetOutputPort());
bookshelf2Top->SetExtent(13, 13, 15, 19, 0, 11);
auto mapBookshelf2Top =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf2Top->SetInputConnection(bookshelf2Top->GetOutputPort());
mapBookshelf2Top->ScalarVisibilityOff();
auto bookshelf2TopActor =
vtkSmartPointer<vtkActor>::New();
bookshelf2TopActor->SetMapper(mapBookshelf2Top);
bookshelf2TopActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto bookshelf2Bottom =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf2Bottom->SetInputConnection(reader->GetOutputPort());
bookshelf2Bottom->SetExtent(20, 20, 15, 19, 0, 11);
auto mapBookshelf2Bottom =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf2Bottom->SetInputConnection(bookshelf2Bottom->GetOutputPort());
mapBookshelf2Bottom->ScalarVisibilityOff();
auto bookshelf2BottomActor =
vtkSmartPointer<vtkActor>::New();
bookshelf2BottomActor->SetMapper(mapBookshelf2Bottom);
bookshelf2BottomActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto bookshelf2Front =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf2Front->SetInputConnection(reader->GetOutputPort());
bookshelf2Front->SetExtent(13, 20, 15, 15, 0, 11);
auto mapBookshelf2Front =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf2Front->SetInputConnection(bookshelf2Front->GetOutputPort());
mapBookshelf2Front->ScalarVisibilityOff();
auto bookshelf2FrontActor =
vtkSmartPointer<vtkActor>::New();
bookshelf2FrontActor->SetMapper(mapBookshelf2Front);
bookshelf2FrontActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto bookshelf2Back =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf2Back->SetInputConnection(reader->GetOutputPort());
bookshelf2Back->SetExtent(13, 20, 19, 19, 0, 11);
auto mapBookshelf2Back =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf2Back->SetInputConnection(bookshelf2Back->GetOutputPort());
mapBookshelf2Back->ScalarVisibilityOff();
auto bookshelf2BackActor =
vtkSmartPointer<vtkActor>::New();
bookshelf2BackActor->SetMapper(mapBookshelf2Back);
bookshelf2BackActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto bookshelf2LHS =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf2LHS->SetInputConnection(reader->GetOutputPort());
bookshelf2LHS->SetExtent(13, 20, 15, 19, 0, 0);
auto mapBookshelf2LHS =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf2LHS->SetInputConnection(bookshelf2LHS->GetOutputPort());
mapBookshelf2LHS->ScalarVisibilityOff();
auto bookshelf2LHSActor =
vtkSmartPointer<vtkActor>::New();
bookshelf2LHSActor->SetMapper(mapBookshelf2LHS);
bookshelf2LHSActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto bookshelf2RHS =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
bookshelf2RHS->SetInputConnection(reader->GetOutputPort());
bookshelf2RHS->SetExtent(13, 20, 15, 19, 11, 11);
auto mapBookshelf2RHS =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapBookshelf2RHS->SetInputConnection(bookshelf2RHS->GetOutputPort());
mapBookshelf2RHS->ScalarVisibilityOff();
auto bookshelf2RHSActor =
vtkSmartPointer<vtkActor>::New();
bookshelf2RHSActor->SetMapper(mapBookshelf2RHS);
bookshelf2RHSActor->GetProperty()->SetColor(
colors->GetColor3d("BookShelf").GetData());
auto window =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
window->SetInputConnection(reader->GetOutputPort());
window->SetExtent(20, 20, 6, 13, 10, 13);
auto mapWindow =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapWindow->SetInputConnection(window->GetOutputPort());
mapWindow->ScalarVisibilityOff();
auto windowActor = vtkSmartPointer<vtkActor>::New();
windowActor->SetMapper(mapWindow);
windowActor->GetProperty()->SetColor(colors->GetColor3d("Window").GetData());
auto outlet =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
outlet->SetInputConnection(reader->GetOutputPort());
outlet->SetExtent(0, 0, 9, 10, 14, 16);
auto mapOutlet =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapOutlet->SetInputConnection(outlet->GetOutputPort());
mapOutlet->ScalarVisibilityOff();
auto outletActor = vtkSmartPointer<vtkActor>::New();
outletActor->SetMapper(mapOutlet);
outletActor->GetProperty()->SetColor(
colors->GetColor3d("lamp_black").GetData());
auto inlet =
vtkSmartPointer<vtkStructuredGridGeometryFilter>::New();
inlet->SetInputConnection(reader->GetOutputPort());
inlet->SetExtent(0, 0, 9, 10, 0, 6);
auto mapInlet =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapInlet->SetInputConnection(inlet->GetOutputPort());
mapInlet->ScalarVisibilityOff();
auto inletActor = vtkSmartPointer<vtkActor>::New();
inletActor->SetMapper(mapInlet);
inletActor->GetProperty()->SetColor(
colors->GetColor3d("lamp_black").GetData());
auto outline =
vtkSmartPointer<vtkStructuredGridOutlineFilter>::New();
outline->SetInputConnection(reader->GetOutputPort());
auto mapOutline =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapOutline->SetInputConnection(outline->GetOutputPort());
auto outlineActor = vtkSmartPointer<vtkActor>::New();
outlineActor->SetMapper(mapOutline);
outlineActor->GetProperty()->SetColor(colors->GetColor3d("Black").GetData());
// Create the source for the streamtubes.
auto seeds =
vtkSmartPointer<vtkPointSource>::New();
seeds->SetRadius(0.075);
seeds->SetCenter(seedCenters[center].data());
seeds->SetNumberOfPoints(25);
auto streamers =
vtkSmartPointer<vtkStreamTracer>::New();
streamers->SetInputConnection(reader->GetOutputPort());
streamers->SetSourceConnection(seeds->GetOutputPort());
streamers->SetMaximumPropagation(500);
streamers->SetMinimumIntegrationStep(0.1);
streamers->SetMaximumIntegrationStep(1.0);
streamers->SetInitialIntegrationStep(0.2);
streamers->SetIntegratorType(2);
streamers->Update();
auto mapStreamers =
vtkSmartPointer<vtkPolyDataMapper>::New();
mapStreamers->SetInputConnection(streamers->GetOutputPort());
mapStreamers->SetScalarRange(
reader->GetOutput()->GetPointData()->GetScalars()->GetRange());
auto streamersActor = vtkSmartPointer<vtkActor>::New();
streamersActor->SetMapper(mapStreamers);
// Now create the usual graphics stuff.
auto renderer = vtkSmartPointer<vtkRenderer>::New();
vtkSmartPointer<vtkRenderWindow> renderWindow =
vtkSmartPointer<vtkRenderWindow>::New();
renderWindow->AddRenderer(renderer);
auto interactor =
vtkSmartPointer<vtkRenderWindowInteractor>::New();
interactor->SetRenderWindow(renderWindow);
renderer->AddActor(table1Actor);
renderer->AddActor(table2Actor);
renderer->AddActor(FilingCabinet1Actor);
renderer->AddActor(FilingCabinet2Actor);
renderer->AddActor(bookshelf1TopActor);
renderer->AddActor(bookshelf1BottomActor);
renderer->AddActor(bookshelf1FrontActor);
renderer->AddActor(bookshelf1BackActor);
renderer->AddActor(bookshelf1LHSActor);
renderer->AddActor(bookshelf1RHSActor);
renderer->AddActor(bookshelf2TopActor);
renderer->AddActor(bookshelf2BottomActor);
renderer->AddActor(bookshelf2FrontActor);
renderer->AddActor(bookshelf2BackActor);
renderer->AddActor(bookshelf2LHSActor);
renderer->AddActor(bookshelf2RHSActor);
renderer->AddActor(windowActor);
renderer->AddActor(outletActor);
renderer->AddActor(inletActor);
renderer->AddActor(outlineActor);
renderer->AddActor(streamersActor);
renderer->SetBackground(colors->GetColor3d("SlateGray").GetData());
// Here we specify a particular view.
auto aCamera =
vtkSmartPointer<vtkCamera>::New();
aCamera->SetClippingRange(0.726079, 36.3039);
aCamera->SetFocalPoint(2.43584, 2.15046, 1.11104);
aCamera->SetPosition(-4.76183, -10.4426, 3.17203);
aCamera->SetViewUp(0.0511273, 0.132773, 0.989827);
aCamera->SetViewAngle(18.604);
aCamera->Zoom(1.2);
renderer->SetActiveCamera(aCamera);
renderWindow->SetSize(640, 400);
renderWindow->Render();
interactor->Start();
return EXIT_SUCCESS;
}
| 42,139
|
https://github.com/chenfengjin/crafty/blob/master/contracts/ExtendedERC20.sol
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
crafty
|
chenfengjin
|
Solidity
|
Code
| 36
| 148
|
pragma solidity ^0.4.21;
import "openzeppelin-zos/contracts/token/ERC20/DetailedERC20.sol";
contract ExtendedERC20 is DetailedERC20 {
string public tokenURI;
function initialize(
string _name,
string _symbol,
uint8 _decimals,
string _tokenURI
)
isInitializer("ExtendedERC20", "0")
public
{
DetailedERC20.initialize(_name, _symbol, _decimals);
tokenURI = _tokenURI;
}
}
| 19,424
|
https://github.com/OpertusMundi/catalogue-service/blob/master/tests/functional/__init__.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
catalogue-service
|
OpertusMundi
|
Python
|
Code
| 55
| 190
|
import logging
import json
import os
from catalogueapi.app import create_app
resources_dir = os.path.realpath(os.path.join(os.path.dirname(__file__), "../resources"));
# Setup/Teardown
app = None
def setup_package():
print(" == Setting up functional tests")
os.environ['TESTING'] = 'True'
os.environ['FLASK_ENV'] = 'testing'
global app
if 'FILE_CONFIG' in os.environ:
app = create_app(os.path.realpath(os.environ['FILE_CONFIG']))
else:
app = create_app()
def teardown_package():
print(" == Tearing down functional tests")
pass
| 11,900
|
https://github.com/TPaitoon/camelprod/blob/master/backend/views/bicyclesteamworkInfo/update.php
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,018
|
camelprod
|
TPaitoon
|
PHP
|
Code
| 47
| 223
|
<?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model common\models\BicyclesteamworkInfo */
$this->title = 'ค่าเข้างานนึ่งยางนอกจกย.';
$this->params['breadcrumbs'][] = ['label' => 'ค่าเข้างานนึ่งยางนอกจกย.', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->empid];
$this->params['breadcrumbs'][] = 'แก้ไขข้อมูล';
?>
<div class="bicyclesteamwork-info-update">
<?= $this->render('_form', [
'model' => $model,
'status' => 0
]) ?>
</div>
| 41,577
|
https://github.com/VasilisG/Game_of_Life_in_OpenMP_and_OpenCL/blob/master/Game of Life/Game_of_Life_GPU_OpenCL/MemoryObject.h
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Game_of_Life_in_OpenMP_and_OpenCL
|
VasilisG
|
C
|
Code
| 65
| 241
|
#ifndef MEMORY_OBJECT_H
#define MEMORY_OBJECT_H
#include <stdio.h>
#include <stdlib.h>
#include <CL/cl.h>
#include <CL/cl_gl.h>
#include <GL/gl.h>
/* Functions that wrap OpenCL memory object functions.*/
cl_mem createBuffer(cl_context context, cl_mem_flags flags, size_t size, void *host_ptr);
cl_mem createSubBuffer(cl_mem buffer, cl_mem_flags flags, cl_buffer_create_type buffer_create_type, const void *buffer_create_info);
cl_mem createFromGLBuffer(cl_context context, cl_mem_flags flags, GLuint bufobj);
cl_mem createFromGLTexture(cl_context context, cl_mem_flags flags, GLenum texture_target, GLint miplevel, GLuint texture);
void releaseMemObject(cl_mem memObject);
#endif // MEMORY_OBJECT_H
| 29,210
|
https://github.com/svelto/pacco/blob/master/src/project/defaults/components.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
pacco
|
svelto
|
JavaScript
|
Code
| 91
| 148
|
// Object used for making partial buildings by filtering out unwanted components
// In the form of `component: enabled`. A component's key can also be divided into sub objects, where each key is a component on its own; in this case the parent component will be assumed to be enabled
// Enabling/disabling is affected by component's key specificity. For instance `'widgets/form': false` will disable `widgets/form/ajax` too, but `'widgets/form/ajax': true` has an higher specificity and will enable it back
/* COMPONENTS */
const components = {};
/* EXPORT */
module.exports = components;
| 47,524
|
https://github.com/drishticone/2.0.0/blob/master/dashboard/header/footer.php
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
2.0.0
|
drishticone
|
PHP
|
Code
| 150
| 834
|
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Drishticone || Footer</title>
</head>
<body >
<?php
include 'header.php';
?><div style="height:200px;"></div>
<footer class="page-footer" style="background:#202020;">
<div class="container">
<div class="row">
<div class="col-md-6">
<a href="http://drishticone.org"><h4 class="title" style="color:#1d9d74;">Drishticone KNIT Newsletter</h4></a>
<div class="row">
<div class="col-md-6">
<p class="footerleft"><a href="#!">About KNIT</a></p>
<p class="footerleft"><a href="#!">Post Article</a></p>
<p class="footerleft"><a href="#!">Alumni Portal</a></p>
<p class="footerleft"><a href="#!">Submit Photo</a></p>
</div>
<div class="col-md-6">
<p class="footerleft"><a href="#!">Write News</a></p>
<p class="footerleft"><a href="#!">Admin Login</a></p>
<p class="footerleft"><a href="#!">Feedback</a></p>
<p class="footerleft"><a href="#!">Report a Problem</a></p>
</div></div>
</div>
<div class="col-md-4 col-md-offset-2 footerright">
<!--for aechive-->
<p class="footerleft" style="margin-top:30px">Archive</p>
<form class="form-inline">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><span class="glyphicon glyphicon-briefcase" aria-hidden="true"></span></div>
<select id="month" name="month" placeholder="Select Month" class="form-control input-md" >
<option value="#">Select Month</option>
<option value="M">Auguest 2015</option>
<option value="F">Sepetember 2015</option> </select>
</div>
</div>
<button type="submit" class="btn btn-primary sub" style="background:#1d9d74; border-radius:0px;">Submit <span class="glyphicon glyphicon-send" aria-hidden="true"></span></button>
</form>
<!--archives end-->
</div>
</div>
</div>
<div class="footer-copyright">
<div class="container">
<div class="row">
<div class="col-md-6">
© 2014 Copyright Drishticone Web Development Team
</div>
<div class="col-md-6">
<a style="float:right; color:#fff;" class="footerleft right" href="#!">Developer</a>
</div></div>
</div></div>
</footer>
</body>
</html>
| 31,324
|
https://github.com/chuongmep/revit/blob/master/samples/Revit 2012 SDK/Samples/Truss/CS/TrussForm.Designer.cs
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,021
|
revit
|
chuongmep
|
C#
|
Code
| 1,188
| 5,505
|
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
namespace Revit.SDK.Samples.Truss.CS
{
/// <summary>
/// window form contains one three picture box to show the
/// profile of truss geometry and profile and tabControl.
/// User can create truss, edit profile of truss and change type of truss members.
/// </summary>
partial class TrussForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.TrussTypeComboBox = new System.Windows.Forms.ComboBox();
this.TrussGraphicsTabControl = new System.Windows.Forms.TabControl();
this.ViewTabPage = new System.Windows.Forms.TabPage();
this.Notelabel = new System.Windows.Forms.Label();
this.ViewComboBox = new System.Windows.Forms.ComboBox();
this.ViewLabel = new System.Windows.Forms.Label();
this.CreateButton = new System.Windows.Forms.Button();
this.TrussMembersTabPage = new System.Windows.Forms.TabPage();
this.BeamTypeLabel = new System.Windows.Forms.Label();
this.ChangeBeamTypeButton = new System.Windows.Forms.Button();
this.BeamTypeComboBox = new System.Windows.Forms.ComboBox();
this.TrussMembersPictureBox = new System.Windows.Forms.PictureBox();
this.ProfileEditTabPage = new System.Windows.Forms.TabPage();
this.CleanChordbutton = new System.Windows.Forms.Button();
this.BottomChordButton = new System.Windows.Forms.Button();
this.TopChordButton = new System.Windows.Forms.Button();
this.UpdateButton = new System.Windows.Forms.Button();
this.RestoreButton = new System.Windows.Forms.Button();
this.ProfileEditPictureBox = new System.Windows.Forms.PictureBox();
this.TrussTypeLabel = new System.Windows.Forms.Label();
this.CloseButton = new System.Windows.Forms.Button();
this.TrussGraphicsTabControl.SuspendLayout();
this.ViewTabPage.SuspendLayout();
this.TrussMembersTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.TrussMembersPictureBox)).BeginInit();
this.ProfileEditTabPage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.ProfileEditPictureBox)).BeginInit();
this.SuspendLayout();
//
// TrussTypeComboBox
//
this.TrussTypeComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.TrussTypeComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.TrussTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.TrussTypeComboBox.FormattingEnabled = true;
this.TrussTypeComboBox.Location = new System.Drawing.Point(84, 6);
this.TrussTypeComboBox.Name = "TrussTypeComboBox";
this.TrussTypeComboBox.Size = new System.Drawing.Size(212, 21);
this.TrussTypeComboBox.TabIndex = 1;
this.TrussTypeComboBox.SelectedIndexChanged += new System.EventHandler(this.TrussTypeComboBox_SelectedIndexChanged);
//
// TrussGraphicsTabControl
//
this.TrussGraphicsTabControl.Controls.Add(this.ViewTabPage);
this.TrussGraphicsTabControl.Controls.Add(this.TrussMembersTabPage);
this.TrussGraphicsTabControl.Controls.Add(this.ProfileEditTabPage);
this.TrussGraphicsTabControl.Location = new System.Drawing.Point(12, 41);
this.TrussGraphicsTabControl.Name = "TrussGraphicsTabControl";
this.TrussGraphicsTabControl.SelectedIndex = 0;
this.TrussGraphicsTabControl.Size = new System.Drawing.Size(404, 343);
this.TrussGraphicsTabControl.TabIndex = 2;
this.TrussGraphicsTabControl.Selecting += new System.Windows.Forms.TabControlCancelEventHandler(this.TrussGraphicsTabControl_Selecting);
this.TrussGraphicsTabControl.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TrussGraphicsTabControl_KeyPress);
//
// ViewTabPage
//
this.ViewTabPage.Controls.Add(this.Notelabel);
this.ViewTabPage.Controls.Add(this.ViewComboBox);
this.ViewTabPage.Controls.Add(this.ViewLabel);
this.ViewTabPage.Controls.Add(this.CreateButton);
this.ViewTabPage.Location = new System.Drawing.Point(4, 22);
this.ViewTabPage.Name = "ViewTabPage";
this.ViewTabPage.Padding = new System.Windows.Forms.Padding(3);
this.ViewTabPage.Size = new System.Drawing.Size(396, 317);
this.ViewTabPage.TabIndex = 0;
this.ViewTabPage.Text = "Create Truss";
this.ViewTabPage.UseVisualStyleBackColor = true;
//
// Notelabel
//
this.Notelabel.AutoSize = true;
this.Notelabel.Location = new System.Drawing.Point(6, 17);
this.Notelabel.Name = "Notelabel";
this.Notelabel.Size = new System.Drawing.Size(155, 13);
this.Notelabel.TabIndex = 5;
this.Notelabel.Text = "Select a View to build truss on :";
//
// ViewComboBox
//
this.ViewComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.ViewComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.ViewComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ViewComboBox.FormattingEnabled = true;
this.ViewComboBox.Location = new System.Drawing.Point(48, 57);
this.ViewComboBox.Name = "ViewComboBox";
this.ViewComboBox.Size = new System.Drawing.Size(236, 21);
this.ViewComboBox.TabIndex = 4;
this.ViewComboBox.SelectedIndexChanged += new System.EventHandler(this.ViewComboBox_SelectedIndexChanged);
//
// ViewLabel
//
this.ViewLabel.AutoSize = true;
this.ViewLabel.Location = new System.Drawing.Point(6, 60);
this.ViewLabel.Name = "ViewLabel";
this.ViewLabel.Size = new System.Drawing.Size(36, 13);
this.ViewLabel.TabIndex = 3;
this.ViewLabel.Text = "View :";
//
// CreateButton
//
this.CreateButton.Location = new System.Drawing.Point(301, 55);
this.CreateButton.Name = "CreateButton";
this.CreateButton.Size = new System.Drawing.Size(80, 23);
this.CreateButton.TabIndex = 2;
this.CreateButton.Text = "&Create Truss";
this.CreateButton.UseVisualStyleBackColor = true;
this.CreateButton.Click += new System.EventHandler(this.CreateButton_Click);
//
// TrussMembersTabPage
//
this.TrussMembersTabPage.Controls.Add(this.BeamTypeLabel);
this.TrussMembersTabPage.Controls.Add(this.ChangeBeamTypeButton);
this.TrussMembersTabPage.Controls.Add(this.BeamTypeComboBox);
this.TrussMembersTabPage.Controls.Add(this.TrussMembersPictureBox);
this.TrussMembersTabPage.Location = new System.Drawing.Point(4, 22);
this.TrussMembersTabPage.Name = "TrussMembersTabPage";
this.TrussMembersTabPage.Padding = new System.Windows.Forms.Padding(3);
this.TrussMembersTabPage.Size = new System.Drawing.Size(396, 317);
this.TrussMembersTabPage.TabIndex = 1;
this.TrussMembersTabPage.Text = "Truss Members";
this.TrussMembersTabPage.UseVisualStyleBackColor = true;
//
// BeamTypeLabel
//
this.BeamTypeLabel.AutoSize = true;
this.BeamTypeLabel.Location = new System.Drawing.Point(6, 291);
this.BeamTypeLabel.Name = "BeamTypeLabel";
this.BeamTypeLabel.Size = new System.Drawing.Size(67, 13);
this.BeamTypeLabel.TabIndex = 3;
this.BeamTypeLabel.Text = "Beam Type :";
//
// ChangeBeamTypeButton
//
this.ChangeBeamTypeButton.Enabled = false;
this.ChangeBeamTypeButton.Location = new System.Drawing.Point(309, 288);
this.ChangeBeamTypeButton.Name = "ChangeBeamTypeButton";
this.ChangeBeamTypeButton.Size = new System.Drawing.Size(81, 21);
this.ChangeBeamTypeButton.TabIndex = 2;
this.ChangeBeamTypeButton.Text = "Change Type";
this.ChangeBeamTypeButton.UseVisualStyleBackColor = true;
this.ChangeBeamTypeButton.Click += new System.EventHandler(this.ChangeBeamTypeButton_Click);
//
// BeamTypeComboBox
//
this.BeamTypeComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.BeamTypeComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
this.BeamTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.BeamTypeComboBox.Enabled = false;
this.BeamTypeComboBox.FormattingEnabled = true;
this.BeamTypeComboBox.Location = new System.Drawing.Point(79, 288);
this.BeamTypeComboBox.Name = "BeamTypeComboBox";
this.BeamTypeComboBox.Size = new System.Drawing.Size(217, 21);
this.BeamTypeComboBox.TabIndex = 1;
this.BeamTypeComboBox.SelectedIndexChanged += new System.EventHandler(this.BeamTypeComboBox_SelectedIndexChanged);
//
// TrussMembersPictureBox
//
this.TrussMembersPictureBox.Location = new System.Drawing.Point(7, 7);
this.TrussMembersPictureBox.Name = "TrussMembersPictureBox";
this.TrussMembersPictureBox.Size = new System.Drawing.Size(384, 274);
this.TrussMembersPictureBox.TabIndex = 0;
this.TrussMembersPictureBox.TabStop = false;
this.TrussMembersPictureBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.TrussGeometryPictureBox_MouseMove);
this.TrussMembersPictureBox.Paint += new System.Windows.Forms.PaintEventHandler(this.TrussGeometryPictureBox_Paint);
this.TrussMembersPictureBox.MouseClick += new System.Windows.Forms.MouseEventHandler(this.TrussGeometryPictureBox_MouseClick);
//
// ProfileEditTabPage
//
this.ProfileEditTabPage.Controls.Add(this.CleanChordbutton);
this.ProfileEditTabPage.Controls.Add(this.BottomChordButton);
this.ProfileEditTabPage.Controls.Add(this.TopChordButton);
this.ProfileEditTabPage.Controls.Add(this.UpdateButton);
this.ProfileEditTabPage.Controls.Add(this.RestoreButton);
this.ProfileEditTabPage.Controls.Add(this.ProfileEditPictureBox);
this.ProfileEditTabPage.Location = new System.Drawing.Point(4, 22);
this.ProfileEditTabPage.Name = "ProfileEditTabPage";
this.ProfileEditTabPage.Size = new System.Drawing.Size(396, 317);
this.ProfileEditTabPage.TabIndex = 2;
this.ProfileEditTabPage.Text = "Profile Edit";
this.ProfileEditTabPage.UseVisualStyleBackColor = true;
//
// CleanChordbutton
//
this.CleanChordbutton.Location = new System.Drawing.Point(177, 286);
this.CleanChordbutton.Name = "CleanChordbutton";
this.CleanChordbutton.Size = new System.Drawing.Size(51, 23);
this.CleanChordbutton.TabIndex = 8;
this.CleanChordbutton.Text = "&Clean";
this.CleanChordbutton.UseVisualStyleBackColor = true;
this.CleanChordbutton.Click += new System.EventHandler(this.CleanChordbutton_Click);
//
// BottomChordButton
//
this.BottomChordButton.Location = new System.Drawing.Point(88, 286);
this.BottomChordButton.Name = "BottomChordButton";
this.BottomChordButton.Size = new System.Drawing.Size(83, 23);
this.BottomChordButton.TabIndex = 7;
this.BottomChordButton.Text = "&Bottom Chord";
this.BottomChordButton.UseVisualStyleBackColor = true;
this.BottomChordButton.Click += new System.EventHandler(this.BottomChordButton_Click);
//
// TopChordButton
//
this.TopChordButton.Location = new System.Drawing.Point(7, 286);
this.TopChordButton.Name = "TopChordButton";
this.TopChordButton.Size = new System.Drawing.Size(75, 23);
this.TopChordButton.TabIndex = 6;
this.TopChordButton.Text = "&Top Chord";
this.TopChordButton.UseVisualStyleBackColor = true;
this.TopChordButton.Click += new System.EventHandler(this.TopChordButton_Click);
//
// UpdateButton
//
this.UpdateButton.Location = new System.Drawing.Point(315, 287);
this.UpdateButton.Name = "UpdateButton";
this.UpdateButton.Size = new System.Drawing.Size(75, 23);
this.UpdateButton.TabIndex = 5;
this.UpdateButton.Text = "&Update";
this.UpdateButton.UseVisualStyleBackColor = true;
this.UpdateButton.Click += new System.EventHandler(this.UpdateButton_Click);
//
// RestoreButton
//
this.RestoreButton.Location = new System.Drawing.Point(234, 287);
this.RestoreButton.Name = "RestoreButton";
this.RestoreButton.Size = new System.Drawing.Size(75, 23);
this.RestoreButton.TabIndex = 4;
this.RestoreButton.Text = "&Restore";
this.RestoreButton.UseVisualStyleBackColor = true;
this.RestoreButton.Click += new System.EventHandler(this.RestoreButton_Click);
//
// ProfileEditPictureBox
//
this.ProfileEditPictureBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.ProfileEditPictureBox.Cursor = System.Windows.Forms.Cursors.Default;
this.ProfileEditPictureBox.Location = new System.Drawing.Point(7, 6);
this.ProfileEditPictureBox.Name = "ProfileEditPictureBox";
this.ProfileEditPictureBox.Size = new System.Drawing.Size(384, 274);
this.ProfileEditPictureBox.TabIndex = 3;
this.ProfileEditPictureBox.TabStop = false;
this.ProfileEditPictureBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ProfileEditPictureBox_MouseMove);
this.ProfileEditPictureBox.Paint += new System.Windows.Forms.PaintEventHandler(this.ProfileEditPictureBox_Paint);
this.ProfileEditPictureBox.MouseClick += new System.Windows.Forms.MouseEventHandler(this.ProfileEditPictureBox_MouseClick);
//
// TrussTypeLabel
//
this.TrussTypeLabel.AutoSize = true;
this.TrussTypeLabel.Location = new System.Drawing.Point(12, 9);
this.TrussTypeLabel.Name = "TrussTypeLabel";
this.TrussTypeLabel.Size = new System.Drawing.Size(66, 13);
this.TrussTypeLabel.TabIndex = 3;
this.TrussTypeLabel.Text = "Truss Type :";
//
// CloseButton
//
this.CloseButton.Location = new System.Drawing.Point(337, 390);
this.CloseButton.Name = "CloseButton";
this.CloseButton.Size = new System.Drawing.Size(80, 23);
this.CloseButton.TabIndex = 4;
this.CloseButton.Text = "&Close";
this.CloseButton.UseVisualStyleBackColor = true;
this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click);
//
// TrussForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.CloseButton;
this.ClientSize = new System.Drawing.Size(426, 420);
this.Controls.Add(this.CloseButton);
this.Controls.Add(this.TrussTypeLabel);
this.Controls.Add(this.TrussGraphicsTabControl);
this.Controls.Add(this.TrussTypeComboBox);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "TrussForm";
this.ShowInTaskbar = false;
this.Text = "TrussForm";
this.Load += new System.EventHandler(this.TrussForm_Load);
this.TrussGraphicsTabControl.ResumeLayout(false);
this.ViewTabPage.ResumeLayout(false);
this.ViewTabPage.PerformLayout();
this.TrussMembersTabPage.ResumeLayout(false);
this.TrussMembersTabPage.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.TrussMembersPictureBox)).EndInit();
this.ProfileEditTabPage.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.ProfileEditPictureBox)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox TrussTypeComboBox;
private System.Windows.Forms.TabControl TrussGraphicsTabControl;
private System.Windows.Forms.TabPage ViewTabPage;
private System.Windows.Forms.TabPage TrussMembersTabPage;
private System.Windows.Forms.TabPage ProfileEditTabPage;
private System.Windows.Forms.Button CreateButton;
private System.Windows.Forms.PictureBox TrussMembersPictureBox;
private System.Windows.Forms.Button UpdateButton;
private System.Windows.Forms.Button RestoreButton;
private System.Windows.Forms.PictureBox ProfileEditPictureBox;
private System.Windows.Forms.Label TrussTypeLabel;
private System.Windows.Forms.Button TopChordButton;
private System.Windows.Forms.Button BottomChordButton;
private System.Windows.Forms.Button CleanChordbutton;
private System.Windows.Forms.Button ChangeBeamTypeButton;
private System.Windows.Forms.ComboBox BeamTypeComboBox;
private System.Windows.Forms.Label BeamTypeLabel;
private System.Windows.Forms.ComboBox ViewComboBox;
private System.Windows.Forms.Label ViewLabel;
private System.Windows.Forms.Label Notelabel;
private System.Windows.Forms.Button CloseButton;
}
}
| 17,768
|
https://github.com/MMathisLab/py-ic-imaging-control/blob/master/setup.py
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
py-ic-imaging-control
|
MMathisLab
|
Python
|
Code
| 60
| 219
|
from setuptools import setup
def readme():
with open('README.md') as f:
return f.read()
setup(name='py-ic-imaging-control',
version='1.0',
description='Python wrapper for the IC Imaging Control SDK from The Imaging Source (TIS)',
long_description=readme(),
classifiers=['Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: GPL-3 License',
'Programming Language :: Python :: 2.7',
'Topic :: Scientific/Engineering',
],
keywords='tis imaging source',
url='https://github.com/zivlab/py-ic-imaging-control',
author='morefigs',
author_email='morefigs@gmail.com',
license='GPL-3',
packages=['pyicic'],
)
| 18,483
|
https://github.com/isgasho/namazu-swarm/blob/master/cmd/nmzswarm-agent.worker/exec.go
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
namazu-swarm
|
isgasho
|
Go
|
Code
| 114
| 416
|
package main
import (
"bytes"
"io"
"log"
"os"
"os/exec"
"time"
nmzswarm "github.com/osrg/namazu-swarm"
)
func exek(executor string, req nmzswarm.ChunkRequest) nmzswarm.ChunkResult {
var (
in bytes.Buffer
out bytes.Buffer
)
for _, workload := range req.Workloads {
log.Printf("Chunk %d: workload: %+v", req.ChunkID, workload)
in.Write([]byte(workload.ID + "\n"))
}
cmd := exec.Command("/bin/sh", "-c", executor)
cmd.Env = os.Environ()
cmd.Stdin = &in
cmd.Stdout = io.MultiWriter(&out, os.Stdout)
cmd.Stderr = io.MultiWriter(&out, os.Stderr)
begin := time.Now()
log.Printf("Chunk %d: executing with %q", req.ChunkID, executor)
err := cmd.Run()
elapsed := time.Now().Sub(begin)
if err != nil {
log.Printf("Chunk %d: got err=%v, elapsed=%v", req.ChunkID, err, elapsed)
} else {
log.Printf("Chunk %d: successful, elapsed=%v", req.ChunkID, elapsed)
}
return nmzswarm.ChunkResult{
ChunkID: req.ChunkID,
Successful: err == nil,
RawLog: out.String(),
}
}
| 10,000
|
https://github.com/Dilanka1997/newloan/blob/master/application/controllers/Login.php
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, MIT
| 2,020
|
newloan
|
Dilanka1997
|
PHP
|
Code
| 258
| 998
|
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
function __construct(){
parent::__construct();
// $this->check_isvalidated();
$this->load->model('App_Model');
}
public function index($msg = null)
{
$data['msg'] = $msg;
$this->load->view('Login', $data);
}
function Admin(){
if(! $this->session->userdata('validated')){
redirect('Login');
}
$AllLoanOne = $this->App_Model->getLoanOneData();
$data['AllLoanOne'] = $AllLoanOne;
$AllLoanTwo = $this->App_Model->getLoanTwoData();
$data['AllLoanTwo'] = $AllLoanTwo;
$this->load->view('adminPanel', $data);
}
function ViewOne(){
$U_id = $this->uri->segment(3);
$AllLoanOne = $this->App_Model->getSelectDataOne($U_id);
$data['AllLoanOne'] = $AllLoanOne;
$this->load->view('ViewPage', $data);
}
function ViewTwo(){
$U_id = $this->uri->segment(3);
$AllLoanOne = $this->App_Model->getSelectDataTwo($U_id);
$data['AllLoanOne'] = $AllLoanOne;
$this->load->view('ViewPageTwo', $data);
}
function DeleteFirst(){
$status = "";
$msg = "";
$id = $this->security->xss_clean($this->input->post('idPH'));
$file_id = $this->App_Model->deleteOne($id);
if ($file_id !== null) {
$status = "success";
$msg = "successfully deleted";
} else {
$status = "error";
$msg = "Something went wrong when deleting the center, please try again.";
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
function DeleteSecond(){
$status = "";
$msg = "";
$id = $this->security->xss_clean($this->input->post('idPH'));
$file_id = $this->App_Model->deleteTwo($id);
if ($file_id !== null) {
$status = "success";
$msg = "successfully deleted";
} else {
$status = "error";
$msg = "Something went wrong when deleting the center, please try again.";
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
public function process(){
// Load the model
$uName = $this->security->xss_clean($this->input->post('username'));
$password = $this->security->xss_clean($this->input->post('password'));
// Validate the user can login
$result = $this->App_Model->validate($uName,$password);
// Now we verify the result
if(! $result){
// If user did not validate, then show them login page again
$msg = '<font color=red>Invalid username and/or password.</font><br />';
// $data['msg'] = $msg;
$this->index($msg);
}else{
// If user did validate,
// Send them to members area
redirect('Login/Admin');
}
}
}
| 34,686
|
https://github.com/maxname/switchyard/blob/master/release/jboss-as7/tests/src/test/java/org/switchyard/test/jca/mockra/MockConnectionFactory.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,016
|
switchyard
|
maxname
|
Java
|
Code
| 387
| 1,054
|
/*
* Copyright 2013 Red Hat Inc. and/or its affiliates and other contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.switchyard.test.jca.mockra;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.naming.NamingException;
import javax.naming.Reference;
import javax.resource.Referenceable;
import javax.resource.ResourceException;
import javax.resource.cci.Connection;
import javax.resource.cci.ConnectionFactory;
import javax.resource.cci.ConnectionSpec;
import javax.resource.cci.RecordFactory;
import javax.resource.cci.ResourceAdapterMetaData;
import javax.resource.spi.ConnectionManager;
import org.apache.log4j.Logger;
/**
* MockConnectionFactory.
*
* @author <a href="mailto:tm.igarashi@gmail.com">Tomohisa Igarashi</a>
*
*/
public class MockConnectionFactory implements ConnectionFactory, Serializable, Referenceable {
private static final long serialVersionUID = 1L;
private Logger _logger = Logger.getLogger(MockConnectionFactory.class);
private ConnectionManager _cm;
private Reference _ref;
private List<InteractionListener> _listener = new ArrayList<InteractionListener>();
/**
* Constructor.
*/
public MockConnectionFactory() {
}
/**
* Constructor.
*
* @param cm {@link ConnectionManager}
*/
public MockConnectionFactory(ConnectionManager cm) {
_logger.debug("call MockConnectionFactory(" + cm + ")");
_cm = (ConnectionManager) cm;
_ref = null;
}
@Override
public Connection getConnection() throws ResourceException {
_logger.debug("call getConnection");
return new MockConnection(_listener);
}
@Override
public Connection getConnection(ConnectionSpec properties)
throws ResourceException {
_logger.debug("call getConnection(" + properties + ")");
return new MockConnection(_listener);
}
@Override
public RecordFactory getRecordFactory() throws ResourceException {
_logger.debug("call getRecordFactory");
return new MockRecordFactory();
}
@Override
public ResourceAdapterMetaData getMetaData() throws ResourceException {
_logger.debug("call getMetaData");
return new ResourceAdapterMetaData() {
@Override
public String getAdapterVersion() {
return null;
}
@Override
public String getAdapterVendorName() {
return null;
}
@Override
public String getAdapterName() {
return null;
}
@Override
public String getAdapterShortDescription() {
return null;
}
@Override
public String getSpecVersion() {
return null;
}
@Override
public String[] getInteractionSpecsSupported() {
return null;
}
@Override
public boolean supportsExecuteWithInputAndOutputRecord() {
return false;
}
@Override
public boolean supportsExecuteWithInputRecordOnly() {
return false;
}
@Override
public boolean supportsLocalTransactionDemarcation() {
return false;
}
};
}
@Override
public Reference getReference() throws NamingException {
_logger.debug("call getReference");
return _ref;
}
@Override
public void setReference(Reference ref) {
_logger.debug("call setReference(" + ref + ")");
_ref = ref;
}
/**
* set InteractionListener.
* @param listener InteractionListener
*/
public void setInteractionListener(InteractionListener listener) {
_listener.add(listener);
}
}
| 24,508
|
https://github.com/ScalablyTyped/ScalajsReactTyped/blob/master/w/workbox-google-analytics/src/main/scala/typingsJapgolly/workboxGoogleAnalytics/mod.scala
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
ScalajsReactTyped
|
ScalablyTyped
|
Scala
|
Code
| 40
| 200
|
package typingsJapgolly.workboxGoogleAnalytics
import typingsJapgolly.workboxGoogleAnalytics.initializeMod.InitializeOptions
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object mod {
@JSImport("workbox-google-analytics", JSImport.Namespace)
@js.native
val ^ : js.Any = js.native
inline def initialize(): Unit = ^.asInstanceOf[js.Dynamic].applyDynamic("initialize")().asInstanceOf[Unit]
inline def initialize(options: InitializeOptions): Unit = ^.asInstanceOf[js.Dynamic].applyDynamic("initialize")(options.asInstanceOf[js.Any]).asInstanceOf[Unit]
}
| 42,655
|
https://github.com/shrinathjoshi/Leetocode-30-day-challenge/blob/master/May Challenge/com/leetcode/MayChallenge/week4/IntervalListIntersections.java
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Leetocode-30-day-challenge
|
shrinathjoshi
|
Java
|
Code
| 202
| 547
|
package com.leetcode.MayChallenge.week4;
import java.util.ArrayList;
import java.util.List;
public class IntervalListIntersections {
public int[][] intervalIntersection(int[][] A, int[][] B) {
int a = 0;
int b = 0;
List<int[]> result = new ArrayList<int[]>();
while (a < A.length && b < B.length) {
int a0 = A[a][0];
int a1 = A[a][1];
int b0 = B[b][0];
int b1 = B[b][1];
if (a0 <= b1 && a1 >= b0) {
int u = Math.max(a0, b0);
int v = Math.min(a1, b1);
result.add(new int[] { u, v });
} else if (a0 >= b1 && a1 <= b0) {
int u = Math.max(a0, b0);
int v = Math.min(a1, b1);
result.add(new int[] { u, v });
}
if (a1 < b1)
a++;
else
b++;
}
return result.toArray(new int[result.size()][]);
}
public static void main(String[] args) {
int[][] A = { { 0, 2 }, { 5, 10 }, { 13, 23 }, { 24, 25 } },
B = { { 1, 5 }, { 8, 12 }, { 15, 24 }, { 25, 26 } };
int result[][] = new IntervalListIntersections().intervalIntersection(A, B);
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[0].length; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
| 36,882
|
https://github.com/rebane2001/2spicy2stream/blob/master/src/main/java/com/rebane2001/twospicytwostream/config/ModConfig.java
|
Github Open Source
|
Open Source
|
Unlicense
| 2,021
|
2spicy2stream
|
rebane2001
|
Java
|
Code
| 98
| 388
|
package com.rebane2001.twospicytwostream.config;
import com.rebane2001.twospicytwostream.BadWords;
import com.rebane2001.twospicytwostream.TwoSpicyTwoStream;
import net.minecraftforge.common.config.Config;
import net.minecraftforge.common.config.ConfigManager;
import net.minecraftforge.fml.client.event.ConfigChangedEvent;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
@Config(modid = TwoSpicyTwoStream.MOD_ID)
public class ModConfig {
@Config.Comment("Censor text")
public static boolean textCensor = true;
@Config.Comment("+ replace")
public static boolean textReplace = true;
@Config.Comment("Disable maps")
public static boolean disableMaps = true;
@Mod.EventBusSubscriber
private static class EventHandler {
/**
* Inject the new values and save to the config file when the config has been changed from the GUI.
*
* @param event The event
*/
@SubscribeEvent
public static void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) {
if (event.getModID().equals(TwoSpicyTwoStream.MOD_ID)) {
ConfigManager.sync(TwoSpicyTwoStream.MOD_ID, Config.Type.INSTANCE);
BadWords.genBadWords();
}
}
}
}
| 45,746
|
https://github.com/Rob--W/phabricator/blob/master/resources/sql/autopatches/20140721.phortune.3.charge.sql
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,022
|
phabricator
|
Rob--W
|
SQL
|
Code
| 82
| 262
|
CREATE TABLE {$NAMESPACE}_phortune.phortune_charge (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
phid VARCHAR(64) NOT NULL COLLATE utf8_bin,
accountPHID VARCHAR(64) NOT NULL COLLATE utf8_bin,
authorPHID VARCHAR(64) NOT NULL COLLATE utf8_bin,
cartPHID VARCHAR(64) NOT NULL COLLATE utf8_bin,
paymentMethodPHID VARCHAR(64) NOT NULL COLLATE utf8_bin,
amountInCents INT NOT NULL,
status VARCHAR(32) NOT NULL COLLATE utf8_bin,
metadata LONGTEXT NOT NULL COLLATE utf8_bin,
dateCreated INT UNSIGNED NOT NULL,
dateModified INT UNSIGNED NOT NULL,
UNIQUE KEY `key_phid` (phid),
KEY `key_cart` (cartPHID),
KEY `key_account` (accountPHID)
) ENGINE=InnoDB, COLLATE utf8_general_ci;
| 31,110
|
https://github.com/dotnet/roslyn/blob/master/src/Features/Core/Portable/Completion/Providers/SymbolCompletionItem.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
roslyn
|
dotnet
|
C#
|
Code
| 1,067
| 3,653
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageService;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
internal static class SymbolCompletionItem
{
private const string InsertionTextProperty = "InsertionText";
private static readonly Func<IReadOnlyList<ISymbol>, CompletionItem, CompletionItem> s_addSymbolEncoding = AddSymbolEncoding;
private static readonly Func<IReadOnlyList<ISymbol>, CompletionItem, CompletionItem> s_addSymbolInfo = AddSymbolInfo;
private static readonly char[] s_projectSeperators = new[] { ';' };
private static CompletionItem CreateWorker(
string displayText,
string? displayTextSuffix,
IReadOnlyList<ISymbol> symbols,
CompletionItemRules rules,
int contextPosition,
Func<IReadOnlyList<ISymbol>, CompletionItem, CompletionItem> symbolEncoder,
string? sortText = null,
string? insertionText = null,
string? filterText = null,
SupportedPlatformData? supportedPlatforms = null,
ImmutableDictionary<string, string>? properties = null,
ImmutableArray<string> tags = default,
string? displayTextPrefix = null,
string? inlineDescription = null,
Glyph? glyph = null,
bool isComplexTextEdit = false)
{
var props = properties ?? ImmutableDictionary<string, string>.Empty;
if (insertionText != null)
{
props = props.Add(InsertionTextProperty, insertionText);
}
props = props.Add("ContextPosition", contextPosition.ToString());
var firstSymbol = symbols[0];
var item = CommonCompletionItem.Create(
displayText: displayText,
displayTextSuffix: displayTextSuffix,
displayTextPrefix: displayTextPrefix,
inlineDescription: inlineDescription,
rules: rules,
filterText: filterText ?? (displayText is ['@', ..] ? displayText : firstSymbol.Name),
sortText: sortText ?? firstSymbol.Name,
glyph: glyph ?? firstSymbol.GetGlyph(),
showsWarningIcon: supportedPlatforms != null,
properties: props,
tags: tags,
isComplexTextEdit: isComplexTextEdit);
item = WithSupportedPlatforms(item, supportedPlatforms);
return symbolEncoder(symbols, item);
}
public static CompletionItem AddSymbolEncoding(IReadOnlyList<ISymbol> symbols, CompletionItem item)
=> item.AddProperty("Symbols", EncodeSymbols(symbols));
public static CompletionItem AddSymbolInfo(IReadOnlyList<ISymbol> symbols, CompletionItem item)
{
var symbol = symbols[0];
var isGeneric = symbol.GetArity() > 0;
item = item
.AddProperty("SymbolKind", ((int)symbol.Kind).ToString())
.AddProperty("SymbolName", symbol.Name);
return isGeneric ? item.AddProperty("IsGeneric", isGeneric.ToString()) : item;
}
public static CompletionItem AddShouldProvideParenthesisCompletion(CompletionItem item)
=> item.AddProperty("ShouldProvideParenthesisCompletion", true.ToString());
public static bool GetShouldProvideParenthesisCompletion(CompletionItem item)
{
if (item.Properties.TryGetValue("ShouldProvideParenthesisCompletion", out _))
{
return true;
}
return false;
}
public static string EncodeSymbols(IReadOnlyList<ISymbol> symbols)
{
if (symbols.Count > 1)
{
return string.Join("|", symbols.Select(EncodeSymbol));
}
else if (symbols.Count == 1)
{
return EncodeSymbol(symbols[0]);
}
else
{
return string.Empty;
}
}
public static string EncodeSymbol(ISymbol symbol)
=> SymbolKey.CreateString(symbol);
public static bool HasSymbols(CompletionItem item)
=> item.Properties.ContainsKey("Symbols");
private static readonly char[] s_symbolSplitters = new[] { '|' };
public static async Task<ImmutableArray<ISymbol>> GetSymbolsAsync(CompletionItem item, Document document, CancellationToken cancellationToken)
{
if (item.Properties.TryGetValue("Symbols", out var symbolIds))
{
var idList = symbolIds.Split(s_symbolSplitters, StringSplitOptions.RemoveEmptyEntries).ToList();
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols);
var compilation = await document.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
DecodeSymbols(idList, compilation, symbols);
// merge in symbols from other linked documents
if (idList.Count > 0)
{
var linkedIds = document.GetLinkedDocumentIds();
if (linkedIds.Length > 0)
{
foreach (var id in linkedIds)
{
var linkedDoc = document.Project.Solution.GetRequiredDocument(id);
var linkedCompilation = await linkedDoc.Project.GetRequiredCompilationAsync(cancellationToken).ConfigureAwait(false);
DecodeSymbols(idList, linkedCompilation, symbols);
}
}
}
return symbols.ToImmutable();
}
return ImmutableArray<ISymbol>.Empty;
}
private static void DecodeSymbols(List<string> ids, Compilation compilation, ArrayBuilder<ISymbol> symbols)
{
for (var i = 0; i < ids.Count;)
{
var id = ids[i];
var symbol = DecodeSymbol(id, compilation);
if (symbol != null)
{
ids.RemoveAt(i); // consume id from the list
symbols.Add(symbol); // add symbol to the results
}
else
{
i++;
}
}
}
private static ISymbol? DecodeSymbol(string id, Compilation compilation)
=> SymbolKey.ResolveString(id, compilation).GetAnySymbol();
public static async Task<CompletionDescription> GetDescriptionAsync(
CompletionItem item, Document document, SymbolDescriptionOptions options, CancellationToken cancellationToken)
{
var symbols = await GetSymbolsAsync(item, document, cancellationToken).ConfigureAwait(false);
return await GetDescriptionForSymbolsAsync(item, document, symbols, options, cancellationToken).ConfigureAwait(false);
}
public static async Task<CompletionDescription> GetDescriptionForSymbolsAsync(
CompletionItem item, Document document, ImmutableArray<ISymbol> symbols, SymbolDescriptionOptions options, CancellationToken cancellationToken)
{
if (symbols.Length == 0)
return CompletionDescription.Empty;
var position = GetDescriptionPosition(item);
if (position == -1)
position = item.Span.Start;
var supportedPlatforms = GetSupportedPlatforms(item, document.Project.Solution);
var contextDocument = FindAppropriateDocumentForDescriptionContext(document, supportedPlatforms);
var semanticModel = await contextDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var services = document.Project.Solution.Services;
return await CommonCompletionUtilities.CreateDescriptionAsync(services, semanticModel, position, symbols, options, supportedPlatforms, cancellationToken).ConfigureAwait(false);
}
private static Document FindAppropriateDocumentForDescriptionContext(Document document, SupportedPlatformData? supportedPlatforms)
{
if (supportedPlatforms != null && supportedPlatforms.InvalidProjects.Contains(document.Id.ProjectId))
{
var contextId = document.GetLinkedDocumentIds().FirstOrDefault(id => !supportedPlatforms.InvalidProjects.Contains(id.ProjectId));
if (contextId != null)
{
return document.Project.Solution.GetRequiredDocument(contextId);
}
}
return document;
}
private static CompletionItem WithSupportedPlatforms(CompletionItem completionItem, SupportedPlatformData? supportedPlatforms)
{
if (supportedPlatforms != null)
{
return completionItem
.AddProperty("InvalidProjects", string.Join(";", supportedPlatforms.InvalidProjects.Select(id => id.Id)))
.AddProperty("CandidateProjects", string.Join(";", supportedPlatforms.CandidateProjects.Select(id => id.Id)));
}
else
{
return completionItem;
}
}
public static SupportedPlatformData? GetSupportedPlatforms(CompletionItem item, Solution solution)
{
if (item.Properties.TryGetValue("InvalidProjects", out var invalidProjects)
&& item.Properties.TryGetValue("CandidateProjects", out var candidateProjects))
{
return new SupportedPlatformData(
solution,
invalidProjects.Split(s_projectSeperators).Select(s => ProjectId.CreateFromSerialized(Guid.Parse(s))).ToList(),
candidateProjects.Split(s_projectSeperators).Select(s => ProjectId.CreateFromSerialized(Guid.Parse(s))).ToList());
}
return null;
}
public static int GetContextPosition(CompletionItem item)
{
if (item.Properties.TryGetValue("ContextPosition", out var text) &&
int.TryParse(text, out var number))
{
return number;
}
else
{
return -1;
}
}
public static int GetDescriptionPosition(CompletionItem item)
=> GetContextPosition(item);
public static string GetInsertionText(CompletionItem item)
=> item.Properties[InsertionTextProperty];
public static bool TryGetInsertionText(CompletionItem item, [NotNullWhen(true)] out string? insertionText)
=> item.Properties.TryGetValue(InsertionTextProperty, out insertionText);
// COMPAT OVERLOAD: This is used by IntelliCode.
public static CompletionItem CreateWithSymbolId(
string displayText,
IReadOnlyList<ISymbol> symbols,
CompletionItemRules rules,
int contextPosition,
string? sortText = null,
string? insertionText = null,
string? filterText = null,
SupportedPlatformData? supportedPlatforms = null,
ImmutableDictionary<string, string>? properties = null,
ImmutableArray<string> tags = default,
bool isComplexTextEdit = false)
{
return CreateWithSymbolId(
displayText,
displayTextSuffix: null,
symbols,
rules,
contextPosition,
sortText,
insertionText,
filterText,
displayTextPrefix: null,
inlineDescription: null,
glyph: null,
supportedPlatforms,
properties,
tags,
isComplexTextEdit);
}
public static CompletionItem CreateWithSymbolId(
string displayText,
string? displayTextSuffix,
IReadOnlyList<ISymbol> symbols,
CompletionItemRules rules,
int contextPosition,
string? sortText = null,
string? insertionText = null,
string? filterText = null,
string? displayTextPrefix = null,
string? inlineDescription = null,
Glyph? glyph = null,
SupportedPlatformData? supportedPlatforms = null,
ImmutableDictionary<string, string>? properties = null,
ImmutableArray<string> tags = default,
bool isComplexTextEdit = false)
{
return CreateWorker(
displayText, displayTextSuffix, symbols, rules, contextPosition,
s_addSymbolEncoding, sortText, insertionText,
filterText, supportedPlatforms, properties, tags, displayTextPrefix,
inlineDescription, glyph, isComplexTextEdit);
}
public static CompletionItem CreateWithNameAndKind(
string displayText,
string displayTextSuffix,
IReadOnlyList<ISymbol> symbols,
CompletionItemRules rules,
int contextPosition,
string? sortText = null,
string? insertionText = null,
string? filterText = null,
string? displayTextPrefix = null,
string? inlineDescription = null,
Glyph? glyph = null,
SupportedPlatformData? supportedPlatforms = null,
ImmutableDictionary<string, string>? properties = null,
ImmutableArray<string> tags = default,
bool isComplexTextEdit = false)
{
return CreateWorker(
displayText, displayTextSuffix, symbols, rules, contextPosition,
s_addSymbolInfo, sortText, insertionText,
filterText, supportedPlatforms, properties, tags,
displayTextPrefix, inlineDescription, glyph, isComplexTextEdit);
}
internal static string? GetSymbolName(CompletionItem item)
=> item.Properties.TryGetValue("SymbolName", out var name) ? name : null;
internal static SymbolKind? GetKind(CompletionItem item)
=> item.Properties.TryGetValue("SymbolKind", out var kind) ? (SymbolKind?)int.Parse(kind) : null;
internal static bool GetSymbolIsGeneric(CompletionItem item)
=> item.Properties.TryGetValue("IsGeneric", out var v) && bool.TryParse(v, out var isGeneric) && isGeneric;
public static async Task<CompletionDescription> GetDescriptionAsync(
CompletionItem item, IReadOnlyList<ISymbol> symbols, Document document, SemanticModel semanticModel, SymbolDescriptionOptions options, CancellationToken cancellationToken)
{
var position = GetDescriptionPosition(item);
var supportedPlatforms = GetSupportedPlatforms(item, document.Project.Solution);
if (symbols.Count != 0)
{
return await CommonCompletionUtilities.CreateDescriptionAsync(document.Project.Solution.Services, semanticModel, position, symbols, options, supportedPlatforms, cancellationToken).ConfigureAwait(false);
}
else
{
return CompletionDescription.Empty;
}
}
}
}
| 23,843
|
https://github.com/yonathan12/kps/blob/master/application/controllers/api/v1/KPS.php
|
Github Open Source
|
Open Source
|
MIT
| null |
kps
|
yonathan12
|
PHP
|
Code
| 59
| 260
|
<?php
require APPPATH . 'controllers/api/v1/BaseController.php';
class KPS extends BaseController
{
public function __construct()
{
parent::__construct();
$this->load->model('KPS001_model');
}
public function index_get()
{
$get_data = $this->KPS001_model->show($this->nisn)->result_object();
if($get_data){
$this->res([
'status' => true,
'data' => [
'kps' => $get_data,
'student' => $this->KPS001_model->showStudent($this->nisn)
]
],'OK');
}else{
$this->res([
'status' => true,
'data' => [
'kps' => $get_data,
'student' => $this->KPS001_model->showStudent($this->nisn)
]
],'OK');
}
}
}
| 9,952
|
https://github.com/flypig5211/zf-admin/blob/master/zf/src/main/java/com/chinazhoufan/admin/modules/msg/dao/uw/WarningDao.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,017
|
zf-admin
|
flypig5211
|
Java
|
Code
| 46
| 228
|
/**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.chinazhoufan.admin.modules.msg.dao.uw;
import java.util.List;
import java.util.Map;
import com.chinazhoufan.admin.common.persistence.CrudDao;
import com.chinazhoufan.admin.common.persistence.annotation.MyBatisDao;
import com.chinazhoufan.admin.modules.msg.entity.uw.Warning;
/**
* 员工报警中心DAO接口
* @author 刘晓东
* @version 2015-12-10
*/
@MyBatisDao
public interface WarningDao extends CrudDao<Warning> {
public List<Warning> findMyPageByUser(Map<String, Object> map);
}
| 14,222
|
https://github.com/cuijianming/ovs-2.13.6/blob/master/datapath-windows/ovsext/PaxHeaders.2308045/Actions.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
ovs-2.13.6
|
cuijianming
|
C
|
Code
| 6
| 43
|
30 mtime=1639777085.361355983
30 atime=1639777086.314355983
30 ctime=1639777127.166355983
| 27,503
|
https://github.com/fangningshao/chinese-poetry-corpus/blob/master/data/宋/poems/赵必常.tsv
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
chinese-poetry-corpus
|
fangningshao
|
TSV
|
Code
| 3
| 82
|
小亭夜坐即景(宋·赵必常) 七言绝句 小亭夜坐涤炎蒸,顿觉风清趣已成。数点流萤亭外度,儿童戏逐月边星①。
| 7,251
|
https://github.com/unifly-aero/powergrid/blob/master/web/datasources/datasource.js
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
powergrid
|
unifly-aero
|
JavaScript
|
Code
| 728
| 1,205
|
/**
* Interface for classes that provide data to a grid. Data (things returned by {@link DataSource#getData} and
* {@link DataSource.getRecordById} exists of objects (records) that contain at least an 'id' property containing a number
* or string that uniquely identifies that record.
*
* @interface DataSource
* @extends EventSource
* @fires DataSource#ready
* @fires DataSource#rowsadded
* @fires DataSource#rowsremoved
* @fires DataSource#dataloaded
* @fires DataSource#datachanged
*/
/**
* Indicates that the datasource has become ready to accept queries.
*
* @event DataSource#ready
*/
/**
* Indicates that new data was added to the data source. This should be fired for each contiguous block of records that
* was added. For example, if in a datasource with records {red, blue, green, orange} data was added so that it became
* {red, mauve, blue, teal, purple, green, orange}, the following events should be fired:
* - rowsadded({start: 1, end: 2})
* - rowsadded({start: 3, end: 5})
* Note that the order in which these events are fired is important (if these two events were swapped, the indices would
* need to be different).
*
* @event DataSource#rowsadded
* @type {object}
* @property {number} start - the index of the first row that was added
* @property {number} end - the index after the last row that was added
*/
/**
* Indicates that data was removed from the data source. This should be fired for each contiguous blocks of records that
* are removed. For example, if in a datasource with records {red, mauve, blue, teal, purple, green, orange} data was added so that it became
* {red, blue, green, orange}, the following events should be fired:
* - rowsremoved({start: 3, end: 5})
* - rowsremoved({start: 1, end: 2})
* Note that the order in which these events are fired is important (if these two events were swapped, the indices would
* need to be different).
*
* @event DataSource#rowsremoved
* @type {object}
* @property {number} start - the index of the first row that was removed
* @property {number} end - the index after the last row that was removed
*/
/**
* Indicates that data has been loaded. In essence, this triggers a complete grid refresh.
*
* @event DataSource#dataloaded
*/
/**
* Indicates that certain values within the dataset have changed (not added nor removed). The accompanying object
* should specify which changes have taken place. This can be done either by specifying which rows have been changed,
* or if full row updates are not a problem which rows have changed.
*
* @event DataSource#datachanged
* @type {object}
* @property {undefined|CellByRowIdAndColumnKey[]} values - the values that have changed
* @property {undefined|object[]} rows - the records that have changed
*/
/**
* @function DataSource#isReady
* @returns {boolean} returns true if the datasource is ready to accept queries.
*/
/**
* @function DataSource#recordCount
* @returns {Promise<number>|number} the number of records in the data set
*/
/**
* Returns all the data in the dataset.
* @function DataSource#getData
* @returns {Promise<object[]>|object[]}
*/
/**
* Returns a range of data in the dataset.
* @function DataSource#getData
* @param {number} start - the index at which to start extracting data. The first row in the dataset is row 0.
* @param {number} end - the index at which to stop extracting data. The row at this index will not be part of the result.
* @returns {Promise<object[]>|object[]}
*/
/**
* Returns a record by its identifier. This can not be a promise, but it should normally only be invoked for records that have
* already previously been fetched through {@link DataSource#getData}.
* @function DataSource#getRecordById
* @param {string|number} id - the identifier of the row to return
* @returns {object}
*/
/**
* Changes a value in the dataset. Implementing this method is optional, and only required if the grid should be editable
* using the {@link Editing} extension.
* @function DataSource#setValue
* @param {string|number} rowId - the id of the row to change.
* @param {string} key - the name of the property that should get the new value
* @param {*} value - the value to change that property to
*/
/**
* Applies a sorting to the dataset. Optional. See {@link Sorting} for more information.
* @function DataSource#sort
* @param {function(a,b)} comparator - the comparator function to use when sorting
* @param {object} order - the sort order
*/
| 39,955
|
https://github.com/kunishi/algebra-ruby2/blob/master/doc-ja/finite-map-ja.rd
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
algebra-ruby2
|
kunishi
|
R
|
Code
| 623
| 2,571
|
########################################################################
# #
# finite-map.rb #
# #
########################################################################
=begin
[((<index-ja|URL:index-ja.html>))]
[((<finite-set-ja|URL:finite-set-ja.html>))]
((<Algebra::Map>))
= Algebra::Map
((*写像クラス*))
写像を表現するクラスです。
== ファイル名:
* ((|finite-map.rb|))
== スーパークラス:
* ((|Set|))
== インクルードしているモジュール:
* ((|Powers|))
== クラスメソッド:
--- ::[]([x0 => y0, [x1 => y1, [x2 => y2, ...]]])
((|x0|)) の時 ((|y0|)), ((|x1|)) の時 ((|y1|)), ((|x2|)) の時 ((|y2|)),..
という値を持つ写像を返します。
例:
require "finite-map"
include Algebra
p Map[0 => 10, 1 => 11, 2 => 12] #=> {0 => 10, 1 => 11, 2 => 12}
p Map[{0 => 10, 1 => 11, 2 => 12}] #=> {0 => 10, 1 => 11, 2 => 12}
p Map.new(0 => 10, 1 => 11, 2 => 12) #=> {0 => 10, 1 => 11, 2 => 12}
p Map.new({0 => 10, 1 => 11, 2 => 12}) #=> {0 => 10, 1 => 11, 2 => 12}
p Map.new_a([0, 10, 1, 11, 2, 12]) #=> {0 => 10, 1 => 11, 2 => 12}
--- ::new([x0 => y0, [x1 => y1, [x2 => y2, ...]]])
((|x0|)) の時 ((|y0|)), ((|x1|)) の時 ((|y1|)), ((|x2|)) の時 ((|y|)),..
という値を持つ写像を返します。((<::[]>)) と同じです。
--- ::new_a(a)
配列 a の偶数番目を定義域の元、奇数番目を値域の元として定義される
写像を生成します。
--- ::phi([t])
空写像(定義域が空集合である写像)を返します。集合 ((|t|)) を
引数にすると、それを定義域 ((<target>)) にします。
例:
p Map.phi #=> {}
p Map.phi(Set[0, 1]) #=> {}
p Map.phi(Set[0, 1]).target #=> {0, 1}
--- ::empty_set
((<::phi>)) のエイリアスです。
--- ::singleton(x, y)
ただ一つの元で構成される集合 (({{x}})) 上で定義された ((|y|)) という
値を取る関数を返します。
== メソッド:
--- target=(s)
写像の値域を ((|s|)) に設定します。((<surjective?>)) などに
利用されます。
--- codomain=(s)
((<target=>)) のエイリアスです。
--- target
写像の値域を返します。
--- codomain
((<target>)) のエイリアスです。
--- source
写像の定義域を返します。
例:
require "finite-map"
include Algebra
m = Map[0 => 10, 1 => 11, 2 => 12]
p m.source #=> {0, 1, 2}
p m.target #=> nil
m.target = Set[10, 11, 12, 13]
p m.target #=> {10, 11, 12, 13}
--- domain
((<source>)) のエイリアスです。
--- phi([t])
値域を ((|t|)) とする空の写像を返します。
--- empty_set
--- null
((<phi>)) のエイリアスです。
--- call(x)
写像の ((|x|)) における値を返します。
--- act
--- []
((<call>)) のエイリアスです。
--- each
すべての (({[原像, 像]})) について繰り返すイテレータです。
例:
require "finite-map"
include Algebra
Map[0 => 10, 1 => 11, 2 => 12].each do |x, y|
p [x, y] #=> [1, 11], [0, 10], [2, 12]
end
--- compose(other)
((|self|)) と ((|other|)) の合成写像を返します。
例:
require "finite-map"
include Algebra
f = Map.new(0 => 10, 1 => 11, 2 => 12)
g = Map.new(10 => 20, 11 => 21, 12 => 22)
p g * f #=> {0 => 20, 1 => 21, 2 => 22}
--- *
((<compose>)) のエイリアスです。
--- dup
自身の複製を返します。値域の値も返します。
--- append!(x, y)
((|x|)) で ((|y|)) という値を取るように設定します。
例:
require "finite-map"
include Algebra
m = Map[0 => 10, 1 => 11]
m.append!(2, 12)
p m #=> {0 => 10, 1 => 11, 2 => 12}
--- []=(x, y)
((<append!>)) のエイリアスです。
--- append(x, y)
((<dup>)) の後、((<append!>))(x, y) したものを返します。
--- include?(x)
((|x|)) が定義域に含まれるとき真を返します。
--- contains?(x)
((<include?>)) のエイリアスです。
--- member?(a)
((|a|)) を配列 (({[x, y]})) としたとき、((|x|)) における値が
((|y|)) となるとき、真を返します。
例:
require "finite-map"
include Algebra
m = Map[0 => 10, 1 => 11]
p m.include?(1) #=> true
p m.member?([1, 11]) #=> true
--- has?
member? のエイリアスです。
--- image([s])
写像の像を返します。定義域の部分集合 ((|s|)) が与えられれば、
((|s|)) の像を返します。
--- inv_image(s)
集合 ((|s|)) の原像を返します。
--- map_s
写像の各 [原像, 像] のペアについて繰り返し、ブロックで得た
値の集合を返します。
例:
require "finite-map"
include Algebra
p Map.new(0 => 10, 1 => 11, 2 => 12).map_s{|x, y| y - 2*x}
#=> Set[10, 9, 8]
--- map_m
写像の各 [原像, 像] のペアについて繰り返し、ブロックで得た
値の配列で構成される写像を返します。
例:
require "finite-map"
include Algebra
p Map.new(0 => 10, 1 => 11, 2 => 12).map_m{|x, y| [y, x]}
#=> {10 => 0, 11 => 1, 12 => 2}
--- inverse
逆写像を返します。
--- inv_coset
各像に逆像の集合を対応させる写像を返します。
例:
require "finite-map"
include Algebra
m = Map[0=>0, 1=>0, 2=>2, 3=>2, 4=>0]
p m.inv_coset #=> {0=>{0, 1, 4}, 2=>{2, 3}}
m.codomain = Set[0, 1, 2, 3]
p m.inv_coset #=> {0=>{0, 1, 4}, 1=>{}, 2=>{2, 3}, 3=>{}}
--- indentity?
恒等写像であるとき、真を返します。
--- surjective?
全射である時、真を返します。あらかじめ ((<target>)) が指定されて
いる必要があります。
--- injective?
単射である時、真を返します。
--- bijective?
全単射である時、真を返します。あらかじめ ((<target>)) が指定されて
いる必要があります。
=end
| 29,651
|
https://github.com/mnipper/rails_survey/blob/master/spec/factories/project.rb
|
Github Open Source
|
Open Source
|
MIT
| null |
rails_survey
|
mnipper
|
Ruby
|
Code
| 15
| 35
|
FactoryGirl.define do
factory :project do
name 'test project'
description 'this is a project'
end
end
| 47,793
|
https://github.com/zendzo/stupid-inventory/blob/master/app/Http/Livewire/CategoryIndex.php
|
Github Open Source
|
Open Source
|
MIT
| null |
stupid-inventory
|
zendzo
|
PHP
|
Code
| 100
| 376
|
<?php
namespace App\Http\Livewire;
use App\Models\Category;
use Livewire\Component;
class CategoryIndex extends Component
{
protected $listeners = [
'categoryStored' => 'handleCategoryStored',
'categoryUpdated' => 'handleCategoryUpdated'
];
public $editCategory = false;
public function render()
{
return view('livewire.category-index',[
'categories' => Category::orderBy('id', 'DESC')->paginate(5)
]);
}
public function handleCategoryStored($category)
{
session()->flash('message', 'Category '.$category['name'].' Successfully Created');
}
public function handleCategoryUpdated($category)
{
session()->flash('message', 'Category '.$category['name'].' Successfully Updated');
$this->editCategory = false;
}
public function getCategory($id)
{
$this->editCategory = true;
$category = Category::findOrfail($id);
$this->emit('getCategory', $category);
}
public function destroy($id)
{
$category = Category::findOrfail($id);
if ($category) {
$category->delete();
}
session()->flash('message', 'Category '.$category['name'].' Deleted');
if ($this->editCategory) {
$this->editCategory = false;
}
}
}
| 47,080
|
https://github.com/zmeggyesi/w_transport/blob/master/lib/src/http/request_exception.dart
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
w_transport
|
zmeggyesi
|
Dart
|
Code
| 311
| 648
|
// Copyright 2015 Workiva Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import 'package:w_transport/src/http/base_request.dart';
import 'package:w_transport/src/http/response.dart';
/// An exception that is raised when a response to a request returns with
/// an unsuccessful status code.
class RequestException implements Exception {
/// Original error, if any.
final Object error;
/// HTTP method.
final String method;
/// Failed request.
final BaseRequest request;
/// Response to the failed request (some of the properties may be unavailable).
final BaseResponse response;
/// URL of the attempted/unsuccessful request.
final Uri uri;
/// Construct a new instance of [RequestException] using information from
/// an HTTP request and response.
RequestException(this.method, this.uri, this.request, this.response,
[this.error]);
/// Descriptive error message that includes the request method & URL and the
/// response status.
String get message {
String msg;
if (request != null && request.autoRetry.numAttempts > 1) {
msg = '$method $uri';
for (int i = 0; i < request.autoRetry.failures.length; i++) {
final failure = request.autoRetry.failures[i];
String attempt = '\n\tAttempt #${i + 1}:';
if (failure.response != null) {
attempt +=
' ${failure.response.status} ${failure.response.statusText}';
}
if (failure.error != null) {
attempt += ' (${failure.error})';
}
msg += attempt;
}
} else {
msg = '$method';
if (response != null) {
msg += ' ${response.status} ${response.statusText}';
}
msg += ' $uri';
if (error != null) {
msg += '\n\t$error';
}
}
return msg;
}
@override
String toString() => 'RequestException: $message';
}
| 39,039
|
https://github.com/SCLD-AFrey/GrpcWpfSample/blob/master/GrpcWpfSample.Client.Wpf/View/ChatClientWindow.xaml.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
GrpcWpfSample
|
SCLD-AFrey
|
C#
|
Code
| 61
| 213
|
using System.Windows;
using System.Windows.Input;
namespace GrpcWpfSample.Client.Wpf.View
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class ChatClientWindow : Window
{
public ChatClientWindow()
{
InitializeComponent();
DataContext = new ChatClientWindowViewModel();
}
private void BodyInput_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Return)
{
(DataContext as ChatClientWindowViewModel).WriteCommand.Execute(BodyInput.Text);
BodyInput.Text = "";
}
}
private void BodyInput_Loaded(object sender, RoutedEventArgs e)
{
BodyInput.Focus();
}
}
}
| 23,337
|
https://github.com/the6thdoor/LumiPBRExt/blob/master/assets/lumi/shaders/material/iron_wood.frag
|
Github Open Source
|
Open Source
|
CC-BY-4.0
| null |
LumiPBRExt
|
the6thdoor
|
GLSL
|
Code
| 92
| 367
|
#include frex:shaders/api/fragment.glsl
#include frex:shaders/api/world.glsl
#include lumi:shaders/lib/bump.glsl
#include lumi:shaders/internal/ext_frag.glsl
/******************************************************
lumi:shaders/material/iron_wood.frag
******************************************************/
void frx_startFragment(inout frx_FragmentData data)
{
#if LUMIEXT_MaterialCoverage == LUMIEXT_MaterialCoverage_ApplyAll
#ifdef LUMI_PBRX
vec4 c = data.spriteColor;
float min_ = min( min(c.r, c.g), c.b );
float max_ = max( max(c.r, c.g), c.b );
float s = max_ > 0 ? (max_ - min_) / max_ : 0;
if (s < 0.4) {
data.spriteColor.rgb += (1-min_) * 0.3;
pbr_metallic = 1.0;
pbr_roughness = 0.6 - s * 0.5;
#ifdef LUMI_BUMP
#ifdef LUMIEXT_ApplyBumpMinerals
_applyBump_step_s(data, 0.4, 0.4, frx_modelOriginType() == MODEL_ORIGIN_REGION);
#endif
#endif
}
#endif
#endif
}
| 24,534
|
https://github.com/UAF-SuperDARN-OPS/SuperDARN_MSI_ROS/blob/master/linux/home/radar/ros.3.6/codebase/analysis/src.lib/aacgm/aacgm.1.15/src/aacgm.c
|
Github Open Source
|
Open Source
|
MIT
| 2,013
|
SuperDARN_MSI_ROS
|
UAF-SuperDARN-OPS
|
C
|
Code
| 257
| 868
|
/* aacgm.c
=======
Author: R.J.Barnes
*/
/*
LICENSE AND DISCLAIMER
Copyright (c) 2012 The Johns Hopkins University/Applied Physics Laboratory
This file is part of the Radar Software Toolkit (RST).
RST is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
RST 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with RST. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "default.h"
#include "convert_geo_coord.h"
extern struct {
double coef[121][3][5][2];
} sph_harm_model;
int AACGMLoadCoefFP(FILE *fp) {
char tmp[64];
int f,l,a,t,i;
if (fp==NULL) return -1;
for (f=0;f<2;f++) {
for (l=0;l<5;l++) {
for (a=0;a<3;a++) {
for (t=0;t<121;t++) {
if (fscanf(fp,"%s",tmp) !=1) {
fclose(fp);
return -1;
}
for (i=0;(tmp[i] !=0) && (tmp[i] !='D');i++);
if (tmp[i]=='D') tmp[i]='e';
sph_harm_model.coef[t][a][l][f]=atof(tmp);
}
}
}
}
return 0;
}
int AACGMLoadCoef(char *fname) {
FILE *fp;
fp=fopen(fname,"r");
if (fp==NULL) return -1;
AACGMLoadCoefFP(fp);
fclose(fp);
return 0;
}
int AACGMInit(int year) {
char fname[256];
char yrstr[32];
if (year==0) year=DEFAULT_YEAR;
sprintf(yrstr,"%4.4d",year);
strcpy(fname,getenv("AACGM_DAT_PREFIX"));
if (strlen(fname)==0) return -1;
strcat(fname,yrstr);
strcat(fname,".asc");
return AACGMLoadCoef(fname);
}
int AACGMConvert(double in_lat,double in_lon,double height,
double *out_lat,double *out_lon,double *r,
int flag) {
int err;
err=convert_geo_coord(in_lat,in_lon,height,
out_lat,out_lon,flag,10);
*r=1.0;
if (err !=0) return -1;
return 0;
}
| 288
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.