hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a1a70e7ded3be0bbcead5a5bf38cc2ec7c3db940 | 3,212 | go | Go | algorithms/list/node_test.go | miry/gosample | ad3cf9dca1e8446db9c9e821bf66709bf0fa9f76 | [
"MIT"
] | 8 | 2018-09-16T16:40:31.000Z | 2022-01-20T03:08:35.000Z | algorithms/list/node_test.go | miry/gosample | ad3cf9dca1e8446db9c9e821bf66709bf0fa9f76 | [
"MIT"
] | 4 | 2018-12-29T14:34:17.000Z | 2021-10-03T20:44:34.000Z | algorithms/list/node_test.go | miry/gosample | ad3cf9dca1e8446db9c9e821bf66709bf0fa9f76 | [
"MIT"
] | 6 | 2019-03-13T22:12:07.000Z | 2021-02-18T00:50:36.000Z | package list_test
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/miry/samples/algorithms/list"
)
func TestNodeValue(t *testing.T) {
subject := list.Node{}
assert.Equal(t, "", subject.Value, "should be empty")
}
func TestNodePrint(t *testing.T) {
subject := list.Node{}
subject.Print()
}
func TestNodeValues(t *testing.T) {
first := &list.Node{Value: "First Node"}
second := &list.Node{Value: "Second Node"}
first.Next = second
assert.Equal(t, []string{"First Node", "Second Node"}, first.Values())
}
func TestNodeAppend(t *testing.T) {
first := &list.Node{Value: "First Node"}
second := &list.Node{Value: "Second Node"}
first.Append(second)
assert.Equal(t, []string{"First Node", "Second Node"}, first.Values())
}
func TestNodeGetSuccess(t *testing.T) {
second := &list.Node{Value: "Second Node"}
first := &list.Node{Value: "First Node", Next: second}
actual, _ := first.Get(1)
assert.Equal(t, "Second Node", actual.Value)
}
func TestNodeGetFailed(t *testing.T) {
second := &list.Node{Value: "Second Node"}
first := &list.Node{Value: "First Node", Next: second}
actual, err := first.Get(2)
assert.Nil(t, actual)
assert.Equal(t, "Out of index", err.Error())
}
func TestNodeGetNegativeFailed(t *testing.T) {
second := &list.Node{Value: "Second Node"}
first := &list.Node{Value: "First Node", Next: second}
actual, err := first.Get(-2)
assert.Nil(t, actual)
assert.Equal(t, "Out of index", err.Error())
}
func TestNodeInsert(t *testing.T) {
second := &list.Node{Value: "Second Node"}
first := &list.Node{Value: "First Node", Next: second}
newSecond := &list.Node{Value: "New Second"}
first.Insert(1, newSecond)
assert.Equal(t, []string{"First Node", "New Second", "Second Node"}, first.Values())
}
func TestNodeInsertFirst(t *testing.T) {
second := &list.Node{Value: "Second Node"}
first := &list.Node{Value: "First Node", Next: second}
newHead := &list.Node{Value: "New First"}
actual, _ := first.Insert(0, newHead)
assert.Equal(t, []string{"New First", "First Node", "Second Node"}, actual.Values())
}
func TestNodeInsertFailed(t *testing.T) {
second := &list.Node{Value: "Second Node"}
first := &list.Node{Value: "First Node", Next: second}
oops := &list.Node{Value: "Should not be in the list"}
actual, err := first.Insert(6, oops)
assert.NotNil(t, actual)
assert.Equal(t, "Out of index", err.Error())
assert.NotContains(t, actual.Values(), "Should not be in the list")
}
func TestNodeDeleteSuccess(t *testing.T) {
second := &list.Node{Value: "Second Node"}
first := &list.Node{Value: "First Node", Next: second}
actual, err := first.Delete(1)
assert.Nil(t, err)
assert.NotContains(t, actual.Values(), "Second Node")
}
func TestNodeDeleteHead(t *testing.T) {
second := &list.Node{Value: "Second Node"}
first := &list.Node{Value: "First Node", Next: second}
actual, err := first.Delete(0)
assert.Nil(t, err)
assert.NotContains(t, actual.Values(), "First Node")
}
func TestNodeDeleteError(t *testing.T) {
second := &list.Node{Value: "Second Node"}
first := &list.Node{Value: "First Node", Next: second}
actual, err := first.Delete(5)
assert.NotNil(t, actual)
assert.Equal(t, "Out of index", err.Error())
}
| 27.689655 | 85 | 0.677148 |
861266f3e39b85f06b5d8b1d8d5deb316471a3ff | 2,976 | java | Java | src/main/java/com/cicciotecchio/yaspl/visitor/Visitor.java | CiccioTecchio/YASPL3 | f2803697003b376dd8cb46daf4e350d93cdd3d57 | [
"MIT"
] | 2 | 2019-11-22T09:50:41.000Z | 2019-11-22T09:50:51.000Z | src/main/java/com/cicciotecchio/yaspl/visitor/Visitor.java | CiccioTecchio/YASPL3 | f2803697003b376dd8cb46daf4e350d93cdd3d57 | [
"MIT"
] | 1 | 2019-11-22T09:50:31.000Z | 2019-11-22T09:50:31.000Z | src/main/java/com/cicciotecchio/yaspl/visitor/Visitor.java | CiccioTecchio/YASPL3.0 | f2803697003b376dd8cb46daf4e350d93cdd3d57 | [
"MIT"
] | 1 | 2019-02-06T11:10:32.000Z | 2019-02-06T11:10:32.000Z | package com.cicciotecchio.yaspl.visitor;
import com.cicciotecchio.yaspl.syntaxTree.*;
import com.cicciotecchio.yaspl.syntaxTree.arithOp.*;
import com.cicciotecchio.yaspl.syntaxTree.components.*;
import com.cicciotecchio.yaspl.syntaxTree.declsOp.*;
import com.cicciotecchio.yaspl.syntaxTree.leaf.*;
import com.cicciotecchio.yaspl.syntaxTree.logicOp.*;
import com.cicciotecchio.yaspl.syntaxTree.relOp.*;
import com.cicciotecchio.yaspl.syntaxTree.statOp.*;
import com.cicciotecchio.yaspl.syntaxTree.utils.ParDeclSon;
import com.cicciotecchio.yaspl.syntaxTree.varDeclInitOp.*;
public interface Visitor<E> {
E visit(Args n) throws RuntimeException;
E visit(Body n) throws RuntimeException;
E visit(CompStat n) throws RuntimeException;
E visit(Decls n) throws RuntimeException;
E visit(DefDeclNoPar n) throws RuntimeException;
E visit(DefDeclPar n) throws RuntimeException;
E visit(ParDecls n) throws RuntimeException;
E visit(Programma n) throws RuntimeException;
E visit(Statements n) throws RuntimeException;
E visit(VarDecl n) throws RuntimeException;
E visit(VarDecls n) throws RuntimeException;
E visit(VarDeclsInit n) throws RuntimeException;
E visit(VarInitValue n) throws RuntimeException;
E visit(Vars n) throws RuntimeException;
E visit(AddOp n) throws RuntimeException;
E visit(DivOp n) throws RuntimeException;
E visit(ModOp n) throws RuntimeException;
E visit(MultOp n) throws RuntimeException;
E visit(SubOp n) throws RuntimeException;
E visit(UminusOp n) throws RuntimeException;
E visit(AndOp n) throws RuntimeException;
E visit(NotOp n) throws RuntimeException;
E visit(OrOp n) throws RuntimeException;
E visit(EqOp n) throws RuntimeException;
E visit(GeOp n) throws RuntimeException;
E visit(GtOp n) throws RuntimeException;
E visit(LeOp n) throws RuntimeException;
E visit(LtOp n) throws RuntimeException;
E visit(BoolConst n) throws RuntimeException;
E visit(IdConst n) throws RuntimeException;
E visit(IntConst n) throws RuntimeException;
E visit(DoubleConst n) throws RuntimeException;
E visit(CharConst n) throws RuntimeException;
E visit(StringConst n) throws RuntimeException;
E visit(AssignOp n) throws RuntimeException;
E visit(CallOp n) throws RuntimeException;
E visit(IfThenElseOp n) throws RuntimeException;
E visit(IfThenOp n) throws RuntimeException;
E visit(ReadOp n) throws RuntimeException;
E visit(WhileOp n) throws RuntimeException;
E visit(ForOp n) throws RuntimeException;
E visit(WriteOp n) throws RuntimeException;
E visit(PreFixInc n) throws RuntimeException;
E visit(PostFixInc n) throws RuntimeException;
E visit(PreFixDec n) throws RuntimeException;
E visit(PostFixDec n) throws RuntimeException;
E visit(Leaf n) throws RuntimeException;
E visit(ParDeclSon n) throws RuntimeException;
E visit(VarInit n) throws RuntimeException;
E visit(VarNotInit n) throws RuntimeException;
E visit(TypeLeaf n) throws RuntimeException;
E visit(ParTypeLeaf n) throws RuntimeException;
}
| 38.649351 | 59 | 0.804099 |
ba8f958090292913182fa7ea5e9c8d71b36369c9 | 3,202 | sql | SQL | triggers.sql | sarismet/Ey-Sanl- | 2e9ab1aa9eb5ad7571fee31c6f6a801ae2e463ba | [
"MIT"
] | null | null | null | triggers.sql | sarismet/Ey-Sanl- | 2e9ab1aa9eb5ad7571fee31c6f6a801ae2e463ba | [
"MIT"
] | null | null | null | triggers.sql | sarismet/Ey-Sanl- | 2e9ab1aa9eb5ad7571fee31c6f6a801ae2e463ba | [
"MIT"
] | null | null | null | DELIMITER //
CREATE TRIGGER likesongtrigger BEFORE UPDATE ON Songs
FOR EACH ROW BEGIN
IF( new.operation = 'like song' ) THEN
SET new.operation = 'NULL';
SET @listenerliked = (SELECT username FROM currentListener LIMIT 1);
INSERT INTO Main (wholiked,title,songid,albumid,creator,asistantartist)
SELECT * FROM (SELECT @listenerliked, new.title,new.id,new.albumid,new.creator,new.asistantartist)
AS tmp WHERE NOT EXISTS (SELECT wholiked, songid FROM Main WHERE wholiked = @listenerliked and songid = new.id) LIMIT 1;
END IF;
END; //
CREATE TRIGGER likesalbumtrigger BEFORE UPDATE ON Songs
FOR EACH ROW BEGIN
IF( new.operation = 'like album' ) THEN
SET new.operation = 'NULL';
SET @listenerliked = (SELECT username FROM currentListener LIMIT 1);
INSERT INTO Main (wholiked,title,songid,albumid,creator,asistantartist)
SELECT * FROM (SELECT @listenerliked, new.title,new.id,new.albumid,new.creator,new.asistantartist) AS tmp WHERE NOT EXISTS (SELECT wholiked, songid FROM Main WHERE wholiked = @listenerliked and songid = new.id) LIMIT 1;
END IF;
END; //
CREATE TRIGGER deletesongtrigger BEFORE UPDATE ON Songs
FOR EACH ROW BEGIN
IF(new.operation = 'delete song' ) THEN
DELETE FROM Main Where songid = new.id;
END IF;
END; //
CREATE TRIGGER deletealbumtrigger BEFORE UPDATE ON Albums
FOR EACH ROW BEGIN
IF(new.operation = 'delete album' ) THEN
DELETE FROM Main WHERE albumid = new.id;
DELETE FROM Songs WHERE albumid = new.id;
END IF;
END; //
CREATE PROCEDURE curdemo(name TEXT,surname TEXT)
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE a CHAR(200);
DECLARE cur1 CURSOR FOR SELECT asistantartist FROM Songs WHERE (creator = CONCAT(name,'_',surname) OR asistantartist like CONCAT("%",name,'_',surname,"%")) AND asistantartist <> 'no';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO a;
IF done THEN
LEAVE read_loop;
END IF;
call Splitforpartner(a);
END LOOP;
CLOSE cur1;
insert into partners select creator from Main where asistantartist like CONCAT("%",name,'_',surname,"%");
select DISTINCT artistnames from partners where artistnames <> CONCAT(name,'_',surname);
END; //
CREATE PROCEDURE Splitforrank(IN Str VARCHAR(200))
BEGIN
DECLARE inipos INT;
DECLARE endpos INT;
DECLARE maxlen INT;
DECLARE fullstr VARCHAR(2000);
DECLARE item VARCHAR(2000);
SET inipos = 1;
SET fullstr = CONCAT(Str, ",");
SET maxlen = LENGTH(fullstr);
REPEAT
SET endpos = LOCATE(",", fullstr, inipos);
SET item = SUBSTR(fullstr, inipos, endpos - inipos);
IF item <> '' AND item IS NOT NULL THEN
insert into rank_artists values(item);
END IF;
SET inipos = endpos + 1;
UNTIL inipos >= maxlen END REPEAT;
END; //
CREATE PROCEDURE Splitforpartner(IN Str VARCHAR(200))
BEGIN
DECLARE inipos INT;
DECLARE endpos INT;
DECLARE maxlen INT;
DECLARE fullstr VARCHAR(2000);
DECLARE item VARCHAR(2000);
SET inipos = 1;
SET fullstr = CONCAT(Str, ",");
SET maxlen = LENGTH(fullstr);
REPEAT
SET endpos = LOCATE(",", fullstr, inipos);
SET item = SUBSTR(fullstr, inipos, endpos - inipos);
IF item <> '' AND item IS NOT NULL THEN
insert into partners values(item);
END IF;
SET inipos = endpos + 1;
UNTIL inipos >= maxlen END REPEAT;
END; //
DELIMITER ; | 29.376147 | 219 | 0.746096 |
db2f7365a02b3febe32020edf52f2574e87149b8 | 93 | sql | SQL | src/test/resources/sql/alter_table/75881dc4.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 66 | 2018-06-15T11:34:03.000Z | 2022-03-16T09:24:49.000Z | src/test/resources/sql/alter_table/75881dc4.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 13 | 2019-03-19T11:56:28.000Z | 2020-08-05T04:20:50.000Z | src/test/resources/sql/alter_table/75881dc4.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 28 | 2019-01-05T19:59:02.000Z | 2022-03-24T11:55:50.000Z | -- file:alter_table.sql ln:2241 expect:true
ALTER TABLE list_parted2 DETACH PARTITION part_7
| 31 | 48 | 0.827957 |
c5386d128f531e2d4d83b44c6d99e49d42c4531f | 562 | cpp | C++ | demo01/test.cpp | targodan/gameProgramming | 5c0b36bee271dca65636d0317324a2bb786613f0 | [
"MIT"
] | 1 | 2019-07-14T11:32:30.000Z | 2019-07-14T11:32:30.000Z | demo01/test.cpp | targodan/gameProgramming | 5c0b36bee271dca65636d0317324a2bb786613f0 | [
"MIT"
] | null | null | null | demo01/test.cpp | targodan/gameProgramming | 5c0b36bee271dca65636d0317324a2bb786613f0 | [
"MIT"
] | null | null | null | #include <iostream>
#include "math/Matrix.h"
using namespace engine::math;
int main(int argc, char** argv) {
Matrix<2, 3> m1 = {
4, 8,
-2, 5,
0, 8
};
Matrix<2, 3> m2 = {
8, 0,
-2.4, -3.2,
0.1, -8
};
Matrix<2, 3> mRes = {
12, 8,
-4.4, 1.8,
-0.1, 0
};
std::cout << std::endl << "pre" << std::endl;
m1.add(m2);
std::cout << std::endl << "post" << std::endl;
m1 = m1 + m2;
// CPPUNIT_ASSERT_EQUAL(mRes, m1 + m2);
return 0;
}
| 16.529412 | 50 | 0.414591 |
2a215ee97ccf9b16e60442752653f918d27e5fde | 1,252 | html | HTML | ch08/myproject_virtualenv/src/django-myproject/myproject/templates/locations/location_list.html | PacktPublishing/Django-3-Web-Development-Cookbook | 6ffe6e0add93a43a9abaff62e0147dc1f4f5351a | [
"MIT"
] | 159 | 2019-11-13T14:11:39.000Z | 2022-03-24T05:47:10.000Z | ch08/myproject_virtualenv/src/django-myproject/myproject/templates/locations/location_list.html | PacktPublishing/Django-3-Web-Development-Cookbook | 6ffe6e0add93a43a9abaff62e0147dc1f4f5351a | [
"MIT"
] | 34 | 2019-11-06T08:32:48.000Z | 2022-01-14T11:31:29.000Z | ch08/myproject_virtualenv/src/django-myproject/myproject/templates/locations/location_list.html | PacktPublishing/Django-3-Web-Development-Cookbook | 6ffe6e0add93a43a9abaff62e0147dc1f4f5351a | [
"MIT"
] | 103 | 2019-08-15T21:35:26.000Z | 2022-03-20T05:29:11.000Z | {% extends "base.html" %}
{% load i18n static %}
{% block content %}
<h2>{% trans "Locations" %}</h2>
<ul class="location-list">
{% for location in location_list %}
<li class="item">
<a href="{% url "location-detail" slug=location.slug %}"
data-popup-url="{% url "location-popup" slug=location.slug %}">
{{ location.title }}</a>
</li>
{% endfor %}
</ul>
{% endblock %}
{% block extrabody %}
<div id="popup" class="modal fade" tabindex="-1" role="dialog"
aria-hidden="true" aria-labelledby="popup-modal-title">
<div class="modal-dialog modal-dialog-centered"
role="document">
<div class="modal-content">
<div class="modal-header">
<h4 id="popup-modal-title"
class="modal-title"></h4>
<button type="button" class="close"
data-dismiss="modal"
aria-label="{% trans 'Close' %}">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
{% endblock %}
{% block js %}
<script src="{% static 'site/js/location_list.js' %}"></script>
{% endblock %}
| 30.536585 | 74 | 0.515176 |
1ce84e62388fa1ab85408b6cdf620beb2fd2f520 | 1,982 | sql | SQL | ElecRecord/db/tb_sys_user_role.sql | tanliu/Electicity | b150d26ca2586a20d323f71f8efcbd0791b94179 | [
"Apache-2.0"
] | null | null | null | ElecRecord/db/tb_sys_user_role.sql | tanliu/Electicity | b150d26ca2586a20d323f71f8efcbd0791b94179 | [
"Apache-2.0"
] | null | null | null | ElecRecord/db/tb_sys_user_role.sql | tanliu/Electicity | b150d26ca2586a20d323f71f8efcbd0791b94179 | [
"Apache-2.0"
] | null | null | null | /*
Navicat MySQL Data Transfer
Source Server : Project
Source Server Version : 50540
Source Host : localhost:3306
Source Database : elecrecord
Target Server Type : MYSQL
Target Server Version : 50540
File Encoding : 65001
Date: 2016-06-08 14:01:36
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `tb_sys_user_role`
-- ----------------------------
DROP TABLE IF EXISTS `tb_sys_user_role`;
CREATE TABLE `tb_sys_user_role` (
`id` varchar(32) NOT NULL COMMENT '主键标识ID',
`user_id` varchar(32) DEFAULT NULL COMMENT '标识ID',
`role_id` varchar(32) DEFAULT NULL COMMENT '主键ID',
PRIMARY KEY (`id`),
KEY `FK_Reference_5` (`role_id`),
KEY `FK_Reference_6` (`user_id`),
CONSTRAINT `FK_Reference_6` FOREIGN KEY (`user_id`) REFERENCES `tb_sys_user` (`user_id`),
CONSTRAINT `FK_Reference_5` FOREIGN KEY (`role_id`) REFERENCES `tb_sys_role` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='一个用户可以有多个角色';
-- ----------------------------
-- Records of tb_sys_user_role
-- ----------------------------
INSERT INTO `tb_sys_user_role` VALUES ('8a8fa1e0551ffe7c01552004fff10012', null, '8a8fa1e0551ffe7c01552004e06d000b');
INSERT INTO `tb_sys_user_role` VALUES ('8a8fa1e055202c6801552032bf960020', '8a8fa1e05513be55015513c43af10002', '8a8fa1e0551c312301551c34ff6a0000');
INSERT INTO `tb_sys_user_role` VALUES ('8a8fa1e055202c6801552032d0560021', '8a8fa1e05513be55015513c8bacf0004', '8a8fa1e0551c312301551c34ff6a0000');
INSERT INTO `tb_sys_user_role` VALUES ('8a8fa1e055202c6801552032ea8f0022', '8a8fa1e05513be55015513c969150005', '8a8fa1e0551c312301551c34ff6a0000');
INSERT INTO `tb_sys_user_role` VALUES ('8a8fa1e055202c6801552032fded0023', '8a8fa1e05513be55015513cb90e60006', '8a8fa1e0551c312301551c34ff6a0000');
INSERT INTO `tb_sys_user_role` VALUES ('8a8fa1e0552da07b01552da1eb310002', '8a8fa1e0552da07b01552da1eb2f0001', '8a8fa1e0551ffe7c01552004e06d000b');
| 47.190476 | 148 | 0.71998 |
e8f4751164f0af5c0a64d647c72d41648acdaa32 | 752 | py | Python | docs/Others/Python_leetcode/Codes/1.Two_Sum.py | mheanng/PythonNote | e3e5ede07968fab0a45f6ac4db96e62092c17026 | [
"Apache-2.0"
] | 2 | 2020-04-09T05:56:23.000Z | 2021-03-25T18:42:36.000Z | docs/Others/Python_leetcode/Codes/1.Two_Sum.py | mheanng/PythonNote | e3e5ede07968fab0a45f6ac4db96e62092c17026 | [
"Apache-2.0"
] | 22 | 2020-04-09T06:09:14.000Z | 2021-01-06T01:05:32.000Z | docs/Others/Python_leetcode/Codes/1.Two_Sum.py | mheanng/PythonNote | e3e5ede07968fab0a45f6ac4db96e62092c17026 | [
"Apache-2.0"
] | 6 | 2020-03-09T07:19:21.000Z | 2021-01-05T23:23:42.000Z | """
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
"""
# %%
class Solution:
def twoSum(self, nums, target):
S = set(nums)
for num in S:
pre = target - num
if num == pre:
if nums.count(num) > 1:
index1 = nums.index(num)
return [index1, nums.index(num, index1+1)]
elif pre in S:
return [nums.index(num), nums.index(target - num)]
nums = [2, 2, 7, 11, 15]
target = 9
print(Solution().twoSum(nums, target))
nums = [2, 5, 5, 11]
target = 10
print(Solution().twoSum(nums, target))
| 22.117647 | 66 | 0.542553 |
cf8a6d5a557d9c15ded82e13b98afd64b420d073 | 434 | asm | Assembly | src/tutorialspoint.com/src/example17.asm | ishirshov/NASM-tutorial-for-Unix | 75173993e35e29bce1c04908573cc034ff32363e | [
"Apache-2.0"
] | null | null | null | src/tutorialspoint.com/src/example17.asm | ishirshov/NASM-tutorial-for-Unix | 75173993e35e29bce1c04908573cc034ff32363e | [
"Apache-2.0"
] | null | null | null | src/tutorialspoint.com/src/example17.asm | ishirshov/NASM-tutorial-for-Unix | 75173993e35e29bce1c04908573cc034ff32363e | [
"Apache-2.0"
] | null | null | null | %include "defines.inc"
section .bss
res resb 1
section .data
msg db "The sum is:", 0x2, 0xA, 0xD
len equ $ - msg
section .text
global _start
_start:
mov ecx, '4'
sub ecx, '0'
mov edx, '5'
sub edx, '0'
call sum
mov [res], eax
sys_call SYS_WRITE, STDOUT, msg, len
sys_call SYS_WRITE, STDOUT, res, 1
sys_exit
sum:
mov eax, ecx
add eax, edx
add eax, '0'
ret | 13.5625 | 40 | 0.564516 |
f51453d8aa504ee63b32cbdb38effa286aa1e5d9 | 11,636 | cxx | C++ | arrows/cuda/integrate_depth_maps.cxx | VIAME/kwiver | b746303025a834f6799b69dfb90d0c8061df64c4 | [
"BSD-3-Clause"
] | null | null | null | arrows/cuda/integrate_depth_maps.cxx | VIAME/kwiver | b746303025a834f6799b69dfb90d0c8061df64c4 | [
"BSD-3-Clause"
] | null | null | null | arrows/cuda/integrate_depth_maps.cxx | VIAME/kwiver | b746303025a834f6799b69dfb90d0c8061df64c4 | [
"BSD-3-Clause"
] | null | null | null | // This file is part of KWIVER, and is distributed under the
// OSI-approved BSD 3-Clause License. See top-level LICENSE file or
// https://github.com/Kitware/kwiver/blob/master/LICENSE for details.
/**
* \file
* \brief Source file for compute_depth, driver for depth from an image sequence
*/
#include <arrows/cuda/integrate_depth_maps.h>
#include <arrows/cuda/cuda_error_check.h>
#include <arrows/cuda/cuda_memory.h>
#include <arrows/core/depth_utils.h>
#include <sstream>
#include <cuda_runtime.h>
#include <cuda.h>
using namespace kwiver::vital;
void cuda_initalize(int h_gridDims[3], double h_gridOrig[3],
double h_gridSpacing[3], double h_rayPThick,
double h_rayPRho, double h_rayPEta, double h_rayPEpsilon,
double h_rayPDelta);
void launch_depth_kernel(double * d_depth, double * d_weight, int depthmap_dims[2],
double d_K[16], double d_RT[16], double* output,
unsigned max_voxels_per_launch);
namespace kwiver {
namespace arrows {
namespace cuda {
/// Private implementation class
class integrate_depth_maps::priv
{
public:
// Constructor
priv()
: ray_potential_rho(1.0),
ray_potential_thickness(20.0),
ray_potential_eta(1.0),
ray_potential_epsilon(0.01),
ray_potential_delta(200.0),
grid_spacing {1.0, 1.0, 1.0},
voxel_spacing_factor(1.0),
max_voxels_per_launch(20000000),
m_logger(vital::get_logger("arrows.cuda.integrate_depth_maps"))
{
}
double ray_potential_rho;
double ray_potential_thickness;
double ray_potential_eta;
double ray_potential_epsilon;
double ray_potential_delta;
int grid_dims[3];
// Actual spacing is computed as
// voxel_scale_factor * pixel_to_world_scale * grid_spacing
// relative spacings per dimension
double grid_spacing[3];
// multiplier on all dimensions of grid spacing
double voxel_spacing_factor;
// Maximum number of voxels to process in a single kernel launch
unsigned max_voxels_per_launch;
// Logger handle
vital::logger_handle_t m_logger;
};
//*****************************************************************************
/// Constructor
integrate_depth_maps::integrate_depth_maps()
: d_(new priv)
{
}
//*****************************************************************************
/// Destructor
integrate_depth_maps::~integrate_depth_maps()
{
}
//*****************************************************************************
/// Get this algorithm's \link vital::config_block configuration block \endlink
vital::config_block_sptr
integrate_depth_maps::get_configuration() const
{
// get base config from base class
auto config = vital::algo::integrate_depth_maps::get_configuration();
config->set_value("ray_potential_thickness", d_->ray_potential_thickness,
"Distance that the TSDF covers sloping from Rho to zero. "
"Units are in voxels.");
config->set_value("ray_potential_rho", d_->ray_potential_rho,
"Maximum magnitude of the TDSF");
config->set_value("ray_potential_eta", d_->ray_potential_eta,
"Fraction of rho to use for free space constraint. "
"Requires 0 <= Eta <= 1.");
config->set_value("ray_potential_epsilon", d_->ray_potential_epsilon,
"Fraction of rho to use in occluded space. "
"Requires 0 <= Epsilon <= 1.");
config->set_value("ray_potential_delta", d_->ray_potential_delta,
"Distance from the surface before the TSDF is truncate. "
"Units are in voxels");
config->set_value("voxel_spacing_factor", d_->voxel_spacing_factor,
"Multiplier on voxel spacing. Set to 1.0 for voxel "
"sizes that project to 1 pixel on average.");
config->set_value("max_voxels_per_launch", d_->max_voxels_per_launch,
"Maximum number of voxels to process in a single kernel "
"launch. Processing too much data at once on the GPU "
"can cause the GPU to time out. Set to zero for "
"unlimited.");
std::ostringstream stream;
stream << d_->grid_spacing[0] << " "
<< d_->grid_spacing[1] << " "
<< d_->grid_spacing[2];
config->set_value("grid_spacing", stream.str(),
"Relative spacing for each dimension of the grid");
return config;
}
//*****************************************************************************
/// Set this algorithm's properties via a config block
void
integrate_depth_maps::set_configuration(vital::config_block_sptr in_config)
{
// Starting with our generated vital::config_block to ensure that
// assumed values are present. An alternative is to check for key
// presence before performing a get_value() call.
vital::config_block_sptr config = this->get_configuration();
config->merge_config(in_config);
d_->ray_potential_rho =
config->get_value<double>("ray_potential_rho", d_->ray_potential_rho);
d_->ray_potential_thickness =
config->get_value<double>("ray_potential_thickness",
d_->ray_potential_thickness);
d_->ray_potential_eta =
config->get_value<double>("ray_potential_eta", d_->ray_potential_eta);
d_->ray_potential_epsilon =
config->get_value<double>("ray_potential_epsilon", d_->ray_potential_epsilon);
d_->ray_potential_delta =
config->get_value<double>("ray_potential_delta", d_->ray_potential_delta);
d_->voxel_spacing_factor =
config->get_value<double>("voxel_spacing_factor", d_->voxel_spacing_factor);
d_->max_voxels_per_launch =
config->get_value<unsigned>("max_voxels_per_launch",
d_->max_voxels_per_launch);
std::ostringstream ostream;
ostream << d_->grid_spacing[0] << " "
<< d_->grid_spacing[1] << " "
<< d_->grid_spacing[2];
std::string spacing =
config->get_value<std::string>("grid_spacing", ostream.str());
std::istringstream istream(spacing);
istream >> d_->grid_spacing[0] >> d_->grid_spacing[1] >> d_->grid_spacing[2];
}
//*****************************************************************************
/// Check that the algorithm's currently configuration is valid
bool
integrate_depth_maps::check_configuration(vital::config_block_sptr config) const
{
return true;
}
//*****************************************************************************
cuda_ptr<double>
copy_img_to_gpu(kwiver::vital::image_container_sptr h_img)
{
size_t size = h_img->height() * h_img->width();
std::unique_ptr<double[]> temp(new double[size]);
//copy to cuda format
kwiver::vital::image img = h_img->get_image();
for (unsigned int i = 0; i < h_img->width(); i++)
{
for (unsigned int j = 0; j < h_img->height(); j++)
{
temp[i*h_img->height() + j] = img.at<double>(i, j);
}
}
auto d_img = make_cuda_mem<double>(size);
CudaErrorCheck(cudaMemcpy(d_img.get(), temp.get(), size * sizeof(double),
cudaMemcpyHostToDevice));
return d_img;
}
//*****************************************************************************
cuda_ptr<double> init_volume_on_gpu(size_t vsize)
{
auto output = make_cuda_mem<double>(vsize);
CudaErrorCheck(cudaMemset(output.get(), 0, vsize * sizeof(double)));
return output;
}
//*****************************************************************************
void copy_camera_to_gpu(kwiver::vital::camera_perspective_sptr camera,
double* d_K, double *d_RT)
{
Eigen::Matrix<double, 4, 4, Eigen::RowMajor> K4x4;
K4x4.setIdentity();
matrix_3x3d K(camera->intrinsics()->as_matrix());
K4x4.block< 3, 3 >(0, 0) = K;
Eigen::Matrix<double, 4, 4, Eigen::RowMajor> RT;
RT.setIdentity();
matrix_3x3d R(camera->rotation().matrix());
vector_3d t(camera->translation());
RT.block< 3, 3 >(0, 0) = R;
RT.block< 3, 1 >(0, 3) = t;
CudaErrorCheck(cudaMemcpy(d_K, K4x4.data(), 16 * sizeof(double),
cudaMemcpyHostToDevice));
CudaErrorCheck(cudaMemcpy(d_RT, RT.data(), 16 * sizeof(double),
cudaMemcpyHostToDevice));
}
//*****************************************************************************
void
integrate_depth_maps::integrate(
vector_3d const& minpt_bound,
vector_3d const& maxpt_bound,
std::vector<image_container_sptr> const& depth_maps,
std::vector<image_container_sptr> const& weight_maps,
std::vector<camera_perspective_sptr> const& cameras,
image_container_sptr& volume,
vector_3d &spacing) const
{
double pixel_to_world_scale;
pixel_to_world_scale =
kwiver::arrows::core::
compute_pixel_to_world_scale(minpt_bound, maxpt_bound, cameras);
vector_3d diff = maxpt_bound - minpt_bound;
vector_3d orig = minpt_bound;
spacing = vector_3d(d_->grid_spacing);
spacing *= pixel_to_world_scale * d_->voxel_spacing_factor;
double max_spacing = spacing.maxCoeff();
for (int i = 0; i < 3; i++)
{
d_->grid_dims[i] = static_cast<int>((diff[i] / spacing[i]));
}
LOG_DEBUG( logger(), "voxel size: " << spacing[0]
<< " " << spacing[1]
<< " " << spacing[2] );
LOG_DEBUG( logger(), "grid: " << d_->grid_dims[0]
<< " " << d_->grid_dims[1]
<< " " << d_->grid_dims[2] );
LOG_INFO( logger(), "initialize" );
cuda_initalize(d_->grid_dims, orig.data(), spacing.data(),
d_->ray_potential_thickness * max_spacing,
d_->ray_potential_rho,
d_->ray_potential_eta,
d_->ray_potential_epsilon,
d_->ray_potential_delta * max_spacing);
const size_t vsize = static_cast<size_t>(d_->grid_dims[0]) *
static_cast<size_t>(d_->grid_dims[1]) *
static_cast<size_t>(d_->grid_dims[2]);
cuda_ptr<double> d_volume = init_volume_on_gpu(vsize);
cuda_ptr<double> d_K = make_cuda_mem<double>(16);
cuda_ptr<double> d_RT = make_cuda_mem<double>(16);
for (size_t i = 0; i < depth_maps.size(); i++)
{
int depthmap_dims[2];
depthmap_dims[0] = static_cast<int>(depth_maps[i]->width());
depthmap_dims[1] = static_cast<int>(depth_maps[i]->height());
cuda_ptr<double> d_depth = copy_img_to_gpu(depth_maps[i]);
cuda_ptr<double> d_weight = nullptr;
if (i < weight_maps.size())
{
auto weight = weight_maps[i];
if (weight->width() == depth_maps[i]->width() &&
weight->height() == depth_maps[i]->height())
{
d_weight = copy_img_to_gpu(weight_maps[i]);
}
}
copy_camera_to_gpu(cameras[i], d_K.get(), d_RT.get());
// run code on device
LOG_INFO( logger(), "depth map " << i );
launch_depth_kernel(d_depth.get(), d_weight.get(), depthmap_dims,
d_K.get(), d_RT.get(), d_volume.get(),
d_->max_voxels_per_launch);
}
// Transfer data from device to host
auto h_volume = std::make_shared<image_memory>(vsize * sizeof(double));
CudaErrorCheck(cudaMemcpy(h_volume->data(), d_volume.get(), vsize * sizeof(double),
cudaMemcpyDeviceToHost));
volume = std::make_shared<simple_image_container>(
image_of<double>(h_volume, reinterpret_cast<const double*>(h_volume->data()),
d_->grid_dims[0], d_->grid_dims[1], d_->grid_dims[2],
1, d_->grid_dims[0], d_->grid_dims[0] * d_->grid_dims[1]));
}
} // end namespace cuda
} // end namespace arrows
} // end namespace kwiver
| 35.693252 | 85 | 0.613011 |
70fb8a6ee2a74feb177778e2444a2ecee3dccf0f | 1,279 | cs | C# | SortingAndSearchingAlgorithms/Quicksorter.cs | pavelhristov/CSharpDataStructuresAndAlgorithms | a2ad23f3adca00421f2a185d2b9541c49060dedf | [
"MIT"
] | null | null | null | SortingAndSearchingAlgorithms/Quicksorter.cs | pavelhristov/CSharpDataStructuresAndAlgorithms | a2ad23f3adca00421f2a185d2b9541c49060dedf | [
"MIT"
] | null | null | null | SortingAndSearchingAlgorithms/Quicksorter.cs | pavelhristov/CSharpDataStructuresAndAlgorithms | a2ad23f3adca00421f2a185d2b9541c49060dedf | [
"MIT"
] | null | null | null | namespace SortingHomework
{
using System;
using System.Collections.Generic;
public class Quicksorter<T> : ISorter<T> where T : IComparable<T>
{
public void Sort(IList<T> collection)
{
QuickSort(collection, 0, collection.Count - 1);
}
private static void QuickSort(IList<T> collection, int low, int high)
{
if (low < high)
{
var p = Partition(collection, low, high);
QuickSort(collection, low, p - 1);
QuickSort(collection, p + 1, high);
}
}
private static int Partition(IList<T> collection, int low, int high)
{
var pivot = collection[high];
var i = low;
for (int j = low; j < high; j++)
{
if (collection[j].CompareTo(pivot) <= 0)
{
Swap(collection, i, j);
i++;
}
}
Swap(collection, i, high);
return i;
}
private static void Swap(IList<T> collection, int i, int j)
{
var temp = collection[i];
collection[i] = collection[j];
collection[j] = temp;
}
}
}
| 26.102041 | 77 | 0.462862 |
f50553800fdf16b708b2cb1288b5355137bf944a | 1,549 | cpp | C++ | trunk/research/thread-model/thread-local.cpp | attenuation/srs | 897d2104fb79c4fc1a89e3889645424c077535bd | [
"MIT"
] | 21 | 2022-01-10T08:41:36.000Z | 2022-03-25T02:52:56.000Z | trunk/research/thread-model/thread-local.cpp | attenuation/srs | 897d2104fb79c4fc1a89e3889645424c077535bd | [
"MIT"
] | 44 | 2022-01-05T03:40:46.000Z | 2022-03-30T03:58:11.000Z | trunk/research/thread-model/thread-local.cpp | attenuation/srs | 897d2104fb79c4fc1a89e3889645424c077535bd | [
"MIT"
] | 17 | 2022-01-05T02:58:25.000Z | 2022-03-30T09:23:36.000Z | /*
g++ -std=c++11 -g -O0 thread-local.cpp -o thread-local
*/
#include <stdio.h>
// @see https://linux.die.net/man/3/pthread_create
#include <pthread.h>
// Global thread local int variable.
thread_local int tl_g_nn = 0;
// Global thread local variable object.
class MyClass
{
public:
int tl_nn;
MyClass(int nn) {
tl_nn = nn;
}
};
thread_local MyClass g_obj(0);
thread_local MyClass* gp_obj = new MyClass(0);
thread_local MyClass* gp_obj2 = NULL;
MyClass* get_gp_obj2()
{
if (!gp_obj2) {
gp_obj2 = new MyClass(0);
}
return gp_obj2;
}
void* pfn(void* arg)
{
int tid = (int)(long long)arg;
tl_g_nn += tid;
g_obj.tl_nn += tid;
gp_obj->tl_nn += tid;
get_gp_obj2()->tl_nn += tid;
printf("PFN%d: tl_g_nn(%p)=%d, g_obj(%p)=%d, gp_obj(%p,%p)=%d, gp_obj2(%p,%p)=%d\n", tid,
&tl_g_nn, tl_g_nn, &g_obj, g_obj.tl_nn, &gp_obj, gp_obj, gp_obj->tl_nn,
&gp_obj2, gp_obj2, get_gp_obj2()->tl_nn);
return NULL;
}
int main(int argc, char** argv)
{
pthread_t trd = NULL, trd2 = NULL;
pthread_create(&trd, NULL, pfn, (void*)1);
pthread_create(&trd2, NULL, pfn, (void*)2);
pthread_join(trd, NULL);
pthread_join(trd2, NULL);
tl_g_nn += 100;
g_obj.tl_nn += 100;
gp_obj->tl_nn += 100;
get_gp_obj2()->tl_nn += 100;
printf("MAIN: tl_g_nn(%p)=%d, g_obj(%p)=%d, gp_obj(%p,%p)=%d, gp_obj2(%p,%p)=%d\n",
&tl_g_nn, tl_g_nn, &g_obj, g_obj.tl_nn, &gp_obj, gp_obj, gp_obj->tl_nn,
&gp_obj2, gp_obj2, get_gp_obj2()->tl_nn);
return 0;
}
| 23.830769 | 93 | 0.60878 |
44864381aff38ba7f6d3d3eacaacf0257c9cc696 | 1,102 | ps1 | PowerShell | Public/ADGroup.ps1 | adbertram/poshspec | 219f44dc5e37ba16fc240a34f38562229e710669 | [
"MIT"
] | 1 | 2017-08-29T20:40:10.000Z | 2017-08-29T20:40:10.000Z | Public/ADGroup.ps1 | adbertram/poshspec | 219f44dc5e37ba16fc240a34f38562229e710669 | [
"MIT"
] | null | null | null | Public/ADGroup.ps1 | adbertram/poshspec | 219f44dc5e37ba16fc240a34f38562229e710669 | [
"MIT"
] | 1 | 2020-07-27T05:53:17.000Z | 2020-07-27T05:53:17.000Z | <#
.SYNOPSIS
Test an Active Directory group.
.DESCRIPTION
Tests multiple attributes associated with an Active Directory group.
.PARAMETER Target
Specifies the samAccountNames of one or more Active Directory groups.
.PARAMETER Should
A Script Block defining a Pester Assertion.
.EXAMPLE
ADGroup GroupOne Scope { Should be 'DomainLocal' }
.EXAMPLE
ADGroup jschmoe Category { Should be 'Security' }
#>
function ADGroup {
[CmdletBinding(DefaultParameterSetName='prop')]
param(
[Parameter(Mandatory, Position=1)]
[Alias("Name")]
[string]$Target,
[Parameter(Position=2, ParameterSetName='prop')]
[ValidateSet('Scope','Category')]
[string]$Property,
[Parameter(Position=2, ParameterSetName='noprop')]
[Parameter(Position=3, ParameterSetName='prop')]
[scriptblock]$Should
)
$testExpression = {
Get-PoshSpecADGroup -Name '$Target'
}
$params = Get-PoshspecParam -TestName ADGroup -TestExpression $testExpression @PSBoundParameters
Invoke-PoshspecExpression @params
} | 29 | 100 | 0.683303 |
e912d5de74127aca93ad84172c82a7ae6de51f07 | 1,159 | hh | C++ | StRoot/StTriggerUtilities/StDSMUtilities/DSM.hh | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StTriggerUtilities/StDSMUtilities/DSM.hh | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StTriggerUtilities/StDSMUtilities/DSM.hh | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | //
// Pibero Djawotho <pibero@comp.tamu.edu>
// Texas A&M University Cyclotron Institute
// 1 Jan 2009
//
#ifndef DSM_HH
#define DSM_HH
#include <string>
#include <sstream>
#include <iomanip>
#include <stdio.h>
using namespace std;
struct DSM {
enum { NREGISTERS = 32, NCHANNELS = 16, LUT_SIZE = 16, INFO_SIZE = 64 };
string name;
int registers[NREGISTERS];
short channels[NCHANNELS];
char lut[LUT_SIZE];
int info[INFO_SIZE];
int output;
DSM(const string& name = "") : name(name) { clear(); }
void clear();
void setName(const string& basename, int layer, int dsm);
void dump();
};
inline void DSM::clear()
{
fill(registers,registers+NREGISTERS,0);
fill(channels,channels+NCHANNELS,0);
fill(lut,lut+LUT_SIZE,0);
fill(info,info+INFO_SIZE,0);
output = 0;
}
inline void DSM::setName(const string& basename, int layer, int dsm)
{
ostringstream ss;
ss << basename << layer << setw(2) << setfill('0') << dsm+1;
name = ss.str();
}
inline void DSM::dump()
{
printf("%s: ", name.c_str());
for (int ch = 0; ch < 8; ++ch)
printf("%04x ", (unsigned short)channels[ch]);
printf("\n");
}
#endif // DSM_HH
| 20.333333 | 74 | 0.644521 |
5c4940c657b6654be5c52f21066fa63cf4c63cd8 | 5,494 | ps1 | PowerShell | REST/PowerShell/Users/ListUsers.ps1 | gdesai1234/OctopusDeploy-Api | c0b70fa5d5fb39b7ba5d0b75d90e0dbfc25e57b2 | [
"Apache-2.0"
] | 199 | 2015-01-16T12:53:36.000Z | 2022-03-22T08:18:16.000Z | REST/PowerShell/Users/ListUsers.ps1 | gdesai1234/OctopusDeploy-Api | c0b70fa5d5fb39b7ba5d0b75d90e0dbfc25e57b2 | [
"Apache-2.0"
] | 66 | 2015-01-27T06:40:25.000Z | 2021-12-17T13:57:42.000Z | REST/PowerShell/Users/ListUsers.ps1 | gdesai1234/OctopusDeploy-Api | c0b70fa5d5fb39b7ba5d0b75d90e0dbfc25e57b2 | [
"Apache-2.0"
] | 139 | 2015-09-16T17:49:09.000Z | 2022-03-10T18:16:07.000Z | $ErrorActionPreference = "Stop";
# Define working variables
$octopusURL = "https://your.octopus.app"
$octopusAPIKey = "API-YOURAPIKEY"
$header = @{ "X-Octopus-ApiKey" = $octopusAPIKey }
# Optional: include user role details?
$includeUserRoles = $False
# Optional: include non-active users in output
$includeNonActiveUsers = $False
# Optional: include AD details
$includeActiveDirectoryDetails = $False
# Optional: include AAD details
$includeAzureActiveDirectoryDetails = $False
# Optional: set a path to export to csv
$csvExportPath = ""
$users = @()
$usersList = @()
$response = $null
do {
$uri = if ($response) { $octopusURL + $response.Links.'Page.Next' } else { "$octopusURL/api/users" }
$response = Invoke-RestMethod -Method Get -Uri $uri -Headers $header
$usersList += $response.Items
} while ($response.Links.'Page.Next')
# Filter non-active users
if($includeNonActiveUsers -eq $False) {
Write-Host "Filtering users who arent active from results"
$usersList = $usersList | Where-Object {$_.IsActive -eq $True}
}
# If we are including user roles, need to get team details
if($includeUserRoles -eq $True) {
$teams = @()
$response = $null
do {
$uri = if ($response) { $octopusURL + $response.Links.'Page.Next' } else { "$octopusURL/api/teams" }
$response = Invoke-RestMethod -Method Get -Uri $uri -Headers $header
$teams += $response.Items
} while ($response.Links.'Page.Next')
foreach($team in $teams) {
$scopedUserRoles = Invoke-RestMethod -Method Get -Uri ("$octopusURL/api/teams/$($team.Id)/scopeduserroles") -Headers $header
$team | Add-Member -MemberType NoteProperty -Name "ScopedUserRoles" -Value $scopedUserRoles.Items
}
$allUserRoles = @()
$response = $null
do {
$uri = if ($response) { $octopusURL + $response.Links.'Page.Next' } else { "$octopusURL/api/userroles" }
$response = Invoke-RestMethod -Method Get -Uri $uri -Headers $header
$allUserRoles += $response.Items
} while ($response.Links.'Page.Next')
$spaces = @()
$response = $null
do {
$uri = if ($response) { $octopusURL + $response.Links.'Page.Next' } else { "$octopusURL/api/spaces" }
$response = Invoke-RestMethod -Method Get -Uri $uri -Headers $header
$spaces += $response.Items
} while ($response.Links.'Page.Next')
}
foreach($userRecord in $usersList) {
$usersRoles = @()
$user = [PSCustomObject]@{
Id = $userRecord.Id
Username = $userRecord.Username
DisplayName = $userRecord.DisplayName
IsActive = $userRecord.IsActive
IsService = $userRecord.IsService
EmailAddress = $userRecord.EmailAddress
}
if($includeActiveDirectoryDetails -eq $True)
{
$user | Add-Member -MemberType NoteProperty -Name "AD_Upn" -Value $null
$user | Add-Member -MemberType NoteProperty -Name "AD_Sam" -Value $null
$user | Add-Member -MemberType NoteProperty -Name "AD_Email" -Value $null
}
if($includeAzureActiveDirectoryDetails -eq $True)
{
$user | Add-Member -MemberType NoteProperty -Name "AAD_DN" -Value $null
$user | Add-Member -MemberType NoteProperty -Name "AAD_Email" -Value $null
}
if($includeUserRoles -eq $True) {
$usersTeams = $teams | Where-Object {$_.MemberUserIds -icontains $user.Id}
foreach($userTeam in $usersTeams) {
$roles = $userTeam.ScopedUserRoles
foreach($role in $roles) {
$userRole = $allUserRoles | Where-Object {$_.Id -eq $role.UserRoleId} | Select-Object -First 1
$roleName = "$($userRole.Name)"
$roleSpace = $spaces | Where-Object {$_.Id -eq $role.SpaceId} | Select-Object -First 1
if (![string]::IsNullOrWhiteSpace($roleSpace)) {
$roleName += " ($($roleSpace.Name))"
}
$usersRoles+= $roleName
}
}
$user | Add-Member -MemberType NoteProperty -Name "ScopedUserRoles" -Value ($usersRoles -Join "|")
}
if($userRecord.Identities.Count -gt 0) {
if($includeActiveDirectoryDetails -eq $True)
{
$activeDirectoryIdentity = $userRecord.Identities | Where-Object {$_.IdentityProviderName -eq "Active Directory"} | Select-Object -ExpandProperty Claims
if($null -ne $activeDirectoryIdentity) {
$user.AD_Upn = (($activeDirectoryIdentity | ForEach-Object {"$($_.upn.Value)"}) -Join "|")
$user.AD_Sam = (($activeDirectoryIdentity | ForEach-Object {"$($_.sam.Value)"}) -Join "|")
$user.AD_Email = (($activeDirectoryIdentity | ForEach-Object {"$($_.email.Value)"}) -Join "|")
}
}
if($includeAzureActiveDirectoryDetails -eq $True)
{
$azureAdIdentity = $userRecord.Identities | Where-Object {$_.IdentityProviderName -eq "Azure AD"} | Select-Object -ExpandProperty Claims
if($null -ne $azureAdIdentity) {
$user.AAD_Dn = (($azureAdIdentity | ForEach-Object {"$($_.dn.Value)"}) -Join "|")
$user.AAD_Email = (($azureAdIdentity | ForEach-Object {"$($_.email.Value)"}) -Join "|")
}
}
}
$users+=$user
}
if (![string]::IsNullOrWhiteSpace($csvExportPath)) {
Write-Host "Exporting results to CSV file: $csvExportPath"
$users | Export-Csv -Path $csvExportPath -NoTypeInformation
}
$users | Format-Table
| 39.811594 | 164 | 0.624681 |
dfdd5c1e8da5b668af3bdaa2db279731590df9b8 | 9,908 | sql | SQL | ace-modules/ace-admin/db/11月/2019-11-12.sql | zcf9916/udax_wallet | f971679e9debc85908ed715ec6485c211137257b | [
"Apache-2.0"
] | 1 | 2020-03-27T08:48:25.000Z | 2020-03-27T08:48:25.000Z | ace-modules/ace-admin/db/11月/2019-11-12.sql | zcf9916/udax_wallet | f971679e9debc85908ed715ec6485c211137257b | [
"Apache-2.0"
] | 7 | 2020-06-30T23:26:49.000Z | 2022-03-31T22:09:38.000Z | ace-modules/ace-admin/db/11月/2019-11-12.sql | zcf9916/udax_wallet | f971679e9debc85908ed715ec6485c211137257b | [
"Apache-2.0"
] | 1 | 2021-01-02T02:18:50.000Z | 2021-01-02T02:18:50.000Z |
INSERT INTO `base_menu` (`id`, `code`, `title`, `parent_id`, `href`, `icon`, `type`, `order_num`, `description`, `path`, `enabled`, `attr1`, `language_type`, `crt_time`, `crt_name`, `upd_time`, `upd_name`) VALUES(NULL,'cmsConfigManager','推荐分成配置','38','/config/cmsConfig','','menu','0',NULL,'/marketingManager/configManager/cmsConfigManager',NULL,'_import(\'/config/cmsConfig/index\')',NULL,NULL,NULL,'2019-09-11 14:08:59','Tian');
insert into `base_menu` (`id`, `code`, `title`, `parent_id`, `href`, `icon`, `type`, `order_num`, `description`, `path`, `enabled`, `attr1`, `language_type`, `crt_time`, `crt_name`, `upd_time`, `upd_name`) values('115','commissionLog','分成明细管理','56','/assets/commissionLog',NULL,'menu','0','分成明细管理','/assetsManager/commissionLog',NULL,'_import(\'assets/commissionLog/index\')',NULL,NULL,NULL,'2019-03-30 17:07:32','Tian');
insert into `base_element` (`id`, `code`, `type`, `name`, `uri`, `menu_id`, `parent_id`, `path`, `method`, `description`, `language_type`, `crt_time`, `crt_name`, `upd_time`, `upd_name`) values(null,'cmsConfigManager:view','uri','View','/cmsConfig/{*}','114',NULL,NULL,'GET',NULL,NULL,NULL,NULL,NULL,NULL);
insert into `base_element` (`id`, `code`, `type`, `name`, `uri`, `menu_id`, `parent_id`, `path`, `method`, `description`, `language_type`, `crt_time`, `crt_name`, `upd_time`, `upd_name`) values(null,'cmsConfigManager:btn_add','button','New','/cmsConfig','114',NULL,NULL,'POST',NULL,NULL,NULL,NULL,NULL,NULL);
insert into `base_element` (`id`, `code`, `type`, `name`, `uri`, `menu_id`, `parent_id`, `path`, `method`, `description`, `language_type`, `crt_time`, `crt_name`, `upd_time`, `upd_name`) values(null,'cmsConfigManager:btn_edit','button','Edit','/cmsConfig/{*}','114',NULL,NULL,'PUT',NULL,NULL,NULL,NULL,NULL,NULL);
insert into `base_element` (`id`, `code`, `type`, `name`, `uri`, `menu_id`, `parent_id`, `path`, `method`, `description`, `language_type`, `crt_time`, `crt_name`, `upd_time`, `upd_name`) values(null,'cmsConfigManager:btn_del','button','Delete','/cmsConfig/{*}','114',NULL,NULL,'DELETE',NULL,NULL,NULL,NULL,NULL,NULL);
ALTER TABLE `wallet`.`front_transfer_detail`
ADD COLUMN `settle_status` TINYINT(1) NULL DEFAULT 0 COMMENT '0:未生成结算记录 1:已生成结算记录' AFTER `remark`;
ALTER TABLE `wallet`.`transfer_order`
ADD COLUMN `settle_status` TINYINT(1) NULL DEFAULT 0 COMMENT '0:未生成结算记录 1:已生成结算记录' AFTER `remark`;
CREATE TABLE `cms_config`
(
`id` bigint(10) NOT NULL AUTO_INCREMENT COMMENT '编号',
`cms_rate` decimal(4, 4) NOT NULL COMMENT '分成比例',
`type` tinyint(4) NOT NULL DEFAULT '1' COMMENT '类型 1:第一级用户 2:第二级用户 3:第三级用户 4:推荐用户分成比例 5:白标分成比例',
`exch_id` bigint(20) NOT NULL DEFAULT '0' COMMENT '白标ID',
`remark` varchar(20) DEFAULT NULL COMMENT '级别描述',
`enable` tinyint(1) NOT NULL DEFAULT '1' COMMENT '0 禁用 1正常',
`create_time` datetime DEFAULT NULL,
`parent_id` bigint(11) DEFAULT '-1' COMMENT '上级id 默认为-1',
PRIMARY KEY (`id`)
) ENGINE = InnoDB
AUTO_INCREMENT = 87
DEFAULT CHARSET = utf8 COMMENT ='用户分佣级别配置表';
CREATE TABLE `commission_log`
(
`id` bigint(10) NOT NULL AUTO_INCREMENT COMMENT '编号',
`order_no` bigint(20) NOT NULL COMMENT '成交单号',
`tradeuser_id` bigint(20) NOT NULL COMMENT '交易用户ID',
`order_type` tinyint(4) NOT NULL COMMENT '分成类型 1 转账 2 转币',
`tradeuser_name` char(20) NOT NULL COMMENT '交易用户名',
`receive_user_id` bigint(20) DEFAULT '0' COMMENT '收取佣金的用户',
`receive_user_name` char(20) NOT NULL COMMENT '交易用户ID',
`exchange_id` bigint(20) NOT NULL COMMENT '白标ID',
`type` tinyint(4) NOT NULL COMMENT '1:第一级用户 2:第二级用户 3:第三级用户 4:白标',
`symbol` char(10) NOT NULL COMMENT '收取的手续费对应的币种',
`settle_symbol` char(10) NOT NULL COMMENT '结算的币种 ',
`total_cms` decimal(16, 8) NOT NULL COMMENT '总的手续费',
`cms_rate` decimal(6, 4) NOT NULL COMMENT '手续费分成比例',
`amount` decimal(16, 8) NOT NULL COMMENT '得到的手续费分成',
`settle_amount` decimal(16, 8) NOT NULL COMMENT '结算的币种手续费分成 ',
`rate` decimal(16, 2) NOT NULL COMMENT '手续费币种和结算币种的转换比例 即一个手续费币种=n个结算币种',
`settle_status` tinyint(1) NOT NULL DEFAULT '0' COMMENT '结算状态: 0:未结算.1:结算入金成功.',
`create_time` datetime NOT NULL COMMENT '创建时间',
`order_time` int(11) NOT NULL COMMENT '订单时间时间戳',
PRIMARY KEY (`id`),
UNIQUE KEY `flow` (`order_no`, `type`),
KEY `dateIndex` (`order_time`, `receive_user_id`),
KEY `receive_user_index` (`receive_user_id`)
) ENGINE = InnoDB
AUTO_INCREMENT = 100128
DEFAULT CHARSET = utf8 COMMENT ='手续费分成明细表';
insert into `base_dict_type` (`id`, `dict_name`, `dict_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values('33','手续费分成等级','commission_level','1','2019-11-12 11:29:26','2019-11-12 11:43:18','Tian','Tian',NULL);
insert into `base_dict_data` (`id`, `dict_id`, `sort`, `dict_label`, `dict_value`, `dict_type`, `language_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values(null,'33','1','直推一级用户','1','commission_level','zh','1','2019-11-12 11:29:43','2019-11-12 11:29:43','Tian','Tian',NULL);
insert into `base_dict_data` (`id`, `dict_id`, `sort`, `dict_label`, `dict_value`, `dict_type`, `language_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values(null,'33','2','第二级用户','2','commission_level','zh','1','2019-11-12 11:30:16','2019-11-12 11:30:16','Tian','Tian',NULL);
insert into `base_dict_data` (`id`, `dict_id`, `sort`, `dict_label`, `dict_value`, `dict_type`, `language_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values(null,'33','3','第三级用户','3','commission_level','zh','1','2019-11-12 11:30:25','2019-11-12 11:30:25','Tian','Tian',NULL);
insert into `base_dict_data` (`id`, `dict_id`, `sort`, `dict_label`, `dict_value`, `dict_type`, `language_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values(null,'33','1','直推一级用户','1','commission_level','en','1','2019-11-12 11:32:16','2019-11-12 11:32:16','Tian','Tian',NULL);
insert into `base_dict_data` (`id`, `dict_id`, `sort`, `dict_label`, `dict_value`, `dict_type`, `language_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values(null,'33','2','第二级用户','2','commission_level','en','1','2019-11-12 11:32:26','2019-11-12 11:32:26','Tian','Tian',NULL);
insert into `base_dict_data` (`id`, `dict_id`, `sort`, `dict_label`, `dict_value`, `dict_type`, `language_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values(null,'33','3','第三级用户','3','commission_level','en','1','2019-11-12 11:32:35','2019-11-12 11:32:35','Tian','Tian',NULL);
insert into `base_dict_data` (`id`, `dict_id`, `sort`, `dict_label`, `dict_value`, `dict_type`, `language_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values(null,'33','4','推荐用户分成比例','4','commission_level','zh','1','2019-11-12 16:18:18','2019-11-12 16:18:18','Tian','Tian',NULL);
insert into `base_dict_data` (`id`, `dict_id`, `sort`, `dict_label`, `dict_value`, `dict_type`, `language_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values(null,'33','4','推荐用户分成比例','4','commission_level','en','1','2019-11-12 16:18:31','2019-11-12 16:18:31','Tian','Tian',NULL);
insert into `base_element` (`id`, `code`, `type`, `name`, `uri`, `menu_id`, `parent_id`, `path`, `method`, `description`, `language_type`, `crt_time`, `crt_name`, `upd_time`, `upd_name`) values(null,'commissionLog:btn_edit','button','Edit','/commissionLog/{*}','115',NULL,NULL,'PUT',NULL,NULL,NULL,NULL,NULL,NULL);
insert into `base_element` (`id`, `code`, `type`, `name`, `uri`, `menu_id`, `parent_id`, `path`, `method`, `description`, `language_type`, `crt_time`, `crt_name`, `upd_time`, `upd_name`) values(null,'commissionLog:btn_batch_edit','button','Edit','/commissionLog/{*}','115',NULL,NULL,'PUT',NULL,NULL,NULL,NULL,NULL,NULL);
insert into `base_element` (`id`, `code`, `type`, `name`, `uri`, `menu_id`, `parent_id`, `path`, `method`, `description`, `language_type`, `crt_time`, `crt_name`, `upd_time`, `upd_name`) values(null,'frontTransferDetailManager:btn_edit','button','Edit','/frontUserManager/{*}','69',NULL,NULL,'PUT',NULL,NULL,NULL,NULL,NULL,NULL);
insert into `base_element` (`id`, `code`, `type`, `name`, `uri`, `menu_id`, `parent_id`, `path`, `method`, `description`, `language_type`, `crt_time`, `crt_name`, `upd_time`, `upd_name`) values(null,'transferOrderManager:btn_edit','button','Edit','/frontUserManager/{*}','60',NULL,NULL,'PUT',NULL,NULL,NULL,NULL,NULL,NULL);
insert into `base_dict_type` (`id`, `dict_name`, `dict_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values('34','充值地址与链类型关联','recharge_protocol','1','2019-11-19 16:30:16','2019-11-19 16:30:16','Tian','Tian','充值分配地址时,根据链类型分配地址');
insert into `base_dict_data` (`id`, `dict_id`, `sort`, `dict_label`, `dict_value`, `dict_type`, `language_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values(null,'34','1','OMNI','USDT','recharge_protocol',NULL,'1','2019-11-19 16:31:48','2019-11-19 16:31:48','Tian','Tian',NULL);
insert into `base_dict_data` (`id`, `dict_id`, `sort`, `dict_label`, `dict_value`, `dict_type`, `language_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values(null,'34','2','ERC20','ETH','recharge_protocol',NULL,'1','2019-11-19 16:32:17','2019-11-19 16:32:17','Tian','Tian',NULL);
insert into `base_dict_data` (`id`, `dict_id`, `sort`, `dict_label`, `dict_value`, `dict_type`, `language_type`, `status`, `crt_time`, `upd_time`, `upd_name`, `crt_name`, `remark`) values(null,'34','3','TRC20','TRX','recharge_protocol',NULL,'1','2019-11-19 16:32:39','2019-11-19 16:32:39','Tian','Tian',NULL);
| 115.209302 | 430 | 0.657953 |
9632c1d881c6af78197948a3d57bd6ca5b3adf69 | 11,045 | php | PHP | src/ExmailQQ/ExmailMailList.php | henrickcn/exmailqq | d9f9dbc60b9aeb471fbe1439241e8627cb4a2440 | [
"MIT"
] | 1 | 2020-12-30T15:51:52.000Z | 2020-12-30T15:51:52.000Z | src/ExmailQQ/ExmailMailList.php | henrickcn/exmailqq | d9f9dbc60b9aeb471fbe1439241e8627cb4a2440 | [
"MIT"
] | null | null | null | src/ExmailQQ/ExmailMailList.php | henrickcn/exmailqq | d9f9dbc60b9aeb471fbe1439241e8627cb4a2440 | [
"MIT"
] | null | null | null | <?php
// +----------------------------------------------------------------------
// | Title : 通讯录接口
// +----------------------------------------------------------------------
// | Created : Henrick (me@hejinmin.cn)
// +----------------------------------------------------------------------
// | From : Shenzhen wepartner network Ltd
// +----------------------------------------------------------------------
// | Date : 2020-05-21 14:33
// +----------------------------------------------------------------------
namespace Henrick\ExmailQQ;
class ExmailMailList extends ExmailQQCore
{
/**
* 创建部门
* @param $token 凭证
* @param $name 部门名称
* @param int $parentid 父部门ID
* @param int $order 排序
* @return mixed
*/
public function createDepartment($token, $name, $parentid=1, $order=0){
$data = [
'name' => $name,
'parentid' => $parentid,
'order' => $order
];
return $this->post('createDept', $token, $data);
}
/**
* 更新部门
*@param $token 凭证
* @param $id 部门ID
* @param $name 部门名称
* @param int $parentid 父部门ID
* @param int $order 排序
* @return mixed
*/
public function updateDepartment($token, $id, $name, $parentid='', $order=''){
$data = [
'id' => intval($id),
'name' => $name
];
$parentid!=='' ? $data['parentid'] = intval($parentid):'';
$order!=='' ? $data['order'] = intval($order) :'';
return $this->post('updateDept', $token, $data);
}
/**
* 查询部门信息
* @param $token 凭证
* @param $name 部门名字
* @param $fuzzy 是否模糊匹配
*/
public function searchDepartment($token, $name, $fuzzy=1){
$data = [
'name' => $name,
'fuzzy' => intval($fuzzy)
];
return $this->post('searchDept', $token, $data);
}
/**
* 删除部门
* @param $token 凭证
* @param $id 部门ID
* @return mixed
*/
public function delDepartment($token, $id){
return $this->get('delDept', $token, ['id' => intval($id)]);
}
/**
* 获取部门
* @param $token 凭证
* @param $id 部门ID
*/
public function getDepartmentList($token, $id=''){
return $this->get('listDept', $token, ['id' => $id]);
}
/**
* 添加成员
* @param $token 调用接口凭证
* @param $userid 企业邮帐号名,邮箱格式
* @param $name 成员名称
* @param $department 成员所属部门ID
* @param $password 登录密码
* @param string $position 职位信息
* @param string $mobile 手机号码
* @param string $tel 座机号码
* @param string $extid 编号
* @param string $gender 性别。1表示男性,2表示女性
* @param string $slaves 别名列表
* @param string $cpwd_login 用户重新登录时是否重设密码 0表示否,1表示是,缺省为0
*/
public function createUser($token, $userid, $name, $department, $password, $position='', $mobile='', $tel='', $extid='', $gender='', $slaves='', $cpwd_login=''){
$data = [
'userid' => $userid,
'name' => $name,
'department' => $department,
'password' => $password
];
$position!=='' ? $data['position'] = $position : '';
$mobile!=='' ? $data['mobile'] = $mobile : '';
$tel!=='' ? $data['tel'] = $tel : '';
$extid!=='' ? $data['extid'] = $extid : '';
$gender!=='' ? $data['gender'] = strval($gender) : '';
$slaves!=='' ? $data['slaves'] = $slaves : '';
$cpwd_login!=='' ? $data['cpwd_login'] = intval($cpwd_login) : '';
return $this->post('createUser', $token, $data);
}
/**
* 更新成员
* @param $token 调用接口凭证
* @param $userid 企业邮帐号名,邮箱格式
* @param $name 成员名称
* @param $department 成员所属部门ID
* @param $password 登录密码
* @param string $position 职位信息
* @param string $mobile 手机号码
* @param string $tel 座机号码
* @param string $extid 编号
* @param string $gender 性别。1表示男性,2表示女性
* @param string $slaves 别名列表
* @param string $cpwd_login 用户重新登录时是否重设密码 0表示否,1表示是,缺省为0
* @param string $enable 启用/禁用成员 1表示启用成员,0表示禁用成员
*/
public function updateUser($token, $userid, $name='', $department='', $password='', $position='', $mobile='', $tel='', $extid='', $gender='', $slaves='', $cpwd_login='', $enable=1){
$data = [
'userid' => $userid,
];
$name!=='' ? $data['name'] = $name : '';
$department!=='' ? $data['department'] = $department : '';
$password!=='' ? $data['password'] = $password : '';
$position!=='' ? $data['position'] = $position : '';
$mobile!=='' ? $data['mobile'] = $mobile : '';
$tel!=='' ? $data['tel'] = $tel : '';
$extid!=='' ? $data['extid'] = $extid : '';
$gender!=='' ? $data['gender'] = strval($gender) : '';
$slaves!=='' ? $data['slaves'] = $slaves : '';
$cpwd_login!=='' ? $data['cpwd_login'] = intval($cpwd_login) : '';
$enable!=='' ? $data['enable'] = intval($enable) : '';
return $this->post('updateUser', $token, $data);
}
/**
* 删除成员
* @param $token
* @param $userid
*/
public function delUser($token, $userid){
return $this->get('delUser', $token, [ 'userid' => $userid ]);
}
/**
* 获取成员
* @param $token
* @param $userid
*/
public function getUser($token, $userid){
return $this->get('getUser', $token, [ 'userid' => $userid ]);
}
/**
* 获取部门成员
* @param $token
* @param $departmentid
* @param int $fetchChild
*/
public function getSimpleListUser($token, $departmentid, $fetchChild=1){
return $this->get('simplelistUser', $token, [ 'department_id' => $departmentid, 'fetch_child' => $fetchChild ]);
}
/**
* 获取部门成员-详情
* @param $token
* @param $departmentid
* @param int $fetchChild
*/
public function getListUser($token, $departmentid, $fetchChild=1){
return $this->get('listUser', $token, [ 'department_id' => $departmentid, 'fetch_child' => $fetchChild ]);
}
/**
* 批量检查帐号
* @param $token
* @param $departmentid
* @param int $fetchChild
*/
public function batchCheck($token, $userlist=[]){
return $this->post('batchcheckUser', $token, ['userlist' => $userlist]);
}
/**
* 创建标签
* @param $token
* @param $departmentid
* @param int $fetchChild
*/
public function createTag($token, $tagname, $tagid=''){
$data = [
'tagname' => $tagname
];
$tagid !== '' ? $data['tagid'] = intval($tagid) : '';
return $this->post('createTag', $token, $data);
}
/**
* 更新标签名字
* @param $token
* @param $departmentid
* @param int $fetchChild
*/
public function updateTag($token, $tagname, $tagid=''){
$data = [
'tagname' => $tagname
];
$tagid !== '' ? $data['tagid'] = intval($tagid) : '';
return $this->post('updateTag', $token, $data);
}
/**
* 获取标签列表
* @param $token
* @return mixed
*/
public function listTag($token){
return $this->get('listTag', $token);
}
/**
* 删除标签
* @param $token
* @return mixed
*/
public function delTag($token, $tagid){
return $this->get('delTag', $token, [ 'tagid' => $tagid ]);
}
/**
* 获取标签成员
* @param $token
* @return mixed
*/
public function getTag($token, $tagid){
return $this->get('getTag', $token, [ 'tagid' => $tagid ]);
}
/**
* 增加标签成员
* @param $token
* @return mixed
*/
public function addTagUsers($token, $tagid, $userlist=[], $partylist){
$data = [
'tagid' => $tagid
];
if(!empty($userlist))
$data['userlist'] = $userlist;
if(!empty($partylist))
$data['partylist'] = $partylist;
return $this->post('addTagUsers', $token, $data);
}
/**
* 删除标签成员
* @param $token
* @return mixed
*/
public function delTagUsers($token, $tagid, $userlist=[], $partylist){
$data = [
'tagid' => $tagid
];
if(!empty($userlist))
$data['userlist'] = $userlist;
if(!empty($partylist))
$data['partylist'] = $partylist;
return $this->post('delTagUsers', $token, $data);
}
/**
* 创建邮件群组
* @param $token
* @param $groupid
* @param $groupname
* @param int $allow_type
* @param array $userlist
* @param array $grouplist
* @param array $department
* @param array $allow_userlist
* @return mixed
*/
public function createGroup($token, $groupid, $groupname, $allow_type=0, $userlist=[], $grouplist=[], $department=[], $allow_userlist=[]){
$data = [
'groupid' => $groupid,
'groupname' => $groupname,
'allow_type' => $allow_type,
'userlist' => $userlist,
'grouplist' => $grouplist,
'department' => $department,
'allow_userlist' => $allow_userlist
];
return $this->post('createGroup', $token, $data);
}
/**
* 更新邮件群组
* @param $token
* @param $groupid
* @param $groupname
* @param string $allow_type
* @param array $userlist
* @param array $grouplist
* @param array $department
* @param array $allow_userlist
* @return mixed
*/
public function updateGroup($token, $groupid, $groupname, $allow_type='', $userlist=[], $grouplist=[], $department=[], $allow_userlist=[]){
$data = [
'groupid' => $groupid,
'groupname' => $groupname,
];
$allow_type!== '' ? $data['allow_type'] = intval($allow_type) : '';
!empty($grouplist) ? $data['grouplist'] = $grouplist : '';
!empty($userlist) ? $data['userlist'] = $userlist : '';
!empty($department) ? $data['department'] = $department : '';
!empty($allow_userlist) ? $data['allow_userlist'] = $allow_userlist : '';
return $this->post('updateGroup', $token, $data);
}
/**
* 删除群组
* @param $token
* @param $groupid
* @return mixed
*/
public function delGroup($token, $groupid){
return $this->get('delGroup', $token, ['groupid' => $groupid]);
}
/**
* 获取邮件群组信息
* @param $token
* @param $groupid
* @return mixed
*/
public function getGroup($token, $groupid){
return $this->get('getGroup', $token, ['groupid' => $groupid]);
}
} | 30.51105 | 185 | 0.469443 |
11df1587bd0caa8d638a3a5193ee77a2bec47e30 | 9,873 | swift | Swift | Xcode Project/Pitch/Common/UartManager.swift | Geremia/pitch-ios-public | b87d373beeb3ce2eb9972a3fb3ca6291d7822deb | [
"MIT"
] | null | null | null | Xcode Project/Pitch/Common/UartManager.swift | Geremia/pitch-ios-public | b87d373beeb3ce2eb9972a3fb3ca6291d7822deb | [
"MIT"
] | null | null | null | Xcode Project/Pitch/Common/UartManager.swift | Geremia/pitch-ios-public | b87d373beeb3ce2eb9972a3fb3ca6291d7822deb | [
"MIT"
] | 1 | 2020-03-09T04:28:30.000Z | 2020-03-09T04:28:30.000Z | //
// UartManager.swift
// Bluefruit Connect
//
// Created by Antonio García on 06/02/16.
// Copyright © 2016 Adafruit. All rights reserved.
//
import Foundation
import CoreBluetooth
class UartManager: NSObject {
enum UartNotifications : String {
case DidSendData = "didSendData"
case DidReceiveData = "didReceiveData"
case DidBecomeReady = "didBecomeReady"
}
// Constants
static let UartServiceUUID = "6e400001-b5a3-f393-e0a9-e50e24dcca9e" // UART service UUID
static let RxCharacteristicUUID = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
static let TxCharacteristicUUID = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
static let TxMaxCharacters = 20
// Manager
static let shared = UartManager()
// Bluetooth Uart
var uartService: CBService?
var rxCharacteristic: CBCharacteristic?
var txCharacteristic: CBCharacteristic?
var txWriteType = CBCharacteristicWriteType.withResponse
var blePeripheral: BlePeripheral? {
didSet {
if blePeripheral?.peripheral.identifier != oldValue?.peripheral.identifier {
// Discover UART
resetService()
if let blePeripheral = blePeripheral {
print("Uart: discover services")
blePeripheral.peripheral.discoverServices([CBUUID(string: UartManager.UartServiceUUID)])
}
}
}
}
// Data
var dataBuffer = [UartDataChunk]()
var dataBufferEnabled = true
override init() {
super.init()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(didDisconnectFromPeripheral(_:)), name: NSNotification.Name(rawValue: BleManager.BleNotifications.DidDisconnectFromPeripheral.rawValue), object: nil)
}
deinit {
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self, name: NSNotification.Name(rawValue: BleManager.BleNotifications.DidDisconnectFromPeripheral.rawValue), object: nil)
}
func didDisconnectFromPeripheral(_ notification: NSNotification) {
clearData()
blePeripheral = nil
resetService()
}
func resetService() {
uartService = nil
rxCharacteristic = nil
txCharacteristic = nil
}
func sendDataWithCrc(data : Data) {
let len = data.count
var dataBytes = [UInt8](repeating: 0, count: len)
var crc: UInt8 = 0
data.copyBytes(to: &dataBytes, count: len)
for i in dataBytes { //add all bytes
crc = crc &+ i
}
crc = ~crc //invert
var dataWithChecksum = data
dataWithChecksum.append(&crc, count: 1)
sendData(dataWithChecksum)
}
func sendData(_ data: Data) {
let dataChunk = UartDataChunk(timestamp: CFAbsoluteTimeGetCurrent(), mode: .tx, data: data)
sendChunk(dataChunk)
}
func sendChunk(_ dataChunk: UartDataChunk) {
if let txCharacteristic = txCharacteristic, let blePeripheral = blePeripheral {
let data = dataChunk.data
if dataBufferEnabled {
blePeripheral.uartData.sentBytes += data.count
dataBuffer.append(dataChunk)
}
// Split data in txmaxcharacters bytes packets
var offset = 0
repeat {
let chunkSize = min(data.count-offset, UartManager.TxMaxCharacters)
let chunk = Data(bytesNoCopy: UnsafeMutableRawPointer(mutating: [UInt8](data))+offset, count: chunkSize, deallocator: .none)
blePeripheral.peripheral.writeValue(chunk, for: txCharacteristic, type: txWriteType)
offset+=chunkSize
} while(offset<data.count)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: UartNotifications.DidSendData.rawValue), object: nil, userInfo:["dataChunk" : dataChunk]);
}
else {
print("Error: sendChunk with uart not ready")
}
}
func receivedData(_ data: Data) {
let dataChunk = UartDataChunk(timestamp: CFAbsoluteTimeGetCurrent(), mode: .rx, data: data)
receivedChunk(dataChunk)
}
private func receivedChunk(_ dataChunk: UartDataChunk) {
print("received: \(dataChunk.data)")
if dataBufferEnabled {
blePeripheral?.uartData.receivedBytes += dataChunk.data.count
dataBuffer.append(dataChunk)
}
NotificationCenter.default.post(name: NSNotification.Name(rawValue: UartNotifications.DidReceiveData.rawValue), object: nil, userInfo:["dataChunk" : dataChunk]);
}
func isReady() -> Bool {
return txCharacteristic != nil && rxCharacteristic != nil// && rxCharacteristic!.isNotifying
}
func clearData() {
dataBuffer.removeAll()
blePeripheral?.uartData.receivedBytes = 0
blePeripheral?.uartData.sentBytes = 0
}
}
// MARK: - CBPeripheralDelegate
extension UartManager: CBPeripheralDelegate {
func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
print("UartManager: resetService because didModifyServices")
resetService()
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard blePeripheral != nil else {
return
}
if uartService == nil {
if let services = peripheral.services {
var found = false
var i = 0
while (!found && i < services.count) {
let service = services[i]
if (service.uuid.uuidString .caseInsensitiveCompare(UartManager.UartServiceUUID) == .orderedSame) {
found = true
uartService = service
peripheral.discoverCharacteristics([CBUUID(string: UartManager.RxCharacteristicUUID), CBUUID(string: UartManager.TxCharacteristicUUID)], for: service)
}
i += 1
}
}
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard blePeripheral != nil else {
return
}
//DLog("uart didDiscoverCharacteristicsForService")
if let uartService = uartService, rxCharacteristic == nil || txCharacteristic == nil {
if rxCharacteristic == nil || txCharacteristic == nil {
if let characteristics = uartService.characteristics {
var found = false
var i = 0
while !found && i < characteristics.count {
let characteristic = characteristics[i]
if characteristic.uuid.uuidString .caseInsensitiveCompare(UartManager.RxCharacteristicUUID) == .orderedSame {
rxCharacteristic = characteristic
}
else if characteristic.uuid.uuidString .caseInsensitiveCompare(UartManager.TxCharacteristicUUID) == .orderedSame {
txCharacteristic = characteristic
txWriteType = characteristic.properties.contains(.writeWithoutResponse) ? .withoutResponse:.withResponse
print("Uart: detected txWriteType: \(txWriteType.rawValue)")
}
found = rxCharacteristic != nil && txCharacteristic != nil
i += 1
}
}
}
// Check if characteristics are ready
if (rxCharacteristic != nil && txCharacteristic != nil) {
// Set rx enabled
peripheral.setNotifyValue(true, for: rxCharacteristic!)
// Send notification that uart is ready
NotificationCenter.default.post(name: NSNotification.Name(rawValue: UartNotifications.DidBecomeReady.rawValue), object: nil, userInfo:nil)
print("Uart: did become ready")
}
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
guard blePeripheral != nil else {
return
}
print("didUpdateNotificationStateForCharacteristic")
/*
if characteristic == rxCharacteristic {
if error != nil {
DLog("Uart RX isNotifying error: \(error)")
}
else {
if characteristic.isNotifying {
DLog("Uart RX isNotifying: true")
// Send notification that uart is ready
NSNotificationCenter.defaultCenter().postNotificationName(UartNotifications.DidBecomeReady.rawValue, object: nil, userInfo:nil)
}
else {
DLog("Uart RX isNotifying: false")
}
}
}
*/
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard blePeripheral != nil else {
return
}
if characteristic == rxCharacteristic && characteristic.service == uartService {
if let characteristicDataValue = characteristic.value {
receivedData(characteristicDataValue)
}
}
}
}
| 36.702602 | 214 | 0.586954 |
5f9ba436e41365c6930d3cef99a71e2eec8a3d7a | 143 | css | CSS | fastfed-idp-app/client/src/app/fastfed/consent/consent.component.css | hoggmania/fastfed-sdk | ddc870cec804da064f64b9d39b9bd4c313d1ea09 | [
"MIT"
] | 11 | 2020-04-03T22:48:57.000Z | 2021-08-18T22:25:19.000Z | fastfed-application-provider/client/src/app/fastfed/discovery/discovery.component.css | sailpoint-oss/fastfed-sdk | f800451343581d7afa8dfda56ae225ecfc949a81 | [
"MIT"
] | 289 | 2021-03-10T13:29:27.000Z | 2022-03-29T16:12:18.000Z | fastfed-idp-app/client/src/app/fastfed/consent/consent.component.css | hoggmania/fastfed-sdk | ddc870cec804da064f64b9d39b9bd4c313d1ea09 | [
"MIT"
] | 1 | 2020-12-21T10:53:17.000Z | 2020-12-21T10:53:17.000Z |
.mat-stroked-button {
background-color: lavender;
margin-right: 5px;
}
.button-container {
margin: 30px 0;
float: right;
}
| 11 | 31 | 0.622378 |
743c1b4859c95f2c142c17599d05c0fdd2583e1e | 607 | kt | Kotlin | app/src/main/java/com/ezzy/adanianpixabay/data/PixabayApi.kt | EzekielWachira/Adalabs-Pixabay | d9fe762a6a2cc293fbf234befd22d2df8f12335a | [
"MIT"
] | 2 | 2022-01-15T10:42:37.000Z | 2022-03-21T21:02:26.000Z | app/src/main/java/com/ezzy/adanianpixabay/data/PixabayApi.kt | EzekielWachira/Adalabs-Pixabay | d9fe762a6a2cc293fbf234befd22d2df8f12335a | [
"MIT"
] | null | null | null | app/src/main/java/com/ezzy/adanianpixabay/data/PixabayApi.kt | EzekielWachira/Adalabs-Pixabay | d9fe762a6a2cc293fbf234befd22d2df8f12335a | [
"MIT"
] | null | null | null | package com.ezzy.adanianpixabay.data
import com.ezzy.adanianpixabay.data.remote.dto.ImageDto
import com.ezzy.adanianpixabay.util.Constants
import retrofit2.http.GET
import retrofit2.http.Query
interface PixabayApi {
@GET("/api/")
suspend fun getImages(
@Query("key") key: String = Constants.API_KEY,
@Query("image_type") imageType: String = "photo"
): ImageDto
@GET("/api/")
suspend fun searchImage(
@Query("key") key: String = Constants.API_KEY,
@Query("q") keyword: String,
@Query("image_type") imageType: String = "photo"
): ImageDto
} | 26.391304 | 56 | 0.672158 |
e8d1e7da478606fd81e73b7674d5b2079cb7d7aa | 476 | dart | Dart | mobile-app/memeory/lib/store/actions/actions.dart | sokomishalov/memeory | 2372aff4bcefecad273b56e52e5d501b4ec5c839 | [
"MIT"
] | 2 | 2019-10-01T12:15:16.000Z | 2019-10-23T12:52:03.000Z | mobile-app/memeory/lib/store/actions/actions.dart | SokoMishaLov/memeory | 2372aff4bcefecad273b56e52e5d501b4ec5c839 | [
"MIT"
] | 137 | 2019-11-08T02:25:11.000Z | 2020-09-29T17:07:37.000Z | mobile-app/memeory/lib/store/actions/actions.dart | SokoMishaLov/memeory | 2372aff4bcefecad273b56e52e5d501b4ec5c839 | [
"MIT"
] | null | null | null | import 'package:memeory/model/channel.dart';
import 'package:memeory/model/topic.dart';
class ProvidersFetchAction {}
class ProvidersReceivedAction {
List<String> providers;
ProvidersReceivedAction(this.providers);
}
class TopicsFetchAction {}
class TopicsReceivedAction {
List<Topic> topics;
TopicsReceivedAction(this.topics);
}
class ChannelsFetchAction {}
class ChannelsReceivedAction {
List<Channel> channels;
ChannelsReceivedAction(this.channels);
}
| 17.62963 | 44 | 0.785714 |
ef68224014e1c26b5aac8762350b6a457c7c4938 | 120 | ps1 | PowerShell | PnP-PowerShell-Azure-Functions/Save-PnP-PowerShell-Module.ps1 | PiaSys/Conferences-Samples | 6ebf8e682e7213cbae61832e80b32f69d521977b | [
"MIT"
] | 18 | 2019-12-02T08:03:16.000Z | 2022-03-04T18:21:08.000Z | PnP-PowerShell-Azure-Functions/Save-PnP-PowerShell-Module.ps1 | PiaSys/Conferences-Samples | 6ebf8e682e7213cbae61832e80b32f69d521977b | [
"MIT"
] | 4 | 2020-08-19T14:32:26.000Z | 2022-02-28T02:36:31.000Z | PnP-PowerShell-Azure-Functions/Save-PnP-PowerShell-Module.ps1 | PiaSys/Conferences-Samples | 6ebf8e682e7213cbae61832e80b32f69d521977b | [
"MIT"
] | 16 | 2020-11-19T12:25:39.000Z | 2022-03-19T12:20:58.000Z | Save-Module -Name SharePointPnPPowerShellOnline -Path C:\temp\PnP-Community-Call-20200305 -RequiredVersion 3.17.2001.2
| 60 | 119 | 0.825 |
81d1d11f2cbe5ec3c56dab568aba2762b77c45f5 | 1,039 | go | Go | local_repository_test.go | yuya-takeyama/ghq | b0059c6806d171cf2c83398484aeb2a9da12d803 | [
"MIT"
] | 1 | 2015-11-08T13:55:56.000Z | 2015-11-08T13:55:56.000Z | local_repository_test.go | yuya-takeyama/ghq | b0059c6806d171cf2c83398484aeb2a9da12d803 | [
"MIT"
] | null | null | null | local_repository_test.go | yuya-takeyama/ghq | b0059c6806d171cf2c83398484aeb2a9da12d803 | [
"MIT"
] | null | null | null | package main
import . "github.com/onsi/gomega"
import "net/url"
import "testing"
func TestNewLocalRepository(t *testing.T) {
RegisterTestingT(t)
_localRepositoryRoots = []string{"/repos"}
r, err := LocalRepositoryFromFullPath("/repos/github.com/motemen/ghq")
Expect(err).To(BeNil())
Expect(r.NonHostPath()).To(Equal("motemen/ghq"))
Expect(r.Subpaths()).To(Equal([]string{"ghq", "motemen/ghq", "github.com/motemen/ghq"}))
r, err = LocalRepositoryFromFullPath("/repos/stash.com/scm/motemen/ghq")
Expect(err).To(BeNil())
Expect(r.NonHostPath()).To(Equal("scm/motemen/ghq"))
Expect(r.Subpaths()).To(Equal([]string{"ghq", "motemen/ghq", "scm/motemen/ghq", "stash.com/scm/motemen/ghq"}))
githubURL, _ := url.Parse("ssh://git@github.com/motemen/ghq.git")
r = LocalRepositoryFromURL(githubURL)
Expect(r.FullPath).To(Equal("/repos/github.com/motemen/ghq"))
stashURL, _ := url.Parse("ssh://git@stash.com/scm/motemen/ghq")
r = LocalRepositoryFromURL(stashURL)
Expect(r.FullPath).To(Equal("/repos/stash.com/scm/motemen/ghq"))
}
| 34.633333 | 111 | 0.716073 |
46cd07e854b52cb13ed10729bd9ccd3c69b3e9cf | 448 | css | CSS | src/app/editor-picks/editor-picks.component.css | gpuett/site-rebuild | 2de3663f9f3da1e074bdbfb36513c4d28b8fecd6 | [
"MIT"
] | null | null | null | src/app/editor-picks/editor-picks.component.css | gpuett/site-rebuild | 2de3663f9f3da1e074bdbfb36513c4d28b8fecd6 | [
"MIT"
] | null | null | null | src/app/editor-picks/editor-picks.component.css | gpuett/site-rebuild | 2de3663f9f3da1e074bdbfb36513c4d28b8fecd6 | [
"MIT"
] | null | null | null | .col{
border-top: 1px solid grey;
}
.picks {
border-bottom: 1px solid gold;
max-width: 250px;
min-height:350px;
}
a{
color: black;
}
a:hover {
color: gold;
text-decoration: none;
}
.descrip:hover {
color: black;
}
.rating {
max-width: 50px;
max-height: 50px;
position: absolute;
top: 33px;
right: 35px;
}
.score {
position: absolute;
top: 39px;
right: 45px;
font-size: 25px;
font-weight: bold;
color: white;
}
| 13.176471 | 32 | 0.629464 |
5f1aec7ad6cf92bd8e0b4f0e47cce9fd53b41a9d | 820 | ts | TypeScript | src/navigator/navigatorOptions.ts | acevedo93/wolox-react-native-technical-interview | d30762a392a232fa540423166b40fbf613ed0139 | [
"MIT"
] | null | null | null | src/navigator/navigatorOptions.ts | acevedo93/wolox-react-native-technical-interview | d30762a392a232fa540423166b40fbf613ed0139 | [
"MIT"
] | null | null | null | src/navigator/navigatorOptions.ts | acevedo93/wolox-react-native-technical-interview | d30762a392a232fa540423166b40fbf613ed0139 | [
"MIT"
] | null | null | null | import {FONT_FAMILY} from '../styles/GlobalStyles';
import {colors} from '../styles/colors';
import {Platform} from 'react-native';
export const screenOptions = {
headerStyle: {
elevation: 0,
shadowColor: 'transparent',
backgroundColor: colors.tertiary,
},
headerBackTitle: ' ',
headerTintColor: colors.lightTint,
headerTitleStyle: {
fontFamily: FONT_FAMILY,
},
headerTitleAlign: 'center',
cardStyle: {
backgroundColor: 'white',
},
};
export const tabBarOptions = {
activeTintColor: colors.primaryTint,
labelStyle: {
marginBottom: Platform.OS === 'ios' ? 0 : 10,
fontFamily: FONT_FAMILY,
},
style: {
borderWidth: 0,
elevation: 0,
height: Platform.OS === 'ios' ? 80 : 60,
position: 'absolute',
backgroundColor: 'rgba(255,255,255,0.92)',
},
};
| 22.777778 | 51 | 0.654878 |
4adcad6d22e1b39322e967be939d8ecda39904a1 | 282 | cs | C# | RuriLib/Models/Blocks/Settings/Interpolated/InterpolatedDictionaryOfStringsSetting.cs | aa1961aa/OpenBullet2 | 876b18931b95d4c0baee6e52f8f7781221c50125 | [
"MIT"
] | 565 | 2021-03-08T20:32:59.000Z | 2022-03-30T18:21:12.000Z | RuriLib/Models/Blocks/Settings/Interpolated/InterpolatedDictionaryOfStringsSetting.cs | aa1961aa/OpenBullet2 | 876b18931b95d4c0baee6e52f8f7781221c50125 | [
"MIT"
] | 637 | 2021-03-08T21:29:58.000Z | 2022-03-31T16:59:04.000Z | RuriLib/Models/Blocks/Settings/Interpolated/InterpolatedDictionaryOfStringsSetting.cs | aa1961aa/OpenBullet2 | 876b18931b95d4c0baee6e52f8f7781221c50125 | [
"MIT"
] | 268 | 2021-03-08T20:31:59.000Z | 2022-03-31T08:16:19.000Z | using System.Collections.Generic;
namespace RuriLib.Models.Blocks.Settings.Interpolated
{
public class InterpolatedDictionaryOfStringsSetting : InterpolatedSetting
{
public Dictionary<string, string> Value { get; set; } = new Dictionary<string, string>();
}
}
| 28.2 | 97 | 0.741135 |
54439dbb122461aa31c4cbb64abf513c4737ad2e | 1,446 | go | Go | vendor/github.com/chromedp/cdproto/testing/testing.go | pressly/screenshot | 2cf9753a98733e27923e5f63c104faebd608bdd7 | [
"MIT"
] | 44 | 2017-12-05T22:36:13.000Z | 2020-07-05T07:16:09.000Z | vendor/github.com/chromedp/cdproto/testing/testing.go | vitraum/svg2png | 117c5e3b7d21016f5da53405d78b78fc1a5814d1 | [
"MIT"
] | 13 | 2017-12-11T17:28:16.000Z | 2018-11-08T20:30:25.000Z | vendor/github.com/chromedp/cdproto/testing/testing.go | pressly/screenshot | 2cf9753a98733e27923e5f63c104faebd608bdd7 | [
"MIT"
] | 12 | 2017-12-14T17:39:00.000Z | 2020-01-23T19:44:32.000Z | // Package testing provides the Chrome DevTools Protocol
// commands, types, and events for the Testing domain.
//
// Testing domain is a dumping ground for the capabilities requires for
// browser or app testing that do not fit other domains.
//
// Generated by the cdproto-gen command.
package testing
// Code generated by cdproto-gen. DO NOT EDIT.
import (
"context"
"github.com/chromedp/cdproto/cdp"
)
// GenerateTestReportParams generates a report for testing.
type GenerateTestReportParams struct {
Message string `json:"message"` // Message to be displayed in the report.
Group string `json:"group,omitempty"` // Specifies the endpoint group to deliver the report to.
}
// GenerateTestReport generates a report for testing.
//
// parameters:
// message - Message to be displayed in the report.
func GenerateTestReport(message string) *GenerateTestReportParams {
return &GenerateTestReportParams{
Message: message,
}
}
// WithGroup specifies the endpoint group to deliver the report to.
func (p GenerateTestReportParams) WithGroup(group string) *GenerateTestReportParams {
p.Group = group
return &p
}
// Do executes Testing.generateTestReport against the provided context.
func (p *GenerateTestReportParams) Do(ctxt context.Context, h cdp.Executor) (err error) {
return h.Execute(ctxt, CommandGenerateTestReport, p, nil)
}
// Command names.
const (
CommandGenerateTestReport = "Testing.generateTestReport"
)
| 29.510204 | 98 | 0.763485 |
66dcd86bd7913563099a3e554119f61b9c1f94d7 | 21,671 | cpp | C++ | gemcutter/Application/Application.cpp | EmilianC/Jewel3D | ce11aa686ab35d4989f018c948b26abed6637d77 | [
"MIT"
] | 30 | 2017-02-02T01:57:13.000Z | 2020-07-04T04:38:20.000Z | gemcutter/Application/Application.cpp | EmilianC/Jewel3D | ce11aa686ab35d4989f018c948b26abed6637d77 | [
"MIT"
] | null | null | null | gemcutter/Application/Application.cpp | EmilianC/Jewel3D | ce11aa686ab35d4989f018c948b26abed6637d77 | [
"MIT"
] | 10 | 2017-07-10T01:31:54.000Z | 2020-01-13T20:38:57.000Z | // Copyright (c) 2017 Emilian Cioca
#include "Application.h"
#include "gemcutter/Application/Logging.h"
#include "gemcutter/Application/Timer.h"
#include "gemcutter/Input/Input.h"
#include "gemcutter/Rendering/Light.h"
#include "gemcutter/Rendering/ParticleEmitter.h"
#include "gemcutter/Rendering/Rendering.h"
#include "gemcutter/Resource/Font.h"
#include "gemcutter/Resource/Model.h"
#include "gemcutter/Resource/ParticleBuffer.h"
#include "gemcutter/Resource/Shader.h"
#include "gemcutter/Resource/Texture.h"
#include "gemcutter/Resource/VertexArray.h"
#include "gemcutter/Sound/SoundSystem.h"
#include <glew/glew.h>
#include <glew/wglew.h>
// This is the HINSTANCE of the application.
extern "C" IMAGE_DOS_HEADER __ImageBase;
#define BITS_PER_PIXEL 32
#define DEPTH_BUFFER_BITS 24
#define STENCIL_BUFFER_BITS 8
#define STYLE_BORDERED (WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_VISIBLE)
#define STYLE_BORDERED_FIXED (WS_CAPTION | WS_SYSMENU | WS_POPUP | WS_MINIMIZEBOX | WS_VISIBLE)
#define STYLE_BORDERLESS (WS_POPUP | WS_VISIBLE)
#define STYLE_EXTENDED (WS_EX_APPWINDOW)
namespace
{
LONG GetStyle(bool fullScreen, bool bordered, bool resizable)
{
if (bordered && !fullScreen)
{
return resizable ? STYLE_BORDERED : STYLE_BORDERED_FIXED;
}
return STYLE_BORDERLESS;
}
RECT GetWindowSize(LONG style, unsigned clientWidth, unsigned clientHeight)
{
RECT windowRect;
windowRect.left = 0;
windowRect.right = clientWidth;
windowRect.top = 0;
windowRect.bottom = clientHeight;
if (!AdjustWindowRectEx(&windowRect, style, FALSE, STYLE_EXTENDED))
{
gem::Warning("Console: Could not resolve the window's size.");
}
return windowRect;
}
bool ApplyFullscreen(HWND window, bool state, unsigned clientWidth, unsigned clientHeight)
{
if (state)
{
DEVMODE dmScreenSettings = {};
dmScreenSettings.dmSize = sizeof(DEVMODE);
dmScreenSettings.dmPelsWidth = clientWidth;
dmScreenSettings.dmPelsHeight = clientHeight;
dmScreenSettings.dmBitsPerPel = BITS_PER_PIXEL;
dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL)
{
gem::Warning("Console: Could not enter fullscreen mode.");
return false;
}
if (SetWindowPos(window, 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW) == ERROR)
{
gem::Warning("Console: Could not enter fullscreen mode.");
return false;
}
}
else
{
if (ChangeDisplaySettings(NULL, 0) != DISP_CHANGE_SUCCESSFUL)
{
gem::Warning("Console: Could not successfully exit fullscreen mode.");
return false;
}
if (SetWindowPos(window, 0, 20, 20, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW) == ERROR)
{
gem::Warning("Console: Could not successfully exit fullscreen mode.");
return false;
}
}
return true;
}
bool ApplyStyle(HWND window, LONG style, unsigned clientWidth, unsigned clientHeight)
{
RECT windowRect = GetWindowSize(style, clientWidth, clientHeight);
if (SetWindowLongPtr(window, GWL_STYLE, style) == ERROR ||
SetWindowPos(window, 0, 0, 0, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, SWP_NOMOVE | SWP_NOZORDER | SWP_FRAMECHANGED | SWP_SHOWWINDOW) == ERROR)
{
gem::Warning("Console: Could not apply the window's border style.");
return false;
}
return true;
}
bool ApplyResolution(HWND window, LONG style, unsigned clientWidth, unsigned clientHeight)
{
RECT windowRect = GetWindowSize(style, clientWidth, clientHeight);
if (SetWindowPos(window, 0, 0, 0, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, SWP_NOMOVE | SWP_NOZORDER | SWP_SHOWWINDOW) == ERROR)
{
gem::Warning("Console: Could not apply the resolution.");
return false;
}
return true;
}
#ifdef _DEBUG
void CALLBACK OpenGLDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* msg, const void* /* unused */)
{
// Ignored messages.
if (
// Usage warning : Generic vertex attribute array # uses a pointer with a small value (#). Is this intended to be used as an offset into a buffer object?
id == 0x00020004 ||
// Buffer info : Total VBO memory usage in the system : #
id == 0x00020070 ||
// Program / shader state info : GLSL shader # failed to compile.
id == 0x00020090)
{
return;
}
char buffer[9] = { '\0' };
snprintf(buffer, 9, "%.8x", id);
std::string message;
message.reserve(128);
message += "OpenGL(0x";
message += buffer;
message += "): ";
switch (type)
{
case GL_DEBUG_TYPE_ERROR:
message += "Error\n";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
message += "Deprecated behaviour\n";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
message += "Undefined behaviour\n";
break;
case GL_DEBUG_TYPE_PORTABILITY:
message += "Portability issue\n";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
message += "Performance issue\n";
break;
case GL_DEBUG_TYPE_MARKER:
message += "Stream annotation\n";
break;
case GL_DEBUG_TYPE_OTHER_ARB:
message += "Other\n";
break;
}
message += "Source: ";
switch (source)
{
case GL_DEBUG_SOURCE_API:
message += "API\n";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
message += "Window system\n";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER:
message += "Shader compiler\n";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY:
message += "Third party\n";
break;
case GL_DEBUG_SOURCE_APPLICATION:
message += "Application\n";
break;
case GL_DEBUG_SOURCE_OTHER:
message += "Other\n";
break;
}
message += "Severity: ";
switch (severity)
{
case GL_DEBUG_SEVERITY_HIGH:
message += "HIGH\n";
break;
case GL_DEBUG_SEVERITY_MEDIUM:
message += "Medium\n";
break;
case GL_DEBUG_SEVERITY_LOW:
message += "Low\n";
break;
case GL_DEBUG_SEVERITY_NOTIFICATION:
message += "Notification\n";
break;
}
message.append(msg, length);
if (message.back() != '\n')
{
message.push_back('\n');
}
if (type == GL_DEBUG_TYPE_ERROR)
{
gem::Error(message);
}
else
{
gem::Log(message);
}
}
#endif
}
namespace gem
{
ApplicationSingleton Application;
void ApplicationSingleton::DrainEventQueue()
{
// Windows message loop.
MSG msg;
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
// Filter input events from other system/windows events and send them to the Input class.
if ((msg.message >= WM_KEYFIRST && msg.message <= WM_KEYLAST) || (msg.message >= WM_MOUSEFIRST && msg.message <= WM_MOUSELAST))
{
// Send WM_CHAR message for capturing character input.
TranslateMessage(&msg);
if (!Input.Update(msg))
{
// If the msg was not handled by the input class, we forward it to the default WndProc.
DefWindowProc(msg.hwnd, msg.message, msg.wParam, msg.lParam);
}
}
else
{
// This message is not input based, send it to our main WndProc.
DispatchMessage(&msg);
}
}
}
bool ApplicationSingleton::CreateGameWindow(std::string_view title, unsigned _glMajorVersion, unsigned _glMinorVersion)
{
ASSERT(hwnd == NULL, "A game window is already open.");
ASSERT(_glMajorVersion > 3 || (_glMajorVersion == 3 && _glMinorVersion == 3), "OpenGL version must be 3.3 or greater.");
apInstance = reinterpret_cast<HINSTANCE>(&__ImageBase);
glMajorVersion = _glMajorVersion;
glMinorVersion = _glMinorVersion;
WNDCLASSEX windowClass;
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = ApplicationSingleton::WndProc;
windowClass.cbClsExtra = 0;
windowClass.cbWndExtra = 0;
windowClass.hInstance = apInstance;
windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // Default icon.
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); // Default arrow.
windowClass.hbrBackground = NULL;
windowClass.lpszMenuName = NULL;
windowClass.lpszClassName = "Gemcutter";
windowClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO); // Windows logo small icon.
if (!RegisterClassEx(&windowClass))
{
Error("Console: Failed to register window.");
return false;
}
LONG style = GetStyle(fullscreen, bordered, resizable);
RECT windowRect = GetWindowSize(style, screenViewport.width, screenViewport.height);
// This will internally send a WM_CREATE message that is handled before the function returns.
if (!CreateWindowEx(
STYLE_EXTENDED,
"Gemcutter", // Class name.
title.data(),
style,
CW_USEDEFAULT, CW_USEDEFAULT,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
NULL, // Handle to parent.
NULL, // Handle to menu.
apInstance,
NULL))
{
Error("Console: Failed to create window.");
return false;
}
SetFullscreen(fullscreen);
ShowWindow(hwnd, SW_SHOW);
SetForegroundWindow(hwnd);
// Ensure that the deltaTime between frames has been computed.
SetUpdatesPerSecond(updatesPerSecond);
return true;
}
void ApplicationSingleton::DestroyGameWindow()
{
ASSERT(hwnd != NULL, "A game window must be created before calling this function.");
// Delete all resources that require the OpenGL context.
UnloadAll<Font>();
UnloadAll<Shader>();
UnloadAll<Texture>();
UnloadAll<Model>();
UnloadAll<ParticleBuffer>();
if (IsFullscreen())
{
SetFullscreen(false);
}
EnableCursor();
#ifdef _DEBUG
// Some drivers will emit erroneous errors on shutdown, so we disable debug info first.
glDebugMessageCallback(NULL, NULL);
#endif
// Release Device and Render Contexts.
wglMakeCurrent(NULL, NULL);
wglDeleteContext(renderContext);
ReleaseDC(hwnd, deviceContext);
DestroyWindow(hwnd);
UnregisterClass("Gemcutter", apInstance);
renderContext = NULL;
deviceContext = NULL;
hwnd = NULL;
}
void ApplicationSingleton::GameLoop(const std::function<void()>& update, const std::function<void()>& draw)
{
ASSERT(update, "An update function must be provided.");
ASSERT(draw, "A draw function must be provided.");
if (hwnd == NULL)
{
Error("Application: Must be initialized and have a window created before a call to GameLoop().");
return;
}
// Timing control variables.
constexpr unsigned MAX_CONCURRENT_UPDATES = 5;
unsigned fpsCounter = 0;
__int64 lastUpdate = Timer::GetCurrentTick();
__int64 lastRender = lastUpdate;
__int64 lastFpsCapture = lastRender;
while (true)
{
// Updates our input and Windows OS events.
DrainEventQueue();
if (!appIsRunning) [[unlikely]]
return;
// Record the FPS for the previous second of time.
__int64 currentTime = Timer::GetCurrentTick();
if (currentTime - lastFpsCapture >= Timer::GetTicksPerSecond())
{
// We don't want to update the timer variable with "+= 1.0" here. After a lag spike this
// would cause FPS to suddenly be recorded more often than once a second.
lastFpsCapture = currentTime;
fps = fpsCounter;
fpsCounter = 0;
}
// Update to keep up with real time.
unsigned updateCount = 0;
while (currentTime - lastUpdate >= updateStep)
{
update();
// The user might have requested to exit during update().
if (!appIsRunning) [[unlikely]]
return;
lastUpdate += updateStep;
updateCount++;
if (skipToPresent) [[unlikely]]
{
lastUpdate = currentTime;
skipToPresent = false;
break;
}
// Avoid spiral of death. This also allows us to keep rendering even in a worst-case scenario.
if (updateCount >= MAX_CONCURRENT_UPDATES)
break;
}
if (updateCount > 0)
{
// If the frame rate is uncapped or we are due for a new frame, render the latest game-state.
if (FPSCap == 0 || (currentTime - lastRender) >= renderStep)
{
draw();
SwapBuffers(deviceContext);
lastRender += renderStep;
fpsCounter++;
}
}
}
}
void ApplicationSingleton::UpdateEngine()
{
// Distribute all queued events to their listeners.
EventQueue.Dispatch();
// Update engine components.
for (Entity& entity : With<ParticleUpdaterTag>())
{
entity.Get<ParticleEmitter>().Update();
}
for (auto& light : All<Light>())
{
light.Update();
}
// Step the SoundSystem.
SoundSystem.Update();
}
void ApplicationSingleton::Exit()
{
appIsRunning = false;
}
void ApplicationSingleton::EnableCursor()
{
while (ShowCursor(true) <= 0);
}
void ApplicationSingleton::DisableCursor()
{
while (ShowCursor(false) > 0);
}
bool ApplicationSingleton::IsFullscreen() const
{
return fullscreen;
}
bool ApplicationSingleton::IsBordered() const
{
return bordered;
}
bool ApplicationSingleton::IsResizable() const
{
return resizable;
}
std::string ApplicationSingleton::GetOpenGLVersionString() const
{
ASSERT(hwnd != NULL, "A game window must be created before calling this function.");
return reinterpret_cast<const char*>(glGetString(GL_VERSION));
}
int ApplicationSingleton::GetScreenWidth() const
{
return screenViewport.width;
}
int ApplicationSingleton::GetScreenHeight() const
{
return screenViewport.height;
}
float ApplicationSingleton::GetAspectRatio() const
{
return screenViewport.GetAspectRatio();
}
float ApplicationSingleton::GetDeltaTime() const
{
return 1.0f / updatesPerSecond;
}
unsigned ApplicationSingleton::GetFPS() const
{
return fps;
}
void ApplicationSingleton::SetFPSCap(unsigned _fps)
{
if (_fps == 0)
{
renderStep = 0;
}
else
{
renderStep = Timer::GetTicksPerSecond() / _fps;
}
FPSCap = _fps;
if (FPSCap > updatesPerSecond)
{
Warning("FPSCap is higher than the Update rate. Frames cannot be rendered more often than there are updates.");
}
}
unsigned ApplicationSingleton::GetFPSCap() const
{
return FPSCap;
}
void ApplicationSingleton::SetUpdatesPerSecond(unsigned ups)
{
ASSERT(ups > 0, "Invalid update rate.");
updateStep = Timer::GetTicksPerSecond() / ups;
updatesPerSecond = ups;
}
unsigned ApplicationSingleton::GetUpdatesPerSecond() const
{
return updatesPerSecond;
}
void ApplicationSingleton::SkipToPresentTime()
{
skipToPresent = true;
}
const Viewport& ApplicationSingleton::GetScreenViewport() const
{
return screenViewport;
}
bool ApplicationSingleton::SetFullscreen(bool state)
{
if (hwnd != NULL)
{
if (state == fullscreen)
{
return true;
}
LONG style;
if (state)
{
style = GetStyle(true, false, false);
}
else
{
style = GetStyle(false, IsBordered(), IsResizable());
}
if (!ApplyStyle(hwnd, style, GetScreenWidth(), GetScreenHeight()))
{
return false;
}
if (!ApplyFullscreen(hwnd, state, GetScreenWidth(), GetScreenHeight()))
{
return false;
}
}
fullscreen = state;
return true;
}
bool ApplicationSingleton::SetBordered(bool state)
{
if (hwnd != NULL)
{
if (state == bordered)
{
return true;
}
if (IsFullscreen())
{
// State will be applied next time we exit fullscreen mode.
bordered = state;
return true;
}
LONG style = GetStyle(false, state, IsResizable());
if (!ApplyStyle(hwnd, style, GetScreenWidth(), GetScreenHeight()))
{
return false;
}
}
bordered = state;
return true;
}
bool ApplicationSingleton::SetResizable(bool state)
{
if (hwnd != NULL)
{
if (state == resizable)
{
return true;
}
if (IsFullscreen() || !IsBordered())
{
// State will be applied next time we exit fullscreen mode and have a border.
resizable = state;
return true;
}
LONG style = GetStyle(false, true, state);
if (!ApplyStyle(hwnd, style, GetScreenWidth(), GetScreenHeight()))
{
return false;
}
}
resizable = state;
return true;
}
bool ApplicationSingleton::SetResolution(unsigned width, unsigned height)
{
ASSERT(width > 0, "'width' must be greater than 0.");
ASSERT(height > 0, "'height' must be greater than 0.");
bool wasFullscreen = fullscreen;
if (hwnd != NULL)
{
if (width == screenViewport.width && height == screenViewport.height)
{
return true;
}
if (wasFullscreen && !SetFullscreen(false))
{
return false;
}
LONG style = GetStyle(fullscreen, IsBordered(), IsResizable());
if (!ApplyResolution(hwnd, style, width, height))
{
return false;
}
}
screenViewport.width = width;
screenViewport.height = height;
if (hwnd != NULL)
{
if (wasFullscreen && !SetFullscreen(true))
{
return false;
}
}
return true;
}
ApplicationSingleton::ApplicationSingleton()
: glMajorVersion(3)
, glMinorVersion(3)
, screenViewport(0, 0, 800, 600)
, hwnd(NULL)
, apInstance(NULL)
, renderContext(NULL)
, deviceContext(NULL)
{
}
ApplicationSingleton::~ApplicationSingleton()
{
if (hwnd != NULL)
{
DestroyGameWindow();
}
}
LRESULT CALLBACK ApplicationSingleton::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_SIZE:
{
// Adjust screen data.
const unsigned width = LOWORD(lParam);
const unsigned height = HIWORD(lParam);
if (width > 0 && height > 0)
{
Application.screenViewport.width = width;
Application.screenViewport.height = height;
Application.screenViewport.bind();
EventQueue.Push(std::make_unique<Resize>(Application.screenViewport.width, Application.screenViewport.height));
}
return 0;
}
case WM_CREATE:
{
Application.hwnd = hWnd;
Application.deviceContext = GetDC(hWnd);
if (Application.deviceContext == 0)
{
Error("Console: DeviceContext could not be created.");
return -1;
}
/* Initialize OpenGL */
PIXELFORMATDESCRIPTOR pfd = {};
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = BITS_PER_PIXEL;
pfd.cDepthBits = DEPTH_BUFFER_BITS;
pfd.cStencilBits = STENCIL_BUFFER_BITS;
pfd.iLayerType = PFD_MAIN_PLANE;
int pixelFormat = ChoosePixelFormat(Application.deviceContext, &pfd);
SetPixelFormat(Application.deviceContext, pixelFormat, &pfd);
int attribs[] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, static_cast<int>(Application.glMajorVersion),
WGL_CONTEXT_MINOR_VERSION_ARB, static_cast<int>(Application.glMinorVersion),
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
#ifdef _DEBUG
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB,
#else
WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
#endif
0 };
// Create a temporary context so we can get a pointer to our newer context
HGLRC tmpContext = wglCreateContext(Application.deviceContext);
if (!wglMakeCurrent(Application.deviceContext, tmpContext))
{
Error("Console: Device-Context could not be made current.\nTry updating your graphics drivers.");
return -1;
}
// Get the function we can use to generate a modern context.
auto wglCreateContextAttribsARB = reinterpret_cast<PFNWGLCREATECONTEXTATTRIBSARBPROC>(wglGetProcAddress("wglCreateContextAttribsARB"));
if (wglCreateContextAttribsARB)
{
// Create modern OpenGL context using the new function and delete the old one.
Application.renderContext = wglCreateContextAttribsARB(Application.deviceContext, 0, attribs);
}
if (Application.renderContext == NULL)
{
Error("Console: Failed to create OpenGL rendering context.\nTry updating your graphics drivers.");
return -1;
}
// Switch to new context.
wglMakeCurrent(Application.deviceContext, NULL);
wglDeleteContext(tmpContext);
if (!wglMakeCurrent(Application.deviceContext, Application.renderContext))
{
Error("Console: Render-Context could not be made current.\nTry updating your graphics drivers.");
return -1;
}
glewExperimental = GL_TRUE;
auto glewResult = glewInit();
if (glewResult != GLEW_OK)
{
Error("Console: GLEW failed to initialize. ( %s )\nTry updating your graphics drivers.",
reinterpret_cast<const char*>(glewGetErrorString(glewResult)));
return -1;
}
// Initializing GLEW can sometimes emit an GL_INVALID_ENUM error, so we discard any errors here.
glGetError();
#ifdef _DEBUG
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(OpenGLDebugCallback, NULL);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE);
glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_LOW, 0, NULL, GL_FALSE);
#endif
// Setup OpenGL settings.
GPUInfo.ScanDevice();
SetCullFunc(CullFunc::Clockwise);
SetDepthFunc(DepthFunc::Normal);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glEnable(GL_PRIMITIVE_RESTART);
glPrimitiveRestartIndex(VertexBuffer::RESTART_INDEX);
if (GLEW_ARB_seamless_cube_map)
{
glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
}
}
return 0;
case WM_CLOSE:
case WM_DESTROY:
Application.Exit();
return 0;
case WM_SYSCOMMAND:
// Ignore screen savers and monitor power-saving modes.
if (wParam == SC_SCREENSAVE || wParam == SC_MONITORPOWER)
{
return 0;
}
break;
}
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
Resize::Resize(unsigned _width, unsigned _height)
: width(_width)
, height(_height)
{
}
float Resize::GetAspectRatio() const
{
return static_cast<float>(width) / static_cast<float>(height);
}
}
| 25.082176 | 177 | 0.700106 |
49d36f9b7ddcd5c6d428144e3c91e471f10b2fc1 | 829 | html | HTML | views/index.html | InSertCod3/Geo-Suggestions-Backend | f1d6a1a372644d148a13462d9c59147bca63b416 | [
"MIT"
] | null | null | null | views/index.html | InSertCod3/Geo-Suggestions-Backend | f1d6a1a372644d148a13462d9c59147bca63b416 | [
"MIT"
] | null | null | null | views/index.html | InSertCod3/Geo-Suggestions-Backend | f1d6a1a372644d148a13462d9c59147bca63b416 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<style>
body {
font-family: "Lucida Console";
}
p {
font-size: 80px;
font-weight: 40;
text-align: center;
}
.endpoint {
font-size: 40px;
font-weight: 20;
text-align: center;
}
</style>
</head>
<body>
<p>Hello, Geo Endpoints.</p>
<p class="endpoint"><a href="/suggestions?q=Brooks">::/suggestions?q=Brooks</a></p>
<p class="endpoint"><a href="/suggestions?q=Fort&result_limit=3">::/suggestions?q=Fort&result_limit=3</a></p>
</body>
</html> | 24.382353 | 113 | 0.537998 |
4aa902369a8e9f8102fb18a536cc492d2ee99e32 | 1,072 | cs | C# | Utilities/DataLoading/EdFi.LoadTools/SmokeTest/PropertyBuilders/IgnorePropertyBuilder.cs | jamessmckay/Ed-Fi-ODS | 64438e6191f17bb529dc360ba38f54f6c0cee6b8 | [
"Apache-2.0"
] | null | null | null | Utilities/DataLoading/EdFi.LoadTools/SmokeTest/PropertyBuilders/IgnorePropertyBuilder.cs | jamessmckay/Ed-Fi-ODS | 64438e6191f17bb529dc360ba38f54f6c0cee6b8 | [
"Apache-2.0"
] | null | null | null | Utilities/DataLoading/EdFi.LoadTools/SmokeTest/PropertyBuilders/IgnorePropertyBuilder.cs | jamessmckay/Ed-Fi-ODS | 64438e6191f17bb529dc360ba38f54f6c0cee6b8 | [
"Apache-2.0"
] | null | null | null | // SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace EdFi.LoadTools.SmokeTest.PropertyBuilders
{
/// <summary>
/// Don't populate a value for Ids, _eTags, links
/// </summary>
public class IgnorePropertyBuilder : BaseBuilder
{
private static readonly List<string> IgnoredPropertyNames = new List<string>
{
"id",
"_etag",
"link"
};
public IgnorePropertyBuilder(IPropertyInfoMetadataLookup metadataLookup)
: base(metadataLookup) { }
public override bool BuildProperty(object obj, PropertyInfo propertyInfo)
{
return IgnoredPropertyNames.Contains(propertyInfo.Name, StringComparer.OrdinalIgnoreCase);
}
}
}
| 31.529412 | 102 | 0.678172 |
85619bc563a6712586dd63e985aa3e7c2c1914d2 | 878 | asm | Assembly | libsrc/video/hd44780/lcd_init.asm | ahjelm/z88dk | c4de367f39a76b41f6390ceeab77737e148178fa | [
"ClArtistic"
] | 640 | 2017-01-14T23:33:45.000Z | 2022-03-30T11:28:42.000Z | libsrc/video/hd44780/lcd_init.asm | C-Chads/z88dk | a4141a8e51205c6414b4ae3263b633c4265778e6 | [
"ClArtistic"
] | 1,600 | 2017-01-15T16:12:02.000Z | 2022-03-31T12:11:12.000Z | libsrc/video/hd44780/lcd_init.asm | C-Chads/z88dk | a4141a8e51205c6414b4ae3263b633c4265778e6 | [
"ClArtistic"
] | 215 | 2017-01-17T10:43:03.000Z | 2022-03-23T17:25:02.000Z |
SECTION code_driver
PUBLIC lcd_init
PUBLIC _lcd_init
PUBLIC asm_lcd_init
EXTERN asm_lcd_write_control
EXTERN asm_lcd_write_data
INCLUDE "hd44780.def"
lcd_init:
_lcd_init:
asm_lcd_init:
ld a,0x38 ; 2 Line, 8-bit, 5x7 dots
call asm_lcd_write_control
ld a,0x38 ; 2 Line, 8-bit, 5x7 dots
call asm_lcd_write_control
ld a,0x38 ; 2 Line, 8-bit, 5x7 dots
call asm_lcd_write_control
ld a,0x38 ; 2 Line, 8-bit, 5x7 dots
call asm_lcd_write_control
ld a,LCD_CLEARDISPLAY
call asm_lcd_write_control
ld a,LCD_DISPLAYCONTROL | LCD_DISPLAYON
call asm_lcd_write_control
ld a,LCD_ENTRYMODESET | LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT
call asm_lcd_write_control
ret
| 25.085714 | 76 | 0.615034 |
b13c3982f3157ab5273e4be4477329f5b8ac27c3 | 661 | asm | Assembly | oeis/105/A105133.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/105/A105133.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/105/A105133.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A105133: Numbers n such that 8n + 5 is prime.
; Submitted by Jon Maiga
; 0,1,3,4,6,7,12,13,18,19,21,22,24,28,33,34,36,39,43,46,48,49,52,57,63,67,69,76,81,82,84,87,88,91,94,96,99,102,103,106,109,117,124,126,127,132,133,136,138,139,147,151,153,154,159,162,171,172,178,181,186,193,199,201,202,204,208,211,213,216,217,223,232,234,237,241,243,246,249,253,256,258,267,276,277,279,283,286,288,291,292,294,297,298,304,309,318,319,327,334
mov $1,4
mov $2,$0
pow $2,2
lpb $2
mov $3,$1
seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0.
sub $0,$3
add $1,8
mov $4,$0
max $4,0
cmp $4,$0
mul $2,$4
sub $2,1
lpe
mov $0,$1
div $0,8
| 31.47619 | 358 | 0.659607 |
db74b81f532b3fe4bd6a3a1b027030ee2ddb5b29 | 3,181 | dart | Dart | app/lib/widgets/ic_segmented_control.dart | stelynx/insanichess | 9a0d516715218080e0fb86b0a9889fbbe9dadab2 | [
"Apache-2.0"
] | 3 | 2022-01-04T09:02:16.000Z | 2022-02-07T17:28:20.000Z | app/lib/widgets/ic_segmented_control.dart | stelynx/insanichess | 9a0d516715218080e0fb86b0a9889fbbe9dadab2 | [
"Apache-2.0"
] | 77 | 2021-12-22T18:15:29.000Z | 2022-02-11T21:31:49.000Z | app/lib/widgets/ic_segmented_control.dart | stelynx/insanichess | 9a0d516715218080e0fb86b0a9889fbbe9dadab2 | [
"Apache-2.0"
] | null | null | null | import 'package:flutter/cupertino.dart';
import '../style/constants.dart';
const double _kHeight = 40;
class ICSegmentedControl<T> extends StatelessWidget {
final T? value;
final List<T> items;
final List<String> labels;
final ValueChanged<T> onChanged;
final double width;
final double lineHeight;
final int? maxItemsInRow;
const ICSegmentedControl({
Key? key,
required this.value,
required this.items,
required this.labels,
required this.onChanged,
required this.width,
this.lineHeight = _kHeight,
this.maxItemsInRow,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final List<Widget> children = <Widget>[];
if (maxItemsInRow == null) {
for (int i = 0; i < items.length; i++) {
children.add(_TaiSegmentedControlElement(
label: labels[i],
onTap: items[i] == value ? null : () => onChanged(items[i]),
width: width / items.length,
));
}
} else {
List<Widget> rowChildren = <Widget>[];
for (int i = 0; i < items.length; i++) {
rowChildren.add(_TaiSegmentedControlElement(
label: labels[i],
onTap: items[i] == value ? null : () => onChanged(items[i]),
width: width / maxItemsInRow!,
));
if (rowChildren.length == maxItemsInRow) {
children.add(Row(children: rowChildren));
rowChildren = <Widget>[];
}
}
if (rowChildren.isNotEmpty) {
children.add(Row(children: rowChildren));
}
}
return Container(
width: width + 2,
constraints: const BoxConstraints(minHeight: _kHeight),
decoration: BoxDecoration(
color: CupertinoTheme.of(context).scaffoldBackgroundColor,
borderRadius: kBorderRadius,
border: Border.all(
width: 1,
color: CupertinoTheme.of(context).primaryColor,
),
),
child: maxItemsInRow == null
? Row(children: children)
: Column(
mainAxisSize: MainAxisSize.min,
children: children,
),
);
}
}
class _TaiSegmentedControlElement extends StatelessWidget {
final String label;
final VoidCallback? onTap;
final double width;
const _TaiSegmentedControlElement({
Key? key,
required this.label,
required this.onTap,
required this.width,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Container(
width: width,
height: _kHeight,
decoration: BoxDecoration(
color: onTap == null
? CupertinoTheme.of(context).primaryColor
: CupertinoTheme.of(context).scaffoldBackgroundColor,
borderRadius: kBorderRadius,
),
child: Center(
child: Text(
label,
style: TextStyle(
color: onTap == null
? CupertinoTheme.of(context).scaffoldBackgroundColor
: CupertinoTheme.of(context).primaryColor,
),
),
),
),
);
}
}
| 27.188034 | 70 | 0.591952 |
1efa464f3fb1394afbe2c36aec641a5411a1c32d | 861 | sql | SQL | 2017-10-22-codeconf/example1-higgs-big/2-1-postgres-create-table.sql | pavlov99/presentations | c2b4402f8c12c0f08a338fdb9ecb45deb444afaf | [
"MIT"
] | 12 | 2017-10-19T05:43:21.000Z | 2021-03-24T17:04:02.000Z | 2017-10-22-codeconf/example1-higgs-big/2-1-postgres-create-table.sql | pavlov99/presentations | c2b4402f8c12c0f08a338fdb9ecb45deb444afaf | [
"MIT"
] | null | null | null | 2017-10-22-codeconf/example1-higgs-big/2-1-postgres-create-table.sql | pavlov99/presentations | c2b4402f8c12c0f08a338fdb9ecb45deb444afaf | [
"MIT"
] | null | null | null | -- Create higgs table
-- Get columns with the following script:
-- cat header.txt | tr '-' '_' | tr ',' '\n' | xargs -n1 -I {} echo {}' numeric,'
CREATE TABLE IF NOT EXISTS higgs (
id SERIAL,
signal numeric,
lepton_pT numeric,
lepton_eta numeric,
lepton_phi numeric,
missing_energy_magnitude numeric,
missing_energy_phi numeric,
jet_1_pt numeric,
jet_1_eta numeric,
jet_1_phi numeric,
jet_1_b_tag numeric,
jet_2_pt numeric,
jet_2_eta numeric,
jet_2_phi numeric,
jet_2_b_tag numeric,
jet_3_pt numeric,
jet_3_eta numeric,
jet_3_phi numeric,
jet_3_b_tag numeric,
jet_4_pt numeric,
jet_4_eta numeric,
jet_4_phi numeric,
jet_4_b_tag numeric,
m_jj numeric,
m_jjj numeric,
m_lv numeric,
m_jlv numeric,
m_bb numeric,
m_wbb numeric,
m_wwbb numeric
)
| 23.916667 | 81 | 0.674797 |
261a63654c9265c89622e0fae26bca72c352f63b | 533 | java | Java | springbootConsumerFeign/src/main/java/common/utils/CommUtils.java | zhaohaiting/springcloud | 592a3b99e3fb5a0f81cdde4e816926b9f5f5a428 | [
"Apache-2.0"
] | null | null | null | springbootConsumerFeign/src/main/java/common/utils/CommUtils.java | zhaohaiting/springcloud | 592a3b99e3fb5a0f81cdde4e816926b9f5f5a428 | [
"Apache-2.0"
] | 3 | 2020-06-22T08:43:53.000Z | 2020-06-22T08:43:55.000Z | springbootservice2/src/main/java/common/utils/CommUtils.java | zhaohaiting/springcloud | 592a3b99e3fb5a0f81cdde4e816926b9f5f5a428 | [
"Apache-2.0"
] | null | null | null | package common.utils;
import javax.servlet.http.HttpServletResponse;
public class CommUtils {
// JSON格式化
public static String printDataJason(HttpServletResponse response, Object item) {
try {
JsonUtils.renderString(response, item);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 随机生成6位随机验证码
*
*/
public static String createRandomVcode(int len) {
// 验证码
String vcode = "";
for (int i = 0; i < len; i++) {
vcode = vcode + (int) (Math.random() * 9);
}
return vcode;
}
} | 16.65625 | 81 | 0.649156 |
0dac4a2072e607053c4a6ff4d0356e0640896f72 | 318 | sql | SQL | migrations/sql/V2020.05.05.15.42__2_5_now_applicaiton.sql | bcgov/mds | 6c427a66a5edb4196222607291adef8fd6677038 | [
"Apache-2.0"
] | 25 | 2018-07-09T19:04:37.000Z | 2022-03-15T17:27:10.000Z | migrations/sql/V2020.05.05.15.42__2_5_now_applicaiton.sql | areyeslo/mds | e8c38e593e09b78e2a57009c0d003d6c4bfa32e6 | [
"Apache-2.0"
] | 983 | 2018-04-25T20:08:07.000Z | 2022-03-31T21:45:20.000Z | migrations/sql/V2020.05.05.15.42__2_5_now_applicaiton.sql | areyeslo/mds | e8c38e593e09b78e2a57009c0d003d6c4bfa32e6 | [
"Apache-2.0"
] | 58 | 2018-05-15T22:35:50.000Z | 2021-11-29T19:40:52.000Z | ---2--reassign now_application_identity parent to common permit record (one for each number)
UPDATE now_application_identity nai
set permit_id =
(select p2.permit_id
from permit p2
where p2.permit_no = p.permit_no
order by p2.permit_id
limit 1)
from permit p
where p.permit_id = nai.permit_id; | 28.909091 | 92 | 0.745283 |
b531b211041b5168503d5b640bb9518c4af89a01 | 2,379 | rs | Rust | src/builder.rs | olivernn/lunr.rs | 94c087f40ed93594407b6f49a886fb545130a362 | [
"MIT"
] | 4 | 2017-11-17T10:50:28.000Z | 2019-09-16T20:17:31.000Z | src/builder.rs | olivernn/lunr.rs | 94c087f40ed93594407b6f49a886fb545130a362 | [
"MIT"
] | 6 | 2017-10-04T17:31:51.000Z | 2017-10-15T18:02:15.000Z | src/builder.rs | olivernn/lunr.rs | 94c087f40ed93594407b6f49a886fb545130a362 | [
"MIT"
] | 2 | 2017-10-04T18:59:21.000Z | 2018-06-30T14:57:39.000Z | use document::Document;
use field_ref::FieldRef;
use inverted_index::{InvertedIndex, Posting};
use vector::Vector;
use token::{Term, Tokens};
use std::collections::{HashMap, HashSet};
pub fn create() -> Builder {
Builder::default()
}
#[derive(Default)]
pub struct Builder {
pub inverted_index: InvertedIndex,
pub field_vectors: HashMap<FieldRef, Vector>,
pub fields: HashSet<String>,
term_frequencies: HashMap<FieldRef, HashMap<Term, u32>>,
field_lengths: HashMap<FieldRef, usize>,
field_refs: Vec<FieldRef>,
}
impl Builder {
pub fn add<'a, T: Document<'a>>(&mut self, document: T) {
for field in document.fields() {
let field_ref = FieldRef::new(document.id(), field.name.to_owned());
let tokens: Tokens = field.text.into();
let field_length = tokens.len();
self.fields.insert(field.name);
*self.field_lengths.entry(field_ref.clone()).or_insert(0) += field_length;
for token in tokens {
*self.term_frequencies
.entry(field_ref.clone())
.or_insert_with(HashMap::new)
.entry(token.term.to_owned())
.or_insert(0) += 1;
self.inverted_index.add(field_ref.clone(), token);
}
self.field_refs.push(field_ref);
}
()
}
pub fn build(&mut self) {
for field_ref in &self.field_refs {
let mut vector: Vector = Default::default();
let term_frequencies =
self.term_frequencies.get(field_ref).expect("token frequencies missing");
for term in term_frequencies.keys() {
let tf = f64::from(*term_frequencies.get(term).expect("token frequency missing"));
let posting = self.inverted_index.posting(term).expect("posting missing");
let idf = self.idf(posting);
let score = tf * idf;
vector.insert(posting.index as u32, score);
}
self.field_vectors.insert(field_ref.clone(), vector);
}
}
fn idf(&self, posting: &Posting) -> f64 {
let total_fields = self.field_lengths.len();
let posting_fields = posting.len();
let x = (total_fields / (1 + posting_fields)) as f64;
(1.0f64 + x.abs()).ln()
}
}
| 30.5 | 98 | 0.577974 |
f534576d77c94cb13a1b0f3ca82517b3a421cfc7 | 3,107 | cpp | C++ | Jolt/TriangleGrouper/TriangleGrouperClosestCentroid.cpp | All8Up/JoltPhysics | 751d13891f5bd8850863ad236eaa3c340e90de9a | [
"MIT"
] | 1,311 | 2021-08-16T07:37:05.000Z | 2022-03-31T21:13:39.000Z | Jolt/TriangleGrouper/TriangleGrouperClosestCentroid.cpp | All8Up/JoltPhysics | 751d13891f5bd8850863ad236eaa3c340e90de9a | [
"MIT"
] | 102 | 2021-08-28T14:41:32.000Z | 2022-03-31T20:25:55.000Z | Jolt/TriangleGrouper/TriangleGrouperClosestCentroid.cpp | All8Up/JoltPhysics | 751d13891f5bd8850863ad236eaa3c340e90de9a | [
"MIT"
] | 65 | 2021-08-16T07:59:04.000Z | 2022-03-28T06:18:49.000Z | // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
// SPDX-License-Identifier: MIT
#include <Jolt.h>
#include <TriangleGrouper/TriangleGrouperClosestCentroid.h>
#include <Geometry/MortonCode.h>
namespace JPH {
void TriangleGrouperClosestCentroid::Group(const VertexList &inVertices, const IndexedTriangleList &inTriangles, int inGroupSize, vector<uint> &outGroupedTriangleIndices)
{
const uint triangle_count = (uint)inTriangles.size();
const uint num_batches = (triangle_count + inGroupSize - 1) / inGroupSize;
vector<Vec3> centroids;
centroids.resize(triangle_count);
outGroupedTriangleIndices.resize(triangle_count);
for (uint t = 0; t < triangle_count; ++t)
{
// Store centroid
centroids[t] = inTriangles[t].GetCentroid(inVertices);
// Initialize sort table
outGroupedTriangleIndices[t] = t;
}
vector<uint>::iterator triangles_end = outGroupedTriangleIndices.end();
// Sort per batch
for (uint b = 0; b < num_batches - 1; ++b)
{
// Get iterators
vector<uint>::iterator batch_begin = outGroupedTriangleIndices.begin() + b * inGroupSize;
vector<uint>::iterator batch_end = batch_begin + inGroupSize;
vector<uint>::iterator batch_begin_plus_1 = batch_begin + 1;
vector<uint>::iterator batch_end_minus_1 = batch_end - 1;
// Find triangle with centroid with lowest X coordinate
vector<uint>::iterator lowest_iter = batch_begin;
float lowest_val = centroids[*lowest_iter].GetX();
for (vector<uint>::iterator other = batch_begin; other != triangles_end; ++other)
{
float val = centroids[*other].GetX();
if (val < lowest_val)
{
lowest_iter = other;
lowest_val = val;
}
}
// Make this triangle the first in a new batch
swap(*batch_begin, *lowest_iter);
Vec3 first_centroid = centroids[*batch_begin];
// Sort remaining triangles in batch on distance to first triangle
sort(batch_begin_plus_1, batch_end,
[&first_centroid, ¢roids](uint inLHS, uint inRHS) -> bool
{
return (centroids[inLHS] - first_centroid).LengthSq() < (centroids[inRHS] - first_centroid).LengthSq();
});
// Loop over remaining triangles
float furthest_dist = (centroids[*batch_end_minus_1] - first_centroid).LengthSq();
for (vector<uint>::iterator other = batch_end; other != triangles_end; ++other)
{
// Check if this triangle is closer than the furthest triangle in the batch
float dist = (centroids[*other] - first_centroid).LengthSq();
if (dist < furthest_dist)
{
// Replace furthest triangle
uint other_val = *other;
*other = *batch_end_minus_1;
// Find first element that is bigger than this one and insert the current item before it
vector<uint>::iterator upper = upper_bound(batch_begin_plus_1, batch_end, dist,
[&first_centroid, ¢roids](float inLHS, uint inRHS) -> bool
{
return inLHS < (centroids[inRHS] - first_centroid).LengthSq();
});
copy_backward(upper, batch_end_minus_1, batch_end);
*upper = other_val;
// Calculate new furthest distance
furthest_dist = (centroids[*batch_end_minus_1] - first_centroid).LengthSq();
}
}
}
}
} // JPH | 33.408602 | 170 | 0.716125 |
fb7981733cb42623f10709321e1a3d94b1583cc4 | 9,096 | java | Java | src/aslan-core/src/main/java/org/avantssar/aslan/ASLanCodeSerializer.java | DDvO/ASLanPPConnector | 53cac1d701b48c7e30b01f8fc06195e9307bebb1 | [
"Apache-2.0"
] | 1 | 2021-07-26T16:01:45.000Z | 2021-07-26T16:01:45.000Z | src/aslan-core/src/main/java/org/avantssar/aslan/ASLanCodeSerializer.java | DDvO/ASLanPPConnector | 53cac1d701b48c7e30b01f8fc06195e9307bebb1 | [
"Apache-2.0"
] | 2 | 2015-03-30T23:37:13.000Z | 2020-03-31T07:50:06.000Z | src/aslan-core/src/main/java/org/avantssar/aslan/ASLanCodeSerializer.java | DDvO/ASLanPPConnector | 53cac1d701b48c7e30b01f8fc06195e9307bebb1 | [
"Apache-2.0"
] | 2 | 2015-08-12T10:38:19.000Z | 2020-05-05T08:38:32.000Z | // Copyright 2010-2013 (c) IeAT, Siemens AG, AVANTSSAR and SPaCIoS consortia.
// 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.avantssar.aslan;
public class ASLanCodeSerializer implements IASLanVisitor {
private static final String SPEC = "spec";
private final StringBuffer sb = new StringBuffer();
private int indent = 0;
public String getCode() {
return sb.toString();
}
@Override
public void visit(IASLanSpec spec) {
sb.append("public ");
sb.append(IASLanSpec.class.getCanonicalName());
sb.append(" getASLanSpec()");
endLine();
sb.append("{");
endLine();
indent();
startLine();
sb.append(IASLanSpec.class.getCanonicalName());
sb.append(" ");
sb.append(SPEC);
sb.append(" = ");
sb.append(ASLanSpecificationBuilder.class.getCanonicalName());
sb.append(".instance().createASLanSpecification();");
endLine();
endLine();
startLine();
sb.append("// supertypes");
endLine();
for (PrimitiveType t : spec.getPrimitiveTypes()) {
if (!t.isPrelude() && t.getSuperType() != null) {
startLine();
sb.append("spec.primitiveType(\"").append(t.getName()).append("\")");
sb.append(".setSuperType(");
sb.append("spec.primitiveType(\"").append(t.getSuperType().getName()).append("\")");
sb.append(");");
endLine();
}
}
endLine();
startLine();
sb.append("// variables");
endLine();
for (Variable v : spec.getVariables()) {
v.accept(this);
}
endLine();
startLine();
sb.append("// constants");
endLine();
for (Constant c : spec.getConstants()) {
if (!c.isPrelude()) {
c.accept(this);
}
}
endLine();
startLine();
sb.append("// functions");
endLine();
for (Function f : spec.getFunctions()) {
if (!f.isPrelude()) {
f.accept(this);
}
}
endLine();
startLine();
sb.append("// equations");
endLine();
for (Equation eq : spec.getEquations()) {
eq.accept(this);
}
endLine();
startLine();
sb.append("// initial states");
endLine();
for (InitialState is : spec.getInitialStates()) {
is.accept(this);
}
endLine();
startLine();
sb.append("// Horn clauses");
endLine();
for (HornClause hc : spec.getHornClauses()) {
hc.accept(this);
}
endLine();
startLine();
sb.append("// rewrite rules");
endLine();
for (RewriteRule rr : spec.getRules()) {
rr.accept(this);
}
endLine();
startLine();
sb.append("// constraints");
endLine();
for (Constraint c : spec.getConstraints()) {
c.accept(this);
}
endLine();
startLine();
sb.append("// attack states");
endLine();
for (AttackState as : spec.getAttackStates()) {
as.accept(this);
}
endLine();
startLine();
sb.append("// goals");
endLine();
for (Goal g : spec.getGoals()) {
g.accept(this);
}
endLine();
startLine();
sb.append("return ").append(SPEC).append(";");
endLine();
unindent();
sb.append("}");
endLine();
}
@Override
public void visit(PrimitiveType type) {
sb.append(SPEC).append(".primitiveType(\"").append(type.getName()).append("\")");
}
@Override
public void visit(PairType type) {
sb.append(SPEC).append(".pairType(");
type.getLeft().accept(this);
sb.append(", ");
type.getRight().accept(this);
sb.append(")");
}
@Override
public void visit(CompoundType type) {
sb.append(SPEC).append(".compoundType(");
sb.append("\"").append(type.getName()).append("\"");
for (IType t : type.getBaseTypes()) {
sb.append(", ");
t.accept(this);
}
sb.append(")");
}
@Override
public void visit(SetType type) {
sb.append(SPEC).append(".setType(");
type.getBaseType().accept(this);
sb.append(")");
}
@Override
public void visit(Function fnc) {
startLine();
sb.append(SPEC).append(".function(\"").append(fnc.getName()).append("\"");
sb.append(", ");
fnc.getType().accept(this);
for (IType t : fnc.getArgumentsTypes()) {
sb.append(", ");
t.accept(this);
}
sb.append(");");
endLine();
}
@Override
public void visit(Constant cnst) {
startLine();
sb.append(SPEC).append(".constant(\"").append(cnst.getName()).append("\"");
sb.append(", ");
cnst.getType().accept(this);
sb.append(");");
endLine();
}
@Override
public void visit(Variable var) {
startLine();
sb.append(SPEC).append(".variable(\"").append(var.getName()).append("\"");
sb.append(", ");
var.getType().accept(this);
sb.append(");");
endLine();
}
@Override
public void visit(Equation eq) {
startLine();
sb.append(SPEC).append(".equation(");
eq.getLeftTerm().accept(this);
sb.append(", ");
eq.getRightTerm().accept(this);
sb.append(");");
endLine();
}
@Override
public void visit(InitialState init) {
startLine();
sb.append(SPEC).append(".initialState(");
sb.append("\"").append(init.getName()).append("\")");
for (ITerm t : init.getFacts()) {
sb.append(".addFact(");
t.accept(this);
sb.append(")");
}
sb.append(";");
endLine();
}
@Override
public void visit(HornClause clause) {
startLine();
sb.append(SPEC).append(".hornClause(");
sb.append("\"").append(clause.getName()).append("\"");
sb.append(", ");
clause.getHead().accept(this);
sb.append(")");
for (ITerm t : clause.getBodyFacts()) {
sb.append(".addBodyFact(");
t.accept(this);
sb.append(")");
}
sb.append(";");
endLine();
}
@Override
public void visit(RewriteRule rule) {
startLine();
sb.append(SPEC).append(".rule(");
sb.append("\"").append(rule.getName()).append("\"");
sb.append(")");
for (ITerm t : rule.getLHS()) {
sb.append(".addLHS(");
t.accept(this);
sb.append(")");
}
for (Variable v : rule.getExists()) {
sb.append(".addExists(");
sb.append(SPEC).append(".findVariable(");
sb.append("\"").append(v.getName()).append("\"");
sb.append("))");
}
for (ITerm t : rule.getRHS()) {
sb.append(".addRHS(");
t.accept(this);
sb.append(")");
}
sb.append(";");
endLine();
}
@Override
public void visit(Constraint constraint) {
startLine();
sb.append(SPEC).append(".constraint(");
sb.append("\"").append(constraint.getName()).append("\"");
sb.append(", ");
constraint.getFormula().accept(this);
sb.append(");");
endLine();
}
@Override
public void visit(Goal goal) {
startLine();
sb.append(SPEC).append(".goal(");
sb.append("\"").append(goal.getName()).append("\"");
sb.append(", ");
goal.getFormula().accept(this);
sb.append(");");
endLine();
}
@Override
public void visit(AttackState attack) {
startLine();
sb.append(SPEC).append(".attackState(");
sb.append("\"").append(attack.getName()).append("\"");
sb.append(")");
for (ITerm t : attack.getFacts()) {
sb.append(".addTerm(");
t.accept(this);
sb.append(")");
}
sb.append(";");
endLine();
}
@Override
public void visit(ConstantTerm term) {
sb.append(SPEC).append(".findConstant(");
sb.append("\"").append(term.getSymbol().getName()).append("\"");
sb.append(").term()");
}
@Override
public void visit(NumericTerm term) {
sb.append(SPEC).append(".numericTerm(");
sb.append(term.getValue()).append(")");
}
@Override
public void visit(FunctionTerm term) {
sb.append(SPEC).append(".findFunction(");
sb.append("\"").append(term.getSymbol().getName()).append("\"");
sb.append(").term(");
boolean first = true;
for (ITerm t : term.getParameters()) {
if (!first) {
sb.append(", ");
}
t.accept(this);
first = false;
}
sb.append(")");
}
@Override
public void visit(FunctionConstantTerm term) {
sb.append(SPEC).append(".findFunction(");
sb.append("\"").append(term.getSymbol().getName()).append("\"");
sb.append(").constantTerm()");
}
@Override
public void visit(VariableTerm term) {
sb.append(SPEC).append(".findVariable(");
sb.append("\"").append(term.getSymbol().getName()).append("\"");
sb.append(").term()");
}
@Override
public void visit(NegatedTerm term) {
term.getBaseTerm().accept(this);
sb.append(".negate()");
}
@Override
public void visit(QuantifiedTerm term) {
term.getBaseTerm().accept(this);
sb.append(".");
if (term.isUniversal()) {
sb.append("forall");
}
else {
sb.append("exists");
}
sb.append("(").append(SPEC).append(".findVariable(");
sb.append("\"").append(term.getSymbol().getName()).append("\"");
sb.append("))");
}
@Override
public String toString() {
return sb.toString();
}
private void indent() {
indent++;
}
private void unindent() {
indent--;
}
private void startLine() {
for (int i = 0; i < indent; i++) {
sb.append("\t");
}
}
private void endLine() {
sb.append("\n");
}
}
| 21.918072 | 88 | 0.614336 |
c7b545ec1f28dbec141df184def7b21934f984db | 1,507 | py | Python | apps/feedback/serializers.py | ecognize-hub/ecognize | e448098d7c5e815c68a7650b14b31d23976a8900 | [
"Apache-2.0"
] | 1 | 2021-04-17T12:53:34.000Z | 2021-04-17T12:53:34.000Z | apps/feedback/serializers.py | ecognize-hub/ecognize | e448098d7c5e815c68a7650b14b31d23976a8900 | [
"Apache-2.0"
] | null | null | null | apps/feedback/serializers.py | ecognize-hub/ecognize | e448098d7c5e815c68a7650b14b31d23976a8900 | [
"Apache-2.0"
] | null | null | null | from crum import get_current_user
from rest_framework import serializers
from .models import Issue, IssueComment
from apps.profiles.serializers import ProfilePreviewSerializer
class IssueSerializer(serializers.ModelSerializer):
author = ProfilePreviewSerializer(read_only=True)
issue_status = serializers.CharField(read_only=True)
closure_reason = serializers.CharField(read_only=True)
id = serializers.IntegerField(read_only=True)
thanks = serializers.IntegerField(read_only=True)
thanked = serializers.SerializerMethodField()
def get_thanked(self, obj):
current_user_profile = get_current_user().profile
return current_user_profile in obj.thanked_by.all()
class Meta:
model = Issue
fields = ('id', 'issue_type', 'title', 'description', 'author', 'issue_status', 'closure_reason', 'thanks', 'thanked')
class IssueCommentSerializer(serializers.ModelSerializer):
author = ProfilePreviewSerializer(read_only=True)
issue = serializers.PrimaryKeyRelatedField(queryset=Issue.objects.all())
id = serializers.IntegerField(read_only=True)
thanks = serializers.IntegerField(read_only=True)
thanked = serializers.SerializerMethodField()
def get_thanked(self, obj):
current_user_profile = get_current_user().profile
return current_user_profile in obj.thanked_by.all()
class Meta:
model = IssueComment
fields = ('id', 'issue', 'sent_timestamp', 'author', 'content', 'thanks', 'thanked')
| 39.657895 | 126 | 0.745853 |
3fbd3f35f53354b28961692ac3bd2fcf77f9ed2b | 1,749 | swift | Swift | APITesters/SwiftAPITester/SwiftAPITester/ErrorCodesAPI.swift | winstondu/purchases-ios | 5c7c778ffb9c705ad45cea67bb6289fc9555961c | [
"MIT"
] | 1 | 2021-12-30T17:04:35.000Z | 2021-12-30T17:04:35.000Z | APITesters/SwiftAPITester/SwiftAPITester/ErrorCodesAPI.swift | KONGFANJI/purchases-ios | 877e8d6f00b4eb618415d3da90fac6eb06bad866 | [
"MIT"
] | null | null | null | APITesters/SwiftAPITester/SwiftAPITester/ErrorCodesAPI.swift | KONGFANJI/purchases-ios | 877e8d6f00b4eb618415d3da90fac6eb06bad866 | [
"MIT"
] | null | null | null | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// ErrorCodesAPI.swift
//
// Created by Madeline Beyl on 9/5/21.
import Foundation
import RevenueCat
var errCode: ErrorCode!
func checkPurchasesErrorCodeEnums() {
switch errCode! {
case .unknownError,
.purchaseCancelledError,
.storeProblemError,
.purchaseNotAllowedError,
.purchaseInvalidError,
.productNotAvailableForPurchaseError,
.productAlreadyPurchasedError,
.receiptAlreadyInUseError,
.invalidReceiptError,
.missingReceiptFileError,
.networkError,
.invalidCredentialsError,
.unexpectedBackendResponseError,
.receiptInUseByOtherSubscriberError,
.invalidAppUserIdError,
.unknownBackendError,
.invalidAppleSubscriptionKeyError,
.ineligibleError,
.insufficientPermissionsError,
.paymentPendingError,
.invalidSubscriberAttributesError,
.logOutAnonymousUserError,
.configurationError,
.unsupportedError,
.operationAlreadyInProgressForProductError,
.emptySubscriberAttributes,
.productDiscountMissingIdentifierError,
.missingAppUserIDForAliasCreationError,
.productDiscountMissingSubscriptionGroupIdentifierError,
.customerInfoError,
.systemInfoError,
.beginRefundRequestError,
.productRequestTimedOut:
print(errCode!)
@unknown default:
fatalError()
}
}
| 30.155172 | 68 | 0.67753 |
f877130a14c80a6b5138398e318dfbb700fea4cb | 1,365 | swift | Swift | Tests/FlockServerTests/FlockServerTests.swift | roop/swift-driver | 90b71d18d684d083f3e2ecf6f9721cccc4cd92eb | [
"Apache-2.0"
] | null | null | null | Tests/FlockServerTests/FlockServerTests.swift | roop/swift-driver | 90b71d18d684d083f3e2ecf6f9721cccc4cd92eb | [
"Apache-2.0"
] | null | null | null | Tests/FlockServerTests/FlockServerTests.swift | roop/swift-driver | 90b71d18d684d083f3e2ecf6f9721cccc4cd92eb | [
"Apache-2.0"
] | null | null | null | //===------------ FlockServerTests.swift - Flock Server Tests -------------===//
//
// Copyright (c) 2020 Roopesh Chander <http://roopc.net/>
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import FlockServer
import TSCBasic
import XCTest
final class FlockServerTests: XCTestCase {
func testServerConfigParsing() throws {
let str = """
# Flock server config
swift_compiler_frontends:
- "/swift1"
- "/swift2"
- "/swift3"
sdks:
"MacOSX10.5" : "/path/to/macosx/10.5/sdk"
"MacOSX10.4" : "/path/to/macosx/10.4/sdk"
port: 8000
number_of_parallel_compilations: 1
"""
let config = try ServerConfiguration.fromContents(str)
XCTAssertEqual(
config.swiftCompilerFrontends,
["/swift1", "/swift2", "/swift3"].map { AbsolutePath($0) })
XCTAssertEqual(
config.sdks,
[
"MacOSX10.5" : AbsolutePath("/path/to/macosx/10.5/sdk"),
"MacOSX10.4" : AbsolutePath("/path/to/macosx/10.4/sdk")
])
XCTAssertEqual(config.port, 8000)
XCTAssertEqual(config.numberOfParallelCompilations, 1)
}
}
| 30.333333 | 80 | 0.599267 |
ddde5197f63a392027e37a2378aba85329912c26 | 2,077 | php | PHP | resources/views/admins/permissions.blade.php | nsra/updates-for-avocode-website | 38066028f89f168d9b80cf1b8972010cd2571973 | [
"MIT"
] | null | null | null | resources/views/admins/permissions.blade.php | nsra/updates-for-avocode-website | 38066028f89f168d9b80cf1b8972010cd2571973 | [
"MIT"
] | null | null | null | resources/views/admins/permissions.blade.php | nsra/updates-for-avocode-website | 38066028f89f168d9b80cf1b8972010cd2571973 | [
"MIT"
] | null | null | null | {{--@if(!(auth()->user()->can('read permissions')))--}}
{{-- <h1> hh</h1>--}}
{{--@elseif(auth()->user()->can('read permissions'))--}}
{{--@can('read permissions')--}}
@extends('base_layout._layout')
@section('header')
<meta name="csrf-token" content="{{ csrf_token() }}">
@endsection
@section('style')
<style>
.permission>li{
float: right;
width: 25%;
height: 160px;
}
</style>
@endsection
@section('body')
<div class="card">
<div class="card-header">
<h3>{{ __('lang.permissions') }}</h3>
</div>
<div class="card-body">
<div class="form-group">
<h3> {{__('lang.role')}}: {{$admin_role}} </h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<form action="{{route('update_admin_permissions')}}" method="POST">
@csrf
<input type="hidden" class="" name="admin_id" value="{{$admin->id}}" >
@foreach($permissions as $permission)
<div class="form-group col-lg-3">
<label for="permission">
<input type="checkbox" class="" name="permissions[]" value="{{$permission->name}}" {{in_array( $permission->name, $admin_permissions->toArray()) ? 'checked' : ''}}>
{{$permission->name}}
</label>
</div>
@endforeach
</div>
<div class="form-action text-center">
<input type="submit" class="btn btn-primary" name="" value="{{__('lang.store')}}" >
</div>
</form>
</div>
</div>
</div>
</div>
@endsection
| 38.462963 | 204 | 0.398652 |
4ad0c2dbd9d4d9666cb8bccc8e0358aab9235a19 | 7,538 | cs | C# | 0-project-files/Car_Renting_Management_System/DiscountOptions.cs | GunaRakulan-GR/car-rental-system | 4fd4befe492d48a8f5f79aa4fd67e0a2fbc35800 | [
"Apache-2.0"
] | 2 | 2021-09-07T06:19:23.000Z | 2021-09-07T12:36:28.000Z | 0-project-files/Car_Renting_Management_System/DiscountOptions.cs | GunaRakulan-GR/car-rental-system | 4fd4befe492d48a8f5f79aa4fd67e0a2fbc35800 | [
"Apache-2.0"
] | null | null | null | 0-project-files/Car_Renting_Management_System/DiscountOptions.cs | GunaRakulan-GR/car-rental-system | 4fd4befe492d48a8f5f79aa4fd67e0a2fbc35800 | [
"Apache-2.0"
] | null | null | null | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Car_Renting_Management_System
{
public partial class DiscountOptions : Form
{
double dura = 0;
double per = 0;
double driverSala = 0;
public DiscountOptions(double duration,double perCh,double driverSalary)
{
InitializeComponent();
dura = duration;
per = perCh;
driverSala = driverSalary;
}
private void label3_Click(object sender, EventArgs e)
{
this.Hide();
}
private void bunifuFlatButton1_Click(object sender, EventArgs e)
{
this.Hide();
textBox1.Text = "no";
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
if (numericUpDown1.Value == 0)
{
double totalAm = (dura * per)+driverSala;
double dis = totalAm * 0 / 100;
double ba = totalAm - dis;
label13.Text = "0%";
label11.Text = "Rs:" + ba;
label9.Text = "Rs:" + dis;
Drawing("Rs:" + totalAm + "", "r");
}
else
{
double totalAm = (dura * per)+driverSala;
label7.Visible = false;
label11.Visible = true;
label9.Visible = true;
label13.Text = numericUpDown1.Value.ToString() + "%";
int percentage = Convert.ToInt32(numericUpDown1.Value);
double dis = totalAm * percentage / 100;
string t = "Rs: " + totalAm.ToString();
Drawing(t);
label9.Text = "Rs: " + dis.ToString();
label11.Text = "Rs: " + (totalAm - dis).ToString();
}
}
int canMo = 0;
int Xc = 0;
int Yc = 0;
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
canMo = 0;
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
canMo = 1;
Xc = e.X;
Yc = e.Y;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (canMo==1) {
this.SetDesktopLocation(MousePosition.X - Xc, MousePosition.Y - Yc);
}
}
private void numericUpDown1_KeyDown(object sender, KeyEventArgs e)
{
}
private void numericUpDown1_KeyPress(object sender, KeyPressEventArgs e)
{
}
private void numericUpDown1_KeyUp(object sender, KeyEventArgs e)
{
label7.Visible = false;
label11.Visible = true;
label9.Visible = true;
if (numericUpDown1.Text == "")
{
double totalAm = (dura * per)+driverSala;
double dis = totalAm * 0 / 100;
double ba = totalAm - dis;
label13.Text = "0%";
label11.Text = "Rs:" + ba;
label9.Text = "Rs:" + dis;
Drawing("Rs:" + totalAm + "", "r");
}
else if (numericUpDown1.Value == 0) {
double totalAm = (dura * per)+driverSala;
double dis = totalAm * 0 / 100;
double ba = totalAm - dis;
label13.Text = "0%";
label11.Text = "Rs:" + ba;
label9.Text = "Rs:" + dis;
Drawing("Rs:" + totalAm + "", "r");
}
else
{
double totalAm = (dura * per)+driverSala;
label13.Text = numericUpDown1.Value.ToString() + "%";
int percentage = Convert.ToInt32(numericUpDown1.Value);
double dis = totalAm * percentage / 100;
string t = "Rs: " + totalAm.ToString();
Drawing(t);
label9.Text = "Rs: " + dis.ToString();
label11.Text = "Rs: " + (totalAm - dis).ToString();
}
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
}
private void DiscountOptions_Load(object sender, EventArgs e)
{
double totalAm = (dura * per)+driverSala;
label7.Text = "Rs: " + totalAm;
double dis = totalAm * 0 / 100;
double ba = totalAm - dis;
label13.Text = "0%";
label11.Text = "Rs:" + ba;
label9.Text = "Rs:" + dis;
textBox1.Visible = false;
}
private void DiscountOptions_Paint(object sender, PaintEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void panel2_Paint(object sender, PaintEventArgs e)
{
}
private void panel2_Paint_1(object sender, PaintEventArgs e)
{
}
private void panel2_Paint_2(object sender, PaintEventArgs e)
{
}
public void Drawing(string value) {
SolidBrush so = new SolidBrush(Color.SpringGreen);
Graphics g = panel2.CreateGraphics();
g.Clear(panel2.BackColor);
FontFamily ff = new FontFamily("Arial");
System.Drawing.Font font = new System.Drawing.Font(ff, 15);
g.DrawString(value, font, so, new PointF(10, 20));
Pen p = new Pen(Color.Red, 3);
g.DrawLine(p, 100, 38, 07, 25);
g.Dispose();
}
public void Drawing(string value,string td)
{
SolidBrush so = new SolidBrush(Color.SpringGreen);
Graphics g = panel2.CreateGraphics();
g.Clear(panel2.BackColor);
FontFamily ff = new FontFamily("Arial");
System.Drawing.Font font = new System.Drawing.Font(ff, 15);
g.DrawString(value, font, so, new PointF(10, 20));
}
private void bunifuCustomTextbox4_TextChanged(object sender, EventArgs e)
{
}
private void label1_MouseUp(object sender, MouseEventArgs e)
{
canMo = 0;
}
private void label1_MouseMove(object sender, MouseEventArgs e)
{
if (canMo == 1) {
this.SetDesktopLocation(MousePosition.X - 360, MousePosition.Y - 18);
}
}
private void label1_MouseDown(object sender, MouseEventArgs e)
{
canMo = 1;
Xc = e.X;
Yc = e.Y;
}
private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
bookForm b = new bookForm();
this.Hide();
textBox1.Text = "yes";
}
}
}
| 25.466216 | 85 | 0.475192 |
aa5e5eb7f6e8e256735127a17f1db35ff3a7b1b0 | 111 | ps1 | PowerShell | scripts/Dell Command Monitor/Bluetooth Module State/DCIMBTDev-Short.ps1 | DHCook/KACE-SMA_CustomInventory | 303bdbbb55c0e6c1ded84a9bf9b6599dff2514a9 | [
"MIT"
] | null | null | null | scripts/Dell Command Monitor/Bluetooth Module State/DCIMBTDev-Short.ps1 | DHCook/KACE-SMA_CustomInventory | 303bdbbb55c0e6c1ded84a9bf9b6599dff2514a9 | [
"MIT"
] | 1 | 2022-03-09T13:54:49.000Z | 2022-03-09T13:54:49.000Z | scripts/Dell Command Monitor/Bluetooth Module State/DCIMBTDev-Short.ps1 | DHCook/KACE-SMA_CustomInventory | 303bdbbb55c0e6c1ded84a9bf9b6599dff2514a9 | [
"MIT"
] | null | null | null | gwmi -n root\dcim\sysman DCIM_BIOSEnumeration -f {AttributeName='Bluetooth Devices'} | select -exp CurrentValue | 111 | 111 | 0.810811 |
6f9df6e8162ee4fbe62212b90428de4c2843bb34 | 12,215 | rs | Rust | interactive_engine/executor/runtime/src/dataflow/operator/unarystep/order.rs | LI-Mingyu/GraphScope-MY | 942060983d3f7f8d3a3377467386e27aba285b33 | [
"Apache-2.0"
] | 1,521 | 2020-10-28T03:20:24.000Z | 2022-03-31T12:42:51.000Z | interactive_engine/executor/runtime/src/dataflow/operator/unarystep/order.rs | LI-Mingyu/GraphScope-MY | 942060983d3f7f8d3a3377467386e27aba285b33 | [
"Apache-2.0"
] | 850 | 2020-12-15T03:17:32.000Z | 2022-03-31T11:40:13.000Z | interactive_engine/executor/runtime/src/dataflow/operator/unarystep/order.rs | LI-Mingyu/GraphScope-MY | 942060983d3f7f8d3a3377467386e27aba285b33 | [
"Apache-2.0"
] | 180 | 2020-11-10T03:43:21.000Z | 2022-03-28T11:13:31.000Z | //
//! Copyright 2020 Alibaba Group Holding Limited.
//!
//! 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.
use dataflow::operator::shuffle::{StreamShuffleType, StreamShuffleKeyType};
use dataflow::manager::requirement::RequirementManager;
use dataflow::message::{RawMessage, RawMessageType, ValuePayload};
use dataflow::manager::order::OrderManager;
use dataflow::builder::{Operator, UnaryOperator, InputStreamShuffle, MessageCollector};
use dataflow::common::iterator::IteratorList;
use maxgraph_common::proto::query_flow::OperatorBase;
use maxgraph_common::proto::message::OrderComparatorList;
use maxgraph_common::util::hash::murmur_hash64;
use protobuf::parse_from_bytes;
use std::collections::HashMap;
use itertools::Itertools;
pub struct OrderOperator<F>
where F: Fn(&i64) -> u64 + 'static + Send + Sync {
id: i32,
input_id: i32,
stream_index: i32,
shuffle_type: StreamShuffleKeyType<F>,
before_requirement: RequirementManager,
after_requirement: RequirementManager,
range_flag: bool,
range_start: usize,
range_end: usize,
order_manager: OrderManager,
comparators: OrderComparatorList,
keyed_order_manager: HashMap<i64, OrderManager>,
order_label_id: i32,
}
impl<F> OrderOperator<F>
where F: Fn(&i64) -> u64 + 'static + Send + Sync {
pub fn new(input_id: i32,
stream_index: i32,
shuffle_type: StreamShuffleKeyType<F>,
base: &OperatorBase) -> Self {
let range_flag = base.has_range_limit();
let (range_start, range_end) = {
if range_flag {
let range_limit = base.get_range_limit();
let range_start = {
if range_limit.range_start < 0 {
0
} else {
range_limit.range_start as usize
}
};
let range_end = {
if range_limit.range_end < 0 {
1000000000
} else {
range_limit.range_end as usize
}
};
(range_start, range_end)
} else {
(0, 0)
}
};
let payload = base.get_argument().get_payload();
let comparators = parse_from_bytes::<OrderComparatorList>(payload).expect("parse comparator list");
let order_manager = OrderManager::new(comparators.clone(), range_end, range_flag);
let order_label_id = base.get_argument().get_int_value();
OrderOperator {
id: base.get_id(),
input_id,
stream_index,
shuffle_type,
before_requirement: RequirementManager::new(base.get_before_requirement().to_vec()),
after_requirement: RequirementManager::new(base.get_after_requirement().to_vec()),
range_flag,
range_start,
range_end,
order_manager,
comparators,
keyed_order_manager: HashMap::new(),
order_label_id,
}
}
}
impl<F> Operator for OrderOperator<F>
where F: Fn(&i64) -> u64 + 'static + Send + Sync {
fn get_id(&self) -> i32 {
self.id
}
}
impl<F> UnaryOperator for OrderOperator<F>
where F: Fn(&i64) -> u64 + 'static + Send + Sync {
fn get_input_id(&self) -> i32 {
self.input_id
}
fn get_input_shuffle(&self) -> Box<InputStreamShuffle> {
Box::new(self.shuffle_type.clone())
}
fn get_stream_index(&self) -> i32 {
self.stream_index
}
fn execute<'a>(&mut self, data: Vec<RawMessage>, _collector: &mut Box<'a + MessageCollector>) {
for message in data.into_iter() {
let message = self.before_requirement.process_requirement(message);
if let Some(key) = message.get_extend_key_payload() {
let order_manager = self.keyed_order_manager.entry(murmur_hash64(key))
.or_insert(OrderManager::new(self.comparators.clone(), self.range_end, self.range_flag));
let mut prop_flag = true;
for prop_id in order_manager.get_order_property_id().iter() {
if message.get_property(*prop_id).is_none() {
prop_flag = false;
break;
}
}
if prop_flag {
order_manager.add_message(message);
}
} else {
let mut prop_flag = true;
for prop_id in self.order_manager.get_order_property_id().iter() {
if message.get_property(*prop_id).is_none() {
prop_flag = false;
break;
}
}
if prop_flag {
self.order_manager.add_message(message);
}
}
}
}
fn finish(&mut self) -> Box<dyn Iterator<Item=RawMessage> + Send> {
if !self.keyed_order_manager.is_empty() {
let mut value_list = vec![];
for (_, mut result_order) in self.keyed_order_manager.drain() {
let result_list = {
if self.range_flag {
result_order.get_range_result_list(self.range_start)
} else {
result_order.get_result_list()
}
};
if self.order_label_id < 0 {
let mut order_result_list = Vec::with_capacity(result_list.len());
let mut order_index = 0;
for mut curr_result in result_list.into_iter() {
curr_result.add_label_entity(RawMessage::from_value(ValuePayload::Int(order_index)), self.order_label_id);
order_result_list.push(curr_result);
order_index = order_index + 1;
}
value_list.push(order_result_list.into_iter());
} else {
value_list.push(result_list.into_iter());
}
}
let after_req = self.after_requirement.clone();
return Box::new(IteratorList::new(value_list).map(move |v| after_req.process_requirement(v)));
} else {
let result_list = {
if self.range_flag {
self.order_manager.get_range_result_list(self.range_start)
} else {
self.order_manager.get_result_list()
}
};
if self.order_label_id < 0 {
let mut order_index = 0;
let mut order_result_list = Vec::with_capacity(result_list.len());
for mut m in result_list.into_iter() {
m.add_label_entity(RawMessage::from_value(ValuePayload::Int(order_index)), self.order_label_id);
order_index += 1;
order_result_list.push(self.after_requirement.process_requirement(m));
}
return Box::new(order_result_list.into_iter());
} else {
let after_req = self.after_requirement.clone();
return Box::new(result_list.into_iter().map(move |v| {
after_req.process_requirement(v)
}));
}
}
}
}
pub struct OrderLocalOperator<F>
where F: Fn(&i64) -> u64 + 'static + Send + Sync {
id: i32,
input_id: i32,
stream_index: i32,
shuffle_type: StreamShuffleType<F>,
before_requirement: RequirementManager,
after_requirement: RequirementManager,
order_manager: OrderManager,
}
impl<F> OrderLocalOperator<F>
where F: Fn(&i64) -> u64 + 'static + Send + Sync {
pub fn new(input_id: i32,
stream_index: i32,
shuffle_type: StreamShuffleType<F>,
base: &OperatorBase) -> Self {
let payload = base.get_argument().get_payload();
let comparators = parse_from_bytes::<OrderComparatorList>(payload).expect("parse comparator list");
let order_manager = OrderManager::new(comparators, 0, false);
OrderLocalOperator {
id: base.get_id(),
input_id,
stream_index,
shuffle_type,
before_requirement: RequirementManager::new(base.get_before_requirement().to_vec()),
after_requirement: RequirementManager::new(base.get_after_requirement().to_vec()),
order_manager,
}
}
}
impl<F> Operator for OrderLocalOperator<F>
where F: Fn(&i64) -> u64 + 'static + Send + Sync {
fn get_id(&self) -> i32 {
self.id
}
}
impl<F> UnaryOperator for OrderLocalOperator<F>
where F: Fn(&i64) -> u64 + 'static + Send + Sync {
fn get_input_id(&self) -> i32 {
self.input_id
}
fn get_input_shuffle(&self) -> Box<InputStreamShuffle> {
Box::new(self.shuffle_type.clone())
}
fn get_stream_index(&self) -> i32 {
self.stream_index
}
fn execute<'a>(&mut self, data: Vec<RawMessage>, collector: &mut Box<'a + MessageCollector>) {
let mut result_list = Vec::with_capacity(data.len());
for message in data.into_iter() {
let mut message = self.before_requirement.process_requirement(message);
match message.get_message_type() {
RawMessageType::LIST => {
if let Some(value) = message.take_value() {
if let Ok(list) = value.take_list() {
for val in list.into_iter() {
self.order_manager.add_message(val);
}
let order_list = self.order_manager.get_result_list();
let mut result = RawMessage::from_value_type(ValuePayload::List(order_list), RawMessageType::LIST);
self.after_requirement.process_take_extend_entity(&mut message, &mut result);
result_list.push(self.after_requirement.process_requirement(result));
}
}
}
RawMessageType::MAP => {
if let Some(value) = message.take_value() {
if let Ok(list) = value.take_map() {
for val in list.into_iter() {
self.order_manager.add_message(RawMessage::from_entry_entity(val));
}
let order_list = self.order_manager
.get_result_list()
.into_iter()
.map(move |mut v| {
v.take_value().unwrap().take_entry().unwrap()
}).collect_vec();
let mut result = RawMessage::from_value_type(ValuePayload::Map(order_list), RawMessageType::MAP);
self.after_requirement.process_take_extend_entity(&mut message, &mut result);
result_list.push(self.after_requirement.process_requirement(result));
}
}
}
_ => {
result_list.push(self.after_requirement.process_requirement(message));
}
}
}
collector.collect_iterator(Box::new(result_list.into_iter()));
}
fn finish(&mut self) -> Box<dyn Iterator<Item=RawMessage> + Send> {
return Box::new(None.into_iter());
}
}
| 39.530744 | 130 | 0.552272 |
35c3f482b42454889092126b515a7d8d82998b8d | 84 | kts | Kotlin | settings.gradle.kts | asad-awadia/docker-client | e1775d272f234acc65abf8af3e6a0f950bcd3c90 | [
"MIT"
] | 91 | 2015-09-07T10:32:34.000Z | 2022-03-07T21:47:26.000Z | settings.gradle.kts | asad-awadia/docker-client | e1775d272f234acc65abf8af3e6a0f950bcd3c90 | [
"MIT"
] | 126 | 2015-07-19T07:43:03.000Z | 2022-03-31T08:13:20.000Z | settings.gradle.kts | asad-awadia/docker-client | e1775d272f234acc65abf8af3e6a0f950bcd3c90 | [
"MIT"
] | 37 | 2015-08-11T14:46:02.000Z | 2021-07-22T14:00:53.000Z | rootProject.name = "docker-client"
include("client", "integration-test", "explore")
| 28 | 48 | 0.738095 |
83d0045b456114d429887e7c32de3f10e0be8457 | 5,534 | java | Java | src/main/java/org/jasig/portlet/emailpreview/AccountSummary.java | cendern/email-preview | c7c2d21f5ec71db70e3c0d61caa24f9bc65759bd | [
"Apache-2.0"
] | null | null | null | src/main/java/org/jasig/portlet/emailpreview/AccountSummary.java | cendern/email-preview | c7c2d21f5ec71db70e3c0d61caa24f9bc65759bd | [
"Apache-2.0"
] | null | null | null | src/main/java/org/jasig/portlet/emailpreview/AccountSummary.java | cendern/email-preview | c7c2d21f5ec71db70e3c0d61caa24f9bc65759bd | [
"Apache-2.0"
] | null | null | null | /**
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you 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 the following location:
*
* 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.jasig.portlet.emailpreview;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Encapsulates basic information about the email INBOX. Typically sent to the
* browser via AJAX.
*
* @author Andreas Christoforides
* @author Jen Bourey, jbourey@unicon.net
* @author Drew Wills, drew@unicon.net
*/
public final class AccountSummary {
private final String inboxUrl;
private final List<? extends EmailMessage> messages;
private final int numUnreadMessages;
private final int numTotalMessages;
private final int messagesStart;
private final int messagesMax;
private final boolean deleteSupported;
private final Throwable errorCause;
private final EmailQuota quota;
public AccountSummary(String inboxUrl, List<? extends EmailMessage> messages,
int numUnreadMessages, int numTotalMessages, int messagesStart,
int messagesMax, boolean deleteSupported, EmailQuota quota) {
// Assertions
if (messages == null) {
String msg = "Argument 'messages' cannot be null";
throw new IllegalArgumentException(msg);
}
// Instance Members
this.inboxUrl = inboxUrl; // NB: May be null
this.messages = Collections.unmodifiableList(new ArrayList<EmailMessage>(messages));
this.numUnreadMessages = numUnreadMessages;
this.numTotalMessages = numTotalMessages;
this.messagesStart = messagesStart;
this.messagesMax = messagesMax;
this.deleteSupported = deleteSupported;
this.errorCause = null;
this.quota = quota;
}
/**
* Indicates the account fetch did not succeed and provides the cause.
* Previously we would communicate this fact by throwing an exception, but
* we learned that (1) the caching API we use writes these exceptions to
* Catalina.out, and (2) occurances of {@link MailAuthenticationException}
* are very common, and the logs were being flooded with them.
*
* @param errorCause
*/
public AccountSummary(Throwable errorCause) {
// Assertions.
if (errorCause == null) {
String msg = "Argument 'errorCause' cannot be null";
throw new IllegalArgumentException(msg);
}
// Instance Members
this.inboxUrl = null;
this.numUnreadMessages = -1;
this.numTotalMessages = -1;
this.messages = null;
this.messagesStart = -1;
this.messagesMax = -1;
this.deleteSupported = false;
this.errorCause = errorCause;
this.quota = null;
}
/**
* Indicates if this object contains valid account details. Otherwise, it
* will contain an error payload.
*
* @return False if this object represents an error condition instead of an
* account summary
*/
public boolean isValid() {
return errorCause == null;
}
public Throwable getErrorCause() {
return errorCause;
}
/**
* Provides the URL to the full-featured web-based mail client, if available.
*
* @return A valid web address or <code>null</code>
*/
public String getInboxUrl() {
return inboxUrl;
}
/**
* Returns the number of unread messages in the user's inbox.
*
* @return The number of unread messages in the user's inbox.
*/
public int getUnreadMessageCount() {
return this.numUnreadMessages;
}
/**
* Returns the total number messages in the user's inbox.
*
* @return The total number of messages in the user's inbox.
*/
public int getTotalMessageCount() {
return this.numTotalMessages;
}
/**
* Returns a list that contains the emails bound by <code>messagesStart</code>
* and <code>messagesCode</code>.
*
* @return A <code>List<EmailMessage></code> containing information about
* emails in the user's inbox
*/
public List<? extends EmailMessage> getMessages() {
return this.messages;
}
/**
* Returns the index of the first message in the Messages list.
*
* @return
*/
public int getMessagesStart() {
return this.messagesStart;
}
/**
* Returns the number of messages requested for the Messages list. The
* actual size of the list may be lower.
*
* @return
*/
public int getMessagesMax() {
return this.messagesMax;
}
public boolean isDeleteSupported() {
return deleteSupported;
}
/**
* Returns the value of disk space , max & used
*
* @return
*/
public EmailQuota getQuota() {
return quota;
}
}
| 30.076087 | 92 | 0.654499 |
fbac51e36fa35fc1e61d15163889dac9d6e96057 | 881 | java | Java | core/src/main/java/com/bombinggames/wurfelengine/core/console/LECommand.java | LittleDevilGames/WurfelEngineSDK | 91c1b71d516565f55e784a8bd31470076734414d | [
"BSD-3-Clause"
] | 96 | 2015-12-05T11:09:35.000Z | 2022-03-25T04:12:33.000Z | core/src/main/java/com/bombinggames/wurfelengine/core/console/LECommand.java | LittleDevilGames/WurfelEngineSDK | 91c1b71d516565f55e784a8bd31470076734414d | [
"BSD-3-Clause"
] | 13 | 2016-10-10T12:16:14.000Z | 2020-10-26T10:04:39.000Z | core/src/main/java/com/bombinggames/wurfelengine/core/console/LECommand.java | BSVogler/WurfelEngineSDK | 924b3d867bd346b1c79be777212054ea78941a0c | [
"BSD-3-Clause"
] | 35 | 2016-05-30T09:23:32.000Z | 2022-02-13T19:24:26.000Z | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.bombinggames.wurfelengine.core.console;
import java.util.StringTokenizer;
import com.bombinggames.wurfelengine.core.Controller;
import com.bombinggames.wurfelengine.core.GameplayScreen;
/**
*
* @author Benedikt Vogler
*/
public class LECommand implements ConsoleCommand {
@Override
public boolean perform(StringTokenizer parameters, GameplayScreen gameplay) {
if (Controller.getLightEngine()!=null)
Controller.getLightEngine().setDebug(!Controller.getLightEngine().isInDebug());
return true;
}
@Override
public String getCommandName() {
return "le";
}
/**
*
* @return
*/
@Override
public String getManual() {
return "toggles the light engine";
}
}
| 22.025 | 82 | 0.745743 |
f09532071f913faab3e10e8b940a40f75bbfccf9 | 3,163 | js | JavaScript | main.js | rubarnes/CooCast | d059e04f2335dfcfb1417f76e285ef06415e3590 | [
"MIT"
] | null | null | null | main.js | rubarnes/CooCast | d059e04f2335dfcfb1417f76e285ef06415e3590 | [
"MIT"
] | null | null | null | main.js | rubarnes/CooCast | d059e04f2335dfcfb1417f76e285ef06415e3590 | [
"MIT"
] | null | null | null | //main.js
//a bunch o' boilerplate
/*MIT License
Copyright (c) 2017 Jonathan Verrecchia
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.*/
const electron = require('electron')
// Module to control application life.
const app = electron.app
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow
const path = require('path')
const url = require('url')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
function createWindow () {
// Create the browser window.
//mainWindow = new BrowserWindow({width: 1280, height: 1024, frame: false, resizable: false})
mainWindow = new BrowserWindow({width: 1280, height: 1024, resizable: false})
// and load the index.html of the app.
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'html/index.html'),
protocol: 'file:',
slashes: true
}))
// Open the DevTools.
//mainWindow.webContents.openDevTools()
// Emitted when the window is closed.
mainWindow.on('closed', function () {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null
})
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)
// Quit when all windows are closed.
app.on('window-all-closed', function () {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (mainWindow === null) {
createWindow()
}
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
| 35.943182 | 95 | 0.741069 |
7065c2af7e409194e61abe1d96c79f9aa872e55e | 2,585 | cs | C# | SaleMTv1_new/SaleMTInterfaces/FrmReporter/FrmReportSale/frmCreateReasion.cs | quynhnvx8/Sale | a7fd8c3f3a51a737e9a2c899d4807d7f665e828c | [
"Apache-2.0"
] | null | null | null | SaleMTv1_new/SaleMTInterfaces/FrmReporter/FrmReportSale/frmCreateReasion.cs | quynhnvx8/Sale | a7fd8c3f3a51a737e9a2c899d4807d7f665e828c | [
"Apache-2.0"
] | null | null | null | SaleMTv1_new/SaleMTInterfaces/FrmReporter/FrmReportSale/frmCreateReasion.cs | quynhnvx8/Sale | a7fd8c3f3a51a737e9a2c899d4807d7f665e828c | [
"Apache-2.0"
] | null | null | null | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SaleMTDataAccessLayer.SaleMTDAL;
using SaleMTDataAccessLayer.SaleMTObj;
using SaleMTCommon;
using System.Data.SqlClient;
using System.Resources;
using System.Reflection;
using SaleMTBusiness.SaleManagement;
using SaleMTInterfaces.PrintBill;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Collections;
using SaleMTInterfaces.FrmReporter.FrmReportSale;
namespace SaleMTInterfaces.FrmReporter.FrmReportSale
{
public partial class frmCreateReasion : Form
{
#region Constructor
public frmCreateReasion(Dictionary<string, string> language)
{
translate = language;
InitializeComponent();
initLanguage();
}
static private Dictionary<string, string> translate = new Dictionary<string, string>();
private void initLanguage()
{
this.label1.Text = translate["frmCreateReasion.label1.Text"];
this.btnSave.Text = translate["frmCreateReasion.btnSave.Text"];
this.Text = translate["frmCreateReasion.Text"];
}
#endregion
#region Methods
public string Titlle;
//private frmCreateReasion cReasion;
//public frmCreateReasion CreateReasion
//{
// get { return cReasion; }
// set { cReasion = value; }
//}
//Luu trang thai check
public void InsertReasion(string title)
{
//string s;
frmProductReportSearch frm = new frmProductReportSearch(translate);
REPORT_CONDITIONS reCon = new REPORT_CONDITIONS();
reCon.CATEGORY = frm.listProGroupTag;
reCon.ACCOUNT = UserImformation.UserName;
reCon.LIST_COLUMN = frm.ListResionTag;
reCon.AUTO_ID = Guid.NewGuid();
reCon.TITLE = title;
reCon.REPORT = "frmReportSale";
reCon.LIST_GROUP = null;
reCon.ATTRIBUTE = "";
reCon.Save(true);
}
#endregion
#region Event
private void btnSave_Click(object sender, EventArgs e)
{
Titlle = txtReasionName.Text;
MessageBox.Show(Properties.rsfPayment.CashPayment1.ToString(), translate["Msg.TitleDialog"], MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.Close();
}
#endregion
}
}
| 30.05814 | 152 | 0.639458 |
5650f736b5212eec0be1acc6233b70514323997b | 7,590 | go | Go | parse.go | ComedicChimera/olive | c9916e4999d60aedecb120a4897117af239c8be8 | [
"MIT"
] | null | null | null | parse.go | ComedicChimera/olive | c9916e4999d60aedecb120a4897117af239c8be8 | [
"MIT"
] | null | null | null | parse.go | ComedicChimera/olive | c9916e4999d60aedecb120a4897117af239c8be8 | [
"MIT"
] | null | null | null | package olive
import (
"fmt"
"strings"
)
// argParser is a state machine used to parse arguments
type argParser struct {
// initialCommand is the command that represents the initial/global state of
// the parser. The entire CLI of an application can essentially be thought of
// as one large command which a bunch of subcommands.
initialCommand *Command
// commandStack is a stack of active commands. This facilitates the fact
// that flags and named arguments that are valid for a base command are also
// valid for all subcommands.
commandStack []*Command
// result is the accumulated result of parsing. This data structure is
// built up during the parsing process to represent the abstract structure
// of the inputted arguments -- it is akin to an AST in language processing.
result *ArgParseResult
// semanticStack stores the components of the arg parse result as they are
// constructed -- this allows for flags to be assigned to their
// corresponding command at any depth within the parsing stack
semanticStack []*ArgParseResult
// allowSubcommands indicates whether or not a flag or argument has already
// been encountered and therefore subcommands are no longer valid
allowSubcommands bool
}
// parse runs the main parsing algorithm on a set of argument values
func (ap *argParser) parse(args []string) (*ArgParseResult, error) {
ap.result = &ArgParseResult{
flags: make(map[string]struct{}),
Arguments: make(map[string]interface{}),
}
ap.commandStack = []*Command{ap.initialCommand}
ap.semanticStack = []*ArgParseResult{ap.result}
ap.allowSubcommands = true
for _, arg := range args {
if err := ap.consume(arg); err != nil {
return nil, err
}
}
// by definition, the last value on the command stack can be the only
// command that might be missing a subcommand -- so that is the only value
// we check. We know that if the last item on the command stack requires a
// subcommand, then it is missing that command (otherwise, there would be a
// next item). We only check this field if there are subcommands to be
// missing
if len(ap.currCommand().subcommands) > 0 && ap.currCommand().RequiresSubcommand {
return nil, fmt.Errorf("`%s` requires a subcommand", ap.currCommand().Name)
}
// since only the last command in the chain can have primary arguments
// (because a command cannot have both subcommands and primary arguments),
// we only have to check to see if the last command is missing a required
// primary argument
if ap.currCommand().primaryArg != nil && ap.currCommand().primaryArg.required && ap.currResult().primaryArg == "" {
return nil, fmt.Errorf("missing required primary argument `%s` for subcommand `%s`", ap.currCommand().Name, ap.currCommand().primaryArg.name)
}
// set all the default values of any unsupplied arguments; go in reverse
// order so most specific subcommand gets precedence
for i := len(ap.commandStack) - 1; i > -1; i-- {
for _, arg := range ap.commandStack[i].args {
if val, ok := arg.GetDefaultValue(); ok {
if _, ok := ap.semanticStack[i].Arguments[arg.Name()]; !ok {
ap.semanticStack[i].Arguments[arg.Name()] = val
}
}
}
}
return ap.result, nil
}
// consume processes a single argument token of input
func (ap *argParser) consume(arg string) error {
if strings.HasPrefix(arg, "--") {
ap.allowSubcommands = false
// handle full-named arguments
argName, argVal := ap.extractComponents(arg)
if argVal == "" {
// => flag
for i := len(ap.commandStack) - 1; i > -1; i-- {
if flag, ok := ap.commandStack[i].flags[argName]; ok {
if err := ap.setFlag(i, flag); err != nil {
return err
} else {
return nil
}
}
}
return fmt.Errorf("unknown flag: `%s`", argName)
} else {
// => argument
for i := len(ap.commandStack) - 1; i > -1; i-- {
if arg, ok := ap.commandStack[i].args[argName]; ok {
if err := ap.setArg(i, arg, argVal); err != nil {
return err
} else {
return nil
}
}
}
return fmt.Errorf("unknown argument: `%s`", argName)
}
} else if strings.HasPrefix(arg, "-") {
ap.allowSubcommands = false
// handle short-named arguments
argName, argVal := ap.extractComponents(arg)
if argVal == "" {
// => flag
for i := len(ap.commandStack) - 1; i > -1; i-- {
if flag, ok := ap.commandStack[i].flagsByShortName[argName]; ok {
if err := ap.setFlag(i, flag); err != nil {
return err
} else {
return nil
}
}
}
return fmt.Errorf("unknown flag by short name: `%s`", argName)
} else {
// => argument
for i := len(ap.commandStack) - 1; i > -1; i-- {
if arg, ok := ap.commandStack[i].argsByShortName[argName]; ok {
if err := ap.setArg(i, arg, argVal); err != nil {
return err
} else {
return nil
}
}
}
return fmt.Errorf("unknown argument by short name: `%s`", argName)
}
} else if ap.currCommand().primaryArg != nil {
ap.allowSubcommands = false
// handle primary arguments
if ap.currResult().primaryArg != "" {
return fmt.Errorf("multiple primary arguments specified for command `%s`", ap.currCommand().Name)
}
ap.currResult().primaryArg = arg
} else if ap.allowSubcommands {
if subc, ok := ap.currCommand().subcommands[arg]; ok {
// handle subcommands
ap.commandStack = append(ap.commandStack, subc)
newResult := &ArgParseResult{
Arguments: make(map[string]interface{}),
flags: make(map[string]struct{}),
}
ap.currResult().subcommandRes = newResult
ap.currResult().subcommandName = subc.Name
ap.semanticStack = append(ap.semanticStack, newResult)
} else {
return fmt.Errorf("unknown subcommand: `%s`", arg)
}
} else {
return fmt.Errorf("unexpected subcommand: `%s`", arg)
}
return nil
}
// extractComponents converts an input string into its two parts: argument name
// and argument value. If this input string is setting a flag, then the
// argument value returned is "".
func (ap *argParser) extractComponents(arg string) (string, string) {
if strings.Contains(arg, "=") {
argComponents := strings.Split(arg, "=")
return strings.TrimLeft(argComponents[0], "-"), strings.Join(argComponents[1:], "=")
} else {
return strings.TrimLeft(arg, "-"), ""
}
}
// setFlag attempts to set a flag in the parse result. The input index is the
// result's position in the semantic stack. This function returns an error if
// the flag is set multiple times.
func (ap *argParser) setFlag(ndx int, flag *Flag) error {
if _, ok := ap.semanticStack[ndx].flags[flag.name]; ok {
return fmt.Errorf("flag `%s` set multiple times", flag.name)
}
ap.semanticStack[ndx].flags[flag.name] = struct{}{}
if flag.action != nil {
flag.action()
}
return nil
}
// setArg attempts to set the value for an argument in the parse result.
// The input index is the result's position in the semantic stack.
func (ap *argParser) setArg(ndx int, arg Argument, value string) error {
if _, ok := ap.semanticStack[ndx].Arguments[arg.Name()]; ok {
return fmt.Errorf("argument `%s` set multiple times", arg.Name())
}
val, err := arg.checkValue(value)
if err == nil {
ap.semanticStack[ndx].Arguments[arg.Name()] = val
return nil
}
return err
}
// currCommand returns the command on top of the command stack
func (ap *argParser) currCommand() *Command {
return ap.commandStack[len(ap.commandStack)-1]
}
// currResult returns the result on top of the semantic stack
func (ap *argParser) currResult() *ArgParseResult {
return ap.semanticStack[len(ap.semanticStack)-1]
}
| 31.757322 | 143 | 0.678261 |
049c94dfb221b19f02f60e942ba7b96ee3429bb0 | 4,932 | java | Java | src/main/java/com/dynatrace/oneagent/sdk/impl/noop/OneAgentSDKNoop.java | Dynatrace/OneAgent-ADK-Java | 398d7e84679e25cbcc0bc2f9583c0f078625b147 | [
"Apache-2.0"
] | 25 | 2018-01-29T07:27:49.000Z | 2022-02-16T03:11:42.000Z | src/main/java/com/dynatrace/oneagent/sdk/impl/noop/OneAgentSDKNoop.java | Dynatrace/OneAgent-ADK-Java | 398d7e84679e25cbcc0bc2f9583c0f078625b147 | [
"Apache-2.0"
] | 6 | 2018-02-05T17:36:58.000Z | 2021-10-20T15:05:45.000Z | src/main/java/com/dynatrace/oneagent/sdk/impl/noop/OneAgentSDKNoop.java | Dynatrace/OneAgent-ADK-Java | 398d7e84679e25cbcc0bc2f9583c0f078625b147 | [
"Apache-2.0"
] | 9 | 2018-05-09T05:58:08.000Z | 2022-03-29T12:10:14.000Z | /*
* Copyright 2021 Dynatrace LLC
*
* 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 com.dynatrace.oneagent.sdk.impl.noop;
import com.dynatrace.oneagent.sdk.api.CustomServiceTracer;
import com.dynatrace.oneagent.sdk.api.DatabaseRequestTracer;
import com.dynatrace.oneagent.sdk.api.InProcessLink;
import com.dynatrace.oneagent.sdk.api.InProcessLinkTracer;
import com.dynatrace.oneagent.sdk.api.IncomingMessageProcessTracer;
import com.dynatrace.oneagent.sdk.api.IncomingMessageReceiveTracer;
import com.dynatrace.oneagent.sdk.api.IncomingRemoteCallTracer;
import com.dynatrace.oneagent.sdk.api.IncomingWebRequestTracer;
import com.dynatrace.oneagent.sdk.api.LoggingCallback;
import com.dynatrace.oneagent.sdk.api.OneAgentSDK;
import com.dynatrace.oneagent.sdk.api.OutgoingMessageTracer;
import com.dynatrace.oneagent.sdk.api.OutgoingRemoteCallTracer;
import com.dynatrace.oneagent.sdk.api.OutgoingWebRequestTracer;
import com.dynatrace.oneagent.sdk.api.enums.ChannelType;
import com.dynatrace.oneagent.sdk.api.enums.MessageDestinationType;
import com.dynatrace.oneagent.sdk.api.enums.SDKState;
import com.dynatrace.oneagent.sdk.api.infos.DatabaseInfo;
import com.dynatrace.oneagent.sdk.api.infos.MessagingSystemInfo;
import com.dynatrace.oneagent.sdk.api.infos.WebApplicationInfo;
/**
* This class provides an empty (NOOP) implementation of the {@link OneAgentSDK}
* interface.
*
* @author Alram.Lechner
*
*/
public final class OneAgentSDKNoop implements OneAgentSDK {
// ***** Webrequests (incoming) *****
@Override
public WebApplicationInfo createWebApplicationInfo(String webServerName, String applicationID, String contextRoot) {
return WebApplicationInfoNoop.INSTANCE;
}
@Override
public IncomingWebRequestTracer traceIncomingWebRequest(WebApplicationInfo webApplicationInfo, String url,
String method) {
return IncomingWebRequestTracerNoop.INSTANCE;
}
// ***** Remote Calls (outgoing & incoming) *****
@Override
public IncomingRemoteCallTracer traceIncomingRemoteCall(String remoteMethod, String remoteService,
String clientEndpoint) {
return RemoteCallServerTracerNoop.INSTANCE;
}
@Override
public OutgoingRemoteCallTracer traceOutgoingRemoteCall(String remoteMethod, String remoteService,
String serviceEndpoint, ChannelType channelType, String channelEndpoint) {
return RemoteCallClientTracerNoop.INSTANCE;
}
// ***** Common *****
@Override
public void setLoggingCallback(LoggingCallback loggingCallback) {
}
@Override
public SDKState getCurrentState() {
return SDKState.PERMANENTLY_INACTIVE;
}
@Override
public InProcessLink createInProcessLink() {
return InProcessLinkNoop.INSTANCE;
}
@Override
public InProcessLinkTracer traceInProcessLink(InProcessLink inProcessLink) {
return InProcessLinkTracerNoop.INSTANCE;
}
@Override
public void addCustomRequestAttribute(String key, String value) {
}
@Override
public void addCustomRequestAttribute(String key, long value) {
}
@Override
public void addCustomRequestAttribute(String key, double value) {
}
@Override
public OutgoingWebRequestTracer traceOutgoingWebRequest(String url, String method) {
return OutgoingWebRequestTracerNoop.INSTANCE;
}
@Override
public MessagingSystemInfo createMessagingSystemInfo(String vendorName, String destinationName,
MessageDestinationType destinationType, ChannelType channelType, String channelEndpoint) {
return MessagingSystemInfoNoop.INSTANCE;
}
@Override
public OutgoingMessageTracer traceOutgoingMessage(MessagingSystemInfo messagingSystem) {
return OutgoingMessageTracerNoop.INSTANCE;
}
@Override
public IncomingMessageReceiveTracer traceIncomingMessageReceive(MessagingSystemInfo messagingSystem) {
return IncomingMessageReceiveTracerNoop.INSTANCE;
}
@Override
public IncomingMessageProcessTracer traceIncomingMessageProcess(MessagingSystemInfo messagingSystem) {
return IncomingMessageProcessTracerNoop.INSTANCE;
}
@Override
public DatabaseInfo createDatabaseInfo(String name, String vendor, ChannelType channelType,
String channelEndpoint) {
return DatabaseInfoNoop.INSTANCE;
}
@Override
public DatabaseRequestTracer traceSqlDatabaseRequest(DatabaseInfo databaseInfo, String statement) {
return DatabaseRequestTracerNoop.INSTANCE;
}
@Override
public CustomServiceTracer traceCustomService(String serviceMethod, String serviceName) {
return CustomServiceTracerNoop.INSTANCE;
}
}
| 33.55102 | 117 | 0.813869 |
fd6cf219aca15f16f8d21809cc2a7cbe0a96ffb6 | 1,164 | h | C | src/xg/image_loader.h | kctan0805/xg | 2935d0c7dac442b007cbf50b81ecd10a470dd087 | [
"MIT"
] | 6 | 2019-12-05T08:01:54.000Z | 2019-12-14T09:37:11.000Z | src/xg/image_loader.h | kctan0805/xg | 2935d0c7dac442b007cbf50b81ecd10a470dd087 | [
"MIT"
] | null | null | null | src/xg/image_loader.h | kctan0805/xg | 2935d0c7dac442b007cbf50b81ecd10a470dd087 | [
"MIT"
] | 1 | 2019-12-05T22:55:22.000Z | 2019-12-05T22:55:22.000Z | // xg - XML Graphics Engine
// Copyright (c) Jim Tan
//
// Free use of the XML Graphics Engine is
// permitted under the guidelines and in accordance with the most
// current version of the MIT License.
// http://www.opensource.org/licenses/MIT
#ifndef XG_IMAGE_LOADER_H_
#define XG_IMAGE_LOADER_H_
#include <memory>
#include <string>
#include "xg/layout.h"
#include "xg/queue.h"
#include "xg/resource_loader.h"
#include "xg/types.h"
namespace xg {
struct ImageLoaderInfo {
std::string file_path;
void* src_ptr = nullptr;
size_t size = static_cast<size_t>(-1);
LayoutImage* limage = nullptr;
AccessFlags dst_access_mask = AccessFlags::kShaderRead;
ImageLayout new_layout = ImageLayout::kShaderReadOnlyOptimal;
Queue* dst_queue = nullptr;
PipelineStageFlags dst_stage_mask = PipelineStageFlags::kFragmentShader;
};
class ImageLoader : public ResourceLoader {
public:
static std::shared_ptr<ImageLoader> Load(const ImageLoaderInfo& info);
void Run(std::shared_ptr<Task> self) override;
const ImageLoaderInfo& GetInfo() const { return info_; }
protected:
ImageLoaderInfo info_;
};
} // namespace xg
#endif // XG_IMAGE_LOADER_H_
| 24.25 | 74 | 0.750859 |
70e74019c7e0c8aa64d5da758c9ff6403aa7c8a1 | 443 | cshtml | C# | Pizzaslice.Client/Views/Locations/ViewSelectedLocation.cshtml | felixwafula/project-1-Pizzaslice | bc3b2dfc03ff1b6b66dc26e881e75c766ac4ca2d | [
"MIT"
] | null | null | null | Pizzaslice.Client/Views/Locations/ViewSelectedLocation.cshtml | felixwafula/project-1-Pizzaslice | bc3b2dfc03ff1b6b66dc26e881e75c766ac4ca2d | [
"MIT"
] | null | null | null | Pizzaslice.Client/Views/Locations/ViewSelectedLocation.cshtml | felixwafula/project-1-Pizzaslice | bc3b2dfc03ff1b6b66dc26e881e75c766ac4ca2d | [
"MIT"
] | null | null | null | @model Pizzaslice.Domain.Models.Location;
<h2>Welcome to Pizzaslice! You chose this store:</h2>
@{
ViewBag.Title = "ViewSelectedLocation";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@Model.LocationId</h2>
<h2>@Model.LocationName</h2>
<h2>@Model.LocationAddress</h2>
<h2>@Model.LocationZipCode</h2>
<h2><a class="nav-link text-dark" asp-area="" asp-controller="Pizzas" asp-action="CreatePizza">Now Lets Make a Pizza!</a></h2>
| 26.058824 | 126 | 0.708804 |
21475592ead3f66385749825ecdbc192dccd8fcf | 1,522 | sql | SQL | sql/04_queries.sql | nicho90/GIITDE | f0319e65f1d33d64affd69f83003346b38027f02 | [
"MIT"
] | null | null | null | sql/04_queries.sql | nicho90/GIITDE | f0319e65f1d33d64affd69f83003346b38027f02 | [
"MIT"
] | null | null | null | sql/04_queries.sql | nicho90/GIITDE | f0319e65f1d33d64affd69f83003346b38027f02 | [
"MIT"
] | null | null | null | -- LIST ALL TRASH BINS
SELECT
trash_bin_id,
created,
updated,
description,
filling_height,
'CENTIMETER' AS filling_height_unit,
capacity,
'LITER' AS capacity_unit,
ST_X(coordinates::geometry) AS lng,
ST_Y(coordinates::geometry) AS lat
FROM Trash_Bins ORDER BY trash_bin_id ASC;
-- LIST ALL NEARBY TRASH BINS
SELECT
trash_bin_id,
created,
updated,
description,
filling_height,
'CENTIMETER' AS filling_height_unit,
capacity,
'LITER' AS capacity_unit,
ST_X(coordinates::geometry) AS lng,
ST_Y(coordinates::geometry) AS lat,
ST_Distance(coordinates, ST_GeographyFromText('POINT(7.603001 51.969037)')) AS distance, -- Kreuzung
'METER' AS distance_unit
FROM Trash_Bins ORDER BY distance ASC;
-- GET A TRASH BIN BY ITS ID
SELECT
trash_bin_id,
created,
updated,
description,
filling_height,
'CENTIMETER' AS filling_height_unit,
capacity,
'LITER' AS capacity_unit,
ST_X(coordinates::geometry) AS lng,
ST_Y(coordinates::geometry) AS lat
FROM Trash_Bins WHERE trash_bin_id=1;
-- EDIT A TRASH BIN BY ITS ID
UPDATE Trash_Bins SET
updated=now(),
description='GEO-1',
filling_height=60,
capacity=60,
coordinates='POINT(7.595934 51.969148)'
WHERE trash_bin_id=1;
-- ADD A NEW TRASH BIN
INSERT INTO Trash_Bins (description, filling_height, capacity, coordinates) VALUES ('TEST', 0, 0, 'POINT(0.0 0.0)');
-- DELETE A TRASH BIN BY ITS ID
DELETE FROM Trash_Bins WHERE trash_bin_id=4;
| 23.78125 | 116 | 0.704336 |
b05390f92f2d8c2af4e13ee0000907c625b06150 | 4,967 | html | HTML | metalacc/website/templates/app_report_cash_flow_statement.html | stricoff92/metalaccounting | 6c9f650b3dd3c74c3ebbe847e0c05bb233e14153 | [
"MIT"
] | null | null | null | metalacc/website/templates/app_report_cash_flow_statement.html | stricoff92/metalaccounting | 6c9f650b3dd3c74c3ebbe847e0c05bb233e14153 | [
"MIT"
] | 3 | 2021-03-30T14:01:37.000Z | 2021-06-10T19:46:42.000Z | metalacc/website/templates/app_report_cash_flow_statement.html | stricoff92/metalaccounting | 6c9f650b3dd3c74c3ebbe847e0c05bb233e14153 | [
"MIT"
] | null | null | null | {% extends 'base_app.html' %}
{% load humanize %}
{% block 'body' %}
<div>
<p class="heading-1">Statement of Cash Flows</p>
<p class="heading-2">{{ period.company.name }}</p>
<p>
For Period
<strong>{{ period.start|date:"M j, Y" }}</strong>
<i class="fas fa-arrow-right"></i>
<strong>{{ period.end|date:"M j, Y" }}</strong>
</p>
</div>
<div class="mt-5" style="display:flex;">
<button class="btn btn-primary" id="reset-worksheet-btn">
<strong>Reset Worksheet</strong>
</button>
<a href="/app/period/{{ period.slug }}/statement-of-cash-flows/worksheet/" {{ user.userprofile.target_attr }} class="ml-4">
Cash Flow Worksheet
</a>
</div>
<script>
$(document).ready(()=>{
$("#reset-worksheet-btn").click(()=>{
postJson(resetCashFlowWorksheetUrl("{{ period.slug }}"), {},
(data, status, xhr)=>{
if(xhr.status == 204) {
window.location = "/app/period/{{ period.slug }}/statement-of-cash-flows/worksheet/?stoast=Worksheet Reset"
}
},
(data, status, xhr)=>{
alert("an error occured")
})
})
})
</script>
<div class="mt-5 pt-3">
<div class="row report-row p-2">
<div class="col-8">
<strong>Cash Balance as of {{ period.start|date:"M j, Y" }}</strong>
</div>
<div class="col-3">
{{ cashflow_data.previous_cash_balance|intcomma }}
</div>
</div>
<div class="row report-row p-2 border-bottom">
<div class="col-8">
Net Income
</div>
<div class="col-3">
{{ cashflow_data.income_data.net_income|intcomma }}
</div>
</div>
<div class="row mt-4">
<div class="col-8">
<p class="heading-3 mb-1">Cash Flow From Operating Activities</p>
</div>
<div class="col-3">
</div>
</div>
<div class="row report-row p-2">
<div class="col-8">
Sources of Cash
</div>
<div class="col-3">
{{ cashflow_data.cash_from_operations|intcomma }}
</div>
</div>
<div class="row report-row p-2">
<div class="col-8">
Uses of Cash
</div>
<div class="col-3">
{{ cashflow_data.cash_for_operations|intcomma }}
</div>
</div>
<div class="row report-row p-2">
<div class="col-8">
Net Cash from Operating Activities
</div>
<div class="col-3">
{{ cashflow_data.net_cash_from_operations|intcomma }}
</div>
</div>
<div class="row mt-4">
<div class="col-8">
<p class="heading-3 mb-1">Cash Flow From Investment Activities</p>
</div>
<div class="col-3">
</div>
</div>
<div class="row report-row p-2">
<div class="col-8">
Sources of Cash
</div>
<div class="col-3">
{{ cashflow_data.cash_from_investments|intcomma }}
</div>
</div>
<div class="row report-row p-2">
<div class="col-8">
Uses of Cash
</div>
<div class="col-3">
{{ cashflow_data.cash_for_investments|intcomma }}
</div>
</div>
<div class="row report-row p-2">
<div class="col-8">
Net Cash from Investment Activities
</div>
<div class="col-3">
{{ cashflow_data.net_cash_from_investments|intcomma }}
</div>
</div>
<div class="row mt-4">
<div class="col-8">
<p class="heading-3 mb-1">Cash Flow From Financing Activities</p>
</div>
<div class="col-3">
</div>
</div>
<div class="row report-row p-2">
<div class="col-8">
Sources of Cash
</div>
<div class="col-3">
{{ cashflow_data.cash_from_financing|intcomma }}
</div>
</div>
<div class="row report-row p-2">
<div class="col-8">
Uses of Cash
</div>
<div class="col-3">
{{ cashflow_data.cash_for_financing|intcomma }}
</div>
</div>
<div class="row report-row p-2">
<div class="col-8">
Net Cash from Financing Activities
</div>
<div class="col-3">
{{ cashflow_data.net_cash_from_financing|intcomma }}
</div>
</div>
<div class="row report-row p-2 mt-4 border-top">
<div class="col-8">
Net Cash
</div>
<div class="col-3">
{{ cashflow_data.net_cash|intcomma }}
</div>
</div>
<div class="row report-row p-2">
<div class="col-8">
<strong>Cash Balance as of {{ period.end|date:"M j, Y" }}</strong>
</div>
<div class="col-3">
{{ cashflow_data.current_cash_balance|intcomma }}
</div>
</div>
</div>
{% endblock %}
| 29.046784 | 127 | 0.502114 |
705bd00adeebc710a774ba6a276a50d2fc2a1c12 | 396 | sql | SQL | src/test/resources/wal2.test_56.sql | jdkoren/sqlite-parser | 9adf75ff5eca36f6e541594d2e062349f9ced654 | [
"MIT"
] | 131 | 2015-03-31T18:59:14.000Z | 2022-03-09T09:51:06.000Z | src/test/resources/wal2.test_56.sql | jdkoren/sqlite-parser | 9adf75ff5eca36f6e541594d2e062349f9ced654 | [
"MIT"
] | 20 | 2015-03-31T21:35:38.000Z | 2018-07-02T16:15:51.000Z | src/test/resources/wal2.test_56.sql | jdkoren/sqlite-parser | 9adf75ff5eca36f6e541594d2e062349f9ced654 | [
"MIT"
] | 43 | 2015-04-28T02:01:55.000Z | 2021-06-06T09:33:38.000Z | -- wal2.test
--
-- execsql {
-- PRAGMA auto_vacuum=OFF;
-- PRAGMA page_size = 1024;
-- PRAGMA journal_mode = WAL;
-- CREATE TABLE t1(x);
-- INSERT INTO t1 VALUES(zeroblob(8188*1020));
-- CREATE TABLE t2(y);
-- }
PRAGMA auto_vacuum=OFF;
PRAGMA page_size = 1024;
PRAGMA journal_mode = WAL;
CREATE TABLE t1(x);
INSERT INTO t1 VALUES(zeroblob(8188*1020));
CREATE TABLE t2(y); | 24.75 | 50 | 0.65404 |
6f64e85142e7b8e4ab2af55291b4d8d40f56396e | 133 | psd1 | PowerShell | Examples/Private/Initialize-ePOConfig/Initialize-ePOConfig.Connect With Https.psd1 | Vertigion/ePOwerShell | e5b441668fb4a849170317a7e22bea8bd3164048 | [
"MIT"
] | 23 | 2018-08-23T04:34:14.000Z | 2021-02-19T15:10:02.000Z | Examples/Private/Initialize-ePOConfig/Initialize-ePOConfig.Connect With Https.psd1 | Vertigion/ePOwerShell | e5b441668fb4a849170317a7e22bea8bd3164048 | [
"MIT"
] | 23 | 2018-08-16T22:05:55.000Z | 2020-07-27T17:04:36.000Z | Examples/Private/Initialize-ePOConfig/Initialize-ePOConfig.Connect With Https.psd1 | Vertigion/ePOwerShell | e5b441668fb4a849170317a7e22bea8bd3164048 | [
"MIT"
] | 12 | 2018-07-24T15:08:44.000Z | 2022-01-05T10:16:30.000Z | @{
Port = '1234'
Server = 'http://Test-ePO-Server.com'
Username = 'domain\username'
Password = 'SomePassword'
} | 22.166667 | 43 | 0.571429 |
9c3ecc94c4995ecf4fdc723a0817e9b4a93379f4 | 1,520 | sql | SQL | web/dbWebSource/procedures_functions/refuel_upd.sql | zettasolutions/zsi-fmis | fc35ae309a55db663ed2cbf5c156b8937c544cd7 | [
"MIT"
] | null | null | null | web/dbWebSource/procedures_functions/refuel_upd.sql | zettasolutions/zsi-fmis | fc35ae309a55db663ed2cbf5c156b8937c544cd7 | [
"MIT"
] | 2 | 2021-05-08T23:02:28.000Z | 2021-05-11T14:17:29.000Z | web/dbWebSource/procedures_functions/refuel_upd.sql | zettasolutions/zsi-fmis | fc35ae309a55db663ed2cbf5c156b8937c544cd7 | [
"MIT"
] | 3 | 2019-11-20T14:33:06.000Z | 2021-01-09T00:46:07.000Z | CREATE procedure [dbo].[refuel_upd](
@tt refuel_transactions_tt readonly
,@user_id int=null
)
as
BEGIN
SET NOCOUNT ON
UPDATE a SET
doc_no = b.doc_no
,doc_date = b.doc_date
,vehicle_id = b.vehicle_id
,driver_id = b.driver_id
,pao_id = b.pao_id
,odo_reading = b.odo_reading
,gas_station_id = b.gas_station_id
,no_liters = b.no_liters
,unit_price = b.unit_price
,refuel_amount = (b.no_liters * b.unit_price)
,updated_by = @user_id
,updated_date = GETDATE()
FROM dbo.refuel_transactions a inner join @tt b
ON a.refuel_id = b.refuel_id
AND ISNULL(b.is_edited,'N')='Y'
AND ISNULL(b.doc_no,'') <> ''
AND ISNULL(b.doc_DATE,'') <> ''
AND ISNULL(b.vehicle_id,0) <> 0
AND ISNULL(b.no_liters,0) <> 0
AND ISNULL(b.unit_price,0) <> 0
INSERT INTO dbo.refuel_transactions
(
doc_no
,doc_date
,vehicle_id
,driver_id
,pao_id
,odo_reading
,gas_station_id
,no_liters
,unit_price
,refuel_amount
,created_by
,created_date
)
SELECT
doc_no
,doc_date
,vehicle_id
,driver_id
,pao_id
,odo_reading
,gas_station_id
,no_liters
,unit_price
,no_liters * unit_price
,@user_id
,GETDATE()
FROM @tt
WHERE ISNULL(refuel_id,0) = 0
AND ISNULL(doc_no,'') <> ''
AND ISNULL(doc_DATE,'') <> ''
AND ISNULL(vehicle_id,0) <> 0
AND ISNULL(no_liters,0) <> 0
AND ISNULL(unit_price,0) <> 0
END;
| 19.240506 | 57 | 0.609211 |
98a8b3da81f70c9539b55d6f51dbfa9fc5cf183b | 1,498 | html | HTML | webrtc-svc/RTCRtpParameters-scalability.html | ziransun/wpt | ab8f451eb39eb198584d547f5d965ef54df2a86a | [
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | webrtc-svc/RTCRtpParameters-scalability.html | ziransun/wpt | ab8f451eb39eb198584d547f5d965ef54df2a86a | [
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | webrtc-svc/RTCRtpParameters-scalability.html | ziransun/wpt | ab8f451eb39eb198584d547f5d965ef54df2a86a | [
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | <!doctype html>
<meta charset=utf-8>
<title>RTCRtpParameters encodings</title>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/webrtc/dictionary-helper.js"></script>
<script src="/webrtc/RTCRtpParameters-helper.js"></script>
<script>
'use strict';
// Test is based on the following editor draft:
// https://w3c.github.io/webrtc-svc/
// Get the first encoding in param.encodings.
// Asserts that param.encodings has at least one element.
function getFirstEncoding(param) {
const { encodings } = param;
assert_equals(encodings.length, 1);
return encodings[0];
}
promise_test(async t => {
const pc = new RTCPeerConnection();
t.add_cleanup(() => pc.close());
const { sender } = pc.addTransceiver('video', {
sendEncodings: [{scalabilityMode: 'L1T3'}],
});
const param = sender.getParameters();
const encoding = getFirstEncoding(param);
assert_equals(encoding.scalabilityMode, 'L1T3');
}, `Setting scalabilityMode to a legal value should be accepted`);
promise_test(async t => {
const capabilities = RTCRtpSender.getCapabilities('video');
var svcSupported = false;
for (const codec of capabilities.codecs) {
if ('scalabilityModes' in codec && codec.scalabilityModes.length > 0) {
svcSupported = true;
}
}
assert_true(svcSupported);
}, `Sender capabilities should include at least some scalability modes`);
</script>
| 31.208333 | 77 | 0.688919 |
5659f29d6292f4df72b84384ebc7dda11b27b64c | 2,354 | swift | Swift | AudioKitSynthOne/Audiobus/Audiobus+MIDI.swift | ForeverTangent/AudioKitSynthOne | f7d11d3a142d5e7015a3bffe8c2b6b0087652b1a | [
"MIT"
] | 3 | 2019-08-16T00:00:22.000Z | 2020-10-19T18:44:45.000Z | AudioKitSynthOne/Audiobus/Audiobus+MIDI.swift | gacky/AudioKitSynthOne | f7d11d3a142d5e7015a3bffe8c2b6b0087652b1a | [
"MIT"
] | 1 | 2019-02-21T11:08:36.000Z | 2019-02-21T11:08:36.000Z | AudioKitSynthOne/Audiobus/Audiobus+MIDI.swift | gacky/AudioKitSynthOne | f7d11d3a142d5e7015a3bffe8c2b6b0087652b1a | [
"MIT"
] | 4 | 2018-12-17T20:12:47.000Z | 2020-12-27T12:31:32.000Z | //
// Audiobus+MIDI.swift
// AudiobusMIDISender
//
// Created by Jeff Holtzkener on 2018/03/28.
// Copyright © 2018 Jeff Holtzkener. All rights reserved.
//
import Foundation
import AudioKit
extension Audiobus {
// MARK: - Preparations
class func addMIDISenderPort(_ port: ABMIDISenderPort) {
guard let client = client else {
print("need to start Audiobus")
return
}
client.controller.addMIDISenderPort(port)
}
class func setUpEnableCoreMIDIBlock(block: ((Bool) -> Void)!) {
guard let client = client else {
print("need to start Audiobus")
return
}
client.controller.enableSendingCoreMIDIBlock = block
}
// MARK: - Triggers
class func addTrigger(_ trigger: ABTrigger) {
guard let client = client else {
print("need to start Audiobus")
return
}
client.controller.add(trigger)
}
// MARK: - Send MIDI Messages
class func sendNoteOnMessage(midiSendPort: ABMIDISenderPort,
status: AKMIDIStatus,
note: MIDINoteNumber,
velocity: MIDIVelocity,
channel: MIDIChannel = 0) {
let noteCommand = MIDIByte(0x90) + channel
let data = [noteCommand, note, velocity]
sendMessage(midiSendPort: midiSendPort, data: data)
}
class func sendNoteOffMessage(midiSendPort: ABMIDISenderPort,
status: AKMIDIStatus,
note: MIDINoteNumber,
velocity: MIDIVelocity,
channel: MIDIChannel = 0) {
let noteCommand = MIDIByte(0x80) + channel
let data = [noteCommand, note, velocity]
sendMessage(midiSendPort: midiSendPort, data: data)
}
class func sendMessage(midiSendPort: ABMIDISenderPort, data: [MIDIByte]) {
let packetListPointer: UnsafeMutablePointer<MIDIPacketList> = UnsafeMutablePointer.allocate(capacity: 1)
var packet = MIDIPacketListInit(packetListPointer)
packet = MIDIPacketListAdd(packetListPointer, 1_024, packet, 0, data.count, data)
ABMIDIPortSendPacketList(midiSendPort, UnsafePointer(packetListPointer))
}
}
| 33.628571 | 112 | 0.596856 |
0b84b4636dfd6d734d772cca8a444833fce6d004 | 221 | py | Python | Modulo_1/semana2/variables_contantes/sentencia-global.py | rubens233/cocid_python | 492ebdf21817e693e5eb330ee006397272f2e0cc | [
"MIT"
] | null | null | null | Modulo_1/semana2/variables_contantes/sentencia-global.py | rubens233/cocid_python | 492ebdf21817e693e5eb330ee006397272f2e0cc | [
"MIT"
] | null | null | null | Modulo_1/semana2/variables_contantes/sentencia-global.py | rubens233/cocid_python | 492ebdf21817e693e5eb330ee006397272f2e0cc | [
"MIT"
] | 1 | 2022-03-04T00:57:18.000Z | 2022-03-04T00:57:18.000Z | variable1 = "variable original"
def variable_global():
global variable1
variable1 = "variable global modificada"
print(variable1)
#variable original
variable_global()
print(variable1)
#variable global modificada
| 20.090909 | 44 | 0.78733 |
c43a39c40b44ae16af2dc7693503641f1447cfb5 | 15,495 | h | C | libs/rvo2_3d/RVOSimulator.h | senthilarul/d-orca | bea510de44daf9d8422ce01d8dc5aca43b8e5dd3 | [
"BSD-3-Clause"
] | null | null | null | libs/rvo2_3d/RVOSimulator.h | senthilarul/d-orca | bea510de44daf9d8422ce01d8dc5aca43b8e5dd3 | [
"BSD-3-Clause"
] | null | null | null | libs/rvo2_3d/RVOSimulator.h | senthilarul/d-orca | bea510de44daf9d8422ce01d8dc5aca43b8e5dd3 | [
"BSD-3-Clause"
] | null | null | null | /*
* RVOSimulator.h
* RVO2-3D Library
*
* Copyright 2008 University of North Carolina at Chapel Hill
*
* 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.
*
* Please send all bug reports to <geom@cs.unc.edu>.
*
* The authors may be contacted via:
*
* Jur van den Berg, Stephen J. Guy, Jamie Snape, Ming C. Lin, Dinesh Manocha
* Dept. of Computer Science
* 201 S. Columbia St.
* Frederick P. Brooks, Jr. Computer Science Bldg.
* Chapel Hill, N.C. 27599-3175
* United States of America
*
* <http://gamma.cs.unc.edu/RVO2/>
*/
/**
* \file RVOSimulator.h
* \brief Contains the RVOSimulator class.
*/
#ifndef RVO_RVO_SIMULATOR_H_
#define RVO_RVO_SIMULATOR_H_
#include "API.h"
#include <cstddef>
#include <limits>
#include <vector>
#include "Vector3.h"
// Static Collision Avoidance
#include "pqp/PQP.h"
#include "tiny_obj_loader.h"
#include <iostream>
#include "ros/ros.h"
#include "ros/package.h"
namespace RVO {
class Agent;
class KdTree;
/**
* \brief Error value.
*
* A value equal to the largest unsigned integer, which is returned in case of an error by functions in RVO::RVOSimulator.
*/
const size_t RVO_ERROR = std::numeric_limits<size_t>::max();
/**
* \brief Defines a plane.
*/
class Plane {
public:
/**
* \brief A point on the plane.
*/
Vector3 point;
/**
* \brief The normal to the plane.
*/
Vector3 normal;
};
/**
* \brief Defines the simulation.
*
* The main class of the library that contains all simulation functionality.
*/
class RVOSimulator {
public:
/**
* \brief Constructs a simulator instance.
*/
RVO_API RVOSimulator();
/**
* \brief Constructs a simulator instance and sets the default properties for any new agent that is added.
* \param timeStep The time step of the simulation. Must be positive.
* \param neighborDist The default maximum distance (center point to center point) to other agents a new agent takes into account in the navigation. The larger this number, the longer he running time of the simulation. If the number is too low, the simulation will not be safe. Must be non-negative.
* \param maxNeighbors The default maximum number of other agents a new agent takes into account in the navigation. The larger this number, the longer the running time of the simulation. If the number is too low, the simulation will not be safe.
* \param timeHorizon The default minimum amount of time for which a new agent's velocities that are computed by the simulation are safe with respect to other agents. The larger this number, the sooner an agent will respond to the presence of other agents, but the less freedom the agent has in choosing its velocities. Must be positive.
* \param radius The default radius of a new agent. Must be non-negative.
* \param maxSpeed The default maximum speed of a new agent. Must be non-negative.
* \param velocity The default initial three-dimensional linear velocity of a new agent (optional).
*/
RVO_API RVOSimulator(float timeStep, float neighborDist, size_t maxNeighbors, float timeHorizon, float radius, float maxSpeed, const Vector3 &velocity = Vector3());
/**
* \brief Destroys this simulator instance.
*/
RVO_API ~RVOSimulator();
/**
* \brief Adds a new agent with default properties to the simulation.
* \param position The three-dimensional starting position of this agent.
* \return The number of the agent, or RVO::RVO_ERROR when the agent defaults have not been set.
*/
RVO_API size_t addAgent(const Vector3 &position);
/**
* \brief Adds a new agent to the simulation.
* \param position The three-dimensional starting position of this agent.
* \param neighborDist The maximum distance (center point to center point) to other agents this agent takes into account in the navigation. The larger this number, the longer the running time of the simulation. If the number is too low, the simulation will not be safe. Must be non-negative.
* \param maxNeighbors The maximum number of other agents this agent takes into account in the navigation. The larger this number, the longer the running time of the simulation. If the number is too low, the simulation will not be safe.
* \param timeHorizon The minimum amount of time for which this agent's velocities that are computed by the simulation are safe with respect to other agents. The larger this number, the sooner this agent will respond to the presence of other agents, but the less freedom this agent has in choosing its velocities. Must be positive.
* \param radius The radius of this agent. Must be non-negative.
* \param maxSpeed The maximum speed of this agent. Must be non-negative.
* \param velocity The initial three-dimensional linear velocity of this agent (optional).
* \return The number of the agent.
*/
RVO_API size_t addAgent(const Vector3 &position, float neighborDist, size_t maxNeighbors, float timeHorizon, float radius, float maxSpeed, const Vector3 &velocity = Vector3());
/**
* \brief Lets the simulator perform a simulation step and updates the three-dimensional position and three-dimensional velocity of each agent.
*/
RVO_API void doStep();
/**
* \brief Returns the specified agent neighbor of the specified agent.
* \param agentNo The number of the agent whose agent neighbor is to be retrieved.
* \param neighborNo The number of the agent neighbor to be retrieved.
* \return The number of the neighboring agent.
*/
RVO_API size_t getAgentAgentNeighbor(size_t agentNo, size_t neighborNo) const;
/**
* \brief Returns the maximum neighbor count of a specified agent.
* \param agentNo The number of the agent whose maximum neighbor count is to be retrieved.
* \return The present maximum neighbor count of the agent.
*/
RVO_API size_t getAgentMaxNeighbors(size_t agentNo) const;
/**
* \brief Returns the maximum speed of a specified agent.
* \param agentNo The number of the agent whose maximum speed is to be retrieved.
* \return The present maximum speed of the agent.
*/
RVO_API float getAgentMaxSpeed(size_t agentNo) const;
/**
* \brief Returns the maximum neighbor distance of a specified agent.
* \param agentNo The number of the agent whose maximum neighbor distance is to be retrieved.
* \return The present maximum neighbor distance of the agent.
*/
RVO_API float getAgentNeighborDist(size_t agentNo) const;
/**
* \brief Returns the count of agent neighbors taken into account to compute the current velocity for the specified agent.
* \param agentNo The number of the agent whose count of agent neighbors is to be retrieved.
* \return The count of agent neighbors taken into account to compute the current velocity for the specified agent.
*/
RVO_API size_t getAgentNumAgentNeighbors(size_t agentNo) const;
/**
* \brief Returns the count of ORCA constraints used to compute the current velocity for the specified agent.
* \param agentNo The number of the agent whose count of ORCA constraints is to be retrieved.
* \return The count of ORCA constraints used to compute the current velocity for the specified agent.
*/
RVO_API size_t getAgentNumORCAPlanes(size_t agentNo) const;
/**
* \brief Returns the specified ORCA constraint of the specified agent.
* \param agentNo The number of the agent whose ORCA constraint is to be retrieved.
* \param planeNo The number of the ORCA constraint to be retrieved.
* \return A plane representing the specified ORCA constraint.
* \note The halfspace to which the normal of the plane points is the region of permissible velocities with respect to the specified ORCA constraint.
*/
RVO_API const Plane &getAgentORCAPlane(size_t agentNo, size_t planeNo) const;
/**
* \brief Returns the three-dimensional position of a specified agent.
* \param agentNo The number of the agent whose three-dimensional position is to be retrieved.
* \return The present three-dimensional position of the (center of the) agent.
*/
RVO_API const Vector3 &getAgentPosition(size_t agentNo) const;
/**
* \brief Returns the three-dimensional preferred velocity of a specified agent.
* \param agentNo The number of the agent whose three-dimensional preferred velocity is to be retrieved.
* \return The present three-dimensional preferred velocity of the agent.
*/
RVO_API const Vector3 &getAgentPrefVelocity(size_t agentNo) const;
/**
* \brief Returns the radius of a specified agent.
* \param agentNo The number of the agent whose radius is to be retrieved.
* \return The present radius of the agent.
*/
RVO_API float getAgentRadius(size_t agentNo) const;
/**
* \brief Returns the time horizon of a specified agent.
* \param agentNo The number of the agent whose time horizon is to be retrieved.
* \return The present time horizon of the agent.
*/
RVO_API float getAgentTimeHorizon(size_t agentNo) const;
/**
* \brief Returns the three-dimensional linear velocity of a specified agent.
* \param agentNo The number of the agent whose three-dimensional linear velocity is to be retrieved.
* \return The present three-dimensional linear velocity of the agent.
*/
RVO_API const Vector3 &getAgentVelocity(size_t agentNo) const;
/**
* \brief Returns the global time of the simulation.
* \return The present global time of the simulation (zero initially).
*/
RVO_API float getGlobalTime() const;
/**
* \brief Returns the count of agents in the simulation.
* \return The count of agents in the simulation.
*/
RVO_API size_t getNumAgents() const;
/**
* \brief Returns the time step of the simulation.
* \return The present time step of the simulation.
*/
RVO_API float getTimeStep() const;
/**
* \brief Removes an agent from the simulation.
* \param agentNo The number of the agent that is to be removed.
* \note After the removal of the agent, the agent that previously had number getNumAgents() - 1 will now have number agentNo.
*/
RVO_API void removeAgent(size_t agentNo);
/**
* \brief Sets the default properties for any new agent that is added.
* \param neighborDist The default maximum distance (center point to center point) to other agents a new agent takes into account in the navigation. The larger this number, the longer he running time of the simulation. If the number is too low, the simulation will not be safe. Must be non-negative.
* \param maxNeighbors The default maximum number of other agents a new agent takes into account in the navigation. The larger this number, the longer the running time of the simulation. If the number is too low, the simulation will not be safe.
* \param timeHorizon The default minimum amount of time for which a new agent's velocities that are computed by the simulation are safe with respect to other agents. The larger this number, the sooner an agent will respond to the presence of other agents, but the less freedom the agent has in choosing its velocities. Must be positive.
* \param radius The default radius of a new agent. Must be non-negative.
* \param maxSpeed The default maximum speed of a new agent. Must be non-negative.
* \param velocity The default initial three-dimensional linear velocity of a new agent (optional).
*/
RVO_API void setAgentDefaults(float neighborDist, size_t maxNeighbors, float timeHorizon, float radius, float maxSpeed, const Vector3 &velocity = Vector3());
/**
* \brief Sets the maximum neighbor count of a specified agent.
* \param agentNo The number of the agent whose maximum neighbor count is to be modified.
* \param maxNeighbors The replacement maximum neighbor count.
*/
RVO_API void setAgentMaxNeighbors(size_t agentNo, size_t maxNeighbors);
/**
* \brief Sets the maximum speed of a specified agent.
* \param agentNo The number of the agent whose maximum speed is to be modified.
* \param maxSpeed The replacement maximum speed. Must be non-negative.
*/
RVO_API void setAgentMaxSpeed(size_t agentNo, float maxSpeed);
/**
* \brief Sets the maximum neighbor distance of a specified agent.
* \param agentNo The number of the agent whose maximum neighbor distance is to be modified.
* \param neighborDist The replacement maximum neighbor distance. Must be non-negative.
*/
RVO_API void setAgentNeighborDist(size_t agentNo, float neighborDist);
/**
* \brief Sets the three-dimensional position of a specified agent.
* \param agentNo The number of the agent whose three-dimensional position is to be modified.
* \param position The replacement of the three-dimensional position.
*/
RVO_API void setAgentPosition(size_t agentNo, const Vector3 &position);
/**
* \brief Sets the three-dimensional preferred velocity of a specified agent.
* \param agentNo The number of the agent whose three-dimensional preferred velocity is to be modified.
* \param prefVelocity The replacement of the three-dimensional preferred velocity.
*/
RVO_API void setAgentPrefVelocity(size_t agentNo, const Vector3 &prefVelocity);
/**
* \brief Sets the radius of a specified agent.
* \param agentNo The number of the agent whose radius is to be modified.
* \param radius The replacement radius. Must be non-negative.
*/
RVO_API void setAgentRadius(size_t agentNo, float radius);
/**
* \brief Sets the time horizon of a specified agent with respect to other agents.
* \param agentNo The number of the agent whose time horizon is to be modified.
* \param timeHorizon The replacement time horizon with respect to other agents. Must be positive.
*/
RVO_API void setAgentTimeHorizon(size_t agentNo, float timeHorizon);
/**
* \brief Sets the three-dimensional linear velocity of a specified agent.
* \param agentNo The number of the agent whose three-dimensional linear velocity is to be modified.
* \param velocity The replacement three-dimensional linear velocity.
*/
RVO_API void setAgentVelocity(size_t agentNo, const Vector3 &velocity);
/**
* \brief Sets the time step of the simulation.
* \param timeStep The time step of the simulation. Must be positive.
*/
RVO_API void setTimeStep(float timeStep);
/**
* \brief PQP model for the quadrotor (sphere).
*/
PQP_Model *b1 = new PQP_Model;
/**
* \brief PQP model for the Environment obstacles.
*/
PQP_Model *b2 = new PQP_Model;
private:
Agent *defaultAgent_;
KdTree *kdTree_;
float globalTime_;
float timeStep_;
std::vector<Agent *> agents_;
friend class Agent;
friend class KdTree;
};
}
#endif
| 44.913043 | 343 | 0.722491 |
dec2cbb561a4099b223a52424e3375e74dcb9ea3 | 184 | rs | Rust | src/domain/event.rs | rebus-rs/rebus | 34d9b2c5acd772c8e9cb55257520825b9172b96b | [
"MIT"
] | null | null | null | src/domain/event.rs | rebus-rs/rebus | 34d9b2c5acd772c8e9cb55257520825b9172b96b | [
"MIT"
] | null | null | null | src/domain/event.rs | rebus-rs/rebus | 34d9b2c5acd772c8e9cb55257520825b9172b96b | [
"MIT"
] | null | null | null | use std::collections::HashMap;
pub struct Event {
pub name: String,
pub params: HashMap<String, Value>,
}
pub enum Value {
String(String),
Int(i64),
Float(f64),
} | 15.333333 | 39 | 0.630435 |
90dce5877b2d84c704d4b43e9b4761454e404981 | 2,899 | py | Python | fairseq/data/tagged_dataset.py | kayoyin/DialogueMT | aa426ebcdbdfe0366ed06081a842945f2108e85f | [
"MIT"
] | null | null | null | fairseq/data/tagged_dataset.py | kayoyin/DialogueMT | aa426ebcdbdfe0366ed06081a842945f2108e85f | [
"MIT"
] | null | null | null | fairseq/data/tagged_dataset.py | kayoyin/DialogueMT | aa426ebcdbdfe0366ed06081a842945f2108e85f | [
"MIT"
] | null | null | null | import json
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
import sentencepiece as spm
from .import FairseqDataset
from .fairseq_dataset import TAG_DICT
from .indexed_dataset import IndexedRawTextDataset
from .collaters import Seq2SeqCollater
class TaggedDataset(IndexedRawTextDataset):
def __init__(self, path, dictionary, append_eos=True, reverse_order=False):
self.src_tokens = []
self.src_sizes = []
self.tgt_tokens = []
self.tgt_sizes = []
self.src = []
self.tgt = []
self.sizes = []
self.append_eos = append_eos
self.reverse_order = reverse_order
self.speakers = []
self.ids = []
self.dictionary = dictionary
self.read_data(path)
self.size = len(self.ids)
def read_data(self, path):
with open(path, 'r', encoding='utf-8') as f:
chat_dict = json.load(f)
for chat in chat_dict.values():
for turn in chat:
src = turn['source']
self.src.append(src)
src_tokens = torch.Tensor(self.dictionary.encode(src))
self.src_tokens.append(src_tokens)
self.src_sizes.append(len(src_tokens))
tgt = turn['target']
self.tgt.append(tgt)
tgt_tokens = torch.Tensor(self.dictionary.encode(tgt)).long()
self.tgt_tokens.append(tgt_tokens)
self.tgt_sizes.append(len(tgt_tokens))
self.speakers.append(turn['speaker'])
self.ids.append(turn['utteranceID'])
self.src_sizes = np.array(self.src_sizes)
self.tgt_sizes = np.array(self.tgt_sizes)
self.sizes = self.src_sizes
def __getitem__(self, idx):
src_speaker = torch.Tensor([self.dictionary.model.piece_to_id(TAG_DICT[self.speakers[idx]])])
source, target = torch.cat((torch.Tensor([self.dictionary.bos()]).long(), src_speaker.long(), self.src_tokens[idx].long(), torch.Tensor([self.dictionary.eos()]).long())) , torch.cat((torch.Tensor([self.dictionary.bos()]).long(), self.tgt_tokens[idx].long(), torch.Tensor([self.dictionary.eos()]).long()))
return {"id": idx, "source": source, "target": target}
def collater(self, samples):
collate_fn = Seq2SeqCollater(pad_index=self.dictionary.model.piece_to_id("<pad>"), eos_index=self.dictionary.model.piece_to_id("</s>"))
samples = collate_fn.collate(samples)
return samples
if __name__ == "__main__":
model = spm.SentencePieceProcessor(model_file="../../../data/wmtchat2020/spm.model")
dataset = TwoToOneDataset("../../../data/wmtchat2020/valid.json", model)
sample = dataset[5]
print(dataset.src[5])
print(spm.decode(sample["source"]))
print(dataset.tgt[5])
print(spm.decode(sample["target"])) | 38.653333 | 313 | 0.626423 |
1be749e27990aaaaeac8fcbdc7bdb727de221669 | 3,612 | py | Python | avod/builders/config_builder_util.py | ecward/avod | d13df44dbc24d718301cbb310ea7286e74f27c71 | [
"MIT"
] | null | null | null | avod/builders/config_builder_util.py | ecward/avod | d13df44dbc24d718301cbb310ea7286e74f27c71 | [
"MIT"
] | null | null | null | avod/builders/config_builder_util.py | ecward/avod | d13df44dbc24d718301cbb310ea7286e74f27c71 | [
"MIT"
] | null | null | null | """Config file reader utils."""
import os
import shutil
from google.protobuf import text_format
import avod
from avod.protos import model_pb2
from avod.protos import pipeline_pb2
class ConfigObj:
pass
def proto_to_obj(config):
"""Hack to convert proto config into an object so repeated fields can be
overwritten
Args:
config: proto config
Returns:
config_obj: object with same fields as the config
"""
all_fields = list(config.DESCRIPTOR.fields_by_name)
config_obj = ConfigObj()
for field in all_fields:
field_value = eval('config.{}'.format(field))
setattr(config_obj, field, field_value)
return config_obj
def get_model_config_from_file(config_path):
"""Reads model configuration from a configuration file.
This merges the layer config info with model default configs.
Args:
config_path: A path to the config
Returns:
layers_config: A configured model_pb2 config
"""
model_config = model_pb2.ModelConfig()
with open(config_path, 'r') as f:
text_format.Merge(f.read(), model_config)
return model_config
def get_configs_from_pipeline_file(pipeline_config_path,
is_training):
"""Reads model configuration from a pipeline_pb2.NetworkPipelineConfig.
Args:
pipeline_config_path: A path directory to the network pipeline config
is_training: A boolean flag to indicate training stage, used for
creating the checkpoint directory which must be created at the
first training iteration.
Returns:
model_config: A model_pb2.ModelConfig
train_config: A train_pb2.TrainConfig
eval_config: A eval_pb2.EvalConfig
dataset_config: A kitti_dataset_pb2.KittiDatasetConfig
"""
pipeline_config = pipeline_pb2.NetworkPipelineConfig()
with open(pipeline_config_path, 'r') as f:
text_format.Merge(f.read(), pipeline_config)
model_config = pipeline_config.model_config
# Make sure the checkpoint name matches the config filename
config_file_name = \
os.path.split(pipeline_config_path)[1].split('.')[0]
checkpoint_name = model_config.checkpoint_name
if config_file_name != checkpoint_name:
raise ValueError('Config and checkpoint names ('+str(config_file_name)+", "+str(checkpoint_name)+')must match.')
output_root_dir = avod.root_dir() + '/data/outputs/' + checkpoint_name
# Construct paths
paths_config = model_config.paths_config
if not paths_config.checkpoint_dir:
checkpoint_dir = output_root_dir + '/checkpoints'
if is_training:
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
paths_config.checkpoint_dir = checkpoint_dir
if not paths_config.logdir:
paths_config.logdir = output_root_dir + '/logs/'
if not paths_config.pred_dir:
paths_config.pred_dir = output_root_dir + '/predictions'
train_config = pipeline_config.train_config
eval_config = pipeline_config.eval_config
dataset_config = pipeline_config.dataset_config
if is_training:
# Copy the config to the experiments folder
experiment_config_path = output_root_dir + '/' +\
model_config.checkpoint_name
experiment_config_path += '.config'
# Copy this even if the config exists, in case some parameters
# were modified
shutil.copy(pipeline_config_path, experiment_config_path)
return model_config, train_config, eval_config, dataset_config
| 31.964602 | 120 | 0.70155 |
80e036a96d53cfb1d86857f8f8633bdd43e6c229 | 15,061 | java | Java | oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/RevisionGCStatsTest.java | sho25/jackrabbit-oak | 1bb8a341fdf907578298f9ed52a48458e4f6efdc | [
"Apache-2.0"
] | null | null | null | oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/RevisionGCStatsTest.java | sho25/jackrabbit-oak | 1bb8a341fdf907578298f9ed52a48458e4f6efdc | [
"Apache-2.0"
] | 2 | 2020-06-15T19:48:29.000Z | 2021-02-08T21:25:54.000Z | oak-store-document/src/test/java/org/apache/jackrabbit/oak/plugins/document/RevisionGCStatsTest.java | sho25/jackrabbit-oak | 1bb8a341fdf907578298f9ed52a48458e4f6efdc | [
"Apache-2.0"
] | null | null | null | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|plugins
operator|.
name|document
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|ScheduledExecutorService
import|;
end_import
begin_import
import|import
name|com
operator|.
name|codahale
operator|.
name|metrics
operator|.
name|Counter
import|;
end_import
begin_import
import|import
name|com
operator|.
name|codahale
operator|.
name|metrics
operator|.
name|Meter
import|;
end_import
begin_import
import|import
name|com
operator|.
name|codahale
operator|.
name|metrics
operator|.
name|Timer
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|commons
operator|.
name|concurrent
operator|.
name|ExecutorCloser
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|plugins
operator|.
name|document
operator|.
name|VersionGarbageCollector
operator|.
name|VersionGCStats
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|plugins
operator|.
name|metric
operator|.
name|MetricStatisticsProvider
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|After
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_import
import|import static
name|java
operator|.
name|lang
operator|.
name|management
operator|.
name|ManagementFactory
operator|.
name|getPlatformMBeanServer
import|;
end_import
begin_import
import|import static
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|Executors
operator|.
name|newSingleThreadScheduledExecutor
import|;
end_import
begin_import
import|import static
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|TimeUnit
operator|.
name|MILLISECONDS
import|;
end_import
begin_import
import|import static
name|java
operator|.
name|util
operator|.
name|concurrent
operator|.
name|TimeUnit
operator|.
name|NANOSECONDS
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|apache
operator|.
name|jackrabbit
operator|.
name|oak
operator|.
name|plugins
operator|.
name|document
operator|.
name|RevisionGCStats
operator|.
name|RGC
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertEquals
import|;
end_import
begin_import
import|import static
name|org
operator|.
name|junit
operator|.
name|Assert
operator|.
name|assertTrue
import|;
end_import
begin_class
specifier|public
class|class
name|RevisionGCStatsTest
block|{
specifier|private
name|ScheduledExecutorService
name|executor
init|=
name|newSingleThreadScheduledExecutor
argument_list|()
decl_stmt|;
specifier|private
name|MetricStatisticsProvider
name|statsProvider
init|=
operator|new
name|MetricStatisticsProvider
argument_list|(
name|getPlatformMBeanServer
argument_list|()
argument_list|,
name|executor
argument_list|)
decl_stmt|;
specifier|private
name|RevisionGCStats
name|stats
init|=
operator|new
name|RevisionGCStats
argument_list|(
name|statsProvider
argument_list|)
decl_stmt|;
annotation|@
name|After
specifier|public
name|void
name|shutDown
parameter_list|()
block|{
name|statsProvider
operator|.
name|close
argument_list|()
expr_stmt|;
operator|new
name|ExecutorCloser
argument_list|(
name|executor
argument_list|)
operator|.
name|close
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|getReadDocCount
parameter_list|()
block|{
name|Meter
name|m
init|=
name|getMeter
argument_list|(
name|RevisionGCStats
operator|.
name|READ_DOC
argument_list|)
decl_stmt|;
name|long
name|count
init|=
name|m
operator|.
name|getCount
argument_list|()
decl_stmt|;
name|stats
operator|.
name|documentRead
argument_list|()
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|1
argument_list|,
name|m
operator|.
name|getCount
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|1
argument_list|,
name|stats
operator|.
name|getReadDocCount
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|getDeletedDocCount
parameter_list|()
block|{
name|Meter
name|m
init|=
name|getMeter
argument_list|(
name|RevisionGCStats
operator|.
name|DELETE_DOC
argument_list|)
decl_stmt|;
name|long
name|count
init|=
name|m
operator|.
name|getCount
argument_list|()
decl_stmt|;
name|stats
operator|.
name|documentsDeleted
argument_list|(
literal|17
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|17
argument_list|,
name|m
operator|.
name|getCount
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|17
argument_list|,
name|stats
operator|.
name|getDeletedDocCount
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|getDeletedLeafDocCount
parameter_list|()
block|{
name|Meter
name|m
init|=
name|getMeter
argument_list|(
name|RevisionGCStats
operator|.
name|DELETE_LEAF_DOC
argument_list|)
decl_stmt|;
name|long
name|count
init|=
name|m
operator|.
name|getCount
argument_list|()
decl_stmt|;
name|stats
operator|.
name|leafDocumentsDeleted
argument_list|(
literal|17
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|17
argument_list|,
name|m
operator|.
name|getCount
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|17
argument_list|,
name|stats
operator|.
name|getDeletedLeafDocCount
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|getDeletedSplitDocCount
parameter_list|()
block|{
name|Meter
name|m
init|=
name|getMeter
argument_list|(
name|RevisionGCStats
operator|.
name|DELETE_SPLIT_DOC
argument_list|)
decl_stmt|;
name|long
name|count
init|=
name|m
operator|.
name|getCount
argument_list|()
decl_stmt|;
name|stats
operator|.
name|splitDocumentsDeleted
argument_list|(
literal|17
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|17
argument_list|,
name|m
operator|.
name|getCount
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|17
argument_list|,
name|stats
operator|.
name|getDeletedSplitDocCount
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|getDeletedIntSplitDocCount
parameter_list|()
block|{
name|Meter
name|m
init|=
name|getMeter
argument_list|(
name|RevisionGCStats
operator|.
name|DELETE_INT_SPLIT_DOC
argument_list|)
decl_stmt|;
name|long
name|count
init|=
name|m
operator|.
name|getCount
argument_list|()
decl_stmt|;
name|stats
operator|.
name|intermediateSplitDocumentsDeleted
argument_list|(
literal|17
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|17
argument_list|,
name|m
operator|.
name|getCount
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|17
argument_list|,
name|stats
operator|.
name|getDeletedIntSplitDocCount
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|getResetDeletedFlagCount
parameter_list|()
block|{
name|Meter
name|m
init|=
name|getMeter
argument_list|(
name|RevisionGCStats
operator|.
name|RESET_DELETED_FLAG
argument_list|)
decl_stmt|;
name|long
name|count
init|=
name|m
operator|.
name|getCount
argument_list|()
decl_stmt|;
name|stats
operator|.
name|deletedOnceFlagReset
argument_list|()
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|1
argument_list|,
name|m
operator|.
name|getCount
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
name|count
operator|+
literal|1
argument_list|,
name|stats
operator|.
name|getResetDeletedFlagCount
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|timers
parameter_list|()
block|{
name|VersionGCStats
name|vgcs
init|=
operator|new
name|VersionGCStats
argument_list|()
decl_stmt|;
name|vgcs
operator|.
name|collectDeletedDocsElapsed
operator|=
name|MILLISECONDS
operator|.
name|toMicros
argument_list|(
literal|2
argument_list|)
expr_stmt|;
name|vgcs
operator|.
name|checkDeletedDocsElapsed
operator|=
name|MILLISECONDS
operator|.
name|toMicros
argument_list|(
literal|3
argument_list|)
expr_stmt|;
name|vgcs
operator|.
name|deleteDeletedDocsElapsed
operator|=
name|MILLISECONDS
operator|.
name|toMicros
argument_list|(
literal|5
argument_list|)
expr_stmt|;
name|vgcs
operator|.
name|collectAndDeleteSplitDocsElapsed
operator|=
name|MILLISECONDS
operator|.
name|toMicros
argument_list|(
literal|7
argument_list|)
expr_stmt|;
name|vgcs
operator|.
name|sortDocIdsElapsed
operator|=
name|MILLISECONDS
operator|.
name|toMicros
argument_list|(
literal|11
argument_list|)
expr_stmt|;
name|vgcs
operator|.
name|updateResurrectedDocumentsElapsed
operator|=
name|MILLISECONDS
operator|.
name|toMicros
argument_list|(
literal|13
argument_list|)
expr_stmt|;
name|vgcs
operator|.
name|active
operator|.
name|start
argument_list|()
expr_stmt|;
while|while
condition|(
name|vgcs
operator|.
name|active
operator|.
name|elapsed
argument_list|(
name|MILLISECONDS
argument_list|)
operator|<
literal|5
condition|)
block|{
comment|// busy wait
name|assertTrue
argument_list|(
name|vgcs
operator|.
name|active
operator|.
name|isRunning
argument_list|()
argument_list|)
expr_stmt|;
block|}
name|vgcs
operator|.
name|active
operator|.
name|stop
argument_list|()
expr_stmt|;
name|stats
operator|.
name|finished
argument_list|(
name|vgcs
argument_list|)
expr_stmt|;
name|assertTimer
argument_list|(
name|vgcs
operator|.
name|active
operator|.
name|elapsed
argument_list|(
name|MILLISECONDS
argument_list|)
argument_list|,
name|RevisionGCStats
operator|.
name|ACTIVE_TIMER
argument_list|)
expr_stmt|;
name|assertTimer
argument_list|(
literal|2
argument_list|,
name|RevisionGCStats
operator|.
name|READ_DOC_TIMER
argument_list|)
expr_stmt|;
name|assertTimer
argument_list|(
literal|3
argument_list|,
name|RevisionGCStats
operator|.
name|CHECK_DELETED_TIMER
argument_list|)
expr_stmt|;
name|assertTimer
argument_list|(
literal|5
argument_list|,
name|RevisionGCStats
operator|.
name|DELETE_DOC_TIMER
argument_list|)
expr_stmt|;
name|assertTimer
argument_list|(
literal|7
argument_list|,
name|RevisionGCStats
operator|.
name|DELETE_SPLIT_DOC_TIMER
argument_list|)
expr_stmt|;
name|assertTimer
argument_list|(
literal|11
argument_list|,
name|RevisionGCStats
operator|.
name|SORT_IDS_TIMER
argument_list|)
expr_stmt|;
name|assertTimer
argument_list|(
literal|13
argument_list|,
name|RevisionGCStats
operator|.
name|RESET_DELETED_FLAG_TIMER
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
specifier|public
name|void
name|counters
parameter_list|()
block|{
name|Counter
name|counter
init|=
name|getCounter
argument_list|(
name|RevisionGCStats
operator|.
name|COUNTER
argument_list|)
decl_stmt|;
name|Counter
name|failureCounter
init|=
name|getCounter
argument_list|(
name|RevisionGCStats
operator|.
name|FAILURE_COUNTER
argument_list|)
decl_stmt|;
name|VersionGCStats
name|vgcs
init|=
operator|new
name|VersionGCStats
argument_list|()
decl_stmt|;
name|stats
operator|.
name|started
argument_list|()
expr_stmt|;
name|stats
operator|.
name|finished
argument_list|(
name|vgcs
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|1
argument_list|,
name|counter
operator|.
name|getCount
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|0
argument_list|,
name|failureCounter
operator|.
name|getCount
argument_list|()
argument_list|)
expr_stmt|;
name|vgcs
operator|.
name|success
operator|=
literal|false
expr_stmt|;
name|stats
operator|.
name|started
argument_list|()
expr_stmt|;
name|stats
operator|.
name|finished
argument_list|(
name|vgcs
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|2
argument_list|,
name|counter
operator|.
name|getCount
argument_list|()
argument_list|)
expr_stmt|;
name|assertEquals
argument_list|(
literal|1
argument_list|,
name|failureCounter
operator|.
name|getCount
argument_list|()
argument_list|)
expr_stmt|;
block|}
specifier|private
name|void
name|assertTimer
parameter_list|(
name|long
name|expected
parameter_list|,
name|String
name|name
parameter_list|)
block|{
name|assertEquals
argument_list|(
name|expected
argument_list|,
name|NANOSECONDS
operator|.
name|toMillis
argument_list|(
name|getTimer
argument_list|(
name|name
argument_list|)
operator|.
name|getSnapshot
argument_list|()
operator|.
name|getMax
argument_list|()
argument_list|)
argument_list|)
expr_stmt|;
block|}
specifier|private
name|Timer
name|getTimer
parameter_list|(
name|String
name|name
parameter_list|)
block|{
return|return
name|statsProvider
operator|.
name|getRegistry
argument_list|()
operator|.
name|getTimers
argument_list|()
operator|.
name|get
argument_list|(
name|RGC
operator|+
literal|"."
operator|+
name|name
argument_list|)
return|;
block|}
specifier|private
name|Meter
name|getMeter
parameter_list|(
name|String
name|name
parameter_list|)
block|{
return|return
name|statsProvider
operator|.
name|getRegistry
argument_list|()
operator|.
name|getMeters
argument_list|()
operator|.
name|get
argument_list|(
name|RGC
operator|+
literal|"."
operator|+
name|name
argument_list|)
return|;
block|}
specifier|private
name|Counter
name|getCounter
parameter_list|(
name|String
name|name
parameter_list|)
block|{
return|return
name|statsProvider
operator|.
name|getRegistry
argument_list|()
operator|.
name|getCounters
argument_list|()
operator|.
name|get
argument_list|(
name|RGC
operator|+
literal|"."
operator|+
name|name
argument_list|)
return|;
block|}
block|}
end_class
end_unit
| 14.168391 | 815 | 0.809375 |
2f4093c076ad019b57dbb701ea34963252ded2c3 | 513 | cs | C# | src/Fakir/Storage/BinaryObject.cs | ztfuqing/Fakir | d79cf85c6d6f6dfa5d89b37df1903ac675aafceb | [
"Apache-2.0"
] | null | null | null | src/Fakir/Storage/BinaryObject.cs | ztfuqing/Fakir | d79cf85c6d6f6dfa5d89b37df1903ac675aafceb | [
"Apache-2.0"
] | null | null | null | src/Fakir/Storage/BinaryObject.cs | ztfuqing/Fakir | d79cf85c6d6f6dfa5d89b37df1903ac675aafceb | [
"Apache-2.0"
] | null | null | null | using Abp.Domain.Entities;
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Fakir.Storage
{
[Table("AppBinaryObjects")]
public class BinaryObject : Entity<Guid>
{
[Required]
public byte[] Bytes { get; set; }
public BinaryObject()
{
Id = Guid.NewGuid();
}
public BinaryObject(byte[] bytes)
: this()
{
Bytes = bytes;
}
}
}
| 19.730769 | 51 | 0.575049 |
26a4c2f8013b977c67a91f3f99a1517f7adc8cf8 | 2,453 | java | Java | test-framework/trunk/src/main/java/org/coconut/test/TestUtil.java | codehaus/coconut | f2bc1fc516c65a9d0fd76ffb3bb148309ef1ba76 | [
"Apache-2.0"
] | null | null | null | test-framework/trunk/src/main/java/org/coconut/test/TestUtil.java | codehaus/coconut | f2bc1fc516c65a9d0fd76ffb3bb148309ef1ba76 | [
"Apache-2.0"
] | null | null | null | test-framework/trunk/src/main/java/org/coconut/test/TestUtil.java | codehaus/coconut | f2bc1fc516c65a9d0fd76ffb3bb148309ef1ba76 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2004 - 2007 Kasper Nielsen <kasper@codehaus.org> Licensed under
* the Apache 2.0 License, see http://coconut.codehaus.org/license.
*/
package org.coconut.test;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.jmock.Mockery;
import junit.framework.AssertionFailedError;
/**
* @author <a href="mailto:kasper@codehaus.org">Kasper Nielsen</a>
* @version $Id$
*/
public class TestUtil {
public static final String LINE_SEPARATOR = System.getProperty("line.separator");
@SuppressWarnings("unchecked")
public static <V> V dummy(Class<V> arg) {
return new Mockery().mock(arg);
}
public static Object serializeAndUnserialize(Object o) {
try {
return readWrite(o);
} catch (Exception e) {
throw new AssertionFailedError(o + " not serialiable");
}
}
public static void assertNotSerializable(Object o) {
try {
readWrite(o);
throw new AssertionFailedError(o + " is serialiable");
} catch (NotSerializableException nse) {/* ok */}
}
public static void assertIsSerializable(Object o) {
// TODO test has serializableID
try {
readWrite(o);
} catch (NotSerializableException e) {
throw new AssertionFailedError(o + " not serialiable");
}
}
static Object readWrite(Object o) throws NotSerializableException {
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream(20000);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(bout));
out.writeObject(o);
out.close();
ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(bin));
return in.readObject();
} catch (NotSerializableException nse) {
throw nse;
} catch (ClassNotFoundException e) {
throw new Error(e);// should'nt happen
} catch (IOException e) {
throw new Error(e);// should'nt happen
}
}
}
| 33.60274 | 93 | 0.635956 |
40f35b045d7fa68ae359c3fa67a1c7159332b618 | 3,510 | py | Python | code/python/apk-monitor.py | baotang2118/My-Capstone-apk-monitor | 42e63df11a8d8a54b88bfe1b7e709592994b6eb5 | [
"MIT"
] | 1 | 2019-01-09T11:18:48.000Z | 2019-01-09T11:18:48.000Z | code/python/apk-monitor.py | baotang2118/Apk-monitor | 42e63df11a8d8a54b88bfe1b7e709592994b6eb5 | [
"MIT"
] | null | null | null | code/python/apk-monitor.py | baotang2118/Apk-monitor | 42e63df11a8d8a54b88bfe1b7e709592994b6eb5 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
from __future__ import print_function
from argparse import ArgumentParser
from androguard.cli import androlyze_main
from androguard.core.androconf import *
from androguard.misc import *
import os
import sql
import sqlstorehash
LIST_NAME_METHODS=["sendBroadcast", "onReceive","startService","onHandleIntent","startActivity","getIntent"];
LIST_HEADER=["STT","APK Name"]+LIST_NAME_METHODS+["Component Type", "Component Name", "Exported Status","getPermissions"]
def count_Method_APK(methodName, listMethods):
count=0
newlist=list()
for element in listMethods:
newlist.append(element.__repr__())
for l in newlist:
if methodName in l:
count+=1
return count
def attribute_Component(apk_Obj):
manifest_Obj=apk_Obj.get_android_manifest_xml()
application_Tag=manifest_Obj.findall("application")
latrr=list()
list_Component=list()
dem=0
for childs in application_Tag:
for child in childs:
keys=list()
keys=child.keys()
newdict=dict()
list_Component.append(child.tag)
for key in keys:
lsplit=key.split("}")
newdict[lsplit[-1]]=child.get(key)
latrr.append(newdict)
return latrr, list_Component
def get_Atrribute(listDict):
list_Name_Of_Component=list()
list_Exported_Of_Component=list()
for dictt in listDict:
list_Name_Of_Component.append(dictt.get('name'))
list_Exported_Of_Component.append(dictt.get('exported'))
return list_Name_Of_Component, list_Exported_Of_Component
def get_List_Contens(path, nameAPK):
try:
a, d, dx=AnalyzeAPK(path)
listMethods=list(dx.get_methods())
list_Count_Methods=list()
list_Count_Methods.append(nameAPK)
for i in range(0,len(LIST_NAME_METHODS)):
list_Count_Methods.append(count_Method_APK(LIST_NAME_METHODS[i], listMethods))
atrrs, components=attribute_Component(a)
names, exports=get_Atrribute(atrrs)
list_Count_Methods.append(components)
list_Count_Methods.append(names)
list_Count_Methods.append(exports)
list_Count_Methods.append(a.get_permissions())
except:
for i in range(0,len(LIST_NAME_METHODS)):
list_Count_Methods.append("Failed!")
return list_Count_Methods
def get_Path_Files(pathFolder):
Fjoin=os.path.join
lapkname=os.listdir(pathFolder)
list_Of_Path_Files=[Fjoin(pathFolder,f) for f in os.listdir(pathFolder)]
return list_Of_Path_Files, lapkname
def map_List_Methods(pathFolder):
lspath, lsnameAPK=get_Path_Files(pathFolder)
newlist=list()
newlist.append(LIST_HEADER)
i=1
for (lp,ln) in zip(lspath,lsnameAPK):
#hash here
md5, sha1, sha256 = sqlstorehash.hashMd5Sha1Sha256(lp)
if(sql.CheckExist(ln,md5, sha1, sha256) == False):
ltemp=get_List_Contens(lp,ln)
ltemp.insert(0,i)
newlist.append(ltemp)
#sql here
sql.InsertApp(ltemp, md5, sha1, sha256)
print ("Completed " + str(round(i/float(len(lspath))*100))+"%.")
i=i+1
return newlist
def main():
#sql.CreateDB();
#sql.CreateTable();
#sql.DangerousPermission();
try:
fh = open("config","r")
fh.close()
except:
fh = open("config","w")
fh.write('1')
fh.close()
map_List_Methods("/root/Downloads/Test")
if __name__ == '__main__':
main() | 32.5 | 121 | 0.667806 |
9840d64890e76e73d86826fb26a038222ab32354 | 178 | html | HTML | templates/head.html | marvindanig/the-sea-gull | a0b8073f08e054fdbf1c77536f60431b157ba1d7 | [
"BlueOak-1.0.0",
"MIT"
] | null | null | null | templates/head.html | marvindanig/the-sea-gull | a0b8073f08e054fdbf1c77536f60431b157ba1d7 | [
"BlueOak-1.0.0",
"MIT"
] | null | null | null | templates/head.html | marvindanig/the-sea-gull | a0b8073f08e054fdbf1c77536f60431b157ba1d7 | [
"BlueOak-1.0.0",
"MIT"
] | null | null | null | <link href="https://fonts.googleapis.com/css?family=EB+Garamond:400,400i|Berkshire+Swash" rel="stylesheet" type="text/css">
<title>The Sea-Gull by Anton Pavlovich Chekhov</title> | 89 | 123 | 0.775281 |
7c91ece799475475cfe6214a3f89ad25e1fafef1 | 2,317 | kt | Kotlin | src/main/kotlin/Playlist.kt | NikitaKarnauhov/epg-gen | d41a9d3784ae36ee9c821b513f4e83d5ed12709b | [
"BSD-2-Clause"
] | null | null | null | src/main/kotlin/Playlist.kt | NikitaKarnauhov/epg-gen | d41a9d3784ae36ee9c821b513f4e83d5ed12709b | [
"BSD-2-Clause"
] | null | null | null | src/main/kotlin/Playlist.kt | NikitaKarnauhov/epg-gen | d41a9d3784ae36ee9c821b513f4e83d5ed12709b | [
"BSD-2-Clause"
] | null | null | null | import com.beust.klaxon.*
import com.iheartradio.m3u8.Encoding
import com.iheartradio.m3u8.Format
import com.iheartradio.m3u8.ParsingMode
import com.iheartradio.m3u8.PlaylistParser
import java.io.InputStream
class Playlist {
var channels = mutableMapOf<String, PlaylistChannel>()
fun set(scraper: Scraper?, name: String, channel: Channel?, id: Int): Boolean {
val updated = !channels.contains(name)
channels[name] = PlaylistChannel(scraper, name, channel, id)
return updated
}
fun toJson(): JsonArray<Any?> {
return json {
array(channels.values.sortedBy { it.id }.map {
val playlistId = it.id
val name = it.name
if (it.scraper != null) {
val id = it.channel?.id ?: 0
obj("scraper" to it.scraper.name, "id" to id,
"playlistId" to playlistId, "name" to name)
} else
obj("playlistId" to playlistId, "name" to name)
})
}
}
companion object {
fun fromJson(arr: JsonArray<JsonObject>, scrapers: Map<String, Scraper>): Playlist {
val result = Playlist()
result.channels = arr.mapNotNull {
val scraper = it.string("scraper")?.let { scrapers[it] }
val id = it.int("id") ?: 0
val playlistId = it.int("playlistId") ?: 0
val name = it.string("name")
name?.let {
val channel = scraper?.channels?.find { it.id == id }
PlaylistChannel(scraper, name, channel, playlistId)
}
}.associateBy {
it.name
}.toMutableMap()
return result
}
fun fromM3U(stream: InputStream): Playlist {
val result = Playlist()
val parser = PlaylistParser(stream, Format.EXT_M3U, Encoding.UTF_8,
ParsingMode.LENIENT)
val playlist = parser.parse()
var id = 0
result.channels = playlist.mediaPlaylist.tracks.associateBy(
{ it.trackInfo.title },
{ PlaylistChannel(null, it.trackInfo.title, id = ++id) }).toMutableMap()
return result
}
}
}
| 36.777778 | 92 | 0.53647 |
29f88c67276a9afc612928ad1e8b56d191c484a1 | 2,193 | ps1 | PowerShell | tools/PSc8y/Public/Reset-UserPassword.ps1 | hanneshofmann/go-c8y-cli | ce972e117ad0cfabbe2156cfcaccb7d956c677a2 | [
"MIT"
] | 17 | 2020-07-14T17:38:38.000Z | 2022-02-02T14:49:00.000Z | tools/PSc8y/Public/Reset-UserPassword.ps1 | hanneshofmann/go-c8y-cli | ce972e117ad0cfabbe2156cfcaccb7d956c677a2 | [
"MIT"
] | 36 | 2020-09-16T14:41:51.000Z | 2022-03-23T21:42:50.000Z | tools/PSc8y/Public/Reset-UserPassword.ps1 | hanneshofmann/go-c8y-cli | ce972e117ad0cfabbe2156cfcaccb7d956c677a2 | [
"MIT"
] | 3 | 2021-09-07T18:21:59.000Z | 2022-02-08T15:37:48.000Z | # Code generated from specification version 1.0.0: DO NOT EDIT
Function Reset-UserPassword {
<#
.SYNOPSIS
Reset user password
.DESCRIPTION
The password can be reset either by issuing a password reset email (default), or be specifying a new password.
.LINK
https://reubenmiller.github.io/go-c8y-cli/docs/cli/c8y/users_resetUserPassword
.EXAMPLE
PS> Reset-UserPassword -Id $User.id -Dry
Resets a user's password by sending a reset email to the user
.EXAMPLE
PS> Reset-UserPassword -Id $User.id -NewPassword (New-RandomPassword)
Resets a user's password by generating a new password
#>
[cmdletbinding(PositionalBinding=$true,
HelpUri='')]
[Alias()]
[OutputType([object])]
Param(
# User id (required)
[Parameter(Mandatory = $true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[object[]]
$Id,
# New user password. Min: 6, max: 32 characters. Only Latin1 chars allowed
[Parameter()]
[string]
$NewPassword,
# Tenant
[Parameter()]
[object]
$Tenant
)
DynamicParam {
Get-ClientCommonParameters -Type "Update", "Template"
}
Begin {
if ($env:C8Y_DISABLE_INHERITANCE -ne $true) {
# Inherit preference variables
Use-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState
}
$c8yargs = New-ClientArgument -Parameters $PSBoundParameters -Command "users resetUserPassword"
$ClientOptions = Get-ClientOutputOption $PSBoundParameters
$TypeOptions = @{
Type = "application/vnd.com.nsn.cumulocity.user+json"
ItemType = ""
BoundParameters = $PSBoundParameters
}
}
Process {
if ($ClientOptions.ConvertToPS) {
$Id `
| Group-ClientRequests `
| c8y users resetUserPassword $c8yargs `
| ConvertFrom-ClientOutput @TypeOptions
}
else {
$Id `
| Group-ClientRequests `
| c8y users resetUserPassword $c8yargs
}
}
End {}
}
| 25.8 | 110 | 0.607843 |
ab26404c3bdab968db6ce4865e8f89e33d9847f3 | 3,298 | cs | C# | Server/Startup.cs | weibaohui/blazork8s | c5119421afebc87889f9d22960c5c08065b47124 | [
"MIT"
] | 26 | 2021-07-06T00:20:50.000Z | 2021-10-20T00:05:59.000Z | Server/Startup.cs | weibaohui/blazork8s | c5119421afebc87889f9d22960c5c08065b47124 | [
"MIT"
] | null | null | null | Server/Startup.cs | weibaohui/blazork8s | c5119421afebc87889f9d22960c5c08065b47124 | [
"MIT"
] | 1 | 2021-08-21T06:51:50.000Z | 2021-08-21T06:51:50.000Z | using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using Server.Controllers;
using Server.Middleware;
using Server.Service;
using Server.Service.K8s;
namespace server
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
private IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
#region CORS
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder => { builder.AllowAnyMethod().AllowAnyOrigin().AllowAnyHeader(); });
});
#endregion
services.AddControllers();
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "server", Version = "v1" }); });
services.AddSingleton<IWatcher,Watcher>();
services.AddSingleton<PodWatcher>();
services.AddSingleton<NodeWatcher>();
services.AddSingleton<RequestLoggingMiddleware>();
#region HttpLoging
// services.AddHttpLogging(logging =>
// {
// // Customize HTTP logging here.
// logging.LoggingFields = HttpLoggingFields.All;
// logging.RequestHeaders.Add("My-Request-Header");
// logging.ResponseHeaders.Add("My-Response-Header");
// logging.MediaTypeOptions.AddText("application/javascript");
// logging.RequestBodyLogLimit = 4096;
// logging.ResponseBodyLogLimit = 4096;
// });
#endregion
#region SignalR
services.AddSignalR().AddNewtonsoftJsonProtocol();
services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
#endregion
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "api"));
}
// app.UseHttpsRedirection();
// app.UseHttpLogging();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseMiddleware<RequestLoggingMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub");
endpoints.MapControllers();
});
}
}
}
| 32.333333 | 119 | 0.587326 |
1a1cfc468a438a3825ba53871f6847fd1a23fbd6 | 36,141 | swift | Swift | Pods/Alamofire/Source/Combine.swift | JackMaarek/weather-app | 7e6c15ede5457b80dd2eb29ad6a759318d28ea5a | [
"MIT"
] | null | null | null | Pods/Alamofire/Source/Combine.swift | JackMaarek/weather-app | 7e6c15ede5457b80dd2eb29ad6a759318d28ea5a | [
"MIT"
] | null | null | null | Pods/Alamofire/Source/Combine.swift | JackMaarek/weather-app | 7e6c15ede5457b80dd2eb29ad6a759318d28ea5a | [
"MIT"
] | null | null | null | //
// Combine.swift
//
// Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/)
//
// 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.
//
#if canImport(Combine)
import Combine
import Dispatch
import Foundation
// MARK: - DataRequest / UploadRequest
/// A Combine `Publisher` that publishes the `DataResponse<Value, AFError>` of the provided `DataRequest`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct DataResponsePublisher<Value>: Publisher {
public typealias Output = DataResponse<Value, AFError>
public typealias Failure = Never
private typealias Handler = (@escaping (_ response: DataResponse<Value, AFError>) -> Void) -> DataRequest
private let request: DataRequest
private let responseHandler: Handler
/// Creates an instance which will serialize responses using the provided `ResponseSerializer`.
///
/// - Parameters:
/// - request: `DataRequest` for which to publish the response.
/// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default.
/// - serializer: `ResponseSerializer` used to produce the published `DataResponse`.
public init<Serializer: ResponseSerializer>(_ request: DataRequest, queue: DispatchQueue, serializer: Serializer)
where Value == Serializer.SerializedObject
{
self.request = request
responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
}
/// Creates an instance which will serialize responses using the provided `DataResponseSerializerProtocol`.
///
/// - Parameters:
/// - request: `DataRequest` for which to publish the response.
/// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default.
/// - serializer: `DataResponseSerializerProtocol` used to produce the published `DataResponse`.
public init<Serializer: DataResponseSerializerProtocol>(_ request: DataRequest,
queue: DispatchQueue,
serializer: Serializer)
where Value == Serializer.SerializedObject
{
self.request = request
responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
}
/// Publishes only the `Result` of the `DataResponse` value.
///
/// - Returns: The `AnyPublisher` publishing the `Result<Value, AFError>` value.
public func result() -> AnyPublisher<Result<Value, AFError>, Never> {
map { $0.result }.eraseToAnyPublisher()
}
/// Publishes the `Result` of the `DataResponse` as a single `Value` or fail with the `AFError` instance.
///
/// - Returns: The `AnyPublisher<Value, AFError>` publishing the stream.
public func value() -> AnyPublisher<Value, AFError> {
setFailureType(to: AFError.self).flatMap { $0.result.publisher }.eraseToAnyPublisher()
}
public func receive<S>(subscriber: S) where S: Subscriber, DataResponsePublisher.Failure == S.Failure, DataResponsePublisher.Output == S.Input {
subscriber.receive(subscription: Inner(request: request,
responseHandler: responseHandler,
downstream: subscriber))
}
private final class Inner<Downstream: Subscriber>: Subscription, Cancellable
where Downstream.Input == Output
{
typealias Failure = Downstream.Failure
@Protected
private var downstream: Downstream?
private let request: DataRequest
private let responseHandler: Handler
init(request: DataRequest, responseHandler: @escaping Handler, downstream: Downstream) {
self.request = request
self.responseHandler = responseHandler
self.downstream = downstream
}
func request(_ demand: Subscribers.Demand) {
assert(demand > 0)
guard let downstream = downstream else { return }
self.downstream = nil
responseHandler { response in
_ = downstream.receive(response)
downstream.receive(completion: .finished)
}.resume()
}
func cancel() {
request.cancel()
downstream = nil
}
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public extension DataResponsePublisher where Value == Data? {
/// Creates an instance which publishes a `DataResponse<Data?, AFError>` value without serialization.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
init(_ request: DataRequest, queue: DispatchQueue) {
self.request = request
responseHandler = { request.response(queue: queue, completionHandler: $0) }
}
}
public extension DataRequest {
/// Creates a `DataResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`.
///
/// - Parameters:
/// - serializer: `ResponseSerializer` used to serialize response `Data`.
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
///
/// - Returns: The `DataResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishResponse<Serializer: ResponseSerializer, T>(using serializer: Serializer, on queue: DispatchQueue = .main) -> DataResponsePublisher<T>
where Serializer.SerializedObject == T
{
DataResponsePublisher(self, queue: queue, serializer: serializer)
}
/// Creates a `DataResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
/// - Returns: The `DataResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishData(queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher<Data>
{
publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyRequestMethods),
on: queue)
}
/// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding
/// will be determined by the server response, falling back to the default HTTP character
/// set, `ISO-8859-1`.
/// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
///
/// - Returns: The `DataResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishString(queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
encoding: String.Encoding? = nil,
emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> DataResponsePublisher<String>
{
publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor,
encoding: encoding,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyRequestMethods),
on: queue)
}
/// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default.
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default.
/// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
///
/// - Returns: The `DataResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishDecodable<T: Decodable>(type _: T.Type = T.self,
queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
decoder: DataDecoder = JSONDecoder(),
emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
emptyResponseMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods) -> DataResponsePublisher<T>
{
publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor,
decoder: decoder,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyResponseMethods),
on: queue)
}
/// Creates a `DataResponsePublisher` for this instance which does not serialize the response before publishing.
///
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
///
/// - Returns: The `DataResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishUnserialized(queue: DispatchQueue = .main) -> DataResponsePublisher<Data?> {
DataResponsePublisher(self, queue: queue)
}
}
// A Combine `Publisher` that publishes a sequence of `Stream<Value, AFError>` values received by the provided `DataStreamRequest`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct DataStreamPublisher<Value>: Publisher {
public typealias Output = DataStreamRequest.Stream<Value, AFError>
public typealias Failure = Never
private typealias Handler = (@escaping DataStreamRequest.Handler<Value, AFError>) -> DataStreamRequest
private let request: DataStreamRequest
private let streamHandler: Handler
/// Creates an instance which will serialize responses using the provided `DataStreamSerializer`.
///
/// - Parameters:
/// - request: `DataStreamRequest` for which to publish the response.
/// - queue: `DispatchQueue` on which the `Stream<Value, AFError>` values will be published. `.main` by
/// default.
/// - serializer: `DataStreamSerializer` used to produce the published `Stream<Value, AFError>` values.
public init<Serializer: DataStreamSerializer>(_ request: DataStreamRequest, queue: DispatchQueue, serializer: Serializer)
where Value == Serializer.SerializedObject
{
self.request = request
streamHandler = { request.responseStream(using: serializer, on: queue, stream: $0) }
}
/// Publishes only the `Result` of the `DataStreamRequest.Stream`'s `Event`s.
///
/// - Returns: The `AnyPublisher` publishing the `Result<Value, AFError>` value.
public func result() -> AnyPublisher<Result<Value, AFError>, Never> {
compactMap { stream in
switch stream.event {
case let .stream(result):
return result
// If the stream has completed with an error, send the error value downstream as a `.failure`.
case let .complete(completion):
return completion.error.map(Result.failure)
}
}
.eraseToAnyPublisher()
}
/// Publishes the streamed values of the `DataStreamRequest.Stream` as a sequence of `Value` or fail with the
/// `AFError` instance.
///
/// - Returns: The `AnyPublisher<Value, AFError>` publishing the stream.
public func value() -> AnyPublisher<Value, AFError> {
result().setFailureType(to: AFError.self).flatMap { $0.publisher }.eraseToAnyPublisher()
}
public func receive<S>(subscriber: S) where S: Subscriber, DataStreamPublisher.Failure == S.Failure, DataStreamPublisher.Output == S.Input {
subscriber.receive(subscription: Inner(request: request,
streamHandler: streamHandler,
downstream: subscriber))
}
private final class Inner<Downstream: Subscriber>: Subscription, Cancellable
where Downstream.Input == Output
{
typealias Failure = Downstream.Failure
@Protected
private var downstream: Downstream?
private let request: DataStreamRequest
private let streamHandler: Handler
init(request: DataStreamRequest, streamHandler: @escaping Handler, downstream: Downstream) {
self.request = request
self.streamHandler = streamHandler
self.downstream = downstream
}
func request(_ demand: Subscribers.Demand) {
assert(demand > 0)
guard let downstream = downstream else { return }
self.downstream = nil
streamHandler { stream in
_ = downstream.receive(stream)
if case .complete = stream.event {
downstream.receive(completion: .finished)
}
}.resume()
}
func cancel() {
request.cancel()
downstream = nil
}
}
}
public extension DataStreamRequest {
/// Creates a `DataStreamPublisher` for this instance using the given `DataStreamSerializer` and `DispatchQueue`.
///
/// - Parameters:
/// - serializer: `DataStreamSerializer` used to serialize the streamed `Data`.
/// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
/// - Returns: The `DataStreamPublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishStream<Serializer: DataStreamSerializer>(using serializer: Serializer,
on queue: DispatchQueue = .main) -> DataStreamPublisher<Serializer.SerializedObject>
{
DataStreamPublisher(self, queue: queue, serializer: serializer)
}
/// Creates a `DataStreamPublisher` for this instance which uses a `PassthroughStreamSerializer` to stream `Data`
/// unserialized.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
/// - Returns: The `DataStreamPublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishData(queue: DispatchQueue = .main) -> DataStreamPublisher<Data> {
publishStream(using: PassthroughStreamSerializer(), on: queue)
}
/// Creates a `DataStreamPublisher` for this instance which uses a `StringStreamSerializer` to serialize stream
/// `Data` values into `String` values.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
/// - Returns: The `DataStreamPublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishString(queue: DispatchQueue = .main) -> DataStreamPublisher<String> {
publishStream(using: StringStreamSerializer(), on: queue)
}
/// Creates a `DataStreamPublisher` for this instance which uses a `DecodableStreamSerializer` with the provided
/// parameters to serialize stream `Data` values into the provided type.
///
/// - Parameters:
/// - type: `Decodable` type to which to decode stream `Data`. Inferred from the context by default.
/// - queue: `DispatchQueue` on which the `DataRequest.Stream` values will be published. `.main` by default.
/// - decoder: `DataDecoder` instance used to decode stream `Data`. `JSONDecoder()` by default.
/// - preprocessor: `DataPreprocessor` which filters incoming stream `Data` before serialization.
/// `PassthroughPreprocessor()` by default.
/// - Returns: The `DataStreamPublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishDecodable<T: Decodable>(type _: T.Type = T.self,
queue: DispatchQueue = .main,
decoder: DataDecoder = JSONDecoder(),
preprocessor: DataPreprocessor = PassthroughPreprocessor()) -> DataStreamPublisher<T>
{
publishStream(using: DecodableStreamSerializer(decoder: decoder,
dataPreprocessor: preprocessor),
on: queue)
}
}
/// A Combine `Publisher` that publishes the `DownloadResponse<Value, AFError>` of the provided `DownloadRequest`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public struct DownloadResponsePublisher<Value>: Publisher {
public typealias Output = DownloadResponse<Value, AFError>
public typealias Failure = Never
private typealias Handler = (@escaping (_ response: DownloadResponse<Value, AFError>) -> Void) -> DownloadRequest
private let request: DownloadRequest
private let responseHandler: Handler
/// Creates an instance which will serialize responses using the provided `ResponseSerializer`.
///
/// - Parameters:
/// - request: `DownloadRequest` for which to publish the response.
/// - queue: `DispatchQueue` on which the `DownloadResponse` value will be published. `.main` by default.
/// - serializer: `ResponseSerializer` used to produce the published `DownloadResponse`.
public init<Serializer: ResponseSerializer>(_ request: DownloadRequest, queue: DispatchQueue, serializer: Serializer)
where Value == Serializer.SerializedObject
{
self.request = request
responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
}
/// Creates an instance which will serialize responses using the provided `DownloadResponseSerializerProtocol` value.
///
/// - Parameters:
/// - request: `DownloadRequest` for which to publish the response.
/// - queue: `DispatchQueue` on which the `DataResponse` value will be published. `.main` by default.
/// - serializer: `DownloadResponseSerializerProtocol` used to produce the published `DownloadResponse`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public init<Serializer: DownloadResponseSerializerProtocol>(_ request: DownloadRequest,
queue: DispatchQueue,
serializer: Serializer)
where Value == Serializer.SerializedObject
{
self.request = request
responseHandler = { request.response(queue: queue, responseSerializer: serializer, completionHandler: $0) }
}
/// Publishes only the `Result` of the `DownloadResponse` value.
///
/// - Returns: The `AnyPublisher` publishing the `Result<Value, AFError>` value.
public func result() -> AnyPublisher<Result<Value, AFError>, Never> {
map { $0.result }.eraseToAnyPublisher()
}
/// Publishes the `Result` of the `DownloadResponse` as a single `Value` or fail with the `AFError` instance.
///
/// - Returns: The `AnyPublisher<Value, AFError>` publishing the stream.
public func value() -> AnyPublisher<Value, AFError> {
setFailureType(to: AFError.self).flatMap { $0.result.publisher }.eraseToAnyPublisher()
}
public func receive<S>(subscriber: S) where S: Subscriber, DownloadResponsePublisher.Failure == S.Failure, DownloadResponsePublisher.Output == S.Input {
subscriber.receive(subscription: Inner(request: request,
responseHandler: responseHandler,
downstream: subscriber))
}
private final class Inner<Downstream: Subscriber>: Subscription, Cancellable
where Downstream.Input == Output
{
typealias Failure = Downstream.Failure
@Protected
private var downstream: Downstream?
private let request: DownloadRequest
private let responseHandler: Handler
init(request: DownloadRequest, responseHandler: @escaping Handler, downstream: Downstream) {
self.request = request
self.responseHandler = responseHandler
self.downstream = downstream
}
func request(_ demand: Subscribers.Demand) {
assert(demand > 0)
guard let downstream = downstream else { return }
self.downstream = nil
responseHandler { response in
_ = downstream.receive(response)
downstream.receive(completion: .finished)
}.resume()
}
func cancel() {
request.cancel()
downstream = nil
}
}
}
public extension DownloadRequest {
/// Creates a `DownloadResponsePublisher` for this instance using the given `ResponseSerializer` and `DispatchQueue`.
///
/// - Parameters:
/// - serializer: `ResponseSerializer` used to serialize the response `Data` from disk.
/// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishResponse<Serializer: ResponseSerializer, T>(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher<T>
where Serializer.SerializedObject == T
{
DownloadResponsePublisher(self, queue: queue, serializer: serializer)
}
/// Creates a `DownloadResponsePublisher` for this instance using the given `DownloadResponseSerializerProtocol` and
/// `DispatchQueue`.
///
/// - Parameters:
/// - serializer: `DownloadResponseSerializer` used to serialize the response `Data` from disk.
/// - queue: `DispatchQueue` on which the `DownloadResponse` will be published.`.main` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishResponse<Serializer: DownloadResponseSerializerProtocol, T>(using serializer: Serializer, on queue: DispatchQueue = .main) -> DownloadResponsePublisher<T>
where Serializer.SerializedObject == T
{
DownloadResponsePublisher(self, queue: queue, serializer: serializer)
}
/// Creates a `DownloadResponsePublisher` for this instance and uses a `URLResponseSerializer` to serialize the
/// response.
///
/// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishURL(queue: DispatchQueue = .main) -> DownloadResponsePublisher<URL> {
publishResponse(using: URLResponseSerializer(), on: queue)
}
/// Creates a `DownloadResponsePublisher` for this instance and uses a `DataResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishData(queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor,
emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher<Data>
{
publishResponse(using: DataResponseSerializer(dataPreprocessor: preprocessor,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyRequestMethods),
on: queue)
}
/// Creates a `DataResponsePublisher` for this instance and uses a `StringResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - encoding: `String.Encoding` to parse the response. `nil` by default, in which case the encoding
/// will be determined by the server response, falling back to the default HTTP character
/// set, `ISO-8859-1`.
/// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishString(queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = StringResponseSerializer.defaultDataPreprocessor,
encoding: String.Encoding? = nil,
emptyResponseCodes: Set<Int> = StringResponseSerializer.defaultEmptyResponseCodes,
emptyRequestMethods: Set<HTTPMethod> = StringResponseSerializer.defaultEmptyRequestMethods) -> DownloadResponsePublisher<String>
{
publishResponse(using: StringResponseSerializer(dataPreprocessor: preprocessor,
encoding: encoding,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyRequestMethods),
on: queue)
}
/// Creates a `DataResponsePublisher` for this instance and uses a `DecodableResponseSerializer` to serialize the
/// response.
///
/// - Parameters:
/// - type: `Decodable` type to which to decode response `Data`. Inferred from the context by default.
/// - queue: `DispatchQueue` on which the `DataResponse` will be published. `.main` by default.
/// - preprocessor: `DataPreprocessor` which filters the `Data` before serialization. `PassthroughPreprocessor()`
/// by default.
/// - decoder: `DataDecoder` instance used to decode response `Data`. `JSONDecoder()` by default.
/// - emptyResponseCodes: `Set<Int>` of HTTP status codes for which empty responses are allowed. `[204, 205]` by
/// default.
/// - emptyRequestMethods: `Set<HTTPMethod>` of `HTTPMethod`s for which empty responses are allowed, regardless of
/// status code. `[.head]` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishDecodable<T: Decodable>(type _: T.Type = T.self,
queue: DispatchQueue = .main,
preprocessor: DataPreprocessor = DecodableResponseSerializer<T>.defaultDataPreprocessor,
decoder: DataDecoder = JSONDecoder(),
emptyResponseCodes: Set<Int> = DecodableResponseSerializer<T>.defaultEmptyResponseCodes,
emptyResponseMethods: Set<HTTPMethod> = DecodableResponseSerializer<T>.defaultEmptyRequestMethods) -> DownloadResponsePublisher<T>
{
publishResponse(using: DecodableResponseSerializer(dataPreprocessor: preprocessor,
decoder: decoder,
emptyResponseCodes: emptyResponseCodes,
emptyRequestMethods: emptyResponseMethods),
on: queue)
}
}
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
public extension DownloadResponsePublisher where Value == URL? {
/// Creates an instance which publishes a `DownloadResponse<URL?, AFError>` value without serialization.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
init(_ request: DownloadRequest, queue: DispatchQueue) {
self.request = request
responseHandler = { request.response(queue: queue, completionHandler: $0) }
}
}
public extension DownloadRequest {
/// Creates a `DownloadResponsePublisher` for this instance which does not serialize the response before publishing.
///
/// - Parameter queue: `DispatchQueue` on which the `DownloadResponse` will be published. `.main` by default.
///
/// - Returns: The `DownloadResponsePublisher`.
@available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *)
func publishUnserialized(on queue: DispatchQueue = .main) -> DownloadResponsePublisher<URL?> {
DownloadResponsePublisher(self, queue: queue)
}
}
#endif
| 56.294393 | 174 | 0.585236 |
5db58106f863e07559363e56ffb17c154ba5b34c | 2,544 | go | Go | 2020/day16/main_p2.go | gcalmettes/AdventOfCode2017 | 374347c981b603981b7d0b21dad3fc594b126c82 | [
"MIT"
] | 1 | 2021-12-12T22:59:49.000Z | 2021-12-12T22:59:49.000Z | 2020/day16/main_p2.go | gcalmettes/AdventOfCode2017 | 374347c981b603981b7d0b21dad3fc594b126c82 | [
"MIT"
] | null | null | null | 2020/day16/main_p2.go | gcalmettes/AdventOfCode2017 | 374347c981b603981b7d0b21dad3fc594b126c82 | [
"MIT"
] | 1 | 2019-12-03T05:37:49.000Z | 2019-12-03T05:37:49.000Z | package main
import (
"fmt"
"io/ioutil"
"log"
"strconv"
"strings"
)
func main() {
input := readInput("input.txt")
rules := input[0]
ticket := input[1]
nearby := input[2]
// Authorized values for fields
authorized := make(map[int]bool)
rulesAuthorizedInt := make(map[string]map[int]bool)
for _, line := range strings.Split(rules, "\n") {
parts := strings.Split(line, ": ")
values := make(map[int]bool)
ranges := strings.Split(parts[1], " or ")
for _, r := range ranges {
bounds := strings.Split(r, "-")
lower, _ := strconv.Atoi(bounds[0])
upper, _ := strconv.Atoi(bounds[1])
for i := lower; i <= upper; i++ {
authorized[i] = true
values[i] = true
}
}
rulesAuthorizedInt[parts[0]] = values
}
validTickets := [][]int{}
for _, t := range strings.Split(nearby, "\n") {
values := strings.Split(t, ",")
valuesInt := []int{}
valid := true
for _, v := range values {
n, _ := strconv.Atoi(v)
valuesInt = append(valuesInt, n)
if !authorized[n] {
valid = false
}
}
if valid {
validTickets = append(validTickets, valuesInt)
}
}
positions := make(map[int][]int)
for _, values := range validTickets {
for p, v := range values {
positions[p] = append(positions[p], v)
}
}
matchPositions := make(map[int][]string)
for pos, values := range positions {
for s, autorizedValues := range rulesAuthorizedInt {
all := true
for _, v := range values {
if !autorizedValues[v] {
all = false
}
}
if all {
matchPositions[pos] = append(matchPositions[pos], s)
}
}
}
matches := make(map[string]int)
myTicket := []int{}
for _, m := range strings.Split(ticket, ",") {
v, _ := strconv.Atoi(m)
myTicket = append(myTicket, v)
}
numberOfFields := len(myTicket)
found := 0
for found < numberOfFields-1 {
for p, list := range matchPositions {
missing := 0
for _, l := range list {
if _, ok := matches[l]; !ok {
missing++
}
}
if missing == 1 {
for _, l := range list {
if _, ok := matches[l]; !ok {
matches[l] = p
found++
}
}
}
}
}
factors := []int{}
for field, p := range matches {
if strings.HasPrefix(field, "departure") {
factors = append(factors, p)
}
}
mul := 1
for _, f := range factors {
mul *= myTicket[f]
}
fmt.Println(mul)
}
func readInput(path string) []string {
file, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal("could not open %s: %v", path, err)
}
data := strings.Split(string(file), "\n\n")
return data
}
| 18.705882 | 56 | 0.582547 |
2815582ddd3242e63caa912f5ae7252f2a152967 | 516 | lua | Lua | lua/match-up.lua | captainko/vim-matchup | 91c9530d490c8ca3e32f05b68dd135580ebe5841 | [
"MIT"
] | null | null | null | lua/match-up.lua | captainko/vim-matchup | 91c9530d490c8ca3e32f05b68dd135580ebe5841 | [
"MIT"
] | null | null | null | lua/match-up.lua | captainko/vim-matchup | 91c9530d490c8ca3e32f05b68dd135580ebe5841 | [
"MIT"
] | null | null | null | local M = {}
local function do_setup(opts, validate)
for mod, elem in pairs(opts) do
for key, val in pairs(type(elem) == 'table' and elem or {}) do
local opt = 'matchup_'..mod..'_'..key
if validate and vim.g[opt] == nil then
error(string.format('invalid option name %s.%s', mod, key))
end
vim.g[opt] = val
end
end
end
function M.setup(opts)
local sync = opts.sync
if sync then
vim.cmd[[runtime! plugin/matchup.vim]]
end
do_setup(opts, sync)
end
return M
| 20.64 | 69 | 0.618217 |
fa18ed7ba53d37913141c0e42d12b4cf1807fdec | 208 | sql | SQL | src/test/resources/pagerfault.test_72.sql | jdkoren/sqlite-parser | 9adf75ff5eca36f6e541594d2e062349f9ced654 | [
"MIT"
] | 131 | 2015-03-31T18:59:14.000Z | 2022-03-09T09:51:06.000Z | src/test/resources/pagerfault.test_72.sql | jdkoren/sqlite-parser | 9adf75ff5eca36f6e541594d2e062349f9ced654 | [
"MIT"
] | 20 | 2015-03-31T21:35:38.000Z | 2018-07-02T16:15:51.000Z | src/test/resources/pagerfault.test_72.sql | jdkoren/sqlite-parser | 9adf75ff5eca36f6e541594d2e062349f9ced654 | [
"MIT"
] | 43 | 2015-04-28T02:01:55.000Z | 2021-06-06T09:33:38.000Z | -- pagerfault.test
--
-- execsql {
-- CREATE TABLE t2(a, b);
-- INSERT INTO t2 SELECT * FROM t1;
-- DELETE FROM t1;
-- }
CREATE TABLE t2(a, b);
INSERT INTO t2 SELECT * FROM t1;
DELETE FROM t1; | 20.8 | 40 | 0.591346 |
afbf06d0913320b3b25b289c2adb164bd541911f | 833 | lua | Lua | runtime/mod/core/data/dialog/common.lua | aidatorajiro/elonafoobar | 057dd281eab7b7f8162e4dac363cfadab61708b4 | [
"MIT"
] | null | null | null | runtime/mod/core/data/dialog/common.lua | aidatorajiro/elonafoobar | 057dd281eab7b7f8162e4dac363cfadab61708b4 | [
"MIT"
] | null | null | null | runtime/mod/core/data/dialog/common.lua | aidatorajiro/elonafoobar | 057dd281eab7b7f8162e4dac363cfadab61708b4 | [
"MIT"
] | 1 | 2020-02-24T18:52:19.000Z | 2020-02-24T18:52:19.000Z | local Chara = require("game.Chara")
local Map = require("game.Map")
local GUI = require("game.GUI")
local I18N = require("game.I18N")
local function create_downstairs(x, y, dungeon_level)
Map.set_feat(x, y, 231, 11, dungeon_level)
end
local function quest_completed()
GUI.txt(I18N.get("core.quest.completed"))
GUI.play_sound("core.complete1")
GUI.txt(I18N.get("core.common.something_is_put_on_the_ground"))
GUI.show_journal_update_message()
end
local function args_name()
return {Chara.player().basename}
end
local function args_title()
return {Chara.player().title}
end
local function args_speaker(t)
return {t.speaker}
end
return {
create_downstairs = create_downstairs,
quest_completed = quest_completed,
args_name = args_name,
args_title = args_title,
args_speaker = args_speaker,
}
| 22.513514 | 66 | 0.740696 |
0f3dcc6438ff3d966aef3ee44eea55db66dbaff0 | 594 | dart | Dart | lib/repository/services/security/security_manager_imp.dart | MuhamedAbdalla/Game-Exchange | 9d8c255815fb60c06602defaae834c4174bef57c | [
"MIT"
] | 2 | 2021-01-28T20:18:43.000Z | 2021-04-26T00:17:15.000Z | lib/repository/services/security/security_manager_imp.dart | MuhamedAbdalla/Game-Exchange | 9d8c255815fb60c06602defaae834c4174bef57c | [
"MIT"
] | null | null | null | lib/repository/services/security/security_manager_imp.dart | MuhamedAbdalla/Game-Exchange | 9d8c255815fb60c06602defaae834c4174bef57c | [
"MIT"
] | null | null | null | import 'package:GM_Nav/repository/services/security/security_manager.dart';
class ISecurityManager implements SecurityManager {
@override
String encrypt(String data) {
if (data == null) return '';
String ret = "";
for (int i = 0; i < data.length; i++) {
ret += (String.fromCharCode(data[i].codeUnitAt(0) + 3));
}
return ret;
}
@override
String decrypt(String data) {
if (data == null) return '';
String ret = "";
for (int i = 0; i < data.length; i++) {
ret += (String.fromCharCode(data[i].codeUnitAt(0) - 3));
}
return ret;
}
}
| 24.75 | 75 | 0.60101 |
70fc6f80a894174553e998f3d60b86abb398dd36 | 15,847 | cs | C# | RangeHighlight/RangeHighlighter.cs | jltaylor-us/StardewRangeHighlight | 6a67e8ce440cc42ed00e2c507b3cdabdc7f0f874 | [
"BSD-3-Clause"
] | 1 | 2021-02-22T03:21:01.000Z | 2021-02-22T03:21:01.000Z | RangeHighlight/RangeHighlighter.cs | jltaylor-us/StardewRangeHighlight | 6a67e8ce440cc42ed00e2c507b3cdabdc7f0f874 | [
"BSD-3-Clause"
] | null | null | null | RangeHighlight/RangeHighlighter.cs | jltaylor-us/StardewRangeHighlight | 6a67e8ce440cc42ed00e2c507b3cdabdc7f0f874 | [
"BSD-3-Clause"
] | 2 | 2021-02-25T08:42:07.000Z | 2022-01-14T17:17:21.000Z | // Copyright 2020 Jamie Taylor
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewModdingAPI;
using StardewModdingAPI.Events;
using StardewModdingAPI.Utilities;
using StardewValley;
using StardewValley.Buildings;
using StardewValley.Locations;
using StardewValley.Menus;
namespace RangeHighlight {
using BlueprintHighlightFunction = Func<BluePrint, Tuple<Color, bool[,], int, int>>;
using BuildingHighlightFunction = Func<Building, Tuple<Color, bool[,], int, int>>;
using ItemHighlightFunction = Func<Item, int, string, Tuple<Color, bool[,]>>;
using TASHighlightFunction = Func<TemporaryAnimatedSprite, Tuple<Color, bool[,]>>;
internal class RangeHighlighter {
private readonly IMonitor monitor;
private readonly IModHelper helper;
private readonly ModConfig config;
private readonly Texture2D tileTexture;
private readonly PerScreen<List<Tuple<Color, Point>>> highlightTiles = new PerScreen<List<Tuple<Color, Point>>>(createNewState: () => new List<Tuple<Color, Point>>());
private readonly PerScreen<Mutex> highlightTilesMutex = new PerScreen<Mutex>(createNewState: () => new Mutex());
private readonly PerScreen<bool> showAllDownLastState = new PerScreen<bool>();
private readonly PerScreen<bool> showAllToggleState = new PerScreen<bool>();
private class Highlighter<T> {
public string uniqueId { get; }
public KeybindList hotkey { get; }
public T highlighter { get; }
private readonly PerScreen<bool> hotkeyDownLastState = new PerScreen<bool>();
internal readonly PerScreen<bool> hotkeyToggleState = new PerScreen<bool>();
public Highlighter(string uniqueId, KeybindList hotkey, T highlighter) {
this.uniqueId = uniqueId;
this.hotkey = hotkey;
this.highlighter = highlighter;
}
public void UpdateHotkeyToggleState(IModHelper helper) {
if (this.hotkey.IsBound) {
bool isDown = hotkey.IsDown();
if (isDown && !hotkeyDownLastState.Value)
hotkeyToggleState.Value = !hotkeyToggleState.Value;
hotkeyDownLastState.Value = isDown;
}
}
}
private class ItemHighlighter : Highlighter<ItemHighlightFunction> {
public bool highlightOthersWhenHeld { get; }
public Action onStart { get; }
public Action onFinish { get; }
public ItemHighlighter(string uniqueId, KeybindList hotkey, bool highlightOthersWhenHeld, ItemHighlightFunction highlighter, Action onStart = null, Action onFinish = null)
: base(uniqueId, hotkey, highlighter) {
this.highlightOthersWhenHeld = highlightOthersWhenHeld;
this.onStart = onStart;
this.onFinish = onFinish;
}
}
// NB: blueprintHighlighters and buildingHighlighters are parallel lists. The highlighter in a blueprintHighlighter may be null.
private readonly List<Highlighter<BlueprintHighlightFunction>> blueprintHighlighters = new List<Highlighter<BlueprintHighlightFunction>>();
private readonly List<Highlighter<BuildingHighlightFunction>> buildingHighlighters = new List<Highlighter<BuildingHighlightFunction>>();
private readonly List<ItemHighlighter> itemHighlighters = new List<ItemHighlighter>();
private readonly List<Highlighter<TASHighlightFunction>> tasHighlighters = new List<Highlighter<TASHighlightFunction>>();
public RangeHighlighter(IMonitor monitor, IModHelper helper, ModConfig config) {
this.monitor = monitor;
this.helper = helper;
this.config = config;
tileTexture = helper.Content.Load<Texture2D>("tile.png");
helper.Events.Display.RenderedWorld += OnRenderedWorld;
helper.Events.GameLoop.UpdateTicked += OnUpdateTicked;
}
private void OnRenderedWorld(object sender, RenderedWorldEventArgs e) {
if (highlightTilesMutex.Value.WaitOne(0)) {
try {
foreach (var tuple in highlightTiles.Value) {
var point = tuple.Item2;
var tint = tuple.Item1;
Game1.spriteBatch.Draw(
tileTexture,
Game1.GlobalToLocal(new Vector2(point.X * Game1.tileSize, point.Y * Game1.tileSize)),
null,
tint,
0.0f,
Vector2.Zero,
Game1.pixelZoom,
SpriteEffects.None,
0.01f);
}
} finally {
highlightTilesMutex.Value.ReleaseMutex();
}
}
}
internal void AddHighlightTiles(Color color, bool[,] shape, int xOrigin, int yOrigin) {
int xOffset = shape.GetLength(0) / 2;
int yOffset = shape.GetLength(1) / 2;
if (highlightTilesMutex.Value.WaitOne(0)) {
try {
for (int x = 0; x < shape.GetLength(0); ++x) {
for (int y = 0; y < shape.GetLength(1); ++y) {
if (shape[x, y])
highlightTiles.Value.Add(new Tuple<Color, Point>(color, new Point(xOrigin + x - xOffset, yOrigin + y - yOffset)));
}
}
} finally {
highlightTilesMutex.Value.ReleaseMutex();
}
}
}
public void AddBuildingHighlighter(string uniqueId, KeybindList hotkey,
BlueprintHighlightFunction blueprintHighlighter, BuildingHighlightFunction buildingHighlighter) {
blueprintHighlighters.Insert(0, new Highlighter<BlueprintHighlightFunction>(uniqueId, hotkey, blueprintHighlighter));
buildingHighlighters.Insert(0, new Highlighter<BuildingHighlightFunction>(uniqueId, hotkey, buildingHighlighter));
}
public void RemoveBuildingHighlighter(string uniqueId) {
blueprintHighlighters.RemoveAll(elt => elt.uniqueId == uniqueId);
buildingHighlighters.RemoveAll(elt => elt.uniqueId == uniqueId);
}
public void AddItemHighlighter(string uniqueId, KeybindList hotkey, bool highlightOthersWhenHeld, ItemHighlightFunction highlighter, Action onStart = null, Action onFinish = null) {
itemHighlighters.Insert(0, new ItemHighlighter(uniqueId, hotkey, highlightOthersWhenHeld, highlighter, onStart, onFinish));
}
public void RemoveItemHighlighter(string uniqueId) {
itemHighlighters.RemoveAll(elt => elt.uniqueId == uniqueId);
}
public void AddTemporaryAnimatedSpriteHighlighter(string uniqueId, TASHighlightFunction highlighter) {
tasHighlighters.Insert(0, new Highlighter<TASHighlightFunction>(uniqueId, null, highlighter));
}
public void RemoveTemporaryAnimatedSpriteHighlighter(string uniqueId) {
tasHighlighters.RemoveAll(elt => elt.uniqueId == uniqueId);
}
internal Vector2 GetCursorTile() {
return helper.Input.GetCursorPosition().Tile;
// Work around bug in SMAPI 3.8.0 - fixed in 3.8.2
//var mouse = Microsoft.Xna.Framework.Input.Mouse.GetState();
//return new Vector2((Game1.viewport.X + mouse.X / Game1.options.zoomLevel) / Game1.tileSize,
// (Game1.viewport.Y + mouse.Y / Game1.options.zoomLevel) / Game1.tileSize);
}
private void OnUpdateTicked(object sender, UpdateTickedEventArgs e) {
if (!e.IsMultipleOf(6)) return; // only do this once every 0.1s or so
if (highlightTilesMutex.Value.WaitOne()) {
try {
highlightTiles.Value.Clear();
} finally {
highlightTilesMutex.Value.ReleaseMutex();
}
}
if (Game1.eventUp || Game1.currentLocation == null) return;
bool[] runBuildingHighlighter = new bool[buildingHighlighters.Count];
bool[] runItemHighlighter = new bool[itemHighlighters.Count];
bool[] itemHighlighterStartCalled = new bool[itemHighlighters.Count];
bool iterateBuildings = false;
bool iterateItems = false;
if (Game1.activeClickableMenu != null) {
if (Game1.activeClickableMenu is CarpenterMenu carpenterMenu && Game1.currentLocation is BuildableGameLocation) {
for (int i = 0; i < blueprintHighlighters.Count; ++i) {
if (blueprintHighlighters[i].highlighter != null) {
var ret = blueprintHighlighters[i].highlighter(carpenterMenu.CurrentBlueprint);
if (ret != null) {
var cursorTile = GetCursorTile();
AddHighlightTiles(ret.Item1, ret.Item2, (int)cursorTile.X + ret.Item3, (int)cursorTile.Y + ret.Item4);
runBuildingHighlighter[i] = true;
iterateBuildings = true;
break;
}
}
}
} else {
return;
}
}
if (Game1.currentLocation is BuildableGameLocation buildableLocation) {
// check to see if the cursor is over a building
Building building = buildableLocation.getBuildingAt(Game1.currentCursorTile);
if (building != null) {
for (int i = 0; i < buildingHighlighters.Count; ++i) {
var ret = buildingHighlighters[i].highlighter(building);
if (ret != null) {
// ignore return value; it will be re-computed later when we iterate buildings
runBuildingHighlighter[i] = true;
iterateBuildings = true;
break;
}
}
}
}
if (Game1.player.CurrentItem != null) {
Item item = Game1.player.CurrentItem;
string itemName = item.Name.ToLower();
int itemID = item.ParentSheetIndex;
for (int i = 0; i < itemHighlighters.Count; ++i) {
if (!itemHighlighterStartCalled[i]) {
itemHighlighters[i].onStart?.Invoke();
itemHighlighterStartCalled[i] = true;
}
var ret = itemHighlighters[i].highlighter(item, itemID, itemName);
if (ret != null) {
var cursorTile = GetCursorTile();
AddHighlightTiles(ret.Item1, ret.Item2, (int)cursorTile.X, (int)cursorTile.Y);
if (itemHighlighters[i].highlightOthersWhenHeld) {
runItemHighlighter[i] = true;
}
iterateItems = true;
break;
}
}
}
if (config.hotkeysToggle) {
bool showAllDown = config.ShowAllRangesKey.IsDown();
if (showAllDown && !showAllDownLastState.Value)
showAllToggleState.Value = !showAllToggleState.Value;
showAllDownLastState.Value = showAllDown;
for (int i = 0; i < buildingHighlighters.Count; ++i) {
buildingHighlighters[i].UpdateHotkeyToggleState(helper);
if (showAllToggleState.Value || buildingHighlighters[i].hotkeyToggleState.Value) {
runBuildingHighlighter[i] = true;
iterateBuildings = true;
}
}
for (int i = 0; i < itemHighlighters.Count; ++i) {
itemHighlighters[i].UpdateHotkeyToggleState(helper);
if (showAllToggleState.Value || itemHighlighters[i].hotkeyToggleState.Value) {
runItemHighlighter[i] = true;
iterateItems = true;
}
}
} else {
bool showAll = config.ShowAllRangesKey.IsDown();
for (int i = 0; i < buildingHighlighters.Count; ++i) {
if (showAll || buildingHighlighters[i].hotkey.IsDown()) {
runBuildingHighlighter[i] = true;
iterateBuildings = true;
}
}
for (int i = 0; i < itemHighlighters.Count; ++i) {
if (showAll || itemHighlighters[i].hotkey.IsDown()) {
runItemHighlighter[i] = true;
iterateItems = true;
}
}
}
if (iterateBuildings) {
if (Game1.currentLocation is BuildableGameLocation bl) {
foreach (Building building in bl.buildings) {
for (int i = 0; i < buildingHighlighters.Count; ++i) {
var ret = buildingHighlighters[i].highlighter(building);
if (ret != null) {
AddHighlightTiles(ret.Item1, ret.Item2, building.tileX.Value + ret.Item3, building.tileY.Value + ret.Item4);
break;
}
}
}
}
}
if (iterateItems) {
foreach (var item in Game1.currentLocation.Objects.Values) {
string itemName = item.Name.ToLower();
int itemID = item.ParentSheetIndex;
for (int i = 0; i < itemHighlighters.Count; ++i) {
if (runItemHighlighter[i]) {
if (!itemHighlighterStartCalled[i]) {
itemHighlighters[i].onStart?.Invoke();
itemHighlighterStartCalled[i] = true;
}
var ret = itemHighlighters[i].highlighter(item, itemID, itemName);
if (ret != null) {
AddHighlightTiles(ret.Item1, ret.Item2, (int)item.TileLocation.X, (int)item.TileLocation.Y);
break;
}
}
}
}
}
if (tasHighlighters.Count > 0) {
foreach (var sprite in Game1.currentLocation.temporarySprites) {
foreach (var highlighter in tasHighlighters) {
var ret = highlighter.highlighter(sprite);
if (ret != null) {
AddHighlightTiles(ret.Item1, ret.Item2,
(int)(sprite.position.X / Game1.tileSize), (int)(sprite.position.Y / Game1.tileSize));
break;
}
}
}
}
for (int i = 0; i < itemHighlighters.Count; ++i) {
if (itemHighlighterStartCalled[i]) {
itemHighlighters[i].onFinish?.Invoke();
}
}
}
}
}
| 49.214286 | 189 | 0.539597 |
1a646d5e307c37853b75f6d96aed3f3181e2b001 | 8,537 | asm | Assembly | bahamut/source/menu-dispatcher.asm | higan-emu/bahamut-lagoon-translation-kit | 6f08de5b92b597c0b9ecebd485cc975b99acfc13 | [
"0BSD"
] | 2 | 2021-08-15T04:10:10.000Z | 2021-08-15T20:14:13.000Z | bahamut/source/menu-dispatcher.asm | higan-emu/bahamut-lagoon-translation-kit | 6f08de5b92b597c0b9ecebd485cc975b99acfc13 | [
"0BSD"
] | 1 | 2022-02-16T02:46:39.000Z | 2022-02-16T04:30:29.000Z | bahamut/source/menu-dispatcher.asm | higan-emu/bahamut-lagoon-translation-kit | 6f08de5b92b597c0b9ecebd485cc975b99acfc13 | [
"0BSD"
] | 1 | 2021-12-25T11:34:57.000Z | 2021-12-25T11:34:57.000Z | namespace menu {
seek(codeCursor)
//Bahamut Lagoon shares a lot of code routines between each screen,
//which interferes greatly with tile allocation strategies.
//the dispatcher attempts to record when screens are entered into,
//in order to disambiguate shared routines, and call handlers for
//specific screens instead.
namespace dispatcher {
enqueue pc
seek($ee7b64); jsl hookCampaignMenu
seek($ee7947); jsl hookPartyMenu; nop
seek($ee6f83); jsl party
seek($eea74d); string.hook(party.other)
seek($eea512); string.hook(party.other)
seek($ee6f6c); string.skip() //"Party" static text (used by several screens)
//unit and status screens
seek($ee6fe4); string.hook(mp.setType) //"MP"
seek($ee6ff1); string.hook(mp.setType) //"SP"
seek($ee705a); jsl mp.setCurrent
seek($ee707f); jsl mp.setMaximum
seek($ee701c); jsl mp.setCurrentUnavailable
seek($ee7039); jsl mp.setMaximumUnavailable
//formations and dragons screens
seek($ee99f8); jsl technique.name
seek($eea5cd); jsl technique.blank
seek($ee9a05); jsl technique.level
seek($ee9a1e); jsl technique.multiplier; nop #5
seek($ee9a2c); jsl technique.count
//formations, equipments, information, shop screens
seek($eef02b); jsl page.index
seek($eef01b); jsl page.total
seek($eee6b6); string.hook(page.noItems) //"No Items" text (shop screen)
seek($eeefa8); string.hook(page.noItems) //"No Items" text (information screen)
//shared positions
seek($ee700f); adc #$0000 //"MP"- position (magic, item, unit screens)
seek($ee702c); adc #$0000 //"MP"/ position (magic, item, unit screens)
seek($ee7044); adc #$0000 //"SP"# position (magic, item, unit screens)
dequeue pc
namespace screen {
variable(2, id)
constant unknown = 0
constant formations = 1
constant dragons = 2
constant information = 3
constant equipments = 4
constant magicItem = 5
constant equipment = 6
constant status = 7
constant unit = 8
}
constant menuIndex = $4c
function hookCampaignMenu {
lda.b menuIndex
enter
cmp #$0000; bne +; lda.w #screen.formations; sta screen.id; jmp return; +
cmp #$0001; bne +; lda.w #screen.dragons; sta screen.id; jmp return; +
cmp #$0002; bne +; lda.w #screen.information; sta screen.id; jmp return; +
cmp #$0003; bne +; lda.w #screen.equipments; sta screen.id; jmp return; +
lda.w #screen.unknown; sta screen.id
return:
leave
asl; tax; rtl
}
function hookPartyMenu {
lda.b menuIndex
enter
cmp #$0000; bne +; lda.w #screen.magicItem; sta screen.id; jmp return; + //Magic
cmp #$0001; bne +; lda.w #screen.magicItem; sta screen.id; jmp return; + //Item
cmp #$0002; bne +; lda.w #screen.equipment; sta screen.id; jmp return; +
cmp #$0003; bne +; lda.w #screen.information; sta screen.id; jmp return; +
lda.w #screen.unknown; sta screen.id
return:
leave
cmp #$0003; rtl
}
//A => party#
function party {
enter
dec; and #$0007
pha; lda $0f,s; tax; pla //X => caller
cpx #$8052; bne +; jsl party.party; leave; rtl; + //Party and Campaign
cpx #$a570; bne +; jsl formations.party; leave; rtl; + //Formations (selected)
cpx #$a75e; bne +; jsl overviews.party; leave; rtl; + //Formations and Equipments (list)
cpx #$cb3e; bne +; jsl dragons.party; leave; rtl; + //Dragon Formation
leave; rtl
//other party
function other {
php; rep #$20; pha
lda $04,s //A => caller
cmp #$a515; bne +; lda #$0006; jsl formations.party; pla; plp; rtl; + //Formations (selected)
cmp #$a750; bne +; lda #$0006; jsl overviews.party; pla; plp; rtl; + //Formations and Equipments (list)
pla; plp; rtl
}
}
namespace mp {
variable(2, screen)
variable(2, type)
//A => type ($00 = MP, $80 = SP)
function setType {
php; rep #$20; pha
and #$0080; sta type
lda $0c,s //A => caller
cmp #$8fb5; bne +; lda.w #screen.magicItem; sta screen; lda type; jsl magicItem.mp.setType; pla; plp; rtl; +
cmp #$9679; bne +; lda.w #screen.status; sta screen; lda type; jsl status.mp.setType; pla; plp; rtl; +
cmp #$ae65; bne +; lda.w #screen.unit; sta screen; lda type; jsl unit.mp.setType; pla; plp; rtl; +
cmp #$b7bf; bne +; lda.w #screen.equipment; sta screen; lda type; jsl equipment.mp.setType; pla; plp; rtl; +
lda.w #screen.unknown; sta screen; pla; plp; rtl
}
//A => current value
function setCurrent {
php; rep #$20; pha
lda screen
cmp.w #screen.magicItem; bne +; pla; jsl magicItem.mp.setCurrent; plp; rtl; +
cmp.w #screen.status; bne +; pla; jsl status.mp.setCurrent; plp; rtl; +
cmp.w #screen.unit; bne +; pla; jsl unit.mp.setCurrent; plp; rtl; +
cmp.w #screen.equipment; bne +; pla; jsl equipment.mp.setCurrent; plp; rtl; +
pla; plp; rtl
}
//A => maximum value
function setMaximum {
php; rep #$20; pha
lda screen
cmp.w #screen.magicItem; bne +; pla; jsl magicItem.mp.setMaximum; plp; rtl; +
cmp.w #screen.status; bne +; pla; jsl status.mp.setMaximum; plp; rtl; +
cmp.w #screen.unit; bne +; pla; jsl unit.mp.setMaximum; plp; rtl; +
cmp.w #screen.equipment; bne +; pla; jsl equipment.mp.setMaximum; plp; rtl; +
pla; plp; rtl
}
function setCurrentUnavailable {
php; rep #$20; pha
lda #$ffff; jsl setCurrent
pla; plp; rtl
}
function setMaximumUnavailable {
php; rep #$20; pha
lda #$ffff; jsl setMaximum
pla; plp; rtl
}
}
namespace technique {
//A => technique name
function name {
php; rep #$20; pha
lda screen.id
cmp.w #screen.formations; bne +; pla; jsl formations.technique.name; plp; rtl; +
cmp.w #screen.dragons; bne +; pla; jsl dragons.technique.name; plp; rtl; +
pla; plp; rtl
}
function blank {
php; rep #$20; pha
lda #$00ff //position of "---------" in technique list
jsl name
pla; plp; rtl
}
//A => technique level
function level {
php; rep #$20; pha
lda screen.id
cmp.w #screen.formations; bne +; pla; jsl formations.technique.level; plp; rtl; +
cmp.w #screen.dragons; bne +; pla; jsl dragons.technique.level; plp; rtl; +
pla; plp; rtl
}
//------
//ee9a1e lda #$00e7
//ee9a21 ora $1862
//ee9a24 sta $c400,x
//------
function multiplier {
enter
tilemap.decrementAddress(2)
tilemap.setColorIvory()
tilemap.write(glyph.multiplier)
leave; rtl
}
//A => technique count
function count {
enter
tilemap.setColorIvory()
and #$00ff; add.w #glyph.numbers; pha
lda tilemap.address; tax; pla
ora tilemap.attributes; sta tilemap.location,x
leave; rtl
}
}
namespace page {
variable(2, pageIndex)
variable(2, pageTotal)
variable(2, counter)
//A => current page
function index {
enter
and #$00ff; sta pageIndex
leave; rtl
}
//A => total number of pages
function total {
enter
tilemap.setColorWhite()
and #$00ff; sta pageTotal
ldx #$0000
append.styleTiny()
append.alignSkip(2)
append.literal("Page")
lda pageTotal; cmp.w #10; jcs total_2
total_1: {
tilemap.write($a0fc)
append.alignLeft()
append.alignSkip(24)
lda pageIndex; append.integer1(); append.literal("/")
lda pageTotal; append.integer1()
lda #$0005; render.small.bpp2()
getTileIndex(counter, 2); mul(6); add #$03f4; tax
lda #$0005; write.bpp2()
leave; rtl
}
total_2: {
append.alignLeft()
append.alignSkip(23)
lda pageIndex; append.integer_2(); append.literal("/")
append.alignLeft()
append.alignSkip(37)
lda pageTotal; append.integer_2()
lda #$0006; render.small.bpp2()
getTileIndex(counter, 2); mul(6); add #$03f4; tax
lda #$0006; write.bpp2()
leave; rtl
}
}
function noItems {
enter
tilemap.setColorWhite()
tilemap.write($a0fc)
ldx #$0000; append.styleTiny()
append.alignSkip(2); append.literal("No Items!")
lda #$0005; render.small.bpp2()
getTileIndex(counter, 2); mul(6); add #$03f4; tax
lda #$0005; write.bpp2()
leave; rtl
}
}
}
codeCursor = pc()
}
| 30.708633 | 114 | 0.606068 |
804ea036f078648d8ff3c03389e808b56d57fb2a | 5,961 | java | Java | code/datastudio/testcode/LLT/org.opengauss.mppdbide.bl.test.fragment/src/org/opengauss/mppdbide/test/bl/object/ProfileMetaTest.java | opengauss-mirror/DataStudio | d240050ffb29fa96cbc8ae69e6d6a2e20525a277 | [
"CC-BY-4.0"
] | null | null | null | code/datastudio/testcode/LLT/org.opengauss.mppdbide.bl.test.fragment/src/org/opengauss/mppdbide/test/bl/object/ProfileMetaTest.java | opengauss-mirror/DataStudio | d240050ffb29fa96cbc8ae69e6d6a2e20525a277 | [
"CC-BY-4.0"
] | null | null | null | code/datastudio/testcode/LLT/org.opengauss.mppdbide.bl.test.fragment/src/org/opengauss/mppdbide/test/bl/object/ProfileMetaTest.java | opengauss-mirror/DataStudio | d240050ffb29fa96cbc8ae69e6d6a2e20525a277 | [
"CC-BY-4.0"
] | null | null | null |
package org.opengauss.mppdbide.test.bl.object;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.opengauss.mppdbide.bl.preferences.BLPreferenceManager;
import org.opengauss.mppdbide.bl.preferences.IBLPreference;
import org.opengauss.mppdbide.bl.serverdatacache.ConnectionProfileManagerImpl;
import org.opengauss.mppdbide.bl.serverdatacache.ProfileDiskUtility;
import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfo;
import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.ServerConnectionInfoJsonValidator;
import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.conif.IServerConnectionInfo;
import org.opengauss.mppdbide.bl.serverdatacache.connectioninfo.connectionupgrade.ConnectionProfileUpgradeManager;
import org.opengauss.mppdbide.bl.serverdatacache.savepsswordoption.SavePrdOptions;
import org.opengauss.mppdbide.bl.util.BLUtils;
import org.opengauss.mppdbide.bl.util.IBLUtils;
import org.opengauss.mppdbide.mock.bl.CommonLLTUtils;
import org.opengauss.mppdbide.mock.bl.MockBLPreferenceImpl;
import org.opengauss.mppdbide.mock.bl.ProfileDiskUtilityHelper;
import org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles.ExportConnectionCore;
import org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles.ImportConnectionProfileCore;
import org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles.ImportConnectionProfileCore.MatchedConnectionProfiles;
import org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles.ImportConnectionProfileManager;
import org.opengauss.mppdbide.presentation.exportimportdsconnectionprofiles.OverridingOptions;
import org.opengauss.mppdbide.utils.MPPDBIDEConstants;
import org.opengauss.mppdbide.utils.exceptions.DataStudioSecurityException;
import org.opengauss.mppdbide.utils.exceptions.DatabaseOperationException;
import org.opengauss.mppdbide.utils.files.DSFilesWrapper;
import org.opengauss.mppdbide.utils.files.FilePermissionFactory;
import org.opengauss.mppdbide.utils.files.ISetFilePermission;
import org.opengauss.mppdbide.utils.security.SecureUtil;
import com.mockrunner.jdbc.BasicJDBCTestCaseAdapter;
public class ProfileMetaTest extends BasicJDBCTestCaseAdapter {
ServerConnectionInfo profile;
@Before
public void setUp() throws Exception {
super.setUp();
CommonLLTUtils.runLinuxFilePermissionInstance();
}
@Test
public void test_renameProfile() {
try {
ConnectionProfileManagerImpl managerImpl = ConnectionProfileManagerImpl.getInstance();
ProfileDiskUtility utility = new ProfileDiskUtility();
managerImpl.setDiskUtility(utility);
List<IServerConnectionInfo> allProfiles = managerImpl.getAllProfiles();
int currentSize = allProfiles.size();
ServerConnectionInfo serverInfonew = new ServerConnectionInfo();
serverInfonew.setConectionName("newConnection");
serverInfonew.setServerIp("");
serverInfonew.setServerPort(5432);
serverInfonew.setDatabaseName("Gauss");
serverInfonew.setUsername("myusername");
serverInfonew.setPrd("mypassword".toCharArray());
serverInfonew.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE);
final String path = "/home/test/";
final String path1 = "home/test1";
IBLUtils blUtils = BLUtils.getInstance();
utility.setOsCurrentUserFolderPath(path);
List<Integer> profIds = utility.getMetaData().getAllProfileIds();
utility.getMetaData().addProfile("Prof1", "109", path, "v1800");
utility.getMetaData().addProfile("Prof1", "109", path1, "v1800");
utility.getMetaData().writeToDisk("home/test1");
utility.getMetaData().getProfileId("jshfedhjs");
managerImpl.saveProfile(serverInfonew);
} catch (DatabaseOperationException e) {
System.out.println("as expected");
} catch (Exception e) {
e.printStackTrace();
System.out.println("as expected");
}
}
@Test
public void test_Invalidpath() {
try {
ConnectionProfileManagerImpl managerImpl = ConnectionProfileManagerImpl.getInstance();
ProfileDiskUtility utility = new ProfileDiskUtility();
managerImpl.setDiskUtility(utility);
List<IServerConnectionInfo> allProfiles = managerImpl.getAllProfiles();
int currentSize = allProfiles.size();
ServerConnectionInfo serverInfonew = new ServerConnectionInfo();
serverInfonew.setConectionName("newConnection");
serverInfonew.setServerIp("");
serverInfonew.setServerPort(5432);
serverInfonew.setDatabaseName("Gauss");
serverInfonew.setUsername("myusername");
serverInfonew.setPrd("mypassword".toCharArray());
serverInfonew.setSavePrdOption(SavePrdOptions.DO_NOT_SAVE);
final String path = "/home/test/";
final String path1 = "home/test1";
IBLUtils blUtils = BLUtils.getInstance();
utility.setOsCurrentUserFolderPath(path);
List<Integer> profIds = utility.getMetaData().getAllProfileIds();
utility.getMetaData().addProfile("Prof1", "109", path, "v1800");
utility.getMetaData().addProfile("Prof1", "109", path1, "v1800");
utility.getMetaData().getProfileId("Prof1");
utility.getMetaData().deleteProfile("Prof1");
utility.getMetaData().writeToDisk("shjgfsyhjd");
} catch (DatabaseOperationException e) {
System.out.println("as expected");
} catch (Exception e) {
e.printStackTrace();
System.out.println("as expected");
}
}
}
| 42.276596 | 130 | 0.804899 |
755dfd344386bd5a3722f7336d27262c719ece5a | 11,226 | h | C | src/master/master_sm.pb.h | CVKiLiu/phxpaxos | 7f0f82df5b307a631cc2310ccc4365a5f7f80a11 | [
"OpenSSL"
] | null | null | null | src/master/master_sm.pb.h | CVKiLiu/phxpaxos | 7f0f82df5b307a631cc2310ccc4365a5f7f80a11 | [
"OpenSSL"
] | null | null | null | src/master/master_sm.pb.h | CVKiLiu/phxpaxos | 7f0f82df5b307a631cc2310ccc4365a5f7f80a11 | [
"OpenSSL"
] | null | null | null | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: master_sm.proto
#ifndef PROTOBUF_master_5fsm_2eproto__INCLUDED
#define PROTOBUF_master_5fsm_2eproto__INCLUDED
#include <string>
#include <google/protobuf/stubs/common.h>
#if GOOGLE_PROTOBUF_VERSION < 3000000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers. Please update
#error your headers.
#endif
#if 3000000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers. Please
#error regenerate this file with a newer version of protoc.
#endif
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>
#include <google/protobuf/extension_set.h>
#include <google/protobuf/unknown_field_set.h>
// @@protoc_insertion_point(includes)
namespace phxpaxos {
// Internal implementation detail -- do not call these.
void protobuf_AddDesc_master_5fsm_2eproto();
void protobuf_AssignDesc_master_5fsm_2eproto();
void protobuf_ShutdownFile_master_5fsm_2eproto();
class MasterOperator;
// ===================================================================
class MasterOperator : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:phxpaxos.MasterOperator) */ {
public:
MasterOperator();
virtual ~MasterOperator();
MasterOperator(const MasterOperator& from);
inline MasterOperator& operator=(const MasterOperator& from) {
CopyFrom(from);
return *this;
}
inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
return _internal_metadata_.unknown_fields();
}
inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
return _internal_metadata_.mutable_unknown_fields();
}
static const ::google::protobuf::Descriptor* descriptor();
static const MasterOperator& default_instance();
void Swap(MasterOperator* other);
// implements Message ----------------------------------------------
inline MasterOperator* New() const { return New(NULL); }
MasterOperator* New(::google::protobuf::Arena* arena) const;
void CopyFrom(const ::google::protobuf::Message& from);
void MergeFrom(const ::google::protobuf::Message& from);
void CopyFrom(const MasterOperator& from);
void MergeFrom(const MasterOperator& from);
void Clear();
bool IsInitialized() const;
int ByteSize() const;
bool MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input);
void SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const;
::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* output) const;
::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const {
return InternalSerializeWithCachedSizesToArray(false, output);
}
int GetCachedSize() const { return _cached_size_; }
private:
void SharedCtor();
void SharedDtor();
void SetCachedSize(int size) const;
void InternalSwap(MasterOperator* other);
private:
inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
return _internal_metadata_.arena();
}
inline void* MaybeArenaPtr() const {
return _internal_metadata_.raw_arena_ptr();
}
public:
::google::protobuf::Metadata GetMetadata() const;
// nested types ----------------------------------------------------
// accessors -------------------------------------------------------
// required uint64 nodeid = 1;
bool has_nodeid() const;
void clear_nodeid();
static const int kNodeidFieldNumber = 1;
::google::protobuf::uint64 nodeid() const;
void set_nodeid(::google::protobuf::uint64 value);
// required uint64 version = 2;
bool has_version() const;
void clear_version();
static const int kVersionFieldNumber = 2;
::google::protobuf::uint64 version() const;
void set_version(::google::protobuf::uint64 value);
// required int32 timeout = 3;
bool has_timeout() const;
void clear_timeout();
static const int kTimeoutFieldNumber = 3;
::google::protobuf::int32 timeout() const;
void set_timeout(::google::protobuf::int32 value);
// required uint32 operator = 4;
bool has_operator_() const;
void clear_operator_();
static const int kOperatorFieldNumber = 4;
::google::protobuf::uint32 operator_() const;
void set_operator_(::google::protobuf::uint32 value);
// required uint32 sid = 5;
bool has_sid() const;
void clear_sid();
static const int kSidFieldNumber = 5;
::google::protobuf::uint32 sid() const;
void set_sid(::google::protobuf::uint32 value);
// optional uint64 lastversion = 6;
bool has_lastversion() const;
void clear_lastversion();
static const int kLastversionFieldNumber = 6;
::google::protobuf::uint64 lastversion() const;
void set_lastversion(::google::protobuf::uint64 value);
// @@protoc_insertion_point(class_scope:phxpaxos.MasterOperator)
private:
inline void set_has_nodeid();
inline void clear_has_nodeid();
inline void set_has_version();
inline void clear_has_version();
inline void set_has_timeout();
inline void clear_has_timeout();
inline void set_has_operator_();
inline void clear_has_operator_();
inline void set_has_sid();
inline void clear_has_sid();
inline void set_has_lastversion();
inline void clear_has_lastversion();
// helper for ByteSize()
int RequiredFieldsByteSizeFallback() const;
::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
::google::protobuf::uint32 _has_bits_[1];
mutable int _cached_size_;
::google::protobuf::uint64 nodeid_;
::google::protobuf::uint64 version_;
::google::protobuf::int32 timeout_;
::google::protobuf::uint32 operator__;
::google::protobuf::uint64 lastversion_;
::google::protobuf::uint32 sid_;
friend void protobuf_AddDesc_master_5fsm_2eproto();
friend void protobuf_AssignDesc_master_5fsm_2eproto();
friend void protobuf_ShutdownFile_master_5fsm_2eproto();
void InitAsDefaultInstance();
static MasterOperator* default_instance_;
};
// ===================================================================
// ===================================================================
#if !PROTOBUF_INLINE_NOT_IN_HEADERS
// MasterOperator
// required uint64 nodeid = 1;
inline bool MasterOperator::has_nodeid() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
inline void MasterOperator::set_has_nodeid() {
_has_bits_[0] |= 0x00000001u;
}
inline void MasterOperator::clear_has_nodeid() {
_has_bits_[0] &= ~0x00000001u;
}
inline void MasterOperator::clear_nodeid() {
nodeid_ = GOOGLE_ULONGLONG(0);
clear_has_nodeid();
}
inline ::google::protobuf::uint64 MasterOperator::nodeid() const {
// @@protoc_insertion_point(field_get:phxpaxos.MasterOperator.nodeid)
return nodeid_;
}
inline void MasterOperator::set_nodeid(::google::protobuf::uint64 value) {
set_has_nodeid();
nodeid_ = value;
// @@protoc_insertion_point(field_set:phxpaxos.MasterOperator.nodeid)
}
// required uint64 version = 2;
inline bool MasterOperator::has_version() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
inline void MasterOperator::set_has_version() {
_has_bits_[0] |= 0x00000002u;
}
inline void MasterOperator::clear_has_version() {
_has_bits_[0] &= ~0x00000002u;
}
inline void MasterOperator::clear_version() {
version_ = GOOGLE_ULONGLONG(0);
clear_has_version();
}
inline ::google::protobuf::uint64 MasterOperator::version() const {
// @@protoc_insertion_point(field_get:phxpaxos.MasterOperator.version)
return version_;
}
inline void MasterOperator::set_version(::google::protobuf::uint64 value) {
set_has_version();
version_ = value;
// @@protoc_insertion_point(field_set:phxpaxos.MasterOperator.version)
}
// required int32 timeout = 3;
inline bool MasterOperator::has_timeout() const {
return (_has_bits_[0] & 0x00000004u) != 0;
}
inline void MasterOperator::set_has_timeout() {
_has_bits_[0] |= 0x00000004u;
}
inline void MasterOperator::clear_has_timeout() {
_has_bits_[0] &= ~0x00000004u;
}
inline void MasterOperator::clear_timeout() {
timeout_ = 0;
clear_has_timeout();
}
inline ::google::protobuf::int32 MasterOperator::timeout() const {
// @@protoc_insertion_point(field_get:phxpaxos.MasterOperator.timeout)
return timeout_;
}
inline void MasterOperator::set_timeout(::google::protobuf::int32 value) {
set_has_timeout();
timeout_ = value;
// @@protoc_insertion_point(field_set:phxpaxos.MasterOperator.timeout)
}
// required uint32 operator = 4;
inline bool MasterOperator::has_operator_() const {
return (_has_bits_[0] & 0x00000008u) != 0;
}
inline void MasterOperator::set_has_operator_() {
_has_bits_[0] |= 0x00000008u;
}
inline void MasterOperator::clear_has_operator_() {
_has_bits_[0] &= ~0x00000008u;
}
inline void MasterOperator::clear_operator_() {
operator__ = 0u;
clear_has_operator_();
}
inline ::google::protobuf::uint32 MasterOperator::operator_() const {
// @@protoc_insertion_point(field_get:phxpaxos.MasterOperator.operator)
return operator__;
}
inline void MasterOperator::set_operator_(::google::protobuf::uint32 value) {
set_has_operator_();
operator__ = value;
// @@protoc_insertion_point(field_set:phxpaxos.MasterOperator.operator)
}
// required uint32 sid = 5;
inline bool MasterOperator::has_sid() const {
return (_has_bits_[0] & 0x00000010u) != 0;
}
inline void MasterOperator::set_has_sid() {
_has_bits_[0] |= 0x00000010u;
}
inline void MasterOperator::clear_has_sid() {
_has_bits_[0] &= ~0x00000010u;
}
inline void MasterOperator::clear_sid() {
sid_ = 0u;
clear_has_sid();
}
inline ::google::protobuf::uint32 MasterOperator::sid() const {
// @@protoc_insertion_point(field_get:phxpaxos.MasterOperator.sid)
return sid_;
}
inline void MasterOperator::set_sid(::google::protobuf::uint32 value) {
set_has_sid();
sid_ = value;
// @@protoc_insertion_point(field_set:phxpaxos.MasterOperator.sid)
}
// optional uint64 lastversion = 6;
inline bool MasterOperator::has_lastversion() const {
return (_has_bits_[0] & 0x00000020u) != 0;
}
inline void MasterOperator::set_has_lastversion() {
_has_bits_[0] |= 0x00000020u;
}
inline void MasterOperator::clear_has_lastversion() {
_has_bits_[0] &= ~0x00000020u;
}
inline void MasterOperator::clear_lastversion() {
lastversion_ = GOOGLE_ULONGLONG(0);
clear_has_lastversion();
}
inline ::google::protobuf::uint64 MasterOperator::lastversion() const {
// @@protoc_insertion_point(field_get:phxpaxos.MasterOperator.lastversion)
return lastversion_;
}
inline void MasterOperator::set_lastversion(::google::protobuf::uint64 value) {
set_has_lastversion();
lastversion_ = value;
// @@protoc_insertion_point(field_set:phxpaxos.MasterOperator.lastversion)
}
#endif // !PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace phxpaxos
// @@protoc_insertion_point(global_scope)
#endif // PROTOBUF_master_5fsm_2eproto__INCLUDED
| 32.258621 | 132 | 0.729645 |
8614057161333cb4a079014128ae63cc370e09f1 | 155 | java | Java | src/main/java/com/noctarius/graphquul/ast/InterfaceTypeDefinition.java | microprograms/graphquul | e28558233e18bc48c769d94e647dfeffe6998e69 | [
"Apache-2.0"
] | 3 | 2017-01-28T20:06:58.000Z | 2020-11-23T13:50:21.000Z | src/main/java/com/noctarius/graphquul/ast/InterfaceTypeDefinition.java | microprograms/graphquul | e28558233e18bc48c769d94e647dfeffe6998e69 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/noctarius/graphquul/ast/InterfaceTypeDefinition.java | microprograms/graphquul | e28558233e18bc48c769d94e647dfeffe6998e69 | [
"Apache-2.0"
] | 2 | 2020-04-12T02:09:14.000Z | 2021-12-07T09:39:39.000Z | package com.noctarius.graphquul.ast;
public interface InterfaceTypeDefinition
extends TypeDefinition, NamedType, Directives, FieldDefinitions {
}
| 25.833333 | 73 | 0.806452 |
7aea00f6df20ffaacd6f7beb2e210c87d6167aaf | 540 | swift | Swift | FDJSport/Scenes/TeamsList/Cell/TeamPresenter.swift | khaled-el-abed/aubay-test | 4eb01be4f88c790787f021fc98002d78699beeef | [
"MIT"
] | null | null | null | FDJSport/Scenes/TeamsList/Cell/TeamPresenter.swift | khaled-el-abed/aubay-test | 4eb01be4f88c790787f021fc98002d78699beeef | [
"MIT"
] | null | null | null | FDJSport/Scenes/TeamsList/Cell/TeamPresenter.swift | khaled-el-abed/aubay-test | 4eb01be4f88c790787f021fc98002d78699beeef | [
"MIT"
] | null | null | null | //
// TeamViewModel.swift
// FDJSport
//
// Created by Khaled ElAbed perso on 15/01/2022.
//
import Foundation
protocol TeamPresenterProtocol {
var logoURL: URL? { get }
}
final class TeamPresenter: TeamPresenterProtocol {
// MARK: - Initialization
init(team: Team) {
self.team = team
}
// MARK: - Public Properties
var logoURL: URL? {
guard let logo = team.logo else { return nil }
return URL(string: logo)
}
// MARK: - Private Propetries
private let team: Team
}
| 15 | 54 | 0.616667 |
dd7e03a64ef58aa5ff31797ddefc6d94ee9ee2fc | 3,578 | php | PHP | classes/Controller/Admin/Pages.php | i118/module-admin | b0e624c8ff64a43e67339536c2939417267edd31 | [
"Apache-2.0"
] | null | null | null | classes/Controller/Admin/Pages.php | i118/module-admin | b0e624c8ff64a43e67339536c2939417267edd31 | [
"Apache-2.0"
] | null | null | null | classes/Controller/Admin/Pages.php | i118/module-admin | b0e624c8ff64a43e67339536c2939417267edd31 | [
"Apache-2.0"
] | 1 | 2018-10-24T11:31:33.000Z | 2018-10-24T11:31:33.000Z | <?php
defined('SYSPATH') or die('No direct script access.');
class Controller_Admin_Pages extends Controller_Admin_Index {
public function before() {
parent::before();
//Вывод в шаблон
$this->template->page_title = 'Страницы';
}
public function action_index() {
$pages = ORM::factory('Pages')->find_all();
$content = View::factory('admin/page/pages', array('pages' => $pages, 'url' => $this->url));
$this->template->page_title = 'Страницы';
$this->template->block_center = $content;
}
public function action_add() {
$pages = ORM::factory('Page');
$all_pages = $pages->fulltree()->as_array();
if (isset($_POST['submit'])) {
$page_data = Arr::extract($_POST, array('page_title', 'page_id', 'url', 'page_content', 'page_status'));
$pages->values($page_data);
try {
if (!$page_data['page_id']) {
$pages->make_root();
} else {
$pages->insert_as_last_child($page_data['page_id']);
}
HTTP::redirect('/admin/pages/add');
# $pages->save();
} catch (ORM_Validation_Exception $e) {
$errors = $e->errors('validation');
var_dump($errors);
exit();
}
}
/*
$data = Arr::extract($_POST, array('page_title', 'page_alias', 'page_text', 'page_description', 'page_keywords', 'page_status'));
$pages = ORM::factory('Pages');
$pages->values($data);
try {
$pages->save();
HTTP::redirect('/admin/pages');
} catch (ORM_Validation_Exception $e) {
$errors = $e->errors('validation');
}
}
*/
$content = View::factory('admin/page/addpages')
->bind('all_pages', $all_pages)
->bind('errors', $errors)
->bind('data', $data);
$this->template->page_title = 'Добавить страницу';
$this->template->block_center = $content;
}
public function action_edit() {
$id = (int) $this->request->param('id');
$pages = ORM::factory('Pages', $id);
if (!$pages->loaded()) {
HTTP::redirect('/admin/pages');
}
$data = $pages->as_array();
// Редактирование
if (isset($_POST['submit'])) {
$data = Arr::extract($_POST, array('page_title', 'page_alias', 'page_text', 'page_description', 'page_keywords', 'page_status'));
$pages->values($data);
try {
$pages->save();
HTTP::redirect('admin/pages');
} catch (ORM_Validation_Exception $e) {
$errors = $e->errors('validation');
}
}
$content = View::factory('admin/page/editpages')
->bind('id', $id)
->bind('errors', $errors)
->bind('data', $data);
$this->template->page_title = 'Редактировть страницу';
$this->template->block_center = $content;
}
public function action_delete() {
if ($this->user->username == 'demo') {
HTTP::redirect('admin/pages?act=demo');
exit;
}
$id = (int) $this->request->param('id');
$pages = ORM::factory('Pages', $id);
if (!$pages->loaded()) {
HTTP::redirect('admin/pages');
}
$pages->delete();
HTTP::redirect('admin/pages');
}
}
| 28.854839 | 141 | 0.49469 |
1683ee9d6982638e17888d97f948f828a34917d2 | 3,465 | h | C | mulberryAR/VVISION/engine/vvision/Renderer/OffscreenRenderTarget.h | polobymulberry/mulberryAR | ae2c207563da7bbf4c382ee27a78558d5c482333 | [
"MIT"
] | 18 | 2017-02-17T09:28:10.000Z | 2021-08-09T04:43:39.000Z | mulberryAR/VVISION/engine/vvision/Renderer/OffscreenRenderTarget.h | jjzhang166/mulberryAR | ae2c207563da7bbf4c382ee27a78558d5c482333 | [
"MIT"
] | 1 | 2018-04-13T02:38:33.000Z | 2018-12-25T06:12:56.000Z | mulberryAR/VVISION/engine/vvision/Renderer/OffscreenRenderTarget.h | jjzhang166/mulberryAR | ae2c207563da7bbf4c382ee27a78558d5c482333 | [
"MIT"
] | 12 | 2017-03-22T09:08:18.000Z | 2021-06-27T12:48:14.000Z | /* OffscreenRenderTarget.h
*
* Virtual Vision Engine . Copyright (C) 2012 Abdallah DIB.
* All rights reserved. Email: Abdallah.dib@virtual-vison.net
* Web: <http://www.virutal-vision.net/>
*
* This program 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
* (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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.*/
#ifndef VVISION_Offscreen_Render_Target_h
#define VVISION_Offscreen_Render_Target_h
#include "FrameBufferObject.h"
#include "RenderBuffer.h"
namespace vvision
{
enum CONTEXT_TYPE
{
/** rgb */
kCONTEXT_COLOR = 0x01,
/** depth context*/
kCONTEXT_DEPTH = 0x02,
/** stencil ( not implemented )*/
kCONTEXT_STENCIL = 0x04,
};
/**
offscreen render target, when enabled all OpenGL drawing command will go through this context, offscreen rendering is useful for post processing effects, shadow mapping, reflections, and gpgpu... this offscreen render target doesnt support MRT, u can only attach a texture to the GL_COLOR_ATTACHMENT0 point and a depth buffer to the GL_DEPTH_ATTACHMENT point.
*/
class COffscreenRenderTarget
{
public :
/** constructor create an offscreen render target
*/
COffscreenRenderTarget();
/** destructor*/
~COffscreenRenderTarget();
/** ( intialiaze offscreen rendering) u should at least create an offscreen target with a color buffer attached
if kCONTEXT_COLOR passed a color texture will be attached to the GL_COLOR_ATTACHMENT0 point
if kCONTEXT_DEPTH passed a depth render buffer will be attached GL_DEPTH_ATTACHMENT point
*/
bool Initialize(uint32 context_type = kCONTEXT_COLOR | kCONTEXT_DEPTH, uint32 context_size = 512);
/** return the attached color buffer*/
inline CTexture* GetColorBuffer() {return m_pColor;}
/** activate context ( all drawing commands will be executed into this context*/
void Enable();
/** disable context and switch back to default context ( the default context is one bound before Enable was called, this is retrieved via glGetIntegerv(GL_FRAMEBUFFER_BINDING, &m_uCurrentFbo); for better performance, it is better to remove the glGet from the rendering loop ( the case when u know the fbo ID )*/
void Disable();
private:
/** not permitted*/
COffscreenRenderTarget(const COffscreenRenderTarget& sm);
COffscreenRenderTarget& operator=(const COffscreenRenderTarget& sm);
void CleanUp();
uint32 m_iContextSize;
CFrameBufferObject* m_pFbo;
CRenderBuffer* m_pDepth;
CTexture* m_pColor;
/** current bound fbo */
int32 m_uCurrentFbo;
/** default viewport*/
int32 m_vViewport[4];
};
}
#endif
| 37.258065 | 364 | 0.673593 |
90cb6bdcc40ec44e620644d7faca6967693d0580 | 2,009 | py | Python | examples/plotting/plot_graph.py | WeilerP/cellrank | c8c2b9f6bd2448861fb414435aee7620ca5a0bad | [
"BSD-3-Clause"
] | 172 | 2020-03-19T19:50:53.000Z | 2022-03-28T09:36:04.000Z | examples/plotting/plot_graph.py | WeilerP/cellrank | c8c2b9f6bd2448861fb414435aee7620ca5a0bad | [
"BSD-3-Clause"
] | 702 | 2020-03-19T08:09:04.000Z | 2022-03-30T09:55:14.000Z | examples/plotting/plot_graph.py | WeilerP/cellrank | c8c2b9f6bd2448861fb414435aee7620ca5a0bad | [
"BSD-3-Clause"
] | 17 | 2020-04-07T03:11:02.000Z | 2022-02-02T20:39:16.000Z | """
Plot graph structures
---------------------
This functions show how to plot graph structures, such as the transition matrix.
"""
import cellrank as cr
import numpy as np
adata = cr.datasets.pancreas_preprocessed("../example.h5ad")
adata
# %%
# First, we create a forward transition matrix using the high-level pipeline.
cr.tl.transition_matrix(
adata, show_progress_bar=False, weight_connectivities=0.2, softmax_scale=4
)
# %%
# We can now plot the transition matrix. Below we don't show any arrows, which dramatically speeds up the plotting.
cr.pl.graph(
adata,
"T_fwd",
edge_alpha=0.1,
node_size=5,
arrows=False,
keys="clusters",
keylocs="obs",
)
# %%
# To further illustrate the functionalities, let us only consider the `'Delta`' cluster. We can also filter the edges
# by their weights, as shown below. Only transitions with probability at least 0.1 are plotted.
ixs = np.where(adata.obs["clusters"] == "Delta")[0]
cr.pl.graph(adata, "T_fwd", ixs=ixs, arrows=True, node_size=200, filter_edges=(0.1, 1))
# %%
# Lastly, we can visualize different edge aggregations, such as minimum or maximum. Here we take at most 3 outgoing
# edges restricted to ``ixs`` for each node in descending order and color the nodes by the maximum outgoing weights.
# Aggregated values are always computed before any filtering happens, such as shown above.
#
# Here we also specify ``edge_reductions_restrict_to_ixs`` (by default, it is the same as ``ixs``) that computes the
# statistic between the cells marked with ``ixs`` and ``edge_reductions_restrict_to_ixs``.
#
# Below we compare the maximum transition from each of the `"Delta"` cells to any of the `"Beta"` cells.
cr.pl.graph(
adata,
"T_fwd",
ixs=ixs,
edge_alpha=0.5,
node_size=200,
keys="outgoing",
arrows=False,
top_n_edges=(3, False, "outgoing"),
title="outgoing to Beta",
edge_reductions=np.max,
edge_reductions_restrict_to_ixs=np.where(adata.obs["clusters"] == "Beta")[0],
)
| 32.403226 | 117 | 0.711797 |
9c609dc57ad05d10e10c90a2c02cde51fa534088 | 1,665 | js | JavaScript | client/src/components/Slide.js | Linton-IET-On-Campus/linton-iet-on-campus | 08d9161eeff1bb86088d34e5b550a42eb481309c | [
"MIT"
] | null | null | null | client/src/components/Slide.js | Linton-IET-On-Campus/linton-iet-on-campus | 08d9161eeff1bb86088d34e5b550a42eb481309c | [
"MIT"
] | 1 | 2022-01-15T03:12:09.000Z | 2022-01-15T03:12:09.000Z | client/src/components/Slide.js | Linton-IET-On-Campus/linton-iet-on-campus | 08d9161eeff1bb86088d34e5b550a42eb481309c | [
"MIT"
] | 1 | 2020-02-25T04:54:09.000Z | 2020-02-25T04:54:09.000Z | import React from 'react';
import Carousel from 'react-bootstrap/Carousel';
import styled from 'styled-components';
const Styles = styled.div`
.d-block{
width: 100% !important;
height: 80vh !important;
}
.carousel{
left: 0;
width: 100%;
z-index:-1;
}
@media only screen and (max-width: 960px) {
.d-block{
height: 80vw !important;
}
}
`;
export const Slide = (props) => (
<Styles>
<Carousel>
<Carousel.Item>
<img
className="d-block"
src="https://image.freepik.com/free-vector/industry-4-0-illustration_46706-810.jpg"
alt="First slide"
/>
<Carousel.Caption>
<h3>Industrial Revolution 4.0</h3>
<p>IR 4.0 is coming faster than anyone expected, are you ready?</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block"
src="https://images.unsplash.com/photo-1453060113865-968cea1ad53a?ixlib=rb-1.2.1&auto=format&fit=crop&w=1050&q=80"
alt="Third slide"
/>
<Carousel.Caption>
<h3>Learn to Code</h3>
<p>Knowing how to code is the most essential skill in 21<sup>st</sup> century.</p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item>
<img
className="d-block"
src="https://images.unsplash.com/photo-1510146758428-e5e4b17b8b6a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1050&q=80"
alt="Third slide"
/>
<Carousel.Caption>
<h3>No Man Is An Island</h3>
<p>We teach, we learn, we play and together we grow.</p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</Styles>
) | 25.615385 | 146 | 0.613213 |
477c0f39c23c6630593b9470ae467dfa9b431cca | 1,959 | html | HTML | haiku/cl-haiku.html | teahelaschuk/site | f4b1e4b8453fa7acc50ac9af27fd664d5a5f73ed | [
"MIT"
] | null | null | null | haiku/cl-haiku.html | teahelaschuk/site | f4b1e4b8453fa7acc50ac9af27fd664d5a5f73ed | [
"MIT"
] | null | null | null | haiku/cl-haiku.html | teahelaschuk/site | f4b1e4b8453fa7acc50ac9af27fd664d5a5f73ed | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h3>Changelog: Haiku Generator</h3>
<h4>Unreleased:</h4>
<ul>
<li>make mobile-friendly</li>
<li>fix dictionary</li>
<li><s>voting daily limit</s> - may not be possible with datalist, need more research</li>
<li>fix error messages</li>
<li>reduce spam</li>
</ul>
<h4>[2.0.1] - July 30 2018:</h4>
<ul>
<li>created dictionary github page + email server, and added links</li>
</ul>
<h4>[2.0] - July 29 2018:</h4>
<ul>
<li>commented + refactored code</li>
</ul>
<h4>[1.4.2] - July 29 2018:</h4>
<ul>
<li>refactored data access code</li>
<li>fixed guestbook and generator to reload or update when approriate</li>
<li>added second update panel for generator</li>
<li>removed page reloads</li>
</ul>
<h4>[1.4.1] - July 29 2018:</h4>
<ul>
<li>added an update panel, fix reloading issues</li>
<li>voting functionality disabled temporarily -- still buggy here</li>
</ul>
<h4>[1.4.0] - July 28 2018:</h4>
<ul>
<li>votes working</li>
</ul>
<h4>[1.3.0] - July 24 2018:</h4>
<ul>
<li>edited dictionary</li>
<li>tweaked css/layout</li>
<li>added insertion into database and display in guestbook</li>
<li>fixed datalist, now updates appropriately</li>
</ul>
<h4>[1.2.0] - July 23 2018:</h4>
<ul>
<li>added guestbook, generator, and image panels</li>
<li>database written and displayed in guestbook</li>
<li>edited dictionary</li>
</ul>
<h4>[1.1.0] - July 21 2018:</h4>
<ul>
<li>attached project to gallery site</li>
<li>edited dictionary</li>
</ul>
<h4>[1.0.0] - July 20 2018:</h4>
<ul>
<li>haiku generating algorithm written</li>
</ul>
</body>
</html> | 25.441558 | 98 | 0.558959 |
717eaa67ec5f0c703082877b7b944f7a3c7929f1 | 4,126 | ts | TypeScript | src/tasks/tasks.service.ts | simasware/gnar-challenge | 88525884fa2557ead2e090fb19bf4a3489ee594f | [
"MIT"
] | null | null | null | src/tasks/tasks.service.ts | simasware/gnar-challenge | 88525884fa2557ead2e090fb19bf4a3489ee594f | [
"MIT"
] | null | null | null | src/tasks/tasks.service.ts | simasware/gnar-challenge | 88525884fa2557ead2e090fb19bf4a3489ee594f | [
"MIT"
] | null | null | null | import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import {
IPaginationOptions,
paginate,
Pagination,
} from 'nestjs-typeorm-paginate';
import { TaskOwners } from 'src/database/Entities/TaskOwners';
import Tasks from 'src/database/Entities/Tasks';
import { Repository } from 'typeorm';
import TaskDTO from './DTO/TaskDTO';
import { TaskInfoDTO } from './DTO/TaskInfoDTO';
import { TaskOwnerDTO } from './DTO/TaskOwnerDTO';
import { UpdateTaskStatusDTO } from './DTO/UpdateTaskStatusDTO';
@Injectable()
export class TasksService {
constructor(
@InjectRepository(Tasks) private readonly taskRepo: Repository<Tasks>,
@InjectRepository(TaskOwners)
private readonly taskOwnerRepo: Repository<TaskOwners>,
) {}
async findAll(options: IPaginationOptions): Promise<Pagination<Tasks>> {
return paginate<Tasks>(this.taskRepo, options);
}
async findOne(taskId: string): Promise<Object | null> {
const children = await this.taskRepo.find({
select: ['id', 'title'],
where: { parentTask: taskId },
});
const tasks = await this.taskRepo.findOne({
where: { id: taskId },
relations: ['owner', 'owners'],
});
return {
taskInfo: tasks,
children: children,
};
}
private checkChildrenDueDate(
parentTask: TaskInfoDTO,
childrenInfo: TaskDTO[],
) {
if (!childrenInfo?.length) {
return true;
}
const maxDate = childrenInfo.reduce((prev, current) => {
return prev.taskInfo.dueDate > current.taskInfo.dueDate ? prev : current;
});
return maxDate.taskInfo.dueDate === parentTask.dueDate;
}
private checkIfChildrenHasChild(childrenInfo: TaskDTO[]) {
const filtered = childrenInfo.filter((child) => {
return child.children?.length > 0;
});
return filtered.length >= 1;
}
private createChildrenTasks(parent: Tasks, children: TaskDTO[]) {
children.forEach(async (child) => {
const childTask = new Tasks(child.taskInfo);
childTask.parentTask = parent.id;
await this.taskRepo.save(childTask);
});
}
private createTaskOwners(parent: Tasks, taskOwners: TaskOwnerDTO[]) {
taskOwners.forEach(async (taskOwner) => {
const owner = new TaskOwners();
owner.taskId = parent.id;
owner.ownerId = taskOwner.ownerId;
await this.taskOwnerRepo.save(owner);
});
}
private async taskHasUnfinishedChildren(taskId: string): Promise<boolean> {
const childrenCount = await this.taskRepo
.createQueryBuilder('tasks')
.select('id as taskId')
.where('parent_task = :taskId', { taskId: taskId })
.andWhere('status != :status', { status: 'done' })
.getCount();
return childrenCount > 0;
}
async createOne(taskDto: TaskDTO): Promise<Tasks | null> {
if (taskDto.children) {
if (this.checkIfChildrenHasChild(taskDto.children)) {
throw new BadRequestException(
'Task children cannot have its own children!',
);
}
if (!this.checkChildrenDueDate(taskDto.taskInfo, taskDto.children)) {
throw new BadRequestException(
'The task due date must match the highest children due date!',
);
}
}
const taskInfo: TaskInfoDTO = taskDto.taskInfo;
const taskOwners: TaskOwnerDTO[] = taskDto.owners;
const tasks = await this.taskRepo.save(taskInfo);
const children: TaskDTO[] = taskDto.children;
this.createTaskOwners(tasks, taskOwners);
if (children?.length > 0) {
this.createChildrenTasks(tasks, children);
}
return tasks;
}
async updateTaskStatus(
updateTaskStatus: UpdateTaskStatusDTO,
): Promise<Tasks | null> {
const isChildrenFinished = await this.taskHasUnfinishedChildren(
updateTaskStatus.taskId,
);
if (isChildrenFinished) {
throw new BadRequestException('Task has unfinished children tasks!');
}
const task = await this.taskRepo.findOne({ id: updateTaskStatus.taskId });
task.status = updateTaskStatus.taskStatus;
return await this.taskRepo.save(task);
}
}
| 31.738462 | 79 | 0.67111 |
2f28dfc22521ee9a9cf991cee0249352f5a49b40 | 1,027 | java | Java | app/src/main/java/com/arduino/cloud/ui/HomePage.java | ControlByDestiny/Cloud | db0f191e2270432821b66f96d0debf9395ca7399 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/arduino/cloud/ui/HomePage.java | ControlByDestiny/Cloud | db0f191e2270432821b66f96d0debf9395ca7399 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/arduino/cloud/ui/HomePage.java | ControlByDestiny/Cloud | db0f191e2270432821b66f96d0debf9395ca7399 | [
"Apache-2.0"
] | null | null | null | package com.arduino.cloud.ui;
import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import com.arduino.cloud.R;
import com.arduino.cloud.util.ApiHelper;
import com.arduino.cloud.util.ApiTest;
public class HomePage extends BasePager {
Button btn_get_status;
public HomePage(@NonNull Context context) {
super(context);
}
@Override
protected void initViews() {
btn_get_status=mRootView.findViewById(R.id.getStatus);
btn_get_status.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ApiHelper apiHelper=ApiHelper.getInstance();
apiHelper.sendCmd("38570211","1");
}
});
}
@Override
protected void initData() {
}
@Override
protected int loadLayoutById() {
return R.layout.page_home;
}
}
| 24.452381 | 66 | 0.638754 |
75e5f25a92ffa2e1cf9b9bcd3392db0c0018bc7b | 3,956 | cshtml | C# | showcase/Views/Shared/_BlogShowPartial.cshtml | xxAtrain223/showcase | 45e995209291dcc1a5648f348bfeda483fbec8f3 | [
"MIT"
] | null | null | null | showcase/Views/Shared/_BlogShowPartial.cshtml | xxAtrain223/showcase | 45e995209291dcc1a5648f348bfeda483fbec8f3 | [
"MIT"
] | null | null | null | showcase/Views/Shared/_BlogShowPartial.cshtml | xxAtrain223/showcase | 45e995209291dcc1a5648f348bfeda483fbec8f3 | [
"MIT"
] | null | null | null | @model showcase.Models.BlogEntry
@{
string cardWidth = "col-12";
string imageOrder = "";
string imgFloat = "";
switch (Model.ImagePlacement)
{
case ImagePlacement.LeftOfCard:
imageOrder = "order-1";
cardWidth = "col-8";
break;
case ImagePlacement.RightOfCard:
imageOrder = "order-3";
cardWidth = "col-8";
break;
case ImagePlacement.CardBodyLeft:
imgFloat = "float-md-left";
break;
case ImagePlacement.CardBodyRight:
imgFloat = "float-md-right";
break;
}
}
@section head {
<link href="~/css/BootstrapAdditions.css" rel="stylesheet" />
@if (Model.Image != null && Model.ImagePlacement == ImagePlacement.Jumbotron)
{
<style>
.jumbotron {
padding: 0;
}
.jumbotron img {
width: 100%;
border-radius: .3rem;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
}
</style>
}
@if (Model.TitlePlacement == TitlePlacement.Jumbotron && (Model.Image != null && Model.ImagePlacement == ImagePlacement.Jumbotron))
{
<style>
.jumbotron {
position: relative;
}
.jumbotron h1 {
position: absolute;
top: 4rem;
bottom: 2rem;
left: 2rem;
right: 4rem;
}
</style>
}
}
@if (User.Identity.IsAuthenticated)
{
<a asp-action="Edit" asp-controller="Blog" asp-route-id="@Model.Id" class="btn btn-warning mb-3">Edit</a>
}
@if (Model.TitlePlacement == TitlePlacement.Jumbotron || (Model.Image != null && Model.ImagePlacement == ImagePlacement.Jumbotron))
{
<div class="jumbotron text-dark">
@if (Model.Image != null && Model.ImagePlacement == ImagePlacement.Jumbotron)
{
<img asp-for="Model.Image" />
}
@if (Model.TitlePlacement == TitlePlacement.Jumbotron)
{
<h1>@Model.Title</h1>
}
</div>
}
@if (Model.TitlePlacement == TitlePlacement.AboveCard)
{
<h1>@Model.Title</h1>
}
@**@
<div class="row">
@if (Model.Image != null && (Model.ImagePlacement == ImagePlacement.LeftOfCard || Model.ImagePlacement == ImagePlacement.RightOfCard))
{
<div class="col-4 @imageOrder">
<img asp-for="Model.Image" class="img-fluid rounded w-100" />
</div>
}
<div class="@cardWidth order-2">
<div class="card text-dark">
@if (Model.Image != null && Model.ImagePlacement == ImagePlacement.CardTop)
{
<img asp-for="Model.Image" class="card-img-top" />
}
@if (Model.TitlePlacement == TitlePlacement.CardHeader)
{
<div class="card-header">
<h1>@Model.Title</h1>
</div>
}
<div class="card-body clearfix">
@if (Model.Image != null && (Model.ImagePlacement == ImagePlacement.CardBodyLeft || Model.ImagePlacement == ImagePlacement.CardBodyRight))
{
<img asp-for="Model.Image" class="img-thumbnail float-sm-none w-sm-100 @imgFloat w-md-50 m-1" />
}
@Html.Raw(Model.Html)
</div>
@if (Model.ShowFooter)
{
<div class="card-footer clearfix">
<strong>Tags:</strong> @String.Join(", ", Model.Tags.Select(t => t.Name))
<span class="float-right">@Model.DateUploaded.Date.ToShortDateString()</span>
</div>
}
</div>
</div>
</div> | 31.396825 | 154 | 0.50455 |
acda59a3edfe460dd68509d6358a91cdb6b50876 | 2,086 | cpp | C++ | benchmarks/src/Helpers.cpp | brian6932/chatterino2 | 95e6d8ac2f639accc091f5618097a4e772d259ad | [
"MIT"
] | null | null | null | benchmarks/src/Helpers.cpp | brian6932/chatterino2 | 95e6d8ac2f639accc091f5618097a4e772d259ad | [
"MIT"
] | null | null | null | benchmarks/src/Helpers.cpp | brian6932/chatterino2 | 95e6d8ac2f639accc091f5618097a4e772d259ad | [
"MIT"
] | null | null | null | #include "util/Helpers.hpp"
#include <benchmark/benchmark.h>
using namespace chatterino;
template <class... Args>
void BM_SplitListIntoBatches(benchmark::State &state, Args &&...args)
{
auto args_tuple = std::make_tuple(std::move(args)...);
for (auto _ : state)
{
auto result = splitListIntoBatches(std::get<0>(args_tuple),
std::get<1>(args_tuple));
assert(!result.empty());
}
}
BENCHMARK_CAPTURE(BM_SplitListIntoBatches, 7 / 3,
QStringList{"", "", "", "", "", "", ""}, 3);
BENCHMARK_CAPTURE(BM_SplitListIntoBatches, 6 / 3,
QStringList{"", "", "", "", "", ""}, 3);
BENCHMARK_CAPTURE(BM_SplitListIntoBatches, 100 / 3,
QStringList{
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "",
},
3);
BENCHMARK_CAPTURE(BM_SplitListIntoBatches, 100 / 49,
QStringList{
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "", "",
},
49);
| 44.382979 | 73 | 0.237776 |
e8b3ddbd8de2b946ed0f47955cd7bda323402b71 | 2,866 | hpp | C++ | images/imagedb/include/db/db.hpp | jeoygin/gadget | de703b53576eac7d11d625316a46a47e57596dcb | [
"MIT"
] | null | null | null | images/imagedb/include/db/db.hpp | jeoygin/gadget | de703b53576eac7d11d625316a46a47e57596dcb | [
"MIT"
] | null | null | null | images/imagedb/include/db/db.hpp | jeoygin/gadget | de703b53576eac7d11d625316a46a47e57596dcb | [
"MIT"
] | null | null | null | #ifndef DB_HPP
#define DB_HPP
#include <string>
#include <iostream>
#include <glog/logging.h>
#include "base64/base64.h"
using namespace std;
namespace db {
enum Mode { READ, WRITE, NEW };
class Iterator {
public:
Iterator() {}
virtual ~Iterator() {}
virtual void seek_to_first() = 0;
virtual void next() = 0;
virtual string key() = 0;
virtual string value() = 0;
virtual void value(vector<unsigned char>& value) {
string str_value = this->value();
value.clear();
if (!str_value.empty()) {
base64_decode(str_value, value);
}
}
virtual bool valid() = 0;
};
class Writer {
public:
Writer() {}
virtual ~Writer() {}
virtual void put(const string& key, const vector<unsigned char>& value) {
string str_value = base64_encode(value.data(), value.size());
put(key, str_value);
}
virtual void put(const string& key, const string& value) = 0;
virtual void flush() = 0;
};
class DB {
public:
DB() {}
virtual ~DB() {}
virtual void open(const string& source, Mode mode) = 0;
virtual void close() = 0;
virtual string get(const string& key) = 0;
virtual void get(const string& key, vector<unsigned char>& value) {
string str_value = get(key);
value.clear();
if (!str_value.empty()) {
base64_decode(str_value, value);
}
}
virtual void put(const string& key, const string& value) = 0;
virtual void put(const string& key, const vector<unsigned char>& value) {
string str_value = base64_encode(value.data(), value.size());
put(key, str_value);
}
virtual int copy(const string& key, DB* dst, const string& dst_key,
vector<unsigned char>& aux) {
if (!dst) {
return -1;
}
aux.clear();
get(key, aux);
if (aux.empty()) {
return -2;
}
dst->put(dst_key, aux);
return 0;
}
virtual int copy(const string& key, Writer* writer, const string& dst_key,
vector<unsigned char>& aux) {
if (!writer) {
return -1;
}
aux.clear();
get(key, aux);
if (aux.empty()) {
return -2;
}
writer->put(dst_key, aux);
return 0;
}
virtual Iterator* new_iterator() = 0;
virtual Writer* new_writer() = 0;
};
DB* get_db(const string& backend);
DB* open_db(const string& source, Mode mode);
} // namespace db
#endif // DB_HPP
| 26.293578 | 82 | 0.500698 |
9794a33f2a8b5297240e5bac70afd14bcdf53741 | 362 | dart | Dart | lib/globalbasestate/action.dart | pluto8172/ColorLive | 587ef2ea07d0690999f588e0c6548a5eae2853ac | [
"Apache-2.0"
] | null | null | null | lib/globalbasestate/action.dart | pluto8172/ColorLive | 587ef2ea07d0690999f588e0c6548a5eae2853ac | [
"Apache-2.0"
] | null | null | null | lib/globalbasestate/action.dart | pluto8172/ColorLive | 587ef2ea07d0690999f588e0c6548a5eae2853ac | [
"Apache-2.0"
] | null | null | null | import 'dart:ui';
import 'package:fish_redux/fish_redux.dart';
enum GlobalAction { changeThemeColor, changeLocale, setUser }
class GlobalActionCreator {
static Action onchangeThemeColor() {
return const Action(GlobalAction.changeThemeColor);
}
static Action changeLocale(Locale l) {
return Action(GlobalAction.changeLocale, payload: l);
}
}
| 21.294118 | 61 | 0.756906 |
2a4c4f3bbcebd0145f9ace5fb66f43152b2dc297 | 3,195 | java | Java | sdk-core/src/main/java/com/sportradar/unifiedodds/sdk/impl/entities/RefereeImpl.java | chaosky/UnifiedOddsSdkJava | 7fda00ff2d46221d691410662d14f978cd6ac4e2 | [
"BSD-3-Clause"
] | 10 | 2019-03-29T11:51:55.000Z | 2021-06-04T16:45:55.000Z | sdk-core/src/main/java/com/sportradar/unifiedodds/sdk/impl/entities/RefereeImpl.java | chaosky/UnifiedOddsSdkJava | 7fda00ff2d46221d691410662d14f978cd6ac4e2 | [
"BSD-3-Clause"
] | 8 | 2021-03-22T08:55:39.000Z | 2022-02-24T18:00:16.000Z | sdk-core/src/main/java/com/sportradar/unifiedodds/sdk/impl/entities/RefereeImpl.java | chaosky/UnifiedOddsSdkJava | 7fda00ff2d46221d691410662d14f978cd6ac4e2 | [
"BSD-3-Clause"
] | 5 | 2019-03-29T12:20:49.000Z | 2022-02-04T09:55:23.000Z | /*
* Copyright (C) Sportradar AG. See LICENSE for full license governing this code
*/
package com.sportradar.unifiedodds.sdk.impl.entities;
import com.google.common.collect.ImmutableMap;
import com.sportradar.unifiedodds.sdk.caching.ci.RefereeCI;
import com.sportradar.unifiedodds.sdk.entities.Referee;
import com.sportradar.utils.URN;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Represents a sport event referee
*/
public class RefereeImpl implements Referee {
/**
* A value used to uniquely identify the current {@link Referee} instance
*/
private final URN id;
/**
* The name of the referee represented by the current {@link Referee} instance
*/
private final String name;
/**
* An unmodifiable {@link Map} containing referee nationality in different languages
* @see com.google.common.collect.ImmutableMap
*/
private final Map<Locale, String> nationalities;
/**
* Initializes a new instance of {@link RefereeImpl} class
*
* @param refereeCI - a {@link RefereeCI} used to create a new instance
* @param locales - a {@link List} of locales supported by the new instance
*/
RefereeImpl(RefereeCI refereeCI, List<Locale> locales) {
this.id = refereeCI.getId();
this.name = refereeCI.getName();
this.nationalities = locales.stream()
.filter(l -> refereeCI.getNationality(l) != null)
.collect(ImmutableMap.toImmutableMap(k -> k, refereeCI::getNationality));
}
/**
* Returns the unique identifier of the current {@link Referee} instance
*
* @return - the unique identifier of the current {@link Referee} instance
*/
@Override
public URN getId() {
return id;
}
/**
* Returns the name of the referee represented by the current {@link Referee} instance
*
* @return - the name of the referee represented by the current {@link Referee} instance
*/
@Override
public String getName() {
return name;
}
/**
* Returns the nationality in the requested locale
*
* @param locale - a {@link Locale} in which the nationality is requested
* @return - the nationality in the requested locale
*/
@Override
public String getNationality(Locale locale) {
return nationalities.get(locale);
}
/**
* Returns an unmodifiable {@link Map} containing referee nationality in different languages
* @see com.google.common.collect.ImmutableMap
*
* @return - an unmodifiable {@link Map} containing referee nationality in different languages
*/
@Override
public Map<Locale, String> getNationalities() {
return nationalities;
}
/**
* Returns a {@link String} describing the current {@link Referee} instance
*
* @return - a {@link String} describing the current {@link Referee} instance
*/
@Override
public String toString() {
return "RefereeImpl{" +
"id=" + id +
", name='" + name + '\'' +
", nationalities=" + nationalities +
'}';
}
}
| 29.583333 | 98 | 0.637559 |
bcc5c18b7c179c99e648a50bbc9bf3a73885d03d | 865 | swift | Swift | Succotash/Carthage/Checkouts/Koloda/Pod/Classes/KolodaView/KolodaCardStorage.swift | AdamSliwakowski/solid-succotash | 9058faf527c0c62e11537527b3070d260419746e | [
"MIT"
] | 1 | 2020-09-04T17:56:41.000Z | 2020-09-04T17:56:41.000Z | Succotash/Carthage/Checkouts/Koloda/Pod/Classes/KolodaView/KolodaCardStorage.swift | AdamSliwakowski/solid-succotash | 9058faf527c0c62e11537527b3070d260419746e | [
"MIT"
] | null | null | null | Succotash/Carthage/Checkouts/Koloda/Pod/Classes/KolodaView/KolodaCardStorage.swift | AdamSliwakowski/solid-succotash | 9058faf527c0c62e11537527b3070d260419746e | [
"MIT"
] | null | null | null | //
// KolodaCardStorage.swift
// Pods
//
// Created by Eugene Andreyev on 3/30/16.
//
//
import Foundation
import UIKit
extension KolodaView {
func createCardAtIndex(index: UInt, frame: CGRect? = nil) -> DraggableCardView {
let cardView = generateCard(frame ?? frameForTopCard())
configureCard(cardView, atIndex: index)
return cardView
}
func generateCard(frame: CGRect) -> DraggableCardView {
let cardView = DraggableCardView(frame: frame)
cardView.delegate = self
return cardView
}
func configureCard(card: DraggableCardView, atIndex index: UInt) {
let contentView = dataSource!.koloda(self, viewForCardAtIndex: index)
card.configure(contentView, overlayView: dataSource?.koloda(self, viewForCardOverlayAtIndex: index))
}
} | 25.441176 | 108 | 0.653179 |