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
sequencelengths 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
sequencelengths 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
sequencelengths 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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7fd11f8d27f57b26a83bf076b156471ed7a8e947 | 2,310 | php | PHP | src/Controller/Printer/PrintController.php | Georges-Ngandeu/crowdfunding_demo | ca012806252a42c0b8dc30a1b77185dfacb3b12b | [
"MIT"
] | null | null | null | src/Controller/Printer/PrintController.php | Georges-Ngandeu/crowdfunding_demo | ca012806252a42c0b8dc30a1b77185dfacb3b12b | [
"MIT"
] | null | null | null | src/Controller/Printer/PrintController.php | Georges-Ngandeu/crowdfunding_demo | ca012806252a42c0b8dc30a1b77185dfacb3b12b | [
"MIT"
] | null | null | null | <?php
namespace App\Controller\Printer;
use App\Manager\SubscriberProjectManager;
use App\Services\PdfService;
use App\Services\SubscriptionService;
use App\Services\Tools\FileService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class PrintController extends AbstractController
{
/**
* @Route("/print/subscription/{id}", name="subscription")
*/
public function subscription(Request $request, $id, PdfService $pdf, SubscriberProjectManager $subscriberProjectManager, FileService $fileService)
{
//$id = $request->get("subscription_id");
$subscription = $subscriberProjectManager->find($id);
$template = "bill/subscribe.html.twig";
$html = $this->renderView(
$template,
array(
'subscription' => $subscription,
)
);
$directory = $this->getParameter("kernel.project_dir"). "/public/subscription/subscription". $id .".pdf";
$pdf->print($html, "P", "A4", $directory);
}
/**
* @Route("/print/contract/{id}", name="contract")
*/
public function contract(Request $request, $id, PdfService $pdf, SubscriberProjectManager $subscriberProjectManager, SubscriptionService $subscriptionService)
{
//$id = $request->get("subscription_id");
$subscription = $subscriberProjectManager->find($id);
$subscriptionService->allowToManager($subscription);
$template = "bill/contract.html.twig";
$html = $this->renderView(
$template,
array(
'subscription' => $subscription,
)
);
$directory = $this->getParameter("kernel.project_dir"). "/public/contract/contract". $id .".pdf";
$pdf->print($html, "L", "A4", $directory);
}
/**
* @Route("/print/reconduction", name="printReconduction")
*/
public function reconduction(Request $request, PdfService $pdf)
{
$template = "bill/reconduction.html.twig";
$html = $this->renderView(
$template,
array(
'data' => $data,
)
);
return $pdf->print($html, "P", "A4");
}
} | 32.083333 | 162 | 0.609091 |
ae3fc09b1124808fbdd0a86cff1901729746e713 | 209 | cs | C# | Hollow Knight/TextMesh Pro/TextMesh Pro/Plugins/TMPro/TMP_InputValidator.cs | nickc01/ViridianCore | ff098c9313996618a843b96ff9c4a0cb777ddc76 | [
"MIT"
] | 4 | 2020-06-29T08:37:25.000Z | 2022-02-14T13:47:42.000Z | Hollow Knight/TextMesh Pro/TextMesh Pro/Plugins/TMPro/TMP_InputValidator.cs | nickc01/ViridianCore | ff098c9313996618a843b96ff9c4a0cb777ddc76 | [
"MIT"
] | 2 | 2021-09-23T21:07:05.000Z | 2022-03-28T21:09:07.000Z | Hollow Knight/TextMesh Pro/TextMesh Pro/Plugins/TMPro/TMP_InputValidator.cs | nickc01/ViridianCore | ff098c9313996618a843b96ff9c4a0cb777ddc76 | [
"MIT"
] | 2 | 2021-05-12T07:29:28.000Z | 2022-02-14T11:43:39.000Z | using System;
using UnityEngine;
namespace TMPro
{
[Serializable]
public abstract class TMP_InputValidator : ScriptableObject
{
public abstract char Validate(ref string text, ref int pos, char ch);
}
}
| 17.416667 | 71 | 0.76555 |
7d91f7168931c812b84423ebf0646f32655925d9 | 941 | css | CSS | src/css/myreset.css | Eventidec/licaibao-responsive | 432bef40517a708205bd3829a5fab06a401305dc | [
"MIT"
] | 33 | 2017-06-01T01:08:18.000Z | 2021-11-07T20:25:47.000Z | src/css/myreset.css | Eventidec/licaibao-responsive | 432bef40517a708205bd3829a5fab06a401305dc | [
"MIT"
] | null | null | null | src/css/myreset.css | Eventidec/licaibao-responsive | 432bef40517a708205bd3829a5fab06a401305dc | [
"MIT"
] | 15 | 2017-07-09T08:32:08.000Z | 2020-06-17T00:40:38.000Z | /**
* 作品:myreset.css
* 维护:白小明
* 更新:2017年5月15日
* 理念:清除和重置是紧密不可分的
* 特色:适应中文,基于最新主流浏览器
*/
/* 清除内外边距 */
@charset "utf-8";
body, h1, h2, h3, h4, h5, h6, hr, p, blockquote,
pre,dl, dt, dd, ul, ol, li,
fieldset, lengend, button, input, textarea,
th, td { margin: 0; padding: 0; }
/* 重置格式元素 */
ul, ol { list-style: none; }
a { text-decoration: none; }
q:before, q:after { content: ''; }
img { border: 0; }
/* 重置表单元素 */
legend { color: #000; } /* for ie6 */
button, textarea { font-size: 100%; border: 0; } /* 使得表单元素在 ie 下能继承字体大小 */
/* 重置表格元素 */
table { border-collapse: collapse; border-spacing: 0; }
/* 清除浮动 */
.fl { float: left; }
.fr { float: right; }
.clearfix:after { display: block; clear: both; content: ""; visibility: hidden; height: 0; }
.clearfix { zoom: 1; }
/* 文字选中效果 */
::selection {
background-color: #b3d4fc;
text-shadow: none;
}
/* 浏览器升级 */
.browser-up {
padding: 1rem;
background: #ccc;
text-align: center;
} | 20.456522 | 92 | 0.608927 |
14f375999fe96c26375856989d8e76cb840d0846 | 866 | swift | Swift | RetricaImglyKit/Classes/Frontend/Stores/ImageInfoRecord.swift | venticake/RetricaImglyKit-iOS | c7f8778bccc7a3a058ffe1ee5c0eb8b75de406b4 | [
"MIT"
] | 3 | 2017-02-27T00:38:52.000Z | 2021-03-23T14:07:34.000Z | RetricaImglyKit/Classes/Frontend/Stores/ImageInfoRecord.swift | venticake/RetricaImglyKit-iOS | c7f8778bccc7a3a058ffe1ee5c0eb8b75de406b4 | [
"MIT"
] | null | null | null | RetricaImglyKit/Classes/Frontend/Stores/ImageInfoRecord.swift | venticake/RetricaImglyKit-iOS | c7f8778bccc7a3a058ffe1ee5c0eb8b75de406b4 | [
"MIT"
] | 1 | 2017-03-15T19:19:47.000Z | 2017-03-15T19:19:47.000Z | // This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
import Foundation
/**
* Represents a single image entry nested within a frame-JSON file.
*/
@available(iOS 8, *)
@objc(IMGLYImageInfoRecord) public class ImageInfoRecord: NSObject {
/// The image ratio that image has, is out for.
public var ratio: Float = 1.0
/// An url atlas. This maps tags like 'thumbnail' onto an url
public var urlAtlas = [String : String]()
}
| 37.652174 | 77 | 0.732102 |
c6c8c8dcd80f2e314fd23333e1e5192e5dc8d599 | 201 | rb | Ruby | vendor/bundle/gems/after_commit_action-1.1.0/spec/models/another_model.rb | happycreator/sample_app | a06f4070ec8cb93609f663ec11ec6eabe8b56f04 | [
"RSA-MD"
] | 26 | 2015-01-18T13:13:04.000Z | 2021-12-31T01:44:13.000Z | vendor/bundle/gems/after_commit_action-1.1.0/spec/models/another_model.rb | happycreator/sample_app | a06f4070ec8cb93609f663ec11ec6eabe8b56f04 | [
"RSA-MD"
] | 11 | 2020-07-02T06:10:05.000Z | 2022-02-19T03:38:23.000Z | vendor/bundle/ruby/2.7.0/gems/after_commit_action-1.1.0/spec/models/another_model.rb | morinakakoki/environment-sample_app | 4ffcd99fde97706f751bd2a83a7f215492edfea6 | [
"RSA-MD"
] | 4 | 2015-03-16T17:46:35.000Z | 2020-01-18T21:50:52.000Z | class AnotherModel < ActiveRecord::Base
include AfterCommitAction
belongs_to :tester
after_save :increment_tester_counter
def increment_tester_counter
tester.increment_counter
end
end
| 16.75 | 39 | 0.810945 |
eaa3f0599a90324c779254eb9d80f04597541f18 | 99 | rb | Ruby | spec/factories/feedback_form_response.rb | kojole/WikiEduDashboard | 7870e0dcdcdef4294f6d9ffb03ff5a14c74465b7 | [
"MIT"
] | 359 | 2015-01-30T03:39:20.000Z | 2022-03-27T10:27:22.000Z | spec/factories/feedback_form_response.rb | kojole/WikiEduDashboard | 7870e0dcdcdef4294f6d9ffb03ff5a14c74465b7 | [
"MIT"
] | 3,140 | 2015-01-13T06:25:43.000Z | 2022-03-31T22:02:11.000Z | spec/factories/feedback_form_response.rb | kojole/WikiEduDashboard | 7870e0dcdcdef4294f6d9ffb03ff5a14c74465b7 | [
"MIT"
] | 596 | 2015-01-24T06:18:15.000Z | 2022-03-31T21:28:32.000Z | # frozen_string_literal: true
FactoryBot.define do
factory :feedback_form_response do
end
end
| 14.142857 | 36 | 0.808081 |
a140af4e160ec9c39cc57e96627c4f3251c55152 | 12,586 | ts | TypeScript | packages/server/test/routes-api/entities/post-root.ts | AlendoStudio/api.auction.chvcm.ru | c6ceeb6784620ed8a5dbbd3f51b1c1905d6d4c0a | [
"MIT"
] | 2 | 2019-01-16T17:33:18.000Z | 2021-02-08T09:23:00.000Z | packages/server/test/routes-api/entities/post-root.ts | AlendoStudio/api.auction.chvcm.ru | c6ceeb6784620ed8a5dbbd3f51b1c1905d6d4c0a | [
"MIT"
] | 65 | 2018-07-30T08:29:45.000Z | 2019-06-15T09:13:51.000Z | packages/server/test/routes-api/entities/post-root.ts | AlendoStudio/api.auction.chvcm.ru | c6ceeb6784620ed8a5dbbd3f51b1c1905d6d4c0a | [
"MIT"
] | 1 | 2019-01-16T17:33:19.000Z | 2019-01-16T17:33:19.000Z | import {prepareApi} from "../../common";
import {expect} from "chai";
import * as sinon from "sinon";
import * as supertest from "supertest";
import waitForExpect from "wait-for-expect";
import {
ApiCodes,
Bcrypt,
Const,
EmailNotifications,
Entity,
Env,
Jwt,
Web,
} from "../../../src";
describe("POST /entities", () => {
prepareApi();
describe("Created 201", () => {
it("ru email", async () => {
const spyMail = sinon.stub();
EmailNotifications.instance.on(EmailNotifications.EMAIL_EVENT, spyMail);
const res = await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(201);
await waitForExpect(() => {
sinon.assert.calledOnce(spyMail);
expect(spyMail.args[0][0].originalMessage.subject).equal(
"Вы успешно зарегистрировались!",
);
expect(spyMail.args[0][0].originalMessage.from).equal(Env.EMAIL_FROM);
expect(spyMail.args[0][0].originalMessage.to).equal("[email protected]");
expect(spyMail.args[0][0].originalMessage.html).contains(
`ООО "ПРИМЕР"`,
);
expect(spyMail.args[0][0].originalMessage.text).contains(
`ООО "ПРИМЕР"`,
);
});
expect(res.body).to.have.keys("token");
expect(res.body.token).be.a("string");
const parsedToken = await Jwt.verifyUser(res.body.token);
expect(parsedToken).to.have.keys("id", "type");
expect(parsedToken.id).equal("1");
expect(parsedToken.type).equal("entity");
const entity = (await Entity.findByPk("1")) as Entity;
expect(entity.id).equal("1");
expect(entity.name).equal(`ООО "ПРИМЕР"`);
expect(entity.email).equal("[email protected]");
expect(entity.phone).equal("+79123456780");
expect(await Bcrypt.compare("super mario", entity.password)).equal(true);
expect(entity.tfa).equal(false);
expect(entity.language).equal("ru");
expect(entity.banned).equal(false);
expect(entity.ceo).equal("Директор: Гордон Андрей Анатольевич");
expect(entity.psrn).equal("1053600591197");
expect(entity.itn).equal("3664069397");
expect(entity.verified).equal(false);
});
it("en email", async () => {
const spyMail = sinon.stub();
EmailNotifications.instance.on(EmailNotifications.EMAIL_EVENT, spyMail);
const res = await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "en",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(201);
await waitForExpect(() => {
sinon.assert.calledOnce(spyMail);
expect(spyMail.args[0][0].originalMessage.subject).equal(
"You have successfully registered!",
);
expect(spyMail.args[0][0].originalMessage.from).equal(Env.EMAIL_FROM);
expect(spyMail.args[0][0].originalMessage.to).equal("[email protected]");
expect(spyMail.args[0][0].originalMessage.html).contains(
`ООО "ПРИМЕР"`,
);
expect(spyMail.args[0][0].originalMessage.text).contains(
`ООО "ПРИМЕР"`,
);
});
expect(res.body).to.have.keys("token");
expect(res.body.token).be.a("string");
const parsedToken = await Jwt.verifyUser(res.body.token);
expect(parsedToken).to.have.keys("id", "type");
expect(parsedToken.id).equal("1");
expect(parsedToken.type).equal("entity");
const entity = (await Entity.findByPk("1")) as Entity;
expect(entity.id).equal("1");
expect(entity.name).equal(`ООО "ПРИМЕР"`);
expect(entity.email).equal("[email protected]");
expect(entity.phone).equal("+79123456780");
expect(await Bcrypt.compare("super mario", entity.password)).equal(true);
expect(entity.tfa).equal(false);
expect(entity.language).equal("en");
expect(entity.banned).equal(false);
expect(entity.ceo).equal("Директор: Гордон Андрей Анатольевич");
expect(entity.psrn).equal("1053600591197");
expect(entity.itn).equal("3664069397");
expect(entity.verified).equal(false);
});
});
it("Bad Request 400", async () => {
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
email: "[email protected]",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(400, {
code: ApiCodes.BAD_REQUEST,
message: `child "ceo" fails because ["ceo" is required]`,
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(400, {
code: ApiCodes.BAD_REQUEST,
message: `child "email" fails because ["email" is required]`,
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(400, {
code: ApiCodes.BAD_REQUEST,
message: `child "itn" fails because ["itn" is required]`,
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(400, {
code: ApiCodes.BAD_REQUEST,
message: `child "language" fails because ["language" is required]`,
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "ru",
password: "super mario",
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(400, {
code: ApiCodes.BAD_REQUEST,
message: `child "name" fails because ["name" is required]`,
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(400, {
code: ApiCodes.BAD_REQUEST,
message: `child "password" fails because ["password" is required]`,
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
psrn: "1053600591197",
})
.expect(400, {
code: ApiCodes.BAD_REQUEST,
message: `child "phone" fails because ["phone" is required]`,
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456780",
})
.expect(400, {
code: ApiCodes.BAD_REQUEST,
message: `child "psrn" fails because ["psrn" is required]`,
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
["g-recaptcha-response"]: "token",
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
extraField: true,
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(400, {
code: ApiCodes.BAD_REQUEST,
message: `"extraField" is not allowed`,
});
});
it("Conflict 409", async () => {
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(201);
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(409, {
code: ApiCodes.USER_FOUND_BY_EMAIL_AND_PHONE,
message: "user with same email and phone already exists",
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456789",
psrn: "1053600591197",
})
.expect(409, {
code: ApiCodes.USER_FOUND_BY_EMAIL,
message: "user with same email already exists",
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456780",
psrn: "1053600591197",
})
.expect(409, {
code: ApiCodes.USER_FOUND_BY_PHONE,
message: "user with same phone already exists",
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456789",
psrn: "1053600591197",
})
.expect(409, {
code: ApiCodes.ENTITY_FOUND_BY_ITN_AND_PSRN,
message: "entity with same itn and psrn already exists",
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "3664069397",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456789",
psrn: "1027601593271",
})
.expect(409, {
code: ApiCodes.ENTITY_FOUND_BY_ITN,
message: "entity with same itn already exists",
});
await supertest(Web.instance.app)
.post(`${Const.API_MOUNT_POINT}/entities`)
.send({
ceo: "Директор: Гордон Андрей Анатольевич",
email: "[email protected]",
itn: "9909068852",
language: "ru",
name: `ООО "ПРИМЕР"`,
password: "super mario",
phone: "+79123456789",
psrn: "1053600591197",
})
.expect(409, {
code: ApiCodes.ENTITY_FOUND_BY_PSRN,
message: "entity with same psrn already exists",
});
});
});
| 31.230769 | 80 | 0.571905 |
0c825f1cfb4de15b100d5a31ae89eff4dfc2ad44 | 4,617 | swift | Swift | Travel-IT/Hot Posts/HotPostsListVC.swift | iamank1t/travel-it-iOS | d4b0a3620cd834d1b9ea67cbc9ac8e530a454ef9 | [
"MIT"
] | 6 | 2018-03-22T20:03:27.000Z | 2020-07-10T22:23:49.000Z | Travel-IT/Hot Posts/HotPostsListVC.swift | iamank1t/travel-it-iOS | d4b0a3620cd834d1b9ea67cbc9ac8e530a454ef9 | [
"MIT"
] | 2 | 2018-03-28T15:25:06.000Z | 2018-04-25T10:14:03.000Z | Travel-IT/Hot Posts/HotPostsListVC.swift | iamank1t/travel-it-iOS | d4b0a3620cd834d1b9ea67cbc9ac8e530a454ef9 | [
"MIT"
] | 6 | 2018-03-22T20:03:34.000Z | 2019-10-24T12:47:04.000Z | //
// HotPostsListVC.swift
// Travel-IT
//
// Created by Ankit Singh on 23/03/18.
// Copyright © 2018 Ankit Singh. All rights reserved.
//
import UIKit
import SwiftyJSON
import NVActivityIndicatorView
class HotPostsListVC: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var hotTravelpostsTableView: UITableView!
private var activityView: NVActivityIndicatorView!
var allPosts = [[String: AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Hot Travel Posts"
self.hotTravelpostsTableView.delegate = self
self.hotTravelpostsTableView.dataSource = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.getHotTravelPosts()
}
func getHotTravelPosts() {
self.showLoadingIndicator()
let url = URL(string: "https://api.steemjs.com/get_discussions_by_hot?query=%7B%22tag%22%3A%22travel%22%2C%20%22limit%22%3A%20%2210%22%7D")!
URLSession.shared.dataTask(with: url, completionHandler: {
(data, response, error) in
if(error != nil){
print("error")
}else{
do{
var json = try JSONSerialization.jsonObject(with: data!, options: []) as! [[String: AnyObject]]
for post in json {
self.allPosts.append(post)
}
DispatchQueue.main.async(execute: {
self.stopLoadingIndicator()
self.hotTravelpostsTableView.reloadData()
})
}catch let error as NSError{
print(error)
}
}
}).resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.allPosts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HotPostsTableCell", for: indexPath) as? HotPostsTableCell
let cellData = self.allPosts[indexPath.row]
cell?.updateCellData(data: cellData)
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 300
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let postData = self.allPosts[indexPath.row]
//let metadata = postData["json_metadata"]! as! String
// var mainImage: String?
// let data = metadata.data(using: .utf8)!
// do {
// if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [String:AnyObject]
// {
// let images = jsonArray["image"] as! [String]
// mainImage = images[0]
// } else {
// print("bad json")
// }
// } catch let error as NSError {
// print(error)
// }
let storyboard = UIStoryboard(name: "HotPosts", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "HotPostShowVC") as! HotPostShowVC
vc.postData = postData
navigationController?.pushViewController(vc,animated: true)
}
func showLoadingIndicator(){
if activityView == nil{
activityView = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50.0, height: 50.0), type: NVActivityIndicatorType.ballClipRotatePulse, color: UIColor.loaderColor, padding: 0.0)
activityView.backgroundColor = UIColor.white
// add subview
view.addSubview(activityView)
// autoresizing mask
activityView.translatesAutoresizingMaskIntoConstraints = false
// constraints
view.addConstraint(NSLayoutConstraint(item: activityView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: activityView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0))
}
activityView.startAnimating()
}
func stopLoadingIndicator(){
activityView.stopAnimating()
}
}
| 41.594595 | 223 | 0.610136 |
c973421d9a33d35b665d31326a1c19e0c3ff7e94 | 1,760 | ts | TypeScript | packages/actor-query-operation-ask/lib/ActorQueryOperationAsk.ts | rubensworks/comunica | 8cddee42ff8a3a8debf9f64659add25054ca167a | [
"MIT"
] | null | null | null | packages/actor-query-operation-ask/lib/ActorQueryOperationAsk.ts | rubensworks/comunica | 8cddee42ff8a3a8debf9f64659add25054ca167a | [
"MIT"
] | null | null | null | packages/actor-query-operation-ask/lib/ActorQueryOperationAsk.ts | rubensworks/comunica | 8cddee42ff8a3a8debf9f64659add25054ca167a | [
"MIT"
] | null | null | null | import type { IActorQueryOperationTypedMediatedArgs } from '@comunica/bus-query-operation';
import { ActorQueryOperation, ActorQueryOperationTypedMediated } from '@comunica/bus-query-operation';
import type { IActorTest } from '@comunica/core';
import type {
IActionContext,
IQueryOperationResult,
IQueryOperationResultBindings,
} from '@comunica/types';
import type { Algebra } from 'sparqlalgebrajs';
/**
* A comunica Ask Query Operation Actor.
*/
export class ActorQueryOperationAsk extends ActorQueryOperationTypedMediated<Algebra.Ask> {
public constructor(args: IActorQueryOperationTypedMediatedArgs) {
super(args, 'ask');
}
public async testOperation(operation: Algebra.Ask, context: IActionContext): Promise<IActorTest> {
return true;
}
public async runOperation(operation: Algebra.Ask, context: IActionContext): Promise<IQueryOperationResult> {
// Call other query operations like this:
const output: IQueryOperationResult = await this.mediatorQueryOperation.mediate(
{ operation: operation.input, context },
);
const bindings: IQueryOperationResultBindings = ActorQueryOperation.getSafeBindings(output);
const execute: () => Promise<boolean> = () => new Promise<boolean>((resolve, reject) => {
// Resolve to true if we find one element, and close immediately
bindings.bindingsStream.once('data', () => {
resolve(true);
bindings.bindingsStream.close();
});
// If we reach the end of the stream without finding anything, resolve to false
bindings.bindingsStream.on('end', () => resolve(false));
// Reject if an error occurs in the stream
bindings.bindingsStream.on('error', reject);
});
return { type: 'boolean', execute };
}
}
| 39.111111 | 110 | 0.721591 |
ef68d0b898b5da9b231204075a0ba5ba6c194195 | 256 | h | C | singdemo/singdemo/SimpleView/ImagCode/QJCCodeSmallView.h | Qiaojuncheng/Repository | 6220cfc278f3ecf1110e572c845b53951446648d | [
"MIT"
] | null | null | null | singdemo/singdemo/SimpleView/ImagCode/QJCCodeSmallView.h | Qiaojuncheng/Repository | 6220cfc278f3ecf1110e572c845b53951446648d | [
"MIT"
] | null | null | null | singdemo/singdemo/SimpleView/ImagCode/QJCCodeSmallView.h | Qiaojuncheng/Repository | 6220cfc278f3ecf1110e572c845b53951446648d | [
"MIT"
] | null | null | null | //
// QJCCodeView.h
// singdemo
//
// Created by MYMAc on 2018/7/18.
// Copyright © 2018年 ShangYu. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface QJCCodeSmallView : UIView
@property (copy ,nonatomic) NSString * CodeStr;// 图形验证码显示的文字
@end
| 18.285714 | 60 | 0.695313 |
9c1d37423e616355aaa823e78c857a7a60a42c48 | 6,724 | rs | Rust | src/game.rs | Ryan1729/aspect-aspic | 2acbc621a288b61e5568c3c1442a46fe891e3dc5 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/game.rs | Ryan1729/aspect-aspic | 2acbc621a288b61e5568c3c1442a46fe891e3dc5 | [
"Apache-2.0",
"MIT"
] | null | null | null | src/game.rs | Ryan1729/aspect-aspic | 2acbc621a288b61e5568c3c1442a46fe891e3dc5 | [
"Apache-2.0",
"MIT"
] | null | null | null | use common::*;
impl GameState {
fn isSelectrix(&self, id: usize) -> bool {
self.entities[id].contains(Component::Player | Component::IntraCellPosition)
&& self.player_types[id] == PlayerType::Selectrix
}
fn isAvatar(&self, id: usize) -> bool {
self.entities[id].contains(Component::Player) && self.player_types[id] == PlayerType::Avatar
}
}
//TODO picking up and throwing orbs (no interactions just placement first)
#[inline]
pub fn update_and_render(state: &mut GameState, framebuffer: &mut Framebuffer, input: Input) {
for i in 0..GameState::ENTITY_COUNT {
if state.mode == Mode::MoveAvatar && state.isAvatar(i) {
let appearance = &mut state.appearances[i];
if appearance.is_offset() {
appearance.reduce_offset(8);
continue;
}
let (mut x, mut y) = state.positions[i];
if input.pressed_this_frame(Button::Left) && x > 0 {
x = x.saturating_sub(1);
appearance.offset.0 = CELL_WIDTH as isize;
}
if input.pressed_this_frame(Button::Right) && x < BOARD_WIDTH - 1 {
x = x.saturating_add(1);
appearance.offset.0 = -(CELL_WIDTH as isize)
}
if input.pressed_this_frame(Button::Up) && y > 0 {
y = y.saturating_sub(1);
appearance.offset.1 = CELL_WIDTH as isize;
}
if input.pressed_this_frame(Button::Down) && y < BOARD_HEIGHT - 1 {
y = y.saturating_add(1);
appearance.offset.1 = -(CELL_WIDTH as isize);
}
state.positions[i] = (x, y);
} else if state.mode == Mode::MoveSelectrix && state.isSelectrix(i) {
let appearance = &mut state.appearances[i];
if appearance.is_offset() {
appearance.reduce_offset(8);
continue;
}
let (mut x, mut y) = state.positions[i];
let mut inter_pos = state.intra_cell_positions[i];
if input.pressed_this_frame(Button::Left) {
if x > 0 && inter_pos.on_left_edge() {
x = x.saturating_sub(1);
inter_pos = inter_pos.left();
appearance.offset.0 = (CELL_WIDTH / 2) as isize;
} else if !inter_pos.on_left_edge() {
inter_pos = inter_pos.left();
appearance.offset.0 = (CELL_WIDTH / 2) as isize;
}
}
if input.pressed_this_frame(Button::Right) {
if x < BOARD_WIDTH - 1 && inter_pos.on_right_edge() {
x = x.saturating_add(1);
inter_pos = inter_pos.right();
appearance.offset.0 = -((CELL_WIDTH / 2) as isize);
} else if !inter_pos.on_right_edge() {
inter_pos = inter_pos.right();
appearance.offset.0 = -((CELL_WIDTH / 2) as isize);
}
}
if input.pressed_this_frame(Button::Up) {
if y > 0 && inter_pos.on_top_edge() {
y = y.saturating_sub(1);
inter_pos = inter_pos.up();
appearance.offset.1 = (CELL_HEIGHT / 2) as isize;
} else if !inter_pos.on_top_edge() {
inter_pos = inter_pos.up();
appearance.offset.1 = (CELL_HEIGHT / 2) as isize;
}
}
if input.pressed_this_frame(Button::Down) {
if y < BOARD_HEIGHT - 1 && inter_pos.on_bottom_edge() {
y = y.saturating_add(1);
inter_pos = inter_pos.down();
appearance.offset.1 = -((CELL_HEIGHT / 2) as isize);
} else if !inter_pos.on_bottom_edge() {
inter_pos = inter_pos.down();
appearance.offset.1 = -((CELL_HEIGHT / 2) as isize);
}
}
state.positions[i] = (x, y);
state.intra_cell_positions[i] = inter_pos;
}
}
state.mode = match state.mode {
Mode::MoveAvatar if input.pressed_this_frame(Button::B) => {
state.positions[state.selectrixId] = state.positions[state.avatarId];
state.entities[state.selectrixId].insert(Component::Appearance);
Mode::MoveSelectrix
}
Mode::MoveSelectrix if input.pressed_this_frame(Button::B) => {
state.entities[state.selectrixId].remove(Component::Appearance);
Mode::MoveAvatar
}
_ => state.mode,
};
if input.pressed_this_frame(Button::Select) {
state.inventory_index = (state.inventory_index + 1) % state.inventory.len() as u8;
}
framebuffer.clear();
for i in 0..GameState::ENTITY_COUNT {
let entity = state.entities[i];
if state.isSelectrix(i) {
if state.mode == Mode::MoveSelectrix {
let pos = state.positions[i];
let inter_pos = state.intra_cell_positions[i];
let appearance = &mut state.appearances[i];
appearance.render_intra_positioned(framebuffer, pos, inter_pos);
}
} else if entity
.contains(Component::Position | Component::Appearance | Component::IntraCellPosition)
{
let pos = state.positions[i];
let inter_pos = state.intra_cell_positions[i];
let appearance = &mut state.appearances[i];
appearance.render_intra_positioned(framebuffer, pos, inter_pos);
} else if entity.contains(Component::Position | Component::Appearance) {
let pos = state.positions[i];
let appearance = &mut state.appearances[i];
appearance.render_positioned(framebuffer, pos);
}
}
framebuffer.draw_filled_rect(HUD_LEFT_EDGE, 0, HUD_WIDTH, SCREEN_HEIGHT, GREY);
for i in 0..state.inventory.len() {
let item = state.inventory[i];
let x = INVENTORY_LEFT_EDGE;
let y = (INVENTORY_HEIGHT + 4) * (i + 1);
framebuffer.draw_filled_rect(x, y, INVENTORY_WIDTH, INVENTORY_HEIGHT, PURPLE);
match item {
OrbType::DeadOrb => {
framebuffer.draw_circle(
x + INVENTORY_WIDTH / 2,
y + INVENTORY_HEIGHT / 2,
ORB_RADIUS,
RED,
);
}
_ => {}
}
if i as u8 == state.inventory_index {
framebuffer.draw_rect(x, y, INVENTORY_WIDTH, INVENTORY_HEIGHT, YELLOW);
}
}
}
| 36.743169 | 100 | 0.53257 |
1a6dbd5a8610afa3435ceeab6b14a5c24b2a373c | 2,967 | py | Python | notebooks/GentoxicityPrediction.py | patlewig/genetox | 881b6fea72f6974a701e0c50b26dde2829027606 | [
"MIT"
] | 1 | 2021-11-15T14:17:35.000Z | 2021-11-15T14:17:35.000Z | notebooks/GentoxicityPrediction.py | patlewig/genetox | 881b6fea72f6974a701e0c50b26dde2829027606 | [
"MIT"
] | null | null | null | notebooks/GentoxicityPrediction.py | patlewig/genetox | 881b6fea72f6974a701e0c50b26dde2829027606 | [
"MIT"
] | 1 | 2021-11-15T14:17:53.000Z | 2021-11-15T14:17:53.000Z | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 11 00:17:40 2020
@author: ppradeep
#######################################################################################################
This script analyses implements an ensemble model to predict genotoxicity for a test chemical
Inputs: Prediction from EPA TEST, Lazar, and OECD alerts
Output: Genotoxicity classification
#######################################################################################################
"""
#%%
###########################################################################
## Set working directory
###########################################################################
import os
clear = lambda: os.system('cls')
clear()
path = 'Y:/Projects/GeneTox/'
path = 'C:/Users/ppradeep/OneDrive - Environmental Protection Agency (EPA)/Profile/Desktop/GeneTox/'
os.chdir(path)
###########################################################################
## Import libraries
###########################################################################
import pandas as pd
#%%
###########################################################################
## Define functions
###########################################################################
#%%
#######################################################################################################
# 1. Read the original data file
#######################################################################################################
genetox_data = pd.read_excel('data/genetox_160120.xlsx')
#%%
######################################################################################################
# 2. Load posterior probability distribution from available data and set the cut-off value
######################################################################################################
# combination = 'comb2_5-T1T2A1A3A4'
final_model = pd.read_csv('output/FinalModel.csv', index_col='Combination')
cut_off = 0.25
#%%
######################################################################################################
# 3. Input data for new chemical and predict
######################################################################################################
print("Enter the tool predictions for the test chemical")
t1 = int(input("EPA TEST Prediction:"))
t2 = int(input("EPA TEST Prediction:"))
a1 = int(input("OECD Alert 1 Prediction:"))
a3 = int(input("OECD Alert 3 Prediction:"))
a4 = int(input("OECD Alert 4 Prediction:"))
# calculate the combination number
comb = 2**0*t1+2**1*t2+2**2*a1+2**3*a3+2**4*a4
# compare the posterior probability with the cut-off and make a prediction
try:
post_prob = final_model.loc[comb][0]
if post_prob>cut_off:
print("The chemical is genotoxic")
else:
print("The chemical is non-genotoxic")
except:
print("The chemical is out of domain for prediction")
| 40.094595 | 104 | 0.389619 |
e77fa822c8ff49c2a42b93b479012e06551e29a8 | 2,196 | php | PHP | tests/QueryTest.php | larryli/IPv4 | 8f2321786405664113baea071036bcef19f9089d | [
"MIT"
] | 15 | 2015-10-15T14:02:32.000Z | 2020-09-09T10:18:36.000Z | tests/QueryTest.php | larryli/IPv4 | 8f2321786405664113baea071036bcef19f9089d | [
"MIT"
] | null | null | null | tests/QueryTest.php | larryli/IPv4 | 8f2321786405664113baea071036bcef19f9089d | [
"MIT"
] | 6 | 2016-09-01T12:58:11.000Z | 2020-08-02T05:40:50.000Z | <?php
/**
* QueryTest.php
*
* Author: Larry Li <[email protected]>
*/
namespace larryli\ipv4\tests;
use larryli\ipv4\BaidumapQuery;
use larryli\ipv4\ChinaQuery;
use larryli\ipv4\FreeipipQuery;
use larryli\ipv4\FullQuery;
use larryli\ipv4\MiniQuery;
use larryli\ipv4\MonipdbQuery;
use larryli\ipv4\QqwryQuery;
use larryli\ipv4\Query;
use larryli\ipv4\SinaQuery;
use larryli\ipv4\TaobaoQuery;
use larryli\ipv4\WorldQuery;
/**
* Class QueryTest
* @package larryli\ipv4\tests\query
*/
class QueryTest extends \PHPUnit_Framework_TestCase
{
/**
*
*/
public function testTime()
{
$this->assertEquals(time(), intval(Query::time() / 10));
}
/**
* @throws \Exception
*/
public function testCreate()
{
$dummy = new DummyDatabase();
$this->assertTrue(MonipdbQuery::is_a(Query::create('monipdb', __DIR__ . '/17monipdb.dat')));
$this->assertTrue(QqwryQuery::is_a(Query::create('qqwry', __DIR__ . '/qqwry.dat')));
$this->assertTrue(FullQuery::is_a(Query::create('full', $dummy)));
$this->assertTrue(MiniQuery::is_a(Query::create('mini', $dummy)));
$this->assertTrue(ChinaQuery::is_a(Query::create('china', $dummy)));
$this->assertTrue(WorldQuery::is_a(Query::create('world', $dummy)));
$this->assertTrue(FreeipipQuery::is_a(Query::create('freeipip', null)));
$this->assertTrue(SinaQuery::is_a(Query::create('sina', null)));
$this->assertTrue(TaobaoQuery::is_a(Query::create('taobao', null)));
$this->assertTrue(BaidumapQuery::is_a(Query::create('baidumap', null)));
$this->assertTrue(DummyQuery::is_a(Query::create('qqwry', [
'class' => DummyQuery::className(),
])));
}
/**
*
*/
public function testGetProviders()
{
$dummy = new DummyQuery();
$this->assertEmpty($dummy->getProviders());
}
/**
*
*/
public function testSetProviders()
{
$dummy = new DummyQuery();
$this->assertEmpty($dummy->getProviders());
$dummy->setProviders([
new FreeipipQuery(),
]);
$this->assertCount(1, $dummy->getProviders());
}
}
| 27.797468 | 100 | 0.616576 |
664b866a09852857fed83506538c063694d71de2 | 1,503 | py | Python | Medium/1791.FindCenterofStarGraph.py | YuriSpiridonov/LeetCode | 2dfcc9c71466ffa2ebc1c89e461ddfca92e2e781 | [
"MIT"
] | 39 | 2020-07-04T11:15:13.000Z | 2022-02-04T22:33:42.000Z | Medium/1791.FindCenterofStarGraph.py | YuriSpiridonov/LeetCode | 2dfcc9c71466ffa2ebc1c89e461ddfca92e2e781 | [
"MIT"
] | 1 | 2020-07-15T11:53:37.000Z | 2020-07-15T11:53:37.000Z | Medium/1791.FindCenterofStarGraph.py | YuriSpiridonov/LeetCode | 2dfcc9c71466ffa2ebc1c89e461ddfca92e2e781 | [
"MIT"
] | 20 | 2020-07-14T19:12:53.000Z | 2022-03-02T06:28:17.000Z | '''
There is an undirected star graph consisting of n nodes
labeled from 1 to n. A star graph is a graph where there
is one center node and exactly n - 1 edges that connect
the center node with every other node.
You are given a 2D integer array edges where each
edges[i] = [ui, vi] indicates that there is an edge
between the nodes ui and vi. Return the center of the
given star graph.
Example:
Input: edges = [[1,2],[2,3],[4,2]]
Output: 2
Explanation: As shown in the figure above, node 2 is
connected to every other node, so 2 is the
center.
Example:
Input: edges = [[1,2],[5,1],[1,3],[1,4]]
Output: 1
Constraints:
- 3 <= n <= 10^5
- edges.length == n - 1
- edges[i].length == 2
- 1 <= ui, vi <= n
- ui != vi
- The given edges represent a valid star graph.
'''
#Difficulty: Medium
#60 / 60 test cases passed.
#Runtime: 836 ms
#Memory Usage: 50.7 MB
#Runtime: 836 ms, faster than 56.70% of Python3 online submissions for Find Center of Star Graph.
#Memory Usage: 50.7 MB, less than 16.71% of Python3 online submissions for Find Center of Star Graph.
class Solution:
def findCenter(self, edges: List[List[int]]) -> int:
count = {}
for edge in edges:
for val in edge:
if val not in count:
count[val] = 0
count[val] += 1
return max(count, key=count.get) | 31.978723 | 101 | 0.586161 |
7f9ff81237f1df86aaba8432997104bb6dcd43ae | 866 | kt | Kotlin | app/src/test/java/org/dhis2/usescases/map/PointViewModelTest.kt | nancyespinoza/dhis2-android-capture-app | caba60d4267bfd8f1cc509f28f6244e71de37920 | [
"BSD-3-Clause"
] | 1 | 2020-08-24T09:29:02.000Z | 2020-08-24T09:29:02.000Z | app/src/test/java/org/dhis2/usescases/map/PointViewModelTest.kt | ankitbansal25/dhis2-android-capture-app | a09f5d22e37f3efcd7946a2bcd42141020cfb043 | [
"BSD-3-Clause"
] | 4 | 2021-06-08T22:01:34.000Z | 2022-03-12T00:41:28.000Z | app/src/test/java/org/dhis2/usescases/map/PointViewModelTest.kt | ankitbansal25/dhis2-android-capture-app | a09f5d22e37f3efcd7946a2bcd42141020cfb043 | [
"BSD-3-Clause"
] | null | null | null | package org.dhis2.usescases.map
import com.mapbox.geojson.Point
import org.dhis2.usescases.map.point.PointViewModel
import org.junit.Before
import org.junit.Test
class PointViewModelTest {
private lateinit var pointViewModel: PointViewModel
@Before
fun setup() {
pointViewModel = PointViewModel()
}
@Test
fun `Should set point`() {
pointViewModel.setPoint(Point.fromLngLat(0.1, 0.0))
assert(pointViewModel.lat.get() == "0.0" && pointViewModel.lng.get() == "0.1")
}
@Test
fun `Should get point as string where point is defined`() {
pointViewModel.setPoint(Point.fromLngLat(0.1, 0.0))
assert(pointViewModel.getPointAsString() == "[0.1,0.0]")
}
@Test
fun `Should get point as string where point is null`() {
assert(pointViewModel.getPointAsString() == null)
}
}
| 25.470588 | 86 | 0.662818 |
ddd66de2ae937c66f7fbe082dcaf70f733148734 | 2,099 | java | Java | programmers/42579/Solution2.java | pparkddo/ps | 7164c694403c2087a7b4b16a64f521ae327e328f | [
"MIT"
] | 1 | 2021-04-02T09:37:11.000Z | 2021-04-02T09:37:11.000Z | programmers/42579/Solution2.java | pparkddo/ps | 7164c694403c2087a7b4b16a64f521ae327e328f | [
"MIT"
] | null | null | null | programmers/42579/Solution2.java | pparkddo/ps | 7164c694403c2087a7b4b16a64f521ae327e328f | [
"MIT"
] | null | null | null | import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.stream.Collectors;
class Music implements Comparable<Music> {
int id;
int play;
String genre;
Music(int id, int play, String genre) {
this.id = id;
this.play = play;
this.genre = genre;
}
@Override
public int compareTo(Music music) {
if (this.play == music.play) {
return -Integer.compare(this.id, music.id);
}
return Integer.compare(this.play, music.play);
}
@Override
public String toString() {
return this.id + " " + this.play + " " + this.genre;
}
}
class Solution2 {
public int[] solution(String[] genres, int[] plays) {
Map<String, Integer> counts = new HashMap<>();
Map<String, PriorityQueue<Music>> musics = new HashMap<>();
for (int i = 0; i < plays.length; i++) {
String genre = genres[i];
int play = plays[i];
counts.put(genre, counts.getOrDefault(genre, 0)+play);
PriorityQueue<Music> pq = musics.getOrDefault(genre, new PriorityQueue<>(Collections.reverseOrder()));
pq.add(new Music(i, play, genre));
musics.put(genre, pq);
}
List<String> sorted = counts
.entrySet()
.stream()
.sorted((a, b) -> -Integer.compare(a.getValue(), b.getValue()))
.map(each -> each.getKey())
.collect(Collectors.toList());
List<Integer> answer = new ArrayList<>();
for (String genre : sorted) {
for (int i = 0; i < 2; i++) {
PriorityQueue<Music> pq = musics.get(genre);
if (pq.isEmpty()) {
break;
}
answer.add(pq.poll().id);
}
}
return answer.stream().mapToInt(i -> i).toArray();
}
}
| 29.56338 | 114 | 0.515484 |
e386fbf84a26cb20958483210d4bfd144b1dbfb3 | 190 | rb | Ruby | db/migrate/20140203175128_create_prodvideos.rb | i5okie/redress_old | f8091c5a95fafc94b6cb7120d77a4f4dd9f327b9 | [
"MIT"
] | 1 | 2015-03-07T02:29:58.000Z | 2015-03-07T02:29:58.000Z | db/migrate/20140203175128_create_prodvideos.rb | i5okie/redress_old | f8091c5a95fafc94b6cb7120d77a4f4dd9f327b9 | [
"MIT"
] | null | null | null | db/migrate/20140203175128_create_prodvideos.rb | i5okie/redress_old | f8091c5a95fafc94b6cb7120d77a4f4dd9f327b9 | [
"MIT"
] | null | null | null | class CreateProdvideos < ActiveRecord::Migration
def change
create_table :prodvideos do |t|
t.integer :product_id
t.integer :video_id
t.timestamps
end
end
end
| 17.272727 | 48 | 0.684211 |
5d4caf277b27ba63bbb807483211bf2ceba71b87 | 1,990 | cpp | C++ | src/fireball.cpp | alohamora/legend-of-zelda | 63b764ab27a171af1f809dcd8aa8e85b2c06accc | [
"MIT"
] | null | null | null | src/fireball.cpp | alohamora/legend-of-zelda | 63b764ab27a171af1f809dcd8aa8e85b2c06accc | [
"MIT"
] | null | null | null | src/fireball.cpp | alohamora/legend-of-zelda | 63b764ab27a171af1f809dcd8aa8e85b2c06accc | [
"MIT"
] | null | null | null | #include"main.h"
#include"fireball.h"
Fireball::Fireball(color_t color){
position = glm::vec3(0,-1,0);
speed = 0.8;
speed_up = 0;
acc_y = 0;
static const GLfloat vertex_buffer_data[] = {
-0.5,-0.5,-0.5, // triangle 1 : begin
-0.5,-0.5, 0.5,
-0.5, 0.5, 0.5, // triangle 1 : end
0.5, 0.5,-0.5, // triangle 2 : begin
-0.5,-0.5,-0.5,
-0.5, 0.5,-0.5, // triangle 2 : end
0.5,-0.5, 0.5,
-0.5,-0.5,-0.5,
0.5,-0.5,-0.5,
0.5, 0.5,-0.5,
0.5,-0.5,-0.5,
-0.5,-0.5,-0.5,
-0.5,-0.5,-0.5,
-0.5, 0.5, 0.5,
-0.5, 0.5,-0.5,
0.5,-0.5, 0.5,
-0.5,-0.5, 0.5,
-0.5,-0.5,-0.5,
-0.5, 0.5, 0.5,
-0.5,-0.5, 0.5,
0.5,-0.5, 0.5,
0.5, 0.5, 0.5,
0.5,-0.5,-0.5,
0.5, 0.5,-0.5,
0.5,-0.5,-0.5,
0.5, 0.5, 0.5,
0.5,-0.5, 0.5,
0.5, 0.5, 0.5,
0.5, 0.5,-0.5,
-0.5, 0.5,-0.5,
0.5, 0.5, 0.5,
-0.5, 0.5,-0.5,
-0.5, 0.5, 0.5,
0.5, 0.5, 0.5,
-0.5, 0.5, 0.5,
0.5,-0.5, 0.5
};
this->fireball = create3DObject(GL_TRIANGLES, 36, vertex_buffer_data, color, GL_FILL);
}
void Fireball::draw(glm::mat4 VP){
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position);
Matrices.model *= translate;
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
draw3DObject(this->fireball);
}
void Fireball::tick() {
this->position.x += speed*sin((rotation*M_PI)/180.0);
this->position.z += speed*cos((rotation*M_PI)/180.0);
this->position.y += speed_up;
speed_up += acc_y;
if(position.y < 0) flag = 0;
}
void Fireball::set_position(float x, float y, float z) {
this->position = glm::vec3(x, y, z);
} | 24.875 | 90 | 0.443216 |
7f6bd5ba63d7a3f1c512a93f753c3c509c4082c5 | 979 | php | PHP | examples/example.php | davidloubere/imap-mail-scraper | 2691761a699e0aa50d9cfb442e740645a51cdd4e | [
"MIT"
] | 4 | 2017-10-29T08:54:43.000Z | 2020-12-31T06:33:16.000Z | examples/example.php | davidloubere/imap-mail-scraper | 2691761a699e0aa50d9cfb442e740645a51cdd4e | [
"MIT"
] | null | null | null | examples/example.php | davidloubere/imap-mail-scraper | 2691761a699e0aa50d9cfb442e740645a51cdd4e | [
"MIT"
] | null | null | null | <?php
$loader = require_once __DIR__.'/../vendor/autoload.php';
use ImapMailScraper\Imap\MailStorage;
use ImapMailScraper\Parse\Parser;
use ImapMailScraper\Scraper;
$data = [];
$followRedirects = true;
$criteria = 'SINCE "30 Jun 2017" BEFORE "01 Jul 2017"';
$mailStorage = new MailStorage([
'host' => 'mail.example.com',
'port' => 993,
'security' => 'ssl',
'username' => '[email protected]',
'password' => '*********',
]);
$messages = $mailStorage->getMessagesByCriteria($criteria);
if (!empty($messages)) {
$scraper = new Scraper(
new Parser()
);
/* @var \ImapMailScraper\Mail\MessageData $message */
foreach ($messages as $message) {
$links = $scraper->getLinks($message, $followRedirects);
$data[] = [
'from' => $message->getFrom(),
'subject' => $message->getSubject(),
'date' => $message->getDate(),
'links' => $links,
];
}
}
print_r($data);
| 22.767442 | 64 | 0.579162 |
ef4e88b3cfac57caa4a234fc66535b31d61c47ec | 953 | php | PHP | routes/web.php | hasan-molla/employeems | ad90f64ba80343653aaa1709ea901a18c6dd6f0b | [
"MIT"
] | null | null | null | routes/web.php | hasan-molla/employeems | ad90f64ba80343653aaa1709ea901a18c6dd6f0b | [
"MIT"
] | null | null | null | routes/web.php | hasan-molla/employeems | ad90f64ba80343653aaa1709ea901a18c6dd6f0b | [
"MIT"
] | null | null | null | <?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Frontend\HomepageController;
use App\Http\Controllers\Backend\UserController;
use App\Http\Controllers\Backend\CountryController;
use App\Http\Controllers\Backend\StateController;
use App\Http\Controllers\Backend\CityController;
use App\Http\Controllers\Backend\DepartmentController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
Route::get('/', [HomepageController::class,'index']);
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::resource('users', UserController::class);
Route::resource('countries', CountryController::class);
Route::resource('states',StateController::class);
Route::resource('cities',CityController::class);
Route::resource('departments',DepartmentController::class);
| 35.296296 | 89 | 0.656873 |
1a7ad68cb77fc8fb804472ea0460efbedc032830 | 642 | py | Python | saleor/api/allocate/urls.py | glosoftgroup/KahawaHardware | 893e94246583addf41c3bb0d58d2ce6bcd233c4f | [
"BSD-3-Clause"
] | null | null | null | saleor/api/allocate/urls.py | glosoftgroup/KahawaHardware | 893e94246583addf41c3bb0d58d2ce6bcd233c4f | [
"BSD-3-Clause"
] | null | null | null | saleor/api/allocate/urls.py | glosoftgroup/KahawaHardware | 893e94246583addf41c3bb0d58d2ce6bcd233c4f | [
"BSD-3-Clause"
] | null | null | null | from django.conf.urls import url
from .views import (
AllocateAgentListAPIView,
AllocateCreateAPIView,
AllocateListAPIView,
AllocateUpdateAPIView,
)
urlpatterns = [
url(r'^$', AllocateListAPIView.as_view(), name='list-allocate'),
url(r'^search/$', AllocateListAPIView.as_view(), name='search-allocate'),
url(r'^agent/(?P<pk>[0-9]+)/$', AllocateAgentListAPIView.as_view(),
name='search-agent-allocate'),
url(r'^update/(?P<pk>[0-9]+)/$', AllocateUpdateAPIView.as_view(),
name='update-allocate'),
url(r'^create/$',
AllocateCreateAPIView.as_view(), name='create-allocate'),
]
| 27.913043 | 77 | 0.658879 |
c38cfa18cbeeb3f4fbb1e8948057f8b92702fe77 | 316 | cs | C# | Jabba/Framework/Genetics/UnconstrainedTree64Factory.cs | EnderPi/FlemishGiant | 24c55d1e462c92cd8c624ac73a1e0f4621e9208b | [
"MIT"
] | null | null | null | Jabba/Framework/Genetics/UnconstrainedTree64Factory.cs | EnderPi/FlemishGiant | 24c55d1e462c92cd8c624ac73a1e0f4621e9208b | [
"MIT"
] | null | null | null | Jabba/Framework/Genetics/UnconstrainedTree64Factory.cs | EnderPi/FlemishGiant | 24c55d1e462c92cd8c624ac73a1e0f4621e9208b | [
"MIT"
] | null | null | null | using EnderPi.Genetics.Tree64Rng;
using EnderPi.Random;
namespace EnderPi.Genetics
{
public class UnconstrainedTree64Factory : IGeneticSpecimenFactory
{
public IGeneticSpecimen CreateGeneticSpecimen(RandomNumberGenerator rng)
{
return new Tree64RngSpecimen();
}
}
}
| 22.571429 | 80 | 0.708861 |
7d912520f5bc50dd39d611675f6bd302d3bc9bd5 | 82 | css | CSS | __tests__/fixtures/files/main.css | CountJr/project-lvl3-s14 | d3bc12d7cec38170ddf7287d6a2adedfed8ccc0b | [
"MIT"
] | null | null | null | __tests__/fixtures/files/main.css | CountJr/project-lvl3-s14 | d3bc12d7cec38170ddf7287d6a2adedfed8ccc0b | [
"MIT"
] | null | null | null | __tests__/fixtures/files/main.css | CountJr/project-lvl3-s14 | d3bc12d7cec38170ddf7287d6a2adedfed8ccc0b | [
"MIT"
] | null | null | null | h5,h6,.h5,.h6 {
font-weight:bold !important
}ul,ol{
padding-left:2rem
}
| 13.666667 | 31 | 0.609756 |
05a568d6f3679b8d20ee93fb1c972db8d485e224 | 7,495 | py | Python | pre_cam.py | hong-chen/ARISE-video | 1fda520b989e2f4f101daa2bf9c6c083941e38af | [
"MIT"
] | null | null | null | pre_cam.py | hong-chen/ARISE-video | 1fda520b989e2f4f101daa2bf9c6c083941e38af | [
"MIT"
] | null | null | null | pre_cam.py | hong-chen/ARISE-video | 1fda520b989e2f4f101daa2bf9c6c083941e38af | [
"MIT"
] | null | null | null | import os
import numpy as np
import glob
import datetime
from PIL import Image
from pytesseract import image_to_string
from scipy import stats
def AVI2PNG(fname_avi, fdir_out_png, fps=2, verbose=False):
if os.path.isdir(fdir_out_png):
if verbose:
print('Warning [AVI2PNG]: %s already exists!' % (fdir_out_png))
print('Warning [AVI2PNG]: deleting all files under %s ...' % (fdir_out_png))
os.system('rm -rf %s/*' % (fdir_out_png))
else:
if verbose:
print('Message [AVI2PNG]: creating %s ...' % (fdir_out_png))
os.system('mkdir -p %s' % (fdir_out_png))
os.system('ffmpeg -loglevel quiet -i %s -vf fps=%d %s/%%07d.png' % (fname_avi, fps, fdir_out_png))
N = len(glob.glob('%s/*png' % fdir_out_png))
if N > 0:
print('Message [AVI2PNG]: %s conversion [AVI->PNG] is complete.' % (fname_avi))
else:
print('Error [AVI2PNG]: %s cannot be converted.' % (fname_avi))
def GTIME_IMAGE(fname, cropRegion, upscaleN=20, iterN=4):
img = Image.open(fname)
img = img.crop(cropRegion)
width, height = img.size
for i in range(iterN):
img = img.convert('L')
img = img.resize((width*upscaleN, height*upscaleN), Image.BICUBIC)
img = img.convert('L')
img = img.resize((width*upscaleN, height*upscaleN), Image.ANTIALIAS)
string = image_to_string(img, config='digits')
return string
def RENAME_PNG(fdir_in, fdir_out, dtime_ref, cropRegion, fps=2, sec_threshold=1.5, sec_vid_len=3600.0):
fnames = sorted(glob.glob('%s/*.png' % fdir_in))
NFile = len(fnames)
XX = np.arange(NFile)
jsec_ocr = np.zeros(NFile, dtype=np.float64) # Julian seconds from OCR by tesseract
# get time stamp from OCR
for i in XX:
fname = fnames[i]
rawString = GTIME_IMAGE(fname, cropRegion)
newString = rawString.replace(' ', '')
try:
dtime = datetime.datetime.strptime(newString, '%Y-%m-%d%H:%M:%S')
jsec_ocr0 = (dtime-dtime_ref).total_seconds()
if np.abs(jsec_ocr0) > sec_vid_len:
dateStr = dtime_ref.strftime('%Y-%m-%d')
timeStr = dtime.strftime('%H:%M:%S')
dtime_new = datetime.datetime.strptime(dateStr+timeStr, '%Y-%m-%d%H:%M:%S')
jsec_ocr0_new = (dtime_new-dtime_ref).total_seconds()
if -1.0 < (jsec_ocr0_new-jsec_ocr[i-1]) < 2.0:
jsec_ocr[i] = jsec_ocr0_new
else:
jsec_ocr[i] = np.nan
else:
jsec_ocr[i] = jsec_ocr0
except ValueError:
jsec_ocr[i] = np.nan
jsec_ref = 1.0/fps*XX
logic_nan = np.isnan(jsec_ocr)
indices_nan_yes = np.where(logic_nan)[0]
indices_nan_not = np.where(np.logical_not(logic_nan))[0]
# find outliers in jsec_ocr[indices_nan_not]
diff_raw = jsec_ocr[indices_nan_not]-jsec_ref[indices_nan_not]
diff_int = np.int_(diff_raw)
diff_int_unique, indices = np.unique(diff_int, return_inverse=True)
counts = np.bincount(indices)
index_max = np.argmax(counts)
diff0 = diff_int_unique[index_max]
diff = diff_raw - diff0
indices_outlier = indices_nan_not[np.where(np.abs(diff)>sec_threshold)[0]]
jsec_ocr[indices_outlier] = np.nan
logic_nan = np.isnan(jsec_ocr)
indices_nan_yes = np.where(logic_nan)[0]
indices_nan_not = np.where(np.logical_not(logic_nan))[0]
slope, intercept, r_value, p_value, std_err = stats.linregress(XX[indices_nan_not], jsec_ocr[indices_nan_not])
jsec_ocr[indices_nan_yes] = np.round(slope*XX[indices_nan_yes] + intercept, decimals=0)
for i in XX:
fname = fnames[i]
ID_str = fname.split('/')[-1][:-4]
dtimeString = (dtime_ref+datetime.timedelta(seconds=jsec_ocr[i])).strftime('%Y-%m-%d_%H:%M:%S')
if i in indices_nan_yes:
fname_new = '%s/%s_%s_bad.png' % (fdir_out, dtimeString, ID_str)
else:
fname_new = '%s/%s_%s_good.png' % (fdir_out, dtimeString, ID_str)
os.system('cp %s %s' % (fname, fname_new))
def MAIN_CAM(init, dtime_s, dtime_e, fdir_cam_data='/argus/field/arise/video'):
# for tag in ['Nadir', 'Forward']:
for tag in ['Forward']:
fnames_all = sorted(glob.glob('%s/%s*.avi' % (fdir_cam_data, tag)))
for fname in fnames_all:
dtime_str = fname[-23:-4]
dtime = datetime.datetime.strptime(dtime_str, '%Y-%m-%d-%H-%M-%S')
if (dtime >= dtime_s) and (dtime <= dtime_e):
filename_no_ext = fname.split('/')[-1][:-4]
if tag == 'Nadir':
fdir_out = init.fdir_ncam_graph
fdir_out_png = '%s/%s' % (fdir_out, filename_no_ext)
cropRegion = (134, 1926, 258, 1942)
elif tag == 'Forward':
fdir_out = init.fdir_fcam_graph
fdir_out_png = '%s/%s' % (fdir_out, filename_no_ext)
cropRegion = (151, 1064, 274, 1077)
AVI2PNG(fname, fdir_out_png)
RENAME_PNG(fdir_out_png, fdir_out, dtime, cropRegion)
def MODIFY_WRONG_MONTH(fdir, dtime_ref):
"""
will be delete
"""
fnames = sorted(glob.glob('%s/*.png' % fdir))
for fname in fnames:
filename = fname.split('/')[-1]
newString = filename[:19]
dtime = datetime.datetime.strptime(newString, '%Y-%m-%d_%H:%M:%S')
diff = np.abs((dtime-dtime_ref).total_seconds())
if diff > 86400.0*2:
dateString = dtime_ref.strftime('%Y-%m-%d')
filename_new = '%s_%s' % (dateString, filename[11:])
print(filename)
print(filename_new)
print()
# os.system('mv %s %s/%s' % (fname, fdir, filename_new))
if __name__ == '__main__':
from pre_vid import ANIM_INIT
# --- 2014-09-10 --- (5\cu)
# date = datetime.datetime(2014, 9, 10)
# dtime_s = datetime.datetime(2014, 9, 10, 19, 0)
# dtime_e = datetime.datetime(2014, 9, 11, 0, 0)
# init = ANIM_INIT(date)
# MAIN_CAM(init, dtime_s, dtime_e)
# --- 2014-09-11 --- (5\cu) Above clouds
date = datetime.datetime(2014, 9, 11)
dtime_s = datetime.datetime(2014, 9, 11, 20, 30, 0)
dtime_e = datetime.datetime(2014, 9, 11, 23, 0, 0)
init = ANIM_INIT(date)
MAIN_CAM(init, dtime_s, dtime_e)
# --- 2014-09-13 --- (5\cu) Below clouds
# date = datetime.datetime(2014, 9, 13)
# dtime_s = datetime.datetime(2014, 9, 13, 19, 30, 0)
# dtime_e = datetime.datetime(2014, 9, 13, 23, 0, 0)
# init = ANIM_INIT(date)
# MAIN_CAM(init, dtime_s, dtime_e)
exit()
# --- 2014-09-21 --- (5\cu)
# date = datetime.datetime(2014, 9, 21)
# dtime_s = datetime.datetime(2014, 9, 21, 18, 0)
# dtime_e = datetime.datetime(2014, 9, 22, 0, 0)
# init = ANIM_INIT(date)
# MAIN_CAM(init, dtime_s, dtime_e)
# --- 2014-09-24 --- (5\cu)
# date = datetime.datetime(2014, 9, 24)
# dtime_s = datetime.datetime(2014, 9, 24, 21, 0)
# dtime_e = datetime.datetime(2014, 9, 25, 1, 0)
# init = ANIM_INIT(date)
# MAIN_CAM(init, dtime_s, dtime_e)
# --- 2014-10-02 --- (5\cu)
# date = datetime.datetime(2014, 10, 2)
# dtime_s = datetime.datetime(2014, 10, 2, 23, 0)
# dtime_e = datetime.datetime(2014, 10, 3, 5, 0)
# init = ANIM_INIT(date)
# MAIN_CAM(init, dtime_s, dtime_e)
| 37.475 | 114 | 0.589326 |
05e5cba33788aeffc62a51c8a7effb5dc8ee4270 | 4,679 | py | Python | datakit_github/commands/integrate.py | associatedpress/datakit-github | 8a76f10987b372d9492f878e869ecff39983dc73 | [
"ISC"
] | 9 | 2019-09-16T19:20:30.000Z | 2022-03-03T07:12:03.000Z | datakit_github/commands/integrate.py | associatedpress/datakit-github | 8a76f10987b372d9492f878e869ecff39983dc73 | [
"ISC"
] | 24 | 2019-07-17T18:16:11.000Z | 2022-01-20T17:49:00.000Z | datakit_github/commands/integrate.py | associatedpress/datakit-github | 8a76f10987b372d9492f878e869ecff39983dc73 | [
"ISC"
] | 3 | 2019-07-26T15:59:47.000Z | 2019-09-17T17:26:38.000Z | # -*- coding: utf-8 -*-
from cliff.command import Command
from github.GithubException import GithubException
from datakit_github.github_api import GithubApi
from datakit_github.repository import Repository
from datakit_github.project_mixin import ProjectMixin
def ask(question):
return input(question)
class Integrate(ProjectMixin, Command):
"Integrate local project code with Github"
def take_action(self, parsed_args):
# Check for Github API key from configs
# TODO: Provide more helpful error message on how to create API key
# and configure plugin locally
api_key = self.configs.get('github_api_key')
if not api_key:
err_msg = "You must configure a Github API key to use this command!!\n"
self.log.error(err_msg)
elif Repository.initialized():
self.log.error("\nERROR: Repo has already been initialized locally!!")
self.log.error(
"You must either remove the .git/ directory " +
"before re-running this command, or manually " +
"configure Github integration.\n"
)
else:
account = self.choose_account(api_key)
confirm = self.confirm_account_choice(account)
if confirm in ["y", ""]:
# TODO: Handle overrides for project settings from
# configs and/or command-line flags (e.g. privacy)
privacy_choice = ask("Should this repo be private? y/n [y]: ").strip().lower()
privacy = True if privacy_choice in ['', 'y'] else False
try:
repo = account.create_repo(self.project_slug, private=privacy)
self.log.info("Repo created at {}".format(repo.html_url))
self.run_local_git_commands(repo)
except GithubException as err:
try:
error_msg = err.data['errors'][0]['message']
except KeyError:
error_msg = err.data['message']
msg = "\nERROR: Failed to create {} for {}: {}!!\n".format(
self.project_slug,
account.login,
error_msg
)
self.log.error(msg)
finally:
return {
'account': account.login,
'repo_name': self.project_slug,
'private_repo': privacy
}
def choose_account(self, api_key):
accounts = GithubApi.accounts(api_key)
if len(accounts) == 1:
target_account = accounts[0]
else:
msg = "Choose an account where the new project should be created:\n"
account_lkup = {}
self.log.info(msg)
for idx, account in enumerate(accounts):
num = idx + 1
account_lkup[num] = account
self.log.info("({}) {}".format(num, account.login))
# TODO: Check plugin for default account configuration,
# otherwise default to personal account
default = account_lkup[1]
choice_msg = "\nType a number or leave blank for default [{}]: ".format(default.login)
choice = ask(choice_msg)
if choice.strip() == '':
target_account = default
else:
target_account = account_lkup[int(choice)]
return target_account
def confirm_account_choice(self, target_account):
self.log.info("Repo will be created on account: {}".format(target_account.login))
choice = ask("Is this correct? y/n [y]: ").strip().lower()
return choice
def run_local_git_commands(self, repo):
self.log.info("Running local Git initialization...")
# TODO: Create a project-level config/datakit-github.json?
# containing name of selected account and possibly account type (org or user)?
# This can be used downstream to configure org or user-specific API calls
# if any (hold off on the "type" config until we
# determine if there are different call ypes)
Repository.init()
Repository.add()
Repository.commit("Initial commit")
Repository.add_remote(repo.ssh_url)
alert_msg = 'Local repo linked to remote origin: \n\t{}'.format(repo.html_url)
self.log.info(alert_msg)
Repository.push()
self.log.info("First commit made locally and pushed to remote")
self.log.info("View the project on Github at {}".format(repo.html_url))
| 44.561905 | 98 | 0.576405 |
f968dc4c27d26462396784d60e1939167323d106 | 364 | lua | Lua | rojtertibia/data/actions/scripts/oramond/oramond_teleport.lua | nneesshh/ot_about | a2fd7acb9a0b229593304a2f7119993227bbdf15 | [
"MIT"
] | null | null | null | rojtertibia/data/actions/scripts/oramond/oramond_teleport.lua | nneesshh/ot_about | a2fd7acb9a0b229593304a2f7119993227bbdf15 | [
"MIT"
] | null | null | null | rojtertibia/data/actions/scripts/oramond/oramond_teleport.lua | nneesshh/ot_about | a2fd7acb9a0b229593304a2f7119993227bbdf15 | [
"MIT"
] | 2 | 2019-12-11T04:13:15.000Z | 2020-02-15T14:42:13.000Z | local upFloorIds = {23668}
function onUse(player, item, fromPosition, target, toPosition, isHotkey)
if isInArray(upFloorIds, item.itemid) then
fromPosition.y = fromPosition.y + 1
fromPosition.z = fromPosition.z - 2
else
fromPosition.x = fromPosition.x + 1
fromPosition.z = fromPosition.z + 2
end
player:teleportTo(fromPosition, false)
return true
end
| 28 | 72 | 0.755495 |
7b60ac651ffc86c97e3a1f7c2353697f8fca1ad3 | 172 | rb | Ruby | db/migrate/20111106162141_add_phoneable_to_phone.rb | amooma/GS5 | acef44a7f28df0274b52a77f3a1d4c9f418d3c63 | [
"MIT"
] | 14 | 2015-01-07T10:20:22.000Z | 2020-02-19T13:35:26.000Z | db/migrate/20111106162141_add_phoneable_to_phone.rb | tpizzle/GS5 | acef44a7f28df0274b52a77f3a1d4c9f418d3c63 | [
"MIT"
] | 3 | 2015-07-22T04:35:10.000Z | 2021-02-20T14:07:27.000Z | db/migrate/20111106162141_add_phoneable_to_phone.rb | tpizzle/GS5 | acef44a7f28df0274b52a77f3a1d4c9f418d3c63 | [
"MIT"
] | 20 | 2015-04-08T07:23:21.000Z | 2021-09-11T09:05:38.000Z | class AddPhoneableToPhone < ActiveRecord::Migration
def change
add_column :phones, :phoneable_type, :string
add_column :phones, :phoneable_id, :integer
end
end
| 24.571429 | 51 | 0.761628 |
5501ba5db2eb0314a7195e56fd3824f859469614 | 237 | sql | SQL | db/CodingTaskDB/dbo/Tables/Optimization_Goal.sql | RyanLiu99/CodingTask | 3ba567cd32002679c21c3c26a2cc0792925ff9dd | [
"MIT"
] | null | null | null | db/CodingTaskDB/dbo/Tables/Optimization_Goal.sql | RyanLiu99/CodingTask | 3ba567cd32002679c21c3c26a2cc0792925ff9dd | [
"MIT"
] | null | null | null | db/CodingTaskDB/dbo/Tables/Optimization_Goal.sql | RyanLiu99/CodingTask | 3ba567cd32002679c21c3c26a2cc0792925ff9dd | [
"MIT"
] | null | null | null | CREATE TABLE [dbo].[optimization_goal] (
[optimization_goal_id] TINYINT NOT NULL,
[optimization_goal] NVARCHAR (50) NOT NULL,
CONSTRAINT [PK_optimization_goal] PRIMARY KEY CLUSTERED ([optimization_goal_id] ASC)
);
| 33.857143 | 88 | 0.721519 |
07690cc6b36f329b3277df920c67ec369e700d79 | 858 | css | CSS | web/css/user.css | mrisviz/EduSystem | 891ca14a967902acbaa4a8a89350b05d93571e37 | [
"BSD-3-Clause"
] | null | null | null | web/css/user.css | mrisviz/EduSystem | 891ca14a967902acbaa4a8a89350b05d93571e37 | [
"BSD-3-Clause"
] | null | null | null | web/css/user.css | mrisviz/EduSystem | 891ca14a967902acbaa4a8a89350b05d93571e37 | [
"BSD-3-Clause"
] | null | null | null | /* $Id: user.css,v 1.4 2006/12/30 07:45:31 dries Exp $ */
#permissions td.module {
font-weight: bold;
}
#permissions td.permission {
padding-left: 1.5em;
}
#access-rules .access-type, #access-rules .rule-type {
margin-right: 1em;
float: left;
}
#access-rules .access-type .form-item, #access-rules .rule-type .form-item {
margin-top: 0;
}
#access-rules .mask {
clear: both;
}
#user-login-form {
text-align: center;
}
#user-admin-filter ul {
list-style-type: none;
padding: 0;
margin: 0;
width: 100%;
}
#user-admin-buttons {
float: left;
margin-left: 0.5em;
clear: right;
}
/* Generated by user.module but used by profile.module: */
.profile {
clear: both;
margin: 1em 0;
}
.profile .picture {
float: right;
margin: 0 1em 1em 0;
}
.profile dt {
margin: 1em 0 0.2em 0;
font-weight: bold;
}
.profile dd {
margin:0;
}
| 17.16 | 76 | 0.644522 |
797f7ee60d7fc45e33a53bf500c1dfaada93c678 | 806 | rb | Ruby | spec/lib/xing_api/company/update/comment_spec.rb | xing/xing_api | db40c4de849b5fd6d0c1c1c664c002196ae0f7da | [
"MIT"
] | 14 | 2015-02-22T19:51:49.000Z | 2020-08-20T13:18:33.000Z | spec/lib/xing_api/company/update/comment_spec.rb | xing/xing_api | db40c4de849b5fd6d0c1c1c664c002196ae0f7da | [
"MIT"
] | 14 | 2015-01-07T22:21:48.000Z | 2018-08-14T19:47:41.000Z | spec/lib/xing_api/company/update/comment_spec.rb | xing/xing_api | db40c4de849b5fd6d0c1c1c664c002196ae0f7da | [
"MIT"
] | 14 | 2015-01-07T10:16:01.000Z | 2021-06-26T05:11:58.000Z | describe XingApi::Company::Update::Comment do
describe '.list' do
it_behaves_like 'a Xing API call'
it 'invokes the correct API call' do
expect_request(:get, '/v1/companies/updates/some_id/comments', {})
described_class.list('some_id')
end
end
describe '.create' do
it_behaves_like 'a Xing API call'
it 'invokes the correct API call' do
expect_request(:post, '/v1/companies/updates/some_id/comments', content: 'My comment')
described_class.create('some_id', 'My comment')
end
end
describe '.delete' do
it_behaves_like 'a Xing API call'
it 'invokes the correct API call' do
expect_request(:delete, '/v1/companies/updates/some_id/comments/another_id', {})
described_class.delete('some_id', 'another_id')
end
end
end
| 25.1875 | 92 | 0.682382 |
4b8a47336a92fb6730f54729b3fdbcfed2b8417b | 4,662 | rs | Rust | src/shader.rs | hoangpq/minigame-rust | 27111236568c30b8acb419aa861dc3d87998ecff | [
"MIT"
] | 1 | 2019-04-21T12:35:57.000Z | 2019-04-21T12:35:57.000Z | src/shader.rs | hoangpq/minigame-rust | 27111236568c30b8acb419aa861dc3d87998ecff | [
"MIT"
] | null | null | null | src/shader.rs | hoangpq/minigame-rust | 27111236568c30b8acb419aa861dc3d87998ecff | [
"MIT"
] | null | null | null | use engine::gl::types::*;
use engine::gl as gl;
use std::ffi::CString;
use std::ptr;
use std::str;
enum Type {
Vertex,
Fragment,
}
#[cfg(any(target_os="android", target_os="ios"))]
fn precision() -> String {
String::from("precision mediump float;\n")
}
#[cfg(not(any(target_os="android", target_os="ios")))]
fn precision() -> String {
String::from("")
}
static VS_SRC: &'static str = "\n\
attribute vec3 vertexPosition;\n\
attribute vec2 vertexTCoord;\n\
attribute vec4 vertexColor;\n\
attribute vec3 vertexNormal;\n\
\n\
varying vec2 tcoord;\n\
varying vec4 color;\n\
\n\
uniform mat4 projectionMatrix;\n\
uniform mat4 modelViewMatrix;\n\
\n\
void main(void) {\n\
\n\
gl_Position = projectionMatrix * modelViewMatrix * vec4(vertexPosition, 1.0);\n\
tcoord = vertexTCoord;\n\
color = vertexColor;\n\
vec3 n = vertexNormal;\n\
gl_PointSize = 1.0;\n\
\n\
}";
static FS_SRC: &'static str = "\n\
uniform sampler2D tex0;\n\
varying vec2 tcoord;\n\
varying vec4 color;\n\
\n\
void main(void) {\n\
\n\
vec4 texcolor = texture2D(tex0, tcoord);\n\
gl_FragColor = color * texcolor;\n\
\n\
}";
#[derive(Debug, Copy, Clone)]
pub struct Shader {
vertShader: GLuint,
fragShader: GLuint,
pub program: GLuint,
}
fn defaultVertexSource() -> String {
precision() + VS_SRC
}
fn defaultFragmentSource() -> String {
precision() + FS_SRC
}
impl Shader {
pub fn new() -> Shader {
Shader {
fragShader: 0,
vertShader: 0,
program: 0,
}
}
fn compile(&mut self, vertexSource: &str, fragmentSource: &str) {
self.vertShader = self.compile_shader(vertexSource, gl::VERTEX_SHADER);
self.fragShader = self.compile_shader(fragmentSource, gl::FRAGMENT_SHADER);
self.program = self.link_program(self.vertShader, self.fragShader)
}
fn compile_shader(&self, src: &str, ty: GLenum) -> GLuint {
let shader;
unsafe {
shader = gl::CreateShader(ty);
// Attempt to compile the shader
let c_str = CString::new(src.as_bytes()).unwrap();
gl::ShaderSource(shader, 1, &c_str.as_ptr(), ptr::null());
gl::CompileShader(shader);
// Get the compile status
let mut status = gl::FALSE as GLint;
gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut status);
// Fail on error
if status != (gl::TRUE as GLint) {
let mut len = 0;
gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut len);
let mut buf = Vec::with_capacity(len as usize);
buf.set_len((len as usize) - 1); // subtract 1 to skip the trailing null character
gl::GetShaderInfoLog(shader,
len,
ptr::null_mut(),
buf.as_mut_ptr() as *mut GLchar);
panic!("{}",
str::from_utf8(&buf)
.ok()
.expect("ShaderInfoLog not valid utf8"));
}
}
shader
}
fn link_program(&self, vs: GLuint, fs: GLuint) -> GLuint {
unsafe {
let program = gl::CreateProgram();
gl::AttachShader(program, vs);
gl::AttachShader(program, fs);
gl::LinkProgram(program);
// Get the link status
let mut status = gl::FALSE as GLint;
gl::GetProgramiv(program, gl::LINK_STATUS, &mut status);
// Fail on error
if status != (gl::TRUE as GLint) {
let mut len: GLint = 0;
gl::GetProgramiv(program, gl::INFO_LOG_LENGTH, &mut len);
let mut buf = Vec::with_capacity(len as usize);
buf.set_len((len as usize) - 1); // subtract 1 to skip the trailing null character
gl::GetProgramInfoLog(program,
len,
ptr::null_mut(),
buf.as_mut_ptr() as *mut GLchar);
panic!("{}",
str::from_utf8(&buf)
.ok()
.expect("ProgramInfoLog not valid utf8"));
}
program
}
}
pub fn load_default(&mut self) {
self.compile(&defaultVertexSource(), &defaultFragmentSource());
}
} | 31.08 | 98 | 0.515015 |
5d25f9e6385c74bdabefe803b6ae3097b8fb9946 | 2,543 | sql | SQL | sql_files/setUp_tables/chapters.sql | YeonwooSung/DB_Implementation | f2b34952982ec4f2729fbc2bee394b73d0ee8d44 | [
"Apache-2.0"
] | null | null | null | sql_files/setUp_tables/chapters.sql | YeonwooSung/DB_Implementation | f2b34952982ec4f2729fbc2bee394b73d0ee8d44 | [
"Apache-2.0"
] | null | null | null | sql_files/setUp_tables/chapters.sql | YeonwooSung/DB_Implementation | f2b34952982ec4f2729fbc2bee394b73d0ee8d44 | [
"Apache-2.0"
] | null | null | null | -- Insert sample data for audiobook chapters
INSERT INTO chapter SET ISBN = '978-0393957242', number = 1, title = "Part I: A Voyage to Lilliput", start = "00:00:00";
INSERT INTO chapter SET ISBN = '978-0393957242', number = 2, title = "Part II: A Voyage to Brobdingnag", start = "01:40:07";
INSERT INTO chapter SET ISBN = '978-0393957242', number = 3, title = " Part III: A Voyage to Laputa, Balnibarbi, Luggnagg, Glubbdubdrib and Japan", start = "03:01:09";
INSERT INTO chapter SET ISBN = '978-0393957242', number = 4, title = "Part IV: A Voyage to the Land of the Houyhnhnms", start = "04:22:05";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 1, title = "The Boy Who Lived", start = "00:00:00";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 2, title = "The Vanishing Glass", start = "00:35:03";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 3, title = "The Letters from No One", start = "01:07:27";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 4,title = "The Keeper of Keys", start = "01:38:01";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 5, title = "Diagon Alley", start = "02:08:25";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 6, title = " The Journey from Platform Nine and Three-Quarters", start = "02:38:50";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 7, title = "The Sorting Hat", start = "03:09:43";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 8, title = "The Potions Master", start = "03:40:03";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 9, title = "The Midnight Due", start = "04:10:27";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 10, title = "Hallowe'en", start = "04:40:48";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 11, title = "Quidditch", start = "05:11:06";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 12, title = "The Mirror of Erised", start = "05:32:38";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 13, title = "Nicholas Flamel", start = "06:11:56";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 14, title = "Norbert the Norwegian Ridgeback", start = "06:52:20";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 15, title = "The Forbidden Forest", start = "07:12:43";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 16, title = "Through the Trapdoor", start = "07:43:05";
INSERT INTO chapter SET ISBN = '978-1408855652', number = 17, title = "The Man with Two Faces", start = "08:15:30";
| 57.795455 | 167 | 0.684624 |
ff5ff5b92e277867f0dafddc28fdde3023cdf3a1 | 3,486 | py | Python | python/src/shipping_allocation/envs/inventory_generators.py | jotaporras/ts_mcfrl | c8c77a8fbd58e80e926e6705320ca8bc1979efdd | [
"MIT"
] | null | null | null | python/src/shipping_allocation/envs/inventory_generators.py | jotaporras/ts_mcfrl | c8c77a8fbd58e80e926e6705320ca8bc1979efdd | [
"MIT"
] | 5 | 2020-09-26T01:26:21.000Z | 2022-02-10T02:45:51.000Z | python/src/shipping_allocation/envs/inventory_generators.py | jotaporras/ts_mcfrl | c8c77a8fbd58e80e926e6705320ca8bc1979efdd | [
"MIT"
] | null | null | null | from abc import ABC
from typing import List
import numpy as np
from network import physical_network
from experiment_utils.Order import Order
class InventoryGenerator(ABC):
# Generates new inventory and distributes it somehow to keep the network balanced for the selected locations.
# Returns a numpy array of shape (num_dcs,num_commodities) representing how much extra inventory is going to appear.
def generate_new_inventory(
self, network: physical_network, open_orders: List[Order]
): # todo add type when it works.
pass
class NaiveInventoryGenerator(InventoryGenerator):
def generate_new_inventory(
self, network: physical_network, open_orders: List[Order]
):
# logging.info("==> inventory generator")
total_inventory = sum(
map(lambda o: o.demand, open_orders)
) # TODO rename and do for many commmodities.
even = total_inventory // network.num_dcs
dc_inv = np.array([even] * network.num_dcs).reshape(
network.num_dcs, -1
) # To keep the (dc,product) shape. #todo validate with multiple commodities
# logging.info("Demand", total_inventory)
# logging.info("Pre level dc_inv")
# logging.info(dc_inv)
# logging.info("Total new inv",np.sum(dc_inv))
imbalance = total_inventory - np.sum(dc_inv, axis=0)
# if total_inventory // network.num_dcs != total_inventory / network.num_dcs:
dc_inv[0, :] = dc_inv[0, :] + imbalance
# logging.info("Rebalanced dc inv",dc_inv)
# logging.info("Rebalanced sum",np.sum(dc_inv))
if (np.sum(dc_inv, axis=0) != total_inventory).any():
raise Exception("np.sum(dc_inv) != total_inventory")
return dc_inv
class DirichletInventoryGenerator(InventoryGenerator):
def __init__(self, network: physical_network):
num_dcs = network.num_dcs
num_commodities = network.num_commodities
self.alpha = np.random.permutation(
num_dcs / np.arange(1, num_dcs + 1)
) # trying to make it skewed.
self.inventory_generation_distribution = np.random.dirichlet(
self.alpha, num_commodities
) # (num_dc,num_k) of dc distribution of inventory.
def generate_new_inventory(
self, network: physical_network, open_orders: List[Order]
):
# logging.info("==> inventory generator")
total_inventory = sum(
map(lambda o: o.demand, open_orders)
) # TODO rename and do for many commmodities.
# even = total_inventory // network.num_dcs
inventory_distribution = self.inventory_generation_distribution
supply_per_dc = np.floor(
total_inventory.reshape(-1, 1) * inventory_distribution
)
imbalance = total_inventory - np.sum(supply_per_dc, axis=1)
supply_per_dc[:, 0] = supply_per_dc[:, 0] + imbalance
# logging.info("Demand", total_inventory)
# logging.info("Pre level dc_inv")
# logging.info(dc_inv)
# logging.info("Total new inv",np.sum(dc_inv))
# if total_inventory // network.num_dcs != total_inventory / network.num_dcs:
# logging.info("Rebalanced dc inv",dc_inv)
# logging.info("Rebalanced sum",np.sum(dc_inv))
if not np.isclose(np.sum(np.sum(supply_per_dc, axis=1) - total_inventory), 0.0):
raise RuntimeError("Demand was not correctly balanced")
return supply_per_dc.transpose()
| 42.512195 | 120 | 0.662651 |
6aa9a1f26b1be38f6bfd14433e94bc9e325688d0 | 280 | kt | Kotlin | src/main/kotlin/me/melijn/melijnbot/internals/utils/message/MessageBuilder.kt | iocaeaniqa/Melijn | e9845bb9c3b50e08713d9c049780d3a2790daf55 | [
"MIT"
] | 87 | 2019-01-09T12:19:50.000Z | 2022-03-30T18:59:21.000Z | src/main/kotlin/me/melijn/melijnbot/internals/utils/message/MessageBuilder.kt | iocaeaniqa/Melijn | e9845bb9c3b50e08713d9c049780d3a2790daf55 | [
"MIT"
] | 51 | 2018-07-27T14:52:29.000Z | 2022-02-15T17:41:36.000Z | src/main/kotlin/me/melijn/melijnbot/internals/utils/message/MessageBuilder.kt | iocaeaniqa/Melijn | e9845bb9c3b50e08713d9c049780d3a2790daf55 | [
"MIT"
] | 31 | 2018-06-16T12:01:49.000Z | 2022-03-19T23:30:11.000Z | package me.melijn.melijnbot.internals.utils.message
import me.melijn.melijnbot.internals.models.ModularMessage
class MessageBuilder {
var content: ModularMessage? = null
var splitter: MessageSplitter = MessageSplitter.Default
var pagination: Pagination? = null
} | 21.538462 | 59 | 0.782143 |
f25c99bb74073bea592d59dcbdbcf8d3e241bb4e | 1,853 | dart | Dart | lib/feature_news/presentation/ui/details/widgets/read_more.dart | suzan-1515/Samachar-Hub | 8e65809d0be74d625a4d946b417e968a5a04e0b0 | [
"Apache-2.0"
] | 3 | 2020-07-07T05:26:51.000Z | 2020-11-06T05:05:21.000Z | lib/feature_news/presentation/ui/details/widgets/read_more.dart | r3pairmen/NepalHub | 8e65809d0be74d625a4d946b417e968a5a04e0b0 | [
"Apache-2.0"
] | null | null | null | lib/feature_news/presentation/ui/details/widgets/read_more.dart | r3pairmen/NepalHub | 8e65809d0be74d625a4d946b417e968a5a04e0b0 | [
"Apache-2.0"
] | 4 | 2020-11-07T06:43:52.000Z | 2022-02-08T13:12:49.000Z | import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:samachar_hub/core/utils/link_utils.dart';
import 'package:samachar_hub/core/widgets/webview_widget.dart';
import 'package:samachar_hub/feature_main/presentation/blocs/settings/settings_cubit.dart';
import 'package:samachar_hub/feature_news/presentation/models/news_feed.dart';
import 'package:scoped_model/scoped_model.dart';
class ReadMore extends StatelessWidget {
const ReadMore({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
margin: EdgeInsets.symmetric(vertical: 16),
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: RaisedButton.icon(
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
color: Theme.of(context).primaryColor,
padding: const EdgeInsets.all(8),
onPressed: () {
final int newsReadMode =
context.read<SettingsCubit>().settings.newsReadMode ?? 0;
final feed = ScopedModel.of<NewsFeedUIModel>(context);
if (newsReadMode == 2) {
return LinkUtils.openLink(feed.entity.link);
} else
Navigator.pushNamed(context, InBuiltWebViewScreen.ROUTE_NAME,
arguments: InBuiltWebViewScreenArgs(
title: feed.entity.title, url: feed.entity.link));
},
icon: Icon(
FontAwesomeIcons.link,
color: Theme.of(context).cardColor,
),
label: Text('Read Full Article',
style: Theme.of(context)
.textTheme
.button
.copyWith(color: Theme.of(context).cardColor)),
),
);
}
}
| 37.816327 | 91 | 0.662169 |
0357ebc67b345b3931933c016b896c149d0dc4f1 | 1,128 | rb | Ruby | spec/jobs/sync_case_comments_spec.rb | discourse/discourse-salesforce | d1c961551ef40535d508b27c19195d93b4d1f2fc | [
"MIT"
] | null | null | null | spec/jobs/sync_case_comments_spec.rb | discourse/discourse-salesforce | d1c961551ef40535d508b27c19195d93b4d1f2fc | [
"MIT"
] | 1 | 2022-03-04T04:50:42.000Z | 2022-03-04T04:50:42.000Z | spec/jobs/sync_case_comments_spec.rb | discourse/discourse-salesforce | d1c961551ef40535d508b27c19195d93b4d1f2fc | [
"MIT"
] | null | null | null | # frozen_string_literal: true
require 'rails_helper'
require_relative '../spec_helper'
RSpec.describe Jobs::SyncCaseComments do
include_context "spec helper"
fab!(:topic) { Fabricate(:topic) }
fab!(:salesforce_case) { Fabricate(:salesforce_case, topic: topic) }
fab!(:post) { Fabricate(:post, topic: topic) }
fab!(:post2) { Fabricate(:post, topic: topic, post_number: 2) }
fab!(:post3) { Fabricate(:post, topic: topic, post_number: 3) }
fab!(:post4) { Fabricate(:post, topic: topic, post_number: 4) }
it 'will not create comments if topic not linked to Salesforce case' do
salesforce_case.destroy!
::Salesforce::CaseComment.any_instance.expects(:create!).never
described_class.new.execute(topic_id: topic.id)
end
it 'creates multiple case comment objects on Salesforce' do
topic.custom_fields["has_salesforce_case"] = true
topic.save_custom_fields
post4.custom_fields[::Salesforce::CaseComment::ID_FIELD] = "case_123"
post4.save_custom_fields
::Salesforce::CaseComment.any_instance.expects(:create!).twice
described_class.new.execute(topic_id: topic.id)
end
end
| 33.176471 | 73 | 0.731383 |
ed30fd4b907a8da818ded8419683ec4e1c094040 | 1,402 | cpp | C++ | src/evl/core/read_buffer.cpp | EventVisionLibrary/evl | 57496ae11b07aa55e42a59b1766c7db83aea095a | [
"BSD-3-Clause"
] | 19 | 2018-06-01T09:06:38.000Z | 2021-07-19T08:52:22.000Z | src/evl/core/read_buffer.cpp | EventVisionLibrary/evl | 57496ae11b07aa55e42a59b1766c7db83aea095a | [
"BSD-3-Clause"
] | 26 | 2018-06-16T09:27:23.000Z | 2019-07-09T05:52:27.000Z | src/evl/core/read_buffer.cpp | EventVisionLibrary/evl | 57496ae11b07aa55e42a59b1766c7db83aea095a | [
"BSD-3-Clause"
] | 6 | 2018-06-03T06:49:29.000Z | 2021-07-01T09:25:14.000Z | // Copyright 2018 Event Vision Library.
#include "read_buffer.hpp"
#include "unistd.h" // for sleep function
#include <mutex>
#include <vector>
#include "common.hpp"
#include "shutdown.hpp"
#include "types.hpp"
std::mutex mtx;
namespace evl {
std::vector<EventTuple> readBufferOnLifetime(EventBuffer *buffer,
int lifetime) {
std::vector<EventTuple> v;
mtx.lock();
EventTuple tup = (*buffer).front(); // get first element
int32_t starttime = std::get<0>(tup);
v.push_back(tup);
for (size_t cnt = 1; cnt < (*buffer).capacity(); cnt++) {
EventTuple tup = (*buffer)[cnt]; // get first element
if (std::get<0>(tup) == 0) {
break;
} else if (std::get<0>(tup) > starttime - lifetime) {
v.push_back(tup);
} else { break; }
}
mtx.unlock();
return v;
}
std::vector<EventTuple> readBufferOnNumber(EventBuffer *buffer, int number) {
std::vector<EventTuple> v;
mtx.lock();
EventTuple tup = (*buffer).front(); // get first element
v.push_back(tup);
for (size_t cnt = 1; cnt < (*buffer).capacity(); cnt++) {
EventTuple tup = (*buffer)[cnt]; // get first element
if (std::get<0>(tup) == 0) {
break;
} else if (v.size() < number) {
v.push_back(tup);
} else { break; }
}
mtx.unlock();
return v;
}
} // namespace evl
| 25.035714 | 77 | 0.575606 |
23c7f5592c835ca38b9489e97a9c11b2866142a7 | 1,407 | js | JavaScript | src/components/Card.js | Adherentman/simple-forum | 07587fdc9943d84075396b16cadf216396452232 | [
"MIT"
] | 1 | 2018-03-03T03:52:31.000Z | 2018-03-03T03:52:31.000Z | src/components/Card.js | Adherentman/simple-forum | 07587fdc9943d84075396b16cadf216396452232 | [
"MIT"
] | null | null | null | src/components/Card.js | Adherentman/simple-forum | 07587fdc9943d84075396b16cadf216396452232 | [
"MIT"
] | null | null | null | import React from 'react';
import { Card } from 'antd';
import { graphql } from 'react-apollo';
import { gql } from 'apollo-boost';
//import * as Immutable from 'immutable';
//import { bindActionCreators } from 'redux';
//import { connect } from 'react-redux';
// import { bookActions, BookActions } from '../actions/bookAction';
import Apolloex from './Apolloex';
const { Meta } = Card;
const cardStyle = {
width: '400px',
margin: '0 auto',
};
const gridStyle = {
width: '300px',
};
class Cards extends React.Component {
componentDidMount() {
//var actions = this.props.actions;
//actions.AddTodo();
}
render() {
//var text: Immutable.List<Immutable.Map<string, any>> = this.props.text;
return (
<div style={cardStyle}>
<Card
hoverable
cover={<img alt="example" src={require('../assets/images/pi.jpg')} />}
style={gridStyle}
>
<Meta
title="Thank you for using!!"
description="if you don't like ant desgin, you can use:"
/>
<code>yarn remove antd</code>
<Apolloex/>
</Card>
</div>
);
}
}
// export default connect(
// (state: stateType) => {
// return {
// text: state.book.get('text'),
// };
// },
// dispatch => ({
// actions: bindActionCreators(bookActions, dispatch),
// })
// )(Cards);
export default Cards; | 24.258621 | 80 | 0.574982 |
d58168d507b61d163c2b1bccfb16fa7b3651e4a7 | 3,526 | sql | SQL | Tienda_create_2018-05-12_12_04.sql | vgalindoc/CTIC_VGalindo | f61f28ca74aab63878ec480307a8c2a0b0fd4155 | [
"Apache-2.0"
] | null | null | null | Tienda_create_2018-05-12_12_04.sql | vgalindoc/CTIC_VGalindo | f61f28ca74aab63878ec480307a8c2a0b0fd4155 | [
"Apache-2.0"
] | null | null | null | Tienda_create_2018-05-12_12_04.sql | vgalindoc/CTIC_VGalindo | f61f28ca74aab63878ec480307a8c2a0b0fd4155 | [
"Apache-2.0"
] | null | null | null | -- Created by Vertabelo (http://vertabelo.com)
-- Last modification date: 2018-05-12 16:33:07.959
-- tables
-- Table: Carrito
CREATE TABLE Carrito (
ID_Carrito int NOT NULL,
DNI int NOT NULL,
ID_Item int NOT NULL,
CONSTRAINT Carrito_pk PRIMARY KEY (ID_Carrito)
);
-- Table: Carrito_MetCompra
CREATE TABLE Carrito_MetCompra (
ID_MetCompra int NOT NULL,
Carrito_ID_Carrito int NOT NULL
);
-- Table: Carrito_MetPago
CREATE TABLE Carrito_MetPago (
ID_MetPago int NOT NULL,
ID_Carrito int NOT NULL
);
-- Table: Carrito_item
CREATE TABLE Carrito_item (
ID Item int NOT NULL,
ID Carrito int NOT NULL
);
-- Table: Cliente
CREATE TABLE Cliente (
DNI int NOT NULL,
Nombre1 int NOT NULL,
Nombre2 int NOT NULL,
Apellido1 int NOT NULL,
Apellido2 int NOT NULL,
CONSTRAINT Cliente_pk PRIMARY KEY (DNI)
);
-- Table: Item_Proveedor
CREATE TABLE Item_Proveedor (
RUC int NOT NULL,
ID_Item int NOT NULL,
Precio_compra int NOT NULL
);
-- Table: Items
CREATE TABLE Items (
ID int NOT NULL,
Descripcion int NOT NULL,
Color int NOT NULL,
Precio_venta int NOT NULL,
CONSTRAINT Items_pk PRIMARY KEY (ID)
);
-- Table: Metodo de Compra
CREATE TABLE Metodo de Compra (
ID int NOT NULL,
Descripcion int NOT NULL,
Tipo int NOT NULL,
Direccion int NOT NULL,
CONSTRAINT Metodo de Compra_pk PRIMARY KEY (ID)
);
-- Table: Metodo de Pago
CREATE TABLE Metodo de Pago (
ID_MetPago int NOT NULL,
Descripcion int NOT NULL,
CONSTRAINT Metodo de Pago_pk PRIMARY KEY (ID_MetPago)
);
-- Table: Proveedor
CREATE TABLE Proveedor (
RUC int NOT NULL,
Nombre int NOT NULL,
Direccion int NOT NULL,
CONSTRAINT RUC PRIMARY KEY (RUC)
);
-- foreign keys
-- Reference: Carrito_Clinte (table: Carrito)
ALTER TABLE Carrito ADD CONSTRAINT Carrito_Clinte
FOREIGN KEY (DNI)
REFERENCES Cliente (DNI);
-- Reference: Carrito_MetCompra_Carrito (table: Carrito_MetCompra)
ALTER TABLE Carrito_MetCompra ADD CONSTRAINT Carrito_MetCompra_Carrito
FOREIGN KEY (Carrito_ID_Carrito)
REFERENCES Carrito (ID_Carrito);
-- Reference: Carrito_MetCompra_Metodo de Compra (table: Carrito_MetCompra)
ALTER TABLE Carrito_MetCompra ADD CONSTRAINT Carrito_MetCompra_Metodo de Compra
FOREIGN KEY (ID_MetCompra)
REFERENCES Metodo de Compra (ID);
-- Reference: Carrito_MetPago_Metodo de Pago (table: Carrito_MetPago)
ALTER TABLE Carrito_MetPago ADD CONSTRAINT Carrito_MetPago_Metodo de Pago
FOREIGN KEY (ID_MetPago)
REFERENCES Metodo de Pago (ID_MetPago);
-- Reference: Carrito_item_Carrito (table: Carrito_item)
ALTER TABLE Carrito_item ADD CONSTRAINT Carrito_item_Carrito
FOREIGN KEY (ID Carrito)
REFERENCES Carrito (ID_Carrito);
-- Reference: Carrito_item_Items (table: Carrito_item)
ALTER TABLE Carrito_item ADD CONSTRAINT Carrito_item_Items
FOREIGN KEY (ID Item)
REFERENCES Items (ID);
-- Reference: Item_Proveedor_Items (table: Item_Proveedor)
ALTER TABLE Item_Proveedor ADD CONSTRAINT Item_Proveedor_Items
FOREIGN KEY (ID_Item)
REFERENCES Items (ID);
-- Reference: Item_Proveedor_Proveedor (table: Item_Proveedor)
ALTER TABLE Item_Proveedor ADD CONSTRAINT Item_Proveedor_Proveedor
FOREIGN KEY (RUC)
REFERENCES Proveedor (RUC);
-- Reference: MMetodo de Pago_Carrito (table: Carrito_MetPago)
ALTER TABLE Carrito_MetPago ADD CONSTRAINT MMetodo de Pago_Carrito
FOREIGN KEY (ID_Carrito)
REFERENCES Carrito (ID_Carrito);
-- End of file.
| 27.333333 | 79 | 0.736812 |
b7821edad4ad56382773a6d0d9dadda5c8d50830 | 356 | swift | Swift | validation-test/compiler_crashers_fixed/02064-swift-diagnosticengine-diagnose.swift | ghostbar/swift-lang.deb | b1a887edd9178a0049a0ef839c4419142781f7a0 | [
"Apache-2.0"
] | 10 | 2015-12-25T02:19:46.000Z | 2021-11-14T15:37:57.000Z | validation-test/compiler_crashers_fixed/02064-swift-diagnosticengine-diagnose.swift | ghostbar/swift-lang.deb | b1a887edd9178a0049a0ef839c4419142781f7a0 | [
"Apache-2.0"
] | 2 | 2016-02-01T08:51:00.000Z | 2017-04-07T09:04:30.000Z | validation-test/compiler_crashers_fixed/02064-swift-diagnosticengine-diagnose.swift | ghostbar/swift-lang.deb | b1a887edd9178a0049a0ef839c4419142781f7a0 | [
"Apache-2.0"
] | 3 | 2016-04-02T15:05:27.000Z | 2019-08-19T15:25:02.000Z | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func g<T {
case c() {
var b = d: AnyObject, object2: BooleanType)) -> Int {
return { self[])
}
}
}(c
protocol A {
typealias g: b
func b> Voi
| 20.941176 | 87 | 0.69382 |
e845fa1c6c70e2ae131f143b128a6129389786b1 | 1,046 | cs | C# | Day2_Operators/Day2_Operators/Solution.cs | alexmacniven/hackerrank | f5aa9ce911610d329c3a42d91ce3104504827be1 | [
"MIT"
] | null | null | null | Day2_Operators/Day2_Operators/Solution.cs | alexmacniven/hackerrank | f5aa9ce911610d329c3a42d91ce3104504827be1 | [
"MIT"
] | 2 | 2019-07-22T21:43:17.000Z | 2019-07-22T21:46:34.000Z | Day2_Operators/Day2_Operators/Solution.cs | alexmacniven/hackerrank | f5aa9ce911610d329c3a42d91ce3104504827be1 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Text;
namespace Day2_Operators
{
class Solution
{
static void Solve(double meal_cost, int tip_percent, int tax_percent)
{
// Calculate tip_percent value as double
double tip_value;
tip_value = meal_cost * (double)tip_percent / 100;
// Calculate tax_percent value as double
double tax_value;
tax_value = meal_cost * (double)tax_percent / 100;
double total;
total = meal_cost + tip_value + tax_value;
Console.WriteLine((int)Math.Round(total, MidpointRounding.AwayFromZero));
}
static void Main(string[] args)
{
double meal_cost = Convert.ToDouble(Console.ReadLine());
int tip_percent = Convert.ToInt32(Console.ReadLine());
int tax_percent = Convert.ToInt32(Console.ReadLine());
Solve(meal_cost, tip_percent, tax_percent);
Console.ReadLine();
}
}
}
| 26.15 | 85 | 0.60325 |
0da9864e46189942890528dac624dad563d5e5d1 | 4,082 | cs | C# | src/TestAppWithTUI/ConsoleTest.cs | makarovsl/Nlog.Repeated | 7cc5b2ac4a2ef30d8b829e30165657dac81a4ea2 | [
"BSD-3-Clause"
] | null | null | null | src/TestAppWithTUI/ConsoleTest.cs | makarovsl/Nlog.Repeated | 7cc5b2ac4a2ef30d8b829e30165657dac81a4ea2 | [
"BSD-3-Clause"
] | null | null | null | src/TestAppWithTUI/ConsoleTest.cs | makarovsl/Nlog.Repeated | 7cc5b2ac4a2ef30d8b829e30165657dac81a4ea2 | [
"BSD-3-Clause"
] | null | null | null | // Licensed under the BSD license
// See the LICENSE file in the project root for more information
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using FakeSyslogServer;
using Microsoft.Extensions.Configuration;
namespace TestAppWithTui
{
public class ConsoleTest : IDisposable
{
private static readonly Dictionary<char, string> ChosenOperation;
private readonly IConfigurationRoot settings;
private readonly TestAppHelper testAppHelper;
private FileStream udpFileStream;
private StreamWriter udpStreamWriter;
private FileStream tcpFileStream;
private StreamWriter tcpStreamWriter;
static ConsoleTest()
{
ChosenOperation = new Dictionary<char, string>
{
{ 'T', "Trace" },
{ 'D', "Debug" },
{ 'I', "Info" },
{ 'W', "Warn" },
{ 'E', "Error" },
{ 'F', "Fatal" },
{ 'R', "FromFile" },
{ 'H', "Huge" },
{ 'M', "Multiple" },
{ 'C', "Continuous" },
{ 'P', "Parallel" },
{ 'S', "StartSyslogServer" },
{ 'Q', "Quit" }
};
}
public ConsoleTest()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appSettings.json");
settings = builder.Build();
testAppHelper = new TestAppHelper(key => settings[key], ToggleSyslogServer);
}
public string PromptUserForOperationChoice()
{
Console.WriteLine("Choose an operation:");
ChosenOperation
.Select(x => $"{x.Key} => {x.Value}")
.ToList()
.ForEach(Console.WriteLine);
var choice = Char.ToUpper(Console.ReadKey().KeyChar);
Console.WriteLine();
return ChosenOperation[choice];
}
public void PerformOperation(string operation)
{
testAppHelper.PerformSelectedOperation(operation);
}
public void Dispose()
{
testAppHelper.Dispose();
DisposeStreams();
}
private void ToggleSyslogServer (bool start, SyslogServer syslogServer)
{
if (start)
{
ChosenOperation['S'] = "StopSyslogServer";
InitStreams();
syslogServer.Start(OnReceivedString, OnException);
}
else
{
ChosenOperation['S'] = "StartSyslogServer";
syslogServer.Stop();
DisposeStreams();
}
}
private void InitStreams()
{
udpFileStream = new FileStream(settings["udpLogEntriesFilePath"], FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
udpFileStream.SetLength(0);
udpStreamWriter = new StreamWriter(udpFileStream);
tcpFileStream = new FileStream(settings["tcpLogEntriesFilePath"], FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
tcpFileStream.SetLength(0);
tcpStreamWriter = new StreamWriter(tcpFileStream);
}
private void OnReceivedString(int protocolType, string receivedString)
{
Trace.WriteLine(receivedString);
var file = protocolType == SyslogServer.UdpProtocolHashCode ? udpStreamWriter : tcpStreamWriter;
file.WriteLine(receivedString);
file.Flush();
}
private void OnException(Task task)
{
Trace.WriteLine(this, task.Exception?.GetBaseException().ToString());
}
private void DisposeStreams()
{
udpStreamWriter.Close();
udpFileStream.Close();
tcpStreamWriter.Close();
tcpFileStream.Close();
}
}
} | 31.890625 | 140 | 0.55463 |
041249e8360e805b3879e9ac3e612954b1c12ed3 | 1,043 | cpp | C++ | fontcharacter.cpp | zheka20012/OMSIFontCreator | 237515473720ca663f87aadbf1eed7950164d0c1 | [
"Unlicense"
] | 2 | 2021-12-19T18:57:45.000Z | 2021-12-21T12:50:50.000Z | fontcharacter.cpp | zheka20012/OMSIFontCreator | 237515473720ca663f87aadbf1eed7950164d0c1 | [
"Unlicense"
] | 1 | 2022-03-07T11:24:39.000Z | 2022-03-07T11:24:39.000Z | fontcharacter.cpp | zheka20012/OMSIFontCreator | 237515473720ca663f87aadbf1eed7950164d0c1 | [
"Unlicense"
] | null | null | null | #include "fontcharacter.h"
FontCharacter::~FontCharacter(){
}
FontCharacter::FontCharacter(const QChar letter)
{
Letter = letter;
LeftPixel = RightPixel = 0;
TopPixel = 0;
}
FontCharacter::FontCharacter(QTextStream &inStream)
{
Letter = inStream.readLine().at(0);
LeftPixel = inStream.readLine().toUShort();
RightPixel = inStream.readLine().toUShort();
TopPixel = inStream.readLine().toUShort();
}
void FontCharacter::SetCharacter(const QChar letter)
{
Letter = letter;
}
void FontCharacter::SetPixels(unsigned int leftPixel, unsigned int rightPixel, unsigned int topPixel)
{
LeftPixel = leftPixel;
RightPixel = rightPixel;
TopPixel = topPixel;
}
void FontCharacter::Save(QTextStream &fileStream)
{
fileStream << "[char]" << Qt::endl;
fileStream << Letter << Qt::endl;
fileStream << LeftPixel << Qt::endl;
fileStream << RightPixel << Qt::endl;
fileStream << TopPixel << Qt::endl;
fileStream << Qt::endl;
}
QChar FontCharacter::GetCharacter()
{
return Letter;
}
| 21.729167 | 103 | 0.683605 |
2d729a4fb672f316362382bcff4e0c7a4bd62513 | 837 | cpp | C++ | cpp/A0560/main.cpp | Modnars/LeetCode | 1c91fe9598418e6ed72233260f9cd8d5737fe216 | [
"Apache-2.0"
] | 2 | 2021-11-26T14:06:13.000Z | 2021-11-26T14:34:34.000Z | cpp/A0560/main.cpp | Modnars/LeetCode | 1c91fe9598418e6ed72233260f9cd8d5737fe216 | [
"Apache-2.0"
] | 2 | 2021-11-26T14:06:49.000Z | 2021-11-28T11:28:49.000Z | cpp/A0560/main.cpp | Modnars/LeetCode | 1c91fe9598418e6ed72233260f9cd8d5737fe216 | [
"Apache-2.0"
] | null | null | null | // URL : https://leetcode-cn.com/problems/subarray-sum-equals-k/
// Author : Modnar
// Date : 2020/05/15
#include <bits/stdc++.h>
/* ************************* */
// Thanks: LeetCode(@leetcode.cn)
// Solution: https://leetcode-cn.com/problems/subarray-sum-equals-k/solution/he-wei-kde-zi-shu-zu-by-leetcode-solution/
// Time: 68ms(68.32%) Memory: 22MB(6.67%)
class Solution {
public:
int subarraySum(std::vector<int> &nums, int k) {
std::unordered_map<int, int> mp;
mp[0] = 1;
int count = 0, pre = 0;
for (auto & x : nums) {
pre += x;
if (mp.find(pre-k) != mp.end())
count += mp[pre-k];
++mp[pre];
}
return count;
}
};
/* ************************* */
int main(int argc, const char *argv[]) {
return EXIT_SUCCESS;
}
| 25.363636 | 119 | 0.51135 |
f47967fc2074f4256ab0acf986407844834e9c6c | 608 | ts | TypeScript | NotifyTodaysReleases/constants.ts | yudai-nkt/sbotify | 76aeb846faff1b67941fbc9eaff6854d5ea993cc | [
"MIT"
] | null | null | null | NotifyTodaysReleases/constants.ts | yudai-nkt/sbotify | 76aeb846faff1b67941fbc9eaff6854d5ea993cc | [
"MIT"
] | null | null | null | NotifyTodaysReleases/constants.ts | yudai-nkt/sbotify | 76aeb846faff1b67941fbc9eaff6854d5ea993cc | [
"MIT"
] | 1 | 2021-03-09T17:11:17.000Z | 2021-03-09T17:11:17.000Z | /**
* An array of artist names who are unlikey to release new materials (mainly because
* they already disbanded) to reduce the number of API calls.
*/
export const EXCLUDES = [
"CYBER",
"SIAM SHAME",
"There For Tomorrow",
"Artificial Language",
"Children Of Bodom",
"Breakdown of Sanity",
"Uchu Conbini",
"sora tob sakana",
"Seiko Matsuda",
"Cynic",
"The Afterimage",
"Euphoreon",
"JUDY AND MARY",
"Ever Forthright",
"桃箱",
"Happy Kuru Kuru",
"BILLIE IDLE",
"YVR",
];
/**
* ID of the denonbu playlist.
*/
export const DENONBU_PLAYLIST_ID = "7i8SGeiff2FhLvl82hQMvg";
| 20.266667 | 84 | 0.662829 |
028e5ec97bbaec3a476e32481d2a4f6b93c99e52 | 5,701 | cpp | C++ | src/Settings/RunawaySourceTerms.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 12 | 2020-09-07T11:19:10.000Z | 2022-02-17T17:40:19.000Z | src/Settings/RunawaySourceTerms.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 110 | 2020-09-02T15:29:24.000Z | 2022-03-09T09:50:01.000Z | src/Settings/RunawaySourceTerms.cpp | chalmersplasmatheory/DREAM | 715637ada94f5e35db16f23c2fd49bb7401f4a27 | [
"MIT"
] | 3 | 2021-05-21T13:24:31.000Z | 2022-02-11T14:43:12.000Z | /**
* Initialization of runaway source terms.
*/
#include "DREAM/Equations/Fluid/TritiumRateTerm.hpp"
#include "DREAM/Equations/Fluid/HottailRateTermHighZ.hpp"
#include "DREAM/Equations/Fluid/ExternalAvalancheTerm.hpp"
#include "DREAM/Equations/RunawaySourceTerm.hpp"
#include "DREAM/IO.hpp"
#include "DREAM/Settings/SimulationGenerator.hpp"
using namespace DREAM;
RunawaySourceTermHandler *SimulationGenerator::ConstructRunawaySourceTermHandler(
FVM::Grid *grid, FVM::Grid *hottailGrid, FVM::Grid *runawayGrid, FVM::Grid *fluidGrid,
FVM::UnknownQuantityHandler *unknowns, RunawayFluid *REFluid,
IonHandler *ions, AnalyticDistributionHottail *distHT,
struct OtherQuantityHandler::eqn_terms *oqty_terms, Settings *s, bool signPositive
) {
const std::string &mod = "eqsys/n_re";
std::string eqnSign = signPositive ? " + " : " - ";
RunawaySourceTermHandler *rsth = new RunawaySourceTermHandler();
// Add avalanche growth rate:
// - fluid mode, use analytical growth rate formula,
// - kinetic mode, add those knockons which are created for p>pMax
OptionConstants::eqterm_avalanche_mode ava_mode = (enum OptionConstants::eqterm_avalanche_mode)s->GetInteger(mod + "/avalanche");
// Add avalanche growth rate
if (ava_mode == OptionConstants::EQTERM_AVALANCHE_MODE_FLUID || ava_mode == OptionConstants::EQTERM_AVALANCHE_MODE_FLUID_HESSLOW)
rsth->AddSourceTerm(eqnSign + "n_re*Gamma_ava", new AvalancheGrowthTerm(grid, unknowns, REFluid, fluidGrid, -1.0) );
else if (ava_mode == OptionConstants::EQTERM_AVALANCHE_MODE_KINETIC) {
if (hottailGrid || runawayGrid != nullptr) {
// XXX: assume same momentum grid at all radii
real_t pCut;
if (hottailGrid != nullptr)
pCut = hottailGrid->GetMomentumGrid(0)->GetP1_f(hottailGrid->GetNp1(0));
else if (runawayGrid != nullptr)
pCut = runawayGrid->GetMomentumGrid(0)->GetP1_f(0);
if (grid == runawayGrid) {
rsth->AddSourceTerm(eqnSign + "external avalanche", new AvalancheSourceRP(grid, unknowns, pCut, -1.0, AvalancheSourceRP::RP_SOURCE_MODE_KINETIC, AvalancheSourceRP::RP_SOURCE_PITCH_POSITIVE) );
rsth->AddAvalancheNreNeg(new AvalancheSourceRP(grid, unknowns, pCut, +1.0, AvalancheSourceRP::RP_SOURCE_MODE_KINETIC, AvalancheSourceRP::RP_SOURCE_PITCH_POSITIVE));
rsth->AddAvalancheNreNegPos(new AvalancheSourceRP(grid, unknowns, pCut, -1.0, AvalancheSourceRP::RP_SOURCE_MODE_KINETIC, AvalancheSourceRP::RP_SOURCE_PITCH_NEGATIVE));
} else if (grid == fluidGrid){
if(runawayGrid == nullptr) // match external growth to fluid formula in E~<Eceff limit
rsth->AddSourceTerm(eqnSign + "external avalanche", new ExternalAvalancheTerm(grid, pCut, -2.0, REFluid, unknowns, -1.0) );
else // use regular external RE growth (RP integrated over p>pCut)
rsth->AddSourceTerm(eqnSign + "external avalanche", new AvalancheSourceRP(grid, unknowns, pCut, -1.0, AvalancheSourceRP::RP_SOURCE_MODE_FLUID) );
}
} else
DREAM::IO::PrintWarning(DREAM::IO::WARNING_KINETIC_AVALANCHE_NO_HOT_GRID, "A kinetic avalanche term is used, but the hot-tail grid is disabled. Ignoring avalanche source...");
}
// Add Dreicer runaway rate
enum OptionConstants::eqterm_dreicer_mode dm =
(enum OptionConstants::eqterm_dreicer_mode)s->GetInteger(mod + "/dreicer");
switch (dm) {
case OptionConstants::EQTERM_DREICER_MODE_CONNOR_HASTIE_NOCORR:
rsth->AddSourceTerm(eqnSign + "dreicer (CH)", new DreicerRateTerm(
grid, unknowns, REFluid,
ions, DreicerRateTerm::CONNOR_HASTIE_NOCORR, -1.0
));
break;
case OptionConstants::EQTERM_DREICER_MODE_CONNOR_HASTIE:
rsth->AddSourceTerm(eqnSign + "dreicer (CH)", new DreicerRateTerm(
grid, unknowns, REFluid,
ions, DreicerRateTerm::CONNOR_HASTIE, -1.0
));
break;
case OptionConstants::EQTERM_DREICER_MODE_NEURAL_NETWORK:
rsth->AddSourceTerm(eqnSign + "dreicer (NN)", new DreicerRateTerm(
grid, unknowns, REFluid,
ions, DreicerRateTerm::NEURAL_NETWORK, -1.0
));
break;
default: break; // Don't add Dreicer runaways
}
// Add compton source
OptionConstants::eqterm_compton_mode compton_mode = (enum OptionConstants::eqterm_compton_mode)s->GetInteger(mod + "/compton/mode");
if (compton_mode == OptionConstants::EQTERM_COMPTON_MODE_FLUID)
rsth->AddSourceTerm(eqnSign + "compton", new ComptonRateTerm(grid, unknowns, REFluid, fluidGrid, -1.0) );
// Add tritium source
bool tritium_enabled = s->GetBool(mod + "/tritium");
if (tritium_enabled) {
const len_t *ti = ions->GetTritiumIndices();
for (len_t i = 0; i < ions->GetNTritiumIndices(); i++)
rsth->AddSourceTerm(eqnSign + "tritium", new TritiumRateTerm(grid, ions, unknowns, ti[i], REFluid, -1.0));
}
// Add hottail source
OptionConstants::eqterm_hottail_mode hottail_mode = (enum OptionConstants::eqterm_hottail_mode)s->GetInteger(mod + "/hottail");
if(distHT!=nullptr && hottail_mode == OptionConstants::EQTERM_HOTTAIL_MODE_ANALYTIC_ALT_PC){
oqty_terms->n_re_hottail_rate = new HottailRateTermHighZ(
grid, distHT, unknowns, ions,
REFluid->GetLnLambda(), -1.0
);
rsth->AddSourceTerm(eqnSign + "hottail", oqty_terms->n_re_hottail_rate);
}
return rsth;
}
| 50.008772 | 208 | 0.6776 |
88664b689a8f48c7707d58d99caed4d3603c7c7e | 23,425 | cs | C# | test/Microsoft.AspNetCore.Mvc.Core.Test/Internal/ApiBehaviorApplicationModelProviderTest.cs | poke/aspnet_Mvc | d40c60d15ba3f9e0fd4854a5f23651148161bc36 | [
"Apache-2.0"
] | 3 | 2021-06-23T03:26:45.000Z | 2021-06-26T12:43:01.000Z | test/Microsoft.AspNetCore.Mvc.Core.Test/Internal/ApiBehaviorApplicationModelProviderTest.cs | poke/aspnet_Mvc | d40c60d15ba3f9e0fd4854a5f23651148161bc36 | [
"Apache-2.0"
] | null | null | null | test/Microsoft.AspNetCore.Mvc.Core.Test/Internal/ApiBehaviorApplicationModelProviderTest.cs | poke/aspnet_Mvc | d40c60d15ba3f9e0fd4854a5f23651148161bc36 | [
"Apache-2.0"
] | 1 | 2020-12-23T17:33:15.000Z | 2020-12-23T17:33:15.000Z | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Internal
{
public class ApiBehaviorApplicationModelProviderTest
{
[Fact]
public void OnProvidersExecuting_AddsModelStateInvalidFilter_IfTypeIsAnnotatedWithAttribute()
{
// Arrange
var context = GetContext(typeof(TestApiController));
var provider = GetProvider();
// Act
provider.OnProvidersExecuting(context);
// Assert
var actionModel = Assert.Single(Assert.Single(context.Result.Controllers).Actions);
Assert.IsType<ModelStateInvalidFilter>(actionModel.Filters.Last());
}
[Fact]
public void OnProvidersExecuting_DoesNotAddModelStateInvalidFilterToController_IfFeatureIsDisabledViaOptions()
{
// Arrange
var context = GetContext(typeof(TestApiController));
var options = new ApiBehaviorOptions
{
SuppressModelStateInvalidFilter = true,
};
var provider = GetProvider(options);
// Act
provider.OnProvidersExecuting(context);
// Assert
var controllerModel = Assert.Single(context.Result.Controllers);
Assert.DoesNotContain(typeof(ModelStateInvalidFilter), controllerModel.Filters.Select(f => f.GetType()));
}
[Fact]
public void OnProvidersExecuting_AddsModelStateInvalidFilter_IfActionIsAnnotatedWithAttribute()
{
// Arrange
var context = GetContext(typeof(SimpleController));
var provider = GetProvider();
// Act
provider.OnProvidersExecuting(context);
// Assert
Assert.Collection(
Assert.Single(context.Result.Controllers).Actions.OrderBy(a => a.ActionName),
action =>
{
Assert.Contains(typeof(ModelStateInvalidFilter), action.Filters.Select(f => f.GetType()));
},
action =>
{
Assert.DoesNotContain(typeof(ModelStateInvalidFilter), action.Filters.Select(f => f.GetType()));
});
}
[Fact]
public void OnProvidersExecuting_SkipsAddingFilterToActionIfFeatureIsDisabledUsingOptions()
{
// Arrange
var context = GetContext(typeof(SimpleController));
var options = new ApiBehaviorOptions
{
SuppressModelStateInvalidFilter = true,
};
var provider = GetProvider(options);
// Act
provider.OnProvidersExecuting(context);
// Assert
Assert.Collection(
Assert.Single(context.Result.Controllers).Actions.OrderBy(a => a.ActionName),
action =>
{
Assert.DoesNotContain(typeof(ModelStateInvalidFilter), action.Filters.Select(f => f.GetType()));
},
action =>
{
Assert.DoesNotContain(typeof(ModelStateInvalidFilter), action.Filters.Select(f => f.GetType()));
});
}
[Fact]
public void OnProvidersExecuting_MakesControllerVisibleInApiExplorer_IfItIsAnnotatedWithAttribute()
{
// Arrange
var context = GetContext(typeof(TestApiController));
var options = new ApiBehaviorOptions
{
SuppressModelStateInvalidFilter = true,
};
var provider = GetProvider(options);
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.True(controller.ApiExplorer.IsVisible);
}
[Fact]
public void OnProvidersExecuting_DoesNotModifyVisibilityInApiExplorer_IfValueIsAlreadySet()
{
// Arrange
var context = GetContext(typeof(TestApiController));
context.Result.Controllers[0].ApiExplorer.IsVisible = false;
var options = new ApiBehaviorOptions
{
SuppressModelStateInvalidFilter = true,
};
var provider = GetProvider(options);
// Act
provider.OnProvidersExecuting(context);
// Assert
var controller = Assert.Single(context.Result.Controllers);
Assert.False(controller.ApiExplorer.IsVisible);
}
[Fact]
public void OnProvidersExecuting_ThrowsIfControllerWithAttribute_HasActionsWithoutAttributeRouting()
{
// Arrange
var actionName = $"{typeof(ActionsWithoutAttributeRouting).FullName}.{nameof(ActionsWithoutAttributeRouting.Index)} ({typeof(ActionsWithoutAttributeRouting).Assembly.GetName().Name})";
var expected = $"Action '{actionName}' does not have an attribute route. Action methods on controllers annotated with ApiControllerAttribute must be attribute routed.";
var context = GetContext(typeof(ActionsWithoutAttributeRouting));
var provider = GetProvider();
// Act & Assert
var ex = Assert.Throws<InvalidOperationException>(() => provider.OnProvidersExecuting(context));
Assert.Equal(expected, ex.Message);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsPath_IfParameterNameExistsInRouteAsSimpleToken()
{
// Arrange
var actionName = nameof(ParameterBindingController.SimpleRouteToken);
var parameter = GetParameterModel(typeof(ParameterBindingController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Path, result);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsPath_IfParameterNameExistsInRouteAsOptionalToken()
{
// Arrange
var actionName = nameof(ParameterBindingController.OptionalRouteToken);
var parameter = GetParameterModel(typeof(ParameterBindingController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Path, result);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsPath_IfParameterNameExistsInRouteAsConstrainedToken()
{
// Arrange
var actionName = nameof(ParameterBindingController.ConstrainedRouteToken);
var parameter = GetParameterModel(typeof(ParameterBindingController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Path, result);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsPath_IfParameterNameExistsInAbsoluteRoute()
{
// Arrange
var actionName = nameof(ParameterBindingController.AbsoluteRoute);
var parameter = GetParameterModel(typeof(ParameterBindingController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Path, result);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsPath_IfParameterAppearsInAllRoutes()
{
// Arrange
var actionName = nameof(ParameterBindingController.ParameterInMultipleRoutes);
var parameter = GetParameterModel(typeof(ParameterBindingController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Path, result);
}
[Fact]
public void InferBindingSourceForParameter_DoesNotReturnPath_IfParameterDoesNotAppearInAllRoutes()
{
// Arrange
var actionName = nameof(ParameterBindingController.ParameterNotInAllRoutes);
var parameter = GetParameterModel(typeof(ParameterBindingController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Query, result);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsPath_IfParameterAppearsInControllerRoute()
{
// Arrange
var actionName = nameof(ParameterInController.ActionWithoutRoute);
var parameter = GetParameterModel(typeof(ParameterInController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Path, result);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsPath_IfParameterAppearsInControllerRoute_AndActionHasRoute()
{
// Arrange
var actionName = nameof(ParameterInController.ActionWithRoute);
var parameter = GetParameterModel(typeof(ParameterInController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Path, result);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsPath_IfParameterAppearsInAllActionRoutes()
{
// Arrange
var actionName = nameof(ParameterInController.MultipleRoute);
var parameter = GetParameterModel(typeof(ParameterInController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Path, result);
}
[Fact]
public void InferBindingSourceForParameter_DoesNotReturnPath_IfActionRouteOverridesControllerRoute()
{
// Arrange
var actionName = nameof(ParameterInController.AbsoluteRoute);
var parameter = GetParameterModel(typeof(ParameterInController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Query, result);
}
[Fact]
public void InferBindingSourceForParameter_DoesNotReturnPath_IfOneActionRouteOverridesControllerRoute()
{
// Arrange
var actionName = nameof(ParameterInController.MultipleRouteWithOverride);
var parameter = GetParameterModel(typeof(ParameterInController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Query, result);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsPath_IfParameterExistsInRoute_OnControllersWithoutSelectors()
{
// Arrange
var actionName = nameof(ParameterBindingNoRoutesOnController.SimpleRoute);
var parameter = GetParameterModel(typeof(ParameterBindingNoRoutesOnController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Path, result);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsPath_IfParameterExistsInAllRoutes_OnControllersWithoutSelectors()
{
// Arrange
var actionName = nameof(ParameterBindingNoRoutesOnController.ParameterInMultipleRoutes);
var parameter = GetParameterModel(typeof(ParameterBindingNoRoutesOnController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Path, result);
}
[Fact]
public void InferBindingSourceForParameter_DoesNotReturnPath_IfNeitherActionNorControllerHasTemplate()
{
// Arrange
var actionName = nameof(ParameterBindingNoRoutesOnController.NoRouteTemplate);
var parameter = GetParameterModel(typeof(ParameterBindingNoRoutesOnController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Query, result);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsBodyForComplexTypes()
{
// Arrange
var actionName = nameof(ParameterBindingController.ComplexTypeModel);
var parameter = GetParameterModel(typeof(ParameterBindingController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Body, result);
}
[Fact]
public void InferBindingSourceForParameter_ReturnsBodyForSimpleTypes()
{
// Arrange
var actionName = nameof(ParameterBindingController.SimpleTypeModel);
var parameter = GetParameterModel(typeof(ParameterBindingController), actionName);
var provider = GetProvider();
// Act
var result = provider.InferBindingSourceForParameter(parameter);
// Assert
Assert.Same(BindingSource.Query, result);
}
[Fact]
public void AddMultipartFormDataConsumesAttribute_NoOpsIfBehaviorIsDisabled()
{
// Arrange
var actionName = nameof(ParameterBindingController.FromFormParameter);
var action = GetActionModel(typeof(ParameterBindingController), actionName);
var options = new ApiBehaviorOptions
{
SuppressConsumesConstraintForFormFileParameters = true,
InvalidModelStateResponseFactory = _ => null,
};
var provider = GetProvider(options);
// Act
provider.AddMultipartFormDataConsumesAttribute(action);
// Assert
Assert.Empty(action.Filters);
}
[Fact]
public void AddMultipartFormDataConsumesAttribute_NoOpsIfConsumesConstraintIsAlreadyPresent()
{
// Arrange
var actionName = nameof(ParameterBindingController.ActionWithConsumesAttribute);
var action = GetActionModel(typeof(ParameterBindingController), actionName);
var options = new ApiBehaviorOptions
{
SuppressConsumesConstraintForFormFileParameters = true,
InvalidModelStateResponseFactory = _ => null,
};
var provider = GetProvider(options);
// Act
provider.AddMultipartFormDataConsumesAttribute(action);
// Assert
var attribute = Assert.Single(action.Filters);
var consumesAttribute = Assert.IsType<ConsumesAttribute>(attribute);
Assert.Equal("application/json", Assert.Single(consumesAttribute.ContentTypes));
}
[Fact]
public void AddMultipartFormDataConsumesAttribute_AddsConsumesAttribute_WhenActionHasFromFormFileParameter()
{
// Arrange
var actionName = nameof(ParameterBindingController.FormFileParameter);
var action = GetActionModel(typeof(ParameterBindingController), actionName);
action.Parameters[0].BindingInfo = new BindingInfo
{
BindingSource = BindingSource.FormFile,
};
var provider = GetProvider();
// Act
provider.AddMultipartFormDataConsumesAttribute(action);
// Assert
var attribute = Assert.Single(action.Filters);
var consumesAttribute = Assert.IsType<ConsumesAttribute>(attribute);
Assert.Equal("multipart/form-data", Assert.Single(consumesAttribute.ContentTypes));
}
private static ApiBehaviorApplicationModelProvider GetProvider(
ApiBehaviorOptions options = null,
IModelMetadataProvider modelMetadataProvider = null)
{
options = options ?? new ApiBehaviorOptions
{
InvalidModelStateResponseFactory = _ => null,
};
var optionsProvider = Options.Create(options);
modelMetadataProvider = modelMetadataProvider ?? new TestModelMetadataProvider();
var loggerFactory = NullLoggerFactory.Instance;
return new ApiBehaviorApplicationModelProvider(optionsProvider, modelMetadataProvider, loggerFactory);
}
private static ApplicationModelProviderContext GetContext(Type type)
{
var context = new ApplicationModelProviderContext(new[] { type.GetTypeInfo() });
new DefaultApplicationModelProvider(Options.Create(new MvcOptions())).OnProvidersExecuting(context);
return context;
}
private static ActionModel GetActionModel(Type controllerType, string actionName)
{
var context = GetContext(controllerType);
var controller = Assert.Single(context.Result.Controllers);
return Assert.Single(controller.Actions, m => m.ActionName == actionName);
}
private static ParameterModel GetParameterModel(Type controllerType, string actionName)
{
var action = GetActionModel(controllerType, actionName);
return Assert.Single(action.Parameters);
}
[ApiController]
[Route("TestApi")]
private class TestApiController : Controller
{
[HttpGet]
public IActionResult TestAction() => null;
}
private class SimpleController : Controller
{
public IActionResult ActionWithoutFilter() => null;
[TestApiBehavior]
[HttpGet("/Simple/ActionWithFilter")]
public IActionResult ActionWithFilter() => null;
}
[ApiController]
private class ActionsWithoutAttributeRouting
{
public IActionResult Index() => null;
}
[AttributeUsage(AttributeTargets.Method)]
private class TestApiBehavior : Attribute, IApiBehaviorMetadata
{
}
[ApiController]
[Route("[controller]/[action]")]
private class ParameterBindingController
{
[HttpGet("{parameter}")]
public IActionResult ActionWithBoundParameter([FromBody] object parameter) => null;
[HttpGet("{id}")]
public IActionResult SimpleRouteToken(int id) => null;
[HttpPost("optional/{id?}")]
public IActionResult OptionalRouteToken(int id) => null;
[HttpDelete("delete-by-status/{status:int?}")]
public IActionResult ConstrainedRouteToken(object status) => null;
[HttpPut("/absolute-route/{status:int}")]
public IActionResult AbsoluteRoute(object status) => null;
[HttpPost("multiple/{id}")]
[HttpPut("multiple/{id}")]
public IActionResult ParameterInMultipleRoutes(int id) => null;
[HttpPatch("patchroute")]
[HttpPost("multiple/{id}")]
[HttpPut("multiple/{id}")]
public IActionResult ParameterNotInAllRoutes(int id) => null;
[HttpPut("put-action/{id}")]
public IActionResult ComplexTypeModel(TestModel model) => null;
[HttpPut("put-action/{id}")]
public IActionResult SimpleTypeModel(ConvertibleFromString model) => null;
[HttpPost("form-file")]
public IActionResult FormFileParameter(IFormFile formFile) => null;
[HttpPost("form-file-collection")]
public IActionResult FormFileCollectionParameter(IFormFileCollection formFiles) => null;
[HttpPost("form-file-sequence")]
public IActionResult FormFileSequenceParameter(IFormFile[] formFiles) => null;
[HttpPost]
public IActionResult FromFormParameter([FromForm] string parameter) => null;
[HttpPost]
[Consumes("application/json")]
public IActionResult ActionWithConsumesAttribute([FromForm] string parameter) => null;
}
[ApiController]
[Route("/route1/[controller]/[action]/{id}")]
[Route("/route2/[controller]/[action]/{id?}")]
private class ParameterInController
{
[HttpGet]
public IActionResult ActionWithoutRoute(int id) => null;
[HttpGet("stuff/{status}")]
public IActionResult ActionWithRoute(int id) => null;
[HttpGet("/absolute-route")]
public IActionResult AbsoluteRoute(int id) => null;
[HttpPut]
[HttpPost("stuff/{status}")]
public IActionResult MultipleRoute(int id) => null;
[HttpPut]
[HttpPost("~/stuff/{status}")]
public IActionResult MultipleRouteWithOverride(int id) => null;
}
[ApiController]
private class ParameterBindingNoRoutesOnController
{
[HttpGet("{parameter}")]
public IActionResult SimpleRoute(int parameter) => null;
[HttpGet]
public IActionResult NoRouteTemplate(int id) => null;
[HttpPost("multiple/{id}")]
[HttpPut("multiple/{id}")]
public IActionResult ParameterInMultipleRoutes(int id) => null;
}
private class TestModel { }
[TypeConverter(typeof(ConvertibleFromStringConverter))]
private class ConvertibleFromString { }
private class ConvertibleFromStringConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
=> sourceType == typeof(string);
}
}
}
| 37.360447 | 196 | 0.625571 |
9fe71933a149f99aec3489200c0cb1189fbfb29a | 5,172 | py | Python | sinkhorn_knopp.py | kkahatapitiya/Numpy-OT | f4698580b4e84e5bd4c2fdd828d086ac7f088295 | [
"MIT"
] | 3 | 2021-04-27T17:08:11.000Z | 2021-04-29T15:28:20.000Z | sinkhorn_knopp.py | kumarak93/numpy_ot | f4698580b4e84e5bd4c2fdd828d086ac7f088295 | [
"MIT"
] | null | null | null | sinkhorn_knopp.py | kumarak93/numpy_ot | f4698580b4e84e5bd4c2fdd828d086ac7f088295 | [
"MIT"
] | 1 | 2021-06-03T17:12:04.000Z | 2021-06-03T17:12:04.000Z | import numpy as np
### from https://github.com/rflamary/POT/blob/master/ot/bregman.py ###
def sinkhorn_knopp(a, b, M, reg, numItermax=1000,
stopThr=1e-9, verbose=False, log=False, **kwargs):
r"""
Solve the entropic regularization optimal transport problem and return the OT matrix
The function solves the following optimization problem:
.. math::
\gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma)
s.t. \gamma 1 = a
\gamma^T 1= b
\gamma\geq 0
where :
- M is the (dim_a, dim_b) metric cost matrix
- :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})`
- a and b are source and target weights (histograms, both sum to 1)
The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_
Parameters
----------
a : ndarray, shape (dim_a,)
samples weights in the source domain
b : ndarray, shape (dim_b,) or ndarray, shape (dim_b, n_hists)
samples in the target domain, compute sinkhorn with multiple targets
and fixed M if b is a matrix (return OT loss + dual variables in log)
M : ndarray, shape (dim_a, dim_b)
loss matrix
reg : float
Regularization term >0
numItermax : int, optional
Max number of iterations
stopThr : float, optional
Stop threshol on error (>0)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
Returns
-------
gamma : ndarray, shape (dim_a, dim_b)
Optimal transportation matrix for the given parameters
log : dict
log dictionary return only if log==True in parameters
Examples
--------
>>> import ot
>>> a=[.5, .5]
>>> b=[.5, .5]
>>> M=[[0., 1.], [1., 0.]]
>>> ot.sinkhorn(a, b, M, 1)
array([[0.36552929, 0.13447071],
[0.13447071, 0.36552929]])
References
----------
.. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013
See Also
--------
ot.lp.emd : Unregularized OT
ot.optim.cg : General regularized OT
"""
a = np.asarray(a, dtype=np.float64)
b = np.asarray(b, dtype=np.float64)
M = np.asarray(M, dtype=np.float64)
if len(a) == 0:
a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0]
if len(b) == 0:
b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1]
# init data
dim_a = len(a)
dim_b = len(b)
if len(b.shape) > 1:
n_hists = b.shape[1]
else:
n_hists = 0
if log:
log = {'err': []}
# we assume that no distances are null except those of the diagonal of
# distances
if n_hists:
u = np.ones((dim_a, n_hists)) / dim_a
v = np.ones((dim_b, n_hists)) / dim_b
else:
u = np.ones(dim_a) / dim_a
v = np.ones(dim_b) / dim_b
# print(reg)
# Next 3 lines equivalent to K= np.exp(-M/reg), but faster to compute
K = np.empty(M.shape, dtype=M.dtype)
np.divide(M, -reg, out=K)
np.exp(K, out=K)
# print(np.min(K))
tmp2 = np.empty(b.shape, dtype=M.dtype)
Kp = (1 / (a+ 1e-299)).reshape(-1, 1) * K
cpt = 0
err = 1
while (err > stopThr and cpt < numItermax):
uprev = u
vprev = v
KtransposeU = np.dot(K.T, u)
v = np.divide(b, (KtransposeU+ 1e-299))
u = 1. / (np.dot(Kp, v)+ 1e-299)
if (np.any(KtransposeU == 0)
or np.any(np.isnan(u)) or np.any(np.isnan(v))
or np.any(np.isinf(u)) or np.any(np.isinf(v))):
# we have reached the machine precision
# come back to previous solution and quit loop
print('Warning: numerical errors at iteration', cpt)
u = uprev
v = vprev
break
if cpt % 10 == 0:
# we can speed up the process by checking for the error only all
# the 10th iterations
if n_hists:
np.einsum('ik,ij,jk->jk', u, K, v, out=tmp2)
else:
# compute right marginal tmp2= (diag(u)Kdiag(v))^T1
np.einsum('i,ij,j->j', u, K, v, out=tmp2)
err = np.linalg.norm(tmp2 - b) # violation of marginal
if log:
log['err'].append(err)
if verbose:
if cpt % 200 == 0:
print(
'{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19)
print('{:5d}|{:8e}|'.format(cpt, err))
cpt = cpt + 1
if log:
log['u'] = u
log['v'] = v
if n_hists: # return only loss
res = np.einsum('ik,ij,jk,ij->k', u, K, v, M)
if log:
return res, cpt, log
else:
return res, cpt
else: # return OT matrix
if log:
return u.reshape((-1, 1)) * K * v.reshape((1, -1)), cpt, log
else:
return u.reshape((-1, 1)) * K * v.reshape((1, -1)), cpt
| 32.942675 | 153 | 0.53983 |
3d47160c5a6ea5f9a15effd32adc0b04574bbc9a | 359 | kt | Kotlin | SpringScanSDK/src/main/java/com/springscan/sdk/internal/apis/login/LoginResponse.kt | SpringRole/springscan-android-sdk | 58f9731d210ac697d06425cd0dc68f6306f5c1ba | [
"DOC",
"Apache-2.0"
] | null | null | null | SpringScanSDK/src/main/java/com/springscan/sdk/internal/apis/login/LoginResponse.kt | SpringRole/springscan-android-sdk | 58f9731d210ac697d06425cd0dc68f6306f5c1ba | [
"DOC",
"Apache-2.0"
] | null | null | null | SpringScanSDK/src/main/java/com/springscan/sdk/internal/apis/login/LoginResponse.kt | SpringRole/springscan-android-sdk | 58f9731d210ac697d06425cd0dc68f6306f5c1ba | [
"DOC",
"Apache-2.0"
] | null | null | null | package com.springscan.sdk.internal.apis.login
import com.google.gson.annotations.SerializedName
data class LoginResponse(
@SerializedName("token")
val token: String?,
@SerializedName("userId")
val userID: String?,
@SerializedName("user_name")
val userName: String?,
@SerializedName("company_name")
val companyName: String?
) | 25.642857 | 49 | 0.724234 |
7f615a018cc436f22ac1aa764f6a0b8e98871ea1 | 1,560 | php | PHP | .devilbox/www/htdocs/vendor/phpmyadmin-4.8.4/ajax.php | axelVO/tourComperator | 578e93668fcd49746371e5cf335beb30146ce013 | [
"MIT"
] | 3,946 | 2016-10-11T09:51:29.000Z | 2022-03-31T10:52:27.000Z | .devilbox/www/htdocs/vendor/phpmyadmin-4.8.4/ajax.php | axelVO/tourComperator | 578e93668fcd49746371e5cf335beb30146ce013 | [
"MIT"
] | 626 | 2016-10-24T12:27:49.000Z | 2022-03-31T11:55:09.000Z | .devilbox/www/htdocs/vendor/phpmyadmin-4.8.4/ajax.php | axelVO/tourComperator | 578e93668fcd49746371e5cf335beb30146ce013 | [
"MIT"
] | 720 | 2016-10-24T14:16:11.000Z | 2022-03-31T03:28:54.000Z | <?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Generic AJAX endpoint for getting information about database
*
* @package PhpMyAdmin
*/
use PhpMyAdmin\Response;
use PhpMyAdmin\Util;
use PhpMyAdmin\Core;
$_GET['ajax_request'] = 'true';
require_once 'libraries/common.inc.php';
$response = Response::getInstance();
$response->setAJAX(true);
if (empty($_POST['type'])) {
Core::fatalError(__('Bad type!'));
}
switch ($_POST['type']) {
case 'list-databases':
$response->addJSON('databases', $GLOBALS['dblist']->databases);
break;
case 'list-tables':
Util::checkParameters(array('db'), true);
$response->addJSON('tables', $GLOBALS['dbi']->getTables($_POST['db']));
break;
case 'list-columns':
Util::checkParameters(array('db', 'table'), true);
$response->addJSON('columns', $GLOBALS['dbi']->getColumnNames($_POST['db'], $_POST['table']));
break;
case 'config-get':
Util::checkParameters(array('key'), true);
$response->addJSON('value', $GLOBALS['PMA_Config']->get($_POST['key']));
break;
case 'config-set':
Util::checkParameters(array('key', 'value'), true);
$result = $GLOBALS['PMA_Config']->setUserValue(null, $_POST['key'], json_decode($_POST['value']));
if ($result !== true) {
$response = Response::getInstance();
$response->setRequestStatus(false);
$response->addJSON('message', $result);
}
break;
default:
Core::fatalError(__('Bad type!'));
}
| 30 | 106 | 0.598077 |
daf49751a618cb6881224f8cecd4ad5f99504995 | 19,305 | sql | SQL | schema.sql | txstate-etc/dosgato | ef39777c055ac0bd145ecff05ba027f22555924e | [
"MIT"
] | null | null | null | schema.sql | txstate-etc/dosgato | ef39777c055ac0bd145ecff05ba027f22555924e | [
"MIT"
] | null | null | null | schema.sql | txstate-etc/dosgato | ef39777c055ac0bd145ecff05ba027f22555924e | [
"MIT"
] | null | null | null | -- -----------------------------------------------------
-- Table `users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `users` (
`id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
`login` VARCHAR(255) CHARACTER SET 'ascii' COLLATE 'ascii_general_ci' NOT NULL,
`name` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`lastlogin` DATETIME,
`lastlogout` DATETIME,
`disabledAt` DATETIME,
PRIMARY KEY (`id`),
UNIQUE INDEX `login_UNIQUE` (`login`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `pagetrees`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `pagetrees` (
`id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
`siteId` SMALLINT UNSIGNED NOT NULL,
`type` ENUM('primary', 'sandbox', 'archive') NOT NULL DEFAULT 'sandbox',
`name` VARCHAR(255) NOT NULL,
`createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`promotedAt` DATETIME,
`archivedAt` DATETIME,
`deletedAt` DATETIME,
`deletedBy` MEDIUMINT UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `nameinsite` (`siteId`, `name`),
INDEX `site_idx` (`siteId`, `type`),
CONSTRAINT `deletedBy`
FOREIGN KEY (`deletedBy`)
REFERENCES `users` (`id`),
CONSTRAINT `siteId`
FOREIGN KEY (`siteId`)
REFERENCES `sites` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `sites`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `sites` (
`id` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`primaryPagetreeId` MEDIUMINT UNSIGNED NOT NULL,
`rootAssetFolderId` MEDIUMINT UNSIGNED NOT NULL,
`launchHost` VARCHAR(255) NOT NULL,
`launchPath` VARCHAR(255) NOT NULL DEFAULT '/',
`organizationId` SMALLINT UNSIGNED,
`ownerId` MEDIUMINT UNSIGNED,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_UNIQUE` (`name`),
UNIQUE INDEX `primary_pagetree_id_UNIQUE` (`primaryPagetreeId`),
UNIQUE INDEX `asset_root_id_UNIQUE` (`rootAssetFolderId`),
INDEX `launchUrl` (`launchHost`, `launchPath`),
CONSTRAINT `pagetree`
FOREIGN KEY (`primaryPagetreeId`)
REFERENCES `pagetrees` (`id`),
CONSTRAINT `owner`
FOREIGN KEY (`ownerId`)
REFERENCES `users` (`id`),
CONSTRAINT `organization`
FOREIGN KEY (`organizationId`)
REFERENCES `organizations` (`id`),
CONSTRAINT `rootAssetFolder`
FOREIGN KEY (`rootAssetFolderId`)
REFERENCES `assetfolders` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `organizations`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `organizations` (
`id` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_UNIQUE` (`name`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `sites_managers`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `sites_managers` (
`siteId` SMALLINT UNSIGNED NOT NULL,
`userId` MEDIUMINT UNSIGNED NOT NULL,
PRIMARY KEY (`siteId`,`userId`),
CONSTRAINT `site`
FOREIGN KEY (`siteId`)
REFERENCES `sites` (`id`),
CONSTRAINT `user`
FOREIGN KEY (`userId`)
REFERENCES `users` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `assetfolders`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `assetfolders` (
`id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
`siteId` SMALLINT UNSIGNED NOT NULL COMMENT 'for lookup convenience, not canonical',
`parentId` MEDIUMINT UNSIGNED,
`name` VARCHAR(255) NOT NULL,
`deletedAt` DATETIME,
`deletedBy` MEDIUMINT UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `site`
FOREIGN KEY (`siteId`)
REFERENCES `sites` (`id`),
CONSTRAINT `folder`
FOREIGN KEY (`parentId`)
REFERENCES `assetfolders` (`id`),
CONSTRAINT `deletedBy`
FOREIGN KEY (`deletedBy`)
REFERENCES `users` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `assets`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `assets` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`folderId` MEDIUMINT UNSIGNED NOT NULL,
`path` VARCHAR(255) NOT NULL COMMENT 'does not include name. not canonical, here for fast lookups',
`dataId` CHAR(10) CHARACTER SET 'ascii' COLLATE 'ascii_general_ci' NOT NULL,
`deletedAt` DATETIME,
`deletedBy` MEDIUMINT UNSIGNED,
PRIMARY KEY (`id`),
INDEX `path_idx` (`path`, `name`),
CONSTRAINT `folder`
FOREIGN KEY (`folderId`)
REFERENCES `assetfolders` (`id`),
CONSTRAINT `deletedBy`
FOREIGN KEY (`deletedBy`)
REFERENCES `users` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `groups`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `groups` (
`id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_UNIQUE` (`name`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `roles` (
`id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_UNIQUE` (`name`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `siterules`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `siterules` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`roleId` MEDIUMINT UNSIGNED NOT NULL,
`siteId` SMALLINT UNSIGNED,
`launch` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`rename` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`manageOwners` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`managePagetrees` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`promotePagetree` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`delete` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`undelete` TINYINT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
CONSTRAINT `role`
FOREIGN KEY (`roleId`)
REFERENCES `roles` (`id`),
CONSTRAINT `site`
FOREIGN KEY (`siteId`)
REFERENCES `sites` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `users_groups`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `users_groups` (
`userId` MEDIUMINT UNSIGNED NOT NULL,
`groupId` MEDIUMINT UNSIGNED NOT NULL,
PRIMARY KEY (`userId`, `groupId`),
CONSTRAINT `user`
FOREIGN KEY (`userId`)
REFERENCES `users` (`id`),
CONSTRAINT `group`
FOREIGN KEY (`groupId`)
REFERENCES `groups` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `pages`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `pages` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`pagetreeId` MEDIUMINT UNSIGNED NOT NULL,
`parentId` INT UNSIGNED,
`dataId` CHAR(10) CHARACTER SET 'ascii' COLLATE 'ascii_bin' NOT NULL,
`linkId` CHAR(10) CHARACTER SET 'ascii' COLLATE 'ascii_bin' NOT NULL,
`deletedAt` DATETIME,
`deletedBy` MEDIUMINT UNSIGNED,
PRIMARY KEY (`id`),
UNIQUE INDEX `data_UNIQUE` (`dataId`),
UNIQUE INDEX `linkId_in_pagetree` (`pagetreeId`, `linkId`),
INDEX `linkId_idx` (`linkId`)
CONSTRAINT `pagetree`
FOREIGN KEY (`pagetreeId`)
REFERENCES `pagetrees` (`id`),
CONSTRAINT `parent`
FOREIGN KEY (`parentId`)
REFERENCES `pages` (`id`),
CONSTRAINT `data`
FOREIGN KEY (`dataId`)
REFERENCES `storage` (`id`),
CONSTRAINT `deletedBy`
FOREIGN KEY (`deletedBy`)
REFERENCES `users` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `binaries`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `binaries` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`shasum` CHAR(40) CHARACTER SET 'ascii' COLLATE 'ascii_bin' NOT NULL,
`mime` VARCHAR(255) CHARACTER SET 'ascii' COLLATE 'ascii_bin' NOT NULL,
`meta` JSON NOT NULL,
`bytes` BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `shasum_UNIQUE` (`shasum`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `groups_roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `groups_roles` (
`groupId` MEDIUMINT UNSIGNED NOT NULL,
`roleId` MEDIUMINT UNSIGNED NOT NULL,
PRIMARY KEY (`roleId`, `groupId`),
CONSTRAINT `group`
FOREIGN KEY (`groupId`)
REFERENCES `groups` (`id`),
CONSTRAINT `role`
FOREIGN KEY (`roleId`)
REFERENCES `roles` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `users_roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `users_roles` (
`userId` MEDIUMINT UNSIGNED NOT NULL,
`roleId` MEDIUMINT UNSIGNED NOT NULL,
PRIMARY KEY (`userId`, `roleId`),
CONSTRAINT `user`
FOREIGN KEY (`userId`)
REFERENCES `users` (`id`),
CONSTRAINT `role`
FOREIGN KEY (`roleId`)
REFERENCES `roles` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `resizes`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `resizes` (
`binaryId` INT UNSIGNED NOT NULL,
`originalBinaryId` INT UNSIGNED NOT NULL,
`width` SMALLINT UNSIGNED NOT NULL,
`height` SMALLINT UNSIGNED NOT NULL,
`quality` TINYINT UNSIGNED NOT NULL,
`othersettings` JSON NOT NULL,
PRIMARY KEY (`binaryId`),
INDEX `resize_idx` (`originalBinaryId`, `width`, `height`, `quality`),
CONSTRAINT `binary`
FOREIGN KEY (`binaryId`)
REFERENCES `binaries` (`id`),
CONSTRAINT `originalBinary`
FOREIGN KEY (`originalBinaryId`)
REFERENCES `binaries` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `templates`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `templates` (
`id` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
`key` VARCHAR(255) CHARACTER SET 'ascii' COLLATE 'ascii_bin' NOT NULL,
`name` VARCHAR(255) NOT NULL,
`type` ENUM('component', 'page', 'data') NOT NULL,
`deleted` TINYINT UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_UNIQUE` (`name`),
UNIQUE INDEX `key_UNIQUE` (`key`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `sites_templates`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `sites_templates` (
`siteId` SMALLINT UNSIGNED NOT NULL,
`templateId` SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (`siteId`, `templateId`),
CONSTRAINT `site`
FOREIGN KEY (`siteId`)
REFERENCES `sites` (`id`),
CONSTRAINT `template`
FOREIGN KEY (`templateId`)
REFERENCES `templates` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `pagerules`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `pagerules` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`roleId` MEDIUMINT UNSIGNED NOT NULL,
`siteId` SMALLINT UNSIGNED,
`pagetreeId` MEDIUMINT UNSIGNED,
`path` VARCHAR(255) NOT NULL DEFAULT '/',
`mode` ENUM('self', 'sub', 'selfsub') NOT NULL DEFAULT 'selfsub',
`viewlatest` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`create` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`update` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`move` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`publish` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`unpublish` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`delete` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`undelete` TINYINT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
INDEX `path` (`path`),
CONSTRAINT `role`
FOREIGN KEY (`roleId`)
REFERENCES `roles` (`id`),
CONSTRAINT `pagetree`
FOREIGN KEY (`pagetreeId`)
REFERENCES `pagetrees` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `assetrules`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `assetrules` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`roleId` MEDIUMINT UNSIGNED NOT NULL,
`siteId` SMALLINT UNSIGNED,
`path` VARCHAR(255) NOT NULL DEFAULT '/',
`mode` ENUM('self', 'sub', 'selfsub') NOT NULL DEFAULT 'selfsub',
`create` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`update` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`move` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`delete` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`undelete` TINYINT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
INDEX `path` (`path`),
CONSTRAINT `siteId`
FOREIGN KEY (`siteId`)
REFERENCES `sites` (`id`),
CONSTRAINT `roleId`
FOREIGN KEY (`roleId`)
REFERENCES `roles` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `pagetrees_templates`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `pagetrees_templates` (
`pagetreeId` MEDIUMINT UNSIGNED NOT NULL,
`templateId` SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (`pagetreeId`, `templateId`),
CONSTRAINT `pagetree`
FOREIGN KEY (`pagetreeId`)
REFERENCES `pagetrees` (`id`),
CONSTRAINT `template`
FOREIGN KEY (`templateId`)
REFERENCES `templates` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `datafolders`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `datafolders` (
`id` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`siteId` SMALLINT UNSIGNED,
`templateId` SMALLINT UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `siteId`
FOREIGN KEY (`siteId`)
REFERENCES `sites` (`id`),
CONSTRAINT `templateId`
FOREIGN KEY (`templateId`)
REFERENCES `templates` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `data`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `data` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`dataId` CHAR(10) CHARACTER SET 'ascii' COLLATE 'ascii_bin' NOT NULL,
`siteId` SMALLINT UNSIGNED,
`folderId` MEDIUMINT UNSIGNED,
`deletedAt` DATETIME,
`deletedBy` MEDIUMINT UNSIGNED,
PRIMARY KEY (`id`),
UNIQUE INDEX `data_UNIQUE` (`dataId`),
CONSTRAINT `deletedBy`
FOREIGN KEY (`deletedBy`)
REFERENCES `users` (`id`),
CONSTRAINT `data`
FOREIGN KEY (`dataId`)
REFERENCES `storage` (`id`),
CONSTRAINT `siteId`
FOREIGN KEY (`siteId`)
REFERENCES `sites` (`id`),
CONSTRAINT `folderId`
FOREIGN KEY (`folderId`)
REFERENCES `datafolders` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `datarules`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `datarules` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`roleId` MEDIUMINT UNSIGNED NOT NULL,
`siteId` SMALLINT UNSIGNED,
`templateId` SMALLINT UNSIGNED,
`path` VARCHAR(255) NOT NULL DEFAULT '/',
`viewlatest` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`create` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`update` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`publish` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`unpublish` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`delete` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`undelete` TINYINT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (`id`),
CONSTRAINT `role`
FOREIGN KEY (`roleId`)
REFERENCES `roles` (`id`),
CONSTRAINT `site`
FOREIGN KEY (`siteId`)
REFERENCES `sites` (`id`),
CONSTRAINT `template`
FOREIGN KEY (`templateId`)
REFERENCES `templates` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `mutationlog`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mutationlog` (
`createdAt` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
`userId` MEDIUMINT UNSIGNED NOT NULL,
`mutation` VARCHAR(255) NOT NULL,
`query` TEXT NOT NULL,
`variables` JSON NOT NULL,
INDEX `createdAt_idx` (`createdAt`),
INDEX `mutation_idx` (`mutation`),
CONSTRAINT `user`
FOREIGN KEY (`userId`)
REFERENCES `users` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `globalrules`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `globalrules` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`roleId` MEDIUMINT UNSIGNED NOT NULL,
`manageUsers` TINYINT UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `roleId`
FOREIGN KEY (`roleId`)
REFERENCES `roles` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
-- -----------------------------------------------------
-- Table `downloads`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `downloads` (
`binaryId` INT UNSIGNED NOT NULL,
`year` SMALLINT UNSIGNED NOT NULL,
`month` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`day` TINYINT UNSIGNED NOT NULL DEFAULT 0,
`downloads` INT UNSIGNED NOT NULL DEFAULT 0,
PRIMARY KEY (`binaryId`, `year`, `month`, `day`),
CONSTRAINT `binaryId`
FOREIGN KEY (`binaryId`)
REFERENCES `binaries` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8mb4
DEFAULT COLLATE = utf8mb4_general_ci;
| 33.284483 | 101 | 0.596633 |
e2701fdd5d2b0e319751fc97a7dbc7f64e849b48 | 4,228 | js | JavaScript | src/Customization.js | M-ZubairAhmed/FabricOn | 459fe14167278be51ce6284cee06fc32a5367aad | [
"MIT"
] | null | null | null | src/Customization.js | M-ZubairAhmed/FabricOn | 459fe14167278be51ce6284cee06fc32a5367aad | [
"MIT"
] | null | null | null | src/Customization.js | M-ZubairAhmed/FabricOn | 459fe14167278be51ce6284cee06fc32a5367aad | [
"MIT"
] | null | null | null | import React from 'react';
import {
Col,
Button,
Panel,
FormGroup,
FormControl,
Image,
Modal,
} from 'react-bootstrap';
import cloudinary from 'cloudinary';
import { cloudinaryConfig } from './secret';
import Canva from './Canva';
import { stickerDesigns } from './mock';
let imageCustomized = '';
export default class Customization extends React.Component {
constructor(props) {
super(props);
this.state = {
customImageURL: '',
customText: '',
showModal: false,
};
cloudinary.config(cloudinaryConfig);
}
getPaintedCanvas = (canvas, dx) => {
imageCustomized = canvas.toDataURL('image/png', 1.0);
};
saveCustomizedProduct = createdImage => {
const uniqueIdPasses =
this.props.uniqueId === '' || this.props.uniqueId === null
? new Date()
: this.props.uniqueId;
if (createdImage !== '') {
cloudinary.uploader.upload(createdImage, result => {}, {
public_id: uniqueIdPasses,
});
this.setState({
showModal: true,
});
}
};
render() {
const stickerDesignStyle = {
width: '50px',
height: '50px',
cursor: 'pointer',
};
const editorStyles = {
marginTop: '4rem',
};
return (
<div style={editorStyles}>
<Col lg={8}>
<Canva
backgroundImage={this.props.backgroundImage}
productType={this.props.productType}
customText={this.state.customText}
customImageURL={this.state.customImageURL}
fontStyle={this.props.fontStyle}
getPaintedCanvas={this.getPaintedCanvas}
/>
</Col>
<Col lg={4}>
<Panel>
<h4>Customize your Product</h4>
<Panel>
<h5>Select decals</h5>
{stickerDesigns.map((stickerDesign, index) => {
return (
<Image
className="stickerDesign"
key={index}
circle
alt="171x180"
src={stickerDesign}
style={stickerDesignStyle}
onClick={() =>
this.setState({ customImageURL: stickerDesign })
}
/>
);
})}
</Panel>
<Panel>
<CustomInput
inputParameter="Add customized text:"
placeholderText="Add text"
onChangeHandler={e =>
this.setState({
customText: e.target.value,
disableButtons:
this.props.customText === '' || e.target.value === '',
})
}
/>
<h5>Font Weight</h5>
<Button
disabled={this.props.disableButtons}
onClick={this.props.onClickBoldButton}
>
{
this.props.fontStyleArray[
this.props.fontStyleIndex !== 2
? this.props.fontStyleIndex + 1
: 0
]
}
</Button>
</Panel>
<Button block>Cancel</Button>
<Button
block
bsStyle="success"
onClick={() => this.saveCustomizedProduct(imageCustomized)}
>
Confirm Changes
</Button>
</Panel>
</Col>
<Modal show={this.state.showModal}>
<Modal.Header closeButton>
<Modal.Title>Customization Successfull</Modal.Title>
</Modal.Header>
<Modal.Body>
You may now add the your customized product to cart
</Modal.Body>
</Modal>
</div>
);
}
}
const CustomInput = ({ inputParameter, onChangeHandler, placeholderText }) => {
return (
<form>
<div id="container" />
<FormGroup controlId="formBasicText">
<h5>{inputParameter}</h5>
<FormControl
type="text"
placeholder={placeholderText}
onChange={onChangeHandler}
/>
</FormGroup>
</form>
);
};
| 27.454545 | 79 | 0.487938 |
a9687195ed2fe70725b9e1d1f214ee30d7ac77e3 | 1,133 | sql | SQL | proj/gatilho3_verifica.sql | mbcsm/BDAD | 6026f1a7ea935488046e89f69e0d4f9e4d267b46 | [
"MIT"
] | null | null | null | proj/gatilho3_verifica.sql | mbcsm/BDAD | 6026f1a7ea935488046e89f69e0d4f9e4d267b46 | [
"MIT"
] | null | null | null | proj/gatilho3_verifica.sql | mbcsm/BDAD | 6026f1a7ea935488046e89f69e0d4f9e4d267b46 | [
"MIT"
] | 1 | 2021-10-05T15:10:05.000Z | 2021-10-05T15:10:05.000Z | PRAGMA foreign_keys=ON;
SELECT * FROM JOGO;
INSERT INTO CLUBE (Nome,Regiao) VALUES ('Porto','Porto');
INSERT INTO CLUBE (Nome,Regiao) VALUES ('Benfica','Lisboa');
INSERT INTO CAMPO (idClube, Localidade, Relvado) VALUES (1, 'Porto', 'Natural');
INSERT INTO Escalao (FaixaEtaria, Sexo) VALUES ('18-35', 'M');
INSERT INTO EQUIPA (Nome, idClube, idEscalao) VALUES ('Futebol Clube do Porto', 1, 5);--1
INSERT INTO EQUIPA (Nome, idClube, idEscalao) VALUES ('Sport Lisboa e Benfica', 2, 5);--3
INSERT INTO JOGADOR (idPessoa, idEquipa) VALUES (1, 1);
INSERT INTO LIGA (Nome, Regiao) VALUES ('Primeira Liga', 'Nacional');
INSERT INTO JOGO (Data, GolosCasa, GolosFora, idEquipaVisitante, idEquipaVisitada, idLiga, idCampo) VALUES ('2018-5-12 20:00:00',0,0, 1, 3, 1, 2);
INSERT INTO EVENTO (idJogo, idJogador, Minuto) VALUES (1, 1, 40);
INSERT INTO EVENTO (idJogo, idJogador, Minuto) VALUES (1, 1, 40);
INSERT INTO CARTAO (Cor, Razao, idEvento) VALUES ('Vermelho', 'Falta', 1);
--trigger triggered
INSERT INTO CARTAO (Cor, Razao, idEvento) VALUES ('Vermelho', 'Falta', 2);
----
SELECT * FROM JOGO;
| 34.333333 | 147 | 0.683142 |
76fab896fd6f206c6a174487419b0e12e36ef65d | 524 | dart | Dart | tests/language_2/mixin/mixin_test.dart | omerlevran46/sdk | b1955d63ad678b651b09db3dd286136c4463f36b | [
"BSD-3-Clause"
] | 8,969 | 2015-05-16T16:49:24.000Z | 2022-03-31T19:54:40.000Z | tests/language_2/mixin/mixin_test.dart | omerlevran46/sdk | b1955d63ad678b651b09db3dd286136c4463f36b | [
"BSD-3-Clause"
] | 30,202 | 2015-05-17T02:27:45.000Z | 2022-03-31T22:54:46.000Z | tests/language_2/mixin/mixin_test.dart | omerlevran46/sdk | b1955d63ad678b651b09db3dd286136c4463f36b | [
"BSD-3-Clause"
] | 1,619 | 2015-05-16T21:36:42.000Z | 2022-03-29T20:36:59.000Z | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// @dart = 2.9
import "package:expect/expect.dart";
class M1 {
foo() => 42;
}
class M2 = Object with M1;
class S {}
class C = S with M2;
main() {
var c = new C();
Expect.isTrue(c is S);
Expect.isTrue(c is M1);
Expect.isTrue(c is M2);
Expect.isTrue(c is C);
Expect.equals(42, c.foo());
}
| 19.407407 | 77 | 0.65458 |
43558f9ef81fd1eec600acae8c78e0328f437fe9 | 471 | tsx | TypeScript | client/pages/orders/[id].tsx | NightClover-code/modern-ecommerce | 4202c66eb034d06d99db2461c707034338ed2d5f | [
"MIT"
] | null | null | null | client/pages/orders/[id].tsx | NightClover-code/modern-ecommerce | 4202c66eb034d06d99db2461c707034338ed2d5f | [
"MIT"
] | null | null | null | client/pages/orders/[id].tsx | NightClover-code/modern-ecommerce | 4202c66eb034d06d99db2461c707034338ed2d5f | [
"MIT"
] | null | null | null | import { NextPage } from 'next';
import { useRouter } from 'next/router';
import Order from '../../components/Order';
import SEO from '../../components/SEO';
import { homeConfig } from '../../utils';
const OrderPage: NextPage = () => {
const router = useRouter();
const { id } = router.query;
return (
<>
<SEO {...homeConfig} />
<main className="wrapper py-5">
<Order pageId={id} />
</main>
</>
);
};
export default OrderPage;
| 22.428571 | 43 | 0.579618 |
a11fe996927e4778a4f962b4ca2376994158ad7f | 1,507 | ts | TypeScript | src/commands/Images/meme.ts | Skillz4Killz/Bot | 860648aa65250b1e8488ceb5a78af0e6fa79d9dc | [
"Apache-2.0"
] | 2 | 2021-08-22T13:29:46.000Z | 2022-02-12T04:45:11.000Z | src/commands/Images/meme.ts | Skillz4Killz/Bot | 860648aa65250b1e8488ceb5a78af0e6fa79d9dc | [
"Apache-2.0"
] | null | null | null | src/commands/Images/meme.ts | Skillz4Killz/Bot | 860648aa65250b1e8488ceb5a78af0e6fa79d9dc | [
"Apache-2.0"
] | 3 | 2020-11-13T14:26:16.000Z | 2021-09-19T12:12:12.000Z | import { Command, CommandOptions } from "@sapphire/framework";
import { Message, TextChannel } from "discord.js";
import { randomSubredditItem } from "@utils/util";
import { ApplyOptions } from "@sapphire/decorators";
import { PreConditions } from "@lib/types/Types";
@ApplyOptions<CommandOptions>({
description: "commands/images:meme.description",
detailedDescription: "noDetailedDescription",
preconditions: [PreConditions.Permissions]
})
export class PenguCommand extends Command {
public subReddits = ["AdviceAnimals", "MemeEconomy", "ComedyCemetery", "memes", "dankmemes", "PrequelMemes", "terriblefacebookmemes", "PewdiepieSubmissions", "funny", "wholesomememes", "fffffffuuuuuuuuuuuu", "BikiniBottomTwitter", "2meirl4meirl", "DeepFriedMemes", "surrealmemes", "firstworldanarchists"];
public async run(message: Message) {
const res = await randomSubredditItem(this.subReddits[Math.floor(Math.random() * this.subReddits.length)], "hot");
if (!res || !res.data) return message.sendTranslated("basicError");
if (res.data.over_18 && !(message.channel as TextChannel).nsfw) return message.sendTranslated("commands/images:meme.nsfwPost");
const completeResponse = [
`**${await message.fetchLanguageKey("commands/images:meme.title")}**: ${res.data.title}`,
`**${await message.fetchLanguageKey("commands/images:meme.link")}**: ${res.data.url}`
];
return message.channel.send(completeResponse.join("\n"));
}
}
| 53.821429 | 309 | 0.709356 |
9a4cff5d6c2c747dbde1892845cd9c252d3994fe | 1,522 | swift | Swift | boostify-client/boostify-client/View Controllers/WebModalViewController.swift | srowhani/boostify | 7da2aae0ce393aac673da17f415a31373a06ed5f | [
"MIT"
] | 5 | 2018-06-20T11:15:32.000Z | 2020-06-15T17:05:18.000Z | boostify-client/boostify-client/View Controllers/WebModalViewController.swift | srowhani/boostify | 7da2aae0ce393aac673da17f415a31373a06ed5f | [
"MIT"
] | 2 | 2018-06-17T18:44:30.000Z | 2018-08-21T20:04:57.000Z | boostify-client/boostify-client/View Controllers/WebModalViewController.swift | srowhani/boostify | 7da2aae0ce393aac673da17f415a31373a06ed5f | [
"MIT"
] | 1 | 2018-06-18T18:20:53.000Z | 2018-06-18T18:20:53.000Z | //
// WebModalViewController.swift
// boostify-client
//
// Created by Mat Schmid on 2018-06-17.
// Copyright © 2018 Mat Schmid. All rights reserved.
//
import UIKit
import WebKit
protocol WebModalDelegate: class {
func didReceiveInstagramAccessToken(token: String)
}
class WebModalViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var webView: WKWebView!
weak var delegate: WebModalDelegate?
override func viewDidLoad() {
super.viewDidLoad()
setNeedsStatusBarAppearanceUpdate()
webView.uiDelegate = self
webView.navigationDelegate = self
loadInstagramAuth()
}
func loadInstagramAuth() {
let authURL = InstagramFetcher.generateAuthURL()
let urlRequest = URLRequest(url: URL(string: authURL)!)
webView.load(urlRequest)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@IBAction func cancelButtonTapped(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
guard let url = webView.url?.absoluteString else { return }
if url.contains("matschmid.me") {
if let range = url.range(of: "#access_token=") {
let accessToken = url[range.upperBound...]
delegate?.didReceiveInstagramAccessToken(token: String(accessToken))
dismiss(animated: true, completion: nil)
}
}
}
}
| 26.241379 | 113 | 0.747043 |
e27f215f0144f327680725dc7ebf5012f5638a05 | 3,464 | py | Python | logic2_analyzers/PCA9571/pd.py | martonmiklos/sigrokdecoders_to_logic2_analyzers | 9dd9b9a610c17e6ae525829c9112d11a80d016e7 | [
"MIT"
] | 5 | 2020-04-15T20:45:06.000Z | 2020-05-31T02:45:21.000Z | logic2_analyzers/PCA9571/pd.py | martonmiklos/sigrokdecoders_to_logic2_analyzers | 9dd9b9a610c17e6ae525829c9112d11a80d016e7 | [
"MIT"
] | 1 | 2020-07-15T09:23:05.000Z | 2020-07-15T10:04:48.000Z | logic2_analyzers/PCA9571/pd.py | martonmiklos/sigrokdecoders_to_logic2_analyzers | 9dd9b9a610c17e6ae525829c9112d11a80d016e7 | [
"MIT"
] | 1 | 2020-04-20T18:49:36.000Z | 2020-04-20T18:49:36.000Z | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2019 Mickael Bosch <[email protected]>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see <http://www.gnu.org/licenses/>.
##
import sigrokdecode as srd
NUM_OUTPUT_CHANNELS = 8
# TODO: Other I²C functions: general call / reset address, device ID address.
class Decoder(srd.Decoder):
api_version = 3
id = 'pca9571'
name = 'PCA9571'
longname = 'NXP PCA9571'
desc = 'NXP PCA9571 8-bit I²C output expander.'
license = 'gplv2+'
inputs = ['i2c']
outputs = []
tags = ['Embedded/industrial', 'IC']
annotations = (
('register', 'Register type'),
('value', 'Register value'),
('warning', 'Warning'),
)
annotation_rows = (
('regs', 'Registers', (0, 1)),
('warnings', 'Warnings', (2,)),
)
def __init__(self):
self.reset()
def reset(self):
self.state = 'IDLE'
self.last_write = 0xFF # Chip port default state is high.
def start(self):
self.out_ann = self.register(srd.OUTPUT_ANN)
def putx(self, data):
self.put(self.ss, self.es, self.out_ann, data)
def handle_io(self, b):
if self.state == 'READ DATA':
operation = ['Outputs read', 'R']
if b != self.last_write:
self.putx([2, ['Warning: read value and last write value '
'(%02X) are different' % self.last_write]])
else:
operation = ['Outputs set', 'W']
self.last_write = b
self.putx([1, [operation[0] + ': %02X' % b,
operation[1] + ': %02X' % b]])
def check_correct_chip(self, addr):
if addr != 0x25:
self.putx([2, ['Warning: I²C slave 0x%02X not a PCA9571 '
'compatible chip.' % addr]])
return False
return True
def decode(self, ss, es, data):
cmd, databyte = data
self.ss, self.es = ss, es
# State machine.
if cmd in ('ACK', 'BITS'): # Discard 'ACK' and 'BITS'.
pass
elif cmd in ('START', 'START REPEAT'): # Start a communication.
self.state = 'GET SLAVE ADDR'
elif cmd in ('NACK', 'STOP'): # Reset the state machine.
self.state = 'IDLE'
elif cmd in ('ADDRESS READ', 'ADDRESS WRITE'):
if ((self.state == 'GET SLAVE ADDR') and
self.check_correct_chip(databyte)):
if cmd == 'ADDRESS READ':
self.state = 'READ DATA'
else:
self.state = 'WRITE DATA'
else:
self.state = 'IDLE'
elif cmd in ('DATA READ', 'DATA WRITE'):
if self.state in ('READ DATA', 'WRITE DATA'):
self.handle_io(databyte)
else:
self.state = 'IDLE'
| 33.631068 | 77 | 0.560335 |
237f3b6e5178258696da01910b1c18d511d4da60 | 822 | js | JavaScript | app/api/v1/domain/county.js | 5calls/civilservices-api | fdcf2e2e7ff04b0815036d32e355666ab53d66d8 | [
"MIT"
] | 51 | 2016-12-25T02:04:45.000Z | 2022-01-11T02:41:54.000Z | app/api/v1/domain/county.js | CivilServiceUSA/api | ead7da0d0971cc248f2784514f91442cab48a105 | [
"MIT"
] | 45 | 2017-01-08T00:07:48.000Z | 2020-07-21T07:02:27.000Z | app/api/v1/domain/county.js | 5calls/civilservices-api | fdcf2e2e7ff04b0815036d32e355666ab53d66d8 | [
"MIT"
] | 13 | 2017-03-07T16:25:42.000Z | 2021-03-29T19:51:40.000Z | /**
* @module domain/county
* @version 1.0.0
* @author Peter Schmalfeldt <[email protected]>
*/
var _ = require('lodash');
/**
* Geolocation
* @type {object}
*/
module.exports = {
/**
* Prepare For API Output
* @param {object} data - Data to be processed for API Output
* @return {object}
*/
prepareForAPIOutput: function(data) {
var fields = [
'fips',
'state_name',
'state_code',
'name'
];
return _.pick(data._source, fields);
},
/**
* Prepare For Elastic Search
* @param {object} data - Data to be Processed for Elastic Search
* @return {object}
*/
prepareForElasticSearch: function(data) {
return {
fips: data.fips,
state_name: data.state_name,
state_code: data.state_code,
name: data.name
};
}
};
| 18.681818 | 67 | 0.594891 |
20dcba74bf2e8503fd50436b2fd50dcb78e910ef | 2,632 | py | Python | app/utils/analyze.py | codingjerk/ztd.blunders-web | 38d4c1049dc3d0bd0b4294ffa419d25cbfbf2b83 | [
"MIT"
] | null | null | null | app/utils/analyze.py | codingjerk/ztd.blunders-web | 38d4c1049dc3d0bd0b4294ffa419d25cbfbf2b83 | [
"MIT"
] | null | null | null | app/utils/analyze.py | codingjerk/ztd.blunders-web | 38d4c1049dc3d0bd0b4294ffa419d25cbfbf2b83 | [
"MIT"
] | null | null | null | import chess
import chess.uci
class Engine:
def __init__(self, path):
self.engine = chess.uci.popen_engine(path)
self.engine.uci()
self.engine.isready()
self.handler = chess.uci.InfoHandler()
self.engine.info_handlers.append(self.handler)
self.board = chess.Board()
if not self.engine.is_alive():
raise Exception("Engine failed to start")
def __enter__(self):
return self
def new(self):
self.engine.ucinewgame()
self.engine.isready()
def set(self, fen):
self.board = chess.Board(fen)
self.engine.position(self.board)
self.engine.isready()
def is_game_over(self):
return self.board.is_game_over()
def __cloneScore(self, score):
return { "cp": score.cp, "mate": score.mate }
def __pvToStr(self, fen, line):
board = chess.Board(fen)
result = []
for move in line:
movestr = board.san(move)
result.append(movestr)
board.push(move)
return result
def __filterMove(self, index):
pv = self.handler.info['pv']
score = self.handler.info['score']
if pv == {} or score == {}:
return None
if index not in pv or index not in score:
return None
lineStr = self.__pvToStr(self.board.fen(), pv[index])
scoreStr = self.__cloneScore(score[index])
return {
'line': lineStr,
'score': scoreStr
}
def think(self, timeToThink, move = None):
searchmoves = None
self.engine.isready()
if move is not None:
searchmoves = [self.board.parse_san(move)]
promise = self.engine.go(movetime=timeToThink, searchmoves=searchmoves, async_callback=True)
promise.result()
result = self.__filterMove(1)
if result is None:
raise Exception('Engine failed to analyze blunder')
return result
def moveLine(self, line):
for move in line:
move_int = self.board.parse_san(move)
if move_int not in self.board.legal_moves:
raise Exception("Illegal move in this position")
self.board.push(move_int)
self.engine.position(self.board)
self.engine.isready()
def moveOne(self, move):
self.moveLine([move])
def unmove(self):
self.board.pop()
self.engine.position(self.board)
self.engine.isready()
def __enter__(self):
return self
def __exit__(self, exception, _1, _2):
self.engine.quit()
| 26.059406 | 100 | 0.583207 |
b744560f65f71bfb7ba61c6f1aefb2db38f6752f | 4,586 | dart | Dart | lib/utils/widgets/notification.dart | higorlapa/pangolin_desktop | e02a9a502bd84cab49e63792439bdffb19cdfe9c | [
"Apache-2.0"
] | 3 | 2020-07-16T19:14:19.000Z | 2020-07-22T16:14:42.000Z | lib/utils/widgets/notification.dart | lohnn/pangolin-desktop | 244a86f1af9a6036eb69fe8c80cc6f2341d41a05 | [
"Apache-2.0"
] | 1 | 2021-03-18T20:05:42.000Z | 2021-03-18T20:05:42.000Z | lib/utils/widgets/notification.dart | lohnn/pangolin-desktop | 244a86f1af9a6036eb69fe8c80cc6f2341d41a05 | [
"Apache-2.0"
] | 1 | 2020-07-22T10:14:22.000Z | 2020-07-22T10:14:22.000Z | /*
Copyright 2019 The dahliaOS Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import 'package:Pangolin/main.dart';
import 'package:flutter/material.dart';
class DahliaNotification {
static showNotification(
String title, String subtitle, IconData icon, Function onClick) async {
OverlayEntry _overlayEntry;
bool _hover = false;
_overlayEntry = OverlayEntry(
builder: (context) => Positioned(
child: Center(
child: SizedBox(
width: 350,
child: GestureDetector(
onTap: () {
onClick;
_overlayEntry.remove();
},
child: MouseRegion(
onHover: (event) {
_hover = true;
},
child: Dismissible(
key: ValueKey(_overlayEntry),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5)),
elevation: 1.5,
child: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Icon(
icon,
size: 15,
),
SizedBox(
width: 10,
),
Text(title,
style: Theme.of(context)
.textTheme
.headline6
.copyWith(fontSize: 17)),
],
),
),
IconButton(
onPressed: () {
_overlayEntry.remove();
},
icon: Icon(
Icons.close,
size: 20,
),
)
],
),
Padding(
padding: const EdgeInsets.only(left: 8.0),
child: Text(subtitle),
),
SizedBox(
height: 5,
),
],
),
),
),
),
),
),
),
),
),
bottom: 50,
right: 5,
));
Pangolin.overlayState.insert(_overlayEntry);
await Future.delayed(Duration(seconds: 5));
if (_hover == false) {
_overlayEntry.remove();
}
}
}
| 40.584071 | 78 | 0.328173 |
a36cdb5c03373ee0381eaff2b268f003bd9fa317 | 435 | ts | TypeScript | packages/nger-provider-typescript/lib/index.ts | meepobrother/nger | 2642f8f707dea1fa4ea13909695eb64efcd76a4e | [
"MIT"
] | 61 | 2019-04-22T13:40:45.000Z | 2021-04-11T15:08:55.000Z | packages/nger-provider-typescript/lib/index.ts | meepobrother/nger | 2642f8f707dea1fa4ea13909695eb64efcd76a4e | [
"MIT"
] | 2 | 2019-04-24T13:29:00.000Z | 2021-04-07T09:49:20.000Z | packages/nger-provider-typescript/lib/index.ts | meepobrother/nger | 2642f8f707dea1fa4ea13909695eb64efcd76a4e | [
"MIT"
] | 16 | 2019-04-23T11:19:09.000Z | 2020-08-19T13:24:52.000Z | import { NgerCompilerTypescript } from 'nger-compiler';
import { StaticProvider } from 'nger-di';
import { NgerBabel } from './babel'
const staticProvider: StaticProvider[] = [{
provide: NgerBabel,
useClass: NgerBabel,
deps: [NgerCompilerTypescript]
}, {
provide: NgerCompilerTypescript,
useClass: NgerCompilerTypescript,
deps: []
}];
export default staticProvider;
export { NgerBabel, NgerCompilerTypescript }
| 29 | 55 | 0.728736 |
d495cd39f8ffa9d98c3883e989974ac23c3d3f38 | 1,769 | lua | Lua | entities.lua | sky-makes/cartridge-tilt | ecd382a7011cb331c3d12d5a69426053e31278d6 | [
"MIT"
] | 1 | 2020-08-17T19:13:23.000Z | 2020-08-17T19:13:23.000Z | entities.lua | WillWare/cartridge-tilt | ecd382a7011cb331c3d12d5a69426053e31278d6 | [
"MIT"
] | null | null | null | entities.lua | WillWare/cartridge-tilt | ecd382a7011cb331c3d12d5a69426053e31278d6 | [
"MIT"
] | null | null | null | --[[
entities.lua
Provides a list of constants identifying various entities in Mari0; the names were
lifted directly from 1.6 and indexed by hand.
]]
REMOVE = 1
MUSHROOM = 2
ONEUP = 3
STAR = 4
MANYCOINS = 5
GOOMBA = 6
KOOPA = 7
SPAWN = 8
GOOMBAHALF = 9
KOOPAHALF = 10
FLAG = 11
KOOPARED = 12
KOOPAREDHALF = 13
VINE = 14
HAMMERBRO = 15
CHEEPRED = 16
CHEEPWHITE = 17
PLATFORMUP = 18
PLATFORMRIGHT = 19
BOX = 20
PIPE = 21
LAKITO = 22
MAZESTART = 23
MAZEEND = 24
MAZEGATE = 25
EMANCEHOR = 26
EMANCEVER = 27
DOORVER = 28
DOORHOR = 29
WALLINDICATOR = 30
PIPESPAWN = 31
PLATFORMFALL = 32
BULLETBILLSTART = 33
BULLETBILLEND = 34
DRAIN = 35
LIGHTBRIDGERIGHT = 36
LIGHTBRIDGELEFT = 37
LIGHTBRIDGEDOWN = 38
LIGHTBRIDGEUP = 39
BUTTON = 40
PLATFORMSPAWNERDOWN = 41
PLATFORMSPAWNERUP = 42
GROUNDLIGHTVER = 43
GROUNDLIGHTHOR = 44
GROUNDLIGHTUPRIGHT = 45
GROUNDLIGHTRIGHTDOWN = 46
GROUNDLIGHTDOWNLEFT = 47
GROUNDLIGHTLEFTUP = 48
FAITHPLATEUP = 49
FAITHPLATERIGHT = 50
FAITHPLATELEFT = 51
LASERRIGHT = 52
LASERDOWN = 53
LASERLEFT = 54
LASERUP = 55
LASERDETECTORRIGHT = 56
LASERDETECTORDOWN = 57
LASERDETECTORLEFT = 58
LASERDETECTORUP = 59
BULLETBILL = 60
BLUEGELDOWN = 61
BLUEGELRIGHT = 62
BLUEGELLEFT = 63
ORANGEGELDOWN = 64
ORANGEGELRIGHT = 65
ORANGEGELLEFT = 66
BOXTUBE = 67
PUSHBUTTONLEFT = 68
PUSHBUTTONRIGHT = 69
PLANT = 70
WHITEGELDOWN = 71
WHITEGELRIGHT = 72
WHITEGELLEFT = 73
TIMER = 74
BEETLE = 75
BEETLEHALF = 76
KOOPAREDFLYING = 77
KOOPAFLYING = 78
CASTLEFIRECCW = 79
SEESAW = 80
WARPPIPE = 81
CASTLEFIRECW = 82
LAKITOEND = 83
NOTGATE = 84
GELTOP = 85
GELLEFT = 86
GELBOTTOM = 87
GELRIGHT = 88
FIRESTART = 89
BOWSER = 90
AXE = 91
PLATFORMBONUS = 92
SPRING = 93
SQUID = 94
FLYINGFISHSTART = 95
FLYINGFISHEND = 96
UPFIRE = 97
SPIKEY = 98
SPIKEYHALF = 99
CHECKPOINT = 100
| 16.37963 | 83 | 0.751837 |
60396fc29e74a4736d020d6588410af51c43ab6a | 65 | dart | Dart | lib/settings/settings.dart | githubmonkey/sliderpuzzle_flutter | da7271bc6bb66c6662baed224278ff59664e3ce5 | [
"MIT"
] | null | null | null | lib/settings/settings.dart | githubmonkey/sliderpuzzle_flutter | da7271bc6bb66c6662baed224278ff59664e3ce5 | [
"MIT"
] | 1 | 2022-03-30T16:05:47.000Z | 2022-03-30T16:05:47.000Z | lib/settings/settings.dart | githubmonkey/sliderpuzzle_flutter | da7271bc6bb66c6662baed224278ff59664e3ce5 | [
"MIT"
] | null | null | null | export 'bloc/settings_bloc.dart';
export 'widgets/widgets.dart';
| 21.666667 | 33 | 0.784615 |
e0380f5fac018566086d0f07f438aefbf23f2f6e | 4,837 | h | C | scanner/rdesktop-fork-bd6aa6acddf0ba640a49834807872f4cc0d0a773/rdesktop.h | wisdark/CVE-2019-0708 | b86362fe1e1797aa0a426f65cd5d0af8b07191bc | [
"Apache-2.0"
] | 1,253 | 2019-05-22T00:49:08.000Z | 2021-12-01T08:40:31.000Z | rdesktop-fork-bd6aa6acddf0ba640a49834807872f4cc0d0a773/rdesktop.h | ilyaglow/CVE-2019-0708 | de63d738543f208a4818659ff2ab8c72d723e73f | [
"Apache-2.0"
] | 19 | 2019-05-22T02:43:16.000Z | 2021-02-11T10:43:53.000Z | rdesktop-fork-bd6aa6acddf0ba640a49834807872f4cc0d0a773/rdesktop.h | ilyaglow/CVE-2019-0708 | de63d738543f208a4818659ff2ab8c72d723e73f | [
"Apache-2.0"
] | 425 | 2019-05-22T02:14:27.000Z | 2021-12-18T22:18:04.000Z | /*
rdesktop: A Remote Desktop Protocol client.
Master include file
Copyright (C) Matthew Chapman 1999-2008
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#ifdef _WIN32
#define WINVER 0x0400
#include <windows.h>
#include <winsock.h>
#include <time.h>
#define DIR int
#else
#include <dirent.h>
#include <sys/time.h>
#ifdef HAVE_SYS_SELECT_H
#include <sys/select.h>
#else
#include <sys/types.h>
#include <unistd.h>
#endif
#endif
#include <limits.h> /* PATH_MAX */
#ifdef HAVE_SYSEXITS_H
#include <sysexits.h>
#endif
/* standard exit codes */
#ifndef EX_OK
#define EX_OK 0
#endif
#ifndef EX_USAGE
#define EX_USAGE 64
#endif
#ifndef EX_DATAERR
#define EX_DATAERR 65
#endif
#ifndef EX_NOINPUT
#define EX_NOINPUT 66
#endif
#ifndef EX_NOUSER
#define EX_NOUSER 67
#endif
#ifndef EX_NOHOST
#define EX_NOHOST 68
#endif
#ifndef EX_UNAVAILABLE
#define EX_UNAVAILABLE 69
#endif
#ifndef EX_SOFTWARE
#define EX_SOFTWARE 70
#endif
#ifndef EX_OSERR
#define EX_OSERR 71
#endif
#ifndef EX_OSFILE
#define EX_OSFILE 72
#endif
#ifndef EX_CANTCREAT
#define EX_CANTCREAT 73
#endif
#ifndef EX_IOERR
#define EX_IOERR 74
#endif
#ifndef EX_TEMPFAIL
#define EX_TEMPFAIL 75
#endif
#ifndef EX_PROTOCOL
#define EX_PROTOCOL 76
#endif
#ifndef EX_NOPERM
#define EX_NOPERM 77
#endif
#ifndef EX_CONFIG
#define EX_CONFIG 78
#endif
/* rdesktop specific exit codes, lined up with disconnect PDU reasons */
#define EXRD_API_DISCONNECT 1
#define EXRD_API_LOGOFF 2
#define EXRD_IDLE_TIMEOUT 3
#define EXRD_LOGON_TIMEOUT 4
#define EXRD_REPLACED 5
#define EXRD_OUT_OF_MEM 6
#define EXRD_DENIED 7
#define EXRD_DENIED_FIPS 8
#define EXRD_INSUFFICIENT_PRIVILEGES 9
#define EXRD_FRESH_CREDENTIALS_REQUIRED 10
#define EXRD_RPC_DISCONNECT_BY_USER 11
#define EXRD_DISCONNECT_BY_USER 12
#define EXRD_LIC_INTERNAL 16
#define EXRD_LIC_NOSERVER 17
#define EXRD_LIC_NOLICENSE 18
#define EXRD_LIC_MSG 19
#define EXRD_LIC_HWID 20
#define EXRD_LIC_CLIENT 21
#define EXRD_LIC_NET 22
#define EXRD_LIC_PROTO 23
#define EXRD_LIC_ENC 24
#define EXRD_LIC_UPGRADE 25
#define EXRD_LIC_NOREMOTE 26
/* other exit codes */
#define EXRD_WINDOW_CLOSED 62
#define EXRD_UNKNOWN 63
#ifdef WITH_DEBUG
#define DEBUG(args) printf args;
#else
#define DEBUG(args)
#endif
#ifdef WITH_DEBUG_KBD
#define DEBUG_KBD(args) printf args;
#else
#define DEBUG_KBD(args)
#endif
#ifdef WITH_DEBUG_RDP5
#define DEBUG_RDP5(args) printf args;
#else
#define DEBUG_RDP5(args)
#endif
#ifdef WITH_DEBUG_CLIPBOARD
#define DEBUG_CLIPBOARD(args) printf args;
#else
#define DEBUG_CLIPBOARD(args)
#endif
#ifdef WITH_DEBUG_SOUND
#define DEBUG_SOUND(args) printf args;
#else
#define DEBUG_SOUND(args)
#endif
#ifdef WITH_DEBUG_CHANNEL
#define DEBUG_CHANNEL(args) printf args;
#else
#define DEBUG_CHANNEL(args)
#endif
#ifdef WITH_DEBUG_SCARD
#define DEBUG_SCARD(args) printf args;
#else
#define DEBUG_SCARD(args)
#endif
#define STRNCPY(dst,src,n) { strncpy(dst,src,n-1); dst[n-1] = 0; }
#ifndef MIN
#define MIN(x,y) (((x) < (y)) ? (x) : (y))
#endif
#ifndef MAX
#define MAX(x,y) (((x) > (y)) ? (x) : (y))
#endif
/* timeval macros */
#ifndef timerisset
#define timerisset(tvp)\
((tvp)->tv_sec || (tvp)->tv_usec)
#endif
#ifndef timercmp
#define timercmp(tvp, uvp, cmp)\
((tvp)->tv_sec cmp (uvp)->tv_sec ||\
(tvp)->tv_sec == (uvp)->tv_sec &&\
(tvp)->tv_usec cmp (uvp)->tv_usec)
#endif
#ifndef timerclear
#define timerclear(tvp)\
((tvp)->tv_sec = (tvp)->tv_usec = 0)
#endif
/* If configure does not define the endianess, try
to find it out */
#if !defined(L_ENDIAN) && !defined(B_ENDIAN)
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define L_ENDIAN
#elif __BYTE_ORDER == __BIG_ENDIAN
#define B_ENDIAN
#else
#error Unknown endianness. Edit rdesktop.h.
#endif
#endif /* B_ENDIAN, L_ENDIAN from configure */
/* No need for alignment on x86 and amd64 */
#if !defined(NEED_ALIGN)
#if !(defined(__x86__) || defined(__x86_64__) || \
defined(__AMD64__) || defined(_M_IX86) || \
defined(__i386__))
#define NEED_ALIGN
#endif
#endif
#include "parse.h"
#include "constants.h"
#include "types.h"
#ifndef MAKE_PROTO
#include "proto.h"
#endif
| 22.086758 | 72 | 0.736614 |
a5d50597fa2bdfb700f8d6f9da199db7f4109d35 | 3,543 | sql | SQL | sql/egg_shop_attachments.sql | PH-C/duapp | b6c2515e12eb23f1e188f6b0779266ea561b2327 | [
"MIT"
] | 2 | 2019-06-22T04:56:33.000Z | 2019-12-31T09:57:58.000Z | sql/egg_shop_attachments.sql | PH-C/duapp | b6c2515e12eb23f1e188f6b0779266ea561b2327 | [
"MIT"
] | null | null | null | sql/egg_shop_attachments.sql | PH-C/duapp | b6c2515e12eb23f1e188f6b0779266ea561b2327 | [
"MIT"
] | null | null | null | -- MySQL dump 10.13 Distrib 8.0.14, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: egg_shop
-- ------------------------------------------------------
-- Server version 8.0.14
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
SET NAMES utf8 ;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `attachments`
--
DROP TABLE IF EXISTS `attachments`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
SET character_set_client = utf8mb4 ;
CREATE TABLE `attachments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`extname` varchar(255) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
`filename` varchar(255) DEFAULT NULL,
`extra` varchar(255) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `attachments`
--
LOCK TABLES `attachments` WRITE;
/*!40000 ALTER TABLE `attachments` DISABLE KEYS */;
INSERT INTO `attachments` VALUES (1,'.jpg','/uploads/fc08e517a6488ca6364ae38db6f95f74.jpg','IMG_20190311_134820R.jpg',NULL,'2019-03-19 00:35:37','2019-03-19 00:35:37'),(2,'.png','/uploads/049bea8511497c03d8e44737ae3ac99b.png','049bea8511497c03d8e44737ae3ac99b',NULL,'2019-03-19 00:41:26','2019-03-19 00:41:26'),(3,'.jpg','/uploads/e470ede8a6439ba96ed353b2a10bbb9a.jpg','e470ede8a6439ba96ed353b2a10bbb9a',NULL,'2019-03-19 00:45:31','2019-03-19 00:45:31'),(4,'.jpg','/uploads/71640e00c152578afc33fd2dc6d86760.jpg','71640e00c152578afc33fd2dc6d86760',NULL,'2019-03-19 00:46:54','2019-03-19 00:46:54'),(5,'.jpg','/uploads/c550df2072d13c59502542e80966a01a.jpg','c550df2072d13c59502542e80966a01a',NULL,'2019-03-19 00:46:54','2019-03-19 00:46:54'),(6,'.jpg','/uploads/93a5de16339d64b9f3d17037a0bd5f06.jpg','93a5de16339d64b9f3d17037a0bd5f06',NULL,'2019-03-19 00:49:05','2019-03-19 00:49:05'),(7,'.jpg','/uploads/b9b3d7bd6d0b7c9284003376d20e4bb1.jpg','b9b3d7bd6d0b7c9284003376d20e4bb1',NULL,'2019-03-19 00:49:24','2019-03-19 00:49:24'),(8,'.jpg','/uploads/a2113f224b995859fb19e41d2da330b0.jpg','a2113f224b995859fb19e41d2da330b0',NULL,'2019-03-19 00:50:25','2019-03-19 00:50:25'),(9,'.jpg','/uploads/e41ce4186dbd628a3357f96253535be2.jpg','e41ce4186dbd628a3357f96253535be2',NULL,'2019-03-19 00:50:25','2019-03-19 00:50:25'),(10,'.jpg','/uploads/c9cb680f3b0c3e65d5cd3087421094d3.jpg','c9cb680f3b0c3e65d5cd3087421094d3',NULL,'2019-03-19 00:56:45','2019-03-19 00:56:45');
/*!40000 ALTER TABLE `attachments` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2019-03-19 1:02:49
| 62.157895 | 1,456 | 0.738357 |
ef518fd81f845809b024eebde359e4d2ad5fd5dc | 4,740 | c | C | ext/pg_binary_encoder.c | sergey-alekseev/ruby-pg | 44300258355e9b221dd53bb27e450ee594e1f57d | [
"Ruby"
] | null | null | null | ext/pg_binary_encoder.c | sergey-alekseev/ruby-pg | 44300258355e9b221dd53bb27e450ee594e1f57d | [
"Ruby"
] | null | null | null | ext/pg_binary_encoder.c | sergey-alekseev/ruby-pg | 44300258355e9b221dd53bb27e450ee594e1f57d | [
"Ruby"
] | null | null | null | /*
* pg_column_map.c - PG::ColumnMap class extension
* $Id$
*
*/
#include "pg.h"
#include "pg_util.h"
#ifdef HAVE_INTTYPES_H
#include <inttypes.h>
#endif
VALUE rb_mPG_BinaryEncoder;
/*
* Document-class: PG::BinaryEncoder::Boolean < PG::SimpleEncoder
*
* This is the encoder class for the PostgreSQL boolean type.
*
* It accepts true and false. Other values will raise an exception.
*
*/
static int
pg_bin_enc_boolean(t_pg_coder *conv, VALUE value, char *out, VALUE *intermediate, int enc_idx)
{
char mybool;
if (value == Qtrue) {
mybool = 1;
} else if (value == Qfalse) {
mybool = 0;
} else {
rb_raise( rb_eTypeError, "wrong data for binary boolean converter" );
}
if(out) *out = mybool;
return 1;
}
/*
* Document-class: PG::BinaryEncoder::Int2 < PG::SimpleEncoder
*
* This is the encoder class for the PostgreSQL int2 type.
*
* Non-Number values are expected to have method +to_i+ defined.
*
*/
static int
pg_bin_enc_int2(t_pg_coder *conv, VALUE value, char *out, VALUE *intermediate, int enc_idx)
{
if(out){
write_nbo16(NUM2INT(*intermediate), out);
}else{
*intermediate = pg_obj_to_i(value);
}
return 2;
}
/*
* Document-class: PG::BinaryEncoder::Int2 < PG::SimpleEncoder
*
* This is the encoder class for the PostgreSQL int4 type.
*
* Non-Number values are expected to have method +to_i+ defined.
*
*/
static int
pg_bin_enc_int4(t_pg_coder *conv, VALUE value, char *out, VALUE *intermediate, int enc_idx)
{
if(out){
write_nbo32(NUM2LONG(*intermediate), out);
}else{
*intermediate = pg_obj_to_i(value);
}
return 4;
}
/*
* Document-class: PG::BinaryEncoder::Int2 < PG::SimpleEncoder
*
* This is the encoder class for the PostgreSQL int8 type.
*
* Non-Number values are expected to have method +to_i+ defined.
*
*/
static int
pg_bin_enc_int8(t_pg_coder *conv, VALUE value, char *out, VALUE *intermediate, int enc_idx)
{
if(out){
write_nbo64(NUM2LL(*intermediate), out);
}else{
*intermediate = pg_obj_to_i(value);
}
return 8;
}
/*
* Document-class: PG::BinaryEncoder::FromBase64 < PG::CompositeEncoder
*
* This is an encoder class for conversion of base64 encoded data
* to it's binary representation.
*
*/
static int
pg_bin_enc_from_base64(t_pg_coder *conv, VALUE value, char *out, VALUE *intermediate, int enc_idx)
{
int strlen;
VALUE subint;
t_pg_composite_coder *this = (t_pg_composite_coder *)conv;
t_pg_coder_enc_func enc_func = pg_coder_enc_func(this->elem);
if(out){
/* Second encoder pass, if required */
strlen = enc_func(this->elem, value, out, intermediate, enc_idx);
strlen = base64_decode( out, out, strlen );
return strlen;
} else {
/* First encoder pass */
strlen = enc_func(this->elem, value, NULL, &subint, enc_idx);
if( strlen == -1 ){
/* Encoded string is returned in subint */
VALUE out_str;
strlen = RSTRING_LENINT(subint);
out_str = rb_str_new(NULL, BASE64_DECODED_SIZE(strlen));
strlen = base64_decode( RSTRING_PTR(out_str), RSTRING_PTR(subint), strlen);
rb_str_set_len( out_str, strlen );
*intermediate = out_str;
return -1;
} else {
*intermediate = subint;
return BASE64_DECODED_SIZE(strlen);
}
}
}
void
init_pg_binary_encoder()
{
/* This module encapsulates all encoder classes with binary output format */
rb_mPG_BinaryEncoder = rb_define_module_under( rb_mPG, "BinaryEncoder" );
/* Make RDoc aware of the encoder classes... */
/* dummy = rb_define_class_under( rb_mPG_BinaryEncoder, "Boolean", rb_cPG_SimpleEncoder ); */
pg_define_coder( "Boolean", pg_bin_enc_boolean, rb_cPG_SimpleEncoder, rb_mPG_BinaryEncoder );
/* dummy = rb_define_class_under( rb_mPG_BinaryEncoder, "Int2", rb_cPG_SimpleEncoder ); */
pg_define_coder( "Int2", pg_bin_enc_int2, rb_cPG_SimpleEncoder, rb_mPG_BinaryEncoder );
/* dummy = rb_define_class_under( rb_mPG_BinaryEncoder, "Int4", rb_cPG_SimpleEncoder ); */
pg_define_coder( "Int4", pg_bin_enc_int4, rb_cPG_SimpleEncoder, rb_mPG_BinaryEncoder );
/* dummy = rb_define_class_under( rb_mPG_BinaryEncoder, "Int8", rb_cPG_SimpleEncoder ); */
pg_define_coder( "Int8", pg_bin_enc_int8, rb_cPG_SimpleEncoder, rb_mPG_BinaryEncoder );
/* dummy = rb_define_class_under( rb_mPG_BinaryEncoder, "String", rb_cPG_SimpleEncoder ); */
pg_define_coder( "String", pg_coder_enc_to_s, rb_cPG_SimpleEncoder, rb_mPG_BinaryEncoder );
/* dummy = rb_define_class_under( rb_mPG_BinaryEncoder, "Bytea", rb_cPG_SimpleEncoder ); */
pg_define_coder( "Bytea", pg_coder_enc_to_s, rb_cPG_SimpleEncoder, rb_mPG_BinaryEncoder );
/* dummy = rb_define_class_under( rb_mPG_BinaryEncoder, "FromBase64", rb_cPG_CompositeEncoder ); */
pg_define_coder( "FromBase64", pg_bin_enc_from_base64, rb_cPG_CompositeEncoder, rb_mPG_BinaryEncoder );
}
| 28.902439 | 104 | 0.72827 |
18ede2613d80b12f6b2b556f3b62d6cf9bd3b47a | 1,986 | rs | Rust | src/archived/p0329_longest_increasing_path_in_a_matrix.rs | gozssky/leetcode-rust | cdfd5e73d9c89c4241c3ba3d91504fa3cf0fdf55 | [
"MIT"
] | 1 | 2021-01-02T06:42:29.000Z | 2021-01-02T06:42:29.000Z | src/archived/p0329_longest_increasing_path_in_a_matrix.rs | gozssky/leetcode-rust | cdfd5e73d9c89c4241c3ba3d91504fa3cf0fdf55 | [
"MIT"
] | null | null | null | src/archived/p0329_longest_increasing_path_in_a_matrix.rs | gozssky/leetcode-rust | cdfd5e73d9c89c4241c3ba3d91504fa3cf0fdf55 | [
"MIT"
] | 1 | 2021-04-25T01:01:00.000Z | 2021-04-25T01:01:00.000Z | #![allow(dead_code)]
pub struct Solution;
impl Solution {
fn dfs(x: usize, y: usize, f: &mut Vec<Vec<i32>>, matrix: &Vec<Vec<i32>>) -> i32 {
if f[x][y] > 0 {
return f[x][y];
}
let m = f.len();
let n = f[0].len();
let mut ans = 0;
if x > 0 && matrix[x - 1][y] > matrix[x][y] {
if f[x - 1][y] == 0 {
Solution::dfs(x - 1, y, f, matrix);
}
ans = ans.max(f[x - 1][y]);
}
if x + 1 < m && matrix[x + 1][y] > matrix[x][y] {
if f[x + 1][y] == 0 {
Solution::dfs(x + 1, y, f, matrix);
}
ans = ans.max(f[x + 1][y]);
}
if y > 0 && matrix[x][y - 1] > matrix[x][y] {
if f[x][y - 1] == 0 {
Solution::dfs(x, y - 1, f, matrix);
}
ans = ans.max(f[x][y - 1]);
}
if y + 1 < n && matrix[x][y + 1] > matrix[x][y] {
if f[x][y + 1] == 0 {
Solution::dfs(x, y + 1, f, matrix);
}
ans = ans.max(f[x][y + 1]);
}
f[x][y] = ans + 1;
f[x][y]
}
pub fn longest_increasing_path(matrix: Vec<Vec<i32>>) -> i32 {
let m = matrix.len();
let n = matrix[0].len();
let mut f = vec![vec![0; n]; m];
let mut ans = 0;
for i in 0..m {
for j in 0..n {
ans = ans.max(Solution::dfs(i, j, &mut f, &matrix));
}
}
ans
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_longest_increasing_path() {
assert_eq!(
Solution::longest_increasing_path(vec![vec![9, 9, 4], vec![6, 6, 8], vec![2, 1, 1]]),
4
);
assert_eq!(
Solution::longest_increasing_path(vec![vec![3, 4, 5], vec![3, 2, 6], vec![2, 2, 1]]),
4
);
assert_eq!(Solution::longest_increasing_path(vec![vec![1]]), 1);
}
}
| 27.971831 | 97 | 0.388721 |
5dd72157657a7f90b29c9333a51eb5164b604f4c | 2,612 | cpp | C++ | modules/core/src/named_output_pipe.cpp | tizenorg/platform.framework.web.wrt-commons | 5835a89c8b013c00b828fecf04f423adc9e5d561 | [
"Apache-2.0"
] | null | null | null | modules/core/src/named_output_pipe.cpp | tizenorg/platform.framework.web.wrt-commons | 5835a89c8b013c00b828fecf04f423adc9e5d561 | [
"Apache-2.0"
] | null | null | null | modules/core/src/named_output_pipe.cpp | tizenorg/platform.framework.web.wrt-commons | 5835a89c8b013c00b828fecf04f423adc9e5d561 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* @file named_output_pipe.cpp
* @author Przemyslaw Dobrowolski ([email protected])
* @version 1.0
* @brief This file is the implementation file of named output pipe
*/
#include <dpl/named_output_pipe.h>
#include <dpl/binary_queue.h>
#include <dpl/scoped_free.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
namespace DPL
{
NamedOutputPipe::NamedOutputPipe()
: m_fifo(-1)
{
}
NamedOutputPipe::~NamedOutputPipe()
{
Close();
}
void NamedOutputPipe::Open(const std::string& pipeName)
{
// Then open it for reading or writing
int fifo = TEMP_FAILURE_RETRY(open(pipeName.c_str(), O_WRONLY | O_NONBLOCK));
if (fifo == -1)
ThrowMsg(Exception::OpenFailed, pipeName);
m_fifo = fifo;
}
void NamedOutputPipe::Close()
{
if (m_fifo == -1)
return;
if (TEMP_FAILURE_RETRY(close(m_fifo)) == -1)
Throw(Exception::CloseFailed);
m_fifo = -1;
}
size_t NamedOutputPipe::Write(const BinaryQueue &buffer, size_t bufferSize)
{
// Adjust write size
if (bufferSize > buffer.Size())
bufferSize = buffer.Size();
// FIXME: User write visitor to write !
// WriteVisitor visitor
ScopedFree<void> flattened(malloc(bufferSize));
buffer.Flatten(flattened.Get(), bufferSize);
ssize_t result = TEMP_FAILURE_RETRY(write(m_fifo, flattened.Get(), bufferSize));
if (result > 0)
{
// Successfuly written some bytes
return static_cast<size_t>(result);
}
else if (result == 0)
{
// This is abnormal result
ThrowMsg(CommonException::InternalError, "Invalid socket write result, 0 bytes written");
}
else
{
// Interpret error result
// FIXME: Handle errno
Throw(AbstractOutput::Exception::WriteFailed);
}
}
int NamedOutputPipe::WaitableWriteHandle() const
{
return m_fifo;
}
} // namespace DPL
| 25.607843 | 97 | 0.667305 |
8d91f91a9b9dd848b4c34aa0f144818769b7363a | 903 | swift | Swift | RescueLink/Models/LocationManager.swift | security-union/armore-ios | 55ef53de10b71780d67cab48e7d62e28f35baf09 | [
"Apache-2.0"
] | 3 | 2021-04-06T02:37:38.000Z | 2021-12-10T08:33:42.000Z | RescueLink/Models/LocationManager.swift | security-union/armore-ios | 55ef53de10b71780d67cab48e7d62e28f35baf09 | [
"Apache-2.0"
] | null | null | null | RescueLink/Models/LocationManager.swift | security-union/armore-ios | 55ef53de10b71780d67cab48e7d62e28f35baf09 | [
"Apache-2.0"
] | null | null | null | //
// LocationManager.swift
// Armore
//
// Created by Dario Talarico on 6/2/20.
// Copyright © 2020 Security Union. All rights reserved.
//
import Foundation
import CoreLocation
protocol LocationManager {
func startForegroundTracking(_ delegate: CLLocationManagerDelegate?,
updateFrequencyForeground: TimeInterval,
updateFrequencyBackground: TimeInterval)
func startTrackingInTheBackground(_ delegate: CLLocationManagerDelegate?,
updateFrequencyForeground: TimeInterval,
updateFrequencyBackground: TimeInterval)
func stop()
func authorizationStatus() -> CLAuthorizationStatus
func accuracyAuthorization() -> CLAccuracyAuthorization
func startTimer()
func stopTimer()
var delegate: CLLocationManagerDelegate? { get set }
}
| 34.730769 | 78 | 0.662237 |
38c740270b80251b8266f303cdffc31234f025bf | 4,605 | php | PHP | tests/PlaygroundGameTest/Mapper/PrizeCategoryTest.php | gregorybesson/PlaygroundGame | c4b36577f3fc0ea9fb7496c0eb81d05425b0341e | [
"MIT"
] | null | null | null | tests/PlaygroundGameTest/Mapper/PrizeCategoryTest.php | gregorybesson/PlaygroundGame | c4b36577f3fc0ea9fb7496c0eb81d05425b0341e | [
"MIT"
] | 22 | 2015-02-01T13:06:53.000Z | 2017-02-13T16:39:29.000Z | tests/PlaygroundGameTest/Mapper/PrizeCategoryTest.php | gregorybesson/PlaygroundGame | c4b36577f3fc0ea9fb7496c0eb81d05425b0341e | [
"MIT"
] | 1 | 2015-11-24T22:11:27.000Z | 2015-11-24T22:11:27.000Z | <?php
namespace PlaygroundGameTest\Mapper;
use \PlaygroundGame\Entity\PrizeCategory as PrizeCategoryEntity;
use PlaygroundGameTest\Bootstrap;
class PrizeCategoryTest extends \PHPUnit\Framework\TestCase
{
protected $traceError = true;
protected function setUp(): void
{
$this->sm = Bootstrap::getServiceManager();
$this->em = $this->sm->get('doctrine.entitymanager.orm_default');
$this->tm = $this->sm->get('playgroundgame_prizecategory_mapper');
$tool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
$classes = $this->em->getMetadataFactory()->getAllMetadata();
$tool->dropSchema($classes);
$tool->createSchema($classes);
}
// public function testFindById()
// {
// $prizeCategory = new PrizeCategoryEntity();
// $prizeCategory->setIdentifier('iden');
// $prizeCategory->setTitle('Un Titre');
// $prizeCategory = $this->tm->insert($prizeCategory);
// $this->assertEquals($prizeCategory, $this->tm->findById($prizeCategory->getId()));
// $this->assertEquals($prizeCategory, current($this->tm->findBy(array('identifier' => 'iden'))));
// $this->tm->remove($prizeCategory);
// $this->assertEmpty($this->tm->findBy(array('identifier' => 'iden')));
// }
// public function testInsertTranslation()
// {
// $translator = $this->sm->get('MvcTranslator');
// $prizeCategory = new PrizeCategoryEntity();
// $translator->setLocale('en_US');
// $prizeCategory->setTitle('Anglais')
// ->setIdentifier('anglais');
// $prizeCategory = $this->tm->insert($prizeCategory);
// $translator->setLocale('fr_FR');
// $prizeCategory->setTitle('Francais')
// ->setIdentifier('francais');
// $prizeCategory = $this->tm->insert($prizeCategory);
// $this->assertCount(1, $this->tm->findAll());
// $this->assertInstanceOf('\PlaygroundGame\Entity\PrizeCategory', current($this->tm->findAll()));
// $prizeCategory = current($this->tm->findAll());
// $this->assertEquals("Francais", $prizeCategory->getTitle());
// $this->assertEquals("francais", $prizeCategory->getIdentifier());
// }
public function testUpdate()
{
$prizeCategory = new PrizeCategoryEntity();
$prizeCategory->setIdentifier('iden');
$prizeCategory->setTitle('Un Titre');
$prizeCategory = $this->tm->insert($prizeCategory);
$prizeCategory->setIdentifier('iden 2');
$prizeCategory = $this->tm->update($prizeCategory);
$this->assertEquals('iden 2', $prizeCategory->getIdentifier());
$this->tm->remove($prizeCategory);
$this->assertEmpty($this->tm->findAll());
}
public function testRemove()
{
$prizeCategory = new PrizeCategoryEntity();
$prizeCategory->setIdentifier('iden');
$prizeCategory->setTitle('Un Titre');
$prizeCategory = $this->tm->insert($prizeCategory);
$id = $prizeCategory->getId();
$this->tm->remove($prizeCategory);
$this->assertNull($this->tm->findById($id));
}
// public function testFindAll()
// {
// $prizeCategory = new PrizeCategoryEntity();
// $prizeCategory->setIdentifier('iden 1');
// $prizeCategory->setTitle('Un Titre 1');
// $prizeCategory = $this->tm->insert($prizeCategory);
// //var_dump($prizeCategory);
// $prizeCategory2 = new PrizeCategoryEntity();
// $prizeCategory2->setIdentifier('iden 2');
// $prizeCategory2->setTitle('Un Titre 2');
// $prizeCategory2 = $this->tm->insert($prizeCategory2);
// //var_dump($prizeCategory2);
// $prizeCategory3 = new PrizeCategoryEntity();
// $prizeCategory3->setIdentifier('iden 3');
// $prizeCategory3->setTitle('Un Titre 3');
// $prizeCategory3 = $this->tm->insert($prizeCategory3);
// //var_dump($prizeCategory);
// $prizeCategories = $this->tm->findAll();
// $this->assertEquals(3, count($prizeCategories));
// foreach ($this->tm->findAll() as $prizeCategory) {
// $this->tm->remove($prizeCategory);
// }
// }
protected function tearDown(): void
{
$tool = new \Doctrine\ORM\Tools\SchemaTool($this->em);
$classes = $this->em->getMetadataFactory()->getAllMetadata();
$tool->dropSchema($classes);
$this->sm = null;
$this->em = null;
unset($this->sm);
unset($this->em);
parent::tearDown();
}
}
| 37.745902 | 106 | 0.599131 |
a140c572dd3a56c1e53326270f1111fa18debd1e | 3,803 | cpp | C++ | src/Backend_SDL2/Filesystem.cpp | GabrielRavier/CuckySonic | 52152460ac39fc96fdb2fcbe9da85b8067f414d3 | [
"MIT"
] | null | null | null | src/Backend_SDL2/Filesystem.cpp | GabrielRavier/CuckySonic | 52152460ac39fc96fdb2fcbe9da85b8067f414d3 | [
"MIT"
] | 1 | 2019-10-21T00:01:43.000Z | 2019-10-21T00:01:43.000Z | src/Backend_SDL2/Filesystem.cpp | GabrielRavier/CuckySonic | 52152460ac39fc96fdb2fcbe9da85b8067f414d3 | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <string.h>
#include "../Filesystem.h"
#include "../GameConstants.h"
#include "../Log.h"
#include "../Error.h"
char *gBasePath;
char *gPrefPath;
//File handle functions
BACKEND_FILE *OpenFile(const char *path, const char *mode) { return SDL_RWFromFile(path, mode); }
void CloseFile(BACKEND_FILE *file) { SDL_RWclose(file); }
const char *GetFileError() { return SDL_GetError(); }
size_t GetFileSize(BACKEND_FILE *file) { return SDL_RWsize(file); }
size_t ReadFile(BACKEND_FILE *file, void *ptr, size_t size, size_t maxnum) { return SDL_RWread(file, ptr, size, maxnum); }
uint8_t ReadFile_Byte(BACKEND_FILE *file) { return SDL_ReadU8(file); }
uint16_t ReadFile_LE16(BACKEND_FILE *file) { return SDL_ReadLE16(file); }
uint16_t ReadFile_BE16(BACKEND_FILE *file) { return SDL_ReadBE16(file); }
uint32_t ReadFile_LE32(BACKEND_FILE *file) { return SDL_ReadLE32(file); }
uint32_t ReadFile_BE32(BACKEND_FILE *file) { return SDL_ReadBE32(file); }
uint64_t ReadFile_LE64(BACKEND_FILE *file) { return SDL_ReadLE64(file); }
uint64_t ReadFile_BE64(BACKEND_FILE *file) { return SDL_ReadBE64(file); }
size_t WriteFile(BACKEND_FILE *file, void *ptr, size_t size, size_t num) { return SDL_RWwrite(file, ptr, size, num); }
size_t WriteFile_Byte(BACKEND_FILE *file, uint8_t value) { return SDL_WriteU8(file, value); }
size_t WriteFile_LE16(BACKEND_FILE *file, uint16_t value) { return SDL_WriteLE16(file, value); }
size_t WriteFile_BE16(BACKEND_FILE *file, uint16_t value) { return SDL_WriteBE16(file, value); }
size_t WriteFile_LE32(BACKEND_FILE *file, uint32_t value) { return SDL_WriteLE32(file, value); }
size_t WriteFile_BE32(BACKEND_FILE *file, uint32_t value) { return SDL_WriteBE32(file, value); }
size_t WriteFile_LE64(BACKEND_FILE *file, uint64_t value) { return SDL_WriteLE64(file, value); }
size_t WriteFile_BE64(BACKEND_FILE *file, uint64_t value) { return SDL_WriteBE64(file, value); }
size_t SeekFile(BACKEND_FILE *file, size_t whence, int offset)
{
switch (offset)
{
case FILESEEK_SET:
return SDL_RWseek(file, whence, RW_SEEK_SET);
case FILESEEK_CUR:
return SDL_RWseek(file, whence, RW_SEEK_CUR);
case FILESEEK_END:
return SDL_RWseek(file, whence, RW_SEEK_END);
}
return -1;
}
size_t TellFile(BACKEND_FILE *file) { return SDL_RWtell(file); }
//Core file path stuff
char *AllocPath(const char *base, const char *name, const char *append)
{
char *newString = new char[
strlen(base) //base (if not null)
+ (name == nullptr ? 0 : strlen(name)) //name (if not null)
+ (append == nullptr ? 0 : strlen(append)) //append (if not null)
+ 1
];
strcpy(newString, base);
if (name != nullptr)
strcat(newString, name);
if (append != nullptr)
strcat(newString, append);
return newString;
}
bool InitializePath()
{
LOG(("Initializing paths... "));
char *basePath = SDL_GetBasePath();
char *prefPath = SDL_GetPrefPath(GAME_ORGANIZATION, GAME_TITLE);
//Get base (executable's) path
if (basePath == nullptr)
{
//Use "./" as a placeholder
gBasePath = AllocPath("./", nullptr, nullptr);
Warn("Couldn't get a path to the executable from SDL, may cause undefined behaviour");
}
else
{
//Copy basePath
gBasePath = AllocPath(basePath, nullptr, nullptr);
SDL_free(basePath);
}
//Get pref (save data) path
if (prefPath == nullptr)
{
//Copy gBasePath as a placeholder
gPrefPath = AllocPath(gBasePath, nullptr, nullptr);
Warn("Couldn't get a path to pref directory from SDL, executable's path will be used instead");
}
else
{
//Copy prefPath
gPrefPath = AllocPath(prefPath, nullptr, nullptr);
SDL_free(prefPath);
}
LOG(("Success!\n"));
return true;
}
void QuitPath()
{
LOG(("Ending paths... "));
delete[] gBasePath;
delete[] gPrefPath;
LOG(("Success!\n"));
}
| 33.069565 | 123 | 0.717065 |
6af8927356e6ba5a28952d46aed4a79fdeb8e668 | 270 | h | C | build/base/gen/include/config/embox/arch/clock.h | clinlfoundation/EMBOX | 00d39726d5ce6fb617ec583c110e29ec25de0c49 | [
"BSD-2-Clause"
] | 2 | 2020-03-27T11:39:06.000Z | 2020-10-10T01:41:10.000Z | build/base/gen/include/config/embox/arch/clock.h | clinlfoundation/EMBOX | 00d39726d5ce6fb617ec583c110e29ec25de0c49 | [
"BSD-2-Clause"
] | null | null | null | build/base/gen/include/config/embox/arch/clock.h | clinlfoundation/EMBOX | 00d39726d5ce6fb617ec583c110e29ec25de0c49 | [
"BSD-2-Clause"
] | 1 | 2020-03-30T09:59:35.000Z | 2020-03-30T09:59:35.000Z | /* Generated by GNU Make 4.2.1. Do not edit. */
#ifndef __CONFIG__embox__arch__clock__H_
#define __CONFIG__embox__arch__clock__H_
// This is a base type of embox.driver.clock.pit
#include <config/embox/driver/clock/pit.h>
#endif /* __CONFIG__embox__arch__clock__H_ */
| 30 | 48 | 0.785185 |
4d16f7e7e51499b3cf94f13ff0af9f3a062f0ce9 | 1,757 | sql | SQL | db/views/api_questions_tree_view/20160202174508.sql | unepwcmc/ORS | 6934c8e6b26a6d0cb585f5e8f342e7db73e9d914 | [
"BSD-3-Clause"
] | 3 | 2016-12-08T09:21:55.000Z | 2019-06-29T16:03:47.000Z | db/views/api_questions_tree_view/20160202174508.sql | unepwcmc/ORS | 6934c8e6b26a6d0cb585f5e8f342e7db73e9d914 | [
"BSD-3-Clause"
] | 26 | 2016-09-22T08:24:45.000Z | 2022-02-26T01:23:32.000Z | db/views/api_questions_tree_view/20160202174508.sql | unepwcmc/ORS | 6934c8e6b26a6d0cb585f5e8f342e7db73e9d914 | [
"BSD-3-Clause"
] | null | null | null | -- DROP VIEW api_questions_tree_view;
CREATE OR REPLACE VIEW api_questions_tree_view AS
WITH mao_options AS (
SELECT mao.multi_answer_id,
mao.language,
array_agg(mao.option_text ORDER BY mao.sort_index) AS options
FROM api_multi_answer_options_view mao
GROUP BY mao.multi_answer_id, mao.language
), rao_options AS (
SELECT rao.range_answer_id,
rao.language,
array_agg(rao.option_text ORDER BY rao.sort_index) AS options
FROM api_range_answer_options_view rao
GROUP BY rao.range_answer_id, rao.language
)
SELECT q.id,
q.section_id,
q.answer_type_id,
q.answer_type_type,
q.is_mandatory,
q.language,
q.is_default_language,
q.title,
q.short_title,
q.description,
q.lft,
q.languages,
s.questionnaire_id,
s.section_type,
s.loop_source_id,
s.loop_item_type_id,
s.looping_section_id,
s.depends_on_question_id,
s.depends_on_option_id,
s.depends_on_option_value,
s.is_hidden,
s.display_in_tab,
s.title AS section_title,
s.tab_title AS section_tab_title,
s.language AS section_language,
s.is_default_language AS section_is_default_language,
s.path,
COALESCE(mao_options.options, rao_options.options::text[]) AS options
FROM api_questions_view q
JOIN api_sections_tree_view s ON q.section_id = s.id AND (q.language = s.language OR s.is_default_language AND NOT s.languages @> ARRAY[q.language])
LEFT JOIN mao_options ON mao_options.multi_answer_id = q.answer_type_id AND mao_options.language = q.language
LEFT JOIN rao_options ON rao_options.range_answer_id = q.answer_type_id AND rao_options.language = q.language;
| 35.857143 | 153 | 0.710871 |
c5583ee46994e768555085c1698676982d9a1e41 | 2,260 | css | CSS | assets/css/improved-sr-only.css | mandrasch/not-a-real-screenreader-pptr | 3bad7e54d667b43f6517fa3b1640500e11745417 | [
"CC0-1.0"
] | 3 | 2021-08-02T02:25:04.000Z | 2021-08-02T15:26:01.000Z | assets/css/improved-sr-only.css | mandrasch/not-a-real-screenreader | 3bad7e54d667b43f6517fa3b1640500e11745417 | [
"CC0-1.0"
] | null | null | null | assets/css/improved-sr-only.css | mandrasch/not-a-real-screenreader | 3bad7e54d667b43f6517fa3b1640500e11745417 | [
"CC0-1.0"
] | null | null | null | /* https://gist.github.com/ffoodd/000b59f431e3e64e4ce1a24d5bb36034 */
/*
Improved screen reader only CSS class
@author Gaël Poupard
@note Based on Yahoo!'s technique
@author Thierry Koblentz
@see https://developer.yahoo.com/blogs/ydn/clip-hidden-content-better-accessibility-53456.html
* 1.
@note `clip` is deprecated but works everywhere
@see https://developer.mozilla.org/en-US/docs/Web/CSS/clip
* 2.
@note `clip-path` is the future-proof version, but not very well supported yet
@see https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path
@see http://caniuse.com/#search=clip-path
@author Yvain Liechti
@see https://twitter.com/ryuran78/status/778943389819604992
* 3.
@note preventing text to be condensed
author J. Renée Beach
@see https://medium.com/@jessebeach/beware-smushed-off-screen-accessible-text-5952a4c2cbfe
@note Drupal 8 goes with word-wrap: normal instead
@see https://www.drupal.org/node/2045151
@see http://cgit.drupalcode.org/drupal/commit/?id=5b847ea
* 4.
@note !important is important
@note Obviously you wanna hide something
@author Harry Roberts
@see https://csswizardry.com/2016/05/the-importance-of-important/
*/
.sr-only {
border: 0 !important;
clip: rect(1px, 1px, 1px, 1px) !important; /* 1 */
-webkit-clip-path: inset(50%) !important;
clip-path: inset(50%) !important; /* 2 */
height: 1px !important;
margin: -1px !important;
overflow: hidden !important;
padding: 0 !important;
position: absolute !important;
width: 1px !important;
white-space: nowrap !important; /* 3 */
}
/*
Use in conjunction with .sr-only to only display content when it's focused.
@note Useful for skip links
@see http://www.w3.org/TR/2013/NOTE-WCAG20-TECHS-20130905/G1
@note Based on a HTML5 Boilerplate technique, included in Bootstrap
@note Fixed a bug with position: static on iOS 10.0.2 + VoiceOver
@author Sylvain Pigeard
@see https://github.com/twbs/bootstrap/issues/20732
*/
.sr-only-focusable:focus,
.sr-only-focusable:active {
clip: auto !important;
-webkit-clip-path: none !important;
clip-path: none !important;
height: auto !important;
margin: auto !important;
overflow: visible !important;
width: auto !important;
white-space: normal !important;
} | 34.769231 | 96 | 0.729646 |
939260dfa05604d2b59cb207ec8502592dfcea15 | 240 | cs | C# | Source/VulkaNetGenerator/GenStructs/GenEventCreateInfo.cs | Zulkir/VulkaNet | ef5a899a5c4db576be15ee9c50ee9218e7ea4a38 | [
"MIT"
] | 3 | 2016-07-24T07:24:36.000Z | 2017-11-20T17:35:02.000Z | Source/VulkaNetGenerator/GenStructs/GenEventCreateInfo.cs | Zulkir/VulkaNet | ef5a899a5c4db576be15ee9c50ee9218e7ea4a38 | [
"MIT"
] | null | null | null | Source/VulkaNetGenerator/GenStructs/GenEventCreateInfo.cs | Zulkir/VulkaNet | ef5a899a5c4db576be15ee9c50ee9218e7ea4a38 | [
"MIT"
] | null | null | null | using VulkaNetGenerator.Dummies;
namespace VulkaNetGenerator.GenStructs
{
public unsafe struct GenEventCreateInfo
{
public VkStructureType sType;
public void* pNext;
public VkEventCreateFlags flags;
}
} | 21.818182 | 43 | 0.7125 |
af9ffa2afa6f222eae7f47b0d9c40faec1abf95b | 763 | py | Python | app/adaptation/strategies/__init__.py | ManCla/TRAPP | 415dd302de0cf573584b57b6718cfed64380d353 | [
"MIT"
] | null | null | null | app/adaptation/strategies/__init__.py | ManCla/TRAPP | 415dd302de0cf573584b57b6718cfed64380d353 | [
"MIT"
] | null | null | null | app/adaptation/strategies/__init__.py | ManCla/TRAPP | 415dd302de0cf573584b57b6718cfed64380d353 | [
"MIT"
] | null | null | null | import app.Config as Config
from app.adaptation.strategies.AvoidOverloadedStreets import AvoidOverLoadedStreets
from app.adaptation.strategies.LoadBalancing import LoadBalancing
from app.adaptation.strategies.TunePlanningResolution import TunePlanningResolution
from app.adaptation.strategies.NoAdaptation import NoAdaptation
def get_adaptation_stategy(tick):
if Config.adaptation_strategy == "load_balancing":
return LoadBalancing(tick)
elif Config.adaptation_strategy == "avoid_overloaded_streets":
return AvoidOverLoadedStreets(tick)
elif Config.adaptation_strategy == "tune_planning_resolution":
return TunePlanningResolution(tick)
elif Config.adaptation_strategy == "no_adaptation":
return NoAdaptation(tick) | 47.6875 | 83 | 0.812582 |
5ba146e02a3d5a9129e4d180476e6d8005ff120e | 4,463 | css | CSS | css/style.css | RVCC-IDMX/about-me-Lori-A | ac30201649995e13c3f44a30e31ff8af4e8622d3 | [
"W3C"
] | null | null | null | css/style.css | RVCC-IDMX/about-me-Lori-A | ac30201649995e13c3f44a30e31ff8af4e8622d3 | [
"W3C"
] | null | null | null | css/style.css | RVCC-IDMX/about-me-Lori-A | ac30201649995e13c3f44a30e31ff8af4e8622d3 | [
"W3C"
] | null | null | null | body{
background-color: #FFE378;
background-image: linear-gradient( #FFE378,#3DB1E0,#5CFFE6, grey);
}
header{
border: solid;
text-align: center;
background-image: url(/img/cherryblossoms.png);
background-size: auto;
}
header img {
margin-top:2em;
}
h1{
font-family: "Bungee Inline";
color: black;
}
h2{
color: #94530A;
font-family: "Oleo Script";
font-size: 50px;
text-align:center;
text-decoration: underline;
}
p{
font-family: "Oleo Script";
}
img{
background-color: #5CFFE6;
border:ridge #94530A;
box-shadow: 2px 3px 10px #94530A;
}
#hobbies
{
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
}
#hobbies ul {
padding:0px;
}
#hobbies ul li {
list-style: none;
margin:0px;
border: 5px solid #5CFFE6;
padding: 30px;
max-width: 100px;
margin-bottom: 30px;
background-image: url(/img/sky.jpg);
background-size: auto;
background-position: center;
box-shadow: 5px 2px 10px #94530A;
transition-duration: 2s;
}
#hobbies ul li:hover {
background-color: #FFE378;
transition-duration:2s;
color: #94530A;
transform: scale(1.5);
}
#hero, footer{
text-align: center;
border: 10px double #FFE378;
padding: 10px;
border-top-left-radius: 90px;
border-bottom-right-radius: 90px;
box-shadow: 5px 2px 5px #94530A;
}
#hero img{
text-align: center;
width: 200px;
}
#bio{
text-align: center;
}
#gallery{
text-align: center;
}
#gallery img{
width:450px;
max-width: 100%;
}
#gallery figure{
margin:0px;
margin-bottom: 95px;
margin-top: 95px;
display: inline-block;
}
#gallery figcaption{
color: #94530A;
font-size: 20px;
max-width:100%;
text-align: center;
border: black 5px double ;
box-shadow: 5px 3px 5px #94530A;
padding-top: 5px;
padding-bottom:5px;
margin: 3px 5px 2px;
}
/* Articel*/
article p :nth-child(odd)::first-letter{
padding: 1rem;
padding-top:0rem;
max-width: 600px;
text-align: justify;
}
/* drop caps*/
article p::first-letter
{
color:black;
font-size: 200%;
border: 5px double black;
padding-left: 3px;
padding-right: 3px;
float: left;
margin-right: 3px;
margin-bottom: 1ex;
clear: both;
margin: 10px;
background-color: blanchedalmond;
background-image: radial-gradient( #94530A,#5CFFE6,#FFE378);
box-shadow: 6px 4px 5px black;
}
/* tablet state*/
@media screen and (min-width: 960px) {
#gallery figure{
display:grid;
grid-template-columns: 1fr 2fr;
}
#gallery figcaption{
display:flex;
justify-content: center;
align-items: center;
font-size: 2rem;
margin-left: 1rem;
}
#lit{
max-width: 100%;
columns: 40rem;
}
}
#lit {
color: #94530A;
}
#video {
text-align: center;
}
#video iframe {
max-width:100%;
}
#contact {
text-align: center;
max-width:400px;
margin-left:auto;
margin-right:auto;
}
#contact label {
display:inline;
}
#contact input[type="text"],
#contact input[type="tel"],
#contact input[type="email"]
{
width:100%;
}
#contact fieldset
{
color:#5CFFE6;
}
#contact ul {
list-style: none;
}
#contact legend{
text-align: center;
}
@media screen and (min-width:100em) {
#gallery {
padding:0px;
margin:0px;
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
#gallery hr {
display: none;
}
#gallery h2 {
grid-column: 1/-1;
}
#gallery figure {
display:block;
}
#gallery figcaption {
width:90%;
margin:auto;
}
}
#flower img{
height: 10em;
background-color: #FFE378;
animation-name: flower;
animation-duration: 4s;
animation-iteration-count:infinite;
}
#flower{
text-align: center;
}
@keyframes flower{
from{background-color: #FFE378;}
to {background-color: #94530A;}
}
#contact input, #contact textarea, #contact select{
margin-bottom: 1em;
}
#contact textarea{
display: block;
width:100%;
}
#flower img{
align-items: center;
}
#flower figcaption{
margin-top: 5px;
}
| 15.604895 | 70 | 0.580103 |
9ff1cb297c75f3c505517d969fa7ab0021da547b | 651 | py | Python | Auto.py | sidhantp1906/Automation-with-python | c79f55aa662ce14621f9ecbb6be8c6a021ed6930 | [
"MIT"
] | null | null | null | Auto.py | sidhantp1906/Automation-with-python | c79f55aa662ce14621f9ecbb6be8c6a021ed6930 | [
"MIT"
] | null | null | null | Auto.py | sidhantp1906/Automation-with-python | c79f55aa662ce14621f9ecbb6be8c6a021ed6930 | [
"MIT"
] | null | null | null | import openpyxl as xl
from openpyxl.chart import BarChart,Reference
wb = xl.load_workbook('transactions.xlsx')
sheet = wb['Sheet1']
cell = sheet['a1']
cell = sheet.cell(2, 1)
print(cell.value)
print(sheet.max_row)
for row in range(2,sheet.max_row + 1):
cell = sheet.cell(row,3)
corrected_value = cell.value * 0.9
corrected_val_cell = sheet.cell(row,4)
corrected_val_cell.value = corrected_value
print(cell.value)
values = Reference(sheet,min_row = 2,max_row = sheet.max_row,min_col = 4,max_col = 4 )
chart = BarChart()
chart.add_data(values)
sheet.add_chart(chart,'e2')
wb.save('transactions2.xlsx')
| 25.038462 | 87 | 0.695853 |
6aded719cdcaf302049aa8eb060075bb113a2bae | 3,449 | h | C | Engine/Plugins/Media/PixelStreaming/Source/PixelStreaming/Public/PixelStreamerInputComponent.h | denfrost/UE5MainStreaming | b16e03a9bf01987d390f066f500bcff4b75ea790 | [
"MIT"
] | 2 | 2021-11-26T13:33:32.000Z | 2021-12-31T08:52:21.000Z | Engine/Plugins/Media/PixelStreaming/Source/PixelStreaming/Public/PixelStreamerInputComponent.h | denfrost/UE5MainStreaming | b16e03a9bf01987d390f066f500bcff4b75ea790 | [
"MIT"
] | null | null | null | Engine/Plugins/Media/PixelStreaming/Source/PixelStreaming/Public/PixelStreamerInputComponent.h | denfrost/UE5MainStreaming | b16e03a9bf01987d390f066f500bcff4b75ea790 | [
"MIT"
] | 1 | 2021-10-11T10:05:52.000Z | 2021-10-11T10:05:52.000Z | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Components/ActorComponent.h"
#include "PixelStreamerInputComponent.generated.h"
class IPixelStreamingModule;
/**
* This component may be attached to an actor to allow UI interactions to be
* handled as the delegate will be notified about the interaction and will be
* supplied with a generic descriptor string containing, for example, JSON data.
* Responses back to the source of the UI interactions may also be sent.
*/
UCLASS(Blueprintable, ClassGroup = (PixelStreamer), meta = (BlueprintSpawnableComponent))
class PIXELSTREAMING_API UPixelStreamerInputComponent : public UActorComponent
{
GENERATED_BODY()
public:
UPixelStreamerInputComponent();
void BeginPlay() override;
void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
// The delegate which will be notified about a UI interaction.
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnInput, const FString&, Descriptor);
UPROPERTY(BlueprintAssignable, Category = "PixelStreamer Input")
FOnInput OnInputEvent;
/**
* Run a built-in command. The commands are defined by a JSON descriptor.
* The currently supported commands are:
*
* 1. A command to run any console command:
* "{ ConsoleCommand: <string> }"
*
* 2. A command to change the resolution to the given width and height.
* "{ Resolution: { Width: <value>, Height: <value> } }"
*
* @param Descriptor - The command JSON descriptor.
* @return True if the command was successfully executed.
*/
bool OnCommand(const FString& Descriptor);
/**
* Send a response back to the source of the UI interactions.
* @param Descriptor - A generic descriptor string.
*/
UFUNCTION(BlueprintCallable, Category = "PixelStreamer Input")
void SendPixelStreamingResponse(const FString& Descriptor);
/**
* Helper function to extract a string field from a JSON descriptor of a
* UI interaction given its field name.
* The field name may be hierarchical, delimited by a period. For example,
* to access the Width value of a Resolution command above you should use
* "Resolution.Width" to get the width value.
* @param Descriptor - The UI interaction JSON descriptor.
* @param FieldName - The name of the field to look for in the JSON.
* @param StringValue - The string value associated with the field name.
* @param Success - True if the field exists in the JSON data.
*/
UFUNCTION(BlueprintPure, Category = "PixelStreamer Input")
void GetJsonStringValue(FString Descriptor, FString FieldName, FString& StringValue, bool& Success);
/**
* Helper function to add a string field to a JSON descriptor. This produces
* a new descriptor which may then be chained to add further string fields.
* @param Descriptor - The initial JSON descriptor which may be blank initially.
* @param FieldName - The name of the field to add to the JSON.
* @param StringValue - The string value associated with the field name.
* @param NewDescriptor - The JSON descriptor with the string field added.
* @param Success - True if the string field could be added successfully.
*/
UFUNCTION(BlueprintPure, Category = "PixelStreamer Input")
void AddJsonStringValue(const FString& Descriptor, FString FieldName, FString StringValue, FString& NewDescriptor, bool& Success);
private:
// For convenience we keep a reference to the Pixel Streaming plugin.
IPixelStreamingModule* PixelStreamingModule;
};
| 41.059524 | 131 | 0.756451 |
eb82d6f2734f9120c4e7cf409f9a5656ecf2046c | 306 | css | CSS | public/css/forms.css | nicolevest/invato | edad89a29130627be505dc69446f7c30fa4facc7 | [
"MIT"
] | null | null | null | public/css/forms.css | nicolevest/invato | edad89a29130627be505dc69446f7c30fa4facc7 | [
"MIT"
] | null | null | null | public/css/forms.css | nicolevest/invato | edad89a29130627be505dc69446f7c30fa4facc7 | [
"MIT"
] | null | null | null | .formulario{
display: block;
background-color: rgba(91, 4, 5,70%);
margin-top:2em;
text-align: center;
}
/* h2{
position: fixed;
} */
.campo{
margin-top: 1em;
margin-bottom: 1em;
color: #FFF;
}
label{
color: #FFF;
font-weight: bolder;
}
.titulo{
color: #FFF;
font-weight: bolder;
}
| 13.304348 | 39 | 0.614379 |
2ca95ab3cfeb727ffc2b331f8f059890d45e5faf | 1,214 | py | Python | tests/resources/test_sns_topic_policy.py | donatoaz/pycfmodel | 1586e290b67d2347493dd4a77d2b0c8ee6c0936b | [
"Apache-2.0"
] | 23 | 2018-06-28T10:45:01.000Z | 2021-05-07T11:12:39.000Z | tests/resources/test_sns_topic_policy.py | donatoaz/pycfmodel | 1586e290b67d2347493dd4a77d2b0c8ee6c0936b | [
"Apache-2.0"
] | 27 | 2019-03-09T08:33:22.000Z | 2022-03-03T14:59:11.000Z | tests/resources/test_sns_topic_policy.py | donatoaz/pycfmodel | 1586e290b67d2347493dd4a77d2b0c8ee6c0936b | [
"Apache-2.0"
] | 7 | 2019-03-09T02:18:18.000Z | 2021-07-22T20:33:09.000Z | import pytest
from pycfmodel.model.resources.sns_topic_policy import SNSTopicPolicy
from pycfmodel.model.utils import OptionallyNamedPolicyDocument
@pytest.fixture()
def sns_topic_policy():
return SNSTopicPolicy(
**{
"Type": "AWS::SNS::TopicPolicy",
"Properties": {
"PolicyDocument": {
"Id": "MyTopicPolicy",
"Version": "2012-10-17",
"Statement": {
"Sid": "My-statement-id",
"Effect": "Allow",
"Principal": "*",
"Action": "sns:Publish",
"Resource": "*",
},
},
"Topics": [{"Ref": "MySNSTopic"}],
},
}
)
def test_sns_topic_policy(sns_topic_policy):
assert len(sns_topic_policy.Properties.Topics) == 1
assert sns_topic_policy.Properties.PolicyDocument.Statement.Effect == "Allow"
def test_sns_policy_documents(sns_topic_policy):
assert sns_topic_policy.policy_documents == [
OptionallyNamedPolicyDocument(name=None, policy_document=sns_topic_policy.Properties.PolicyDocument)
]
| 31.128205 | 108 | 0.551895 |
d68666c2533ec945af0d4b7765e27e775268cb70 | 3,494 | dart | Dart | packages/conduit/tool/generated_test_runner.dart | anycode/conduit | f3baca4b1d4f2f24e542d7e12859d6ab6d6ffcb3 | [
"BSD-2-Clause"
] | null | null | null | packages/conduit/tool/generated_test_runner.dart | anycode/conduit | f3baca4b1d4f2f24e542d7e12859d6ab6d6ffcb3 | [
"BSD-2-Clause"
] | null | null | null | packages/conduit/tool/generated_test_runner.dart | anycode/conduit | f3baca4b1d4f2f24e542d7e12859d6ab6d6ffcb3 | [
"BSD-2-Clause"
] | null | null | null | import 'dart:async';
import 'dart:io';
import 'package:conduit_runtime/runtime.dart';
Future main(List<String> args) async {
final conduitDir = Directory.current.uri;
final blacklist = [
(String s) => s.contains('test/command/'),
(String s) => s.contains('/compilation_errors/'),
(String s) => s.contains('test/openapi/'),
(String s) => s.contains('postgresql/migration/'),
(String s) => s.contains('db/migration/'),
(String s) => s.endsWith('entity_mirrors_test.dart'),
(String s) => s.endsWith('moc_openapi_test.dart'),
(String s) => s.endsWith('auth_documentation_test.dart'),
(String s) => s.endsWith('entity_mirrors_test.dart'),
(String s) => s.endsWith('cli/command_test.dart'),
];
List<File> testFiles;
if (args.length == 1) {
testFiles = [File(args.first)];
} else {
final testDir = args.isNotEmpty
? conduitDir.resolveUri(Uri.parse(args[0]))
: conduitDir.resolve('test/');
testFiles = Directory.fromUri(testDir)
.listSync(recursive: true)
.whereType<File>()
.where((f) => f.path.endsWith('_test.dart'))
.where((f) => blacklist.every(
(blacklistFunction) => blacklistFunction(f.uri.path) == false))
.toList();
}
var remainingCounter = testFiles.length;
final passingFiles = <File>[];
final failingFiles = <File>[];
for (var f in testFiles) {
final currentTime = DateTime.now();
final makePrompt = () =>
'(Pass: ${passingFiles.length} Fail: ${failingFiles.length} Remain: $remainingCounter)';
print('Running tests derived from ${f.path}...');
final ctx = BuildContext(
conduitDir.resolve('lib/').resolve('conduit.dart'),
Directory.current.uri.resolve('../').resolve('_build/'),
Directory.current.uri.resolve('../').resolve('run'),
File(conduitDir.resolve(f.path).path).readAsStringSync(),
forTests: true);
final bm = BuildManager(ctx);
await bm.build();
final result = await Process.start('dart', ['test/main_test.dart'],
workingDirectory:
ctx.buildDirectoryUri.toFilePath(windows: Platform.isWindows),
environment: {
'CONDUIT_CI_DIR_LOCATION': Directory.current.uri
.resolve('../../')
.resolve('ci/')
.toFilePath(windows: Platform.isWindows)
});
// ignore: unawaited_futures
stdout.addStream(result.stdout);
// ignore: unawaited_futures
stderr.addStream(result.stderr);
if (await result.exitCode != 0) {
exitCode = -1;
failingFiles.add(f);
print('Tests FAILED in ${f.path}.');
} else {
passingFiles.add(f);
}
final elapsed = DateTime.now().difference(currentTime);
remainingCounter--;
print(
'${makePrompt()} (${elapsed.inSeconds}s) Completed tests derived from ${f.path}.');
await bm.clean();
}
print('==============');
print('Result Summary');
print('==============');
final testRoot =
Directory.current.uri.resolve('../').resolve('conduit/').resolve('test/');
String stripParentDir(Uri uri) {
final testPathList = uri.pathSegments;
final parentDirPathList = testRoot.pathSegments;
final components = testPathList.skip(parentDirPathList.length - 1);
return components.join('/');
}
passingFiles.forEach((f) {
print(' ${stripParentDir(f.uri)}: success');
});
failingFiles.forEach((f) {
print(' ${stripParentDir(f.uri)}: FAILURE');
});
}
| 32.962264 | 96 | 0.618489 |
f46fc0a1cf684d0f183ea51a7ec271a118445b3a | 395 | ts | TypeScript | example/example.ts | ZachBray/stylus-to-typescript-converter | 6a75be4514ccb447edf1cf01445d9edbc2495497 | [
"MIT"
] | null | null | null | example/example.ts | ZachBray/stylus-to-typescript-converter | 6a75be4514ccb447edf1cf01445d9edbc2495497 | [
"MIT"
] | null | null | null | example/example.ts | ZachBray/stylus-to-typescript-converter | 6a75be4514ccb447edf1cf01445d9edbc2495497 | [
"MIT"
] | null | null | null | // This file was generated by stsc. Please do not edit by hand.
export const aFg = '#fff';
export const bBg = 'rgba(119, 134, 153, 0.59)';
export const aClass = {
fontFamily: 'Roboto',
fontSize: '14px',
fontWeight: '500',
lineHeight: '2.57',
color: aFg
};
export const bClass = {
fontFamily: 'Roboto',
fontSize: '14px',
fontWeight: '500',
lineHeight: '2.57',
color: bBg
}; | 19.75 | 63 | 0.637975 |
fa5493a80a3e558b8cf6d9dfb4f48e75ae6b7dca | 3,429 | rb | Ruby | spec/requests/carto/builder/datasets_controller_spec.rb | yuyf-fsd/cartodb | c19d6fd3bd0e26106dd8dd931e6570619dd629e7 | [
"BSD-3-Clause"
] | null | null | null | spec/requests/carto/builder/datasets_controller_spec.rb | yuyf-fsd/cartodb | c19d6fd3bd0e26106dd8dd931e6570619dd629e7 | [
"BSD-3-Clause"
] | 1 | 2020-04-27T00:59:05.000Z | 2020-04-27T00:59:05.000Z | spec/requests/carto/builder/datasets_controller_spec.rb | techonomics69/cartodb | d9f16023ecc8956810b3afe86cc1203817076ab3 | [
"BSD-3-Clause"
] | 1 | 2020-01-12T22:05:33.000Z | 2020-01-12T22:05:33.000Z | require_relative '../../../spec_helper'
describe Carto::Builder::DatasetsController do
include Warden::Test::Helpers
describe '#show' do
before(:all) do
CartoDB::UserModule::DBService.any_instance.stubs(:enable_remote_db_user).returns(true)
bypass_named_maps
@user = FactoryGirl.build(:valid_user, builder_enabled: true).save
@table = FactoryGirl.create(:carto_user_table, :full, user_id: @user.id, map: @map)
@map = @table.map
@visualization = @table.table_visualization
end
before(:each) do
login(@user)
end
after(:all) do
@visualization.destroy
@table.destroy
@map.destroy
CartoDB::UserModule::DBService.any_instance.stubs(:enable_remote_db_user).returns(true)
@user.destroy
@feature_flag.destroy
end
it 'redirects to public view non-builder users requests' do
@user.stubs(:builder_enabled).returns(false)
get builder_dataset_url(id: @visualization.id)
response.status.should eq 302
response.location.should end_with public_table_map_path(id: @visualization.id)
end
it 'returns 404 for non-existent visualizations' do
get builder_dataset_url(id: UUIDTools::UUID.timestamp_create.to_s)
response.status.should == 404
end
it 'redirects to public view for visualizations not writable by user' do
bypass_named_maps
@other_visualization = FactoryGirl.create(:carto_visualization, type: Carto::Visualization::TYPE_CANONICAL)
get builder_dataset_url(id: @other_visualization.id)
response.status.should eq 302
response.location.should end_with public_table_map_path(id: @other_visualization.id)
end
it 'returns visualization' do
get builder_dataset_url(id: @visualization.id)
response.status.should == 200
response.body.should include(@visualization.id)
end
it 'does not show derived visualizations' do
Carto::Visualization.any_instance.stubs(:type).returns(Carto::Visualization::TYPE_DERIVED)
get builder_dataset_url(id: @visualization.id)
response.status.should == 404
end
it 'does not show raster visualizations' do
Carto::Visualization.any_instance.stubs(:kind).returns(Carto::Visualization::KIND_RASTER)
get builder_dataset_url(id: @visualization.id)
response.status.should == 404
end
it 'does not include google maps if not configured' do
@map.provider = 'googlemaps'
@map.save
@user.google_maps_key = ''
@user.save
get builder_dataset_url(id: @visualization.id)
response.status.should == 200
response.body.should_not include("maps.google.com/maps/api/js")
end
it 'includes the google maps client id if configured' do
@map.provider = 'googlemaps'
@map.save
@user.google_maps_key = 'client=wadus_cid'
@user.save
get builder_dataset_url(id: @visualization.id)
response.status.should == 200
response.body.should include("maps.google.com/maps/api/js?client=wadus_cid")
end
it 'does not include google maps if the map does not need it' do
@map.provider = 'leaflet'
@map.save
@user.google_maps_key = 'client=wadus_cid'
@user.save
get builder_dataset_url(id: @visualization.id)
response.status.should == 200
response.body.should_not include("maps.google.com/maps/api/js")
end
end
end
| 30.891892 | 113 | 0.696996 |
8d58409b0004cbdd81a3379fa999dc68fe85a9a4 | 8,392 | rs | Rust | examples/server/service/snapshot.rs | PatrickNicholas/sdcons | 69e5790cbf54f2006bdb79a3da8b1af9d52fd249 | [
"Apache-2.0"
] | 3 | 2021-07-24T14:51:21.000Z | 2021-11-08T00:30:39.000Z | examples/server/service/snapshot.rs | w41ter-l/sdcons | 69e5790cbf54f2006bdb79a3da8b1af9d52fd249 | [
"Apache-2.0"
] | null | null | null | examples/server/service/snapshot.rs | w41ter-l/sdcons | 69e5790cbf54f2006bdb79a3da8b1af9d52fd249 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The sdcons Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex,
};
use base::proto::snapshot::*;
use tarpc::context;
use crate::node::{FileBasedSnapshotMeta, FileMeta};
#[derive(Debug)]
struct Channel {
url: String,
last_heartbeat_ns: i64,
next_resource_id: u32,
resource_chunk_meta: HashMap<u32, usize>,
resource_map: HashMap<u32, String>,
snapshot_meta: FileBasedSnapshotMeta,
}
#[derive(Debug)]
struct InnerService {
next_service_id: u32,
channels: HashMap<u32, Channel>,
}
#[derive(Debug, Clone)]
pub struct SnapshotService {
base_path: String,
inner: Arc<Mutex<InnerService>>,
}
impl SnapshotService {
pub fn new(base_path: String) -> SnapshotService {
SnapshotService {
base_path,
inner: Arc::new(Mutex::new(InnerService {
next_service_id: 1,
channels: HashMap::new(),
})),
}
}
pub fn setup_channel_recycle(&self) -> (Arc<AtomicBool>, std::thread::JoinHandle<()>) {
let exit_flags = Arc::new(AtomicBool::new(false));
let return_exit_flags = exit_flags.clone();
let inner = self.inner.clone();
let now = chrono::Local::now().timestamp_nanos();
let handler = std::thread::spawn(move || {
while !exit_flags.load(Ordering::Acquire) {
let mut inner_service = inner.lock().unwrap();
let timeout_channels = inner_service
.channels
.iter()
.filter(|(_id, c)| now - c.last_heartbeat_ns >= 1000 * 1000 * 1000 * 3) // 3s
.map(|(id, _c)| *id)
.collect::<Vec<_>>();
for channel_id in timeout_channels {
inner_service.channels.remove(&channel_id);
}
std::thread::sleep(std::time::Duration::from_secs(1));
}
});
(return_exit_flags, handler)
}
}
fn to_error_string<E: std::error::Error>(e: E) -> String {
format!("{}", e)
}
#[tarpc::server]
impl Snapshot for SnapshotService {
async fn connect(self, _: context::Context, url: String) -> Result<SnapshotDetail, String> {
let meta_name = format!("{}/META", url);
let meta_file = File::open(meta_name).map_err(to_error_string)?;
let meta: FileBasedSnapshotMeta =
serde_json::from_reader(&meta_file).map_err(to_error_string)?;
let channel = Channel {
url,
next_resource_id: 1,
last_heartbeat_ns: chrono::Local::now().timestamp_nanos(),
resource_chunk_meta: HashMap::new(),
resource_map: HashMap::new(),
snapshot_meta: meta.clone(),
};
let service_id = {
let mut inner_service = self.inner.lock().unwrap();
let service_id = inner_service.next_service_id;
inner_service.next_service_id += 1;
inner_service.channels.insert(service_id, channel);
service_id
};
let mut resources = meta
.files
.iter()
.map(|(k, _)| k.clone())
.collect::<Vec<_>>();
resources.push(String::from("META"));
Ok(SnapshotDetail {
ref_id: service_id,
checksum: meta.checksum,
applied_ids: meta
.desc
.channel_metas
.iter()
.map(|(c, m)| (*c, m.id))
.collect(),
resources,
})
}
async fn shutdown(self, _: context::Context, ref_id: u32) -> Option<()> {
let mut inner_service = self.inner.lock().unwrap();
if let None = inner_service.channels.remove(&ref_id) {
return None;
}
if inner_service.channels.is_empty() {
inner_service.next_service_id = 1;
}
Some(())
}
async fn open(self, _: context::Context, ref_id: u32, uri: String) -> Result<u64, String> {
let mut inner_service = self.inner.lock().unwrap();
let channel = match inner_service.channels.get_mut(&ref_id) {
Some(c) => c,
None => return Err(String::from("no such channel exists")),
};
channel.last_heartbeat_ns = chrono::Local::now().timestamp_nanos();
if channel.snapshot_meta.files.get(&uri).is_none() {
return Err(String::from("no such file exists"));
};
let resource_id = channel.next_resource_id;
channel.next_resource_id += 1;
channel.resource_chunk_meta.insert(resource_id, 0);
channel.resource_map.insert(resource_id, uri);
let global_resource_id = ((ref_id as u64) << 32) | (resource_id as u64);
Ok(global_resource_id)
}
async fn next(self, _: context::Context, resource_id: u64) -> Option<Vec<u8>> {
let local_resource_id = resource_id as u32;
let service_id = (resource_id >> 32) as u32;
let (uri, offset) = {
let mut inner_service = self.inner.lock().unwrap();
let channel = match inner_service.channels.get_mut(&service_id) {
Some(c) => c,
None => return None,
};
channel.last_heartbeat_ns = chrono::Local::now().timestamp_nanos();
let offset = match channel.resource_chunk_meta.get(&local_resource_id) {
Some(v) => v,
None => return None,
};
let uri = channel.resource_map.get(&local_resource_id).unwrap();
(uri.clone(), *offset)
};
let filename = format!("{}/{}", self.base_path, uri);
let mut file = match File::open(filename) {
Ok(f) => f,
Err(_) => return None,
};
match file.seek(SeekFrom::Start(offset as u64)) {
Ok(_) => (),
Err(_) => return None,
};
let mut buf = Vec::with_capacity(4096);
buf.resize(4096, 0);
loop {
let size = match file.read(&mut buf) {
Ok(v) => v,
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(_) => return None,
};
buf.resize(size, 0);
{
let mut inner_service = self.inner.lock().unwrap();
let channel = match inner_service.channels.get_mut(&service_id) {
Some(c) => c,
None => return None,
};
match channel.resource_chunk_meta.get_mut(&local_resource_id) {
Some(v) if *v == offset => *v += size,
_ => return None,
}
}
return Some(buf);
}
}
async fn close(self, _: context::Context, resource_id: u64) -> Option<ResourceMeta> {
let local_resource_id = resource_id as u32;
let service_id = (resource_id >> 32) as u32;
let mut inner_service = self.inner.lock().unwrap();
let channel = match inner_service.channels.get_mut(&service_id) {
Some(c) => c,
None => return None,
};
channel.last_heartbeat_ns = chrono::Local::now().timestamp_nanos();
if channel
.resource_chunk_meta
.remove(&local_resource_id)
.is_none()
{
return None;
}
let uri = channel.resource_map.get(&local_resource_id).unwrap();
let file_meta = channel.snapshot_meta.files.get(uri).unwrap();
Some(ResourceMeta {
resource_id,
checksum: file_meta.checksum,
size: 0,
uri: uri.clone(),
})
}
}
| 33.975709 | 97 | 0.555172 |
c3cddf43cf7f740e36caa60fabda5528814acb5f | 1,055 | cshtml | C# | Plugins/MVC/Aspose.MVC.ExportContentToImages/ExportContentToImages/Views/Shared/AsposeContentToImage.cshtml | Web-Dev-Collaborative/Aspose.Words-for-.NET | bf62ae46d38c0514485f47e9a0e6d295dcf818f1 | [
"MIT"
] | 310 | 2016-04-18T06:50:54.000Z | 2022-03-29T13:24:09.000Z | Plugins/MVC/Aspose.MVC.ExportContentToImages/ExportContentToImages/Views/Shared/AsposeContentToImage.cshtml | xinqinglhj/Aspose.Words-for-.NET | d9e31afc957f1240d93d55735482131ea92161fc | [
"MIT"
] | 34 | 2016-04-15T16:39:43.000Z | 2022-01-04T18:13:20.000Z | Plugins/MVC/Aspose.MVC.ExportContentToImages/ExportContentToImages/Views/Shared/AsposeContentToImage.cshtml | xinqinglhj/Aspose.Words-for-.NET | d9e31afc957f1240d93d55735482131ea92161fc | [
"MIT"
] | 149 | 2016-04-08T03:30:01.000Z | 2022-03-27T14:55:25.000Z |
<style>
.setDiv {
display: flex;
}
</style>
<div class="setDiv">
<select id="AsposeContentExportImagesTypes" class="form-control">
<option value="">Select an Export Format</option>
<option value="JPEG">JPEG Image format (*.jpeg)</option>
<option value="PNG">PNG Image format (*.png)</option>
<option value="BMP">BMP Image format (*.bmp)</option>
<option value="TIFF">TIFF Image format (*.tiff)</option>
</select>
<div class="Padding">
<a class="btn btn-primary" onclick=" redirect(); ">Export To Image</a>
</div>
</div>
<script type="text/javascript">
var result = "";
document.getElementById('AsposeContentExportImagesTypes').onchange = function ()
{
result = this.value;
}
function redirect() {
if (result != '') {
window.location.href = '@Url.Action("Index", "ExportToImage")/' + '?format=' + result;
} else {
alert("Please Select Export Format");
}
}
</script>
| 21.979167 | 98 | 0.565877 |
3ef93cded39bf7a9a6fca0ba6e0b30b094ddbb64 | 2,318 | swift | Swift | Example/AwesomeBubbles/ViewController.swift | chaucyzhang/AwesomeBubbles | db7b3753a72101923faf7a4134813960b396f41a | [
"MIT"
] | null | null | null | Example/AwesomeBubbles/ViewController.swift | chaucyzhang/AwesomeBubbles | db7b3753a72101923faf7a4134813960b396f41a | [
"MIT"
] | null | null | null | Example/AwesomeBubbles/ViewController.swift | chaucyzhang/AwesomeBubbles | db7b3753a72101923faf7a4134813960b396f41a | [
"MIT"
] | null | null | null | //
// ViewController.swift
// AwesomeBubbles
//
// Created by [email protected] on 09/26/2017.
// Copyright (c) 2017 [email protected]. All rights reserved.
//
import UIKit
import AwesomeBubbles
class ViewController: UIViewController, AwesomeBubbleContainerViewDelegate, AwesomeBubbleContainerViewDataSource {
@IBOutlet weak var contentView: AwesomeBubbleContainerView!
override func viewDidLoad() {
super.viewDidLoad()
self.contentView.delegate = self
self.contentView.dataSource = self
self.contentView.reload()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func minimalSizeForBubble(in view: AwesomeBubbleContainerView) -> CGSize {
return CGSize(width: 60.0, height: 60.0)
}
func maximumSizeForBubble(in view: AwesomeBubbleContainerView) -> CGSize {
return CGSize(width: 80.0, height: 80.0)
}
func AwesomeBubbleContainerView(_ view: AwesomeBubbleContainerView, didSelectItemAt index: Int) {
}
func countOfSizes(in view: AwesomeBubbleContainerView) -> Int {
return 3
}
func numberOfItems(in view: AwesomeBubbleContainerView) -> Int {
return 30
}
func addOrUpdateAwesomeBubble(forItemAt index: Int, currentView: AwesomeBubble?) -> AwesomeBubble {
var bubble: AwesomeBubble! = currentView
if bubble == nil {
if let customizedView = UINib(nibName: "CustomizedBubble", bundle: nil).instantiate(withOwner: nil, options: nil).first as? CustomizedBubble {
bubble = customizedView
bubble.backgroundColor = UIColor.clear
bubble.contentColor = UIColor.clear
bubble.borderColor = UIColor.darkGray
}
}
// let bubble:AwesomeBubble = AwesomeBubble()
let point = CGPoint(x:drand48() * Double(self.contentView.frame.size.width * 2 / 3), y:drand48() * Double(self.contentView.frame.size.height) * 2 / 3)
bubble.frame = CGRect(origin:point, size:CGSize.zero)
return bubble;
}
}
| 32.647887 | 158 | 0.653581 |
da52d595a22c0ab9f4692d653c5129fe3762c38c | 1,641 | php | PHP | app/User.php | cx783/topics | 29d1b37dd51264d3c5b439e3bcede3862d6fe8c1 | [
"MIT"
] | null | null | null | app/User.php | cx783/topics | 29d1b37dd51264d3c5b439e3bcede3862d6fe8c1 | [
"MIT"
] | 3 | 2021-03-09T20:07:04.000Z | 2022-02-18T12:45:36.000Z | app/User.php | cx783/topics | 29d1b37dd51264d3c5b439e3bcede3862d6fe8c1 | [
"MIT"
] | null | null | null | <?php
namespace App;
use App\Topic;
use App\Concern\HasTopics;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Silber\Bouncer\Database\HasRolesAndAbilities;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable, HasRolesAndAbilities, HasTopics, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function followers()
{
return $this->belongsToMany(User::class, 'followers', 'user_id', 'follower_id')
->withTimestamps();
}
public function follows()
{
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id')
->withTimestamps();
}
public function allFollows()
{
return User::where('id', '<>', $this->id)
->lastTopicDate()
->addSelect(['is_following' => function ($query) {
$query->selectRaw('count(*)')
->from('followers')
->whereColumn('user_id', 'users.id')
->where('follower_id', $this->id);
}]);
}
}
| 23.782609 | 87 | 0.575868 |
685cacae88d955a75232648195f9c9e10cf5dea5 | 2,473 | php | PHP | views/user/_form.php | agusedyc/letter-sig | 303e39b4df11d08db4f7ccfc7dcc99026cf79120 | [
"BSD-3-Clause"
] | null | null | null | views/user/_form.php | agusedyc/letter-sig | 303e39b4df11d08db4f7ccfc7dcc99026cf79120 | [
"BSD-3-Clause"
] | null | null | null | views/user/_form.php | agusedyc/letter-sig | 303e39b4df11d08db4f7ccfc7dcc99026cf79120 | [
"BSD-3-Clause"
] | null | null | null | <?php
use kartik\switchinput\SwitchInput;
use kartik\widgets\Select2;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* @var $this yii\web\View */
/* @var $model app\models\User */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="user-form">
<div class="panel panel-default">
<div class="panel-body">
<?php $form = ActiveForm::begin([
'options' => [
// 'class' => 'form-horizontal',
'enctype' => 'multipart/form-data'
],
// 'fieldConfig' => [
// 'template' => "{label}\n<div class=\"col-lg-9\">{input}</div>\n<div class=\"col-sm-offset-3 col-lg-9\">{error}\n{hint}</div>",
// 'labelOptions' => ['class' => 'col-lg-3 control-label'],
// ],
]); ?>
<?= $form->field($model, 'nama_lengkap')->textInput() ?>
<?= $form->field($model, 'nip')->textInput() ?>
<?= $form->field($model, 'jabatan_id')->widget(Select2::classname(), [
'data' => $jabatan,
'options' => ['placeholder' => 'Select ...'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<?php if (!$model->isNewRecord) { ?>
<strong> Leave blank if not change password</strong>
<div class="ui divider"></div>
<?= $form->field($model, 'new_password') ?>
<?= $form->field($model, 'repeat_password') ?>
<?php } else { ?>
<?= $form->field($model, 'password')->textInput(['maxlength' => true]) ?>
<?php } ?>
<small class="label pull-right bg-orange">Only .p12</small>
<?= $form->field($model, 'certificate')->fileInput() ?>
<?= $form->field($model, 'status')->widget(SwitchInput::classname(), [
'pluginOptions' => [
'onText' => 'Active',
'offText' => 'Banned',
]
]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
| 33.418919 | 158 | 0.451274 |
87b0a134ab1365055680d5f39264c539df98d2d3 | 2,450 | swift | Swift | TempiBeatDetection/TempiUtilities.swift | jasonmarkperez/TempiBeatDetection | c5e747155f67626135919c51701184e75d5caa52 | [
"MIT"
] | 36 | 2017-06-09T09:42:59.000Z | 2022-02-16T21:35:51.000Z | TempiBeatDetection/TempiUtilities.swift | jasonmarkperez/TempiBeatDetection | c5e747155f67626135919c51701184e75d5caa52 | [
"MIT"
] | null | null | null | TempiBeatDetection/TempiUtilities.swift | jasonmarkperez/TempiBeatDetection | c5e747155f67626135919c51701184e75d5caa52 | [
"MIT"
] | 13 | 2017-05-16T15:18:51.000Z | 2021-12-23T14:43:56.000Z | //
// TempiUtilities.swift
// TempiBeatDetection
//
// Created by John Scalo on 1/8/16.
// Copyright © 2016 John Scalo. See accompanying License.txt for terms.
import Foundation
import Accelerate
func tempi_dispatch_delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
func tempi_is_power_of_2 (n: Int) -> Bool {
let lg2 = logbf(Float(n))
return remainderf(Float(n), powf(2.0, lg2)) == 0
}
func tempi_max(a: [Float]) -> Float {
var max: Float = 0.0
vDSP_maxv(a, 1, &max, UInt(a.count))
return max
}
func tempi_smooth(a: [Float], w: Int) -> [Float] {
var newA: [Float] = [Float]()
for i in 0..<a.count {
let realW = min(w, a.count - i)
var avg: Float = 0.0
let subArray: [Float] = Array(a[i..<i+realW])
vDSP_meanv(subArray, 1, &avg, UInt(realW))
newA.append(avg)
}
return newA
}
func tempi_median(a: [Float]) -> Float {
// I tried to make this an Array extension and failed. See below.
let sortedArray : [Float] = a.sort( { $0 < $1 } )
var median : Float
if sortedArray.count == 1 {
return sortedArray[0]
}
if sortedArray.count % 2 == 0 {
let f1 : Float = sortedArray[sortedArray.count / 2 - 1]
let f2 : Float = sortedArray[sortedArray.count / 2]
median = (f1 + f2) / 2.0
} else {
median = sortedArray[sortedArray.count / 2]
}
return median
}
func tempi_mean(a: [Float]) -> Float {
// Again, would be better as an Array extension.
var total : Float = 0
for (_, f) in a.enumerate() {
total += f
}
return total/Float(a.count)
}
//extension Array where Element : IntegerArithmeticType {
// func median() -> Float {
// let sortedArray : [Float] = a.sort( { $0 < $1 } )
// var median : Float
//
// if sortedArray.count == 1 {
// return sortedArray[0]
// }
//
// if sortedArray.count % 2 == 0 {
// let f1 : Float = sortedArray[sortedArray.count / 2 - 1]
// let f2 : Float = sortedArray[sortedArray.count / 2]
// median = (f1 + f2) / 2.0
// } else {
// median = sortedArray[sortedArray.count / 2]
// }
//
// return median
// }
//}
| 25.789474 | 72 | 0.550204 |
1a7faeacd83f1f044393b1b8c323eea332a2a1ec | 2,328 | py | Python | modern-infrastructure-wednesday/2020-05-06/gcp-py-functions/funcs.py | nimbinatus/pulumitv | 19477611afde5d00d90838956d3a7b1cc7c1f705 | [
"Apache-2.0"
] | 13 | 2020-05-09T17:37:06.000Z | 2022-01-09T06:26:19.000Z | modern-infrastructure-wednesday/2020-05-06/gcp-py-functions/funcs.py | nimbinatus/pulumitv | 19477611afde5d00d90838956d3a7b1cc7c1f705 | [
"Apache-2.0"
] | 28 | 2020-04-24T05:51:39.000Z | 2022-03-31T13:31:38.000Z | modern-infrastructure-wednesday/2020-05-06/gcp-py-functions/funcs.py | nimbinatus/pulumitv | 19477611afde5d00d90838956d3a7b1cc7c1f705 | [
"Apache-2.0"
] | 10 | 2020-03-24T19:29:52.000Z | 2021-06-18T11:01:21.000Z |
import time
import os
import pulumi
from pulumi_gcp import storage
from pulumi_gcp import cloudfunctions
# Disable rule for that module-level exports be ALL_CAPS, for legibility.
# pylint: disable=C0103
# File path to where the Cloud Function's source code is located.
PATH_TO_SOURCE_CODE = "./functions"
# Get values from Pulumi config to use as environment variables in our Cloud Function.
config = pulumi.Config(name=None)
config_values = {
# Target destination and travel time offset.
"DESTINATION": config.get("destination"),
"TRAVEL_OFFSET": config.get("travelOffset"),
# Google Maps API key.
"GOOGLE_MAPS_API_KEY": config.get("googleMapsApiKey"),
# Twilio account for sending SMS messages.
"TWILLIO_ACCESS_TOKEN": config.get("twillioAccessToken"),
"TWILLIO_ACCOUNT_SID": config.get("twillioAccountSid"),
"TO_PHONE_NUMBER": config.get("toPhoneNumber"),
"FROM_PHONE_NUMBER": config.get("fromPhoneNumber"),
}
# We will store the source code to the Cloud Function in a Google Cloud Storage bucket.
bucket = storage.Bucket("eta_demo_bucket")
# The Cloud Function source code itself needs to be zipped up into an
# archive, which we create using the pulumi.AssetArchive primitive.
assets = {}
for file in os.listdir(PATH_TO_SOURCE_CODE):
location = os.path.join(PATH_TO_SOURCE_CODE, file)
asset = pulumi.FileAsset(path=location)
assets[file] = asset
archive = pulumi.AssetArchive(assets=assets)
# Create the single Cloud Storage object, which contains all of the function's
# source code. ("main.py" and "requirements.txt".)
source_archive_object = storage.BucketObject(
"eta_demo_object",
name="main.py-%f" % time.time(),
bucket=bucket.name,
source=archive)
# Create the Cloud Function, deploying the source we just uploaded to Google
# Cloud Storage.
fxn = cloudfunctions.Function(
"eta_demo_function",
entry_point="get_demo",
environment_variables=config_values,
region="us-central1",
runtime="python37",
source_archive_bucket=bucket.name,
source_archive_object=source_archive_object.name,
trigger_http=True)
invoker = cloudfunctions.FunctionIamMember(
"invoker",
project=fxn.project,
region=fxn.region,
cloud_function=fxn.name,
role="roles/cloudfunctions.invoker",
member="allUsers",
)
| 31.890411 | 87 | 0.746134 |
7ab9697636197813ce80085f0b34e83bcaa0200c | 7,233 | cs | C# | src/FubuCore.Testing/Binding/Values/DictionaryValueSourceTester.cs | DovetailSoftware/fubucore | 6ea269b9edf2e58ff3ec207f6936bf6a163f4a8b | [
"Apache-2.0"
] | null | null | null | src/FubuCore.Testing/Binding/Values/DictionaryValueSourceTester.cs | DovetailSoftware/fubucore | 6ea269b9edf2e58ff3ec207f6936bf6a163f4a8b | [
"Apache-2.0"
] | 1 | 2020-07-01T22:22:13.000Z | 2020-11-11T18:18:59.000Z | src/FubuCore.Testing/Binding/Values/DictionaryValueSourceTester.cs | DovetailSoftware/fubucore | 6ea269b9edf2e58ff3ec207f6936bf6a163f4a8b | [
"Apache-2.0"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Linq;
using FubuCore.Binding;
using FubuCore.Binding.Values;
using FubuCore.Configuration;
using Moq;
using NUnit.Framework;
namespace FubuCore.Testing.Binding.Values
{
[TestFixture]
public class ValueSourceLoaderTester
{
[Test]
public void load_several_levels_of_nested_properties()
{
var source = new SettingsData(new Dictionary<string, object>(), "some name");
source["A"] = 1;
source["B"] = 2;
source["Child.A"] = 2;
source["Child.B"] = 3;
source["Child.Nested.A"] = 4;
source["Child.Nested.B"] = 5;
source.Get("A").ShouldEqual(1);
source.Get("B").ShouldEqual(2);
source.As<IValueSource>().GetChild("Child").Get("A").ShouldEqual(2);
source.As<IValueSource>().GetChild("Child").Get("B").ShouldEqual(3);
source.As<IValueSource>().GetChild("Child").GetChild("Nested").Get("A").ShouldEqual(4);
source.As<IValueSource>().GetChild("Child").GetChild("Nested").Get("B").ShouldEqual(5);
}
}
[TestFixture]
public class DictionaryValueSourceTester
{
private Dictionary<string, object> theDictionary;
private SettingsData theSource;
[SetUp]
public void SetUp()
{
theDictionary = new Dictionary<string, object>();
theSource = new SettingsData(theDictionary, "a name");
}
[Test]
public void has_the_name()
{
theSource.Provenance.ShouldEqual("a name");
}
[Test]
public void has()
{
theSource.Has("a").ShouldBeFalse();
theSource.Has("b").ShouldBeFalse();
theDictionary.Add("a", 1);
theSource.Has("a").ShouldBeTrue();
theSource.Has("b").ShouldBeFalse();
}
[Test]
public void get()
{
theDictionary.Add("a", 1);
theDictionary.Add("b", 2);
theSource.Get("a").ShouldEqual(1);
theSource.Get("b").ShouldEqual(2);
}
[Test]
public void has_child()
{
var child = new Dictionary<string, object>();
theDictionary.Add("a", "something");
theDictionary.Add("child", child);
theSource.HasChild("a").ShouldBeFalse();
theSource.HasChild("random").ShouldBeFalse();
theSource.HasChild("child").ShouldBeTrue();
}
[Test]
public void get_child_when_it_already_exists()
{
var child = new Dictionary<string, object>();
theDictionary.Add("a", "something");
theDictionary.Add("child", child);
child.Add("abc", 123);
var childValueSource = theSource.As<IValueSource>().GetChild("child");
childValueSource.Get("abc").ShouldEqual(123);
}
[Test]
public void get_child_when_it_does_not_exist()
{
var childValueSource = theSource.As<IValueSource>().GetChild("child");
childValueSource.ShouldNotBeNull().ShouldBeOfType<SettingsData>()
.Provenance.ShouldEqual("a name.child");
// It's idempotent on the add
theSource.As<IValueSource>().GetChild("child").ShouldEqual(childValueSource);
}
[Test]
public void get_child_name()
{
var child = new Dictionary<string, object>();
theDictionary.Add("child", child);
var childValueSource = theSource.As<IValueSource>().GetChild("child");
childValueSource.Provenance.ShouldEqual(theSource.Provenance + ".child");
}
[Test]
public void get_children_when_there_are_none()
{
theSource.As<IValueSource>().GetChildren("nonexistent").Any().ShouldBeFalse();
}
[Test]
public void get_children_when_there_are_children()
{
var list = new List<IDictionary<string, object>>(){
new Dictionary<string, object>(),
new Dictionary<string, object>(),
new Dictionary<string, object>()
};
list[0].Add("a", 0);
list[1].Add("a", 1);
list[2].Add("a", 2);
theDictionary.Add("list", list);
var children = theSource.As<IValueSource>().GetChildren("list");
children.Count().ShouldEqual(3);
children.ElementAt(0).Get("a").ShouldEqual(0);
children.ElementAt(1).Get("a").ShouldEqual(1);
children.ElementAt(2).Get("a").ShouldEqual(2);
}
[Test]
public void get_children_when_there_are_children_name()
{
var list = new List<IDictionary<string, object>>(){
new Dictionary<string, object>(),
new Dictionary<string, object>(),
new Dictionary<string, object>()
};
list[0].Add("a", 0);
list[1].Add("a", 1);
list[2].Add("a", 2);
theDictionary.Add("list", list);
var children = theSource.As<IValueSource>().GetChildren("list");
children.Count().ShouldEqual(3);
children.ElementAt(0).Provenance.ShouldEqual("a name.list[0]");
children.ElementAt(1).Provenance.ShouldEqual("a name.list[1]");
children.ElementAt(2).Provenance.ShouldEqual("a name.list[2]");
}
[Test]
public void value_miss()
{
theSource.As<IValueSource>().Value("nonexistent", x => Assert.Fail("Should not call this")).ShouldBeFalse();
}
[Test]
public void value_hit_at_top_level()
{
var action = new Mock<Action<BindingValue>>();
theDictionary.Add("a", 1);
theSource.As<IValueSource>().Value("a", action.Object).ShouldBeTrue();
action.Verify(x => x.Invoke(new BindingValue(){
RawKey = "a",
RawValue = 1,
Source = theSource.Provenance
}));
}
[Test]
public void can_retrieve_a_child_element()
{
var child2 = theSource.GetChildrenElement("children", 2);
var child1 = theSource.GetChildrenElement("children", 1);
var child0 = theSource.GetChildrenElement("children", 0);
child0.Set("a", 0);
child1.Set("a", 1);
child2.Set("a", 2);
theSource.GetChildrenElement("children", 2).Set("b", 22);
theDictionary.Children("children").ElementAt(0)["a"].ShouldEqual(0);
theDictionary.Children("children").ElementAt(1)["a"].ShouldEqual(1);
theDictionary.Children("children").ElementAt(2)["a"].ShouldEqual(2);
theDictionary.Children("children").ElementAt(2)["b"].ShouldEqual(22);
}
}
} | 32.877273 | 121 | 0.533665 |
f447f73ce8edbcb34ca56ace49f4d7c1a901e5ac | 2,272 | ts | TypeScript | src/routes/spaces.ts | ianleon/production-saas | f9f14ebf7af4dc35b5116c9c37519a761d319473 | [
"MIT"
] | null | null | null | src/routes/spaces.ts | ianleon/production-saas | f9f14ebf7af4dc35b5116c9c37519a761d319473 | [
"MIT"
] | null | null | null | src/routes/spaces.ts | ianleon/production-saas | f9f14ebf7af4dc35b5116c9c37519a761d319473 | [
"MIT"
] | null | null | null | import { compose } from 'worktop';
import * as Space from 'lib/models/space';
import * as User from 'lib/models/user';
import * as utils from 'lib/utils';
/**
* GET /spaces
* @requires Authentication
*/
export const list = compose(
User.authenticate,
async function (req, context) {
const IDs = await Space.list(context.user!);
const rows = await Promise.all(IDs.map(Space.find));
let i=0, output=[];
for (; i < rows.length; i++) {
if (rows[i]) output.push(
Space.output(rows[i] as Space.Space)
);
}
return utils.send(200, output);
}
);
/**
* POST /spaces
* @requires Authentication
*/
export const create = compose(
User.authenticate,
async function (req, context) {
const input = await utils.body<{ name?: string }>(req);
const name = input && input.name && input.name.trim();
if (!name) {
return utils.send(400, 'TODO: port over validation lib');
}
const doc = await Space.insert({ name }, context.user!);
if (!doc) return utils.send(500, 'Error creating document');
const output = Space.output(doc);
return utils.send(201, output);
}
);
/**
* GET /spaces/:spaceid
* @requires Authentication,Ownership
*/
export const show = compose(
User.authenticate,
Space.load, Space.isAuthorized,
function (req, context) {
const space = context.space!;
return utils.send(200, Space.output(space));
}
);
/**
* PUT /spaces/:spaceid
* @requires Authentication,Ownership
*/
export const update = compose(
User.authenticate,
Space.load, Space.isAuthorized,
async function (req, context) {
const input = await utils.body<{ name?: string }>(req);
const name = input && input.name && input.name.trim();
if (!name) return utils.send(400, 'TODO: port over validation lib');
const doc = await Space.update(context.space!, { name });
if (doc) return utils.send(200, Space.output(doc));
return utils.send(500, 'Error updating document');
}
);
/**
* DELETE /spaces/:spaceid
* @requires Authentication,Ownership
*/
export const destroy = compose(
User.authenticate,
Space.load, Space.isAuthorized,
async function (req, context) {
const { user, space } = context;
if (await Space.destroy(space!, user!)) return utils.send(204);
return utils.send(500, 'Error while destroying Space');
}
);
| 24.170213 | 70 | 0.671655 |
6b232a78835d71cf5bea3b09d97895d2bf22b521 | 1,061 | kt | Kotlin | android/src/main/kotlin/com/usercentrics/sdk/flutter/bridge/SaveOptOutForCCPABridge.kt | Usercentrics/usercentrics-flutter-sdk | ee756905c5a029bd9d1d7c06fdd0726c1ad0e20a | [
"Apache-2.0"
] | 1 | 2022-01-21T11:00:49.000Z | 2022-01-21T11:00:49.000Z | android/src/main/kotlin/com/usercentrics/sdk/flutter/bridge/SaveOptOutForCCPABridge.kt | Usercentrics/usercentrics-flutter-sdk | ee756905c5a029bd9d1d7c06fdd0726c1ad0e20a | [
"Apache-2.0"
] | 1 | 2021-10-29T18:26:00.000Z | 2021-11-04T13:07:55.000Z | android/src/main/kotlin/com/usercentrics/sdk/flutter/bridge/SaveOptOutForCCPABridge.kt | Usercentrics/usercentrics-flutter-sdk | ee756905c5a029bd9d1d7c06fdd0726c1ad0e20a | [
"Apache-2.0"
] | 1 | 2022-01-19T18:21:26.000Z | 2022-01-19T18:21:26.000Z | package com.usercentrics.sdk.flutter.bridge
import com.usercentrics.sdk.flutter.api.FlutterMethodCall
import com.usercentrics.sdk.flutter.api.FlutterResult
import com.usercentrics.sdk.flutter.api.UsercentricsProxy
import com.usercentrics.sdk.flutter.api.UsercentricsProxySingleton
import com.usercentrics.sdk.flutter.serializer.serialize
import com.usercentrics.sdk.models.settings.UsercentricsConsentType
internal class SaveOptOutForCCPABridge(
private val usercentrics: UsercentricsProxy = UsercentricsProxySingleton
) : MethodBridge {
override val name: String
get() = "saveOptOutForCCPA"
override fun invoke(call: FlutterMethodCall, result: FlutterResult) {
assert(name == call.method)
val argsMap = call.arguments as Map<*, *>
val consents = usercentrics.instance.saveOptOutForCCPA(
isOptedOut = argsMap["isOptedOut"] as Boolean,
consentType = UsercentricsConsentType.valueOf(argsMap["consentType"] as String)
)
result.success(consents.map { it.serialize() })
}
} | 39.296296 | 91 | 0.756833 |
0af712883ae99c2d8586e434ac6402b53a74319c | 4,364 | cs | C# | LivelogsPlayerStatParser/Menu.cs | Paymh/LivelogsPlayerStatParser | 52b4bbed005793c75e426d8188bb5732c66ddc56 | [
"MIT"
] | null | null | null | LivelogsPlayerStatParser/Menu.cs | Paymh/LivelogsPlayerStatParser | 52b4bbed005793c75e426d8188bb5732c66ddc56 | [
"MIT"
] | null | null | null | LivelogsPlayerStatParser/Menu.cs | Paymh/LivelogsPlayerStatParser | 52b4bbed005793c75e426d8188bb5732c66ddc56 | [
"MIT"
] | 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 System.Net;
namespace LivelogsPlayerStatParser
{
public partial class Menu : Form
{
public Menu()
{
InitializeComponent();
lstLogsTracked.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
}
private void btnExportExcel_Click(object sender, EventArgs e)
{
ExcelHandler.CreateExcel();
ExcelHandler.ShowExcel();
List<Log> logsToOutput = new List<Log>();
foreach (ListViewItem item in lstLogsTracked.Items)
{
if (item.Checked)
logsToOutput.Add(LogHandler.logsTracked[item.Index]);
}
if (chkAverageOutput.Checked)
ExcelHandler.OutputExcel(false);
else
ExcelHandler.OutputExcel(true);
}
private void btnParseLog_Click(object sender, EventArgs e)
{
if (txtLogUri.Text != "")
{
if (txtLogWeighting.Text == "")
txtLogWeighting.Text = "0.5";
bool result = LogHandler.ParseLog(txtLogUri.Text, Convert.ToDouble(txtLogWeighting.Text));
if (result)
{
fillListView();
}
}
}
private void fillListView()
{
lstLogsTracked.Items.Clear();
foreach (Log log in LogHandler.logsTracked)
{
ListViewItem item = new ListViewItem();
item.SubItems[0].Text = log.URL.Replace(@"http://livelogs.ozfortress.com/view/", "");
item.SubItems.Add(log.dateTime.ToString());
item.SubItems.Add(log.Map);
item.SubItems.Add(log.Weighting.ToString());
lstLogsTracked.Items.Add(item);
}
lstLogsTracked.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
}
private void btnClearHistory_Click(object sender, EventArgs e)
{
LogHandler.logsTracked.Clear();
lstLogsTracked.Items.Clear();
}
private void btnRemoveLogs_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in lstLogsTracked.Items)
{
if (item.Checked)
{
LogHandler.logsTracked.RemoveAt(item.Index);
item.Remove();
}
}
}
private void btnOpenHistory_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.InitialDirectory = System.IO.Directory.GetCurrentDirectory();
dialog.Filter = "Config files | *.cfg";
if (dialog.ShowDialog() == DialogResult.OK)
{
LogHandler.logsTracked.Clear();
lstLogsTracked.Items.Clear();
foreach (String line in System.IO.File.ReadAllLines(dialog.FileName))
{
string[] temp = line.Split(' ');
LogHandler.ParseLog(temp[0], Convert.ToDouble(temp[1]));
}
fillListView();
}
}
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Config files | *.cfg";
dialog.InitialDirectory = System.IO.Directory.GetCurrentDirectory();
if (dialog.ShowDialog() == DialogResult.OK)
{
String output = "";
foreach (Log log in LogHandler.logsTracked)
{
output += log.URL + " " + log.Weighting + "\r\n";
}
System.IO.File.WriteAllText(dialog.FileName, output);
}
}
private void chkFullOutput_CheckedChanged(object sender, EventArgs e)
{
chkAverageOutput.Checked = !chkFullOutput.Checked;
}
private void chkAverageOutput_CheckedChanged(object sender, EventArgs e)
{
chkFullOutput.Checked = !chkAverageOutput.Checked;
}
}
}
| 34.09375 | 106 | 0.542621 |
2fe5e3ddcd011b63788bbf021557d32814aaffb8 | 6,389 | py | Python | de_course_downloader.py | vedangnaik/depp-utils | 134f40c331e2a9c722d6d99888dcafe7bfe32f93 | [
"MIT"
] | null | null | null | de_course_downloader.py | vedangnaik/depp-utils | 134f40c331e2a9c722d6d99888dcafe7bfe32f93 | [
"MIT"
] | null | null | null | de_course_downloader.py | vedangnaik/depp-utils | 134f40c331e2a9c722d6d99888dcafe7bfe32f93 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import requests
from pathlib import Path
import json
import argparse
import sys
import re
from constants import allCoursesRe, allProgramsRe, prerequisiteRe
getCourseInfoGETHeader = {
"Host": "degreeexplorer.utoronto.ca",
"Connection": "keep-alive",
"sec-ch-ua": '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
"Accept": "application/json, text/plain, */*",
"DNT": "1",
"sec-ch-ua-mobile": "?0",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Dest": "empty",
"Referer": "https://degreeexplorer.utoronto.ca/degreeExplorer/planner",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Cookie": ""
}
addCoursePOSTHeader = {
"Host": "degreeexplorer.utoronto.ca",
"Connection": "keep-alive",
"Content-Length": "0",
"sec-ch-ua": '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
"Accept": "application/json, text/plain, */*",
"DNT": "1",
"X-XSRF-TOKEN": "eYH6RC3MRwtk1RJfFsMbjTt1KBpsAcDC7wuTvHMJ+Uw=",
"sec-ch-ua-mobile": "?0",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36",
"Content-Type": "text/plain",
"Origin": "https://degreeexplorer.utoronto.ca",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Dest": "empty",
"Referer": "https://degreeexplorer.utoronto.ca/degreeExplorer/planner",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Cookie": ""
}
# Set up argument parsing
parser = argparse.ArgumentParser(description='Downloads course JSON objects from https://degreeexplorer.utoronto.ca/.')
parser.add_argument('cookie', type=str, help="cookie from a valid Degree Explorer session. To obtain this, log into DE with your UofT credentials, then copy the cookie from the Network tab of Chrome Devtools")
parser.add_argument('row_num', type=int, help="row num of DE timetable into which to add courses before download")
parser.add_argument('col_num', type=int, help="col num of DE timetable into which to add courses before download")
parser.add_argument('--c_jsons_dir', type=str, help="path to directory to store downloaded course JSONs. default: ./course_data", default="./course_data", metavar='dir')
parser.add_argument('--c_cc_ids_file', type=argparse.FileType('a'), help="path to ASCII file to store course categories from downloaded course JSONs. default: ./courses-course-category-ids.txt", default="./courses-course-category-ids.txt", metavar='file')
if __name__ == "__main__":
args = parser.parse_args()
print("Starting course download...")
# If a directory is indicated, create it if it doesn't exist.
if args.c_jsons_dir:
Path(args.c_jsons_dir).mkdir(exist_ok=True, parents=True)
# Load the cookies into the headers.
addCoursePOSTHeader["Cookie"] = args.cookie
getCourseInfoGETHeader["Cookie"] = args.cookie
# Status vars.
attempted = 0
successes = 0
skipped = []
failures = []
# Used to keep track of how many have failed in a row. If it's more than a threshold, the cookie has likely become invalid. Auto-quit at that point to stop hammering the server.
consecutive_failures = 0
# Loop through all courses.
for line in sys.stdin:
if consecutive_failures >= 20:
print(f"Detected {consecutive_failures} consecutive failures. This is likely because the cookie has become invalid. Quitting now to avoid unnecessary API calls.")
break
courseID = line.strip()
attempted += 1
print(f"{courseID} - Status: ", end="")
# Skip the course if we've already scraped it.
f = Path(f"{args.c_jsons_dir}/{courseID}.json")
if f.is_file():
skipped.append(courseID)
print("Skipped")
continue
# Add the course, then get it's info. Equivalent to adding it by hovering+typing, then seeing the information by clicking on the tile.
r = requests.post(f"https://degreeexplorer.utoronto.ca/degreeExplorer/rest/dxPlanner/saveCourseEntry?tabIndex=1&selRowIndex={args.row_num}&selColIndex={args.col_num}&newCourseCode={courseID}", headers=addCoursePOSTHeader)
if (r.status_code != 200):
failures.append(courseID)
consecutive_failures += 1
print("Failed")
continue
r = requests.get(f"https://degreeexplorer.utoronto.ca/degreeExplorer/rest/dxPlanner/getCellDetails?tabIndex=1&rowIndex={args.row_num}&colIndex={args.col_num}", headers=getCourseInfoGETHeader)
if (r.status_code != 200):
failures.append(courseID)
consecutive_failures += 1
print("Failed")
continue
thisCourseObj = r.json()
# Save the program info to file
with open(f"{args.c_jsons_dir}/{courseID}.json", 'w') as f:
json.dump(thisCourseObj, f, ensure_ascii=False, indent=2)
# Save any course categories from this one's exclusions, corequisites, and prerequisites
for category in ["prerequisites", "corequisites", "orderedExclusions"]:
for categoryObj in thisCourseObj[category]:
for requisiteItem in categoryObj["requisiteItems"]:
code = requisiteItem["code"]
# If the code isn't a course from any campus or a program or a prerequisite ID or empty, then it must be a course category
if not allCoursesRe.match(code) and not allProgramsRe.match(code) and not prerequisiteRe.match(code) and code != "":
args.c_cc_ids_file.write(code + "\n")
print("Succeeded")
consecutive_failures = 0 # Reset this.
successes += 1
# Print status information and exit.
print("Finished.")
print(f"Attempted to download {attempted} course(s) from Degree Explorer:")
print(f"\tSucceeded in downloading {successes} course(s)")
print(f"\tSkipped {len(skipped)} course(s) because they have already been scraped. Skipped: {skipped}")
print(f"\tFailed to download {len(failures)} course(s). Failures: {failures}") | 46.977941 | 255 | 0.668023 |
1a6812ef082046267361e612312abbd6008a8ca1 | 301 | cs | C# | InBusinessForTests/Data/Managers/Facade/ICustomerManager.cs | thor1824/Test_ReadyApi_Jenkins | 46d93ea03bfd866a5bc5943e73f416be0a4e27b7 | [
"Apache-2.0"
] | null | null | null | InBusinessForTests/Data/Managers/Facade/ICustomerManager.cs | thor1824/Test_ReadyApi_Jenkins | 46d93ea03bfd866a5bc5943e73f416be0a4e27b7 | [
"Apache-2.0"
] | null | null | null | InBusinessForTests/Data/Managers/Facade/ICustomerManager.cs | thor1824/Test_ReadyApi_Jenkins | 46d93ea03bfd866a5bc5943e73f416be0a4e27b7 | [
"Apache-2.0"
] | null | null | null | using System.Threading.Tasks;
using InBusinessForTests.Data.Model;
namespace InBusinessForTests.Data.Managers.Facade
{
public interface ICustomerManager
{
Task<BusinessResponse<Customer>> DeleteAsync(int id);
Task<BusinessResponse<Customer>> CreateAsync(string name);
}
} | 27.363636 | 66 | 0.750831 |
a385a303f41ae47ca92a93a3c0adea97c826ac8d | 1,350 | tsx | TypeScript | src/uniprotkb/components/protein-data-views/__tests__/UniProtEvidenceTag.spec.tsx | ebi-uniprot/uniprot-website | 2adc2d8529ef9d5459e567ee6bacd03817e617a5 | [
"MIT"
] | null | null | null | src/uniprotkb/components/protein-data-views/__tests__/UniProtEvidenceTag.spec.tsx | ebi-uniprot/uniprot-website | 2adc2d8529ef9d5459e567ee6bacd03817e617a5 | [
"MIT"
] | 152 | 2018-11-07T15:44:50.000Z | 2022-03-25T16:33:10.000Z | src/uniprotkb/components/protein-data-views/__tests__/UniProtEvidenceTag.spec.tsx | ebi-uniprot/uniprot-website | 2adc2d8529ef9d5459e567ee6bacd03817e617a5 | [
"MIT"
] | 2 | 2019-08-23T18:17:53.000Z | 2021-11-10T13:35:13.000Z | import customRender from '../../../../shared/__test-helpers__/customRender';
import UniProtKBEvidenceTag from '../UniProtKBEvidenceTag';
import { Evidence } from '../../../types/modelTypes';
describe('UniProtKBEvidenceTag components', () => {
test('should render automatic annotation', () => {
const evidences: Evidence[] = [
{
evidenceCode: 'ECO:0000255',
source: 'PROSITE-ProRule',
id: 'PRU10023',
},
];
const { asFragment } = customRender(
<UniProtKBEvidenceTag evidences={evidences} />
);
expect(asFragment()).toMatchSnapshot();
});
test('should render publications count', () => {
const evidences: Evidence[] = [
{
evidenceCode: 'ECO:0000269',
source: 'PubMed',
id: '12345',
},
{
evidenceCode: 'ECO:0000269',
source: 'PubMed',
id: '12346',
},
];
const { asFragment } = customRender(
<UniProtKBEvidenceTag evidences={evidences} />
);
expect(asFragment()).toMatchSnapshot();
});
test('should render automatic ', () => {
const evidences: Evidence[] = [
{
evidenceCode: 'ECO:0000313',
},
];
const { asFragment } = customRender(
<UniProtKBEvidenceTag evidences={evidences} />
);
expect(asFragment()).toMatchSnapshot();
});
});
| 25.471698 | 76 | 0.577037 |
4cdf2f68940022bc418529909c08b2c4c4ee0f1c | 1,513 | py | Python | lib/python/treadmill/cli/scheduler/apps.py | drienyov/treadmill | ce21537cd9a2fdb0567ac2aa3de1afcb2f6861de | [
"Apache-2.0"
] | 2 | 2017-10-31T18:48:20.000Z | 2018-03-04T20:35:20.000Z | lib/python/treadmill/cli/scheduler/apps.py | bretttegart/treadmill | 812109e31c503a6eddaee2d3f2e1faf2833b6aaf | [
"Apache-2.0"
] | null | null | null | lib/python/treadmill/cli/scheduler/apps.py | bretttegart/treadmill | 812109e31c503a6eddaee2d3f2e1faf2833b6aaf | [
"Apache-2.0"
] | null | null | null | """Show apps report."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import click
import pandas as pd
from treadmill import cli
from treadmill.cli.scheduler import fetch_report, print_report
from treadmill import restclient
def init():
"""Return top level command handler."""
@click.command()
@cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS)
@click.option('--match', help='Server name pattern match')
@click.option('--partition', help='Partition name pattern match')
@click.option('--full', is_flag=True, default=False)
@click.pass_context
def apps(ctx, match, partition, full):
"""View apps report."""
report = fetch_report(ctx.obj.get('api'), 'apps', match, partition)
# Replace integer N/As
for col in ['identity', 'expires', 'lease', 'data_retention']:
report.loc[report[col] == -1, col] = ''
# Convert to datetimes
for col in ['expires']:
report[col] = pd.to_datetime(report[col], unit='s')
# Convert to timedeltas
for col in ['lease', 'data_retention']:
report[col] = pd.to_timedelta(report[col], unit='s')
report = report.fillna('')
if not full:
report = report[[
'instance', 'allocation', 'partition', 'server',
'mem', 'cpu', 'disk'
]]
print_report(report)
return apps
| 30.877551 | 75 | 0.631196 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.