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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e241ac5a2b50b0cfcd60db56fff48026f135f0dd | 175 | js | JavaScript | caps.js | ClementBuchanan/caps | 91d5319154527bb75ad4411b28f8546de8ea9cc3 | [
"MIT"
] | null | null | null | caps.js | ClementBuchanan/caps | 91d5319154527bb75ad4411b28f8546de8ea9cc3 | [
"MIT"
] | null | null | null | caps.js | ClementBuchanan/caps | 91d5319154527bb75ad4411b28f8546de8ea9cc3 | [
"MIT"
] | null | null | null | 'use strict';
const driver = require('./driver/driver.js');
const vendor = require('./vendor/vendor.js');
const events = require('./events/events.js');
events.emit('start');
| 25 | 45 | 0.685714 |
d2a2f470d766da81cf7988d71ef2da3df870c8ee | 866 | rs | Rust | examples/vmod_timestamp/src/lib.rs | gquintard/varnish-rs | ec44230166e20f27ff3f893a1e907f2cd1ebb3ff | [
"BSD-3-Clause"
] | 3 | 2021-12-06T01:35:42.000Z | 2021-12-28T14:42:58.000Z | examples/vmod_timestamp/src/lib.rs | gquintard/varnish-rs | ec44230166e20f27ff3f893a1e907f2cd1ebb3ff | [
"BSD-3-Clause"
] | 5 | 2021-12-14T03:08:33.000Z | 2022-03-21T17:36:16.000Z | examples/vmod_timestamp/src/lib.rs | gquintard/varnish-rs | ec44230166e20f27ff3f893a1e907f2cd1ebb3ff | [
"BSD-3-Clause"
] | null | null | null | varnish::boilerplate!();
use std::time::{Duration, Instant};
use varnish::vcl::ctx::Ctx;
use varnish::vcl::vpriv::VPriv;
varnish::vtc!(test01);
// VPriv can wrap any (possibly custom) struct, here we only need an Instand from std::time.
// Storing and getting is up to the vmod writer but this removes the worry of NULL dereferencing
// and of the memory management
pub fn timestamp(_: &Ctx, vp: &mut VPriv<Instant>) -> Duration {
// we will need this either way
let now = Instant::now();
let interval = match vp.as_ref() {
// if `.get()` returns None, we just store `now` and interval is 0
None => Duration::new(0, 0),
// if there was a value, compute the difference with now
Some(old_now) => now.duration_since(*old_now),
};
// store the current time and return `interval`
vp.store(now);
interval
}
| 32.074074 | 96 | 0.658199 |
a35a9c7fa696d6b217a97e73ebf1332cde9f06f1 | 422 | ts | TypeScript | src/projectable.ts | angelsolaorbaiceta/inkgeom2d | 7efeef329f6b82710b3a08890249cfbf1b127c88 | [
"MIT"
] | 3 | 2020-11-12T18:21:43.000Z | 2021-03-13T01:51:41.000Z | src/projectable.ts | angelsolaorbaiceta/inkgeom2d | 7efeef329f6b82710b3a08890249cfbf1b127c88 | [
"MIT"
] | 10 | 2020-11-23T08:09:59.000Z | 2021-12-13T18:13:08.000Z | src/projectable.ts | angelsolaorbaiceta/inkgeom2d | 7efeef329f6b82710b3a08890249cfbf1b127c88 | [
"MIT"
] | null | null | null | export interface Projectable {
readonly x: number
readonly y: number
}
export const origin: Projectable = Object.freeze({
x: 0,
y: 0
})
export function roundProjections(p: Projectable) {
return {
x: Math.round(p.x),
y: Math.round(p.y)
}
}
export function distanceBetween(p: Projectable, q: Projectable): number {
const dx = p.x - q.x
const dy = p.y - q.y
return Math.sqrt(dx * dx + dy * dy)
}
| 18.347826 | 73 | 0.651659 |
f4b6eb15abbf58a5e7518cf7779378e26b2ba677 | 872 | tsx | TypeScript | web/src/pages/Landing.tsx | jacksonsr45/nlw3_happy | 742b7649dd03b3c0864e878b28260b6dab6a0bb1 | [
"MIT"
] | null | null | null | web/src/pages/Landing.tsx | jacksonsr45/nlw3_happy | 742b7649dd03b3c0864e878b28260b6dab6a0bb1 | [
"MIT"
] | null | null | null | web/src/pages/Landing.tsx | jacksonsr45/nlw3_happy | 742b7649dd03b3c0864e878b28260b6dab6a0bb1 | [
"MIT"
] | null | null | null | import React from 'react'
import { Link } from 'react-router-dom'
import '../styles/pages/landing.css'
import logoImg from '../images/logo.svg'
import arrowRight from '../images/arrow-right.svg'
function Landing() {
return (
<div id="page-landing">
<div className="content-wrapper">
<img src={logoImg} alt="Happy"/>
<main>
<h1>
Leve felicidade para o mundo
</h1>
<p>
Visite orfanatos e mude o dia de muitas crianças.
</p>
<div className="location">
<strong>Jacarezinho</strong>
<span>Paraná</span>
</div>
<Link className="enter-app" to="/app">
<img src={arrowRight} alt="App"/>
</Link>
</main>
</div>
</div>
)
}
export default Landing | 25.647059 | 63 | 0.509174 |
fa67ae37381bdd4e1b94aa38eae0735dbf1edc5c | 1,272 | cpp | C++ | tests/vertex_pruning_test.cpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | null | null | null | tests/vertex_pruning_test.cpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | 4 | 2020-04-18T16:16:05.000Z | 2020-04-18T16:17:36.000Z | tests/vertex_pruning_test.cpp | mtao/core | 91f9bc6e852417989ed62675e2bb372e6afc7325 | [
"MIT"
] | null | null | null | #include <iostream>
#include <mtao/geometry/kdtree.hpp>
#include <mtao/geometry/prune_vertices.hpp>
#include <algorithm>
int main(int argc, char* argv[]) {
mtao::vector<mtao::Vector<double,1>> p;
p.push_back(mtao::Vector<double,1>(0.));
p.push_back(mtao::Vector<double,1>(.5));
p.push_back(mtao::Vector<double,1>(.25));
p.push_back(mtao::Vector<double,1>(.75));
p.push_back(mtao::Vector<double,1>(.125));
p.push_back(mtao::Vector<double,1>(.375));
p.push_back(mtao::Vector<double,1>(.625));
p.push_back(mtao::Vector<double,1>(.875));
p.push_back(mtao::Vector<double,1>(1.));
size_t cursize = p.size();
p.push_back(mtao::Vector<double,1>(.5));
p.push_back(mtao::Vector<double,1>(.25));
p.push_back(mtao::Vector<double,1>(.75));
p.resize(1000);
std::generate(p.begin()+cursize,p.end(),[]() { return (mtao::Vector<double,1>::Random().array() /2 + .5).eval(); });
auto [p2,remap] = mtao::geometry::prune(p,.0625);
for(auto&& v: p2) {
std::cout << v.transpose() << std::endl;
}
for(auto&& [a,b]: remap) {
std::cout << a << "=>" << b << std::endl;
}
std::cout << "Initial size: " << cursize << std::endl;
std::cout << "Final size: " << p2.size() << std::endl;
}
| 33.473684 | 120 | 0.58805 |
54a17042bc1b379623b9f87307f56c266b0a1d4a | 2,225 | swift | Swift | Expenses/User Interface/Add Edit Transaction/Tags/Add Tag/AddTagView.swift | nominalista/expenses-ios | 1b90452aae817b7c83056f59634e3429225da16c | [
"Apache-2.0"
] | null | null | null | Expenses/User Interface/Add Edit Transaction/Tags/Add Tag/AddTagView.swift | nominalista/expenses-ios | 1b90452aae817b7c83056f59634e3429225da16c | [
"Apache-2.0"
] | null | null | null | Expenses/User Interface/Add Edit Transaction/Tags/Add Tag/AddTagView.swift | nominalista/expenses-ios | 1b90452aae817b7c83056f59634e3429225da16c | [
"Apache-2.0"
] | null | null | null | import SwiftUI
struct AddTagView: View {
@StateObject var viewModel: AddTagViewModel
@Environment(\.dismiss) var dismiss
var body: some View {
Form {
nameRow
}
.navigationTitle("Add tag")
.navigationBarTitleDisplayMode(.inline)
.navigationBarBackButtonHidden(true)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button {
dismiss()
} label: {
Image.icArrowBack24pt
}
.buttonStyle(.toolbarIcon)
}
ToolbarItem(placement: .navigationBarTrailing) {
Button {
viewModel.saveTag()
} label: {
Text("Save")
}
.buttonStyle(.toolbarText)
.disabled(!viewModel.isSaveEnabled)
}
}
.onReceive(viewModel.dismissPublisher) { _ in
dismiss()
}
}
private var nameRow: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Spacer().frame(width: 8)
Text("Name")
.font(.subheadline)
.foregroundColor(.secondaryLabel)
}
ModifiableTextField($viewModel.name)
.placeholder("Bills, Entertainment, Shopping, etc.")
.insets(EdgeInsets(16))
.background(Color.secondarySystemGroupedBackground)
.cornerRadius(8)
if !viewModel.isSaveEnabled && !viewModel.name.isEmptyOrBlank {
HStack {
Spacer().frame(width: 8)
Text("This tag already exists.")
.foregroundColor(.systemRed)
.font(.subheadline)
}
}
}
.listRowInsets(.zero)
.listRowBackground(Color.clear)
.listRowSeparator(.hidden)
}
}
struct AddTagView_Previews: PreviewProvider {
static var previews: some View {
AddTagView(viewModel: .fake(restrictedTagNames: []))
}
}
| 28.525641 | 75 | 0.486292 |
e25a2107796ff9eaab3c149963b1ff56b90020cc | 444 | py | Python | src/1312_min_palindrome_insertions.py | soamsy/leetcode | 091f3b33e44613fac130ff1018c8b63493798f09 | [
"MIT"
] | null | null | null | src/1312_min_palindrome_insertions.py | soamsy/leetcode | 091f3b33e44613fac130ff1018c8b63493798f09 | [
"MIT"
] | null | null | null | src/1312_min_palindrome_insertions.py | soamsy/leetcode | 091f3b33e44613fac130ff1018c8b63493798f09 | [
"MIT"
] | null | null | null | def minInsertions(s: str) -> int:
dp = [[0] * len(s) for _ in range(len(s))]
for left in range(len(s) - 1, -1, -1):
for right in range(0, len(s)):
if left >= right:
continue
if s[left] == s[right]:
dp[left][right] = dp[left+1][right-1]
else:
dp[left][right] = 1 + min(dp[left+1][right], dp[left][right-1])
return dp[0][len(s) - 1] | 34.153846 | 79 | 0.448198 |
06e65ba65ef82394c79328fc0c89f38e06d4e776 | 1,055 | py | Python | 2017/day01.py | bovarysme/advent | 9a7a3310984d4b7548ad23e2dfa017c6fe9e2c9c | [
"MIT"
] | 4 | 2017-12-05T00:53:21.000Z | 2018-12-03T14:00:56.000Z | 2017/day01.py | bovarysme/advent | 9a7a3310984d4b7548ad23e2dfa017c6fe9e2c9c | [
"MIT"
] | null | null | null | 2017/day01.py | bovarysme/advent | 9a7a3310984d4b7548ad23e2dfa017c6fe9e2c9c | [
"MIT"
] | null | null | null | def pairs(digits):
for i in range(len(digits) - 1):
yield digits[i], digits[i+1]
yield digits[-1], digits[0]
def halfway(digits):
half = len(digits) // 2
for i in range(half):
yield digits[i], digits[half+i]
for i in range(half, len(digits)):
yield digits[i], digits[i-half]
def solve(iterator, digits):
return sum(int(x) for x, y in iterator(digits) if x == y)
def part_one(digits):
return solve(pairs, digits)
def part_two(digits):
return solve(halfway, digits)
if __name__ == '__main__':
assert part_one('1122') == 3
assert part_one('1111') == 4
assert part_one('1234') == 0
assert part_one('91212129') == 9
assert part_two('1212') == 6
assert part_two('1221') == 0
assert part_two('123425') == 4
assert part_two('123123') == 12
assert part_two('12131415') == 4
with open('inputs/day1.txt', 'r') as f:
digits = f.read().rstrip()
print('Answer for part one:', part_one(digits))
print('Answer for part two:', part_two(digits))
| 22.934783 | 61 | 0.609479 |
c747841cda2ffb42cef8b254d3c349942fe021e3 | 11,054 | swift | Swift | STPostWebView/STPostWebView.swift | shien7654321/STPostWebView | a4ce90818887dbde048eb713d1827ab8c7e414b9 | [
"MIT"
] | 8 | 2018-08-29T03:06:45.000Z | 2021-07-16T16:03:54.000Z | STPostWebView/STPostWebView.swift | shien7654321/STPostWebView | a4ce90818887dbde048eb713d1827ab8c7e414b9 | [
"MIT"
] | null | null | null | STPostWebView/STPostWebView.swift | shien7654321/STPostWebView | a4ce90818887dbde048eb713d1827ab8c7e414b9 | [
"MIT"
] | 2 | 2018-08-29T03:06:46.000Z | 2019-04-25T05:05:05.000Z | //
// STPostWebView.swift
// STPostWebView
//
// Created by Suta on 2018/8/24.
// Copyright © 2018年 Suta. All rights reserved.
//
import Foundation
import UIKit
import WebKit
public class STPostWebView: WKWebView, STPostWebViewScriptMessagePresenterDelegate {
private var posted = false
private var postUserScript: WKUserScript?
private var shouldSaveBackForwardListItem = false
private var postedBackForwardListItems = Set<WKBackForwardListItem>()
override public var canGoBack: Bool {
get {
if super.canGoBack {
var can = false
for item in backForwardList.backList {
if postedBackForwardListItems.contains(item) {
continue
}
can = true
break
}
return can
} else {
return super.canGoBack
}
}
}
// MARK: -
convenience public init(frame: CGRect) {
self.init(frame: frame, configuration: WKWebViewConfiguration())
}
override public init(frame: CGRect, configuration: WKWebViewConfiguration) {
super.init(frame: frame, configuration: configuration)
configurePost()
}
required public init?(coder: NSCoder) {
super.init(coder: coder)
configurePost()
}
@discardableResult override public func load(_ request: URLRequest) -> WKNavigation? {
guard let httpMethod = request.httpMethod?.uppercased(), httpMethod == "POST" else {
return super.load(request)
}
guard let httpBody = request.httpBody, httpBody.count > 0 else {
return super.load(request)
}
guard let urlString = request.url?.absoluteString else {
return super.load(request)
}
guard let httpBodyString = String(data: httpBody, encoding: .utf8), httpBodyString.count > 0 else {
return super.load(request)
}
posted = false
let jsObjectString = httpBodyJSObjectString(httpBodyString: httpBodyString)
let postScript = "STPostWebViewPost({path: '\(urlString)', params: \(jsObjectString)});"
postUserScript = WKUserScript(source: postScript, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
configuration.userContentController.addUserScript(postUserScript!)
return super.load(request)
}
override public func goBack() -> WKNavigation? {
if canGoBack {
var targetItem: WKBackForwardListItem?
for item in backForwardList.backList.reversed() {
if !postedBackForwardListItems.contains(item) {
targetItem = item
break
}
}
if let item = targetItem {
return go(to: item)
} else {
return nil
}
} else {
return nil
}
}
override public func goForward() -> WKNavigation? {
if canGoForward {
var targetItem: WKBackForwardListItem?
for item in backForwardList.forwardList {
if !postedBackForwardListItems.contains(item) {
targetItem = item
break
}
}
if let item = targetItem {
return go(to: item)
} else {
return nil
}
} else {
return nil
}
}
// MARK: - Private
private func configurePost() {
let scriptMessagePresenter = STPostWebViewScriptMessagePresenter(delegate: self)
let startScript = """
var STPostWebViewGetPosted = function () {
};
STPostWebViewGetPosted.prototype.callback = function (callback) {
STPostWebViewGetPostedCallback = callback;
return this;
};
STPostWebViewGetPosted.prototype.postMessage = function () {
window.webkit.messageHandlers.STPostWebViewGetPosted.postMessage({});
};
var STPostWebViewGetPostedCallback = function () {
};
var STPostWebViewSetPosted = function () {
};
STPostWebViewSetPosted.prototype.callback = function (callback) {
STPostWebViewSetPostedCallback = callback;
return this;
};
STPostWebViewSetPosted.prototype.postMessage = function (args) {
window.webkit.messageHandlers.STPostWebViewSetPosted.postMessage(args);
};
var STPostWebViewSetPostedCallback = function () {
};
function STPostWebViewPost(args) {
var getPosted = new STPostWebViewGetPosted();
getPosted.callback(function (result) {
var posted = result.posted;
if (!posted) {
var setPosted = new STPostWebViewSetPosted();
setPosted.callback(function () {
var method = "post";
var path = args["path"];
var params = args["params"];
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}).postMessage({
posted: true
});
}
}).postMessage();
}
"""
let startUserScript = WKUserScript(source: startScript, injectionTime: .atDocumentStart, forMainFrameOnly: false)
let endUserScript = WKUserScript(source: "window.webkit.messageHandlers.STPostWebViewDidFinishNavigation.postMessage({});", injectionTime: .atDocumentEnd, forMainFrameOnly: false)
configuration.userContentController.addUserScript(startUserScript)
configuration.userContentController.addUserScript(endUserScript)
configuration.userContentController.add(scriptMessagePresenter, name: "STPostWebViewGetPosted")
configuration.userContentController.add(scriptMessagePresenter, name: "STPostWebViewSetPosted")
configuration.userContentController.add(scriptMessagePresenter, name: "STPostWebViewDidFinishNavigation")
}
private func httpBodyJSObjectString(httpBodyString: String) -> String {
let subParameterStringArray = httpBodyString.components(separatedBy: "&")
var jsObjectString = "{"
for subParameterString in subParameterStringArray {
if jsObjectString.count > 1 {
jsObjectString += ", "
}
if let range = subParameterString.range(of: "=") {
let key = String(subParameterString[..<range.lowerBound])
let value = String(subParameterString[range.upperBound...])
jsObjectString.append("\(key): '\(value)'")
} else {
jsObjectString.append("\(subParameterString): ''")
}
}
jsObjectString.append("}")
return jsObjectString
}
private func removePostUserScript() {
guard let thePostUserScript = postUserScript else {
return
}
var userScripts = configuration.userContentController.userScripts
guard let index = userScripts.firstIndex(of: thePostUserScript) else {
postUserScript = nil
return
}
userScripts.remove(at: index)
configuration.userContentController.removeAllUserScripts()
for userScript in userScripts {
configuration.userContentController.addUserScript(userScript)
}
postUserScript = nil
}
private func removeUnusedPostedBackForwardListItem() {
var unusedPostedBackForwardListItems = Set<WKBackForwardListItem>()
for item in postedBackForwardListItems {
var use = false
for backListItem in backForwardList.backList {
if backListItem.isEqual(item) {
use = true
break
}
}
if !use {
for forwardListItem in backForwardList.forwardList {
if forwardListItem.isEqual(item) {
use = true
break
}
}
}
if !use {
unusedPostedBackForwardListItems.insert(item)
}
}
for item in unusedPostedBackForwardListItems {
postedBackForwardListItems.remove(item)
}
}
// MARK: - STPostWebViewScriptMessagePresenterDelegate
fileprivate func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
switch message.name {
case "STPostWebViewGetPosted":
let js = "STPostWebViewGetPostedCallback({posted: \(posted ? "true" : "false")})"
evaluateJavaScript(js, completionHandler: nil)
case "STPostWebViewSetPosted":
if let result = message.body as? [String: Bool] {
if let newPosted = result["posted"] {
posted = newPosted
let js = "STPostWebViewSetPostedCallback()"
evaluateJavaScript(js, completionHandler: nil)
shouldSaveBackForwardListItem = true
}
}
case "STPostWebViewDidFinishNavigation":
if posted {
removePostUserScript()
}
if shouldSaveBackForwardListItem {
shouldSaveBackForwardListItem = false
if let item = backForwardList.backList.last, !postedBackForwardListItems.contains(item) {
postedBackForwardListItems.insert(item)
}
}
removeUnusedPostedBackForwardListItem()
default:
break
}
}
}
// MARK: -
@objc fileprivate protocol STPostWebViewScriptMessagePresenterDelegate {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
}
// MARK: -
fileprivate class STPostWebViewScriptMessagePresenter: NSObject, WKScriptMessageHandler {
weak var delegate: STPostWebViewScriptMessagePresenterDelegate?
override private init() {
super.init()
}
convenience init(delegate: STPostWebViewScriptMessagePresenterDelegate) {
self.init()
self.delegate = delegate
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
delegate?.userContentController(userContentController, didReceive: message)
}
}
| 34.981013 | 187 | 0.600597 |
af57ebbdb444061df146a19cd7a6babc819e1eeb | 9,411 | py | Python | StudyStuff/DataAnalysis/read csv.py | MatKier/LatinIME-ebm-study-Android-Studio | 1a09013befd4327bae140ed8376d3bde93315451 | [
"Apache-2.0"
] | 1 | 2018-09-19T09:49:55.000Z | 2018-09-19T09:49:55.000Z | StudyStuff/DataAnalysis/read csv.py | MatKier/LatinIME-ebm-study-Android-Studio | 1a09013befd4327bae140ed8376d3bde93315451 | [
"Apache-2.0"
] | null | null | null | StudyStuff/DataAnalysis/read csv.py | MatKier/LatinIME-ebm-study-Android-Studio | 1a09013befd4327bae140ed8376d3bde93315451 | [
"Apache-2.0"
] | null | null | null | import pandas as pd
import numpy as np
import math as maths
import matplotlib.pyplot as plt
import os
usecols_ = ["x", "y", "offsetX", "offsetY", "keyCenterX", "keyCenterY", "holdTime", "flightTime", "pressure"]
usecols = ["offsetX", "offsetY", "keyCenterX", "keyCenterY", "holdTime", "flightTime", "pressure"]
defaultHoldTimeError = []
longHoldTimeError = []
defaultFlightTimeError = []
longFlightTimeError = []
defaultAreaError = []
bigAreaError = []
centerOffsetError = []
leftOffsetError = []
rightOffsetError = []
topOffsetError = []
bottomOffsetError = []
path_ = "C:/Users/mathi/OneDrive/Bachelor Stuff/Hauptstudie/Pilot/KeyStrokeLog/"
path = "E:/OneDrive/Bachelor Stuff/Hauptstudie/Pilot/KeyStrokeLog/"
targetGroupPath = path + "ID_targetValues/"
pidList = os.listdir(path)
pidList.remove("ID_targetValues")
pidList.remove("read csv.py")
#One iteration = one Participant
for pid in pidList:
taskGroupPath = path + pid + "/"
taskGroupList = os.listdir(taskGroupPath)
taskPathDict = {}
targetPathDict = {}
for taskGroup in taskGroupList:
taskDirs = [task for task in sorted(os.listdir(taskGroupPath + taskGroup))]
taskPathDict[taskGroup] = [(taskGroup + "/" + taskDir) for taskDir in taskDirs]
targetPathDict[taskGroup] = [(taskGroup + "/" + taskDir) for taskDir in taskDirs if not taskDir == "17_user-created password"]
# One iteration = one taskgroup
for key in sorted(taskPathDict.keys()):
#One iteration = one task (3 csv files per task)
for task in sorted(taskPathDict[key]):
# last 3 csv files in <task> read as a list of dataframes
csvFileList = [pd.read_csv(taskGroupPath + task + "/" + entry, sep=';', header=0, usecols=usecols) for entry in [taskEntry for taskEntry in sorted(os.listdir(taskGroupPath + task), reverse=True) if taskEntry.startswith('valid')][:3]]
# combines the 3 dataframes into one group
groupedCsvList = pd.concat(csvFileList).groupby(level=0)
mean = groupedCsvList.mean()
if task[:2] != "17":
targetCsv = pd.read_csv(targetGroupPath + task + "/" + os.listdir(targetGroupPath + task)[0], sep=';', header=0, usecols=usecols)
meanDistanceToTarget = targetCsv.subtract(mean, fill_value=0)
# Temp lists for calculating the mean error of all events for the current task and feature
tempDefaultHoldTimeError = []
tempLongHoldTimeError = []
tempDefaultFlightTimeError = []
tempLongFlightTimeError = []
tempDefaultAreaError = []
tempBigAreaError = []
tempCenterOffsetError = []
tempLeftOffsetError = []
tempRightOffsetError = []
tempTopOffsetError = []
tempBottomOffsetError = []
taskId = task[-2:]
# Iterate over the mean error of all touch events in this task and add the mean error for every event to its corresponding tempList
# One iteration = one touch event (up or down)
for index, meanDistanceToTargetRrow in meanDistanceToTarget.iterrows():
# HoldTime Error
if targetCsv.at[index, 'holdTime'] == 80:
tempDefaultHoldTimeError.append(meanDistanceToTargetRrow['holdTime'])
elif targetCsv.at[index, 'holdTime'] == 300:
tempLongHoldTimeError.append(meanDistanceToTargetRrow['holdTime'])
# FlightTime Error
if targetCsv.at[index, 'flightTime'] == 260:
tempDefaultFlightTimeError.append(meanDistanceToTargetRrow['flightTime'])
elif targetCsv.at[index, 'flightTime'] == 1000:
tempLongFlightTimeError.append(meanDistanceToTargetRrow['flightTime'])
# Area Error
if targetCsv.at[index, 'pressure'] == 0.20:
tempDefaultAreaError.append(meanDistanceToTargetRrow['pressure'])
elif targetCsv.at[index, 'pressure'] == 0.45:
tempBigAreaError.append(meanDistanceToTargetRrow['pressure'])
# Offset
# groupedCsvList contains the grouped values for the current task,
#'[" offsetX", " offsetY"].get_group(index).reset_index(drop=True)' returns a dataframe containing the (grouped)offsets for the event at index
offsets = groupedCsvList["offsetX", "offsetY"].get_group(index).reset_index(drop=True)
# Calculates the average distance between the target-offset and the users' offset (3 points for each event(index))
distSum = 0
for j in range(len(offsets)):
distSum += maths.hypot(targetCsv.at[index, 'offsetX'] - offsets.at[j, 'offsetX'], targetCsv.at[index, 'offsetY'] - offsets.at[j, 'offsetY'])
avgDist = distSum / len(offsets)
if targetCsv.at[index, 'offsetX'] == 0 and targetCsv.at[index, 'offsetY'] == 0:
tempCenterOffsetError.append(avgDist)
elif targetCsv.at[index, 'offsetX'] == -45 and targetCsv.at[index, 'offsetY'] == 0:
tempLeftOffsetError.append(avgDist)
elif targetCsv.at[index, 'offsetX'] == 45 and targetCsv.at[index, 'offsetY'] == 0:
tempRightOffsetError.append(avgDist)
elif targetCsv.at[index, 'offsetX'] == 0 and targetCsv.at[index, 'offsetY'] == -80:
tempTopOffsetError.append(avgDist)
elif targetCsv.at[index, 'offsetX'] == 0 and targetCsv.at[index, 'offsetY'] == 80:
tempBottomOffsetError.append(avgDist)
# Calculate the mean of all the event means of the current task
# and add it to its corresponding list
# HoldTime
defaultHoldTimeError.append([np.mean(tempDefaultHoldTimeError), taskId, pid])
longHoldTimeError.append([np.mean(tempLongHoldTimeError), taskId, pid])
# FlightTime
defaultFlightTimeError.append([np.mean(tempDefaultFlightTimeError), taskId, pid])
longFlightTimeError.append([np.mean(tempLongFlightTimeError), taskId, pid])
# Area
defaultAreaError.append([np.mean(tempDefaultAreaError), taskId, pid])
bigAreaError.append([np.mean(tempBigAreaError), taskId, pid])
# Offset
centerOffsetError.append([np.mean(tempCenterOffsetError), taskId, pid])
leftOffsetError.append([np.mean(tempLeftOffsetError), taskId, pid])
rightOffsetError.append([np.mean(tempRightOffsetError), taskId, pid])
topOffsetError.append([np.mean(tempTopOffsetError), taskId, pid])
bottomOffsetError.append([np.mean(tempBottomOffsetError), taskId, pid])
print 'finishied ' + pid
offset_means = (np.nanmean([error[0] for error in centerOffsetError]),
np.nanmean([error[0] for error in leftOffsetError]),
np.nanmean([error[0] for error in rightOffsetError]),
np.nanmean([error[0] for error in topOffsetError]),
np.nanmean([error[0] for error in bottomOffsetError]))
offset_std = (np.nanstd([error[0] for error in centerOffsetError]),
np.nanstd([error[0] for error in leftOffsetError]),
np.nanstd([error[0] for error in rightOffsetError]),
np.nanstd([error[0] for error in topOffsetError]),
np.nanstd([error[0] for error in bottomOffsetError]))
fig, ax = plt.subplots()
index = np.arange(len(offset_means))
bar_width = 0.35
opacity = 0.4
error_config = {'ecolor': '0.3'}
rects = ax.bar(index, offset_means, bar_width,
alpha=opacity, color='g',
yerr=offset_std, error_kw=error_config)
ax.set_xlabel('Offset direction')
ax.set_ylabel('Error')
ax.set_title('Offset error by offset direction')
ax.set_xticks(index)
ax.set_xticklabels(('Center', 'Left', 'Righ', 'Top', 'Bottom'))
ax.legend()
fig.tight_layout()
plt.show()
area_means = (np.nanmean([error[0] for error in defaultAreaError]),
np.nanmean([error[0] for error in bigAreaError]))
area_std = (np.nanstd([error[0] for error in defaultAreaError]),
np.nanstd([error[0] for error in bigAreaError]))
fig, ax = plt.subplots()
index = np.arange(len(area_means))
bar_width = 0.75
opacity = 0.4
error_config = {'ecolor': '0.3'}
rects = ax.bar(index, area_means, bar_width,
alpha=opacity, color='b',
yerr=area_std, error_kw=error_config)
ax.set_xlabel('Area characteristic')
ax.set_ylabel('Error')
ax.set_title('Area error by area characteristic')
ax.set_xticks(index)
ax.set_xticklabels(('Default', 'Big'))
ax.legend()
fig.tight_layout()
plt.show()
flight_time_means = (np.nanmean([error[0] for error in defaultFlightTimeError]),
np.nanmean([error[0] for error in longFlightTimeError]))
flight_time_std = (np.nanstd([error[0] for error in defaultFlightTimeError]),
np.nanstd([error[0] for error in longFlightTimeError]))
fig, ax = plt.subplots()
index = np.arange(len(area_means))
bar_width = 0.75
opacity = 0.4
error_config = {'ecolor': '0.3'}
rects = ax.bar(index, flight_time_means, bar_width,
alpha=opacity, color='r',
yerr=flight_time_std, error_kw=error_config)
ax.set_xlabel('Flight time characteristic')
ax.set_ylabel('Error')
ax.set_title('Flight time error by flight time characteristic')
ax.set_xticks(index)
ax.set_xticklabels(('Default', 'Long'))
ax.legend()
fig.tight_layout()
plt.show()
hold_time_means = (np.nanmean([error[0] for error in defaultHoldTimeError]),
np.nanmean([error[0] for error in longHoldTimeError]))
hold_time_std = (np.nanstd([error[0] for error in defaultHoldTimeError]),
np.nanstd([error[0] for error in longHoldTimeError]))
fig, ax = plt.subplots()
index = np.arange(len(area_means))
bar_width = 0.75
opacity = 0.4
error_config = {'ecolor': '0.3'}
rects = ax.bar(index, hold_time_means, bar_width,
alpha=opacity, color='y',
yerr=hold_time_std, error_kw=error_config)
ax.set_xlabel('Hold time characteristic')
ax.set_ylabel('Error')
ax.set_title('Hold time error by hold time characteristic')
ax.set_xticks(index)
ax.set_xticklabels(('Default', 'Long'))
ax.legend()
fig.tight_layout()
plt.show() | 39.049793 | 236 | 0.71714 |
0ab009f91c4cc32e89dd6c58e759ab90bcd59bd2 | 210 | cs | C# | KofteKalkan.Models/FreeGamesNotification.cs | RastgeleReyiz/KofteKalkan | 518641219d32b201cb97857943ae369d4c69915c | [
"MIT"
] | null | null | null | KofteKalkan.Models/FreeGamesNotification.cs | RastgeleReyiz/KofteKalkan | 518641219d32b201cb97857943ae369d4c69915c | [
"MIT"
] | null | null | null | KofteKalkan.Models/FreeGamesNotification.cs | RastgeleReyiz/KofteKalkan | 518641219d32b201cb97857943ae369d4c69915c | [
"MIT"
] | null | null | null | namespace KofteKalkan.Models
{
public class FreeGamesNotification
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public string Summary
{
get;
set;
}
}
}
| 8.75 | 35 | 0.580952 |
3f5777ddaff0f1d03886c297c46b680629832a12 | 1,693 | rb | Ruby | lib/weese/bus/stop.rb | emma-k-alexandra/weese | 3a86f1a1308ab4575366e4a8c945caff0e629848 | [
"MIT"
] | null | null | null | lib/weese/bus/stop.rb | emma-k-alexandra/weese | 3a86f1a1308ab4575366e4a8c945caff0e629848 | [
"MIT"
] | null | null | null | lib/weese/bus/stop.rb | emma-k-alexandra/weese | 3a86f1a1308ab4575366e4a8c945caff0e629848 | [
"MIT"
] | null | null | null | # frozen_string_literal: true
require 'weese/bus/urls'
module Weese
module Bus
# A MetroBus stop.
class Stop
# @return [Integer] The WMATA Stop ID of this Stop
attr_accessor :id
#
# Create a Stop
#
# @param [Integer] id WMATA Stop ID
#
def initialize(id)
@id = id
end
end
# These requests require a Stop
module RequiresStop
include Requests::Requester
#
# Next bus arrivals at a given stop.
# {https://developer.wmata.com/docs/services/5476365e031f590f38092508/operations/5476365e031f5909e4fe331d WMATA Documentation}
#
# @param [Stop] stop A Stop
#
# @raise [WeeseError] If request or JSON parse fails
#
# @return [Hash] JSON Response
#
def next_buses(stop)
fetch(
Requests::Request.new(
@api_key,
Bus::Urls::NEXT_BUSES,
StopID: stop.id
)
)
end
#
# Buses scheduled at a stop for an optional given date.
# {https://developer.wmata.com/docs/services/54763629281d83086473f231/operations/5476362a281d830c946a3d6c WMATA Documentation}
#
# @param [Stop] stop A Stop
# @param [Date] date An optional Date
#
# @raise [WeeseError] If request or JSON parse fails
#
# @return [Hash] JSON Response
#
def stop_schedule(stop, date = nil)
query = { StopID: stop.id }
query['Date'] = date.to_s if date
fetch(
Requests::Request.new(
@api_key,
Bus::Urls::STOP_SCHEDULE,
query
)
)
end
end
end
end
| 23.191781 | 132 | 0.564678 |
e2567a15624b3a433c3491ee4e7e37ab221ea90d | 603 | rb | Ruby | app/models/message.rb | ArtefactGitHub/tsunagaru-clone-repo | af4cdedc31775c63485932f59c083c779feb69ca | [
"MIT"
] | null | null | null | app/models/message.rb | ArtefactGitHub/tsunagaru-clone-repo | af4cdedc31775c63485932f59c083c779feb69ca | [
"MIT"
] | null | null | null | app/models/message.rb | ArtefactGitHub/tsunagaru-clone-repo | af4cdedc31775c63485932f59c083c779feb69ca | [
"MIT"
] | null | null | null | class Message < ApplicationRecord
include RoomNotifierModule
belongs_to :user
belongs_to :room
after_create_commit {
# update_at_message の前に通知処理を走らせる(更新時刻が条件に関わるため)
send_room_notify self
update_at_message self.room
MessageBroadcastJob.perform_later self
}
default_scope -> { order(created_at: :desc) }
validates :content, length: { in: 1..100 }
validates :user_id, presence: true
validates :room_id, presence: true
class << self
def system_to_room(content, room)
Message.create!(content: content, user: User.system_user, room: room)
end
end
end
| 22.333333 | 75 | 0.729685 |
cd80b069a076a0e4333015e2a3bf5577548d4acc | 7,083 | cs | C# | src/System.Xml.XPath.XmlDocument/System/Xml/XPath/XmlDocumentExtensions.cs | aniono/corefx | fdd0430aece54ab7337a19335e6647654aba63c7 | [
"MIT"
] | 1 | 2021-05-26T08:22:28.000Z | 2021-05-26T08:22:28.000Z | src/System.Xml.XPath.XmlDocument/System/Xml/XPath/XmlDocumentExtensions.cs | shyamalschandra/corefx | cbd550036f510b1503b4bdbbc7dcd763e5d65ae2 | [
"MIT"
] | null | null | null | src/System.Xml.XPath.XmlDocument/System/Xml/XPath/XmlDocumentExtensions.cs | shyamalschandra/corefx | cbd550036f510b1503b4bdbbc7dcd763e5d65ae2 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
namespace System.Xml.XPath
{
public static class XmlDocumentExtensions
{
private class XmlDocumentNavigable : IXPathNavigable
{
private XmlNode node;
public XmlDocumentNavigable(XmlNode n)
{
this.node = n;
}
public XPathNavigator CreateNavigator()
{
return node.CreateNavigator();
}
}
public static XmlNodeList SelectNodes(this XmlNode node, string xpath)
{
XPathNavigator navigator = CreateNavigator(node);
if (navigator == null)
return null;
return new XPathNodeList(navigator.Select(xpath));
}
public static XmlNodeList SelectNodes(this XmlNode node, string xpath, XmlNamespaceManager nsmgr)
{
XPathNavigator navigator = CreateNavigator(node);
if (navigator == null)
return null;
return new XPathNodeList(navigator.Select(xpath, nsmgr));
}
public static XmlNode SelectSingleNode(this XmlNode node, string xpath)
{
XmlNodeList list = SelectNodes(node, xpath);
return list != null ? list[0] : null;
}
public static XmlNode SelectSingleNode(this XmlNode node, string xpath, XmlNamespaceManager nsmgr)
{
XmlNodeList list = SelectNodes(node, xpath, nsmgr);
return list != null ? list[0] : null;
}
//if the method is called on node types like DocType, Entity, XmlDeclaration,
//the navigator returned is null. So just return null from here for those node types.
public static XPathNavigator CreateNavigator(this XmlNode node)
{
XmlDocument thisAsDoc = node as XmlDocument;
if (thisAsDoc != null)
{
return CreateNavigator(thisAsDoc, node);
}
XmlDocument doc = node.OwnerDocument;
System.Diagnostics.Debug.Assert(doc != null);
return CreateNavigator(doc, node);
}
public static IXPathNavigable ToXPathNavigable(this XmlNode node)
{
return new XmlDocumentNavigable(node);
}
public static XPathNavigator CreateNavigator(this XmlDocument document)
{
return CreateNavigator(document, document);
}
public static XPathNavigator CreateNavigator(this XmlDocument document, XmlNode node)
{
XmlNodeType nodeType = node.NodeType;
XmlNode parent;
XmlNodeType parentType;
switch (nodeType)
{
case XmlNodeType.EntityReference:
case XmlNodeType.Entity:
case XmlNodeType.DocumentType:
case XmlNodeType.Notation:
case XmlNodeType.XmlDeclaration:
return null;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.SignificantWhitespace:
parent = node.ParentNode;
if (parent != null)
{
do
{
parentType = parent.NodeType;
if (parentType == XmlNodeType.Attribute)
{
return null;
}
else if (parentType == XmlNodeType.EntityReference)
{
parent = parent.ParentNode;
}
else
{
break;
}
}
while (parent != null);
}
node = NormalizeText(node);
break;
case XmlNodeType.Whitespace:
parent = node.ParentNode;
if (parent != null)
{
do
{
parentType = parent.NodeType;
if (parentType == XmlNodeType.Document
|| parentType == XmlNodeType.Attribute)
{
return null;
}
else if (parentType == XmlNodeType.EntityReference)
{
parent = parent.ParentNode;
}
else
{
break;
}
}
while (parent != null);
}
node = NormalizeText(node);
break;
default:
break;
}
return new DocumentXPathNavigator(document, node);
}
private static XmlNode NormalizeText(XmlNode n)
{
XmlNode retnode = null;
while (n.IsText())
{
retnode = n;
n = n.PreviousSibling;
if (n == null)
{
XmlNode intnode = retnode;
while (true)
{
if (intnode.ParentNode != null && intnode.ParentNode.NodeType == XmlNodeType.EntityReference)
{
if (intnode.ParentNode.PreviousSibling != null)
{
n = intnode.ParentNode.PreviousSibling;
break;
}
else
{
intnode = intnode.ParentNode;
if (intnode == null)
break;
}
}
else
break;
}
}
if (n == null)
break;
while (n.NodeType == XmlNodeType.EntityReference)
{
n = n.LastChild;
// The only possibility of this happening is when
// XmlEntityReference is not expanded.
// All entities are expanded when created in XmlDocument.
// If you try to create standalone XmlEntityReference
// it is not expanded until you set its parent.
Debug.Assert(n != null);
}
}
return retnode;
}
}
}
| 36.137755 | 117 | 0.436115 |
05b6b30cd93d53473d5e66bba9111d92bf8eac54 | 3,882 | py | Python | magma/uniquification.py | leonardt/magma | d3e8c9500ec3b167df8ed067e0c0305781c94ab6 | [
"MIT"
] | 167 | 2017-10-08T00:59:22.000Z | 2022-02-08T00:14:39.000Z | magma/uniquification.py | leonardt/magma | d3e8c9500ec3b167df8ed067e0c0305781c94ab6 | [
"MIT"
] | 719 | 2017-08-29T17:58:28.000Z | 2022-03-31T23:39:18.000Z | magma/uniquification.py | leonardt/magma | d3e8c9500ec3b167df8ed067e0c0305781c94ab6 | [
"MIT"
] | 14 | 2017-09-01T03:25:16.000Z | 2021-11-05T13:30:24.000Z | from dataclasses import dataclass
from enum import Enum, auto
from magma.is_definition import isdefinition
from magma.logging import root_logger
from magma.passes import DefinitionPass
_logger = root_logger()
class MultipleDefinitionException(Exception):
pass
class UniquificationMode(Enum):
WARN = auto()
ERROR = auto()
UNIQUIFY = auto()
@dataclass(frozen=True)
class _HashStruct:
defn_repr: str
is_verilog: bool
verilog_str: bool
inline_verilog: tuple
def _make_hash_struct(definition):
repr_ = repr(definition)
inline_verilog = tuple()
for inline_str, connect_references in definition.inline_verilog_strs:
connect_references = tuple(connect_references.items())
inline_verilog += (inline_str, connect_references)
if hasattr(definition, "verilogFile") and definition.verilogFile:
return _HashStruct(repr_, True, definition.verilogFile, inline_verilog)
return _HashStruct(repr_, False, "", inline_verilog)
def _hash(definition):
hash_struct = _make_hash_struct(definition)
return hash(hash_struct)
class UniquificationPass(DefinitionPass):
def __init__(self, main, mode):
super().__init__(main)
self.mode = mode
self.seen = {}
self.original_names = {}
def _rename(self, ckt, new_name):
assert ckt not in self.original_names
self.original_names[ckt] = ckt.name
type(ckt).rename(ckt, new_name)
def __call__(self, definition):
for module in definition.bind_modules:
self._run(module)
name = definition.name
key = _hash(definition)
seen = self.seen.setdefault(name, {})
if key not in seen:
if self.mode is UniquificationMode.UNIQUIFY and len(seen) > 0:
suffix = "_unq" + str(len(seen))
new_name = name + suffix
self._rename(definition, new_name)
seen[key] = [definition]
else:
if self.mode is not UniquificationMode.UNIQUIFY:
assert seen[key][0].name == name
elif name != seen[key][0].name:
new_name = seen[key][0].name
self._rename(definition, new_name)
seen[key].append(definition)
def run(self):
super().run()
duplicated = []
for name, definitions in self.seen.items():
if len(definitions) > 1:
duplicated.append((name, definitions))
UniquificationPass.handle(duplicated, self.mode)
@staticmethod
def handle(duplicated, mode):
if len(duplicated):
msg = f"Multiple definitions: {[name for name, _ in duplicated]}"
if mode is UniquificationMode.ERROR:
error(msg)
raise MultipleDefinitionException([name for name, _ in duplicated])
elif mode is UniquificationMode.WARN:
warning(msg)
def _get_mode(mode_or_str):
if isinstance(mode_or_str, str):
try:
return UniquificationMode[mode_or_str]
except KeyError as e:
modes = [k for k in UniquificationMode.__members__]
raise ValueError(f"Valid uniq. modes are {modes}")
if isinstance(mode_or_str, UniquificationMode):
return mode_or_str
raise NotImplementedError(f"Unsupported type: {type(mode_or_str)}")
def reset_names(original_names):
for ckt, original_name in original_names.items():
type(ckt).rename(ckt, original_name)
# This pass runs uniquification according to @mode and returns a dictionary
# mapping any renamed circuits to their original names. If @mode is ERROR or
# WARN the returned dictionary should be empty.
def uniquification_pass(circuit, mode_or_str):
mode = _get_mode(mode_or_str)
pass_ = UniquificationPass(circuit, mode)
pass_.run()
return pass_.original_names
| 31.560976 | 83 | 0.658939 |
0d011da2317a73dacda5b3852c9b483199187ae0 | 1,825 | rb | Ruby | spec/factories.rb | polytene/polytene | f5d316e734b8370fdf3160640f2d83f4c2053315 | [
"MIT"
] | 1 | 2015-06-23T08:25:17.000Z | 2015-06-23T08:25:17.000Z | spec/factories.rb | Polytene/polytene | f5d316e734b8370fdf3160640f2d83f4c2053315 | [
"MIT"
] | 2 | 2021-05-18T16:21:23.000Z | 2021-11-04T19:08:20.000Z | spec/factories.rb | polytene/polytene | f5d316e734b8370fdf3160640f2d83f4c2053315 | [
"MIT"
] | null | null | null | include ActionDispatch::TestProcess
FactoryGirl.define do
sequence(:private_token) { |n| "Private_Token_#{n}" }
sequence(:gitlab_ci_token) { |n| "Gitlab-CI-Token_#{n}" }
sequence(:project_token) { |n| "Project Token_#{n}" }
sequence(:id) {|n| n}
factory :runner do
private_token
user_id 1
name "MyString"
last_seen "2014-11-06 14:20:44"
is_active true
end
factory :role do
end
factory :profile do
user_id 897675454778
gitlab_private_token "asasa9ak9jjkkxu"
gitlab_url {Faker::Internet.uri('http')}
gitlab_ci_url {Faker::Internet.uri('http')}
end
factory :project_branch do
end
factory :project do
gitlab_ci_id {generate(:id)}
gitlab_ci_name "Project from CI"
gitlab_ci_token
gitlab_ci_default_ref 'master'
gitlab_url {Faker::Internet.uri('http')}
gitlab_ssh_url_to_repo {Faker::Internet.uri('http')}
gitlab_id 1
user_id 1
token {generate(:project_token)}
runner_id 1
end
sequence :sentence, aliases: [:title, :content] do
Faker::Lorem.sentence
end
sequence :name, aliases: [:file_name] do
Faker::Name.name
end
sequence(:url) { Faker::Internet.uri('http') }
factory :build do
status "failed"
started_at {Faker::Time.date}
finished_at {Faker::Time.date}
deployment_status "failed"
deployment_started_at {Faker::Time.date}
deployment_finished_at {Faker::Time.date}
runner_token "kd9jejdlksru3o"
sha "da39a3ee5e6b4b0d3255bfef95601890afd80709"
ref "master"
gitlab_ci_id 1
gitlab_ci_project_id 2
before_sha 'da39a3ee5e6b4b0d3255bfef95601890afd801212'
push_data {}.to_json
end
factory :user do
email { Faker::Internet.email }
private_token "asja8jas8hhd"
password "12345678"
password_confirmation { password }
end
end
| 23.101266 | 59 | 0.69589 |
ed6840a097a60247cdc6981d7b17b5b1e3e38059 | 388 | h | C | plugin_III/game_III/CQueuedMode.h | Aleksandr-Belousov/plugin-sdk | 5ca5f7d5575ae4138a4f165410a1acf0ae922260 | [
"Zlib"
] | 3 | 2020-01-25T18:54:05.000Z | 2022-03-23T09:27:09.000Z | plugin_III/game_III/CQueuedMode.h | Kewun0/plugin-sdk-master | 561188779aaa4946ba4ab8ac3e044f2044261e4b | [
"Zlib"
] | null | null | null | plugin_III/game_III/CQueuedMode.h | Kewun0/plugin-sdk-master | 561188779aaa4946ba4ab8ac3e044f2044261e4b | [
"Zlib"
] | 3 | 2020-10-03T21:34:05.000Z | 2020-12-19T01:52:38.000Z | /*
Plugin-SDK (Grand Theft Auto 3) header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#pragma once
#include "PluginBase.h"
struct CQueuedMode {
short Mode;
//short _pad2;
float Duration;
short MinZoom;
short MaxZoom;
};
VALIDATE_SIZE(CQueuedMode, 0xC);
| 19.4 | 59 | 0.685567 |
ccae221a3881b2e84176822afdead6a450171793 | 898 | swift | Swift | O3/TokenSale/TokenSaleTransactionInfoTableViewCell.swift | XuLiCC/OzoneWalletIOS | 7fe06bda30447c0562b8ef86d26dabe68ec3e792 | [
"MIT"
] | 42 | 2017-10-03T12:25:09.000Z | 2021-12-12T13:44:55.000Z | O3/TokenSale/TokenSaleTransactionInfoTableViewCell.swift | XuLiCC/OzoneWalletIOS | 7fe06bda30447c0562b8ef86d26dabe68ec3e792 | [
"MIT"
] | 42 | 2017-10-03T14:06:43.000Z | 2018-07-20T10:38:17.000Z | O3/TokenSale/TokenSaleTransactionInfoTableViewCell.swift | XuLiCC/OzoneWalletIOS | 7fe06bda30447c0562b8ef86d26dabe68ec3e792 | [
"MIT"
] | 17 | 2017-10-03T12:25:12.000Z | 2019-03-22T18:32:16.000Z | //
// TokenSaleTransactionInfoTableViewCell.swift
// O3
//
// Created by Apisit Toompakdee on 4/18/18.
// Copyright © 2018 drei. All rights reserved.
//
import UIKit
class TokenSaleTransactionInfoTableViewCell: UITableViewCell {
@IBOutlet var titleLabel: UILabel?
@IBOutlet var ValueLabel: UILabel?
struct TokenSaleTransactionItem {
var title: String
var value: String
}
var info: TokenSaleTransactionItem! {
didSet {
titleLabel?.text = info.title
ValueLabel?.text = info.value
}
}
override func awakeFromNib() {
titleLabel?.theme_textColor = O3Theme.lightTextColorPicker
ValueLabel?.theme_textColor = O3Theme.titleColorPicker
contentView.theme_backgroundColor = O3Theme.cardColorPicker
theme_backgroundColor = O3Theme.cardColorPicker
super.awakeFromNib()
}
}
| 24.944444 | 67 | 0.682628 |
8bfec23cb84d4ca7cd88c802baf664132c0e43ae | 1,733 | dart | Dart | example/lib/main.dart | Flutter-Italia-Developers/blur_matrix | a3e9ab786df31cb1b556d9fc6b0348b30869f3f5 | [
"BSD-2-Clause"
] | null | null | null | example/lib/main.dart | Flutter-Italia-Developers/blur_matrix | a3e9ab786df31cb1b556d9fc6b0348b30869f3f5 | [
"BSD-2-Clause"
] | null | null | null | example/lib/main.dart | Flutter-Italia-Developers/blur_matrix | a3e9ab786df31cb1b556d9fc6b0348b30869f3f5 | [
"BSD-2-Clause"
] | 1 | 2021-08-24T12:16:53.000Z | 2021-08-24T12:16:53.000Z | import 'package:blur_matrix/blur_matrix.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Blur Matrix Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late List<List<Color>> colors;
@override
void initState() {
// colors = [
// [Colors.red, Colors.blue, Colors.yellowAccent],
// [Colors.green, Colors.black, Colors.cyanAccent],
// [Colors.yellowAccent, Colors.deepPurpleAccent, Colors.white],
// [Colors.red, Colors.blue, Colors.yellowAccent],
// ];
colors = [
[Colors.green.withOpacity(0.6), Colors.white.withOpacity(0.8)],
[Colors.black.withOpacity(0.8), Colors.blue.withOpacity(0.6)],
];
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Stack(
fit: StackFit.expand,
children: [
Image.asset('assets/lago-blu-cervino.webp', fit: BoxFit.fill),
ConstrainedBox(
constraints: BoxConstraints.expand(),
child: BlurMatrixAnimate(
colors: colors,
),
),
],
),
);
}
}
| 25.115942 | 79 | 0.59146 |
1ac47212b5a75667e8e9d4465b33f575516e2836 | 841 | py | Python | benchmark/paddle/image/provider.py | OleNet/Paddle | 59271d643b13b13346889d12355611b9a2ce4e31 | [
"Apache-2.0"
] | 1 | 2016-10-07T20:40:11.000Z | 2016-10-07T20:40:11.000Z | benchmark/paddle/image/provider.py | anuranrc/Paddle | 21fa3eb0688459d3b71141d316e8358d31882b8d | [
"Apache-2.0"
] | 1 | 2017-05-26T18:33:00.000Z | 2017-05-26T18:33:00.000Z | benchmark/paddle/image/provider.py | anuranrc/Paddle | 21fa3eb0688459d3b71141d316e8358d31882b8d | [
"Apache-2.0"
] | 1 | 2016-10-07T00:50:53.000Z | 2016-10-07T00:50:53.000Z | import io, os
import random
import numpy as np
from paddle.trainer.PyDataProvider2 import *
def initHook(settings, height, width, color, num_class, **kwargs):
settings.height = height
settings.width = width
settings.color = color
settings.num_class = num_class
if settings.color:
settings.data_size = settings.height * settings.width * 3
else:
settings.data_size = settings.height * settings.width
settings.slots = [dense_vector(settings.data_size), integer_value(1)]
@provider(
init_hook=initHook, min_pool_size=-1, cache=CacheType.CACHE_PASS_IN_MEM)
def process(settings, file_list):
for i in xrange(1024):
img = np.random.rand(1, settings.data_size).reshape(-1, 1).flatten()
lab = random.randint(0, settings.num_class)
yield img.astype('float32'), int(lab)
| 31.148148 | 76 | 0.706302 |
91d9d393bf6900dd738177a9ef4eea33fca2afc1 | 113 | sql | SQL | users.sql | dineshredhat/terraform-mysql-azure | 296517fa430981bd1912d8ad0b281dc1141305b4 | [
"MIT"
] | null | null | null | users.sql | dineshredhat/terraform-mysql-azure | 296517fa430981bd1912d8ad0b281dc1141305b4 | [
"MIT"
] | null | null | null | users.sql | dineshredhat/terraform-mysql-azure | 296517fa430981bd1912d8ad0b281dc1141305b4 | [
"MIT"
] | null | null | null |
CREATE DATABASE books;
USE books;
CREATE TABLE authors (id INT, name VARCHAR(20), email VARCHAR(20));
| 14.125 | 68 | 0.681416 |
5a82b21e4759e4bd1aea7f243bccabdd79060c23 | 399 | kt | Kotlin | protocol/src/commonMain/kotlin/com/sourceplusplus/protocol/artifact/trace/TraceOrderType.kt | chess-equality/SourceMarker-Alpha | 7c157711d11b4836d38209daf32d4ee3b3d831de | [
"Apache-2.0"
] | null | null | null | protocol/src/commonMain/kotlin/com/sourceplusplus/protocol/artifact/trace/TraceOrderType.kt | chess-equality/SourceMarker-Alpha | 7c157711d11b4836d38209daf32d4ee3b3d831de | [
"Apache-2.0"
] | null | null | null | protocol/src/commonMain/kotlin/com/sourceplusplus/protocol/artifact/trace/TraceOrderType.kt | chess-equality/SourceMarker-Alpha | 7c157711d11b4836d38209daf32d4ee3b3d831de | [
"Apache-2.0"
] | null | null | null | package com.sourceplusplus.protocol.artifact.trace
/**
* todo: description.
*
* @since 0.0.1
* @author [Brandon Fergerson](mailto:[email protected])
*/
enum class TraceOrderType {
LATEST_TRACES,
SLOWEST_TRACES,
FAILED_TRACES;
//todo: not need to replace _TRACES?
val id = name.replace("_TRACES", "").toLowerCase()
val description = id.toLowerCase().capitalize()
}
| 22.166667 | 60 | 0.691729 |
cdd9fc41c617cfd895dc1c7851cd576fea8b6fd5 | 39,720 | cs | C# | Assets/Scripts/Generate/UnityEngine_Networking_UnityWebRequestWrap.cs | mx5566/ColaFrameWork | cc2b98112a280f9244002453175f39ba40cf0d19 | [
"MIT"
] | null | null | null | Assets/Scripts/Generate/UnityEngine_Networking_UnityWebRequestWrap.cs | mx5566/ColaFrameWork | cc2b98112a280f9244002453175f39ba40cf0d19 | [
"MIT"
] | null | null | null | Assets/Scripts/Generate/UnityEngine_Networking_UnityWebRequestWrap.cs | mx5566/ColaFrameWork | cc2b98112a280f9244002453175f39ba40cf0d19 | [
"MIT"
] | null | null | null | //this source code was auto-generated by tolua#, do not modify it
using System;
using LuaInterface;
public class UnityEngine_Networking_UnityWebRequestWrap
{
public static void Register(LuaState L)
{
L.BeginClass(typeof(UnityEngine.Networking.UnityWebRequest), typeof(System.Object));
L.RegFunction("ClearCookieCache", ClearCookieCache);
L.RegFunction("Dispose", Dispose);
L.RegFunction("SendWebRequest", SendWebRequest);
L.RegFunction("Abort", Abort);
L.RegFunction("GetRequestHeader", GetRequestHeader);
L.RegFunction("SetRequestHeader", SetRequestHeader);
L.RegFunction("GetResponseHeader", GetResponseHeader);
L.RegFunction("GetResponseHeaders", GetResponseHeaders);
L.RegFunction("Get", Get);
L.RegFunction("Delete", Delete);
L.RegFunction("Head", Head);
L.RegFunction("Put", Put);
L.RegFunction("Post", Post);
L.RegFunction("EscapeURL", EscapeURL);
L.RegFunction("UnEscapeURL", UnEscapeURL);
L.RegFunction("SerializeFormSections", SerializeFormSections);
L.RegFunction("GenerateBoundary", GenerateBoundary);
L.RegFunction("SerializeSimpleForm", SerializeSimpleForm);
L.RegFunction("New", _CreateUnityEngine_Networking_UnityWebRequest);
L.RegFunction("__tostring", ToLua.op_ToString);
L.RegVar("kHttpVerbGET", get_kHttpVerbGET, null);
L.RegVar("kHttpVerbHEAD", get_kHttpVerbHEAD, null);
L.RegVar("kHttpVerbPOST", get_kHttpVerbPOST, null);
L.RegVar("kHttpVerbPUT", get_kHttpVerbPUT, null);
L.RegVar("kHttpVerbCREATE", get_kHttpVerbCREATE, null);
L.RegVar("kHttpVerbDELETE", get_kHttpVerbDELETE, null);
L.RegVar("disposeCertificateHandlerOnDispose", get_disposeCertificateHandlerOnDispose, set_disposeCertificateHandlerOnDispose);
L.RegVar("disposeDownloadHandlerOnDispose", get_disposeDownloadHandlerOnDispose, set_disposeDownloadHandlerOnDispose);
L.RegVar("disposeUploadHandlerOnDispose", get_disposeUploadHandlerOnDispose, set_disposeUploadHandlerOnDispose);
L.RegVar("method", get_method, set_method);
L.RegVar("error", get_error, null);
L.RegVar("useHttpContinue", get_useHttpContinue, set_useHttpContinue);
L.RegVar("url", get_url, set_url);
L.RegVar("uri", get_uri, set_uri);
L.RegVar("responseCode", get_responseCode, null);
L.RegVar("uploadProgress", get_uploadProgress, null);
L.RegVar("isModifiable", get_isModifiable, null);
L.RegVar("isDone", get_isDone, null);
L.RegVar("result", get_result, null);
L.RegVar("downloadProgress", get_downloadProgress, null);
L.RegVar("uploadedBytes", get_uploadedBytes, null);
L.RegVar("downloadedBytes", get_downloadedBytes, null);
L.RegVar("redirectLimit", get_redirectLimit, set_redirectLimit);
L.RegVar("uploadHandler", get_uploadHandler, set_uploadHandler);
L.RegVar("downloadHandler", get_downloadHandler, set_downloadHandler);
L.RegVar("certificateHandler", get_certificateHandler, set_certificateHandler);
L.RegVar("timeout", get_timeout, set_timeout);
L.EndClass();
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _CreateUnityEngine_Networking_UnityWebRequest(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 0)
{
UnityEngine.Networking.UnityWebRequest obj = new UnityEngine.Networking.UnityWebRequest();
ToLua.PushObject(L, obj);
return 1;
}
else if (count == 1 && TypeChecker.CheckTypes<string>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
UnityEngine.Networking.UnityWebRequest obj = new UnityEngine.Networking.UnityWebRequest(arg0);
ToLua.PushObject(L, obj);
return 1;
}
else if (count == 1 && TypeChecker.CheckTypes<System.Uri>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = new UnityEngine.Networking.UnityWebRequest(arg0);
ToLua.PushObject(L, obj);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<string, string>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
string arg1 = ToLua.ToString(L, 2);
UnityEngine.Networking.UnityWebRequest obj = new UnityEngine.Networking.UnityWebRequest(arg0, arg1);
ToLua.PushObject(L, obj);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<System.Uri, string>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
string arg1 = ToLua.ToString(L, 2);
UnityEngine.Networking.UnityWebRequest obj = new UnityEngine.Networking.UnityWebRequest(arg0, arg1);
ToLua.PushObject(L, obj);
return 1;
}
else if (count == 4 && TypeChecker.CheckTypes<string, string, UnityEngine.Networking.DownloadHandler, UnityEngine.Networking.UploadHandler>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
string arg1 = ToLua.ToString(L, 2);
UnityEngine.Networking.DownloadHandler arg2 = (UnityEngine.Networking.DownloadHandler)ToLua.ToObject(L, 3);
UnityEngine.Networking.UploadHandler arg3 = (UnityEngine.Networking.UploadHandler)ToLua.ToObject(L, 4);
UnityEngine.Networking.UnityWebRequest obj = new UnityEngine.Networking.UnityWebRequest(arg0, arg1, arg2, arg3);
ToLua.PushObject(L, obj);
return 1;
}
else if (count == 4 && TypeChecker.CheckTypes<System.Uri, string, UnityEngine.Networking.DownloadHandler, UnityEngine.Networking.UploadHandler>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
string arg1 = ToLua.ToString(L, 2);
UnityEngine.Networking.DownloadHandler arg2 = (UnityEngine.Networking.DownloadHandler)ToLua.ToObject(L, 3);
UnityEngine.Networking.UploadHandler arg3 = (UnityEngine.Networking.UploadHandler)ToLua.ToObject(L, 4);
UnityEngine.Networking.UnityWebRequest obj = new UnityEngine.Networking.UnityWebRequest(arg0, arg1, arg2, arg3);
ToLua.PushObject(L, obj);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to ctor method: UnityEngine.Networking.UnityWebRequest.New");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int ClearCookieCache(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 0)
{
UnityEngine.Networking.UnityWebRequest.ClearCookieCache();
return 0;
}
else if (count == 1)
{
System.Uri arg0 = (System.Uri)ToLua.CheckObject<System.Uri>(L, 1);
UnityEngine.Networking.UnityWebRequest.ClearCookieCache(arg0);
return 0;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Networking.UnityWebRequest.ClearCookieCache");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Dispose(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)ToLua.CheckObject<UnityEngine.Networking.UnityWebRequest>(L, 1);
obj.Dispose();
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int SendWebRequest(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)ToLua.CheckObject<UnityEngine.Networking.UnityWebRequest>(L, 1);
UnityEngine.Networking.UnityWebRequestAsyncOperation o = obj.SendWebRequest();
ToLua.PushObject(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Abort(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)ToLua.CheckObject<UnityEngine.Networking.UnityWebRequest>(L, 1);
obj.Abort();
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetRequestHeader(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 2);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)ToLua.CheckObject<UnityEngine.Networking.UnityWebRequest>(L, 1);
string arg0 = ToLua.CheckString(L, 2);
string o = obj.GetRequestHeader(arg0);
LuaDLL.lua_pushstring(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int SetRequestHeader(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 3);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)ToLua.CheckObject<UnityEngine.Networking.UnityWebRequest>(L, 1);
string arg0 = ToLua.CheckString(L, 2);
string arg1 = ToLua.CheckString(L, 3);
obj.SetRequestHeader(arg0, arg1);
return 0;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetResponseHeader(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 2);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)ToLua.CheckObject<UnityEngine.Networking.UnityWebRequest>(L, 1);
string arg0 = ToLua.CheckString(L, 2);
string o = obj.GetResponseHeader(arg0);
LuaDLL.lua_pushstring(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetResponseHeaders(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)ToLua.CheckObject<UnityEngine.Networking.UnityWebRequest>(L, 1);
System.Collections.Generic.Dictionary<string,string> o = obj.GetResponseHeaders();
ToLua.PushSealed(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Get(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 1 && TypeChecker.CheckTypes<string>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Get(arg0);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 1 && TypeChecker.CheckTypes<System.Uri>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Get(arg0);
ToLua.PushObject(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Networking.UnityWebRequest.Get");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Delete(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 1 && TypeChecker.CheckTypes<string>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Delete(arg0);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 1 && TypeChecker.CheckTypes<System.Uri>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Delete(arg0);
ToLua.PushObject(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Networking.UnityWebRequest.Delete");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Head(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 1 && TypeChecker.CheckTypes<string>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Head(arg0);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 1 && TypeChecker.CheckTypes<System.Uri>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Head(arg0);
ToLua.PushObject(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Networking.UnityWebRequest.Head");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Put(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 2 && TypeChecker.CheckTypes<string, byte[]>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
byte[] arg1 = ToLua.CheckByteBuffer(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Put(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<System.Uri, byte[]>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
byte[] arg1 = ToLua.CheckByteBuffer(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Put(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<string, string>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
string arg1 = ToLua.ToString(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Put(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<System.Uri, string>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
string arg1 = ToLua.ToString(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Put(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Networking.UnityWebRequest.Put");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Post(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 2 && TypeChecker.CheckTypes<string, string>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
string arg1 = ToLua.ToString(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Post(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<System.Uri, string>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
string arg1 = ToLua.ToString(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Post(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<string, UnityEngine.WWWForm>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
UnityEngine.WWWForm arg1 = (UnityEngine.WWWForm)ToLua.ToObject(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Post(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<System.Uri, UnityEngine.WWWForm>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
UnityEngine.WWWForm arg1 = (UnityEngine.WWWForm)ToLua.ToObject(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Post(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<string, System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection>>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection> arg1 = (System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection>)ToLua.ToObject(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Post(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<System.Uri, System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection>>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection> arg1 = (System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection>)ToLua.ToObject(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Post(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<string, System.Collections.Generic.Dictionary<string,string>>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
System.Collections.Generic.Dictionary<string,string> arg1 = (System.Collections.Generic.Dictionary<string,string>)ToLua.ToObject(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Post(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 2 && TypeChecker.CheckTypes<System.Uri, System.Collections.Generic.Dictionary<string,string>>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
System.Collections.Generic.Dictionary<string,string> arg1 = (System.Collections.Generic.Dictionary<string,string>)ToLua.ToObject(L, 2);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Post(arg0, arg1);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 3 && TypeChecker.CheckTypes<string, System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection>, byte[]>(L, 1))
{
string arg0 = ToLua.ToString(L, 1);
System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection> arg1 = (System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection>)ToLua.ToObject(L, 2);
byte[] arg2 = ToLua.CheckByteBuffer(L, 3);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Post(arg0, arg1, arg2);
ToLua.PushObject(L, o);
return 1;
}
else if (count == 3 && TypeChecker.CheckTypes<System.Uri, System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection>, byte[]>(L, 1))
{
System.Uri arg0 = (System.Uri)ToLua.ToObject(L, 1);
System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection> arg1 = (System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection>)ToLua.ToObject(L, 2);
byte[] arg2 = ToLua.CheckByteBuffer(L, 3);
UnityEngine.Networking.UnityWebRequest o = UnityEngine.Networking.UnityWebRequest.Post(arg0, arg1, arg2);
ToLua.PushObject(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Networking.UnityWebRequest.Post");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int EscapeURL(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 1)
{
string arg0 = ToLua.CheckString(L, 1);
string o = UnityEngine.Networking.UnityWebRequest.EscapeURL(arg0);
LuaDLL.lua_pushstring(L, o);
return 1;
}
else if (count == 2)
{
string arg0 = ToLua.CheckString(L, 1);
System.Text.Encoding arg1 = (System.Text.Encoding)ToLua.CheckObject<System.Text.Encoding>(L, 2);
string o = UnityEngine.Networking.UnityWebRequest.EscapeURL(arg0, arg1);
LuaDLL.lua_pushstring(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Networking.UnityWebRequest.EscapeURL");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int UnEscapeURL(IntPtr L)
{
try
{
int count = LuaDLL.lua_gettop(L);
if (count == 1)
{
string arg0 = ToLua.CheckString(L, 1);
string o = UnityEngine.Networking.UnityWebRequest.UnEscapeURL(arg0);
LuaDLL.lua_pushstring(L, o);
return 1;
}
else if (count == 2)
{
string arg0 = ToLua.CheckString(L, 1);
System.Text.Encoding arg1 = (System.Text.Encoding)ToLua.CheckObject<System.Text.Encoding>(L, 2);
string o = UnityEngine.Networking.UnityWebRequest.UnEscapeURL(arg0, arg1);
LuaDLL.lua_pushstring(L, o);
return 1;
}
else
{
return LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Networking.UnityWebRequest.UnEscapeURL");
}
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int SerializeFormSections(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 2);
System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection> arg0 = (System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection>)ToLua.CheckObject(L, 1, typeof(System.Collections.Generic.List<UnityEngine.Networking.IMultipartFormSection>));
byte[] arg1 = ToLua.CheckByteBuffer(L, 2);
byte[] o = UnityEngine.Networking.UnityWebRequest.SerializeFormSections(arg0, arg1);
ToLua.Push(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GenerateBoundary(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 0);
byte[] o = UnityEngine.Networking.UnityWebRequest.GenerateBoundary();
ToLua.Push(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int SerializeSimpleForm(IntPtr L)
{
try
{
ToLua.CheckArgsCount(L, 1);
System.Collections.Generic.Dictionary<string,string> arg0 = (System.Collections.Generic.Dictionary<string,string>)ToLua.CheckObject(L, 1, typeof(System.Collections.Generic.Dictionary<string,string>));
byte[] o = UnityEngine.Networking.UnityWebRequest.SerializeSimpleForm(arg0);
ToLua.Push(L, o);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_kHttpVerbGET(IntPtr L)
{
try
{
LuaDLL.lua_pushstring(L, UnityEngine.Networking.UnityWebRequest.kHttpVerbGET);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_kHttpVerbHEAD(IntPtr L)
{
try
{
LuaDLL.lua_pushstring(L, UnityEngine.Networking.UnityWebRequest.kHttpVerbHEAD);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_kHttpVerbPOST(IntPtr L)
{
try
{
LuaDLL.lua_pushstring(L, UnityEngine.Networking.UnityWebRequest.kHttpVerbPOST);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_kHttpVerbPUT(IntPtr L)
{
try
{
LuaDLL.lua_pushstring(L, UnityEngine.Networking.UnityWebRequest.kHttpVerbPUT);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_kHttpVerbCREATE(IntPtr L)
{
try
{
LuaDLL.lua_pushstring(L, UnityEngine.Networking.UnityWebRequest.kHttpVerbCREATE);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_kHttpVerbDELETE(IntPtr L)
{
try
{
LuaDLL.lua_pushstring(L, UnityEngine.Networking.UnityWebRequest.kHttpVerbDELETE);
return 1;
}
catch (Exception e)
{
return LuaDLL.toluaL_exception(L, e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_disposeCertificateHandlerOnDispose(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
bool ret = obj.disposeCertificateHandlerOnDispose;
LuaDLL.lua_pushboolean(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index disposeCertificateHandlerOnDispose on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_disposeDownloadHandlerOnDispose(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
bool ret = obj.disposeDownloadHandlerOnDispose;
LuaDLL.lua_pushboolean(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index disposeDownloadHandlerOnDispose on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_disposeUploadHandlerOnDispose(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
bool ret = obj.disposeUploadHandlerOnDispose;
LuaDLL.lua_pushboolean(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index disposeUploadHandlerOnDispose on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_method(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
string ret = obj.method;
LuaDLL.lua_pushstring(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index method on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_error(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
string ret = obj.error;
LuaDLL.lua_pushstring(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index error on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_useHttpContinue(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
bool ret = obj.useHttpContinue;
LuaDLL.lua_pushboolean(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index useHttpContinue on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_url(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
string ret = obj.url;
LuaDLL.lua_pushstring(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index url on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_uri(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
System.Uri ret = obj.uri;
ToLua.PushObject(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index uri on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_responseCode(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
long ret = obj.responseCode;
LuaDLL.tolua_pushint64(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index responseCode on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_uploadProgress(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
float ret = obj.uploadProgress;
LuaDLL.lua_pushnumber(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index uploadProgress on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_isModifiable(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
bool ret = obj.isModifiable;
LuaDLL.lua_pushboolean(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index isModifiable on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_isDone(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
bool ret = obj.isDone;
LuaDLL.lua_pushboolean(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index isDone on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_result(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
UnityEngine.Networking.UnityWebRequest.Result ret = obj.result;
ToLua.Push(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index result on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_downloadProgress(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
float ret = obj.downloadProgress;
LuaDLL.lua_pushnumber(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index downloadProgress on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_uploadedBytes(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
ulong ret = obj.uploadedBytes;
LuaDLL.tolua_pushuint64(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index uploadedBytes on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_downloadedBytes(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
ulong ret = obj.downloadedBytes;
LuaDLL.tolua_pushuint64(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index downloadedBytes on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_redirectLimit(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
int ret = obj.redirectLimit;
LuaDLL.lua_pushinteger(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index redirectLimit on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_uploadHandler(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
UnityEngine.Networking.UploadHandler ret = obj.uploadHandler;
ToLua.PushObject(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index uploadHandler on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_downloadHandler(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
UnityEngine.Networking.DownloadHandler ret = obj.downloadHandler;
ToLua.PushObject(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index downloadHandler on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_certificateHandler(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
UnityEngine.Networking.CertificateHandler ret = obj.certificateHandler;
ToLua.PushObject(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index certificateHandler on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_timeout(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
int ret = obj.timeout;
LuaDLL.lua_pushinteger(L, ret);
return 1;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index timeout on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_disposeCertificateHandlerOnDispose(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
bool arg0 = LuaDLL.luaL_checkboolean(L, 2);
obj.disposeCertificateHandlerOnDispose = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index disposeCertificateHandlerOnDispose on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_disposeDownloadHandlerOnDispose(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
bool arg0 = LuaDLL.luaL_checkboolean(L, 2);
obj.disposeDownloadHandlerOnDispose = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index disposeDownloadHandlerOnDispose on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_disposeUploadHandlerOnDispose(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
bool arg0 = LuaDLL.luaL_checkboolean(L, 2);
obj.disposeUploadHandlerOnDispose = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index disposeUploadHandlerOnDispose on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_method(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
string arg0 = ToLua.CheckString(L, 2);
obj.method = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index method on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_useHttpContinue(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
bool arg0 = LuaDLL.luaL_checkboolean(L, 2);
obj.useHttpContinue = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index useHttpContinue on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_url(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
string arg0 = ToLua.CheckString(L, 2);
obj.url = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index url on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_uri(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
System.Uri arg0 = (System.Uri)ToLua.CheckObject<System.Uri>(L, 2);
obj.uri = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index uri on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_redirectLimit(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
int arg0 = (int)LuaDLL.luaL_checknumber(L, 2);
obj.redirectLimit = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index redirectLimit on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_uploadHandler(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
UnityEngine.Networking.UploadHandler arg0 = (UnityEngine.Networking.UploadHandler)ToLua.CheckObject<UnityEngine.Networking.UploadHandler>(L, 2);
obj.uploadHandler = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index uploadHandler on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_downloadHandler(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
UnityEngine.Networking.DownloadHandler arg0 = (UnityEngine.Networking.DownloadHandler)ToLua.CheckObject<UnityEngine.Networking.DownloadHandler>(L, 2);
obj.downloadHandler = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index downloadHandler on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_certificateHandler(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
UnityEngine.Networking.CertificateHandler arg0 = (UnityEngine.Networking.CertificateHandler)ToLua.CheckObject<UnityEngine.Networking.CertificateHandler>(L, 2);
obj.certificateHandler = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index certificateHandler on a nil value");
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_timeout(IntPtr L)
{
object o = null;
try
{
o = ToLua.ToObject(L, 1);
UnityEngine.Networking.UnityWebRequest obj = (UnityEngine.Networking.UnityWebRequest)o;
int arg0 = (int)LuaDLL.luaL_checknumber(L, 2);
obj.timeout = arg0;
return 0;
}
catch(Exception e)
{
return LuaDLL.toluaL_exception(L, e, o, "attempt to index timeout on a nil value");
}
}
}
| 29.248895 | 278 | 0.717649 |
cd451447fc3d8f8c4a199faf28913daa4b825a3a | 32,839 | cs | C# | MedicationMngAPI/App_Code/Service.cs | johphil/MedicationMngApp | 6e2fc996d60d1a2fcfb17aaf260b90636b25ec3f | [
"MIT"
] | null | null | null | MedicationMngAPI/App_Code/Service.cs | johphil/MedicationMngApp | 6e2fc996d60d1a2fcfb17aaf260b90636b25ec3f | [
"MIT"
] | 1 | 2021-06-12T01:45:45.000Z | 2021-06-12T01:49:06.000Z | MedicationMngAPI/App_Code/Service.cs | johphil/MedicationMngApp | 6e2fc996d60d1a2fcfb17aaf260b90636b25ec3f | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
//Database Conenction String
protected string conStr = ConfigurationManager.ConnectionStrings["MEDMNG_DBF"].ConnectionString;
/// <summary>
/// Used to get the account information of the user
/// </summary>
/// <param name="account_id">ID assigned to the user's account</param>
/// <returns>Account object which contains the information</returns>
public Account GetAccountDetails(string account_id)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spGetAccountDetails", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("id", SqlDbType.Int).Value = DBConvert.From(int.Parse(account_id));
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
return new Account
{
Account_ID = DBConvert.To<int>(reader[0]),
FirstName = DBConvert.To<string>(reader[1]),
LastName = DBConvert.To<string>(reader[2]),
Birthday = DBConvert.To<string>(reader[3]),
Email = DBConvert.To<string>(reader[4]),
Username = DBConvert.To<string>(reader[5]),
Date_Registered = DBConvert.To<string>(reader[6])
};
}
}
}
}
return null;
}
catch
{
return null;
}
}
/// <summary>
/// Used to add a new user account after successfull registration
/// </summary>
/// <param name="account">Account object which contains the supplied information by the user</param>
/// <returns>Returns integer value -69 if username exists, -70 if email exists, -1 if failed, and 1 if success</returns>
public int AddAccount(Account account)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spAddAccount", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("firstname", SqlDbType.VarChar, 99).Value = DBConvert.From(account.FirstName);
command.Parameters.Add("lastname", SqlDbType.VarChar, 99).Value = DBConvert.From(account.LastName);
command.Parameters.Add("birthday", SqlDbType.Date).Value = DBConvert.From(account.Birthday);
command.Parameters.Add("email", SqlDbType.VarChar, 99).Value = DBConvert.From(account.Email);
command.Parameters.Add("username", SqlDbType.VarChar, 99).Value = DBConvert.From(account.Username);
command.Parameters.Add("password", SqlDbType.VarChar, 99).Value = DBConvert.From(PassHash.MD5Hash(account.Password));
connection.Open();
return (int)command.ExecuteScalar();
}
}
}
catch
{
return -1;
}
}
/// <summary>
/// Used to updated the user's account information to the database
/// </summary>
/// <param name="account">Account object which contains the supplied information by the user</param>
/// <returns>returns positive integer if success otherwise failed</returns>
public int UpdateAccountDetails(Account account)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spUpdateAccountDetails", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("account_id", SqlDbType.Int).Value = DBConvert.From(account.Account_ID);
command.Parameters.Add("firstname", SqlDbType.VarChar, 99).Value = DBConvert.From(account.FirstName);
command.Parameters.Add("lastname", SqlDbType.VarChar, 99).Value = DBConvert.From(account.LastName);
connection.Open();
return command.ExecuteNonQuery();
}
}
}
catch
{
return -1;
}
}
/// <summary>
/// Used to activate or deactivate a medication
/// </summary>
/// <param name="med_take_id">ID assigned to the selected medication</param>
/// <param name="enabled">1 if true, 0 if false</param>
/// <returns>returns positive integer if success otherwise failed</returns>
public int UpdateMedTakeEnable(string med_take_id, string enabled)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spUpdateMedTakeStatus", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("med_take_id", SqlDbType.Int).Value = DBConvert.From(int.Parse(med_take_id));
command.Parameters.Add("isactive", SqlDbType.Bit).Value = DBConvert.From(int.Parse(enabled));
connection.Open();
return command.ExecuteNonQuery();
}
}
}
catch
{
return -1;
}
}
/// <summary>
/// Used to update the user's account password
/// </summary>
/// <param name="account_id">ID assigned to the user's account</param>
/// <param name="old_password">Current password of the user</param>
/// <param name="new_password">New password supplied by the user</param>
/// <returns>returns positive integer if success otherwise failed</returns>
public int UpdateAccountPassword(int account_id, string old_password, string new_password)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spUpdateAccountPassword", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("account_id", SqlDbType.Int).Value = DBConvert.From(account_id);
command.Parameters.Add("oldPw", SqlDbType.VarChar, 99).Value = DBConvert.From(PassHash.MD5Hash(old_password));
command.Parameters.Add("newPw", SqlDbType.VarChar, 99).Value = DBConvert.From(PassHash.MD5Hash(new_password));
connection.Open();
return (int)command.ExecuteScalar();
}
}
}
catch
{
return -1;
}
}
/// <summary>
/// Used to authenticate the user credentials before accessing the main interface of the application
/// </summary>
/// <param name="username">Username of the user</param>
/// <param name="password">Password of the user</param>
/// <returns>returns the account id of the authenticated user</returns>
public int LoginAccount(string username, string password)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spLoginAccount", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("username", SqlDbType.VarChar, 99).Value = DBConvert.From(username);
command.Parameters.Add("password", SqlDbType.VarChar, 99).Value = DBConvert.From(PassHash.MD5Hash(password));
connection.Open();
return (int)command.ExecuteScalar(); //returns id of user
}
}
}
catch
{
return -1;
}
}
/// <summary>
/// Used to add the user's ratings and recommendation
/// </summary>
/// <param name="ratings">Ratings_Recommendation object which contains the ratings and feedback by the user</param>
/// <returns>returns positive integer if success otherwise failed</returns>
public int AddRatingsRecommendation(Ratings_Recommendation ratings)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spAddRatings", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("account_id", SqlDbType.Int).Value = DBConvert.From(ratings.Account_ID);
command.Parameters.Add("ratings", SqlDbType.Int).Value = DBConvert.From(ratings.Ratings);
command.Parameters.Add("recommendation", SqlDbType.VarChar).Value = DBConvert.From(ratings.Recommendation);
connection.Open();
return command.ExecuteNonQuery();
}
}
}
catch
{
return -1;
}
}
/// <summary>
/// Used to add a new medication from the user
/// </summary>
/// <param name="medtake">MedTake object</param>
/// <param name="medtakeschedules">Collection of MedTakeSchedule object</param>
/// <returns>returns positive integer if success otherwise failed</returns>
public int AddMedTake(MedTake medtake, List<MedTakeSchedule> medtakeschedules)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
connection.Open();
using (SqlTransaction transaction = connection.BeginTransaction())
{
try
{
using (SqlCommand command = new SqlCommand("spAddMedTake", connection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("account_id", SqlDbType.Int).Value = DBConvert.From(medtake.Account_ID);
command.Parameters.Add("med_name", SqlDbType.VarChar, 20).Value = DBConvert.From(medtake.Med_Name);
command.Parameters.Add("med_count", SqlDbType.Int).Value = DBConvert.From(medtake.Med_Count);
command.Parameters.Add("med_count_critical", SqlDbType.Int).Value = DBConvert.From(medtake.Med_Count_Critical);
command.Parameters.Add("med_type_id", SqlDbType.Int).Value = DBConvert.From(medtake.Med_Type_ID);
medtake.Med_Take_ID = (int)command.ExecuteScalar();
if (medtake.Med_Take_ID > 0)
{
command.Parameters.Clear();
command.CommandText = "spAddMedTakeSchedule";
foreach (var schedule in medtakeschedules)
{
command.Parameters.Add("med_take_id", SqlDbType.Int).Value = DBConvert.From(medtake.Med_Take_ID);
command.Parameters.Add("day_of_week", SqlDbType.Int).Value = DBConvert.From(schedule.Day_Of_Week);
command.Parameters.Add("dosage_count", SqlDbType.Int).Value = DBConvert.From(schedule.Dosage_Count);
command.Parameters.Add("time", SqlDbType.Time, 7).Value = DBConvert.From(schedule.Time);
command.ExecuteNonQuery();
command.Parameters.Clear();
}
}
}
transaction.Commit();
}
catch
{
transaction.Rollback();
return -1;
}
}
}
return 1;
}
catch
{
return -1;
}
}
/// <summary>
/// Used to get all medications added by the user
/// </summary>
/// <param name="account_id">ID assigned to the user</param>
/// <returns>returns a collection of medications</returns>
public List<MedTake> GetMedTakes(string account_id)
{
try
{
List<MedTake> collection = new List<MedTake>();
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spGetMedTakes", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("account_id", SqlDbType.Int).Value = DBConvert.From(int.Parse(account_id));
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
collection.Add(new MedTake
{
Med_Take_ID = DBConvert.To<int>(reader[0]),
Account_ID = DBConvert.To<int>(reader[1]),
Med_Name = DBConvert.To<string>(reader[2]),
Med_Count = DBConvert.To<int>(reader[3]),
Med_Count_Critical = DBConvert.To<int>(reader[4]),
Med_Type_ID = DBConvert.To<int>(reader[5]),
Med_Type_Name = DBConvert.To<string>(reader[6]),
IsCount = DBConvert.To<bool>(reader[7]),
Image = DBConvert.To<string>(reader[8]),
IsActive = DBConvert.To<bool>(reader[9])
});
}
}
}
}
return collection;
}
catch
{
return null;
}
}
/// <summary>
/// Used to update the information of the selected medication
/// </summary>
/// <param name="medtake">MedTake object</param>
/// <param name="deletemedtakeschedules">List of MedTakes that will be deleted</param>
/// <param name="updatemedtakeschedules">List of MedTakes that will be updated</param>
/// <param name="createmedtakeschedules">List of MedTakes that will be created</param>
/// <returns>returns positive integer if success otherwise failed</returns>
public int UpdateMedTake(MedTake medtake, List<MedTakeSchedule> deletemedtakeschedules, List<MedTakeSchedule> updatemedtakeschedules, List<MedTakeSchedule> createmedtakeschedules)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
connection.Open();
using (SqlTransaction transaction = connection.BeginTransaction())
{
try
{
using (SqlCommand command = new SqlCommand("spUpdateMedTake", connection, transaction))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("med_take_id", SqlDbType.Int).Value = DBConvert.From(medtake.Med_Take_ID);
command.Parameters.Add("med_name", SqlDbType.VarChar, 20).Value = DBConvert.From(medtake.Med_Name);
command.Parameters.Add("med_count", SqlDbType.Int).Value = DBConvert.From(medtake.Med_Count);
command.Parameters.Add("med_count_critical", SqlDbType.Int).Value = DBConvert.From(medtake.Med_Count_Critical);
command.Parameters.Add("med_type_id", SqlDbType.Int).Value = DBConvert.From(medtake.Med_Type_ID);
int result = command.ExecuteNonQuery();
if (result > 0)
{
//Create MedTake Schedule
if (createmedtakeschedules != null && createmedtakeschedules.Count > 0)
{
command.Parameters.Clear();
command.CommandText = "spAddMedTakeSchedule";
foreach (var schedule in createmedtakeschedules)
{
command.Parameters.Add("med_take_id", SqlDbType.Int).Value = DBConvert.From(medtake.Med_Take_ID);
command.Parameters.Add("day_of_week", SqlDbType.Int).Value = DBConvert.From(schedule.Day_Of_Week);
command.Parameters.Add("dosage_count", SqlDbType.Int).Value = DBConvert.From(schedule.Dosage_Count);
command.Parameters.Add("time", SqlDbType.Time, 7).Value = DBConvert.From(schedule.Time);
command.ExecuteNonQuery();
command.Parameters.Clear();
}
}
//Update MedTake Schedule
if (updatemedtakeschedules != null && updatemedtakeschedules.Count > 0)
{
command.Parameters.Clear();
command.CommandText = "spUpdateMedTakeSchedule";
foreach (var schedule in updatemedtakeschedules)
{
command.Parameters.Add("med_take_schedule_id", SqlDbType.Int).Value = DBConvert.From(schedule.Med_Take_Schedule_ID);
command.Parameters.Add("day_of_week", SqlDbType.Int).Value = DBConvert.From(schedule.Day_Of_Week);
command.Parameters.Add("dosage_count", SqlDbType.Int).Value = DBConvert.From(schedule.Dosage_Count);
command.Parameters.Add("time", SqlDbType.Time, 7).Value = DBConvert.From(schedule.Time);
command.ExecuteNonQuery();
command.Parameters.Clear();
}
}
//Delete MedTake Schedule
if (deletemedtakeschedules != null && deletemedtakeschedules.Count > 0)
{
command.Parameters.Clear();
command.CommandText = "spDeleteMedTakeSchedule";
foreach (var schedule in deletemedtakeschedules)
{
command.Parameters.Add("med_take_schedule_id", SqlDbType.Int).Value = DBConvert.From(schedule.Med_Take_Schedule_ID);
command.ExecuteNonQuery();
command.Parameters.Clear();
}
}
}
}
transaction.Commit();
}
catch
{
transaction.Rollback();
return -1;
}
}
}
return 1;
}
catch
{
return -1;
}
}
/// <summary>
/// Used to delete a medication
/// </summary>
/// <param name="med_take_id">ID assigned to the selected medication</param>
/// <returns>returns positive integer if success otherwise failed</returns>
public int DeleteMedTake(string med_take_id)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spDeleteMedTake", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("med_take_id", SqlDbType.Int).Value = DBConvert.From(int.Parse(med_take_id));
connection.Open();
return command.ExecuteNonQuery();
}
}
}
catch
{
return -1;
}
}
/// <summary>
/// Used to get all available types of medication from the database
/// </summary>
/// <returns>returns the list of medtypes</returns>
public List<MedType> GetMedTypes()
{
try
{
List<MedType> collection = new List<MedType>();
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spGetMedTypes", connection))
{
command.CommandType = CommandType.StoredProcedure;
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
collection.Add(new MedType
{
Med_Type_ID = DBConvert.To<int>(reader[0]),
Med_Type_Name = DBConvert.To<string>(reader[1]),
IsCount = DBConvert.To<bool>(reader[2]),
Image = DBConvert.To<string>(reader[3])
});
}
}
}
}
return collection;
}
catch
{
return null;
}
}
/// <summary>
/// Used to get the schedules of a medication
/// </summary>
/// <param name="med_take_id">ID of the selected medication</param>
/// <returns>returns a collection of MedTakeSchedule</returns>
public List<MedTakeSchedule> GetMedTakeSchedules(string med_take_id)
{
try
{
List<MedTakeSchedule> collection = new List<MedTakeSchedule>();
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spGetMedTakeSchedules", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("med_take_id", SqlDbType.Int).Value = DBConvert.From(int.Parse(med_take_id));
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
collection.Add(new MedTakeSchedule
{
Med_Take_Schedule_ID = DBConvert.To<int>(reader[0]),
Med_Take_ID = DBConvert.To<int>(reader[1]),
Day_Of_Week = DBConvert.To<int>(reader[2]),
Dosage_Count = DBConvert.To<int>(reader[3]),
Time = DBConvert.To<TimeSpan>(reader[4]).ToString(),
});
}
}
}
}
return collection;
}
catch
{
return null;
}
}
/// <summary>
/// Used to get the medications scheduled for the day
/// </summary>
/// <param name="account_id">ID assigned to the user</param>
/// <param name="day_of_week">Day of week in integer</param>
/// <returns>returns the list of medications to be taken for the day</returns>
public List<MedTakeToday> GetMedTakeToday(string account_id, string day_of_week)
{
try
{
List<MedTakeToday> collection = new List<MedTakeToday>();
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spGetMedTakeToday", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("account_id", SqlDbType.Int).Value = DBConvert.From(int.Parse(account_id));
command.Parameters.Add("day_of_week", SqlDbType.Int).Value = DBConvert.From(int.Parse(day_of_week));
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
collection.Add(new MedTakeToday
{
Med_Take_ID = DBConvert.To<int>(reader[0]),
Med_Take_Schedule_ID = DBConvert.To<int>(reader[1]),
Time = DBConvert.To<TimeSpan>(reader[2]).ToString(),
Day_Of_Week = DBConvert.To<int>(reader[3]),
Med_Name = DBConvert.To<string>(reader[4]),
Dosage_Count = DBConvert.To<int>(reader[5]),
Image = DBConvert.To<string>(reader[6]),
Last_Take = DBConvert.To<DateTime?>(reader[7]),
});
}
}
}
}
return collection;
}
catch
{
return null;
}
}
/// <summary>
/// Used to get the password of a user
/// </summary>
/// <param name="email">Email of the user</param>
/// <returns>returns the decrypted password</returns>
public string GetAccountPassword(string email)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spGetAccountPassword", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("email", SqlDbType.VarChar, 99).Value = DBConvert.From(email);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
return PassHash.MD5HashDecrypt(DBConvert.To<string>(reader[0]));
}
}
}
}
return null;
}
catch
{
return null;
}
}
/// <summary>
/// Used to get the logs information of an account
/// </summary>
/// <param name="account_id">ID assigned to the user</param>
/// <returns>returns the list of AccountLog</returns>
public List<AccountLog> GetAccountLogs(string account_id)
{
try
{
List<AccountLog> collection = new List<AccountLog>();
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spGetAccountLogs", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("account_id", SqlDbType.Int).Value = DBConvert.From(int.Parse(account_id));
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
collection.Add(new AccountLog
{
Account_Log_ID = DBConvert.To<int>(reader[0]),
Account_ID = DBConvert.To<int>(reader[1]),
Date = DBConvert.To<DateTime>(reader[2]),
Tag = DBConvert.To<string>(reader[3]),
Description = DBConvert.To<string>(reader[4])
});
}
}
}
}
return collection;
}
catch
{
return null;
}
}
/// <summary>
/// Used to set the status of the selected medication schedule as taken
/// </summary>
/// <param name="med_take_schedule_id">ID assigned to the medication schedule</param>
/// <param name="med_take_id">ID assigned to the medication</param>
/// <returns>returns positive integer if success otherwise failed</returns>
public int TakeMedicine(string med_take_schedule_id, string med_take_id)
{
try
{
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spTakeMedicine", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("med_take_id", SqlDbType.Int).Value = DBConvert.From(int.Parse(med_take_id));
command.Parameters.Add("med_take_schedule_id", SqlDbType.Int).Value = DBConvert.From(int.Parse(med_take_schedule_id));
connection.Open();
return (int)command.ExecuteScalar();
}
}
}
catch
{
return -1;
}
}
/// <summary>
/// Used to get the intake logs of a user
/// </summary>
/// <param name="account_id">ID assigned to the user</param>
/// <returns>returns the list of intake logs of a user</returns>
public List<IntakeLog> GetIntakeLogs(string account_id)
{
try
{
List<IntakeLog> collection = new List<IntakeLog>();
using (SqlConnection connection = new SqlConnection(conStr))
{
using (SqlCommand command = new SqlCommand("spGetIntakeLogs", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("account_id", SqlDbType.Int).Value = DBConvert.From(int.Parse(account_id));
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
collection.Add(new IntakeLog
{
Intake_Log_ID = DBConvert.To<int>(reader[0]),
Account_ID = DBConvert.To<int>(reader[1]),
Med_Name = DBConvert.To<string>(reader[2]),
Dosage_Count = DBConvert.To<int>(reader[3]),
Med_Type_Name = DBConvert.To<string>(reader[4]),
Image = DBConvert.To<string>(reader[5]),
Taken = DBConvert.To<string>(reader.GetDateTime(6).ToDateWithTime())
});
}
}
}
}
return collection;
}
catch
{
return null;
}
}
}
| 43.152431 | 183 | 0.506806 |
1451710f3d68139efd5e249cca7279f748b0b197 | 549 | ts | TypeScript | src/config/index.ts | crysfel/cc-rest-api | fd12e4989a491e092da95087bc470706628fb8c9 | [
"MIT"
] | null | null | null | src/config/index.ts | crysfel/cc-rest-api | fd12e4989a491e092da95087bc470706628fb8c9 | [
"MIT"
] | 4 | 2020-09-04T21:54:34.000Z | 2022-02-12T10:30:34.000Z | src/config/index.ts | crysfel/cc-rest-api | fd12e4989a491e092da95087bc470706628fb8c9 | [
"MIT"
] | null | null | null |
const config = {
mongo: {
url: process.env.MONGO_DATABASE_URL,
},
auth0: {
// to decode the token
frontend: {
CLIENT_ID: process.env.AUTH0_FRONTEND_CLIENT_ID,
CLIENT_SECRET: process.env.AUTH0_FRONTEND_CLIENT_SECRET,
DOMAIN: process.env.AUTH0_DOMAIN,
},
// To get access to auth0 admin features
backend: {
CLIENT_ID: process.env.AUTH0_BACKEND_CLIENT_ID,
CLIENT_SECRET: process.env.AUTH0_BACKEND_CLIENT_SECRET,
DOMAIN: process.env.AUTH0_DOMAIN,
},
},
};
export default config;
| 23.869565 | 62 | 0.68306 |
69f514fed791511d6050b8ba56b4033ad51c72da | 6,649 | sh | Shell | dockerfiles/zoneminder/files/zmlinkcontent.sh | hyperbolic2346/coreos | 00509cb185c957ff93a944a92b2ff9201652234d | [
"MIT"
] | null | null | null | dockerfiles/zoneminder/files/zmlinkcontent.sh | hyperbolic2346/coreos | 00509cb185c957ff93a944a92b2ff9201652234d | [
"MIT"
] | null | null | null | dockerfiles/zoneminder/files/zmlinkcontent.sh | hyperbolic2346/coreos | 00509cb185c957ff93a944a92b2ff9201652234d | [
"MIT"
] | null | null | null | #!/bin/bash
# The purpose of this file is to create the symlinks in the web folder to the content folder. It can use an existing content folder or create a new one.
# Set the content dir default to be the one supplied to cmake
ZM_PATH_CONTENT="/var/lib/zoneminder"
echo "*** This bash script creates the nessecary symlinks for the zoneminder content"
echo "*** It can use an existing content folder or create a new one"
echo "*** For usage: use -h"
echo "*** The default content directory is: $ZM_PATH_CONTENT"
echo ""
usage()
{
cat <<EOF
Usage: $0 [-q] [-z zm.conf] [-w WEB DIRECTORY] [CONTENT DIRECTORY]
OPTIONS:
-h Show this message and quit
-z ZoneMinder configuration file
-w Override the web directory from zm.conf
-q Quick mode. Do not change ownership recursively.
If the -w option is not used to specify the path to the web directory,
the script will use the path from zoneminder's configuration file.
If the -z option is used, the argument will be used instead of zm.conf
Otherwise, it will attempt to read zm.conf from the local directory.
If that fails, it will try from /etc/zm.conf
EOF
}
while getopts "hz:w:q" OPTION
do
case $OPTION in
h)
usage
exit 50
;;
z)
ZM_CONFIG=$OPTARG
;;
w)
ZM_PATH_WEB_FORCE=$OPTARG
;;
q)
QUICK=1
;;
esac
done
shift $(( OPTIND - 1 ))
# Lets check that we are root
if [ "$(id -u)" != "0" ]; then
echo "Error: This script needs to run as root."
exit 1
fi
# Check if zm.conf was supplied as an argument and that it exists
if [[ -n "$ZM_CONFIG" && ! -f "$ZM_CONFIG" ]]; then
echo "The zoneminder configuration file $ZM_CONFIG does not exist!"
exit 40
fi
# Load zm.conf
if [ -n "$ZM_CONFIG" ]; then
echo "Using custom zm.conf $ZM_CONFIG"
source "$ZM_CONFIG"
elif [ -f "zm.conf" ]; then
echo "Using local zm.conf"
source "zm.conf"
elif [ -f "/etc/zm.conf"]; then
echo "Using system zm.conf"
source "/etc/zm.conf"
else
echo "Failed locating zoneminder configuration file (zm.conf)\nUse the -z option to specify the full path to the zoneminder configuration file"
exit 45
fi
# Override the web directory path from zm.conf
if [ -n "$ZM_PATH_WEB_FORCE" ]; then
ZM_PATH_WEB="$(readlink -f $ZM_PATH_WEB_FORCE)"
fi
# Override the default content path
if [[ -n "$@" ]]; then
ZM_PATH_CONTENT="$(readlink -f $@)"
fi
# Print some information
echo "Web folder : $ZM_PATH_WEB"
echo "Content folder : $ZM_PATH_CONTENT"
echo ""
# Verify the web folder is a real directory
echo -n "Verifying the web folder is a directory... "
if [ -d "$ZM_PATH_WEB" ]; then
echo "OK"
else
echo "Failed"
exit 3
fi
# Check if the content folder exists, and if not, create it
echo -n "Checking if the content folder exists... "
if [ -d "$ZM_PATH_CONTENT" ]; then
echo "Yes"
else
echo "No"
echo -n "Creating the content folder... "
mkdir "$ZM_PATH_CONTENT"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 4
fi
fi
# Check if the content/images folder exists, and if not, create it
echo -n "Checking if the images folder exists inside the content folder... "
if [ -d "$ZM_PATH_CONTENT/images" ]; then
echo "Yes"
else
echo "No"
echo -n "Creating the images folder inside the content folder... "
mkdir "$ZM_PATH_CONTENT/images"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 6
fi
fi
# Check if the content/events folder exists, and if not, create it
echo -n "Checking if the events folder exists inside the content folder... "
if [ -d "$ZM_PATH_CONTENT/events" ]; then
echo "Yes"
else
echo "No"
echo -n "Creating the events folder inside the content folder... "
mkdir "$ZM_PATH_CONTENT/events"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 7
fi
fi
if [ -d "$ZM_PATH_WEB/images" ]; then
if [ -L "$ZM_PATH_WEB/images" ]; then
echo -n "Unlinking current symlink for the images folder... "
unlink "$ZM_PATH_WEB/images"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 35
fi
else
echo "Existing $ZM_PATH_WEB/images is not a symlink. Aborting to prevent data loss"
exit 10
fi
fi
if [ -d "$ZM_PATH_WEB/events" ]; then
if [ -L "$ZM_PATH_WEB/events" ]; then
echo -n "Unlinking current symlink for the events folder... "
unlink "$ZM_PATH_WEB/events"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 36
fi
else
echo "Existing $ZM_PATH_WEB/events is not a symlink. Aborting to prevent data loss"
exit 11
fi
fi
# Create the symlink for the images folder
echo -n "Creating the symlink for the images folder... "
ln -s -f "$ZM_PATH_CONTENT/images" "$ZM_PATH_WEB/images"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 15
fi
# Create the symlink for the events folder
echo -n "Creating the symlink for the events folder... "
ln -s -f "$ZM_PATH_CONTENT/events" "$ZM_PATH_WEB/events"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 16
fi
# change ownership for the images folder. do it recursively unless -q is used
if [ -n "$QUICK" ]; then
echo -n "Changing ownership of the images folder to ${ZM_WEB_USER} ${ZM_WEB_GROUP}... "
chown ${ZM_WEB_USER}:${ZM_WEB_GROUP} "$ZM_PATH_CONTENT/images"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 20
fi
else
echo -n "Changing ownership of the images folder recursively to ${ZM_WEB_USER} ${ZM_WEB_GROUP}... "
chown -R ${ZM_WEB_USER}:${ZM_WEB_GROUP} "$ZM_PATH_CONTENT/images"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 21
fi
fi
# change ownership for the events folder. do it recursively unless -q is used
if [ -n "$QUICK" ]; then
echo -n "Changing ownership of the events folder to ${ZM_WEB_USER} ${ZM_WEB_GROUP}... "
chown ${ZM_WEB_USER}:${ZM_WEB_GROUP} "$ZM_PATH_CONTENT/events"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 25
fi
else
echo -n "Changing ownership of the events folder recursively to ${ZM_WEB_USER} ${ZM_WEB_GROUP}... "
chown -R ${ZM_WEB_USER}:${ZM_WEB_GROUP} "$ZM_PATH_CONTENT/events"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 26
fi
fi
# Change directory permissions for the images folder
echo -n "Changing permissions of the images folder to 775... "
chmod 775 "$ZM_PATH_CONTENT/images"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 30
fi
# Change directory permissions for the events folder
echo -n "Changing permissions of the events folder to 775... "
chmod 775 "$ZM_PATH_CONTENT/events"
if [ "$?" = "0" ]; then
echo "OK"
else
echo "Failed"
exit 31
fi
echo ""
echo "All done"
| 24.902622 | 152 | 0.665514 |
0ad3978a93caa0fcaf9243ef71ddef6f9384515e | 1,950 | cpp | C++ | d3d12/ScreenContext.cpp | hal1932/d3d12 | 7b52d9fab7ca0e50b820901562da427f9ef43bbf | [
"MIT"
] | 1 | 2021-06-18T19:25:38.000Z | 2021-06-18T19:25:38.000Z | d3d12/ScreenContext.cpp | hal1932/d3d12 | 7b52d9fab7ca0e50b820901562da427f9ef43bbf | [
"MIT"
] | null | null | null | d3d12/ScreenContext.cpp | hal1932/d3d12 | 7b52d9fab7ca0e50b820901562da427f9ef43bbf | [
"MIT"
] | null | null | null | #include "ScreenContext.h"
#include "common.h"
#include "Device.h"
#include "CommandQueue.h"
#include <wrl.h>
using Microsoft::WRL::ComPtr;
ScreenContext::~ScreenContext()
{
Reset();
}
void ScreenContext::Create(Device* pDevice, CommandQueue* pCommandQueue, const ScreenContextDesc& desc)
{
DXGI_SWAP_CHAIN_DESC rawDesc = {};
rawDesc.BufferCount = static_cast<UINT>(desc.BufferCount);
rawDesc.BufferDesc.Format = desc.Format;
rawDesc.BufferDesc.Width = static_cast<UINT>(desc.Width);
rawDesc.BufferDesc.Height = static_cast<UINT>(desc.Height);
rawDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
rawDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
rawDesc.OutputWindow = desc.OutputWindow;
rawDesc.SampleDesc.Count = 1;
rawDesc.Windowed = (desc.Windowed) ? TRUE : FALSE;
if (rawDesc.BufferDesc.Format == DXGI_FORMAT_R8G8B8A8_UNORM_SRGB)
{
rawDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
}
auto factoryFlags = 0U;
if (pDevice->IsDebugEnabled())
{
factoryFlags |= DXGI_CREATE_FACTORY_DEBUG;
}
HRESULT result;
ComPtr<IDXGIFactory4> pFactory;
result = CreateDXGIFactory2(factoryFlags, IID_PPV_ARGS(&pFactory));
ThrowIfFailed(result);
ComPtr<IDXGISwapChain> pTmpSwapChain;
result = pFactory->CreateSwapChain(pCommandQueue->NativePtr(), &rawDesc, pTmpSwapChain.GetAddressOf());
ThrowIfFailed(result);
result = pTmpSwapChain->QueryInterface(IID_PPV_ARGS(&pSwapChain_));
ThrowIfFailed(result);
frameIndex_ = pSwapChain_->GetCurrentBackBufferIndex();
desc_ = desc;
pDevice_ = pDevice;
}
void ScreenContext::Reset()
{
pSwapChain_.Reset();
frameIndex_ = 0U;
}
void ScreenContext::UpdateFrameIndex()
{
frameIndex_ = pSwapChain_->GetCurrentBackBufferIndex();
}
void ScreenContext::SwapBuffers(int syncInterval)
{
pSwapChain_->Present(syncInterval, 0);
}
HRESULT ScreenContext::GetBackBufferView(UINT index, ID3D12Resource** ppView)
{
return pSwapChain_->GetBuffer(index, IID_PPV_ARGS(ppView));
}
| 24.683544 | 104 | 0.774872 |
9d9bbee628b923cbc17cdd90015061e9c383438a | 4,409 | rs | Rust | src/load.rs | woojinnn/RMI | 85389f6dbc434f81ca7df964c4cd9bd049397c1e | [
"MIT"
] | 134 | 2019-12-02T13:57:25.000Z | 2022-03-31T07:28:23.000Z | src/load.rs | woojinnn/RMI | 85389f6dbc434f81ca7df964c4cd9bd049397c1e | [
"MIT"
] | 7 | 2020-02-27T19:41:05.000Z | 2021-07-13T07:06:36.000Z | src/load.rs | woojinnn/RMI | 85389f6dbc434f81ca7df964c4cd9bd049397c1e | [
"MIT"
] | 27 | 2019-12-28T17:13:18.000Z | 2022-03-22T09:27:40.000Z | // < begin copyright >
// Copyright Ryan Marcus 2020
//
// See root directory of this project for license terms.
//
// < end copyright >
use memmap::MmapOptions;
use rmi_lib::{RMITrainingData, RMITrainingDataIteratorProvider, KeyType};
use byteorder::{LittleEndian, ReadBytesExt};
use std::fs::File;
use std::convert::TryInto;
pub enum DataType {
UINT64,
UINT32,
FLOAT64
}
struct SliceAdapterU64 {
data: memmap::Mmap,
length: usize
}
impl RMITrainingDataIteratorProvider for SliceAdapterU64 {
type InpType = u64;
fn cdf_iter(&self) -> Box<dyn Iterator<Item = (Self::InpType, usize)> + '_> {
Box::new((0..self.length).map(move |i| self.get(i).unwrap()))
}
fn get(&self, idx: usize) -> Option<(Self::InpType, usize)> {
if idx >= self.length { return None; };
let mi = u64::from_le_bytes((&self.data[8 + idx * 8..8 + (idx + 1) * 8])
.try_into().unwrap());
return Some((mi.into(), idx));
}
fn key_type(&self) -> KeyType {
KeyType::U64
}
fn len(&self) -> usize { self.length }
}
struct SliceAdapterU32 {
data: memmap::Mmap,
length: usize
}
impl RMITrainingDataIteratorProvider for SliceAdapterU32 {
type InpType = u32;
fn cdf_iter(&self) -> Box<dyn Iterator<Item = (Self::InpType, usize)> + '_> {
Box::new((0..self.length).map(move |i| self.get(i).unwrap()))
}
fn get(&self, idx: usize) -> Option<(Self::InpType, usize)> {
if idx >= self.length { return None; };
let mi = (&self.data[8 + idx * 4..8 + (idx + 1) * 4])
.read_u32::<LittleEndian>().unwrap().into();
return Some((mi, idx));
}
fn key_type(&self) -> KeyType {
KeyType::U32
}
fn len(&self) -> usize { self.length }
}
struct SliceAdapterF64 {
data: memmap::Mmap,
length: usize
}
impl RMITrainingDataIteratorProvider for SliceAdapterF64 {
type InpType = f64;
fn cdf_iter(&self) -> Box<dyn Iterator<Item = (Self::InpType, usize)> + '_> {
Box::new((0..self.length).map(move |i| self.get(i).unwrap()))
}
fn get(&self, idx: usize) -> Option<(Self::InpType, usize)> {
if idx >= self.length { return None; };
let mi = (&self.data[8 + idx * 8..8 + (idx + 1) * 8])
.read_f64::<LittleEndian>().unwrap().into();
return Some((mi, idx));
}
fn key_type(&self) -> KeyType {
KeyType::F64
}
fn len(&self) -> usize { self.length }
}
pub enum RMIMMap {
UINT64(RMITrainingData<u64>),
UINT32(RMITrainingData<u32>),
FLOAT64(RMITrainingData<f64>)
}
macro_rules! dynamic {
($funcname: expr, $data: expr $(, $p: expr )*) => {
match $data {
load::RMIMMap::UINT64(mut x) => $funcname(&mut x, $($p),*),
load::RMIMMap::UINT32(mut x) => $funcname(&mut x, $($p),*),
load::RMIMMap::FLOAT64(mut x) => $funcname(&mut x, $($p),*),
}
}
}
impl RMIMMap {
pub fn soft_copy(&self) -> RMIMMap {
match self {
RMIMMap::UINT64(x) => RMIMMap::UINT64(x.soft_copy()),
RMIMMap::UINT32(x) => RMIMMap::UINT32(x.soft_copy()),
RMIMMap::FLOAT64(x) => RMIMMap::FLOAT64(x.soft_copy()),
}
}
pub fn into_u64(self) -> Option<RMITrainingData<u64>> {
match self {
RMIMMap::UINT64(x) => Some(x),
_ => None
}
}
}
pub fn load_data(filepath: &str,
dt: DataType) -> (usize, RMIMMap) {
let fd = File::open(filepath).unwrap_or_else(|_| {
panic!("Unable to open data file at {}", filepath)
});
let mmap = unsafe { MmapOptions::new().map(&fd).unwrap() };
let num_items = (&mmap[0..8]).read_u64::<LittleEndian>().unwrap() as usize;
let rtd = match dt {
DataType::UINT64 =>
RMIMMap::UINT64(RMITrainingData::new(Box::new(
SliceAdapterU64 { data: mmap, length: num_items }
))),
DataType::UINT32 =>
RMIMMap::UINT32(RMITrainingData::new(Box::new(
SliceAdapterU32 { data: mmap, length: num_items }
))),
DataType::FLOAT64 =>
RMIMMap::FLOAT64(RMITrainingData::new(Box::new(
SliceAdapterF64 { data: mmap, length: num_items }
)))
};
return (num_items, rtd);
}
| 27.905063 | 81 | 0.551145 |
4484a81588eb87439b6eac76283279795fdffd65 | 3,914 | py | Python | board/views/user.py | DPS0340/DjangoCRUDBoard | 0211e6aeb05c2e20af4f39a61744188eb5490534 | [
"MIT"
] | 14 | 2020-12-28T08:56:18.000Z | 2022-03-16T18:04:02.000Z | board/views/user.py | DPS0340/DjangoCRUDBoard | 0211e6aeb05c2e20af4f39a61744188eb5490534 | [
"MIT"
] | 27 | 2020-12-28T10:51:04.000Z | 2021-03-12T10:11:33.000Z | board/views/user.py | DPS0340/DjangoCRUDBoard | 0211e6aeb05c2e20af4f39a61744188eb5490534 | [
"MIT"
] | 7 | 2020-12-28T06:28:05.000Z | 2021-03-03T23:47:34.000Z | from ..responses import *
from ..utils import send_json, pop_args, byte_to_dict, get_user
from django.contrib.auth.models import User as Default_User
from ..models import User
from django.contrib.auth.hashers import make_password
from django.views import View
import sys
sys.path.append("../../")
import json
from DjangoCRUDBoard import settings
class UserView(View):
def get(self, request):
keys = ['username']
dic = pop_args(request.GET, *keys)
if None in dic.values():
return send_json(illegalArgument)
users = User.objects.filter(username=dic['username'])
result = get_user(users)
return send_json(result)
def post(self, request):
keys = ['username', 'nickname', 'email', 'password']
dic = pop_args(request.POST, *keys)
if None in dic.values():
return send_json(illegalArgument)
filtered = User.objects.filter(username=dic['username'])
if filtered.count() != 0:
return send_json(userAlreadyRegistered)
filtered = User.objects.filter(nickname=dic['nickname'])
if filtered.count() != 0:
return send_json(userAlreadyRegistered)
User.objects.create_user(**dic)
return send_json(registerSucceed)
def delete(self, request):
keys = ['username', 'email', 'password']
request_dict = byte_to_dict(request.body)
dic = pop_args(request_dict, *keys)
if None in dic.values():
return send_json(illegalArgument)
filtered = User.objects.filter(username=dic['username'], email=dic['email'])
if filtered.count() == 0:
return send_json(noUser)
if not filtered[0].check_password(dic['password']):
return send_json(userDoesNotMatch)
filtered.delete()
return send_json(deleteUserSucceed)
def put(self, request):
original = ['username', 'nickname', 'email', 'password']
to_modified = ['m_username', 'm_nickname', 'm_email', 'm_password']
keys = [*original, *to_modified]
request_dict = byte_to_dict(request.body)
divide_index = len(keys)
dic = pop_args(request_dict, *keys)
# username, email, password 파라미터 없이 온다면
if None in list(dic.values())[:divide_index]:
return send_json(illegalArgument)
# m_username, m_email, m_password 다 아무것도 없을시
if not any(list(dic.values())[divide_index:]):
return send_json(illegalModifyArgument)
filtered = User.objects.filter(username=dic['username'], email=dic['email'])
if filtered.count() == 0:
return send_json(noUser)
if not filtered[0].check_password(dic['password']):
return send_json(userDoesNotMatch)
# 변경하려는 username이 기존에 존재하는지 처리 분기문
filtered_exist = User.objects.filter(username=dic['m_username'])
if filtered_exist.count() != 0:
return send_json(userAlreadyRegistered)
# 변경하려는 아이디, 이메일, 패스워드가 기존과 같다면 어떻게 처리해줘야할지..
update_value = dic.copy()
del update_value['m_username'], update_value['m_email'], update_value['m_password']
'''
해당 딕셔너리 copy 해준 후 뒷 부분 없애줌. 각 if문 마다 filtered.update해주기에는 비효율적이어서
이와 같이 기존 값을 그대로 가지고 있게 하여 m_username만 있고 m_email, m_password없는 등 부분적으로
컬럼이 없을시에도 기존 값을 가지고 있음으로써 1번만 update해주면 됨
'''
if dic['m_username']:
update_value['username'] = dic['m_username']
if dic['m_email']:
update_value['email'] = dic['m_email']
if dic['m_password']:
update_value['password'] = dic['m_password']
filtered.update(username=update_value['username'], email=update_value['email'], password=make_password(update_value['password']))
# 현재 이방식은 normalize_email, normalize_username 를 안해주는데 괜찮을지?! create_user 함수 확인 요구됨.
return send_json(modifyUserSucceed)
| 43.488889 | 137 | 0.642054 |
0742edbf60c178dd1c1d3d7b4ab6f17980fc34f7 | 4,735 | hpp | C++ | vif/vifIndex.hpp | thorfdbg/ssim | 7d9d1b3c2b8e4338d8cec34088d948025c23e559 | [
"Zlib"
] | 9 | 2017-04-13T19:18:03.000Z | 2021-01-21T15:29:48.000Z | vif/vifIndex.hpp | thorfdbg/ssim | 7d9d1b3c2b8e4338d8cec34088d948025c23e559 | [
"Zlib"
] | 1 | 2019-11-25T12:58:01.000Z | 2019-12-05T18:15:55.000Z | vif/vifIndex.hpp | thorfdbg/ssim | 7d9d1b3c2b8e4338d8cec34088d948025c23e559 | [
"Zlib"
] | 1 | 2017-12-31T06:57:00.000Z | 2017-12-31T06:57:00.000Z | /************************************************************************************
** Copyright (C) 2005-2007 TU Berlin, Felix Oum, Thomas Richter **
** **
** This software is provided 'as-is', without any express or implied **
** warranty. In no event will the authors be held liable for any damages **
** arising from the use of this software. **
** **
** Permission is granted to anyone to use this software for any purpose, **
** including commercial applications, and to alter it and redistribute it **
** freely, subject to the following restrictions: **
** **
** 1. The origin of this software must not be misrepresented; you must not **
** claim that you wrote the original software. If you use this software **
** in a product, an acknowledgment in the product documentation would be **
** appreciated but is not required. **
** 2. Altered source versions must be plainly marked as such, and must not be **
** misrepresented as being the original software. **
** 3. This notice may not be removed or altered from any source distribution. **
** **
** Felix Oum Thomas Richter **
** [email protected] **
** **
************************************************************************************/
#ifndef VIFINDEX_HPP
#define VIFINDEX_HPP
/*
** This Class calculate the overall vif-index between 2 pictures.
*/
#include "global/types.hpp"
#include "global/matrix.hpp"
#include "img/image.hpp"
#include "img/component.hpp"
#ifndef NO_POSIX
extern "C" {
#include <pthread.h>
}
#endif
class vifIndex {
//
// K is the variance of the perception noise, picked as 0.1
static const DOUBLE K,K1,K2;
//
// The window size.
enum {
WindowSize = 3 // this is what the article does.
};
//
//This method represent the gausswindowfunction .
static Matrix<DOUBLE> CreateGaussFilter(ULONG w, ULONG h);
//
// This method creates a Hamming window of the given size.
static Matrix<DOUBLE> CreateHammingWindow(ULONG w, ULONG h);
//
// This structure is used to start a new thread with a partial ssim computation.
struct vifTask {
const vifIndex *that;
const Matrix<FLOAT> *img1;
const Matrix<FLOAT> *img2;
Matrix <UBYTE> *mask;
Matrix <UBYTE> *err;
const Image *pic1;
const Image *pic2;
ULONG offset;
ULONG interleave;
DOUBLE numerator; // will return the numerator of the VIF, information capacity for distorted image
DOUBLE denominator; // information capacity for the reference image.
DOUBLE scale;
DOUBLE var; // variance
//
#ifndef NO_POSIX
// pthread helpers here.
pthread_attr_t attr;
pthread_t pid;
#endif
};
//
// The window function.
const Matrix<DOUBLE> m_Gauss;
//
#ifndef NO_POSIX
// The entry point to start a SSIM thread.
static void *pthread_entry(void *arg);
#endif
//
// Compute vif with a certain interleaving (only every n-th row) with the given start offset
// from the start of the picture, return numerator and denominator.
void vifFactor(const Matrix<FLOAT>& img1,const Matrix<FLOAT>& img2,DOUBLE scale,
ULONG offset, ULONG interleave,DOUBLE var,
DOUBLE &numerator,DOUBLE &denominator) const;
//
//
// Compute the vif factor for a multi-core CPU with potentially using threads.
void vifMultiCoreFactor(const Matrix<FLOAT>& img1,const Matrix<FLOAT>& img2,DOUBLE scaling,int ncpus,
double &numerator,double &denominator) const;
//
// Return the global vif for the given images.
void vifFactorScales(Component& img1,Component& img2,DOUBLE scaling,int ncpus,bool bylevel,
DOUBLE &numerator,DOUBLE &denominator) const;
//
// Computes the variance = \sigma_x^2 of the given matrix.
static double variance(const Matrix<FLOAT> &img);
//
public:
//
// Global SIM including color with a naive color weighting.
double vifFactor(const Image& img1,const Image& img2,int ncpus = 1,bool bylevel = false) const;
//
//
vifIndex(void);
//
~vifIndex()
{ }
};
#endif
| 39.132231 | 106 | 0.56114 |
c459882e7b80214d0930a4a7dea9843803f5011d | 6,872 | hpp | C++ | examples/select/select.hpp | stevenybw/thrill | a2dc05035f4e24f64af0a22b60155e80843a5ba9 | [
"BSD-2-Clause"
] | 609 | 2015-08-27T11:09:24.000Z | 2022-03-28T21:34:05.000Z | examples/select/select.hpp | tim3z/thrill | f0e5aa2326a55af3c9a92fc418f8eb8e3cf8c5fa | [
"BSD-2-Clause"
] | 109 | 2015-09-10T21:34:42.000Z | 2022-02-15T14:46:26.000Z | examples/select/select.hpp | tim3z/thrill | f0e5aa2326a55af3c9a92fc418f8eb8e3cf8c5fa | [
"BSD-2-Clause"
] | 114 | 2015-08-27T14:54:13.000Z | 2021-12-08T07:28:35.000Z | /*******************************************************************************
* examples/select/select.hpp
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2016 Lorenz Hübschle-Schneider <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#ifndef THRILL_EXAMPLES_SELECT_SELECT_HEADER
#define THRILL_EXAMPLES_SELECT_SELECT_HEADER
#include <thrill/api/bernoulli_sample.hpp>
#include <thrill/api/collapse.hpp>
#include <thrill/api/dia.hpp>
#include <thrill/api/gather.hpp>
#include <thrill/api/size.hpp>
#include <thrill/api/sum.hpp>
#include <thrill/common/logger.hpp>
#include <algorithm>
#include <cmath>
#include <functional>
#include <utility>
namespace examples {
namespace select {
using namespace thrill; // NOLINT
static constexpr bool debug = false;
static constexpr double delta = 0.1; // 0 < delta < 0.25
static constexpr size_t base_case_size = 1024;
#define LOGM LOGC(debug && ctx.my_rank() == 0)
template <typename ValueType, typename InStack,
typename Compare = std::less<ValueType> >
std::pair<ValueType, ValueType>
PickPivots(const DIA<ValueType, InStack>& data, size_t size, size_t rank,
const Compare& compare = Compare()) {
api::Context& ctx = data.context();
const size_t num_workers(ctx.num_workers());
const double size_d = static_cast<double>(size);
const double p = 20 * sqrt(static_cast<double>(num_workers)) / size_d;
// materialized at worker 0
auto sample = data.Keep().BernoulliSample(p).Gather();
std::pair<ValueType, ValueType> pivots;
if (ctx.my_rank() == 0) {
LOG << "got " << sample.size() << " samples (p = " << p << ")";
// Sort the samples
std::sort(sample.begin(), sample.end(), compare);
const double base_pos =
static_cast<double>(rank * sample.size()) / size_d;
const double offset = pow(size_d, 0.25 + delta);
long lower_pos = static_cast<long>(floor(base_pos - offset));
long upper_pos = static_cast<long>(floor(base_pos + offset));
size_t lower = static_cast<size_t>(std::max(0L, lower_pos));
size_t upper = static_cast<size_t>(
std::min(upper_pos, static_cast<long>(sample.size() - 1)));
assert(0 <= lower && lower < sample.size());
assert(0 <= upper && upper < sample.size());
LOG << "Selected pivots at positions " << lower << " and " << upper
<< ": " << sample[lower] << " and " << sample[upper];
pivots = std::make_pair(sample[lower], sample[upper]);
}
pivots = ctx.net.Broadcast(pivots);
LOGM << "pivots: " << pivots.first << " and " << pivots.second;
return pivots;
}
template <typename ValueType, typename InStack,
typename Compare = std::less<ValueType> >
ValueType Select(const DIA<ValueType, InStack>& data, size_t rank,
const Compare& compare = Compare()) {
api::Context& ctx = data.context();
const size_t size = data.Keep().Size();
assert(0 <= rank && rank < size);
if (size <= base_case_size) {
// base case, gather all data at worker with rank 0
ValueType result = ValueType();
auto elements = data.Gather();
if (ctx.my_rank() == 0) {
assert(rank < elements.size());
std::nth_element(elements.begin(), elements.begin() + rank,
elements.end(), compare);
result = elements[rank];
LOG << "base case: " << size << " elements remaining, result is "
<< result;
}
result = ctx.net.Broadcast(result);
return result;
}
ValueType left_pivot, right_pivot;
std::tie(left_pivot, right_pivot) = PickPivots(data, size, rank, compare);
size_t left_size, middle_size, right_size;
using PartSizes = std::pair<size_t, size_t>;
std::tie(left_size, middle_size) =
data.Keep().Map(
[&](const ValueType& elem) -> PartSizes {
if (compare(elem, left_pivot))
return PartSizes { 1, 0 };
else if (!compare(right_pivot, elem))
return PartSizes { 0, 1 };
else
return PartSizes { 0, 0 };
})
.Sum(
[](const PartSizes& a, const PartSizes& b) -> PartSizes {
return PartSizes { a.first + b.first, a.second + b.second };
},
PartSizes { 0, 0 });
right_size = size - left_size - middle_size;
LOGM << "left_size = " << left_size << ", middle_size = " << middle_size
<< ", right_size = " << right_size << ", rank = " << rank;
if (rank == left_size) {
// all the elements strictly smaller than the left pivot are on the left
// side -> left_size-th element is the left pivot
LOGM << "result is left pivot: " << left_pivot;
return left_pivot;
}
else if (rank == left_size + middle_size - 1) {
// only the elements strictly greater than the right pivot are on the
// right side, so the result is the right pivot in this case
LOGM << "result is right pivot: " << right_pivot;
return right_pivot;
}
else if (rank < left_size) {
// recurse on the left partition
LOGM << "Recursing left, " << left_size
<< " elements remaining (rank = " << rank << ")\n";
auto left = data.Filter(
[&](const ValueType& elem) -> bool {
return compare(elem, left_pivot);
}).Collapse();
return Select(left, rank, compare);
}
else if (left_size + middle_size <= rank) {
// recurse on the right partition
LOGM << "Recursing right, " << right_size
<< " elements remaining (rank = " << rank - left_size - middle_size
<< ")\n";
auto right = data.Filter(
[&](const ValueType& elem) -> bool {
return compare(right_pivot, elem);
}).Collapse();
return Select(right, rank - left_size - middle_size, compare);
}
else {
// recurse on the middle partition
LOGM << "Recursing middle, " << middle_size
<< " elements remaining (rank = " << rank - left_size << ")\n";
auto middle = data.Filter(
[&](const ValueType& elem) -> bool {
return !compare(elem, left_pivot) &&
!compare(right_pivot, elem);
}).Collapse();
return Select(middle, rank - left_size, compare);
}
}
} // namespace select
} // namespace examples
#endif // !THRILL_EXAMPLES_SELECT_SELECT_HEADER
/******************************************************************************/
| 34.532663 | 80 | 0.565192 |
de581a2806966955cb8231b870616831ea68ba16 | 2,183 | swift | Swift | 0025. Reverse Nodes in k-Group.swift | sergeyleschev/leetcode-swift | b73b8fa61a14849e48fb38e27e51ea6c12817d64 | [
"MIT"
] | 10 | 2021-05-16T07:19:41.000Z | 2021-08-02T19:02:00.000Z | 0025. Reverse Nodes in k-Group.swift | sergeyleschev/leetcode-swift | b73b8fa61a14849e48fb38e27e51ea6c12817d64 | [
"MIT"
] | null | null | null | 0025. Reverse Nodes in k-Group.swift | sergeyleschev/leetcode-swift | b73b8fa61a14849e48fb38e27e51ea6c12817d64 | [
"MIT"
] | 1 | 2021-08-18T05:33:00.000Z | 2021-08-18T05:33:00.000Z | /**
* Definition for singly-linked list.
* public class ListNode {
* public var val: Int
* public var next: ListNode?
* public init() { self.val = 0; self.next = nil; }
* public init(_ val: Int) { self.val = val; self.next = nil; }
* public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
* }
*/
class Solution {
// Solution @ Sergey Leschev, Belarusian State University
// 25. Reverse Nodes in k-Group
// Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
// k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.
// You may not alter the values in the list's nodes, only nodes themselves may be changed.
// Example 1:
// Input: head = [1,2,3,4,5], k = 2
// Output: [2,1,4,3,5]
// Example 2:
// Input: head = [1,2,3,4,5], k = 3
// Output: [3,2,1,4,5]
// Example 3:
// Input: head = [1,2,3,4,5], k = 1
// Output: [1,2,3,4,5]
// Example 4:
// Input: head = [1], k = 1
// Output: [1]
// Constraints:
// The number of nodes in the list is in the range sz.
// 1 <= sz <= 5000
// 0 <= Node.val <= 1000
// 1 <= k <= sz
// Follow-up: Can you solve the problem in O(1) extra memory space?
func reverseKGroup(_ head: ListNode?, _ k: Int) -> ListNode? {
var tmp1: ListNode? = head
for _ in 0..<k - 1 { tmp1 = tmp1?.next }
if tmp1 == nil {
return head
} else {
var current: ListNode?
var tmp2: ListNode?
for _ in 0..<k {
if current == nil {
current = head?.next
head?.next = reverseKGroup(tmp1?.next, k)
tmp1 = head
} else {
tmp2 = current?.next
current?.next = tmp1
tmp1 = current
current = tmp2
}
}
return tmp1
}
}
} | 31.185714 | 193 | 0.505268 |
da769cd019d1c67883ad2aed4c400f1496252368 | 5,548 | php | PHP | resources/views/project/add_project.blade.php | moutaz-althwabteh/HassanHome_ | a0896efb263854a48938eb60ffce5a809bf1f350 | [
"MIT"
] | null | null | null | resources/views/project/add_project.blade.php | moutaz-althwabteh/HassanHome_ | a0896efb263854a48938eb60ffce5a809bf1f350 | [
"MIT"
] | null | null | null | resources/views/project/add_project.blade.php | moutaz-althwabteh/HassanHome_ | a0896efb263854a48938eb60ffce5a809bf1f350 | [
"MIT"
] | null | null | null | @extends('project.layouts')
@section('content')
<div class="row" >
<div class="col-md-12">
<div class="portlet box blue ">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift"></i> اضافة بيانات المشروع </div>
<div class="tools">
<a href="" class="collapse"> </a>
<a href="" class="remove"> </a>
</div>
</div>
<div class="portlet-body form">
<form method="post" action="{{ route('projects.store') }}">
@csrf
<div class="row" style="padding:5px">
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="project_name" class="form-control" placeholder="اسم المشروع "> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="project_num" class="form-control" placeholder="رقم المبنى"> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="Project_gps" class="form-control" placeholder="الإحداثيات "> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="Project_owner" class="form-control" placeholder="مالك العقار "> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="Project_mfawd" class="form-control" placeholder=" المفوض "> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="bulding_mfaud_id" class="form-control" placeholder=" رقم هوية المفوض "> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="bulding_mfaud_address" class="form-control" placeholder="عنوان المفوض "> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="bulding_part" class="form-control" placeholder="رقم القطعة والقسيمة "> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="project_flw" class="form-control" placeholder="مساحة الأرض "> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="project_emp" class="form-control" placeholder="الموظف المشرف "> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<select class="form-control select2me" name="project_type">
<option value="0">نوع المشروع</option>
<option value="1">استثماري </option>
<option value="2">مقاولة</option>
</select>
</div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="project_status" class="form-control" placeholder=" الحالة"> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="project_sdate" class="form-control" placeholder=" تاريخ البدء"> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="project_edate" class="form-control" placeholder=" تاريخ الانتهاء"> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<input type="text" name="project_budget" class="form-control" placeholder=" الموازنة بالأيام "> </div>
<div class="col-md-3" style=" margin-bottom:0.1px">
<select class="form-control select2me" name="project_budget_curr">
<option value="0">العملة</option>
<option value="1">دولار </option>
<option value="2">دينار</option>
<option value="3">شيكل</option>
<option value="4">يورو</option>
</select>
</div>
<div class="col-md-6" style=" margin-bottom:0.1px">
<textarea name="project_contract" placeholder="ادخل تفاصيل العقد هنا .." data-provide="markdown" rows="4" data-error-container="#editor_error"></textarea></div>
<div class="col-md-3">
<input type="text" name="project_notes" class="form-control" placeholder="ملاحظات "></div>
<div class="col-md-3">
<span class="input-group-btn">
<button class="btn blue" type="submit">حفـــظ</button>
</span></div>
<!-- /input-group -->
</div>
</div>
<div style="float:left;"> </div>
</form>
<!-- END FORM-->
</div>
@endsection | 66.047619 | 193 | 0.459084 |
a4ab72794e7b6de74c0e12bfbdd40f647bd98f6a | 584 | php | PHP | app/Http/Controllers/User/AuthController.php | master-raihan/profiler-backend-final | aeea20d843bc0dea7914048b61dff77af0fe68f3 | [
"MIT"
] | null | null | null | app/Http/Controllers/User/AuthController.php | master-raihan/profiler-backend-final | aeea20d843bc0dea7914048b61dff77af0fe68f3 | [
"MIT"
] | null | null | null | app/Http/Controllers/User/AuthController.php | master-raihan/profiler-backend-final | aeea20d843bc0dea7914048b61dff77af0fe68f3 | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers\User;
use App\Contracts\Services\AuthContract;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AuthController extends Controller
{
private $authService;
protected $guard = 'user';
public function __construct(AuthContract $authService)
{
$this->authService = $authService;
}
public function login(Request $request)
{
$serviceResponse = $this->authService->login($request, $this->guard);
return response()->json($serviceResponse, $serviceResponse['status']);
}
}
| 22.461538 | 78 | 0.69863 |
af9802bfb415c4598595c612f388f673886cfca2 | 3,737 | py | Python | essence.py | aggixx/poe_filter_unique_generator | 1359daf862115a664f66797854ab0cefbb59384e | [
"Unlicense"
] | null | null | null | essence.py | aggixx/poe_filter_unique_generator | 1359daf862115a664f66797854ab0cefbb59384e | [
"Unlicense"
] | null | null | null | essence.py | aggixx/poe_filter_unique_generator | 1359daf862115a664f66797854ab0cefbb59384e | [
"Unlicense"
] | null | null | null | import util
class EssenceGenerator:
tiers = [
{
"minValue": 12,
"soundId": 5,
"volume": 170,
"iconShape": "Circle",
"iconColor": "Red",
"iconSize": 0,
"flareColor": "Red",
"borderColor": [255, 0, 255],
},
{
"minValue": 5,
"soundId": 8,
"volume": 150,
"iconShape": "Circle",
"iconColor": "Yellow",
"iconSize": 1,
"flareColor": "Yellow",
"borderColor": [210, 178, 135],
},
{
"minValue": 1.01,
"soundId": 8,
"volume": 130,
"iconShape": "Circle",
"iconColor": "White",
"iconSize": 2,
"flareColor": "White",
},
];
def __init__(self, league):
self.endpoint = "http://poe.ninja/api/Data";
self.urlformat = "{}/itemoverview?league={}&type={}"
self.league = league
self.type = "Essence"
self.chunk = None
self.data = self.pullData()
def buildURL(self):
return util.encodeURI(self.urlformat.format(self.endpoint, self.league, self.type))
def pullData(self):
url = self.buildURL()
print url
return util.get_url_as_json(url)
def sortToTiers(self):
for tier in self.tiers:
tier['items'] = [];
for item in self.data['lines']:
shown = False;
for idx in range(0, len(self.tiers)):
tier = self.tiers[idx]
if item['chaosValue'] >= tier['minValue']:
tier['items'].append(item['name'])
shown = True
break;
"""
if not shown:
print("Hiding {} ({:2f}c)..".format(item['name'], item['chaosValue']))
"""
"""
for tier in self.tiers:
print(tier['items'])
"""
def buildFilterEntry(self, tier):
s = u"""Show # {}c+ ({} entries)
SetFontSize 45
PlayAlertSound {} {}
Class Stackable Currency
BaseType {}""".format(
tier['minValue'],
len(tier['items']),
tier['soundId'],
tier['volume'],
u" ".join(map(lambda i: u'"{}"'.format(i), tier['items']))
)
if 'iconShape' in tier:
s += u"\nMinimapIcon {} {} {}".format(tier['iconSize'], tier['iconColor'], tier['iconShape'])
if 'flareColor' in tier:
s += u"\nPlayEffect {}".format(tier['flareColor'])
if 'borderColor' in tier:
s += u"\nSetBorderColor {} {} {}".format(tier['borderColor'][0], tier['borderColor'][1], tier['borderColor'][2])
return s
def indent(self, chunk):
chunk = chunk.replace('\t', '')
lines = chunk.split('\n')
for idx in range(1, len(lines)):
line = lines[idx]
if not (line[:5] == u"Show " or line[:5] == u"Hide "):
lines[idx] = u"\t" + line
return u"\n".join(lines)
def getFallbackEntry(self):
return u"""Show # Remnant
Class Stackable Currency
SetFontSize 45
PlayAlertSound 8 130
MinimapIcon 2 White Circle
PlayEffect White
BaseType "Remnant of Corruption"
Hide # Other essences
Class Stackable Currency
BaseType "Essence of"
SetFontSize 1"""
def buildFilterChunk(self):
entries = [];
for tier in self.tiers:
if len(tier['items']) > 0:
entries.append(self.buildFilterEntry(tier))
entries.append(self.getFallbackEntry())
chunk = u"\n\n".join(entries)
return self.indent(chunk)
def getFilterChunk(self):
if not self.chunk:
self.sortToTiers()
self.chunk = self.buildFilterChunk()
return self.chunk
def apply(self, filter):
#try:
# Find uniques section
start = filter.index("-\r\n# [3708] Essence Tier List")
# Find end of header
start2 = filter.index("\r\n\r\n", start) + 4
# Find end of uniques section
end = filter.index("-\r\n# [3709]")
# Find start of header
end2 = filter.rfind("\r\n\r\n", 0, end)
# Splice filter
before = filter[:start2]
after = filter[end2:]
filter = before + self.getFilterChunk() + after
#except ValueError:
# print "Could not find {} section".format(self.type)
print "Updated essences section."
return filter | 21.477011 | 115 | 0.614397 |
5db211d52454403423f764c810f79400bea39e98 | 18,794 | rs | Rust | src/data_store.rs | meldron/psoco | 8c55de2684249f5cbdeb791844e2924eea305933 | [
"MIT"
] | 3 | 2020-06-22T14:02:59.000Z | 2021-04-29T14:27:07.000Z | src/data_store.rs | meldron/psoco | 8c55de2684249f5cbdeb791844e2924eea305933 | [
"MIT"
] | 2 | 2020-07-24T13:44:36.000Z | 2021-01-12T13:59:23.000Z | src/data_store.rs | meldron/psoco | 8c55de2684249f5cbdeb791844e2924eea305933 | [
"MIT"
] | 2 | 2021-04-29T14:27:10.000Z | 2022-03-29T07:49:58.000Z | use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use prettytable::{Cell, Row};
use serde_json::{json, Value as JSONValue};
pub use crate::crypto2::*;
pub use crate::errors::*;
pub enum PsonoItemType {
Password,
Shared,
Unknown,
}
#[allow(dead_code)]
#[derive(Clone, Debug, PartialEq)]
pub enum PsonoFolderType {
Owned,
Shared,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DataStoreEncrypted {
pub data: String,
pub data_nonce: String,
#[serde(rename = "type")]
pub type_field: String,
pub description: String,
pub secret_key: String,
pub secret_key_nonce: String,
pub is_default: bool,
}
// #[derive(Clone, Debug, Deserialize, Serialize)]
// pub struct DataStoreEncrypted {
// pub text: String,
// pub text_nonce: String,
// }
#[allow(dead_code)]
impl DataStoreEncrypted {
pub fn open(&self, user_secret_key_hex: &str) -> Result<String, APIError> {
let data_store_secret_raw = open_secret_box(
&self.secret_key,
&self.secret_key_nonce,
user_secret_key_hex,
)?;
let data_store_secret = String::from_utf8(data_store_secret_raw)?;
let data_raw = open_secret_box(&self.data, &self.data_nonce, &data_store_secret)?;
let data = String::from_utf8(data_raw)?;
Ok(data)
}
}
pub type ShareIndex = HashMap<String, ShareIndexEntry>;
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DataStore {
#[serde(rename = "datastore_id")]
pub id: String,
#[serde(default)]
pub folders: Vec<Folder>,
#[serde(default)]
pub share_index: Option<ShareIndex>,
#[serde(default)]
pub items: Vec<Item>,
#[serde(default)]
pub shares: HashMap<String, Share>,
}
fn share_secrets(path: &str, share: &Share) -> Vec<SecretItem> {
let mut secret_items: Vec<SecretItem> = Vec::new();
let new_path = format!("{}/{}", path, share.name);
if share.secret_id.is_some() && share.secret_key.is_some() {
let item = share
.to_secret_item(&new_path)
.expect("could not to_secret_item");
secret_items.push(item);
}
if let Some(folders) = share.folders.as_ref() {
for f in folders {
secret_items.append(&mut folder_secrets(&new_path, f, share.sub_shares.as_ref()));
}
};
if let Some(items) = share.items.as_ref() {
for i in items {
secret_items.append(&mut item_secrets(
&new_path,
i,
share.sub_shares.as_ref().and_then(|s| s.get(&i.id)),
));
}
}
secret_items
}
fn item_secrets(path: &str, item: &Item, share: Option<&Share>) -> Vec<SecretItem> {
let mut secret_items: Vec<SecretItem> = Vec::new();
let new_path = format!("{}/{}", path, item.name);
if item.secret_id.is_some() && item.secret_key.is_some() {
let item = item
.to_secret_item(&new_path)
.expect("could not to_secret_item");
secret_items.push(item);
} else if item.share_id.is_some() {
if let Some(s) = share {
secret_items.push(s.to_secret_item(&new_path).expect("to secret item error"));
}
}
secret_items
}
#[allow(dead_code)]
fn folder_secrets(
path: &str,
folder: &Folder,
shares: Option<&HashMap<String, Share>>,
) -> Vec<SecretItem> {
let mut items: Vec<SecretItem> = Vec::new();
let new_path = format!("{}/{}", path, folder.name);
match folder.get_type() {
PsonoFolderType::Shared => {
let shared_folder =
SharedFolder::from_folder(folder).expect("could not get shared_folder from folder");
match shares.as_ref() {
Some(sl) => match sl.get(&shared_folder.share_id) {
Some(s) => {
items.append(&mut share_secrets(&new_path, s));
}
None => {
println!(
"No share with id {} but {} is a shared folder",
&shared_folder.share_id, shared_folder.id
);
}
},
None => {}
};
}
PsonoFolderType::Owned => {
let owned_folder = OwnedFolder::from_folder(folder);
for f in &owned_folder.folders {
items.append(&mut folder_secrets(&new_path, f, None));
}
for i in &owned_folder.items {
let share = match i.share_id.as_ref() {
Some(share_id) => shares.and_then(|x| x.get(share_id)),
None => None,
};
items.append(&mut item_secrets(&new_path, i, share));
}
}
};
items
}
impl DataStore {
pub fn get_secrets_list(&self) -> Vec<SecretItem> {
let mut secret_items: Vec<SecretItem> = Vec::new();
let mut set: HashMap<String, SecretItem> = HashMap::new();
let path = "";
for f in &self.folders {
secret_items.append(&mut folder_secrets(path, f, Some(&self.shares)));
}
for i in &self.items {
let share = match i.share_id.as_ref() {
Some(share_id) => self.shares.get(share_id),
None => None,
};
secret_items.append(&mut item_secrets(&path, i, share));
}
for mut s in secret_items {
if set.contains_key(&s.secret_id) {
let v = set.get_mut(&s.secret_id).expect("hash get mut failed");
if s.path != v.path {
v.path.append(&mut s.path);
}
} else {
set.insert(s.secret_id.clone(), s);
}
}
let secret_items_filtered: Vec<SecretItem> = set.into_iter().map(|(_k, v)| v).collect();
secret_items_filtered
}
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShareIndexEntry {
pub paths: Vec<Vec<String>>,
pub secret_key: String,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Folder {
pub name: String,
#[serde(default)]
pub share_id: Option<String>,
#[serde(default)]
pub share_secret_key: Option<String>,
pub id: String,
#[serde(default)]
pub items: Vec<Item>,
#[serde(default)]
pub folders: Vec<Folder>,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OwnedFolder {
pub name: String,
pub id: String,
pub items: Vec<Item>,
pub folders: Vec<Folder>,
}
#[allow(dead_code)]
impl OwnedFolder {
pub fn from_folder(f: &Folder) -> Self {
OwnedFolder {
name: f.name.clone(),
id: f.id.clone(),
items: f.items.clone(),
folders: f.folders.clone(),
}
}
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SharedFolder {
pub name: String,
pub id: String,
pub share_id: String,
pub share_secret_key: String,
}
#[allow(dead_code)]
impl SharedFolder {
pub fn from_folder(f: &Folder) -> Result<Self, APIError> {
let share_id = f.share_id.clone().ok_or(APIError::SharedFolderError {
missing: "share_id".to_owned(),
})?;
let share_secret_key = f
.share_secret_key
.clone()
.ok_or(APIError::SharedFolderError {
missing: "share_secret_key".to_owned(),
})?;
Ok(SharedFolder {
name: f.name.clone(),
id: f.id.clone(),
share_id,
share_secret_key,
})
}
}
#[allow(dead_code)]
impl Folder {
pub fn get_type(&self) -> PsonoFolderType {
if self.share_id.is_some() && self.share_secret_key.is_some() {
return PsonoFolderType::Shared;
}
PsonoFolderType::Owned
}
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Item {
pub name: String,
#[serde(default)]
pub share_id: Option<String>,
#[serde(default)]
pub share_secret_key: Option<String>,
pub id: String,
#[serde(rename = "type")]
#[serde(default)]
pub type_field: Option<String>,
#[serde(default)]
pub secret_id: Option<String>,
#[serde(default)]
pub secret_key: Option<String>,
#[serde(default)]
pub urlfilter: Option<String>,
}
#[allow(dead_code)]
impl Item {
pub fn get_type(&self) -> PsonoItemType {
if self.share_id.is_some() && self.share_secret_key.is_some() {
return PsonoItemType::Shared;
}
let is_password_type = match &self.type_field {
Some(t) => t == "website_password",
None => false,
};
if self.secret_id.is_some() && self.secret_key.is_some() && is_password_type {
return PsonoItemType::Password;
}
PsonoItemType::Unknown
}
pub fn to_secret_item(&self, path: &str) -> Result<SecretItem, APIError> {
let secret_id = self
.secret_id
.as_ref()
.ok_or(APIError::OwnFolderError {
missing: "secret_id".to_owned(),
})?
.clone();
let secret_key = self
.secret_key
.as_ref()
.ok_or(APIError::OwnFolderError {
missing: "secret_key".to_owned(),
})?
.clone();
Ok(SecretItem {
id: self.id.to_string(),
name: self.name.to_string(),
path: vec![path.to_owned()],
secret_id,
secret_key,
urlfilter: self.urlfilter.clone(),
})
}
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct OwnedItem {
pub name: String,
pub id: String,
#[serde(rename = "type")]
pub type_field: String,
pub secret_id: String,
pub secret_key: String,
#[serde(default)]
pub urlfilter: Option<String>,
}
#[allow(dead_code)]
impl OwnedItem {
pub fn from_item(i: Item) -> Result<Self, APIError> {
let type_field = i.type_field.ok_or(APIError::OwnFolderError {
missing: "type_field".to_owned(),
})?;
let secret_id = i.secret_id.ok_or(APIError::OwnFolderError {
missing: "secret_id".to_owned(),
})?;
let secret_key = i.secret_key.ok_or(APIError::OwnFolderError {
missing: "secret_key".to_owned(),
})?;
Ok(OwnedItem {
name: i.name,
id: i.id,
type_field,
secret_id,
secret_key,
urlfilter: i.urlfilter,
})
}
}
#[allow(dead_code)]
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DatastoreList {
pub datastores: Vec<DatastoreListEntry>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DatastoreListEntry {
pub id: String,
#[serde(rename = "type")]
pub type_field: String,
pub description: String,
pub is_default: bool,
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Share {
#[serde(default)]
pub id: String,
pub name: String,
#[serde(rename = "type")]
#[serde(default)]
pub type_field: Option<String>,
#[serde(default)]
pub secret_id: Option<String>,
#[serde(default)]
pub secret_key: Option<String>,
#[serde(default)]
pub urlfilter: Option<String>,
#[serde(default)]
pub share_secret_key: Option<String>,
#[serde(default)]
pub items: Option<Vec<Item>>,
#[serde(default)]
pub folders: Option<Vec<Folder>>,
#[serde(default)]
pub share_index: Option<ShareIndex>,
#[serde(default)]
pub sub_shares: Option<HashMap<String, Share>>,
}
impl Share {
pub fn to_secret_item(&self, path: &str) -> Result<SecretItem, APIError> {
let secret_id = self
.secret_id
.as_ref()
.ok_or(APIError::OwnFolderError {
missing: "secret_id".to_owned(),
})?
.clone();
let secret_key = self
.secret_key
.as_ref()
.ok_or(APIError::OwnFolderError {
missing: "secret_key".to_owned(),
})?
.clone();
Ok(SecretItem {
id: self.id.to_owned(),
name: self.name.to_owned(),
path: vec![path.to_owned()],
secret_id,
secret_key,
urlfilter: self.urlfilter.clone(),
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct SecretItem {
pub id: String,
pub name: String,
pub path: Vec<String>,
#[serde(skip_serializing)]
pub secret_id: String,
#[serde(skip_serializing)]
pub secret_key: String,
#[serde(skip_serializing)]
pub urlfilter: Option<String>,
}
impl SecretItem {
pub fn contains(&self, search: &str) -> bool {
if self.name.to_lowercase().contains(search) {
return true;
}
if let Some(uf) = &self.urlfilter {
if uf.to_lowercase().contains(search) {
return true;
}
}
for p in &self.path {
if p.to_lowercase().contains(search) {
return true;
}
}
false
}
pub fn short_path(&self) -> Vec<String> {
let short_paths: Vec<String> = self
.path
.iter()
.map(|p| {
let sub_paths: Vec<String> = p.split('/').map(|s| s.to_string()).collect();
match sub_paths.len() {
0 | 1 | 2 | 3 => sub_paths.join("/"),
_ => format!(
"{}/{}/.../{}",
sub_paths.first().unwrap(),
sub_paths.get(1).unwrap(),
sub_paths.last().unwrap()
),
}
})
.collect();
short_paths
}
pub fn to_row_short_paths(&self) -> Row {
Row::new(vec![
Cell::new(&self.name),
Cell::new(&self.short_path().join(",")),
Cell::new(&self.id),
])
}
pub fn to_row(&self) -> Row {
Row::new(vec![
Cell::new(&self.name),
Cell::new(&self.path.join(",")),
Cell::new(&self.id),
])
}
}
#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SecretValues {
pub website_password_url_filter: Option<String>,
pub website_password_notes: Option<String>,
pub website_password_password: Option<String>,
pub website_password_username: Option<String>,
pub website_password_url: Option<String>,
pub website_password_title: Option<String>,
}
impl SecretValues {
pub fn contains(&self, search: &str) -> bool {
if let Some(s) = &self.website_password_url_filter {
if s.to_lowercase().contains(search) {
return true;
}
}
if let Some(s) = &self.website_password_notes {
if s.to_lowercase().contains(search) {
return true;
}
}
if let Some(s) = &self.website_password_username {
if s.to_lowercase().contains(search) {
return true;
}
}
if let Some(s) = &self.website_password_password {
if s.to_lowercase().contains(search) {
return true;
}
}
if let Some(s) = &self.website_password_url {
if s.to_lowercase().contains(search) {
return true;
}
}
if let Some(s) = &self.website_password_title {
if s.to_lowercase().contains(search) {
return true;
}
}
false
}
pub fn to_row_all(&self, id: &str) -> Row {
let empty = String::from("");
Row::new(vec![
Cell::new(id),
Cell::new(&self.website_password_title.as_ref().unwrap_or(&empty)),
Cell::new(&self.website_password_username.as_ref().unwrap_or(&empty)),
Cell::new(&self.website_password_password.as_ref().unwrap_or(&empty)),
Cell::new(&self.website_password_notes.as_ref().unwrap_or(&empty)),
Cell::new(&self.website_password_url.as_ref().unwrap_or(&empty)),
Cell::new(&self.website_password_url_filter.as_ref().unwrap_or(&empty)),
])
}
pub fn to_row_user_pwd(&self, id: &str) -> Row {
let empty = String::from("");
Row::new(vec![
Cell::new(id),
Cell::new(&self.website_password_title.as_ref().unwrap_or(&empty)),
Cell::new(&self.website_password_username.as_ref().unwrap_or(&empty)),
Cell::new(&self.website_password_password.as_ref().unwrap_or(&empty)),
])
}
pub fn to_row_user(&self, id: &str) -> Row {
let empty = String::from("");
Row::new(vec![
Cell::new(id),
Cell::new(&self.website_password_title.as_ref().unwrap_or(&empty)),
Cell::new(&self.website_password_username.as_ref().unwrap_or(&empty)),
])
}
pub fn to_row_pwd(&self, id: &str) -> Row {
let empty = String::from("");
Row::new(vec![
Cell::new(id),
Cell::new(&self.website_password_title.as_ref().unwrap_or(&empty)),
Cell::new(&self.website_password_password.as_ref().unwrap_or(&empty)),
])
}
pub fn to_json_all(&self, id: &str) -> JSONValue {
json!({
"id": id,
"title": &self.website_password_title,
"username": &self.website_password_username,
"password": &self.website_password_password,
"notes": &self.website_password_notes,
"url": &self.website_password_url,
"url_filter": &self.website_password_url_filter,
})
}
pub fn to_json_user_pwd(&self, id: &str) -> JSONValue {
json!({
"id": id,
"title": &self.website_password_title,
"username": &self.website_password_username,
"password": &self.website_password_password
})
}
pub fn to_json_user(&self, id: &str) -> JSONValue {
json!({
"id": id,
"title": &self.website_password_title,
"username": &self.website_password_username,
})
}
pub fn to_json_pwd(&self, id: &str) -> JSONValue {
json!({
"id": id,
"title": &self.website_password_title,
"password": &self.website_password_password
})
}
}
| 29.137984 | 100 | 0.551293 |
8ac98c88c31c94464e09ce7de200657dae3acc35 | 1,948 | ps1 | PowerShell | code/Tools/Ops/Scripts/Remove-OBAEnvironment.ps1 | microsoft/EmbeddedSocial-SyncService-for-OBA | 7f2a33959742106a6acc63b5f41329e2ae73c4c1 | [
"MIT"
] | 2 | 2020-05-09T09:32:21.000Z | 2020-09-06T18:05:07.000Z | code/Tools/Ops/Scripts/Remove-OBAEnvironment.ps1 | microsoft/EmbeddedSocial-SyncService-for-OBA | 7f2a33959742106a6acc63b5f41329e2ae73c4c1 | [
"MIT"
] | null | null | null | code/Tools/Ops/Scripts/Remove-OBAEnvironment.ps1 | microsoft/EmbeddedSocial-SyncService-for-OBA | 7f2a33959742106a6acc63b5f41329e2ae73c4c1 | [
"MIT"
] | 3 | 2020-06-30T15:45:51.000Z | 2020-08-05T14:08:39.000Z | function Remove-OBAEnvironment {
<#
.NOTES
Name: Remove-OBAEnvironment.ps1
Requires: Azure Powershell version 2.1 or higher.
.SYNOPSIS
Removes an OBA Server Azure instance.
.DESCRIPTION
Implements all logic needed to delete an instance of the OBA Server on Azure.
Assumes that the user is already logged to Azure RM.
.PARAMETER Name
Name of the OBA environment to remove.
.EXAMPLE
[PS] C:\>Remove-OBAEnvironment -Name oba-dev-alec -Verbose
#>
param (
[Parameter(Mandatory=$true,HelpMessage='Environment name')]
[Alias("Name")]
[string] $EnvironmentName
)
begin {
}
process {
Write-Host "Deleting all resources for account $EnvironmentName..."
$rg = $EnvironmentName
$count = (Get-AzureRmResourceGroup -Name $rg | Measure-Object).Count
Write-Verbose "Get resource group returned count = $count."
# check that the resource group exists before we try to delete it
if ($count -eq 1) {
# Ask the user to press 'y' to continue
$message = 'This script deletes all Azure resources of a OBA Server environment.'
$question = 'Are you sure you want to proceed?'
$choices = New-Object Collections.ObjectModel.Collection[Management.Automation.Host.ChoiceDescription]
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes'))
$choices.Add((New-Object Management.Automation.Host.ChoiceDescription -ArgumentList '&No'))
$decision = $Host.UI.PromptForChoice($message, $question, $choices, 1)
if ($decision -ne 0) {
throw 'cancelled'
}
Write-Verbose "Removing resource group $rg"
Remove-AzureRmResourceGroup -Name $rg -Force
}
}
end {
Write-Verbose "Finished."
}
}
| 31.934426 | 114 | 0.623203 |
20e287e88403f91746ddb97cfd1363acafca9a0d | 7,725 | py | Python | SpaceHabitRPG/Tests/JSTests/LoginJSTest.py | joelliusp/SpaceHabit | 5656ef4d9c57f3e58d0ed756a3aa754c8a7dd6a5 | [
"MIT"
] | null | null | null | SpaceHabitRPG/Tests/JSTests/LoginJSTest.py | joelliusp/SpaceHabit | 5656ef4d9c57f3e58d0ed756a3aa754c8a7dd6a5 | [
"MIT"
] | 13 | 2016-07-19T04:13:20.000Z | 2016-08-17T06:06:47.000Z | SpaceHabitRPG/Tests/JSTests/LoginJSTest.py | joelliusp/SpaceHabit | 5656ef4d9c57f3e58d0ed756a3aa754c8a7dd6a5 | [
"MIT"
] | null | null | null | from SpaceUnitTest import SpaceUnitTest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import SpaceHabitServer
import threading
import cherrypy
import time
import requests
import AuthenticationLayer
import DatabaseLayer
import DatabaseTestSetupCleanup as dbHelp
class Test_LoginJSTest(SpaceUnitTest):
@classmethod
def setUpClass(cls):
DatabaseLayer.isUnitTestMode = True
cls.server = SpaceHabitServer.HabitServer()
cls.server.start()
ticks = 0
while cherrypy.engine.state != cherrypy.engine.states.STARTED:
time.sleep(1)
ticks += 1
if ticks >= 10:
raise TimeoutError("ran out of time")
return super().setUpClass()
@classmethod
def tearDownClass(cls):
dbHelp.clean_up()
cls.server.stop()
ticks = 0
while cherrypy.engine.state != cherrypy.engine.states.STOPPED:
time.sleep(1)
ticks += 1
if ticks >= 10:
raise TimeoutError("ran out of time")
return super().tearDownClass()
def setUp(self):
self.driver = webdriver.Firefox()
self.driver.implicitly_wait(5)
self.driver.get("http://127.0.0.1:8080")
self.input1 = self.driver.find_element_by_xpath("//input[@name='email_input_1']")
self.input2 = self.driver.find_element_by_xpath("//input[@name='email_input_2']")
self.pw1 = self.driver.find_element_by_xpath("//input[@name='pw_input_1']")
self.pw2 = self.driver.find_element_by_xpath("//input[@name='pw_input_2']")
self.ship = self.driver.find_element_by_xpath("//input[@name='ship_input']")
self.newUserModal = self.driver.find_element_by_id("new_user_box")
self.pwModal = self.driver.find_element_by_id("forgotten_pw_box")
return super().setUp()
def tearDown(self):
self.driver.quit()
return super().tearDown()
def open_new_user_box(self):
clickElem = self.driver.find_element_by_id("create_account")
clickElem.click()
def test_clearNewAccountWindow(self):
self.open_new_user_box()
self.input1.send_keys("aaaaa")
self.input2.send_keys("bbbbb")
self.pw1.send_keys("cccc")
self.pw2.send_keys("dddd")
self.ship.send_keys("eeee")
self.driver.execute_script("clearNewAccountWindow();")
self.assertEqual(self.input1.get_attribute('value'),"")
self.assertEqual(self.input2.get_attribute('value'),"")
self.assertEqual(self.pw1.get_attribute('value'),"")
self.assertEqual(self.pw2.get_attribute('value'),"")
self.assertEqual(self.ship.get_attribute('value'),"")
elem = self.driver.find_element_by_id("bad_email")
self.assertFalse(elem.is_displayed())
elem = self.driver.find_element_by_id("taken_email")
self.assertFalse(elem.is_displayed())
elem = self.driver.find_element_by_id("mismatched_email")
self.assertFalse(elem.is_displayed())
elem = self.driver.find_element_by_id("good_email")
self.assertFalse(elem.is_displayed())
elem = self.driver.find_element_by_id("short_pw")
self.assertFalse(elem.is_displayed())
elem = self.driver.find_element_by_id("mismatched_pw")
self.assertFalse(elem.is_displayed())
def test_createAccountClick(self):
elem = self.driver.find_element_by_id("new_user_box")
self.assertFalse(elem.is_displayed())
self.driver.execute_script("createAccountClick();")
self.assertTrue(elem.is_displayed())
def test_forgotPWClick(self):
self.assertFalse(self.pwModal.is_displayed())
self.driver.execute_script("forgotPWClick();")
self.assertTrue(self.pwModal.is_displayed())
def test_cancelAddClick(self):
self.open_new_user_box()
self.assertTrue(self.newUserModal.is_displayed())
self.driver.execute_script("cancelAddClick();")
self.assertFalse(self.newUserModal.is_displayed())
def test_cancelForgotPassword(self):
self.driver.find_element_by_id("forgot_pw").click()
self.assertTrue(self.pwModal.is_displayed())
self.driver.execute_script("cancelForgotPassword();")
self.assertFalse(self.pwModal.is_displayed())
def test_validateEmailAjaxSuccess(self):
self.open_new_user_box()
self.driver.execute_script(
"validateNewEmailAjaxSuccess("
"{'messages':['#bad_email'],'success':false});")
elem = self.driver.find_element_by_id("bad_email")
self.assertTrue(elem.is_displayed())
self.driver.execute_script(
"validateNewEmailAjaxSuccess("
"{'messages':['#bad_email','#taken_email'],'success':false});")
elem = self.driver.find_element_by_id("bad_email")
self.assertTrue(elem.is_displayed())
elem = self.driver.find_element_by_id("taken_email")
self.assertTrue(elem.is_displayed())
self.driver.execute_script(
"validateNewEmailAjaxSuccess("
"{'messages':['#good_email'],'success':true});")
elem = self.driver.find_element_by_id("bad_email")
self.assertFalse(elem.is_displayed())
elem = self.driver.find_element_by_id("taken_email")
self.assertFalse(elem.is_displayed())
elem = self.driver.find_element_by_id("good_email")
self.assertTrue(elem.is_displayed())
def test_loginAjaxSuccessSession(self):
AuthenticationLayer.disableAuthenticationRedirects = True
self.driver.execute_script("loginAjaxSuccess({'messages':[\"#bad_login\",\"#bad_login_pw\"],'success':false});")
self.assertEqual(self.driver.title,"Login to Space Habit Frontier")
elem = self.driver.find_element_by_id("bad_login")
self.assertTrue(elem.is_displayed())
elem = self.driver.find_element_by_id("bad_login_pw")
self.assertTrue(elem.is_displayed())
self.driver.execute_script("loginAjaxSuccess({'messages':[\"#bad_login_pw\"],'success':false});")
self.assertEqual(self.driver.title,"Login to Space Habit Frontier")
elem = self.driver.find_element_by_id("bad_login")
self.assertFalse(elem.is_displayed())
elem = self.driver.find_element_by_id("bad_login_pw")
self.assertTrue(elem.is_displayed())
self.driver.execute_script("loginAjaxSuccess({'messages':[],'success':true});")
#WebDriverWait(self.driver,10).until(EC.title_is("Space Habit Frontier!"))
self.assertEqual(self.driver.title,"Space Habit Frontier!")
def test_onEmail2InputBlur(self):
self.open_new_user_box()
self.input1.send_keys("[email protected]")
self.input2.send_keys("[email protected]")
self.driver.execute_script("onEmail2InputBlur();")
elem = self.driver.find_element_by_id("mismatched_email")
self.assertTrue(elem.is_displayed())
self.input2.clear()
self.input2.send_keys("[email protected]")
self.assertEqual(self.input1.get_attribute('value'),self.input2.get_attribute('value'))
self.driver.execute_script("onEmail2InputBlur();")
self.assertFalse(elem.is_displayed())
def test_onPw1InputBlur(self):
self.open_new_user_box()
self.pw1.send_keys("123")
self.driver.execute_script("onPw1InputBlur();")
elem = self.driver.find_element_by_id("short_pw")
self.assertTrue(elem.is_displayed())
self.pw1.clear()
self.pw1.send_keys("123456")
self.driver.execute_script("onPw1InputBlur();")
self.assertFalse(elem.is_displayed())
def test_onPw2InputBlur(self):
self.open_new_user_box()
self.pw1.send_keys("abcdef")
self.pw2.send_keys("Abcdef")
self.driver.execute_script("onPw2InputBlur();")
elem = self.driver.find_element_by_id("mismatched_pw")
self.assertTrue(elem.is_displayed())
self.pw2.clear()
self.pw2.send_keys("abcdef")
self.assertEqual(self.pw1.get_attribute('value'),self.pw2.get_attribute('value'))
self.driver.execute_script("onPw2InputBlur();")
self.assertFalse(elem.is_displayed())
if __name__ == '__main__':
unittest.main()
| 35.763889 | 116 | 0.725178 |
c6edeabef1d5d2d8a8039a8f4b9cb99f0a55ea3c | 2,709 | py | Python | test.py | pren1/DD_real_time_radar | 23c40de48b43ed78f93bdc3305598cfc378a46a4 | [
"MIT"
] | 11 | 2020-04-05T18:36:59.000Z | 2021-11-25T14:58:18.000Z | test.py | pren1/DD_real_time_radar | 23c40de48b43ed78f93bdc3305598cfc378a46a4 | [
"MIT"
] | null | null | null | test.py | pren1/DD_real_time_radar | 23c40de48b43ed78f93bdc3305598cfc378a46a4 | [
"MIT"
] | null | null | null | # # import requests
# # import pprint
# # import pdb
# #
# # contents = requests.get('https://api.vtbs.moe/v1/info').json()
# # result = []
# # for single in contents:
# # if single['liveStatus'] == 1:
# # result.append(single['roomid'])
# # print(len(result))
# # pdb.set_trace()
# #
# # s1 = [21501730,1491028,21302070,21720301,21712857,1191799,22463523,43307,21412734,22319939,7554620]
# # s2 = [22535566,21362762,21345362,21180272,4637570,7173352,4992290,21718578,596082,8112629,11306]
# # s3 = [21720308,11312,1625715,1603600,3473293,801580,21564812,7439941,15978,19064,10947031]
# # s4 = [21927742,671472,22389319,21696957,15536,21302469,236672,22377405,10801,157501,6608174,708397]
# #
# # # print(f"s1: {len(s1)}, set: {len(set(s1))}")
# # # print(f"s2: {len(s2)}, set: {len(set(s2))}")
# # # print(f"s3: {len(s3)}, set: {len(set(s3))}")
# # # print(f"s4: {len(s4)}, set: {len(set(s4))}")
# #
# # res = s1 + s2 + s3 + s4
# # print(f"res: {len(res)}, set: {len(set(res))}")
# #
# # diff = set(res) - set(result)
# #
# #
# # def get_difference_between_two_lists(old_list, new_list):
# # total_set = set(old_list + new_list)
# # removed_list = []
# # added_list = []
# # for single in total_set:
# # if single in old_list and single in new_list:
# # continue
# # elif single in old_list and single not in new_list:
# # removed_list.append(single)
# # elif single not in old_list and single in new_list:
# # added_list.append(single)
# # else:
# # assert 1 == 0, "Fatal logic error"
# # return removed_list, added_list
# #
# #
# # remove, add = get_difference_between_two_lists(result, res)
# # print(remove)
# # print(add)
# # pdb.set_trace()
# import time
# import threading
#
# def timer_func():
# # pass
# # next_call = time.time()
# while True:
# try:
# period_seconds = 3
# print('test!')
# time.sleep(period_seconds)
# raise ValueError('Represents a hidden bug, do not catch this')
# except Exception as error:
# print('Caught this error: ' + repr(error), file=open("log.txt", "a"))
#
# threading.Thread(target=timer_func).start()
import traceback
def test_func():
print("testing..")
var = [0]
# print(var[1])
# assert False, "wrong assert!"
raise ValueError('Represents a hidden bug, do not catch this')
try:
test_func()
except Exception as error:
print('Caught this error: ' + repr(error), file=open("log.txt", "a"))
traceback_str = ''.join(traceback.format_tb(error.__traceback__))
print('Caught this traceback: ' + traceback_str, file=open("log.txt", "a")) | 34.291139 | 103 | 0.611296 |
148c3d83899eba8c41b564337acf5f4dcbcd171e | 1,181 | ts | TypeScript | src/app/documentation/documentation.module.ts | Mainioco/forms | 4731752a64ac1caf1b78cb4522daf6e643dfd59e | [
"MIT"
] | null | null | null | src/app/documentation/documentation.module.ts | Mainioco/forms | 4731752a64ac1caf1b78cb4522daf6e643dfd59e | [
"MIT"
] | 5 | 2018-07-18T17:38:22.000Z | 2018-07-20T07:17:50.000Z | src/app/documentation/documentation.module.ts | Mainioco/forms | 4731752a64ac1caf1b78cb4522daf6e643dfd59e | [
"MIT"
] | null | null | null | import { NgModule } from "@angular/core";
import { CommonModule } from "@angular/common";
import { WelcomeComponent } from "./welcome/welcome.component";
import { MatSidenavModule, MatButtonModule } from "@angular/material";
import { NavigationComponent } from "./navigation/navigation.component";
import { RouterModule } from "@angular/router";
import { IntroComponent } from "./getting-started/intro/intro.component";
import { MarkdownModule } from "ngx-markdown";
import { ItemComponent } from "./navigation/components/item/item.component";
export const documentationRoutes = [
{
path: "documentation",
component: WelcomeComponent
},
{
path: "documentation/getting-started",
component: IntroComponent,
pathMatch: "prefix"
},
{
path: "documentation/api/form-fields",
component: IntroComponent,
pathMatch: "prefix"
}
];
@NgModule({
imports: [
CommonModule,
MatSidenavModule,
MatButtonModule,
RouterModule,
MarkdownModule.forRoot()
],
declarations: [
WelcomeComponent,
NavigationComponent,
IntroComponent,
ItemComponent
],
exports: [WelcomeComponent]
})
export class DocumentationModule {}
| 26.840909 | 76 | 0.712108 |
3c6a09392321a37182f6d042ba04838ca059a57b | 994 | dart | Dart | example/lib/components/badge_demo.dart | flutter-jp/flutter_ui | 53d9283439186ec4226ff6375ccb772a8cb437cb | [
"MIT"
] | 20 | 2019-10-29T02:39:43.000Z | 2022-03-02T08:22:50.000Z | example/lib/components/badge_demo.dart | flutter-jp/flutter_ui | 53d9283439186ec4226ff6375ccb772a8cb437cb | [
"MIT"
] | 1 | 2019-11-22T07:21:46.000Z | 2019-11-22T07:21:46.000Z | example/lib/components/badge_demo.dart | flutter-jp/flutter_ui | 53d9283439186ec4226ff6375ccb772a8cb437cb | [
"MIT"
] | 5 | 2019-11-01T11:13:56.000Z | 2020-10-07T23:51:07.000Z | import 'package:flutter/material.dart';
import 'package:flutter_ui/entity.dart';
import 'package:flutter_ui/material.dart';
class BadgeDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('badge'),
),
body: Column(children: <Widget>[
_buildNormalBadge(),
Divider(
color: Colors.grey,
),
_buildNormalBadge(),
]));
}
Widget _buildNormalBadge() {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
MBadge(
label: '1',
color: MColor.dangerBgColor,
),
MBadge(
label: '2',
color: MColor.warningBgColor,
),
MBadge(
label: '3',
color: MColor.infoBgColor,
),
MBadge(
label: '4',
color: MColor.successBgColor,
),
],
);
}
}
| 22.088889 | 55 | 0.532193 |
641bda3052bba4bf9941da7364723d92a8d023d3 | 1,949 | py | Python | main.py | mrinalpande/Music-Encrypt | 95e0f128232be307c844066cdf85a39097855d47 | [
"MIT"
] | 6 | 2017-08-19T21:41:57.000Z | 2022-01-15T22:25:09.000Z | main.py | mrinalpande/Music-Encrypt | 95e0f128232be307c844066cdf85a39097855d47 | [
"MIT"
] | null | null | null | main.py | mrinalpande/Music-Encrypt | 95e0f128232be307c844066cdf85a39097855d47 | [
"MIT"
] | 2 | 2017-11-28T00:18:02.000Z | 2022-01-16T06:57:42.000Z | ### Author: Mrinal Pande
### Date: Aug,15 2017
import sys
import os.path
import encrypt
import decrypt
def main():
print("---------------------------------------------------")
print("Music Encrypt - Music Based Encryption")
print("Author: Mrinal Pande")
print("---------------------------------------------------")
if len(sys.argv) < 2:
print("Invalid input \nFor Help:",sys.argv[0],"-h")
elif sys.argv[1] == "-h":
print("Help For Music Encrypt")
print("---------------------------------------------------")
print("Options Description")
print("-f File to encrypt/Decrypt")
print("-e Encrypt the file")
print("-d Decrypt the file")
print("-k Key to Encrypt")
print("-o name of output file")
print("\nFor encrypting a file:")
print("python main.py -f <filename> -e -k <key> -o <output file name>")
print("\nFor decrypting a file:")
print("python main.py -f <filename> -d -k <key>")
print("---------------------------------------------------")
elif sys.argv[3] == "-e" and len(sys.argv) == 8:
fpath = sys.argv[2]
key = sys.argv[5]
outfile = sys.argv[7]
print("Starting Encryption...")
if os.path.isfile(fpath):
encrypt.encrypt(fpath,key,outfile)
else:
print("File not found \n")
print("Invalid input\nFor Help:",sys.argv[0],"-h")
elif sys.argv[3] == "-d" and len(sys.argv) == 6:
print("Decryption")
fpath = sys.argv[2]
key = sys.argv[5]
print("Starting decryption...")
if os.path.isfile(fpath):
decrypt.decrypt(fpath,key)
else:
print("File not found \n")
print("Invalid input\nFor Help:",sys.argv[0],"-h")
else:
print("Invalid input\nFor Help:",sys.argv[0],"-h")
main() | 38.215686 | 79 | 0.473063 |
b096c910a97d50c940bb7cc9f5b1a1cb0d02d539 | 11,258 | py | Python | sitegate/south_migrations/0003_auto__add_preferences__add_emailconfirmation__chg_field_invitationcode.py | imposeren/django-sitegate | f25049b5d8c6541e4775f12e3df455376669674b | [
"BSD-3-Clause"
] | null | null | null | sitegate/south_migrations/0003_auto__add_preferences__add_emailconfirmation__chg_field_invitationcode.py | imposeren/django-sitegate | f25049b5d8c6541e4775f12e3df455376669674b | [
"BSD-3-Clause"
] | null | null | null | sitegate/south_migrations/0003_auto__add_preferences__add_emailconfirmation__chg_field_invitationcode.py | imposeren/django-sitegate | f25049b5d8c6541e4775f12e3df455376669674b | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Preferences'
db.create_table('sitegate_preferences', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('signin_enabled', self.gf('django.db.models.fields.BooleanField')(default=True)),
('signin_disabled_text', self.gf('django.db.models.fields.TextField')(default='Sign in is disabled.')),
('signup_enabled', self.gf('django.db.models.fields.BooleanField')(default=True)),
('signup_disabled_text', self.gf('django.db.models.fields.TextField')(default='Sign up is disabled.')),
('signup_verify_email_title', self.gf('django.db.models.fields.CharField')(max_length=160, default='Account activation')),
('signup_verify_email_body', self.gf('django.db.models.fields.TextField')(default='Please follow the link below to activate your account:\n%(link)s')),
))
db.send_create_signal('sitegate', ['Preferences'])
# Adding model 'EmailConfirmation'
db.create_table('sitegate_emailconfirmation', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('code', self.gf('django.db.models.fields.CharField')(unique=True, max_length=128)),
('time_created', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
('time_accepted', self.gf('django.db.models.fields.DateTimeField')(null=True)),
('expired', self.gf('django.db.models.fields.BooleanField')(db_index=True, default=False)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['apps.User'])),
))
db.send_create_signal('sitegate', ['EmailConfirmation'])
# Changing field 'InvitationCode.acceptor'
db.alter_column('sitegate_invitationcode', 'acceptor_id', self.gf('django.db.models.fields.related.ForeignKey')(null=True, to=orm['apps.User']))
# Changing field 'InvitationCode.creator'
db.alter_column('sitegate_invitationcode', 'creator_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['apps.User']))
def backwards(self, orm):
# Deleting model 'Preferences'
db.delete_table('sitegate_preferences')
# Deleting model 'EmailConfirmation'
db.delete_table('sitegate_emailconfirmation')
# Changing field 'InvitationCode.acceptor'
db.alter_column('sitegate_invitationcode', 'acceptor_id', self.gf('django.db.models.fields.related.ForeignKey')(null=True, to=orm['auth.User']))
# Changing field 'InvitationCode.creator'
db.alter_column('sitegate_invitationcode', 'creator_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User']))
models = {
'apps.place': {
'Meta': {'object_name': 'Place'},
'geo_bounds': ('django.db.models.fields.CharField', [], {'null': 'True', 'max_length': '255', 'blank': 'True'}),
'geo_pos': ('django.db.models.fields.CharField', [], {'null': 'True', 'max_length': '255', 'blank': 'True'}),
'geo_title': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'geo_type': ('django.db.models.fields.CharField', [], {'null': 'True', 'db_index': 'True', 'blank': 'True', 'max_length': '25'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'raters_num': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'rating': ('django.db.models.fields.FloatField', [], {'db_index': 'True', 'default': '0'}),
'status': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}),
'time_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'time_modified': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'auto_now': 'True', 'blank': 'True'}),
'time_published': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'user_title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'apps.user': {
'Meta': {'object_name': 'User'},
'comments_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'disqus_category_id': ('django.db.models.fields.CharField', [], {'null': 'True', 'max_length': '30', 'blank': 'True'}),
'disqus_shortname': ('django.db.models.fields.CharField', [], {'null': 'True', 'max_length': '100', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'to': "orm['auth.Group']", 'symmetrical': 'False', 'related_name': "'user_set'"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'place': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'related_name': "'users'", 'to': "orm['apps.Place']", 'blank': 'True'}),
'raters_num': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'rating': ('django.db.models.fields.FloatField', [], {'db_index': 'True', 'default': '0'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'to': "orm['auth.Permission']", 'symmetrical': 'False', 'related_name': "'user_set'"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'blank': 'True', 'to': "orm['auth.Permission']", 'symmetrical': 'False'})
},
'auth.permission': {
'Meta': {'object_name': 'Permission', 'unique_together': "(('content_type', 'codename'),)", 'ordering': "('content_type__app_label', 'content_type__model', 'codename')"},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'contenttypes.contenttype': {
'Meta': {'object_name': 'ContentType', 'db_table': "'django_content_type'", 'unique_together': "(('app_label', 'model'),)", 'ordering': "('name',)"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'sitegate.blacklisteddomain': {
'Meta': {'object_name': 'BlacklistedDomain'},
'domain': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '253'}),
'enabled': ('django.db.models.fields.BooleanField', [], {'db_index': 'True', 'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
},
'sitegate.emailconfirmation': {
'Meta': {'object_name': 'EmailConfirmation'},
'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}),
'expired': ('django.db.models.fields.BooleanField', [], {'db_index': 'True', 'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'time_accepted': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'time_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['apps.User']"})
},
'sitegate.invitationcode': {
'Meta': {'object_name': 'InvitationCode'},
'acceptor': ('django.db.models.fields.related.ForeignKey', [], {'null': 'True', 'related_name': "'acceptors'", 'to': "orm['apps.User']", 'blank': 'True'}),
'code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}),
'creator': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'creators'", 'to': "orm['apps.User']"}),
'expired': ('django.db.models.fields.BooleanField', [], {'db_index': 'True', 'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'time_accepted': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
'time_created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
},
'sitegate.preferences': {
'Meta': {'object_name': 'Preferences'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'signin_disabled_text': ('django.db.models.fields.TextField', [], {'default': "'Sign in is disabled.'"}),
'signin_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'signup_disabled_text': ('django.db.models.fields.TextField', [], {'default': "'Sign up is disabled.'"}),
'signup_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'signup_verify_email_body': ('django.db.models.fields.TextField', [], {'default': "'Please follow the link below to activate your account:\\n%(link)s'"}),
'signup_verify_email_title': ('django.db.models.fields.CharField', [], {'max_length': '160', 'default': "'Account activation'"})
}
}
complete_apps = ['sitegate'] | 75.053333 | 193 | 0.593978 |
74d48fe17c33860326858daace0ddf131c3bb43c | 329 | css | CSS | public/css/products.css | zqxhhh/item_one | a645535a58fb8dd768c3b71fe9366decc1b8b029 | [
"MIT"
] | null | null | null | public/css/products.css | zqxhhh/item_one | a645535a58fb8dd768c3b71fe9366decc1b8b029 | [
"MIT"
] | null | null | null | public/css/products.css | zqxhhh/item_one | a645535a58fb8dd768c3b71fe9366decc1b8b029 | [
"MIT"
] | null | null | null |
#top_img img{width:100%;}
#products{background:#212121}
.products::before{content: "";display: table;}
.products_ul{border:0;margin:20px 0;}
.nav-item{border:0;}
.page_ul{width:20%;margin:20px auto;}
.page_ul li{margin: 0 5px;}
.page_ul li a{border-radius: 2PX;color:#fff !important;background:#666 !important;border:0;}
| 19.352941 | 92 | 0.717325 |
b71238fe90d5bf983e82cf2e31424a232d3b3126 | 857 | cs | C# | lab/SeedingWeedingOutAndDestroyingStartup/NSeed.xUnit/UseSeedingStartupAttribute.cs | nseedio/nseed | 3312c8dcf04bdc7033d8e1b8a6c871447a911aaa | [
"MIT"
] | 1 | 2020-12-04T13:13:23.000Z | 2020-12-04T13:13:23.000Z | lab/SeedingWeedingOutAndDestroyingStartup/NSeed.xUnit/UseSeedingStartupAttribute.cs | nseedio/nseed | 3312c8dcf04bdc7033d8e1b8a6c871447a911aaa | [
"MIT"
] | 5 | 2019-08-20T20:12:56.000Z | 2020-04-09T20:13:27.000Z | lab/SeedingWeedingOutAndDestroyingStartup/NSeed.xUnit/UseSeedingStartupAttribute.cs | nseedio/nseed | 3312c8dcf04bdc7033d8e1b8a6c871447a911aaa | [
"MIT"
] | null | null | null | using NSeed.Discovery.SeedBucket.ReflectionBased;
using NSeed.Seeding;
using System;
using System.Linq;
using System.Reflection;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace NSeed.Xunit
{
/// <summary>
/// TODO.
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = false, Inherited = true)]
public sealed class UseSeedingStartupAttribute : Attribute
{
public Type SeedingStartupType { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="UseSeedingStartupAttribute"/> class.
/// </summary>
/// <param name="seedingStartupType">TODO.</param>
public UseSeedingStartupAttribute(Type seedingStartupType)
{
SeedingStartupType = seedingStartupType;
}
}
}
| 29.551724 | 139 | 0.681447 |
dd5afa31420e09bd76bb47be1f4385ec670d40b4 | 1,747 | java | Java | test/src/main/java/lk/exame/test/dao/QuestionDAO.java | TharakaCz/Mock-Exame-Final | b0ed54d904d38abe84f3d62c2add4b4c2591d2d1 | [
"MIT"
] | null | null | null | test/src/main/java/lk/exame/test/dao/QuestionDAO.java | TharakaCz/Mock-Exame-Final | b0ed54d904d38abe84f3d62c2add4b4c2591d2d1 | [
"MIT"
] | null | null | null | test/src/main/java/lk/exame/test/dao/QuestionDAO.java | TharakaCz/Mock-Exame-Final | b0ed54d904d38abe84f3d62c2add4b4c2591d2d1 | [
"MIT"
] | null | null | null | package lk.exame.test.dao;
import java.util.ArrayList;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import lk.exame.test.entity.LanguageEntity;
import lk.exame.test.entity.QuestionEntity;
import lk.exame.test.entity.SubjectEntity;
/**
*
* @author Tharaka Chandralal
*/
public interface QuestionDAO extends JpaRepository<QuestionEntity, Integer>{
List<QuestionEntity>findAllByQuestionLeval(String questionLeval);
QuestionEntity findByQuesId(Integer quesId);
QuestionEntity findOneByQuestion(String question);
List<QuestionEntity> findAllByStatus(String status);
List<QuestionEntity>findAllByStatusAndLanguageEntitiey(String status,LanguageEntity languageEntity);
List<QuestionEntity>findAllByStatusAndSubjectEntitiy(String status,SubjectEntity subjectEntity);
List<QuestionEntity>findAllByStatusAndSubjectEntitiyAndLanguageEntitiey(String status,SubjectEntity subjectEntity,LanguageEntity languageEntity);
List<QuestionEntity>findAllByStatusAndSubjectEntitiyOrLanguageEntitiey(String status,SubjectEntity subjectEntity , LanguageEntity languageEntity);
ArrayList<QuestionEntity> findOneQuesIdByQuestionLevalAndStatusAndLanguageEntitieyAndSubjectEntitiy(String questionLeval,String status,LanguageEntity languageEntity,SubjectEntity subjectEntity);
ArrayList<QuestionEntity>findOneQuesIdByQuestionLevalAndStatusAndLanguageEntitieyAndSubjectEntitiyAndQuesIdNotIn(String questionLeval,String status,LanguageEntity languageEntity,SubjectEntity subjectEntity,List<Integer>questionIds);
QuestionEntity findOneByLanguageEntitiey(LanguageEntity languageEntity);
QuestionEntity findOneBySubjectEntitiy(SubjectEntity subjectEntity);
}
| 40.627907 | 235 | 0.847739 |
93fa665b08fcf055f07d071d5c5edf09546508b8 | 5,951 | cs | C# | Eliza.UI/Forms/FurnitureDataForm.cs | adiktus/Eliza | 7c5040c28c738a39692e36e95fdc80afa97662ac | [
"MIT"
] | 4 | 2021-07-04T02:49:15.000Z | 2022-03-31T12:09:55.000Z | Eliza.UI/Forms/FurnitureDataForm.cs | adiktus/Eliza | 7c5040c28c738a39692e36e95fdc80afa97662ac | [
"MIT"
] | 7 | 2021-06-27T15:28:10.000Z | 2022-03-29T05:13:37.000Z | Eliza.UI/Forms/FurnitureDataForm.cs | adiktus/Eliza | 7c5040c28c738a39692e36e95fdc80afa97662ac | [
"MIT"
] | 2 | 2022-03-23T19:56:37.000Z | 2022-03-27T12:41:38.000Z | using Eliza.Model.SaveData;
using Eliza.UI.Helpers;
using Eliza.UI.Widgets;
using Eto.Forms;
using System;
namespace Eliza.UI.Forms
{
internal class FurnitureDataForm : Form
{
public FurnitureDataForm(RF5FurnitureData furnitureData)
{
Title = "Furniture Data";
var unk1 = new SpinBox(
new Ref<int>(() => furnitureData.Unk1, v => { furnitureData.Unk1 = v; }),
"Unk 1"
);
var unk2 = new SpinBox(
new Ref<int>(() => furnitureData.Unk2, v => { furnitureData.Unk2 = v; }),
"Unk 2"
);
var furnitureSaveData = new GroupBox()
{
Text = "Furniture Save Data"
};
{
var furnitureSaveDataList = new ListBox();
var furnitureSaveDataHBox = new HBox();
var furnitureSaveDataData = new VBox();
for (int i = 0; i < furnitureData.FurnitureSaveData.Count; i++)
{
furnitureSaveDataList.Items.Add($"Furniture {i}");
}
var pos = new Vector3Group("Pos");
var rot = new QuaternionGroup("Rot");
var sceneId = new SpinBox("Scene ID");
var id = new SpinBox("ID");
var uniqueId = new LineEdit("Unique ID");
var point = new SpinBox("Point");
var hp = new SpinBox("HP");
var have = new Widgets.CheckBox("Have");
furnitureSaveDataList.SelectedIndexChanged += (object sender, EventArgs e) =>
{
pos.ChangeReferenceValue(
new Ref<float>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Pos.X, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Pos.X = v; }),
new Ref<float>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Pos.Y, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Pos.Y = v; }),
new Ref<float>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Pos.Z, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Pos.Z = v; })
);
rot.ChangeReferenceValue(
new Ref<float>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Rot.W, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Rot.W = v; }),
new Ref<float>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Rot.X, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Rot.X = v; }),
new Ref<float>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Rot.Y, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Rot.Y = v; }),
new Ref<float>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Rot.Z, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Rot.Z = v; })
);
sceneId.ChangeReferenceValue(
new Ref<int>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].SceneId, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].SceneId = v; })
);
id.ChangeReferenceValue(
new Ref<int>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Id, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Id = v; })
);
uniqueId.ChangeReferenceValue(
new Ref<string>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].UniqueId, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].UniqueId = v; })
);
point.ChangeReferenceValue(
new Ref<int>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Point, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Point = v; })
);
hp.ChangeReferenceValue(
new Ref<int>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Hp, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Hp = v; })
);
have.ChangeReferenceValue(
new Ref<bool>(() => furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Have, v => { furnitureData.FurnitureSaveData[furnitureSaveDataList.SelectedIndex].Have = v; })
);
};
StackLayoutItem[] furnitureSaveDataDataItems =
{
pos,
rot,
sceneId,
id,
uniqueId,
point,
hp,
have
};
foreach (var item in furnitureSaveDataDataItems)
{
furnitureSaveDataData.Items.Add(item);
}
furnitureSaveDataHBox.Items.Add(furnitureSaveDataList);
furnitureSaveDataHBox.Items.Add(furnitureSaveDataData);
furnitureSaveData.Content = furnitureSaveDataHBox;
}
var vBox = new VBox();
vBox.Items.Add(unk1);
vBox.Items.Add(unk2);
vBox.Items.Add(furnitureSaveData);
var scroll = new Scrollable();
scroll.Content = vBox;
Content = scroll;
}
}
} | 51.301724 | 217 | 0.568644 |
385c0b2d09a16f8a7297543884539b07cfaea458 | 1,388 | cs | C# | src/Gemini.Demo.MonoGame/Modules/SceneViewer/ViewModels/SceneViewModel.cs | KornnerStudios/gemini | a3dbb43f14e860b4f9ae86a59523b288646b961d | [
"MS-PL"
] | 11 | 2020-01-05T19:54:13.000Z | 2022-01-22T21:00:13.000Z | src/Gemini.Demo.MonoGame/Modules/SceneViewer/ViewModels/SceneViewModel.cs | KornnerStudios/gemini | a3dbb43f14e860b4f9ae86a59523b288646b961d | [
"MS-PL"
] | 12 | 2019-06-29T17:18:33.000Z | 2019-09-12T03:07:27.000Z | src/Gemini.Demo.MonoGame/Modules/SceneViewer/ViewModels/SceneViewModel.cs | KornnerStudios/gemini | a3dbb43f14e860b4f9ae86a59523b288646b961d | [
"MS-PL"
] | 4 | 2019-10-21T21:30:36.000Z | 2022-02-28T04:08:44.000Z | using System;
using System.ComponentModel.Composition;
using Gemini.Demo.MonoGame.Modules.SceneViewer.Views;
using Gemini.Framework;
using Microsoft.Xna.Framework;
namespace Gemini.Demo.MonoGame.Modules.SceneViewer.ViewModels
{
[Export(typeof(SceneViewModel))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class SceneViewModel : Document
{
private ISceneView _sceneView;
public override bool ShouldReopenOnStart
{
get { return true; }
}
private Vector3 _position;
public Vector3 Position
{
get { return _position; }
set
{
_position = value;
NotifyOfPropertyChange(() => Position);
if (_sceneView != null)
_sceneView.Invalidate();
}
}
public SceneViewModel()
{
DisplayName = "3D Scene";
}
protected override void OnViewLoaded(object view)
{
_sceneView = view as ISceneView;
base.OnViewLoaded(view);
}
protected override void OnDeactivate(bool close)
{
if (close)
{
var view = GetView() as IDisposable;
if (view != null)
view.Dispose();
}
base.OnDeactivate(close);
}
}
} | 24.350877 | 61 | 0.548271 |
6654587d82f9297e39fe40639e90ccff599a025c | 1,873 | py | Python | dungeon_game/decorators.py | erem2k/dungeon_game | 02659aa03237c48867c126fedfa123133ff6edbf | [
"MIT"
] | null | null | null | dungeon_game/decorators.py | erem2k/dungeon_game | 02659aa03237c48867c126fedfa123133ff6edbf | [
"MIT"
] | null | null | null | dungeon_game/decorators.py | erem2k/dungeon_game | 02659aa03237c48867c126fedfa123133ff6edbf | [
"MIT"
] | null | null | null | """
This module lists decorators for task 6.1 from Coding Campus 2018 Python course
(Dungeon Game)
"""
import logging
import inspect
import functools
import dungeon_game.log as log
import dungeon_game.config as config
logger = logging.getLogger(log.LOGGER_NAME)
def log_decorator(func):
"""
Decorator for function call logger
:param func: Function to decorate with call logger
:return: Wrapper function
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
return_value = None
log_level = 0
if config.IS_DEBUG:
log_level = config.LEVEL_INFO
else:
log_level = config.LEVEL_DEBUG
logger.log(log_level, f"Calling {func.__name__}")
return_value = func(*args, **kwargs)
logger.log(log_level, f"Function {func.__name__} executed successfully")
return return_value
return wrapper
def debug_log_decorator(func):
"""
Debug decorator for function call logger
:param func: Function to decorate with debug call logger
:return: Wrapper function
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
return_value = None
log_level = 0
if config.IS_DEBUG:
log_level = config.LEVEL_INFO
else:
log_level = config.LEVEL_DEBUG
bound = inspect.signature(func).bind(*args, **kwargs)
log_string_arg_list = ["Arguments passed:"]
for key, value in bound.arguments.items():
log_string_arg_list.append(f"{key} : {value}")
logger.log(log_level, ' '.join(log_string_arg_list))
return_value = func(*args, **kwargs)
logger.log(log_level, f"Function {func.__name__} returned {return_value}")
return return_value
return wrapper
| 24.973333 | 83 | 0.625734 |
f5bf170c8fc612cd5fb3cf94fe96ff97bbfad61d | 1,478 | go | Go | rest/model/conversions.go | xdg-forks/evergreen | 012cd09d902cf600cf04929949b50be2732f449a | [
"Apache-2.0"
] | null | null | null | rest/model/conversions.go | xdg-forks/evergreen | 012cd09d902cf600cf04929949b50be2732f449a | [
"Apache-2.0"
] | null | null | null | rest/model/conversions.go | xdg-forks/evergreen | 012cd09d902cf600cf04929949b50be2732f449a | [
"Apache-2.0"
] | null | null | null | package model
import (
"go/types"
"github.com/pkg/errors"
)
type convertType string
func stringToString(in string) string {
return in
}
func stringToStringPtr(in string) *string {
return &in
}
func stringPtrToString(in *string) string {
if in == nil {
return ""
}
return *in
}
func stringPtrToStringPtr(in *string) *string {
return in
}
func intToInt(in int) int {
return in
}
func intToIntPtr(in int) *int {
return &in
}
func intPtrToInt(in *int) int {
if in == nil {
return 0
}
return *in
}
func intPtrToIntPtr(in *int) *int {
return in
}
func conversionFn(in types.Type, outIsPtr bool) (string, error) {
if intype, inIsPrimitive := in.(*types.Basic); inIsPrimitive {
switch intype.Kind() {
case types.String:
if outIsPtr {
return "stringToStringPtr", nil
}
return "stringToString", nil
case types.Int:
if outIsPtr {
return "intToIntPtr", nil
}
return "intToInt", nil
}
}
if intype, inIsPtr := in.(*types.Pointer); inIsPtr {
value, isPrimitive := intype.Elem().(*types.Basic)
if !isPrimitive {
return "", errors.New("pointers to complex objects not implemented yet")
}
switch value.Kind() {
case types.String:
if outIsPtr {
return "stringPtrToStringPtr", nil
}
return "stringPtrToString", nil
case types.Int:
if outIsPtr {
return "intPtrToIntPtr", nil
}
return "intPtrToInt", nil
}
}
return "", errors.Errorf("converting type %s is not supported", in.String())
}
| 17.388235 | 77 | 0.668471 |
bb6552d8345f0f052bd23876c0ce27c3e686b9a7 | 8,573 | cs | C# | src/ComService/Boudaries/Controllers/NewsController.cs | chumano/nextone | 7a387d7b96c7c33aa69f97be1a76ec51496c9c3c | [
"Apache-2.0"
] | null | null | null | src/ComService/Boudaries/Controllers/NewsController.cs | chumano/nextone | 7a387d7b96c7c33aa69f97be1a76ec51496c9c3c | [
"Apache-2.0"
] | null | null | null | src/ComService/Boudaries/Controllers/NewsController.cs | chumano/nextone | 7a387d7b96c7c33aa69f97be1a76ec51496c9c3c | [
"Apache-2.0"
] | null | null | null | using ComService.Domain;
using ComService.DTOs;
using ComService.DTOs.News;
using ComService.Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NextOne.Infrastructure.Core;
using NextOne.Shared.Common;
using NextOne.Shared.Security;
using System.Linq;
using System.Threading.Tasks;
namespace ComService.Boudaries.Controllers
{
[Route("[controller]")]
[ApiController]
public class NewsController : ControllerBase
{
private readonly IUserContext _userContext;
private readonly ComDbContext _dbContext;
protected readonly IdGenerator _idGenerator;
public NewsController(
IUserContext userContext,
IdGenerator idGenerator,
ComDbContext comDbContext)
{
_userContext = userContext;
_idGenerator = idGenerator;
_dbContext = comDbContext;
}
[AllowAnonymous]
[HttpGet("GetList")]
public async Task<IActionResult> GetList([FromQuery] GetListNewsDTO getListDTO)
{
var userId = _userContext.User.UserId;
var pageOptions = new PageOptions(getListDTO.Offset, getListDTO.PageSize);
var query = _dbContext.News.AsNoTracking();
if (!string.IsNullOrWhiteSpace(getListDTO.TextSearch))
{
var textSearch = getListDTO.TextSearch.Trim();
query = query.Where(o =>
o.Title.Contains(textSearch)
|| o.Description.Contains(textSearch)
|| o.ImageDescription.Contains(textSearch)
|| o.PublishedUserName.Contains(textSearch)
);
}
if (!_userContext.IsAuthenticated)
{
query = query.Where(o => o.IsPublished == true);
}
else
{
if (getListDTO.PublishState != null && getListDTO.PublishState != YesNoEnum.All)
{
bool isPublished = getListDTO.PublishState == YesNoEnum.Yes;
query = query.Where(o => o.IsPublished == isPublished);
}
}
if (getListDTO.FromDate != null)
{
query = query.Where(o => o.PublishedDate >= getListDTO.FromDate);
}
if (getListDTO.ToDate != null)
{
query = query.Where(o => o.PublishedDate <= getListDTO.ToDate);
}
var items = await query
.OrderByDescending(o => o.PublishedDate)
.Skip(pageOptions.Offset)
.Take(pageOptions.PageSize)
.ToListAsync();
return Ok(ApiResult.Success(items));
}
[AllowAnonymous]
[HttpGet("Count")]
public async Task<IActionResult> Count([FromQuery] GetListNewsDTO getListDTO)
{
var userId = _userContext.User.UserId;
var pageOptions = new PageOptions(getListDTO.Offset, getListDTO.PageSize);
var query = _dbContext.News.AsNoTracking();
if (!string.IsNullOrWhiteSpace(getListDTO.TextSearch))
{
var textSearch = getListDTO.TextSearch.Trim();
query = query.Where(o =>
o.Title.Contains(textSearch)
|| o.Description.Contains(textSearch)
|| o.ImageDescription.Contains(textSearch)
|| o.PublishedUserName.Contains(textSearch)
);
}
if (!_userContext.IsAuthenticated)
{
query = query.Where(o => o.IsPublished == true);
}
else
{
if (getListDTO.PublishState != null && getListDTO.PublishState != YesNoEnum.All)
{
bool isPublished = getListDTO.PublishState == YesNoEnum.Yes;
query = query.Where(o => o.IsPublished == isPublished);
}
}
if (getListDTO.FromDate != null)
{
query = query.Where(o => o.PublishedDate >= getListDTO.FromDate);
}
if (getListDTO.ToDate != null)
{
query = query.Where(o => o.PublishedDate <= getListDTO.ToDate);
}
var count = await query.CountAsync();
return Ok(ApiResult.Success(count));
}
[AllowAnonymous]
[HttpGet("{id}")]
public async Task<IActionResult> Get(string id)
{
var item = await _dbContext.News.FindAsync(id);
return Ok(ApiResult.Success(item));
}
[HttpPost("CreateNews")]
public async Task<IActionResult> CreateNews(CreateNewsDTO newsDTO)
{
var userId = _userContext.User.UserId;
var userName = _userContext.User.Name;
var id = _idGenerator.GenerateNew();
var aNews = new News()
{
Id = id,
Title = newsDTO.Title,
Description = newsDTO.Description,
Content = newsDTO.Content,
ImageUrl = newsDTO.ImageUrl,
ImageDescription = newsDTO.ImageDescription,
IsPublished = false,
PublishedDate = System.DateTime.Now,
PublishedBy = userId,
PublishedUserName = userName,
};
_dbContext.News.Add(aNews);
await _dbContext.SaveChangesAsync();
return Ok(ApiResult.Success(id));
}
[HttpPost("update/{id}")]
public async Task<IActionResult> UpdateNews(string id, UpdateNewsDTO newsDTO)
{
var userId = _userContext.User.UserId;
var userName = _userContext.User.Name;
var item = await _dbContext.News.FindAsync(id);
if (item == null)
{
throw new System.Exception($"News Id {id} is not found");
}
item.Title = newsDTO.Title;
item.Description = newsDTO.Description;
item.Content = newsDTO.Content;
item.ImageUrl = newsDTO.ImageUrl;
item.ImageDescription = newsDTO.ImageDescription;
item.PublishedDate = System.DateTime.Now;
item.PublishedBy = userId;
item.PublishedUserName = userName;
_dbContext.News.Update(item);
await _dbContext.SaveChangesAsync();
return Ok(ApiResult.Success(null));
}
[HttpPost("publish/{id}")]
public async Task<IActionResult> Publish(string id)
{
var userId = _userContext.User.UserId;
var userName = _userContext.User.Name;
var item = await _dbContext.News.FindAsync(id);
if (item == null)
{
throw new System.Exception($"News Id {id} is not found");
}
item.IsPublished = true;
item.PublishedDate = System.DateTime.Now;
item.PublishedBy = userId;
item.PublishedUserName = userName;
_dbContext.News.Update(item);
await _dbContext.SaveChangesAsync();
return Ok(ApiResult.Success(null));
}
[HttpPost("unpublish/{id}")]
public async Task<IActionResult> UnPublish( string id)
{
var userId = _userContext.User.UserId;
var userName = _userContext.User.Name;
var item = await _dbContext.News.FindAsync(id);
if (item == null)
{
throw new System.Exception($"News Id {id} is not found");
}
item.IsPublished = false;
item.PublishedDate = System.DateTime.Now;
item.PublishedBy = userId;
item.PublishedUserName = userName;
_dbContext.News.Update(item);
await _dbContext.SaveChangesAsync();
return Ok(ApiResult.Success(null));
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(string id)
{
var item = await _dbContext.News.FindAsync(id);
if(item == null)
{
throw new System.Exception($"News Id {id} is not found");
}
_dbContext.News.Remove(item);
await _dbContext.SaveChangesAsync();
return Ok(ApiResult.Success(null));
}
}
}
| 33.751969 | 96 | 0.546483 |
391d2cf9d275c1adf7a44809f6d0704aa6600f81 | 1,858 | py | Python | mcpython/client/state/WorldListRenderer.py | mcpython4-coding/core | e4c4f59dab68c90e2028db3add2e5065116bf4a6 | [
"CC0-1.0",
"MIT"
] | 2 | 2019-11-02T05:26:11.000Z | 2019-11-03T08:52:18.000Z | mcpython/client/state/WorldListRenderer.py | mcpython4-coding/core | e4c4f59dab68c90e2028db3add2e5065116bf4a6 | [
"CC0-1.0",
"MIT"
] | 25 | 2019-11-02T05:24:29.000Z | 2022-02-09T14:09:08.000Z | mcpython/client/state/WorldListRenderer.py | mcpython4-coding/core | 8698efe93f5a25421bfa508d769d8fdc8e9ce24c | [
"CC0-1.0",
"MIT"
] | 5 | 2019-11-09T05:36:06.000Z | 2021-11-28T13:07:08.000Z | """
mcpython - a minecraft clone written in python licenced under the MIT-licence
(https://github.com/mcpython4-coding/core)
Contributors: uuk, xkcdjerry (inactive)
Based on the game of fogleman (https://github.com/fogleman/Minecraft), licenced under the MIT-licence
Original game "minecraft" by Mojang Studios (www.minecraft.net), licenced under the EULA
(https://account.mojang.com/documents/minecraft_eula)
Mod loader inspired by "Minecraft Forge" (https://github.com/MinecraftForge/MinecraftForge) and similar
This project is not official by mojang and does not relate to it.
"""
import pyglet
from mcpython import shared
from mcpython.util.opengl import draw_line_rectangle
from .AbstractStateRenderer import AbstractStateRenderer
class WorldListRenderer(AbstractStateRenderer):
def draw(self):
wx, wy = shared.window.get_size()
pyglet.gl.glClearColor(1.0, 1.0, 1.0, 1.0)
x, y = shared.window.mouse_position
self.assigned_state.scissor_group.set_state()
for i, (_, icon, labels, _) in enumerate(self.assigned_state.world_data):
icon.draw()
for label in labels:
label.draw()
if i == self.assigned_state.selected_world:
x, y = icon.position
draw_line_rectangle((x - 2, y - 2), (wx - 130, 54), (1, 1, 1))
px, py = icon.position
if 0 <= x - px <= wx and 0 <= y - py <= 50:
if 0 <= x - px <= 50:
self.assigned_state.selection_sprite.position = (
icon.position[0] + 25 - 16,
icon.position[1] + 25 - 16,
)
self.assigned_state.selection_sprite.draw()
self.assigned_state.scissor_group.unset_state()
draw_line_rectangle((45, 100), (wx - 90, wy - 160), (1, 1, 1))
| 42.227273 | 103 | 0.631862 |
0d8a122507d0306c418c2a6a2560e5c1619e6adf | 149 | rb | Ruby | spec/factories/addresses.rb | janicelaset/daycare_hub | a2b75601ba451105c7b49c466d5c84bcc991b4d4 | [
"MIT",
"Unlicense"
] | 2 | 2015-11-16T00:00:05.000Z | 2017-04-28T04:39:06.000Z | spec/factories/addresses.rb | janicelaset/daycare_hub | a2b75601ba451105c7b49c466d5c84bcc991b4d4 | [
"MIT",
"Unlicense"
] | null | null | null | spec/factories/addresses.rb | janicelaset/daycare_hub | a2b75601ba451105c7b49c466d5c84bcc991b4d4 | [
"MIT",
"Unlicense"
] | null | null | null | FactoryGirl.define do
factory :address do
street '1800 SW Farmington Rd'
city 'Aloha'
state 'OR'
zip '97007'
daycare
end
end
| 14.9 | 34 | 0.644295 |
f4d6fa442cdba485eb94300a68334d45c748bed1 | 487 | lua | Lua | examples/coclinet.lua | LuaDist-testing/lluv-ssl | 10d94d0769a0a06de6f5e0e9e64251a99f6272cf | [
"MIT"
] | 7 | 2015-02-26T14:32:35.000Z | 2020-05-01T13:58:37.000Z | examples/coclinet.lua | LuaDist-testing/lluv-ssl | 10d94d0769a0a06de6f5e0e9e64251a99f6272cf | [
"MIT"
] | 2 | 2015-07-17T03:10:14.000Z | 2015-07-17T12:11:18.000Z | examples/coclinet.lua | LuaDist-testing/lluv-ssl | 10d94d0769a0a06de6f5e0e9e64251a99f6272cf | [
"MIT"
] | 4 | 2015-03-12T08:47:07.000Z | 2020-03-04T03:55:42.000Z | local uv = require "lluv"
local ut = require "lluv.utils"
local ssl = require "lluv.ssl"
local socket = require "lluv.ssl.luasocket"
local config = require "./config"
local ctx = assert(ssl.context(config))
ut.corun(function()
while true do
local cli = socket.ssl(ctx)
local ok, err = cli:connect("127.0.0.1", 8881)
if not ok then
print("Connect fail:", err)
break
end
print("Recv:", cli:receive("*a"))
cli:close()
end
end)
uv.run()
| 21.173913 | 50 | 0.62423 |
cd5025f37eba7ec5b4a55f9f49529b1a6f694b6c | 5,945 | cs | C# | src/Backup/DbLinq/Util/IDataRecordExtensions.cs | RWooters/dblinq2007 | 97e1fce9260e1ee6198c01e4ddae6f393fef553c | [
"MIT"
] | null | null | null | src/Backup/DbLinq/Util/IDataRecordExtensions.cs | RWooters/dblinq2007 | 97e1fce9260e1ee6198c01e4ddae6f393fef553c | [
"MIT"
] | null | null | null | src/Backup/DbLinq/Util/IDataRecordExtensions.cs | RWooters/dblinq2007 | 97e1fce9260e1ee6198c01e4ddae6f393fef553c | [
"MIT"
] | 1 | 2018-09-30T23:46:57.000Z | 2018-09-30T23:46:57.000Z | #region MIT license
//
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#endregion
using System;
using System.Data;
namespace DbLinq.Util
{
#if !MONO_STRICT
public
#endif
static class IDataRecordExtensions
{
// please note that sometimes (depending on driver), GetValue() returns DBNull instead of null
// so at this level, we handle both
public static string GetAsString(this IDataRecord dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
object o = dataRecord.GetValue(index);
if (o == null) // this is not supposed to happen
return null;
return o.ToString();
}
public static bool GetAsBool(this IDataRecord dataRecord, int index)
{
object b = dataRecord.GetValue(index);
return TypeConvert.ToBoolean(b);
}
public static bool? GetAsNullableBool(this IDataRecord dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
return GetAsBool(dataRecord, index);
}
public static char GetAsChar(this IDataRecord dataRecord, int index)
{
object c = dataRecord.GetValue(index);
return TypeConvert.ToChar(c);
}
public static char? GetAsNullableChar(this IDataRecord dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
return GetAsChar(dataRecord, index);
}
public static U GetAsNumeric<U>(this IDataRecord dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return default(U);
return GetAsNumeric<U>(dataRecord.GetValue(index));
}
public static U? GetAsNullableNumeric<U>(this IDataRecord dataRecord, int index)
where U : struct
{
if (dataRecord.IsDBNull(index))
return null;
return GetAsNumeric<U>(dataRecord.GetValue(index));
}
private static U GetAsNumeric<U>(object o)
{
if (o == null || o is DBNull)
return default(U);
return TypeConvert.ToNumber<U>(o);
}
public static int GetAsEnum(this IDataRecord dataRecord, Type enumType, int index)
{
int enumAsInt = dataRecord.GetAsNumeric<int>(index);
return enumAsInt;
}
public static byte[] GetAsBytes(this IDataRecord dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return new byte[0];
object obj = dataRecord.GetValue(index);
if (obj == null)
return new byte[0]; //nullable blob?
byte[] bytes = obj as byte[];
if (bytes != null)
return bytes; //works for BLOB field
Console.WriteLine("GetBytes: received unexpected type:" + obj);
//return _rdr.GetInt32(index);
return new byte[0];
}
public static System.Data.Linq.Binary GetAsBinary(this IDataRecord dataRecord, int index)
{
byte[] bytes = GetAsBytes(dataRecord, index);
if (bytes.Length == 0)
return null;
return new System.Data.Linq.Binary(bytes);
}
public static object GetAsObject(this IDataRecord dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
object obj = dataRecord.GetValue(index);
return obj;
}
public static DateTime GetAsDateTime(this IDataRecord dataRecord, int index)
{
// Convert an InvalidCastException (thrown for example by Npgsql when an
// operation like "SELECT '2012-'::timestamp - NULL" that is perfectly
// legal on PostgreSQL returns a null instead of a DateTime) into the
// correct InvalidOperationException.
if (dataRecord.IsDBNull(index))
throw new InvalidOperationException("NULL found where DateTime expected");
return dataRecord.GetDateTime(index);
}
public static DateTime? GetAsNullableDateTime(this IDataRecord dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
return GetAsDateTime(dataRecord, index);
}
public static Guid GetAsGuid(this IDataRecord dataRecord, int index)
{
return dataRecord.GetGuid(index);
}
public static Guid? GetAsNullableGuid(this IDataRecord dataRecord, int index)
{
if (dataRecord.IsDBNull(index))
return null;
return GetAsGuid(dataRecord, index);
}
}
}
| 36.030303 | 102 | 0.61312 |
142353b4f8fbe6fd093a5733f334bb6daba286a4 | 1,582 | ts | TypeScript | src/server/Config.ts | nuggxyz/dotnugg-vscode | 3f051012fc199b06cbb019b11365585a58e43489 | [
"MIT"
] | null | null | null | src/server/Config.ts | nuggxyz/dotnugg-vscode | 3f051012fc199b06cbb019b11365585a58e43489 | [
"MIT"
] | null | null | null | src/server/Config.ts | nuggxyz/dotnugg-vscode | 3f051012fc199b06cbb019b11365585a58e43489 | [
"MIT"
] | null | null | null | import fs from 'fs';
import { dotnugg } from '@nuggxyz/dotnugg-sdk';
import { Collection } from '@nuggxyz/dotnugg-sdk/dist/builder/types/TransformTypes';
export class Config {
public static readonly EMPTY_CONFIG = { rules: {} };
private static ideRules: any;
private static fileConfig: any;
private static currentWatchFile: string;
public static collection: Collection;
public static get collectionFeatureKeys() {
return Object.keys(this.collection.features);
}
public static init(rootPath: string, ideRules: any) {
this.loadFileConfig(rootPath);
this.setIdeRules(ideRules);
}
public static setIdeRules(rules: any) {
this.ideRules = rules || {};
}
private static readFileConfig(filePath: string) {
if (fs.existsSync(filePath)) {
const parser = dotnugg.parser.parsePath(filePath);
this.collection = dotnugg.builder.transform.fromParser(parser).input.collection;
} else {
this.collection = undefined;
}
}
public static isRootPathSet(rootPath: string): boolean {
return typeof rootPath !== 'undefined' && rootPath !== null;
}
public static loadFileConfig(rootPath: string) {
if (this.isRootPathSet(rootPath)) {
const filePath = `${rootPath}/collection.nugg`;
const readConfig = this.readFileConfig.bind(this, filePath);
readConfig();
this.currentWatchFile = filePath;
} else {
this.fileConfig = Config.EMPTY_CONFIG;
}
}
}
| 29.849057 | 92 | 0.6378 |
972a03a77087896128d4a59905dc0fd46482923a | 464 | rb | Ruby | lib/patterns/collection.rb | caglarcakar/pattern | d683c4b8dbdf650f21793eaec00837e64718614c | [
"MIT"
] | 529 | 2017-04-12T19:55:07.000Z | 2022-03-28T01:34:39.000Z | lib/patterns/collection.rb | caglarcakar/pattern | d683c4b8dbdf650f21793eaec00837e64718614c | [
"MIT"
] | 17 | 2017-05-16T13:18:06.000Z | 2021-12-10T07:40:37.000Z | lib/patterns/collection.rb | caglarcakar/pattern | d683c4b8dbdf650f21793eaec00837e64718614c | [
"MIT"
] | 32 | 2017-12-26T13:26:07.000Z | 2022-03-25T04:33:44.000Z | module Patterns
class Collection
include Enumerable
def initialize(*args)
@options = args.extract_options!
@subject = args.first
end
def each
collection.each do |*args|
yield(*args)
end
end
class << self
alias from new
alias for new
end
private
attr_reader :options, :subject
def collection
raise NotImplementedError, "#collection not implemented"
end
end
end
| 15.466667 | 62 | 0.618534 |
ca19f658881b7cb49520fb3d3f718957531f5f5d | 684 | sql | SQL | paprika-db/mysql/create/paprika/ddl/tab/chunks.sql | thunder-/paprika | af262407ec9c195dbb5a7c205510e6ad2fb65f36 | [
"MIT"
] | null | null | null | paprika-db/mysql/create/paprika/ddl/tab/chunks.sql | thunder-/paprika | af262407ec9c195dbb5a7c205510e6ad2fb65f36 | [
"MIT"
] | null | null | null | paprika-db/mysql/create/paprika/ddl/tab/chunks.sql | thunder-/paprika | af262407ec9c195dbb5a7c205510e6ad2fb65f36 | [
"MIT"
] | null | null | null | CREATE TABLE chunks
(
id int(11) NOT NULL AUTO_INCREMENT primary key,
job_name varchar(255),
pcs_id int(11),
state varchar(50),
datasource varchar(255),
tablename varchar(255),
selector varchar(4000),
options varchar(4000),
payload varchar(4000),
message varchar(4000),
backtrace varchar(4000),
rle_id int(11),
rule varchar(50),
pattern varchar(4000),
hashcode varchar(255),
created_at datetime,
created_by varchar(45),
updated_at datetime,
updated_by varchar(45)
); | 31.090909 | 64 | 0.532164 |
a10c301c4c7d72d4051b3ec9372009c562c730cc | 514 | lua | Lua | averages/ma_tma.lua | eortigoza5/quadcodescript-library | 6cc36e6292d47d85a584f24b482db16929351a81 | [
"Apache-2.0"
] | 13 | 2021-06-23T12:04:56.000Z | 2022-03-18T12:33:20.000Z | averages/ma_tma.lua | eortigoza5/quadcodescript-library | 6cc36e6292d47d85a584f24b482db16929351a81 | [
"Apache-2.0"
] | 3 | 2021-06-14T08:45:04.000Z | 2022-01-18T07:38:19.000Z | averages/ma_tma.lua | eortigoza5/quadcodescript-library | 6cc36e6292d47d85a584f24b482db16929351a81 | [
"Apache-2.0"
] | 17 | 2021-06-09T21:21:43.000Z | 2022-03-27T13:30:43.000Z | instrument { name = "Triangular Moving Average", short_name = "TMA", overlay = true, icon="indicators:MA" }
period = input (10, "front.period", input.integer, 1)
source = input (1, "front.ind.source", input.string_selection, inputs.titles_overlay)
input_group {
"front.ind.dpo.generalline",
color = input { default = "#4BFFB5", type = input.color },
width = input { default = 1, type = input.line_width}
}
local sourceSeries = inputs [source]
plot (tma (sourceSeries, period), "TMA", color, width)
| 34.266667 | 107 | 0.690661 |
6684f996e2070367ccc0c2285b2e4aea467da08b | 1,407 | css | CSS | src/presentational/Landing/Landing.css | varnebla/codeval-frontend | f86316c6bade2508e487bfdfa8cb83f4ec9f9faa | [
"MIT"
] | null | null | null | src/presentational/Landing/Landing.css | varnebla/codeval-frontend | f86316c6bade2508e487bfdfa8cb83f4ec9f9faa | [
"MIT"
] | null | null | null | src/presentational/Landing/Landing.css | varnebla/codeval-frontend | f86316c6bade2508e487bfdfa8cb83f4ec9f9faa | [
"MIT"
] | null | null | null | .landing-navbar{
background-color:black;
}
.navbar-logo{
color: white !important;
}
.introduction-container{
top:0;
left:0;
position: fixed;
padding-top:55px;
height:100vh;
width:100vw;
}
.introduction-background{
height: 100%;
width: 100%;
background-color:white;
display: flex;
justify-content: center;
align-items: center;
}
.introduction-box{
width:50%;
height: 100%;
display:flex;
justify-content: center;
}
.box{
width: 500px;
height: 450px;
align-self: center;
background-image: url('../../assets/landing_pic.svg');
/* background-color: red; */
background-repeat: no-repeat;
margin: 5%;
}
.landing-video{
height: 100%;
background-image: url('../../assets/landing_video.gif');
background-repeat: no-repeat;
background-size: 100%;
margin: 16px 44px 0px 44px;
}
.text-block{
width:50%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.button-get-started{
margin: 30px 0;
height: 50px;
font-size:25px;
}
.button-get-started:active{
border:white ;
}
.codeval-explanation{
word-wrap: normal;
max-width: 400px;
text-align: center;
font-size: 18px;
}
.brand-title{
background-image: url('../../assets/logo-final-02.svg');
background-repeat: no-repeat;
background-size:100%;
height: 130px;
width: 350px;
}
.slogan{
font-weight: 700;
font-size:35px;
} | 17.810127 | 58 | 0.67022 |
239ba439788cf9c6ea58ec813b96ecdb2e4c1494 | 1,969 | js | JavaScript | server/middleware/tracing.js | NoeSamaille/inventory-management-ui-solution | 9cba419d8d3c53e4e48a94cb92e2a9715d9293e5 | [
"Apache-2.0"
] | 1 | 2022-01-22T20:28:39.000Z | 2022-01-22T20:28:39.000Z | server/middleware/tracing.js | NoeSamaille/inventory-management-ui-solution | 9cba419d8d3c53e4e48a94cb92e2a9715d9293e5 | [
"Apache-2.0"
] | 6 | 2020-11-04T03:51:11.000Z | 2021-03-10T05:22:56.000Z | server/middleware/tracing.js | NoeSamaille/inventory-management-ui-solution | 9cba419d8d3c53e4e48a94cb92e2a9715d9293e5 | [
"Apache-2.0"
] | 11 | 2019-11-19T22:53:12.000Z | 2021-03-13T12:21:14.000Z | function tracingMiddleWare (req, res, next) {
const tracer = opentracing.globalTracer();
// Extracting the tracing headers from the incoming http request
const wireCtx = tracer.extract(opentracing.FORMAT_HTTP_HEADERS, req.headers)
// Creating our span with context from incoming request
const span = tracer.startSpan(req.path, { childOf: wireCtx })
// Use the log api to capture a log
span.log({ event: 'request_received' })
// Use the setTag api to capture standard span tags for http traces
span.setTag(opentracing.Tags.HTTP_METHOD, req.method)
span.setTag(opentracing.Tags.SPAN_KIND, opentracing.Tags.SPAN_KIND_RPC_SERVER)
span.setTag(opentracing.Tags.HTTP_URL, req.path)
// include trace ID in headers so that we can debug slow requests we see in
// the browser by looking up the trace ID found in response headers
const responseHeaders = {}
tracer.inject(span, opentracing.FORMAT_HTTP_HEADERS, responseHeaders)
res.set(responseHeaders)
// add the span to the request object for any other handler to use the span
Object.assign(req, { span })
// finalize the span when the response is completed
const finishSpan = () => {
if (res.statusCode >= 500) {
// Force the span to be collected for http errors
span.setTag(opentracing.Tags.SAMPLING_PRIORITY, 1)
// If error then set the span to error
span.setTag(opentracing.Tags.ERROR, true)
// Response should have meaning info to futher troubleshooting
span.log({ event: 'error', message: res.statusMessage })
}
// Capture the status code
span.setTag(opentracing.Tags.HTTP_STATUS_CODE, res.statusCode)
span.log({ event: 'request_end' })
span.finish()
}
res.on('finish', finishSpan)
next()
}
function applyTracingMiddleware(app) {
app.use(tracingMiddleWare);
}
module.exports = applyTracingMiddleware; | 41.020833 | 82 | 0.690198 |
eb23edaacbb3559ec1cb3a17a942c791bfc39c2e | 507 | css | CSS | web/js/tagit/css/master.css | sjaanus/ifresco-0.3 | d1d2b29922afbe5a247f9720e19b2673936d630f | [
"Apache-2.0"
] | null | null | null | web/js/tagit/css/master.css | sjaanus/ifresco-0.3 | d1d2b29922afbe5a247f9720e19b2673936d630f | [
"Apache-2.0"
] | null | null | null | web/js/tagit/css/master.css | sjaanus/ifresco-0.3 | d1d2b29922afbe5a247f9720e19b2673936d630f | [
"Apache-2.0"
] | null | null | null | @charset "UTF-8";
/* base */
html {
font-size: 62.5%;
}
a {
text-decoration:underline;
}
p {
margin-bottom:10px;
line-height:18px;
}
/* end of base */
body, input, a {
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
color: #333;
font-size:12px;
}
#content {
width:600px;
margin:20px 0 20px 40px;
}
.myform {
padding:20px 0px;
}
.myform div.line {
clear:both;
min-height:50px;
margin-bottom:15px;
}
.myform label {
display:block;
font-weight:bold;
margin-bottom:5px;
}
| 12.675 | 65 | 0.65286 |
15f74b5b73b37fab108841e98849accc23189fb0 | 1,888 | rb | Ruby | app/models/legal_services/upload.rb | Crown-Commercial-Service/crown-marketplace-legacy | f32c7be36ef3f680749ac1003209c4a51e37674b | [
"MIT"
] | null | null | null | app/models/legal_services/upload.rb | Crown-Commercial-Service/crown-marketplace-legacy | f32c7be36ef3f680749ac1003209c4a51e37674b | [
"MIT"
] | 19 | 2021-05-21T10:24:29.000Z | 2022-03-31T15:02:24.000Z | app/models/legal_services/upload.rb | Crown-Commercial-Service/crown-marketplace-legacy | f32c7be36ef3f680749ac1003209c4a51e37674b | [
"MIT"
] | null | null | null | module LegalServices
class Upload < ApplicationRecord
def self.upload!(suppliers)
error = all_or_none(Supplier) do
Supplier.delete_all_with_dependents
suppliers.map do |supplier_data|
create_supplier!(supplier_data)
end
create!
end
raise error if error
end
def self.all_or_none(transaction_class)
error = nil
transaction_class.transaction do
yield
rescue ActiveRecord::RecordInvalid => e
error = e
raise ActiveRecord::Rollback
end
error
end
# rubocop:disable Metrics/AbcSize
def self.create_supplier!(data)
supplier = Supplier.create!(
id: data['supplier_id'],
name: data['name'],
email: data['email'],
phone_number: data['phone_number'],
sme: data['sme'],
address: data['address'],
website: data['website'],
duns: data['duns'],
rate_cards: data['rate_cards'],
lot_1_prospectus_link: data['lot_1_prospectus_link'],
lot_2_prospectus_link: data['lot_2_prospectus_link'],
lot_3_prospectus_link: data['lot_3_prospectus_link'],
lot_4_prospectus_link: data['lot_4_prospectus_link'],
)
lot_1_services = data.fetch('lot_1_services', {})
lot_1_services.each do |service|
supplier.regional_availabilities.create!(
region_code: service['region_code'],
service_code: service['service_code']
)
end
lots = data.fetch('lots', [])
lots.each do |lot|
lot_number = lot['lot_number']
services = lot.fetch('services', [])
services.each do |service|
supplier.service_offerings.create!(
lot_number: lot_number,
service_code: service
)
end
end
end
# rubocop:enable Metrics/AbcSize
end
end
| 26.971429 | 61 | 0.611758 |
91d489236e4f8355ed5e2f337e78ab57736948cf | 42,266 | html | HTML | es-AR/index.html | caidevOficial/Resume | db5604e02b16b8cac5405783e2e0557043a1bd1c | [
"MIT"
] | null | null | null | es-AR/index.html | caidevOficial/Resume | db5604e02b16b8cac5405783e2e0557043a1bd1c | [
"MIT"
] | null | null | null | es-AR/index.html | caidevOficial/Resume | db5604e02b16b8cac5405783e2e0557043a1bd1c | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="es-AR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta property="og:site_name" content="CV Facu Falcone" />
<meta property="og:title" content="Currículum" />
<meta property="og:image" content="https://caidevoficial.github.io/Curriculum/pm/pageImgs/preview.png" />
<link rel="image_src" href="https://caidevoficial.github.io/Curriculum/preview.png" />
<link rel="icon" type="image/x-icon" href="../media/icons/taiIcon.png" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/devicons/[email protected]/devicon.min.css">
<link rel="stylesheet" href="../css/style.css">
<link rel="stylesheet" href="../css/animation.css">
<script src="../js/mainScript.js" type="module" defer></script>
<script>
function openURL(url, width, height) {
open(url, '', `top=100,left=100,width=${width},height=${height}`);
}
</script>
<title>CV Facu Falcone</title>
</head>
<body>
<header>
<nav class="bounceInDown animated navbar navbar-expand-lg navbar-light bg-light d-flex justify-content-center ">
<!-- TOP RIGHT RIBBON: START COPYING HERE -->
<div class="github-fork-ribbon-wrapper right">
<div class="github-fork-ribbon">
<a href="#" target="_blank">En Construcción</a>
</div>
</div>
<button class="navbar-toggler green-back" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon green-back"></span>
</button>
<div class="green-back collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav green-back">
<a align="center" class="green nav-link active white-lt" href="https://github.com/caidevOficial/">Mi Github</a>
</div>
</div>
</nav>
<div id="myBar"></div>
<div class="container">
<div class="language animated bounceInUp">
<a href="../es-AR/index.html"><img src="../media/icons/flags/argentina.svg" alt="Español" width="30px" height="30px"></a>
<a href="../en-US/index.html"><img src="../media/icons/flags/united-states.svg" alt="English" width="30px" height="30px"></a>
</div>
</div>
</header>
<div class="container">
<div class="row">
<div class="col-md-4 p-2" style="border-radius: 10px" id="credential">
<div class="photoSection animated bounceInUp">
<section class="foto d-flex justify-content-center">
<img src="../media/pm/personal_image.png" height="200" alt="me" id="myPhoto" class="shadow">
</section>
<hr>
</div>
<div class="leftSide animated bounceInRight ">
<section class="about-me">
<div class="light-blue">
<h3><img src="../media/icons/personal/Personal_information.svg" alt="" width="30px"> Información Personal <br></h3>
</div>
<ul>
<li>
<h6 class="m-1 green">Amilcar Facundo Falcone</h6>
</li>
<li><img src="../media/icons/personal/loc.png" alt="Address" width="15px"> Berazategui, Buenos Aires.<br></li>
<li><img src="../media/icons/personal/mail.png" alt="eMail" width="15px"> [email protected] <br></li>
<li><img src="../media/icons/personal/calendar2.svg" alt="birthdate" width="15px"> 25-02-1990 <br></li>
<li><img src="../media/icons/personal/tool.png" alt="Github" width="15px"><a class="green" href="https://github.com/caidevOficial"> Mi Github</a> <br></li>
<li>
<a href="https://www.linkedin.com/in/facundo-falcone/"><img src="../media/icons/personal/linkedin.png" alt="Linkedin" width="75px"></a>
</li>
</ul>
<!-- <img src="media/icons/personal/phone.png" alt="Phone" width="15px"><br> -->
</section>
<hr>
<section class="natural-languajes">
<div class="light-blue">
<h3><img src="../media/icons/personal/Languages.svg" alt="" width="20px"> Idiomas <br></h3>
</div>
<ul>
<li>Español - Nativo.</li>
<li>Inglés - Avanzado - C1.</li>
<li>Chino - Básico (HSK1 Aprobado).</li>
<li>Japonés - Básico.</li>
</ul>
</section>
<hr>
<section class="skills">
<div class="light-blue">
<h3><img src="../media/icons/personal/skills.svg" alt="Skills" width="20px"> Skills <br></h3>
</div>
<article>
<p align="left">
<a href="https://www.python.org" target="_blank"> <img src="../media/icons/python/python-original.svg" alt="python" width="40" height="40" /> </a>
<a href="https://pandas.pydata.org/" target="_blank"> <img src="https://github.com/devicons/devicon/blob/master/icons/pandas/pandas-original-wordmark.svg?raw=true" alt="Pandas" width="40" height="40" /> </a>
<a href="https://numpy.org/" target="_blank"> <img src="../media/icons/numpy/numpy_logo.svg" alt="NumPy" width="40" height="40" /> </a>
<a href="https://matplotlib.org/" target="_blank"> <img src="https://camo.githubusercontent.com/9f609b65162567643c396ef42e9ccc2f755906847714389cbc1dcd707b234ebb/68747470733a2f2f6d6174706c6f746c69622e6f72672f5f7374617469632f6c6f676f325f636f6d707265737365642e7376673f7261773d74727565" alt="Matplotlib" width="40" height="40" /> </a>
<a href="https://www.djangoproject.com/" target="_blank"> <img src="../media/icons/django/django-original.svg" alt="django" width="40" height="40" /> </a>
<a href="https://www.java.com" target="_blank"> <img src="https://github.com/caidevOficial/Logos/blob/master/Lenguajes/java.png?raw=true" alt="java" width="40" height="40" /> </a>
<a href="https://www.w3schools.com/cs/" target="_blank"> <img src="../media/icons/csharp/csharp-original.svg" alt="csharp" width="40" height="40" /></a>
<a href="https://www.cprogramming.com/" target="_blank"> <img src="../media/icons/c/c-original.svg" alt="c" width="40" height="40" /> </a>
<a href="https://tomcat.apache.org/" target="_blank"> <img src="../media/icons/tomcat/tomcat-original.svg" alt="Tomcat" width="40" height="40" /> </a>
<a href="https://www.arduino.cc/" target="_blank"> <img src="https://cdn.worldvectorlogo.com/logos/arduino-1.svg" alt="arduino" width="40" height="40" /> </a>
</p>
</article>
<article>
<p align="left">
<a href="https://cloud.google.com/bigquery" target="_blank"> <img src="https://www.vectorlogo.zone/logos/google_bigquery/google_bigquery-icon.svg" alt="BigQuery" width="40" height="40" /> </a>
<a href="https://cloud.google.com/" target="_blank"> <img src="https://www.vectorlogo.zone/logos/google_cloud/google_cloud-icon.svg?raw=true" alt="GCP" width="40" height="40" /> </a>
<a href="https://azure.microsoft.com/en-in/" target="_blank"> <img src="https://camo.githubusercontent.com/6df31a460cb0c38f960e92812c8b6f8bce4c7f13170fb4782f0b31ab8e792ac2/68747470733a2f2f7777772e766563746f726c6f676f2e7a6f6e652f6c6f676f732f6d6963726f736f66745f617a7572652f6d6963726f736f66745f617a7572652d69636f6e2e737667" alt="Azure" width="40" height="40" /> </a>
<a href="https://www.sqlite.org/" target="_blank"> <img src="https://www.vectorlogo.zone/logos/sqlite/sqlite-icon.svg" alt="sqlite" width="40" height="40" /> </a>
<a href="https://mariadb.org/" target="_blank"> <img src="https://www.vectorlogo.zone/logos/mariadb/mariadb-icon.svg" alt="mariadb" width="40" height="40" /> </a>
<a href="https://www.mysql.com/" target="_blank"> <img src="../media/icons/mysql/mysql-original-wordmark.svg" alt="mysql" width="40" height="40" /> </a>
<a href="https://www.microsoft.com/es-es/sql-server/sql-server-downloads/" target="_blank"> <img src="../media/icons/mssql/microsoft-sql-server.svg" alt="mssql" width="40" height="40" /> </a>
<a href="https://www.apachefriends.org/es/index.html/" target="_blank"> <img src="https://github.com/devicons/devicon/raw/master/icons/php/php-original.svg?raw=true" alt="php" width="40" height="40" /> </a>
<a href="https://apache.org/" target="_blank"> <img src="../media/icons/apache/apache-original.svg" alt="Apache" width="40" height="40" /> </a>
<a href="https://www.postman.com/" target="_blank"> <img src="../media/icons/postman/getpostman-icon.svg" alt="Postman" width="40" height="40" /> </a>
</p>
</article>
<article>
<p align="left">
<a href="https://getbootstrap.com" target="_blank"> <img width="40" heigth="40" src="../media/icons/bootstrap/bootstrap-plain-wordmark.svg" alt="Bootstrap"></i>
</a>
<a href="https://www.w3schools.com/css/" target="_blank"> <img src="../media/icons/css3/css3-original.svg" alt="css3" width="40" height="40" /></a>
<a href="https://www.w3.org/html/" target="_blank"> <img src="../media/icons/html5/html5-original.svg" alt="html5" width="40" height="40" /> </a>
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank"> <img src="https://github.com/devicons/devicon/blob/master/icons/javascript/javascript-original.svg?raw=true" alt="javascript" width="35" height="39" /> </a>
</p>
</article>
<article>
<p align="left">
<a href="https://www.eclipse.org/" target="_blank"> <img src="https://github.com/caidevOficial/Logos/blob/master/Lenguajes/logo-eclipse.png?raw=true" alt="Eclipse" width="40" height="40" /> </a>
<a href="https://netbeans.apache.org/download/" target="_blank"> <img src="https://netbeans.apache.org/images/apache-netbeans.svg" alt="Netbeans" width="40" height="40" /> </a>
<a href="https://code.visualstudio.com/" target="_blank"> <img src="https://github.com/caidevOficial/Logos/blob/master/Lenguajes/visual-studio-code.svg?raw=true" alt="visualStudio" width="40" height="40" /> </a>
<a href="https://visualstudio.microsoft.com/es/vs/community/" target="_blank"> <img src="https://github.com/devicons/devicon/blob/master/icons/visualstudio/visualstudio-plain.svg?raw=true" alt="visualStudio" width="40" height="40" /> </a>
<a href="https://www.jetbrains.com/es-es/pycharm/" target="_blank"> <img src="../media/icons/pycharm/pycharm-original.svg" alt="PyCharm" width="40" height="40" /> </a>
<a href="https://git-scm.com/" target="_blank"> <img src="https://www.vectorlogo.zone/logos/git-scm/git-scm-icon.svg" alt="git" width="40" height="40" /> </a>
<a href="https://github.com/CaidevOficial" target="_blank"> <img src="https://github.com/devicons/devicon/blob/master/icons/github/github-original-wordmark.svg?raw=true" alt="git" width="40" height="40" /> </a>
<a href="https://slack.com/intl/es-la/" target="_blank"> <img src="../media/icons/slack/slack-original.svg" alt="Slack" width="40" height="40" /> </a>
<a href="https://trello.com/" target="_blank"> <img src="../media/icons/trello/trello-plain.svg" alt="Trello" width="40" height="40" /> </a>
</p>
</article>
<article>
<p align="left">
<a href="https://www.linux.org/" target="_blank"> <img src="../media/icons/linux/linux-original.svg" alt="linux" width="40" height="40" /> </a>
<a href="https://www.debian.org/" target="_blank"> <img src="https://www.debian.org/Pics/openlogo-50.png" alt="Debian" width="40" height="40" /> </a>
<a href="https://www.deepin.org/" target="_blank"> <img src="../media/pm/deepin-logo.svg" alt="Deepin" width="40" height="40" /> </a>
<a href="https://ubuntu.com/" target="_blank"> <img src="../media/icons/ubuntu/ubuntu-plain.svg" alt="Ubuntu" width="40" height="40" /> </a>
<a href="https://www.microsoft.com/es-ar/windows/" target="_blank"> <img src="https://github.com/caidevOficial/Logos/blob/master/Lenguajes/windows.svg?raw=true" alt="Windows" width="40" height="40" /> </a>
</p>
</article>
</section>
<hr>
<section class="git-content">
<div class="light-blue">
<h3><img src="../media/icons/personal/github.svg" alt="" width="15px"> Mi Github <br></h3>
</div>
<a href="https://github.com/caidevOficial/caidevOficial"> <img height="120" width="240" align="left" src="https://github-readme-stats-caidevposeidon.vercel.app/api/top-langs/?username=caidevOficial&layout=compact&theme=chartreuse-dark&langs_count=10&exclude_repo=Logos&hide=html,css,tsql" alt="caidevoficial"/>
</a>
<img height="120" width="240" align="center" src="https://github-readme-streak-stats.herokuapp.com/?user=caidevoficial&theme=chartreuse-dark" alt="caidevoficial" />
<a href="https://github.com/caidevOficial/caidevOficial"> <img height="120" width="240" src="https://github-readme-stats-caidevposeidon.vercel.app/api?username=caidevOficial&show_icons=true&theme=chartreuse-dark&count_private=true&show_owner=true&include_all_commits=true" />
</a>
</section>
<hr>
<section class="Jobs">
<div class="light-blue">
<h3><img src="../media/icons/personal/job-interview.svg" alt="" width="30px"> Experiencia Laboral</h3>
</div>
<article id="Accenture">
<p>
<div class="green">
<h5>Analytics Associate</h5>
</div>
<div class="coral">
Accenture | Enero 2021 - Presente
</div>
<ul>
<li>Python Dev.</li>
<li>Implementación de Backend con GCP.</li>
<li>Migración de queries a bigquery.</li>
<li>Creacion de pipelines.</li>
</ul>
</p>
</article>
<article id="UTN">
<p>
<div class="green">
<h5>Ayudante de Cátedra</h5>
</div>
<div class="coral">
UTN | Enero 2021 - Presente
</div>
<ul>
<li>Asistencia al profesor a cargo de la clase con contenido y correcciones.</li>
<li>Preparacion de temas para cada clase.</li>
</ul>
</p>
</article>
<article id="Autonomous">
<p>
<div class="green">
<h5>Mantenimiento y reparación de pc - Soporte técnico</h5>
</div>
<div class="coral">
Autónomo | Noviembre 2014 - Presente
</div>
<ul>
<li>Tareas de backup, formateo y particionado de discos, instalación de S.O. y softwares diversos.</li>
<li>Armado de pc a medida.</li>
<li>Atención al cliente via online o presencial.</li>
</ul>
</p>
</article>
<article id="HP">
<p>
<div class="green">
<h5>Merchant para Hewlett-Packard</h5>
</div>
<div class="coral">
Integra-GO | Febrero 2018 - Abril 2019
</div>
<ul>
<li>Fuí el nexo entre el cliente y la marca brindando soporte con capacitaciones a vendedores y material promocional.</li>
<li>Colocación de material PoP respetando lineamientos y negociación de nuevos espacios para la marca.</li>
</ul>
<div class="coral">
Premio recibido
</div>
<ul>
<li>Premio a la mejor exhibición en el canál hipermercados.</li>
</ul>
<img align="center" src="../media/pm/hypermarket_exhibition.jpg" alt="Coto" width="300px">
</p>
</article>
</section>
<hr>
</div>
</div>
<div class="col-md-8 p-3" style="border-radius: 10px">
<section class="gif">
<div class="light-blue">
<p align="center">
<a href="https://github.com/CaidevOficial">
<img height="100px" src="https://github-profile-trophy.vercel.app/?username=caidevoficial&theme=nord&column=7" alt="caidevoficial" />
</a>
</p>
</div>
</section>
<hr>
<div align='center' id="spinner"></div>
<div id="right">
<section class="info">
<div class="light-blue">
<h3><img src="../media/icons/personal/identity-card.svg" alt="" width="30px"> Sobre mí </h3>
</div>
<p>
Me considero una persona con facilidad para aprender nuevas habilidades, tecnologías y por eso me capacito constantemente en plataformas de e-learning. Actualmente soy estudiante de la Universidad Tecnológica Nacional (Tecnicatura universitaria en programación).
Estoy interesado en ingresar al área de sistemas en una empresa pujante con posibilidades de desarrollo.
</p>
</section>
<hr>
<section class="Study">
<div class="light-blue">
<h3><img src="../media/icons/personal/formation.svg" alt="" width="27px"> Formación Académica </h3>
</div>
<img src="https://raw.githubusercontent.com/caidevOficial/Logos/master/Instituciones/logo-utn_blanco.png" alt="" width="100px"> <br> Universidad Tecnológica Nacional (2020-2022)<br> Tecnicatura universitaria en programación. <br><br>
<img src="https://github.com/caidevOficial/Logos/blob/master/Instituciones/logo_unqui.png?raw=true" alt="" width="100px"> <br> Universidad Nacional de Quilmes (2014)<br> Tecnicatura en armado y reparación de pc. <br>
</section>
<hr>
<section class="Courses">
<div class="light-blue">
<h3><img src="../media/icons/personal/ribbon.svg" alt="" width="30px"> Cursos y Seminarios</h3>
</div>
<article class="ITBA">
<img src="https://github.com/caidevOficial/Logos/raw/master/Instituciones/logo_oficial_itba_ieee.png?raw=true" alt="ITBA Student Branch Logo" height="30"><br>
<ul>
<li>Análisis de Datos con Python - Octubre 2021 - <a href="javascript:openURL('../media/pm/certif/ITBA_Certif.png','500','500')" class="green">Enlace a Certificado</a><img src="../media/icons/new-gif-image.gif"alt="New" height="20"></li>
</ul>
</article>
<article class="PoloTic">
<img src="https://github.com/caidevOficial/Logos/raw/master/Instituciones/polo_logo_2020.png" alt="PoloTic Logo" height="30"><br>
<ul>
<li>Desarrollador web Fullstack Junior Java - Diciembre 2020 - <a href="javascript:openURL('../media/pm/certif/Java_FT_Certif.png','500','500')" class="green">Enlace a Certificado</a></li>
<li>Desarrollador web Fullstack Junior Python & Javascript - Noviembre 2020 - <a href="javascript:openURL('../media/pm/certif/Python_FT_Certif.png','500','500')" class="green">Enlace a Certificado</a></li>
<li>Metodologías Ágiles y SCRUM - Septiembre 2020 - <a href="javascript:openURL('../media/pm/certif/SCRUM_Certif.png','500','500')" class="green">Enlace a Certificado</a></li>
</ul>
</article>
<article class="Platzi">
<img src="https://raw.githubusercontent.com/caidevOficial/Logos/master/Instituciones/Platzi.png" alt="Platzy Logo" height="30"><br>
<ul>
<li>Curso Python Intermedio [17 hs] - Abril 2021 - <a class="green" href="javascript:openURL('https://platzi.com/p/facufalcone/curso/2255-course/diploma/detalle/','500','500')">Enlace a Certificado </a></li>
<li>Curso de SQL & MySQL [18 hs] - Marzo 2021 - <a class="green" href="javascript:openURL('https://platzi.com/p/facufalcone/curso/1272-course/diploma/detalle/','500','500')">Enlace a Certificado </a></li>
<li>Fundamentos de bases de datos [26 hs] - Marzo 2021 - <a class="green" href="javascript:openURL('https://platzi.com/p/facufalcone/curso/1566-bd/diploma/detalle/','500','500')">Enlace a Certificado </a></li>
<li>Curso de Pensamiento Computacional con Python [18 hs] - Marzo 2021 - <a class="green" href="javascript:openURL('https://platzi.com/p/facufalcone/curso/1764-course/diploma/detalle/','500','500')">Enlace a Certificado </a></li>
<li>Curso de POO y Algoritmos con Python [16 hs] - Marzo 2021 - <a class="green" href="javascript:openURL('https://platzi.com/p/facufalcone/curso/1775-poo-python/diploma/detalle/','500','500')">Enlace a Certificado </a></li>
<li>Curso de persistencia de dátos Java SE [11 hs] - Enero 2021 - <a class="green" href="javascript:openURL('https://platzi.com/p/facufalcone/curso/1760-java-persistencia/diploma/detalle/','500','500')">Enlace a Certificado</a></li>
<li>Java SE [PPP] - Diciembre 2020 - <a class="green" href="javascript:openURL('https://platzi.com/p/facufalcone/curso/1629-course/diploma/detalle/','500','500')">Enlace a Certificado</a></li>
<li>Curso de OOP - Diciembre 2020 - <a class="green" href="javascript:openURL('https://platzi.com/p/facufalcone/curso/1474-oop/diploma/detalle/','500','500')">Enlace a Certificado</a></li>
<li>Introducción a la terminal y línea de comandos - Diciembre 2020 - <a class="green" href="javascript:openURL('https://platzi.com/p/facufalcone/curso/1748-terminal/diploma/detalle/','500','500')">Enlace a Certificado</a></li>
<li>Introducción a Java SE - Diciembre 2020. - <a class="green" href="javascript:openURL('https://platzi.com/p/facufalcone/curso/1631-java-basico/diploma/detalle/','500','500')">Enlace a Certificado</a></li>
<li>Python básico - Diciembre 2020 - <a class="green" href="javascript:openURL('https://platzi.com/p/facufalcone/curso/1937-course/diploma/detalle/','500','500')">Enlace a Certificado</a></li>
</ul>
</article>
<article class="Udemy">
<img src="../media/logos/Logo_Udemy.svg" alt="Udemy Logo" height="30"><br>
<ul>
<li>Php Basico - Septiembre 2021 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-89d86480-3cfb-4097-aae8-8cd6f113522a/','500','500')">Enlace a Certificado</a></li>
<li>C# en Profundidad [8.5 hs] - Junio 2021 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-3a7a65ce-1eb6-4560-af95-2cde172ee073/','500','500')">Enlace a Certificado</a></li>
<li>Certificación C# y Python [7 hs] - Junio 2021 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-3f481854-e619-4aaf-b282-f4bcc7773dd1/','500','500')">Enlace a Certificado</a></li>
<li>Programación Básica C# .NET - Mayo 2021 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-d9731ef8-ea09-4f63-b5e5-c1cdde9e356c/','500','500')">Enlace a Certificado</a></li>
<li>Programación Java Avanzado - Octubre 2020 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-55be9a8e-deef-4255-971b-a4411254c7ef/','500','500')">Enlace a Certificado</a></li>
<li>Java Avanzado - Octubre 2020 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-73f68372-b7a9-4873-86f0-86b27b48e645/','500','500')">Enlace a Certificado</a></li>
<li>Certificación Java - Octubre 2020 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-2cf776e7-8435-44e9-900a-dcfa15a19a0a/','500','500')">Enlace a Certificado</a></li>
<li>Programación Completa con C [22 hs] - Agosto 2020 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-7cb7da20-eb81-4d5c-9412-11b1f6778bdf/','500','500')">Enlace a Certificado</a></li>
<li>Estructura de dátos con C - Agosto 2020 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-0133f4cb-2946-456d-aec5-9519c8a26d73/','500','500')">Enlace a Certificado</a></li>
<li>Programación en C principiante [33.5 hs] - Agosto 2020 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-59002d8e-ddd1-4ade-8c35-69a890f853e1/','500','500')">Enlace a Certificado</a></li>
<li>Python - Marzo 2020 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-acc8dc70-8549-4023-891a-c7c7a8cdde82/','500','500')">Enlace a Certificado</a></li>
<li>Introducción al Backend con Php - Marzo 2020 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-c65cb843-334d-4ab1-a646-190d590aef2d/','500','500')">Enlace a Certificado</a></li>
<li>Introducción a Git y Github - Febrero 2020 - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-d4ad791e-4cfd-4bfe-80e3-abc819d68cfa/','500','500')">Enlace a Certificado</a></li>
<li>Python 3 [9 hs] - Febrero 2020. - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-fd14afac-cc3e-4490-a353-6cb094a531dc/','500','500')">Enlace a Certificado</a></li>
<li>Power BI, Máxima Orientación - Febrero 2020. - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-e9ec71fd-d634-4dcb-b2c7-ba650a33f90a/','500','500')">Enlace a Certificado</a></li>
<li>Introducción a la programación con Javascript - Febrero 2020. - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-9cfbfaa5-56f7-4651-8db1-2d393dc64d06/','500','500')">Enlace a Certificado</a></li>
<li>Redes CCDA - Noviembre 2019. - <a class="green" href="javascript:openURL('https://www.udemy.com/certificate/UC-C8LUJV60/','500','500')">Enlace a Certificado</a></li>
</ul>
</article>
<article class="SoloLearn">
<img src="../media/logos/Logo_SoloLearn.svg" alt="SoloLearn Logo" height="30"><br>
<ul>
<li>Javascript Course - Octubre 2021 - <a class="green" href="javascript:openURL('https://www.sololearn.com/certificates/course/en/7481559/1024/landscape/png','500','500')">Enlace a Certificado </a><img src="../media/icons/new-gif-image.gif"alt="New" height="20"></li>
<li>PHP Course - Septiembre 2021 - <a class="green" href="javascript:openURL('https://www.sololearn.com/Certificate/1059-7481559/jpg','500','500')">Enlace a Certificado</a></li>
<li>C# - Septiembre 2021 - <a class="green" href="javascript:openURL('https://www.sololearn.com/certificates/course/en/7481559/1080/landscape/png','500','500')">Enlace a Certificado</a></li>
<li>Python Intermedio - Septiembre 2021 - <a class="green" href="javascript:openURL('https://www.sololearn.com/certificates/course/en/7481559/1158/landscape/png','500','500')">Enlace a Certificado</a></li>
<li>Python Core - Septiembre 2021 - <a class="green" href="javascript:openURL('https://www.sololearn.com/certificates/course/en/7481559/1073/landscape/png','500','500')">Enlace a Certificado</a></li>
<li>SQL - Septiembre 2021 - <a class="green" href="javascript:openURL('https://www.sololearn.com/certificates/course/en/7481559/1060/landscape/png','500','500')">Enlace a Certificado</a></li>
</ul>
</article>
<article class="LinkedIn">
<img src="../media/icons/linkedin/linkedin.svg" alt="LinkedIn Logo" height="30"><br>
<ul>
<li>SCRUM - Agosto 2020 - <a class="green" href="javascript:openURL('../media/pm/certif/SCRUM_Certif_Linked.png','500','500')">Enlace a Certificado</a></li>
</ul>
</article>
<article class="Codigo_Facilito">
<img src="https://codigofacilito.com/assets/logo-cbf2a784ebee5d642aa7b8182df3e388d4feba0a23577eed1d2747fa05861f73.png" alt="Codigo_Facilito Logo" height="30"><br>
<ul>
<li>Curso Profesional GIT - Junio 2020 - <a class="green" href="javascript:openURL('./media/pm/certif/Git_Certif_CF.png','500','500')">Enlace a Certificado</a></li>
</ul>
</article>
<article class="Eduonix">
<img src="../media/logos/Logo_Eduonix.png" alt="Eduonix Logo" height="45"><br>
<ul>
<li>Git Básico - Agosto 2020 - <a class="green" href="javascript:openURL('https://www.eduonix.com/certificate/9993d6ee1c','500','500')">Enlace a Certificado</a></li>
</ul>
</article>
<article class="Skillsoft_Percipio">
<img src="../media/logos/Logo_Skillsoft_Percipio.svg" alt="Skillsoft Logo" height="30"><br>
<ul>
<li>Java SE 11: <strong>Objectos & Clases</strong> - Octubre 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/b9b9d65e-3474-4c55-b0f7-88b5d627412b','500','500')">Enlace a Certificado</a></li>
<li>Tipos de datos complejos en Python: <strong>Shallow & Deep Copies en Python</strong> - Octubre 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/2c135447-0854-45b0-a91e-5e2a499ef0e7','500','500')">Enlace a Certificado</a></li>
<li>Funciones en Python: <strong>Comprensión profunda de las funciones de Python</strong> - Octubre 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/dbf36d7e-f4fc-4500-adff-896c850fe283','500','500')">Enlace a Certificado</a></li>
<li>Funciones en Python: <strong>Características avanzadas de funciones de Python</strong> - Octubre 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/9933e085-e950-43a5-b734-2cb4d4cc338b','500','500')">Enlace a Certificado</a></li>
<li>Funciones en Python: <strong>Introducción</strong> - Octubre 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/d7b13f38-1de7-479c-990d-b4272641b0df','500','500')">Enlace a Certificado</a></li>
<li>Declaraciones condicionales y bucles: <strong>While</strong> - Julio 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/e04a0137-3126-43c3-b7b6-2b30b45bdf8c','500','500')">Enlace a Certificado</a></li>
<li>Tipos de datos complejos en Python: <strong>Dictionarios & Sets</strong> - Mayo 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/fb0b303b-ebc9-42cd-bd36-0f0b20239cb8','500','500')">Enlace a Certificado</a></li>
<li>Tipos de datos complejos en Python: <strong>Listas & Tuplas</strong> - Abril 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/856c0753-bb75-44f8-ad82-6944a9668964','500','500')">Enlace a Certificado</a></li>
<li>Clases & Herencia en Python: <strong>Introducción</strong> - Abril 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/76631bd7-f8ae-4876-ab57-00804a14f13d#gs.bc8tmb','500','500')">Enlace a Certificado</a></li>
<li>Declaraciones condicionales y bucles <strong>For</strong> - April 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/9c9fc67c-164f-4c82-ae39-4bc10f01e3b5','500','500')">Enlace a Certificado</a></li>
<li>Declaraciones condicionales y bucles: <strong>Avanzado</strong> - Marzo 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/e3f0c13d-9f7c-44e4-acb2-68ba978b2adf','500','500')">Enlace a Certificado</a></li>
<li>Declaraciones condicionales y bucles - Marzo 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/4e6f1f77-a87d-4b48-99d7-003be4371e97','500','500')">Enlace a Certificado</a></li>
<li>Getting Started with Python: <strong>Introducción</strong> - Marzo 2021 - <a class="green" href="javascript:openURL('https://skillsoft.digitalbadges.skillsoft.com/07ecf20b-2aad-4f0b-87bd-ef2d7828d584','500','500')">Enlace a Certificado</a></li>
</ul>
</article>
<article class="Movistar">
<img src="https://www.fundaciontelefonica.com.ar/wp-content/uploads/2020/08/Logo-FTM-Arg.png" alt="Movistar Logo" height="30"><br>
<ul>
<li>Java SE [40hs] - Diciembre 2020 - <a class="green" href="javascript:openURL('../media/pm/certif/FTM_Java_Certif.png','500','500')">Enlace a Certificado</a></li>
<li>Javascript [40hs] - Diciembre 2020 - <a class="green" href="javascript:openURL('../media/pm/certif/FTM_JS_Certif.png','500','500')">Enlace a Certificado</a></li>
</ul>
</article>
<article class="CUV">
<img src="https://github.com/caidevOficial/Logos/raw/master/Instituciones/logo-cuv.png" alt="CUV Logo" height="30"><br>
<ul>
<li>Java SE [42hs] - Noviembre 2020 - <a class="green" href="javascript:openURL('../media/pm/certif/CUV_certif.png','500','500')">Enlace a Certificado</a></li>
</ul>
</article>
<article class="TodoCode">
<img src="../media/logos/Logo_TodoCode.png" alt="TodoCode Logo" height="30"><br>
<ul>
<li>Introducción a bases de datos relacionales [MySQL] - Septiembre 2021 - <a class="green" href="javascript:openURL('../media/pm/certif/todoCode_sql_certif.png','500','500')">Enlace a Certificado</a></li>
<li>Algoritmos de programación - Febrero 2021 - <a class="green" href="javascript:openURL('../media/pm/certif/todoCode_certif.png','500','500')">Enlace a Certificado</a></li>
</ul>
</article>
<hr>
</section>
<section class="linkedinFrame">
<iframe src="https://www.linkedin.com/embed/feed/update/urn:li:share:6860761026942533632" height="718" width="504" frameborder="0" allowfullscreen="" title="Publicación integrada"></iframe>
</section>
</div>
</div>
</div>
</div>
<footer>
<div class="footer">
<div class="footer-inner animated bounceInDown">
<div class="container">
<div class="row">
<div class="span12"> © 2021 <a class="green" href="# "> Facu Falcone - CaidevOficial </a>. </div>
</div>
<!-- /row -->
</div>
<!-- /container -->
</div>
<!-- /footer-inner -->
</div>
</footer>
<!-- /footer -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js " integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin=" anonymous ">
</script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js " integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj " crossorigin="anonymous "></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js " integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx " crossorigin="anonymous "></script>
</body>
</html> | 93.302428 | 396 | 0.541262 |
a007950e3f9817feb4cdc18cd5e8e5151668de55 | 1,370 | ts | TypeScript | windows-admin-center-developer-tools/src/app/hello/tree-example/testData.ts | t-literr/sdk-copy | b67434efde81bf3451ba5501794aab5eedf85648 | [
"MIT"
] | null | null | null | windows-admin-center-developer-tools/src/app/hello/tree-example/testData.ts | t-literr/sdk-copy | b67434efde81bf3451ba5501794aab5eedf85648 | [
"MIT"
] | null | null | null | windows-admin-center-developer-tools/src/app/hello/tree-example/testData.ts | t-literr/sdk-copy | b67434efde81bf3451ba5501794aab5eedf85648 | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
import { TreeNodeDataItem } from '@microsoft/windows-admin-center-sdk/angular';
/* tslint:disable */
export var TestData = <TreeNodeDataItem>{
data: {
label: 'API Examples',
type: 'folder',
expanded: true,
data: 'WMI',
isLeaf: false
},
children: [
{
data: {
label: 'WMI',
type: '',
expanded: true,
data: 'WMI',
isLeaf: true
}
},
{
data: {
label: 'PowerShell',
type: '',
expanded: true,
data: 'WMI',
isLeaf: true
}
},
{
data: {
label: 'Tree View Code',
type: '',
expanded: true,
data: 'TreeCode',
isLeaf: true
}
},
{
data: {
label: 'User Profile',
type: '',
expanded: true,
data: 'UserProfile',
isLeaf: true
}
},
{
data: {
label: 'Notifications',
type: '',
expanded: true,
data: 'Notifications',
isLeaf: true
}
},
{
data: {
label: 'Gateway Extensions',
type: '',
expanded: true,
data: 'DLL',
isLeaf: true
}
}
]
};
| 19.027778 | 80 | 0.431387 |
af7f95cd4be4e44e03d89a35b207c4d918a8d81d | 1,076 | py | Python | 27_36_DAYS_OF_TYPE_2020.py | eduairet/eat36daysOfType2020 | 89b35c5be102ea3afb4e19daccffe39a8c24e816 | [
"CC0-1.0"
] | 1 | 2020-07-29T22:33:39.000Z | 2020-07-29T22:33:39.000Z | 27_36_DAYS_OF_TYPE_2020.py | eduairet/eat36daysOfType2020 | 89b35c5be102ea3afb4e19daccffe39a8c24e816 | [
"CC0-1.0"
] | null | null | null | 27_36_DAYS_OF_TYPE_2020.py | eduairet/eat36daysOfType2020 | 89b35c5be102ea3afb4e19daccffe39a8c24e816 | [
"CC0-1.0"
] | null | null | null | side = 1080
thickness = side*0.4
frames = 84
def skPts():
points = []
for i in range(360):
x = cos(radians(i))
y = sin(radians(i))
points.append((x, y))
return points
def shape(step, var):
speed = var/step
fill(1, 1, 1, 0.05)
stroke(None)
shape = BezierPath()
shape.oval(0 - (thickness/2), 0 - (thickness/2), thickness, thickness)
with savedState():
scale(0.8, 1, (side*0.5, side*0.5))
translate(side*0.2 + (thickness/4), side*0.2 + (thickness/4))
rotate(2 * pi + speed, center=(side*0.2, side*0.2))
drawPath(shape)
points = skPts()
print(points)
for i in range(int(-frames/2), int(frames/2)):
if i != 0:
newPage(side, side)
fill(0)
rect(0, 0, side, side)
for j in range(0, 360, 12):
with savedState():
translate(
points[j][0],
points[j][1]
)
if j != 0:
shape(i, j)
saveImage('~/Desktop/27_36_DAYS_OF_TYPE_2020.mp4') | 26.243902 | 74 | 0.501859 |
2fc423f893bd3252b0386c8c3d77fadc7763c6cf | 175 | py | Python | positive.py | sreeja808/area | d9356edae588cbbe1723ebb50206718bd5506e1a | [
"MIT"
] | null | null | null | positive.py | sreeja808/area | d9356edae588cbbe1723ebb50206718bd5506e1a | [
"MIT"
] | null | null | null | positive.py | sreeja808/area | d9356edae588cbbe1723ebb50206718bd5506e1a | [
"MIT"
] | 1 | 2021-05-26T03:50:29.000Z | 2021-05-26T03:50:29.000Z | list1 = [12,3,5,-5,-6,-1]
for i in list1:
if i >= 0:
print (i)
list2 = [12,4,-95,3]
for num in list2:
if num >= 0:
print (" [ ",num," ] ")
| 14.583333 | 31 | 0.405714 |
2ca90626c2839ad729800f30daddb71e9c9d17de | 699 | cpp | C++ | Math/PillaiFunction.cpp | igortakeo/Algorithms | 6608132e442df7b0fb295aa63f287fa65a941939 | [
"MIT"
] | null | null | null | Math/PillaiFunction.cpp | igortakeo/Algorithms | 6608132e442df7b0fb295aa63f287fa65a941939 | [
"MIT"
] | null | null | null | Math/PillaiFunction.cpp | igortakeo/Algorithms | 6608132e442df7b0fb295aa63f287fa65a941939 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define pb push_back
using namespace std;
// Pillai's Arithmetical Function search result to for(i = 1 until n) sum += gcd(i, n)
vector<int> Divisors(int n){
vector<int>v;
for(int i=1; i*i <= n; i++){
if(n%i == 0){
v.pb(i);
if(i != (n/i))v.pb(n/i);
}
}
return v;
}
double phi(int n){
double totient = n;
for(int i=2; i*i<=n; i++){
if(n%i == 0){
while(n%i == 0) n/=i;
totient *= (1.0 -(1.0/(double)i));
}
}
if(n>1) totient *= (1.0 -(1.0/(double)n));
return totient;
}
int main(){
int n, ans = 0;
cin >> n;
vector<int> d = Divisors(n);
for(auto a : d){
ans += a*phi(n/a);
}
cout << ans << endl;
return 0;
}
| 14.265306 | 87 | 0.515021 |
08afdfe58a6af2609a42d54a3926051542406ee9 | 4,747 | css | CSS | samples/htmlx/htmlx.css | AlecHaring/sciter-js-sdk | 6cedc57ff09404ad17e1899abc06f843a4677b69 | [
"BSD-3-Clause"
] | 1,688 | 2020-10-10T06:08:27.000Z | 2022-03-31T09:57:58.000Z | samples/htmlx/htmlx.css | AlecHaring/sciter-js-sdk | 6cedc57ff09404ad17e1899abc06f843a4677b69 | [
"BSD-3-Clause"
] | 156 | 2020-10-16T05:50:01.000Z | 2022-03-31T13:26:18.000Z | samples/htmlx/htmlx.css | AlecHaring/sciter-js-sdk | 6cedc57ff09404ad17e1899abc06f843a4677b69 | [
"BSD-3-Clause"
] | 111 | 2020-10-12T00:37:54.000Z | 2022-03-30T07:56:33.000Z |
anchor { prototype: HTMLAnchorElement url(htmlx.js); }
area { prototype: HTMLAreaElement url(htmlx.js); }
audio { prototype: HTMLAudioElement url(htmlx.js); }
base { prototype: HTMLBaseElement url(htmlx.js); }
body { prototype: HTMLBodyElement url(htmlx.js); }
br { prototype: HTMLBRElement url(htmlx.js); }
button { prototype: HTMLButtonElement url(htmlx.js); }
canvas { prototype: HTMLCanvasElement url(htmlx.js); }
content { prototype: HTMLContentElement url(htmlx.js); }
data { prototype: HTMLDataElement url(htmlx.js); }
datalist { prototype: HTMLDataListElement url(htmlx.js); }
details { prototype: HTMLDetailsElement url(htmlx.js); }
dialog { prototype: HTMLDialogElement url(htmlx.js); }
div { prototype: HTMLDivElement url(htmlx.js); }
dlist { prototype: HTMLDListElement url(htmlx.js); }
embed { prototype: HTMLEmbedElement url(htmlx.js); }
fieldset { prototype: HTMLFieldSetElement url(htmlx.js); }
font { prototype: HTMLFontElement url(htmlx.js); }
form { prototype: HTMLFormElement url(htmlx.js); }
frameset { prototype: HTMLFrameSetElement url(htmlx.js); }
head { prototype: HTMLHeadElement url(htmlx.js); }
h1 { prototype: HTMLHeadingElement url(htmlx.js); }
h2 { prototype: HTMLHeadingElement url(htmlx.js); }
h3 { prototype: HTMLHeadingElement url(htmlx.js); }
h4 { prototype: HTMLHeadingElement url(htmlx.js); }
h5 { prototype: HTMLHeadingElement url(htmlx.js); }
h6 { prototype: HTMLHeadingElement url(htmlx.js); }
hr { prototype: HTMLHRElement url(htmlx.js); }
html { prototype: HTMLHtmlElement url(htmlx.js); }
iframe { prototype: HTMLIFrameElement url(htmlx.js); }
image { prototype: HTMLImageElement url(htmlx.js); }
input { prototype: HTMLInputElement url(htmlx.js); }
keygen { prototype: HTMLKeygenElement url(htmlx.js); }
label { prototype: HTMLLabelElement url(htmlx.js); }
legend { prototype: HTMLLegendElement url(htmlx.js); }
li { prototype: HTMLLIElement url(htmlx.js); }
link { prototype: HTMLLinkElement url(htmlx.js); }
map { prototype: HTMLMapElement url(htmlx.js); }
marquee { prototype: HTMLMarqueeElement url(htmlx.js); }
media { prototype: HTMLMediaElement url(htmlx.js); }
menu { prototype: HTMLMenuElement url(htmlx.js); }
meta { prototype: HTMLMetaElement url(htmlx.js); }
meter { prototype: HTMLMeterElement url(htmlx.js); }
mod { prototype: HTMLModElement url(htmlx.js); }
object { prototype: HTMLObjectElement url(htmlx.js); }
olist { prototype: HTMLOListElement url(htmlx.js); }
optgroup { prototype: HTMLOptGroupElement url(htmlx.js); }
option { prototype: HTMLOptionElement url(htmlx.js); }
output { prototype: HTMLOutputElement url(htmlx.js); }
p { prototype: HTMLParagraphElement url(htmlx.js); }
param { prototype: HTMLParamElement url(htmlx.js); }
picture { prototype: HTMLPictureElement url(htmlx.js); }
pre { prototype: HTMLPreElement url(htmlx.js); }
progress { prototype: HTMLProgressElement url(htmlx.js); }
quote { prototype: HTMLQuoteElement url(htmlx.js); }
script { prototype: HTMLScriptElement url(htmlx.js); }
select { prototype: HTMLSelectElement url(htmlx.js); }
shadow { prototype: HTMLShadowElement url(htmlx.js); }
slot { prototype: HTMLSlotElement url(htmlx.js); }
source { prototype: HTMLSourceElement url(htmlx.js); }
span { prototype: HTMLSpanElement url(htmlx.js); }
style { prototype: HTMLStyleElement url(htmlx.js); }
caption { prototype: HTMLTableCaptionElement url(htmlx.js); }
td { prototype: HTMLTableCellElement url(htmlx.js); }
th { prototype: HTMLTableCellElement url(htmlx.js); }
col { prototype: HTMLTableColElement url(htmlx.js); }
table { prototype: HTMLTableElement url(htmlx.js); }
tr { prototype: HTMLTableRowElement url(htmlx.js); }
tbody { prototype: HTMLTableSectionElement url(htmlx.js); }
thead { prototype: HTMLTableSectionElement url(htmlx.js); }
tfoot { prototype: HTMLTableSectionElement url(htmlx.js); }
template { prototype: HTMLTemplateElement url(htmlx.js); }
textarea { prototype: HTMLTextAreaElement url(htmlx.js); }
time { prototype: HTMLTimeElement url(htmlx.js); }
title { prototype: HTMLTitleElement url(htmlx.js); }
track { prototype: HTMLTrackElement url(htmlx.js); }
ulist { prototype: HTMLUListElement url(htmlx.js); }
unknown { prototype: HTMLUnknownElement url(htmlx.js); }
video { prototype: HTMLVideoElement url(htmlx.js); }
| 57.192771 | 65 | 0.67727 |
75e4ce731ce3dc1f49c359c7b7397b172f40b8ef | 181 | css | CSS | Timeline/webclient/static/css/AddHover.css | Lapeth/timeline | a85ca9a2e451700ff489bf5fc738b8070bf38041 | [
"Apache-2.0"
] | null | null | null | Timeline/webclient/static/css/AddHover.css | Lapeth/timeline | a85ca9a2e451700ff489bf5fc738b8070bf38041 | [
"Apache-2.0"
] | null | null | null | Timeline/webclient/static/css/AddHover.css | Lapeth/timeline | a85ca9a2e451700ff489bf5fc738b8070bf38041 | [
"Apache-2.0"
] | null | null | null | .AddHover {
width: 24px;
height: 30px;
}
.AddHover.above {
background-image: url('../img/add-above.png');
}
.AddHover.below {
background-image: url('../img/add-below.png');
}
| 13.923077 | 47 | 0.646409 |
9411451c877b8f221d81e1cccfa874db1cd5d538 | 1,625 | swift | Swift | iOS-Weather/Extension/String+Extension.swift | mdSanada/iOS-Weather | 8d9e30a0bb620b28abd57bc69dcda9e1e60f1368 | [
"MIT"
] | null | null | null | iOS-Weather/Extension/String+Extension.swift | mdSanada/iOS-Weather | 8d9e30a0bb620b28abd57bc69dcda9e1e60f1368 | [
"MIT"
] | null | null | null | iOS-Weather/Extension/String+Extension.swift | mdSanada/iOS-Weather | 8d9e30a0bb620b28abd57bc69dcda9e1e60f1368 | [
"MIT"
] | null | null | null | //
// String+Extension.swift
// iOS-Weather
//
// Created by Matheus D Sanada on 05/02/21.
//
import UIKit
extension String {
func getIcon() -> UIImage {
let str: String = self
switch str {
case "01d":
return UIImage(systemName: "sun.max")!
case "02d":
return UIImage(systemName: "cloud.sun")!
case "03d":
return UIImage(systemName: "cloud")!
case "04d":
return UIImage(systemName: "cloud.fill")!
case "09d":
return UIImage(systemName: "cloud.rain")!
case "10d":
return UIImage(systemName: "cloud.sun.rain")!
case "11d":
return UIImage(systemName: "cloud.bolt")!
case "13d":
return UIImage(systemName: "snow")!
case "50d":
return UIImage(systemName: "cloud.fog")!
case "01n":
return UIImage(systemName: "moon")!
case "02n":
return UIImage(systemName: "cloud.moon")!
case "03n":
return UIImage(systemName: "cloud")!
case "04n":
return UIImage(systemName: "cloud.fill")!
case "09n":
return UIImage(systemName: "cloud.rain")!
case "10n":
return UIImage(systemName: "cloud.moon.rain")!
case "11n":
return UIImage(systemName: "cloud.bolt")!
case "13n":
return UIImage(systemName: "cloud.fog")!
case "50n":
return UIImage(systemName: "snow")!
default:
return UIImage(systemName: "exclamationmark.triangle")!
}
}
}
| 29.545455 | 67 | 0.531077 |
b7979d4151b9fc7fe8cc8bc8d2db246cdb4860fc | 2,018 | hh | C++ | include/Apertures/StandardAperturePolygon.hh | aaronbamberger/gerber_rs274x_parser | d2bbd6c66d322ab47715771642255f8302521300 | [
"BSD-2-Clause"
] | 6 | 2016-09-28T18:26:42.000Z | 2021-04-10T13:19:05.000Z | include/Apertures/StandardAperturePolygon.hh | aaronbamberger/gerber_rs274x_parser | d2bbd6c66d322ab47715771642255f8302521300 | [
"BSD-2-Clause"
] | 1 | 2021-02-09T00:24:04.000Z | 2021-02-27T22:08:05.000Z | include/Apertures/StandardAperturePolygon.hh | aaronbamberger/gerber_rs274x_parser | d2bbd6c66d322ab47715771642255f8302521300 | [
"BSD-2-Clause"
] | 5 | 2017-09-14T09:48:17.000Z | 2021-07-19T07:58:34.000Z | /*
* Copyright 2021 Aaron Bamberger
* Licensed under BSD 2-clause license
* See LICENSE file at root of source tree,
* or https://opensource.org/licenses/BSD-2-Clause
*/
#ifndef _STANDARD_APERTURE_POLYGON_H
#define _STANDARD_APERTURE_POLYGON_H
#include "Apertures/StandardAperture.hh"
#include "GlobalDefs.hh"
#include "SemanticIssueList.hh"
#include "location.hh"
#include <iostream>
#include <memory>
class StandardAperturePolygon : public StandardAperture {
public:
StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle, double hole_diameter);
StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle);
StandardAperturePolygon(double diameter, double num_vertices);
StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle, double hole_diameter,
yy::location diameter_location, yy::location num_vertices_location, yy::location rotation_angle_location,
yy::location hole_diameter_location, yy::location location);
StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle,
yy::location diameter_location, yy::location num_vertices_location, yy::location rotation_angle_location,
yy::location location);
StandardAperturePolygon(double diameter, double num_vertices,
yy::location diameter_location, yy::location num_vertices_location, yy::location location);
virtual ~StandardAperturePolygon();
private:
Gerber::SemanticValidity do_check_semantic_validity(SemanticIssueList& issue_list);
std::ostream& do_print(std::ostream& os) const;
std::shared_ptr<StandardAperture> do_clone();
double m_diameter;
double m_num_vertices;
double m_rotation_angle;
double m_hole_diameter;
bool m_has_rotation;
bool m_has_hole;
yy::location m_diameter_location;
yy::location m_num_vertices_location;
yy::location m_rotation_angle_location;
yy::location m_hole_diameter_location;
yy::location m_location;
};
#endif // _STANDARD_APERTURE_POLYGON_H
| 38.075472 | 113 | 0.806739 |
35de929c892c7d967cb460a66b23efdf0e300918 | 585 | sql | SQL | openGaussBase/testcase/KEYWORDS/sequences/Opengauss_Function_Keyword_Sequences_Case0025.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | openGaussBase/testcase/KEYWORDS/sequences/Opengauss_Function_Keyword_Sequences_Case0025.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | openGaussBase/testcase/KEYWORDS/sequences/Opengauss_Function_Keyword_Sequences_Case0025.sql | opengauss-mirror/Yat | aef107a8304b94e5d99b4f1f36eb46755eb8919e | [
"MulanPSL-1.0"
] | null | null | null | -- @testpoint:opengauss关键字sequences(非保留),作为角色名
--关键字不带引号-成功
drop role if exists sequences;
create role sequences with password 'gauss@123' valid until '2020-12-31';
drop role sequences;
--关键字带双引号-成功
drop role if exists "sequences";
create role "sequences" with password 'gauss@123' valid until '2020-12-31';
drop role "sequences";
--关键字带单引号-合理报错
drop role if exists 'sequences';
create role 'sequences' with password 'gauss@123' valid until '2020-12-31';
--关键字带反引号-合理报错
drop role if exists `sequences`;
create role `sequences` with password 'gauss@123' valid until '2020-12-31';
| 27.857143 | 75 | 0.752137 |
497557d0a9f291b9e68e288320172c719e075398 | 481 | py | Python | classification/views/views_autocomplete.py | SACGF/variantgrid | 515195e2f03a0da3a3e5f2919d8e0431babfd9c9 | [
"RSA-MD"
] | 5 | 2021-01-14T03:34:42.000Z | 2022-03-07T15:34:18.000Z | classification/views/views_autocomplete.py | SACGF/variantgrid | 515195e2f03a0da3a3e5f2919d8e0431babfd9c9 | [
"RSA-MD"
] | 551 | 2020-10-19T00:02:38.000Z | 2022-03-30T02:18:22.000Z | classification/views/views_autocomplete.py | SACGF/variantgrid | 515195e2f03a0da3a3e5f2919d8e0431babfd9c9 | [
"RSA-MD"
] | null | null | null | from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from classification.models import EvidenceKey
from library.constants import MINUTE_SECS
from library.django_utils.autocomplete_utils import AutocompleteView
@method_decorator(cache_page(MINUTE_SECS), name='dispatch')
class EvidenceKeyAutocompleteView(AutocompleteView):
fields = ['key']
def get_user_queryset(self, user):
return EvidenceKey.objects.all()
| 32.066667 | 68 | 0.821206 |
6d03e9597d1688ef6a178397d500d15debe2cc38 | 572 | ts | TypeScript | tests/rules/non-control-statement-curly.test.ts | CyanSalt/eslint-plugin-galaxy | 17997c2d1c59ed0921d368fc652d620533841371 | [
"0BSD"
] | 2 | 2021-06-11T06:02:45.000Z | 2021-09-13T21:01:43.000Z | tests/rules/non-control-statement-curly.test.ts | CyanSalt/eslint-plugin-galaxy | 17997c2d1c59ed0921d368fc652d620533841371 | [
"0BSD"
] | null | null | null | tests/rules/non-control-statement-curly.test.ts | CyanSalt/eslint-plugin-galaxy | 17997c2d1c59ed0921d368fc652d620533841371 | [
"0BSD"
] | null | null | null | import rule from '../../src/rules/non-control-statement-curly'
import { ruleTester } from '../tester'
ruleTester.run('non-control-statement-curly', rule, {
valid: [
{
code: `
if (foo) {
bar()
}
`,
},
{
code: `function demo() { if (foo) return }`,
},
{
code: `if (foo) throw new Error('An error occurred.')`,
},
],
invalid: [
{
code: `if (foo) bar()`,
errors: [
{ messageId: 'non-control-statement-curly' },
],
output: `if (foo) { bar() }`,
},
],
})
| 19.066667 | 62 | 0.465035 |
3baf4bc7e4b27e54894a47ee9c1c44be69b991a6 | 58 | ps1 | PowerShell | Labo_1/Pepijn/Installatie.ps1 | ManuCardoen/hogent_sel | 5b5331594c43a3fb64315214fc31e99d76ef38e2 | [
"MIT"
] | 1 | 2021-02-22T21:37:06.000Z | 2021-02-22T21:37:06.000Z | Labo_1/Pepijn/Installatie.ps1 | ManuCardoen/hogent_sel | 5b5331594c43a3fb64315214fc31e99d76ef38e2 | [
"MIT"
] | null | null | null | Labo_1/Pepijn/Installatie.ps1 | ManuCardoen/hogent_sel | 5b5331594c43a3fb64315214fc31e99d76ef38e2 | [
"MIT"
] | 1 | 2021-02-22T21:38:18.000Z | 2021-02-22T21:38:18.000Z | Start-Transcript "logboek.txt"
Write-Host "Hello World"
| 14.5 | 31 | 0.758621 |
258a5eabb996eb09722754e024a54bf8b58debdf | 1,128 | js | JavaScript | src/components/CommandHistory/DetailsModal.js | stephb9959/wlan-cloud-ucentralgw-ui | 241827319140fdf6bf89a5b17c72dcc721db4703 | [
"BSD-3-Clause"
] | 2 | 2021-08-04T02:31:05.000Z | 2022-01-25T09:28:15.000Z | src/components/CommandHistory/DetailsModal.js | stephb9959/wlan-cloud-ucentralgw-ui | 241827319140fdf6bf89a5b17c72dcc721db4703 | [
"BSD-3-Clause"
] | 19 | 2021-06-21T18:59:04.000Z | 2021-09-28T13:12:36.000Z | src/components/CommandHistory/DetailsModal.js | stephb9959/wlan-cloud-ucentralgw-ui | 241827319140fdf6bf89a5b17c72dcc721db4703 | [
"BSD-3-Clause"
] | 3 | 2021-06-21T19:21:30.000Z | 2022-01-03T16:18:00.000Z | import React from 'react';
import PropTypes from 'prop-types';
import { CButton, CModal, CModalHeader, CModalBody, CModalTitle, CPopover } from '@coreui/react';
import CIcon from '@coreui/icons-react';
import { cilX } from '@coreui/icons';
const DetailsModal = ({ t, show, toggle, details, commandUuid }) => (
<CModal size="lg" show={show} onClose={toggle}>
<CModalHeader className="p-1">
<CModalTitle className="text-dark">{commandUuid}</CModalTitle>
<div className="text-right">
<CPopover content={t('common.close')}>
<CButton color="primary" variant="outline" className="ml-2" onClick={toggle}>
<CIcon content={cilX} />
</CButton>
</CPopover>
</div>
</CModalHeader>
<CModalBody>
<pre className="ignore">{JSON.stringify(details, null, 2)}</pre>
</CModalBody>
</CModal>
);
DetailsModal.propTypes = {
t: PropTypes.func.isRequired,
show: PropTypes.bool.isRequired,
toggle: PropTypes.func.isRequired,
details: PropTypes.instanceOf(Object).isRequired,
commandUuid: PropTypes.string.isRequired,
};
export default DetailsModal;
| 33.176471 | 97 | 0.672872 |
8edecf0b087ee16a71105d05b61255cb39918ee3 | 763 | swift | Swift | Pushup/Pushup/Views/InstructionCollectionViewCell.swift | drudolpho/Pushup | 8e480caee832400c408bc65cc55ccc22ec85bf62 | [
"MIT"
] | null | null | null | Pushup/Pushup/Views/InstructionCollectionViewCell.swift | drudolpho/Pushup | 8e480caee832400c408bc65cc55ccc22ec85bf62 | [
"MIT"
] | null | null | null | Pushup/Pushup/Views/InstructionCollectionViewCell.swift | drudolpho/Pushup | 8e480caee832400c408bc65cc55ccc22ec85bf62 | [
"MIT"
] | null | null | null | //
// InstructionCollectionViewCell.swift
// Pushup
//
// Created by Dennis Rudolph on 5/8/20.
// Copyright © 2020 Lambda School. All rights reserved.
//
import UIKit
class InstructionCollectionViewCell: UICollectionViewCell {
override func awakeFromNib() {
super.awakeFromNib()
//custom logic goes here
self.backgroundColor = .white
self.layer.cornerRadius = 40
self.layer.shadowColor = UIColor.lightGray.cgColor
self.layer.shadowOpacity = 0.3
self.layer.shadowOffset = .zero
self.layer.shadowRadius = 10
self.layer.masksToBounds = false
// self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.contentView.layer.cornerRadius).cgPath
}
}
| 29.346154 | 130 | 0.689384 |
f4c0aaa44f3018ce6934368925334267fdd79239 | 67 | ts | TypeScript | src/reducers/index.ts | umbiliko/um-react-core | 94ed3a2525db3a5385ca6cd37c8f0a81657db00f | [
"MIT"
] | null | null | null | src/reducers/index.ts | umbiliko/um-react-core | 94ed3a2525db3a5385ca6cd37c8f0a81657db00f | [
"MIT"
] | null | null | null | src/reducers/index.ts | umbiliko/um-react-core | 94ed3a2525db3a5385ca6cd37c8f0a81657db00f | [
"MIT"
] | null | null | null | // export * from './arrayReducer';
export * from './stateReducer';
| 22.333333 | 34 | 0.656716 |
0dec4f35205b6426d14734a86633dc9946e79fae | 2,780 | kt | Kotlin | kotlin/src/test/kotlin/adventofcode/codeforces/KotlinHeroesPractice3.kt | 3ygun/adventofcode | 69f95bca3d22032fba6ee7d9d6ec307d4d2163cf | [
"MIT"
] | null | null | null | kotlin/src/test/kotlin/adventofcode/codeforces/KotlinHeroesPractice3.kt | 3ygun/adventofcode | 69f95bca3d22032fba6ee7d9d6ec307d4d2163cf | [
"MIT"
] | null | null | null | kotlin/src/test/kotlin/adventofcode/codeforces/KotlinHeroesPractice3.kt | 3ygun/adventofcode | 69f95bca3d22032fba6ee7d9d6ec307d4d2163cf | [
"MIT"
] | null | null | null | package adventofcode.codeforces
import io.kotlintest.should
import io.kotlintest.shouldBe
import io.kotlintest.specs.FreeSpec
import io.kotlintest.tables.row
class KotlinHeroesPractice3Tests : FreeSpec({
"Problem A - Restoring Three Numbers" - {
listOf(
row(row(3L, 6L, 5L, 4L), Triple(1L, 2L, 3L)),
row(row(4L, 7L, 6L, 4L), Triple(1L, 3L, 3L)),
row(row(40L, 40L, 40L, 60L), Triple(20L, 20L, 20L)),
row(row(120L, 120L, 120L, 180L), Triple(60L, 60L, 60L)),
row(row(201L, 101L, 101L, 200L), Triple(1L, 100L, 100L)),
row(row(5L, 100L, 101L, 103L), Triple(2L, 3L, 98L))
).map { (input, output) ->
"$input to $output" {
val (x1, x2, x3, x4) = input
KotlinHeroesPractice3.problemA(x1, x2, x3, x4) should { it == output.toList() }
}
}
}
"Problem B - Remove Duplicates" - {
listOf(
row("6", "1 5 5 1 6 1", "3", "5 6 1"),
row("5", "2 4 2 4 4", "2", "2 4"),
row("5", "6 6 6 6 6", "1", "6")
).map { (numInputs, input, numOutputs, output) ->
"From: '$input' To: '$output'" {
val (numResult, result) = KotlinHeroesPractice3.problemB(numInputs, input)
numResult shouldBe numOutputs
result shouldBe output
}
}
}
"Problem C - File Name" - {
listOf(
row("xxxiii", 1),
row("xxoxx", 0),
row("xxxxxxxxxx", 8)
).map { (input, expected) ->
"Expected removal $expected from: $input" {
KotlinHeroesPractice3.problemC(input) shouldBe expected
}
}
}
"Problem D - Bus Video System" - {
listOf(
row("3 5", "2 1 -3", 3L),
row("2 4", "-1 1", 4L),
row("4 10", "2 4 1 2", 2L),
row("3 10", "-2 -2 -5", 2L),
row("1 10", "10", 1L),
row("2 10", "9 -10", 1L),
row("3 10", "9 -5 -5", 1L),
row("4 10", "-2 -2 -5 9", 2L),
row("4 10", "9 -5 6 -10", 1L),
row("4 12", "9 -5 3 -7", 4L),
row("1 99", "-99", 1L),
row("5 99", "0 0 0 0 0", 100L),
row("2 99", "-55 -43", 2L),
row("2 100", "-50 1", 51L),
row("1 10", "-100", 0L),
row("1 10", "100", 0L),
row("4 10", "-1 -9 -7 10", 0L),
row("5 10", "5 -1 -9 -7 10", 0L),
row("3 10", "1 2", 0L)
).map { (bus, changes, expected) ->
"Bus Inputs: '$bus', Changes: '$changes', Expecting: $expected" {
KotlinHeroesPractice3.problemD(bus, changes) shouldBe expected
}
}
}
})
| 35.189873 | 95 | 0.449281 |
53dabf23adeb9a8e8fe4ec2b811cea58e9f7d0ac | 1,864 | rb | Ruby | lib/facebook_ads/ad_objects/instant_article_insights_query_result.rb | lookprintufc/facebook-ruby-business-sdk | 37e2f3cd3796479fb2c42c6f296b9e08b259826f | [
"Ruby"
] | 115 | 2018-05-02T10:59:45.000Z | 2022-03-24T16:00:43.000Z | lib/facebook_ads/ad_objects/instant_article_insights_query_result.rb | lookprintufc/facebook-ruby-business-sdk | 37e2f3cd3796479fb2c42c6f296b9e08b259826f | [
"Ruby"
] | 132 | 2018-05-08T12:55:02.000Z | 2022-03-30T15:52:02.000Z | lib/facebook_ads/ad_objects/instant_article_insights_query_result.rb | lookprintufc/facebook-ruby-business-sdk | 37e2f3cd3796479fb2c42c6f296b9e08b259826f | [
"Ruby"
] | 122 | 2018-05-16T14:01:09.000Z | 2022-03-08T07:59:09.000Z | # Copyright (c) 2017-present, Facebook, Inc. All rights reserved.
#
# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
# copy, modify, and distribute this software in source code or binary form for use
# in connection with the web services and APIs provided by Facebook.
#
# As with any software that integrates with the Facebook platform, your use of
# this software is subject to the Facebook Platform Policy
# [http://developers.facebook.com/policy/]. This copyright notice shall be
# included in all copies or substantial portions of the software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# FB:AUTOGEN
module FacebookAds
# This class is auto-generated.
# For any issues or feature requests related to this class, please let us know
# on github and we'll fix in our codegen framework. We'll not be able to accept
# pull request for this class.
class InstantArticleInsightsQueryResult < AdObject
BREAKDOWN = [
"age",
"country",
"gender",
"gender_and_age",
"is_organic",
"is_shared_by_ia_owner",
"no_breakdown",
"platform",
"region",
]
PERIOD = [
"day",
"days_28",
"lifetime",
"month",
"week",
]
field :breakdowns, 'hash'
field :name, 'string'
field :time, 'datetime'
field :value, 'string'
has_no_id
has_no_get
has_no_post
has_no_delete
end
end
| 30.557377 | 82 | 0.703863 |
14fb1f9c87c13f54c8f9998e53fb10f8a31078b9 | 454 | ts | TypeScript | tutorials/frontend/vue-apollo/app-final/src/main.ts | Makohan/learn-graphql | ac3c0eebcc95f51c0cdcd3525d67df7c9e4ff9db | [
"MIT"
] | 2 | 2022-01-20T08:06:13.000Z | 2022-02-23T18:35:18.000Z | tutorials/frontend/vue-apollo/app-final/src/main.ts | Makohan/learn-graphql | ac3c0eebcc95f51c0cdcd3525d67df7c9e4ff9db | [
"MIT"
] | null | null | null | tutorials/frontend/vue-apollo/app-final/src/main.ts | Makohan/learn-graphql | ac3c0eebcc95f51c0cdcd3525d67df7c9e4ff9db | [
"MIT"
] | 1 | 2022-02-25T15:16:00.000Z | 2022-02-25T15:16:00.000Z | import { createApp, provide, h } from "vue"
import { DefaultApolloClient } from "@vue/apollo-composable"
// @ts-ignore
import App from "./App.vue"
import { apolloClient } from "./apollo-client"
import { router } from "./router"
import authPlugin from "./auth/authPlugin"
const app = createApp({
setup() {
provide(DefaultApolloClient, apolloClient)
},
render: () => h(App),
})
app.use(authPlugin)
app.use(router)
app.mount("#app")
| 21.619048 | 60 | 0.669604 |
89c4dfddf3e2fe1a25a2c0ae1477e25dd6a9d85b | 604 | lua | Lua | platform/bootloader/component/scripts/bootloader_core_validation.lua | bojanpotocnik/gecko_sdk | 9e70b13fc4701459c5f8a8f5e8918ec3f5ea8903 | [
"Zlib"
] | 82 | 2016-06-29T17:24:43.000Z | 2021-04-16T06:49:17.000Z | platform/bootloader/component/scripts/bootloader_core_validation.lua | bojanpotocnik/gecko_sdk | 9e70b13fc4701459c5f8a8f5e8918ec3f5ea8903 | [
"Zlib"
] | 2 | 2017-02-13T10:07:17.000Z | 2017-03-22T21:28:26.000Z | platform/bootloader/component/scripts/bootloader_core_validation.lua | bojanpotocnik/gecko_sdk | 9e70b13fc4701459c5f8a8f5e8918ec3f5ea8903 | [
"Zlib"
] | 56 | 2016-08-02T10:50:50.000Z | 2021-07-19T08:57:34.000Z | --Validation script for Bootloader Image Parser with no encryption component
local has_parser_noenc = slc.is_selected("bootloader_image_parser_nonenc")
local btl_enforce_signed_upgrade = slc.config('BOOTLOADER_ENFORCE_SIGNED_UPGRADE')
local btl_enforce_encryption = slc.config('BOOTLOADER_ENFORCE_ENCRYPTED_UPGRADE')
if btl_enforce_encryption.value == "1" and has_parser_noenc then
validation.error('Can not use parser without encryption support, since the bootloader is configured to enforce encrypted upgrade files',
validation.target_for_defines({'BOOTLOADER_ENFORCE_ENCRYPTED_UPGRADE'}))
end
| 50.333333 | 140 | 0.842715 |
a32ed4db844becdac04fde0bcc12d16c574649cb | 63 | ts | TypeScript | jest.init.ts | jkorrek/ionic-native-http-connection-backend | 08f523ce3808e97e32c6663753cbfab64164de9e | [
"MIT"
] | 168 | 2017-08-02T08:33:04.000Z | 2022-02-22T09:47:29.000Z | jest.init.ts | jkorrek/ionic-native-http-connection-backend | 08f523ce3808e97e32c6663753cbfab64164de9e | [
"MIT"
] | 148 | 2017-08-12T18:03:12.000Z | 2022-01-13T17:50:39.000Z | jest.init.ts | jkorrek/ionic-native-http-connection-backend | 08f523ce3808e97e32c6663753cbfab64164de9e | [
"MIT"
] | 48 | 2017-08-11T11:03:46.000Z | 2022-03-06T08:17:50.000Z | import 'zone.js';
import 'core-js/proposals/reflect-metadata';
| 21 | 44 | 0.761905 |
aa6fb8d126319461b52073ca59c5aa271c21435e | 149 | lua | Lua | Kick + Reason.lua | xVoid-xyz/Roblox-Scripts | 7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2 | [
"BSD-3-Clause"
] | 70 | 2021-02-09T17:21:32.000Z | 2022-03-28T12:41:42.000Z | Kick + Reason.lua | xVoid-xyz/Roblox-Scripts | 7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2 | [
"BSD-3-Clause"
] | 4 | 2021-08-19T22:05:58.000Z | 2022-03-19T18:58:01.000Z | Kick + Reason.lua | xVoid-xyz/Roblox-Scripts | 7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2 | [
"BSD-3-Clause"
] | 325 | 2021-02-26T22:23:41.000Z | 2022-03-31T19:36:12.000Z | getglobal game
getfield -1 Players
getfield -1 LocalPlayer
getfield -1 Kick
pushvalue -2
pushstring your message goes here lol
pcall 2 0 0
emptystack | 18.625 | 37 | 0.818792 |
83535ad7d21d0cd3d8df9a18b927c44679d3ff5e | 50 | ts | TypeScript | src/shared/interfaces/BaseDomainException.ts | adziok/authorization-domain | 0afe3f09ba1bc86a8d6960f1ea531afb8debb063 | [
"MIT"
] | null | null | null | src/shared/interfaces/BaseDomainException.ts | adziok/authorization-domain | 0afe3f09ba1bc86a8d6960f1ea531afb8debb063 | [
"MIT"
] | null | null | null | src/shared/interfaces/BaseDomainException.ts | adziok/authorization-domain | 0afe3f09ba1bc86a8d6960f1ea531afb8debb063 | [
"MIT"
] | null | null | null | export class BaseDomainException extends Error {}
| 25 | 49 | 0.84 |
06caca715317e5cfe5ead1bb8633ddcb9dff7dc5 | 21,448 | py | Python | unet_methods/unet_2d/utilities/data.py | DiamondLightSource/gas-hydrate-segmentation-unets | e635c30788c58f5c56929e437cc4704f5cbf6b79 | [
"Apache-2.0"
] | null | null | null | unet_methods/unet_2d/utilities/data.py | DiamondLightSource/gas-hydrate-segmentation-unets | e635c30788c58f5c56929e437cc4704f5cbf6b79 | [
"Apache-2.0"
] | null | null | null | unet_methods/unet_2d/utilities/data.py | DiamondLightSource/gas-hydrate-segmentation-unets | e635c30788c58f5c56929e437cc4704f5cbf6b79 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
"""Data utilities for U-net training and prediction.
"""
import glob
import logging
import os
import re
import sys
import warnings
from datetime import date
from itertools import chain, product
from pathlib import Path
import dask.array as da
import h5py as h5
import numpy as np
import yaml
from fastai.vision import Image, crop_pad, pil2tensor
from skimage import exposure, img_as_float, img_as_ubyte, io
from tqdm import tqdm
from . import config as cfg
warnings.filterwarnings("ignore", category=UserWarning)
class SettingsData:
"""Class to sanity check and then store settings from the commandline and
a YAML settings file. Assumes given commandline args are filepaths.
Args:
settings_path (pathlib.Path): Path to the YAML file containing user settings.
parser_args (argparse.Namespace): Parsed commandline arguments from argparse.
"""
def __init__(self, settings_path, parser_args):
logging.info(f"Loading settings from {settings_path}")
if settings_path.exists():
self.settings_path = settings_path
with open(settings_path, 'r') as stream:
self.settings_dict = yaml.safe_load(stream)
else:
logging.error("Couldn't find settings file... Exiting!")
sys.exit(1)
logging.debug(f"Commandline args given: {vars(parser_args)}")
# Set the data as attributes, check paths are valid files
for k, v in self.settings_dict.items():
setattr(self, k, v)
for k, v in vars(parser_args).items():
# Check that files exist
v = Path(v)
if v.is_file():
setattr(self, k, v)
else:
logging.error(f"The file {v} does not appear to exist. Exiting!")
sys.exit(1)
class DataSlicerBase:
"""Base class for classes that convert 3d data volumes into 2d image slices on disk.
Slicing is carried in all of the xy (z), xz (y) and yz (x) planes.
Args:
settings (SettingsData): An initialised SettingsData object.
"""
def __init__(self, settings):
self.st_dev_factor = settings.st_dev_factor
if settings.clip:
self.data_vol = self.clip_to_uint8(self.data_vol)
def numpy_from_hdf5(self, path, hdf5_path='/data', nexus=False):
"""Returns a numpy array when given a path to an HDF5 file.
The data is assumed to be found in '/data' in the file.
Args:
path(pathlib.Path): The path to the HDF5 file.
hdf5_path (str): The internal HDF5 path to the data.
Returns:
numpy.array: A numpy array object for the data stored in the HDF5 file.
"""
with h5.File(path, 'r') as f:
data = f[hdf5_path][()]
return data
def clip_to_uint8(self, data):
"""Clips data to a certain number of st_devs of the mean and reduces
bit depth to uint8.
Args:
data(np.array): The data to be processed.
Returns:
np.array: A unit8 data array.
"""
logging.info("Clipping data and converting to uint8.")
data_st_dev = np.std(data)
data_mean = np.mean(data)
num_vox = np.prod(data.shape)
lower_bound = data_mean - (data_st_dev * self.st_dev_factor)
upper_bound = data_mean + (data_st_dev * self.st_dev_factor)
gt_ub = (data > upper_bound).sum()
lt_lb = (data < lower_bound).sum()
logging.info(f"Lower bound: {lower_bound}, upper bound: {upper_bound}")
logging.info(
f"Number of voxels above upper bound to be clipped {gt_ub} - percentage {gt_ub/num_vox * 100:.3f}%")
logging.info(
f"Number of voxels below lower bound to be clipped {lt_lb} - percentage {lt_lb/num_vox * 100:.3f}%")
data = np.clip(data, lower_bound, upper_bound)
data = exposure.rescale_intensity(data, out_range='float')
return img_as_ubyte(data)
def get_axis_index_pairs(self, vol_shape):
"""Gets all combinations of axis and image slice index that are found
in a 3d volume.
Args:
vol_shape (tuple): 3d volume shape (z, y, x)
Returns:
itertools.chain: An iterable containing all combinations of axis
and image index that are found in the volume.
"""
return chain(
product('z', range(vol_shape[0])),
product('y', range(vol_shape[1])),
product('x', range(vol_shape[2]))
)
def axis_index_to_slice(self, vol, axis, index):
"""Converts an axis and image slice index for a 3d volume into a 2d
data array (slice).
Args:
vol (3d array): The data volume to be sliced.
axis (str): One of 'z', 'y' and 'x'.
index (int): An image slice index found in that axis.
Returns:
2d array: A 2d image slice corresponding to the axis and index.
"""
if axis == 'z':
return vol[index, :, :]
if axis == 'y':
return vol[:, index, :]
if axis == 'x':
return vol[:, :, index]
def get_num_of_ims(self, vol_shape):
"""Calculates the total number of images that will be created when slicing
an image volume in the z, y and x planes.
Args:
vol_shape (tuple): 3d volume shape (z, y, x).
Returns:
int: Total number of images that will be created when the volume is
sliced.
"""
return sum(vol_shape)
class TrainingDataSlicer(DataSlicerBase):
"""Class that converts 3d data volumes into 2d image slices on disk for
model training.
Slicing is carried in all of the xy (z), xz (y) and yz (x) planes.
Args:
settings (SettingsData): An initialised SettingsData object.
"""
def __init__(self, settings):
data_vol_path = getattr(settings, cfg.TRAIN_DATA_ARG)
self.data_vol = self.numpy_from_hdf5(data_vol_path,
hdf5_path=settings.train_data_hdf5_path)
super().__init__(settings)
self.multilabel = False
self.data_im_out_dir = None
self.seg_im_out_dir = None
seg_vol_path = getattr(settings, cfg.LABEL_DATA_ARG)
self.seg_vol = self.numpy_from_hdf5(seg_vol_path,
hdf5_path=settings.seg_hdf5_path)
seg_classes = np.unique(self.seg_vol)
self.num_seg_classes = len(seg_classes)
if self.num_seg_classes > 2:
self.multilabel = True
logging.info("Number of classes in segmentation dataset:"
f" {self.num_seg_classes}")
logging.info(f"These classes are: {seg_classes}")
if seg_classes[0] != 0:
logging.info("Fixing label classes.")
self.fix_label_classes(seg_classes)
self.codes = [f"label_val_{i}" for i in seg_classes]
def fix_label_classes(self, seg_classes):
"""Changes the data values of classes in a segmented volume so that
they start from zero.
Args:
seg_classes(list): An ascending list of the labels in the volume.
"""
if isinstance(self.seg_vol, da.core.Array):
self.seg_vol = self.seg_vol
for idx, current in enumerate(seg_classes):
self.seg_vol[self.seg_vol == current] = idx
def output_data_slices(self, data_dir):
"""Wrapper method to intitiate slicing data volume to disk.
Args:
data_dir (pathlib.Path): The path to the directory where images will be saved.
"""
self.data_im_out_dir = data_dir
logging.info(
'Slicing data volume and saving slices to disk')
os.makedirs(data_dir, exist_ok=True)
self.output_slices_to_disk(self.data_vol, data_dir, 'data')
def output_label_slices(self, data_dir):
"""Wrapper method to intitiate slicing label volume to disk.
Args:
data_dir (pathlib.Path): The path to the directory where images will be saved.
"""
self.seg_im_out_dir = data_dir
logging.info(
'Slicing label volume and saving slices to disk')
os.makedirs(data_dir, exist_ok=True)
self.output_slices_to_disk(
self.seg_vol, data_dir, 'seg', label=True)
def output_slices_to_disk(self, data_arr, output_path, name_prefix, label=False):
"""Coordinates the slicing of an image volume in the three orthogonal
planes to images on disk.
Args:
data_arr (array): The data volume to be sliced.
output_path (pathlib.Path): A Path object to the output directory.
label (bool): Whether this is a label volume.
"""
shape_tup = data_arr.shape
ax_idx_pairs = self.get_axis_index_pairs(shape_tup)
num_ims = self.get_num_of_ims(shape_tup)
for axis, index in tqdm(ax_idx_pairs, total=num_ims):
out_path = output_path/f"{name_prefix}_{axis}_stack_{index}"
self.output_im(self.axis_index_to_slice(data_arr, axis, index),
out_path, label)
def output_im(self, data, path, label=False):
"""Converts a slice of data into an image on disk.
Args:
data (numpy.array): The data slice to be converted.
path (str): The path of the image file including the filename prefix.
label (bool): Whether to convert values >1 to 1 for binary segmentation.
"""
if isinstance(data, da.core.Array):
data = data
if label and not self.multilabel:
data[data > 1] = 1
io.imsave(f'{path}.png', data)
def delete_data_im_slices(self):
"""Deletes image slices in the data image output directory. Leaves the
directory in place since it contains model training history.
"""
if self.data_im_out_dir:
data_ims = glob.glob(f"{str(self.data_im_out_dir) + '/*.png'}")
logging.info(f"Deleting {len(data_ims)} image slices")
for fn in data_ims:
os.remove(fn)
def delete_label_im_slices(self):
"""Deletes label image slices in the segmented image output directory.
Also deletes the directory itself.
"""
if self.seg_im_out_dir:
seg_ims = glob.glob(f"{str(self.seg_im_out_dir) + '/*.png'}")
logging.info(f"Deleting {len(seg_ims)} segmentation slices")
for fn in seg_ims:
os.remove(fn)
logging.info(f"Deleting the empty segmentation image directory")
os.rmdir(self.seg_im_out_dir)
def clean_up_slices(self):
"""Wrapper function that cleans up data and label image slices.
"""
self.delete_data_im_slices()
self.delete_label_im_slices()
class PredictionDataSlicer(DataSlicerBase):
"""Class that converts 3d data volumes into 2d image slices for
segmentation prediction and that combines the slices back into volumes after
prediction.
1. Slicing is carried in the xy (z), xz (y) and yz (x) planes. 2. The data
volume is rotated by 90 degrees. Steps 1 and 2 are then repeated untill
4 rotations have been sliced.
The class also has methods to combine the image slices in to 3d volumes and
also to combine these volumes and perform consensus thresholding.
Args:
settings (SettingsData): An initialised SettingsData object.
predictor (Unet2dPredictor): A Unet2dPredictor object with a trained
2d U-net as an attribute.
"""
def __init__(self, settings, predictor):
data_vol_path = getattr(settings, cfg.PREDICT_DATA_ARG)
self.data_vol = self.numpy_from_hdf5(data_vol_path,
hdf5_path=settings.predict_data_hdf5_path)
super().__init__(settings)
self.consensus_vals = map(int, settings.consensus_vals)
self.predictor = predictor
self.delete_vols = settings.del_vols # Whether to clean up predicted vols
def setup_folder_stucture(self, root_path):
"""Sets up a folder structure to store the predicted images.
Args:
root_path (Path): The top level directory for data output.
"""
vol_dir= root_path/f'{date.today()}_predicted_volumes'
non_rotated = vol_dir/f'{date.today()}_non_rotated_volumes'
rot_90_seg = vol_dir/f'{date.today()}_rot_90_volumes'
rot_180_seg = vol_dir/f'{date.today()}_rot_180_volumes'
rot_270_seg = vol_dir/f'{date.today()}_rot_270_volumes'
self.dir_list = [
('non_rotated', non_rotated),
('rot_90_seg', rot_90_seg),
('rot_180_seg', rot_180_seg),
('rot_270_seg', rot_270_seg)
]
for _, dir_path in self.dir_list:
os.makedirs(dir_path, exist_ok=True)
def combine_slices_to_vol(self, folder_path):
"""Combines the orthogonally sliced png images in a folder to HDF5
volumes. One volume for each direction. These are then saved with a
common orientation. The images slices are then deleted.
Args:
folder_path (pathlib.Path): Path to a folder containing images that
were sliced in the three orthogonal planes.
Returns:
list of pathlib.Path: Paths to the created volumes.
"""
output_path_list = []
file_list = folder_path.ls()
axis_list = ['z', 'y', 'x']
number_regex = re.compile(r'\_(\d+)\.png')
for axis in axis_list:
# Generate list of files for that axis
axis_files = [x for x in file_list if re.search(
f'\_({axis})\_', str(x))]
logging.info(f'Axis {axis}: {len(axis_files)} files found, creating' \
' volume')
# Load in the first image to get dimensions
first_im = io.imread(axis_files[0])
shape_tuple = first_im.shape
z_dim = len(axis_files)
y_dim, x_dim = shape_tuple
data_vol = np.empty([z_dim, y_dim, x_dim], dtype=np.uint8)
for filename in axis_files:
m = number_regex.search(str(filename))
index = int(m.group(1))
im_data = io.imread(filename)
data_vol[index, :, :] = im_data
if axis == 'y':
data_vol = np.swapaxes(data_vol, 0, 1)
if axis == 'x':
data_vol = np.swapaxes(data_vol, 0, 2)
data_vol = np.swapaxes(data_vol, 0, 1)
output_path = folder_path/f'{axis}_axis_seg_combined.h5'
output_path_list.append(output_path)
logging.info(f'Outputting {axis} axis volume to {output_path}')
with h5.File(output_path, 'w') as f:
f['/data'] = data_vol
# Delete the images
logging.info(f"Deleting {len(axis_files)} image files for axis {axis}")
for filename in axis_files:
os.remove(filename)
return output_path_list
def combine_vols(self, output_path_list, k, prefix, final=False):
"""Sums volumes to give a combination of binary segmentations and saves to disk.
Args:
output_path_list (list of pathlib.Path): Paths to the volumes to be combined.
k (int): Number of 90 degree rotations that these image volumes
have been transformed by before slicing.
prefix (str): A filename prefix to give the final volume.
final (bool, optional): Set to True if this is the final combination
of the volumes that were created from each of the 90 degree rotations.
Defaults to False.
Returns:
pathlib.Path: A file path to the combined HDF5 volume that was saved.
"""
num_vols = len(output_path_list)
combined = self.numpy_from_hdf5(output_path_list[0])
for subsequent in output_path_list[1:]:
combined += self.numpy_from_hdf5(subsequent)
combined_out_path = output_path_list[0].parent.parent / \
f'{date.today()}_{prefix}_{num_vols}_volumes_combined.h5'
if final:
combined_out_path = output_path_list[0].parent / \
f'{date.today()}_{prefix}_12_volumes_combined.h5'
logging.info(f'Saving the {num_vols} combined volumes to {combined_out_path}')
combined = combined
combined = np.rot90(combined, 0 - k)
with h5.File(combined_out_path, 'w') as f:
f['/data'] = combined
if self.delete_vols:
logging.info("Deleting the source volumes for the combined volume")
for vol_filepath in output_path_list:
os.remove(vol_filepath)
return combined_out_path
def predict_single_slice(self, axis, index, data, output_path):
"""Takes in a 2d data array and saves the predicted U-net segmentation to disk.
Args:
axis (str): The name of the axis to incorporate in the output filename.
index (int): The slice number to incorporate in the output filename.
data (numpy.array): The 2d data array to be fed into the U-net.
output_path (pathlib.Path): The path to directory for file output.
"""
data = img_as_float(data)
img = Image(pil2tensor(data, dtype=np.float32))
self.fix_odd_sides(img)
prediction = self.predictor.model.predict(img)
pred_slice = img_as_ubyte(prediction[1][0])
io.imsave(
output_path/f"unet_prediction_{axis}_stack_{index}.png", pred_slice)
def fix_odd_sides(self, example_image):
"""Replaces an an odd image dimension with an even dimension by padding.
Taken from https://forums.fast.ai/t/segmentation-mask-prediction-on-different-input-image-sizes/44389/7.
Args:
example_image (fastai.vision.Image): The image to be fixed.
"""
if (list(example_image.size)[0] % 2) != 0:
example_image = crop_pad(example_image,
size=(list(example_image.size)[
0]+1, list(example_image.size)[1]),
padding_mode='reflection')
if (list(example_image.size)[1] % 2) != 0:
example_image = crop_pad(example_image,
size=(list(example_image.size)[0], list(
example_image.size)[1] + 1),
padding_mode='reflection')
def predict_orthog_slices_to_disk(self, data_arr, output_path):
"""Outputs slices from data or ground truth seg volumes sliced in
all three of the orthogonal planes
Args:
data_array (numpy.array): The 3d data volume to be sliced and predicted.
output_path (pathlib.Path): A Path to the output directory.
"""
shape_tup = data_arr.shape
ax_idx_pairs = self.get_axis_index_pairs(shape_tup)
num_ims = self.get_num_of_ims(shape_tup)
for axis, index in tqdm(ax_idx_pairs, total=num_ims):
self.predict_single_slice(
axis, index, self.axis_index_to_slice(data_arr, axis, index), output_path)
def consensus_threshold(self, input_path):
"""Saves a consensus thresholded volume from combination of binary volumes.
Args:
input_path (pathlib.Path): Path to the combined HDF5 volume that is
to be thresholded.
"""
for val in self.consensus_vals:
combined = self.numpy_from_hdf5(input_path)
combined_out = input_path.parent / \
f'{date.today()}_combined_consensus_thresh_cutoff_{val}.h5'
combined[combined < val] = 0
combined[combined >= val] = 255
logging.info(f'Writing to {combined_out}')
with h5.File(combined_out, 'w') as f:
f['/data'] = combined
def predict_12_ways(self, root_path):
"""Runs the loop that coordinates the prediction of a 3d data volume
by a 2d U-net in 12 orientations and then combination of the segmented
binary outputs.
Args:
root_path (pathlib.Path): Path to the top level directory for data
output.
"""
self.setup_folder_stucture(root_path)
combined_vol_paths = []
for k in tqdm(range(4), ncols=100, desc='Total progress', postfix="\n"):
key, output_path = self.dir_list[k]
logging.info(f'Rotating volume {k * 90} degrees')
rotated = np.rot90(self.data_vol, k)
logging.info("Predicting slices to disk.")
self.predict_orthog_slices_to_disk(rotated, output_path)
output_path_list = self.combine_slices_to_vol(output_path)
fp = self.combine_vols(output_path_list, k, key)
combined_vol_paths.append(fp)
# Combine all the volumes
final_combined = self.combine_vols(combined_vol_paths, 0, 'final', True)
self.consensus_threshold(final_combined)
if self.delete_vols:
for _, vol_dir in self.dir_list:
os.rmdir(vol_dir)
| 41.166987 | 112 | 0.61423 |
76fe2f78d317dbbd369ce1a2d52898040f69f0ec | 8,668 | h | C | src/events/events_MovementSubscriptionParams.h | hyena/mutgos_server | 855c154be840f70c3b878fabde23d2148ad028b3 | [
"MIT"
] | 5 | 2019-02-24T06:42:52.000Z | 2021-04-09T19:16:24.000Z | src/events/events_MovementSubscriptionParams.h | hyena/mutgos_server | 855c154be840f70c3b878fabde23d2148ad028b3 | [
"MIT"
] | 40 | 2019-02-24T15:25:54.000Z | 2021-05-17T04:22:43.000Z | src/events/events_MovementSubscriptionParams.h | hyena/mutgos_server | 855c154be840f70c3b878fabde23d2148ad028b3 | [
"MIT"
] | 2 | 2019-02-23T22:58:36.000Z | 2019-02-27T01:27:42.000Z | /*
* events_MovementSubscriptionParams.h
*/
#ifndef MUTGOS_EVENTS_MOVEMENTSUBSCRIPTIONPARAMS_H
#define MUTGOS_EVENTS_MOVEMENTSUBSCRIPTIONPARAMS_H
#include <set>
#include "dbtypes/dbtype_Id.h"
#include "dbtypes/dbtype_Entity.h"
#include "events/events_SubscriptionParams.h"
namespace mutgos
{
namespace events
{
// Forward declarations
//
class MovementEvent;
/**
* A movement subscription. This allows the subscriber to get notified
* when an Entity has been moved from one Container to another, which
* also includes when an Entity is newly created.
*
* Fields that are left at defaults (or empty) are considered wildcards.
* For an example, not filling in who moved will match all movers.
*
* The movement site may only be filled in if the from and to are not
* filled in.
*
* Note this is not a general purpose container. Attributes, once set,
* may not always be unsettable.
*/
class MovementSubscriptionParams : public SubscriptionParams
{
public:
/**
* Interested types for the cause of movement.
*/
enum MovementType
{
/** Movement was due to a program moving the Entity*/
MOVEMENT_TYPE_PROGRAM,
/** Movement was due to an Entity going through an Exit */
MOVEMENT_TYPE_EXIT,
/** Any movement type */
MOVEMENT_TYPE_ALL
};
/**
* Constructor with nothing set.
*/
MovementSubscriptionParams(void);
/**
* Constructor that sets everything.
* Refer to individual setters for more details about each parameter.
* @param who[in] The Entities interested in knowing when they move.
* @param from[in] The interested originating location of the movement.
* @param to[in] The destination location of the movement.
* @param site[in] The site ID of interest, if who, from, and to are
* not set.
* @param type[in] The type of the cause of movement.
* @param how[in] The interested cause / how the movement occurred.
*/
MovementSubscriptionParams(
const dbtype::Entity::IdVector &who,
const dbtype::Entity::IdVector &from,
const dbtype::Entity::IdVector &to,
const dbtype::Id::SiteIdType site,
const MovementType type,
const dbtype::Id &how);
/**
* Copy constructor.
* @param rhs[in] The source for the copy.
*/
MovementSubscriptionParams(const MovementSubscriptionParams &rhs);
/**
* Virtual destructor.
*/
virtual ~MovementSubscriptionParams();
/**
* Assignment operator.
* @param rhs[in] The source for the copy.
* @return The updated destination.
*/
MovementSubscriptionParams &operator=(
const MovementSubscriptionParams &rhs);
/**
* Equals operator.
* @param rhs[in] The class instance to check.
* @return True if both instances are equal.
*/
bool operator==(const MovementSubscriptionParams &rhs) const;
/**
* Adds an entity ID which we want to know if it moves.
* Cannot be called if setting an interested site.
* @param entity_id[in] The entity ID that we want to know if it moves.
*/
void add_who(const dbtype::Id &entity_id)
{ movement_who.push_back(entity_id); }
/**
* @return The entity IDs interested in knowing if they move.
*/
const dbtype::Entity::IdVector &get_who(void) const
{ return movement_who; }
/**
* Adds an entity ID of a Container which we want to know if anything
* moves from it.
* Cannot be called if setting an interested site.
* @param entity_id[in] The entity ID that we want to know if anything
* moves from it.
*/
void add_from(const dbtype::Id &entity_id)
{ movement_from.push_back(entity_id); }
/**
* @return The entity IDs interested in knowing if anything moves from
* them.
*/
const dbtype::Entity::IdVector &get_from(void) const
{ return movement_from; }
/**
* Adds an entity ID of a Container which we want to know if anything
* moves to it.
* Cannot be called if setting an interested site.
* @param entity_id[in] The entity ID that we want to know if anything
* moves to it.
*/
void add_to(const dbtype::Id &entity_id)
{ movement_to.push_back(entity_id); }
/**
* @return The entity IDs interested in knowing if anything moves to
* them.
*/
const dbtype::Entity::IdVector &get_to(void) const
{ return movement_to;}
/**
* Sets a site ID for the site we are interested in all movement in.
* If this is set, cannot add 'who', 'from', or 'to' Entities.
* You can still set 'how', but it will be of limited use unless
* the programs are global.
* @param site_id[in] The site ID of interest.
*/
void set_site(const dbtype::Id::SiteIdType site_id)
{ movement_site = site_id; }
/**
* @return The site ID we are interested in knowing about any movement
* in.
*/
const dbtype::Id::SiteIdType get_site(void) const
{ return movement_site; }
/**
* Sets the interested type of how the entity moved (for instance,
* via a program, or an exit). The default is interested in every
* type.
* @param type[in] The type of movement of interest.
*/
void set_movement_type(const MovementType type)
{ movement_type = type;}
/**
* @return The type of movement of interest.
*/
const MovementType get_movement_type(void) const
{ return movement_type; }
/**
* Sets the interested cause of the movement. It could be the entity
* ID of a program, entity ID of an exit, etc, based on the
* movement type.
* @param entity_id[in] The cause of the movement.
*/
void set_movement_how(const dbtype::Id &entity_id)
{ movement_how = entity_id; }
/**
* @return The cause of the movement.
*/
const dbtype::Id &get_movement_how(void) const
{ return movement_how; }
/**
* Validates that the subscription is valid (has all needed fields
* filled in and that they are properly filled in.
* @return True if subscription is valid, false if there is a problem.
*/
virtual bool validate(void) const;
/**
* @return A copy of this subscription. Caller is responsible for
* managing the pointer.
*/
virtual SubscriptionParams *clone(void) const;
/**
* @param id[in] The ID to check.
* @return True if the subscription parameters specifically reference
* the given ID anywhere.
*/
virtual bool references_id(const dbtype::Id &id) const;
/**
* @param site_id[in] The site ID to check.
* @return True if the subscription parameters specifically reference
* the given site ID anywhere, including in entity IDs.
*/
virtual bool references_site(
const dbtype::Id::SiteIdType site_id) const;
/**
* @return The subscription as a string, for diagnostic/logging
* purposes.
*/
virtual std::string to_string(void) const;
/**
* Evaluates the event and determine if it matches this subscription.
* @param event_ptr[in] The event to evaluate.
* @return True if subscription matches event.
*/
virtual bool is_match(const MovementEvent *event_ptr) const;
private:
dbtype::Entity::IdVector movement_who; ///< Entities we want to know if moved
dbtype::Entity::IdVector movement_from; ///< Interested sources of movement
dbtype::Entity::IdVector movement_to; ///< Interested destinations of movement
dbtype::Id::SiteIdType movement_site; ///< Site ID of interest
MovementType movement_type; ///< Interested movement cause type
dbtype::Id movement_how; ///< Interested cause of the movement
};
}
}
#endif //MUTGOS_EVENTS_MOVEMENTSUBSCRIPTIONPARAMS_H
| 34.533865 | 86 | 0.599562 |
e0748c355082eeca7071a69909fec313af781425 | 1,135 | h | C | inc/oni-core/graphic/oni-graphic-renderer-ogl-quad.h | sina-/granite | 95b873bc545cd4925b5cea8c632a82f2d815be6e | [
"MIT"
] | 2 | 2019-08-01T09:18:49.000Z | 2020-03-26T05:59:52.000Z | inc/oni-core/graphic/oni-graphic-renderer-ogl-quad.h | sina-/granite | 95b873bc545cd4925b5cea8c632a82f2d815be6e | [
"MIT"
] | null | null | null | inc/oni-core/graphic/oni-graphic-renderer-ogl-quad.h | sina-/granite | 95b873bc545cd4925b5cea8c632a82f2d815be6e | [
"MIT"
] | 1 | 2020-03-26T05:59:53.000Z | 2020-03-26T05:59:53.000Z | #pragma once
#include <oni-core/graphic/oni-graphic-renderer-ogl.h>
namespace oni {
class Shader;
class Renderer_OpenGL_Quad : public Renderer_OpenGL {
public:
explicit Renderer_OpenGL_Quad(oniGLsizei maxSpriteCount,
TextureManager &);
~Renderer_OpenGL_Quad() override;
void
submit(const Renderable &renderable) override;
// TODO: These are only used to render to texture, so there is no need to unify it at the moment.
void
submit(const Quad &,
const Color &,
const Texture *);
void
submit(const Quad &,
const Color &,
const Texture &front,
const Texture &back);
protected:
void
enableShader(const RenderSpec &) override;
oniGLsizei
getIndexCount() override;
void
resetIndexCount() override;
private:
oniGLsizei mMaxPrimitiveCount{0};
oniGLsizei mMaxIndicesCount{0};
// Actual number of indices used.
oniGLsizei mIndexCount{0};
};
}
| 23.645833 | 105 | 0.577974 |
5db22772f68619ce17961d2ef93c4b6f337860c7 | 2,047 | cpp | C++ | apps/qmimicruntime/src/settingswidget.cpp | peter-kozarec/qMimic | ee8b7d2206a30569f118fe26b9b6412a5289c7de | [
"Apache-2.0"
] | 1 | 2021-08-03T20:18:40.000Z | 2021-08-03T20:18:40.000Z | apps/qmimicruntime/src/settingswidget.cpp | peter-kozarec/qMimic | ee8b7d2206a30569f118fe26b9b6412a5289c7de | [
"Apache-2.0"
] | 6 | 2021-08-04T14:56:28.000Z | 2021-11-14T15:16:01.000Z | apps/qmimicruntime/src/settingswidget.cpp | peter-kozarec/qMimic | ee8b7d2206a30569f118fe26b9b6412a5289c7de | [
"Apache-2.0"
] | null | null | null | /******************************************************************************
* Copyright (C) 2021 Peter Kozarec *
* *
* 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 <https://www.gnu.org/licenses/>. *
******************************************************************************/
#include "settingswidget.hpp"
#include <QIcon>
CSettingsWidget::CSettingsWidget(QWidget *parent) : QWidget(parent)
{
m_search.setCompleter(&m_completer);
m_search.setFrame(false);
m_search.setMinimumSize(250, 30);
m_search.setClearButtonEnabled(true);
m_search.addAction(QIcon(":/resources/graphics/search.png"), QLineEdit::LeadingPosition);
m_search.setPlaceholderText("Search...");
m_search.setTextMargins(30, 0 , 5, 0);
m_search.setStyleSheet("QLineEdit { border-radius: 7px; border: 1px solid black; }");
m_searchLayout.addStretch();
m_searchLayout.addWidget(&m_search);
m_searchLayout.addStretch();
m_mainLayout.addStretch(1);
m_mainLayout.addLayout(&m_searchLayout);
m_mainLayout.addStretch(9);
setLayout(&m_mainLayout);
}
| 46.522727 | 91 | 0.533952 |
e83e435ea100111a05cded86dabf497d47fd74f4 | 2,965 | cs | C# | source/Htc.Vita.Core/Interop/Windows.User32.cs | ViveportSoftware/vita_core_csharp | 8cfd6fbb381b8e3b7c35017705e0204cdccb9ac8 | [
"MIT"
] | null | null | null | source/Htc.Vita.Core/Interop/Windows.User32.cs | ViveportSoftware/vita_core_csharp | 8cfd6fbb381b8e3b7c35017705e0204cdccb9ac8 | [
"MIT"
] | 2 | 2019-11-18T08:52:57.000Z | 2020-11-23T07:48:27.000Z | source/Htc.Vita.Core/Interop/Windows.User32.cs | ViveportSoftware/vita_core_csharp | 8cfd6fbb381b8e3b7c35017705e0204cdccb9ac8 | [
"MIT"
] | 3 | 2019-06-11T06:37:02.000Z | 2019-11-18T06:04:17.000Z | using System;
using System.Runtime.InteropServices;
using Htc.Vita.Core.Util;
namespace Htc.Vita.Core.Interop
{
internal static partial class Windows
{
[ExternalReference("https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumdisplaydevicesw")]
[DllImport(Libraries.WindowsUser32,
CallingConvention = CallingConvention.Winapi,
CharSet = CharSet.Unicode,
ExactSpelling = true,
SetLastError = true)]
internal static extern bool EnumDisplayDevicesW(
/* _In_ LPCWSTR */ [In] string lpDevice,
/* _In_ DWORD */ [In] uint iDevNum,
/* _Inout_ PDISPLAY_DEVICEW */ [In][Out] ref DisplayDevice lpDisplayDevice,
/* _In_ DWORD */ [In] EnumDisplayDeviceFlags dwFlags
);
[ExternalReference("https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-exitwindowsex")]
[DllImport(Libraries.WindowsUser32,
CallingConvention = CallingConvention.Winapi,
CharSet = CharSet.Unicode,
ExactSpelling = true,
SetLastError = true)]
internal static extern bool ExitWindowsEx(
/* _In_ UINT */ [In] ExitTypes uFlags,
/* _In_ DWORD */ [In] uint dwReason
);
[ExternalReference("https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getmonitorinfow")]
[DllImport(Libraries.WindowsUser32,
CallingConvention = CallingConvention.Winapi,
CharSet = CharSet.Unicode,
ExactSpelling = true,
SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetMonitorInfoW(
/* _In_ HMONITOR */ [In] IntPtr hMonitor,
/* _Inout_ LPMONITORINFO */ [In][Out] ref MonitorInfoEx monitorInfo
);
[ExternalReference("https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getshellwindow")]
[DllImport(Libraries.WindowsUser32,
CallingConvention = CallingConvention.Winapi,
CharSet = CharSet.Unicode,
ExactSpelling = true,
SetLastError = true)]
internal static extern IntPtr GetShellWindow();
[ExternalReference("https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowthreadprocessid")]
[DllImport(Libraries.WindowsUser32,
CallingConvention = CallingConvention.Winapi,
CharSet = CharSet.Unicode,
ExactSpelling = true,
SetLastError = true)]
internal static extern uint GetWindowThreadProcessId(
/* _In_ HWND */ [In] IntPtr hWnd,
/* _Out_opt_ LPDWORD */ [In][Out] ref uint lpdwProcessId
);
}
}
| 45.615385 | 125 | 0.599325 |
a16cf6cd9435137476594be658ed627c446dca11 | 731 | tsx | TypeScript | app-ui/src/Custom-Components/CustomLinkFactory.tsx | Kunal-2001/app-ui | e6a0d72f08a7bed60cb01bc22f41bf7124e492c0 | [
"Apache-2.0"
] | 1 | 2021-11-14T17:14:02.000Z | 2021-11-14T17:14:02.000Z | app-ui/src/Custom-Components/CustomLinkFactory.tsx | Kunal-2001/app-ui | e6a0d72f08a7bed60cb01bc22f41bf7124e492c0 | [
"Apache-2.0"
] | null | null | null | app-ui/src/Custom-Components/CustomLinkFactory.tsx | Kunal-2001/app-ui | e6a0d72f08a7bed60cb01bc22f41bf7124e492c0 | [
"Apache-2.0"
] | 1 | 2021-12-30T16:49:54.000Z | 2021-12-30T16:49:54.000Z | import { DefaultLinkFactory } from "@projectstorm/react-diagrams";
import { CustomLinkModel } from "./CustomLinkModel";
import { CustomLinkSegment } from "./CustomLinkSegment";
export class CustomLinkFactory extends DefaultLinkFactory {
constructor() {
super("advanced");
}
generateModel(): CustomLinkModel {
return new CustomLinkModel();
}
/**
* @override the DefaultLinkWidget makes use of this, and it normally renders that
* familiar gray line, so in this case we simply make it return a new advanced segment.
*/
generateLinkSegment(model: CustomLinkModel, selected: boolean, path: string) {
return (
<g>
<CustomLinkSegment model={model} path={path} />
</g>
);
}
}
| 28.115385 | 89 | 0.692202 |
46ee0673924463e391a7d74db0429ea8e7ec648d | 423 | py | Python | solutions/1026_maximum_difference_between_node_and_ancestor.py | YiqunPeng/leetcode_pro | 7e6376984f9baec49a5e827d98330fe3d1b656f0 | [
"MIT"
] | null | null | null | solutions/1026_maximum_difference_between_node_and_ancestor.py | YiqunPeng/leetcode_pro | 7e6376984f9baec49a5e827d98330fe3d1b656f0 | [
"MIT"
] | null | null | null | solutions/1026_maximum_difference_between_node_and_ancestor.py | YiqunPeng/leetcode_pro | 7e6376984f9baec49a5e827d98330fe3d1b656f0 | [
"MIT"
] | null | null | null | class Solution:
def maxAncestorDiff(self, root: TreeNode) -> int:
return self._traverse(root, root.val, root.val)
def _traverse(self, root, minv, maxv):
if not root:
return maxv - minv
minv = min(minv, root.val)
maxv = max(maxv, root.val)
l = self._traverse(root.left, minv, maxv)
r = self._traverse(root.right, minv, maxv)
return max(l, r)
| 32.538462 | 55 | 0.58156 |
b4f84950562573298b151eb34f6f748474e8ed80 | 45 | dart | Dart | lib/utils.dart | quetool/story_view | 358d1224984b052917f5e21f95635de5a2fb4bbf | [
"BSD-3-Clause"
] | 27 | 2020-06-11T06:55:38.000Z | 2021-12-25T15:18:54.000Z | lib/src/ui/story_view/utils.dart | codenameakshay/ariel-news-app | 2f3baaa3fd1a8eecce1f2bda3ccf5fcfe1ae7909 | [
"BSD-3-Clause"
] | 13 | 2020-05-17T18:39:50.000Z | 2020-07-28T14:55:29.000Z | lib/src/ui/story_view/utils.dart | codenameakshay/ariel-news-app | 2f3baaa3fd1a8eecce1f2bda3ccf5fcfe1ae7909 | [
"BSD-3-Clause"
] | 7 | 2020-05-26T02:01:08.000Z | 2021-09-08T09:13:12.000Z | enum LoadState { loading, success, failure }
| 22.5 | 44 | 0.755556 |
4b03973fda3d849b19772febc5c9089ab2b61d4b | 8,712 | rb | Ruby | spec/models/issue_spec.rb | technoeleganceteam/kanban_on_rails | 6f3e3900c2955d4db28cd118ea27a79c5f0e8ebd | [
"MIT"
] | 47 | 2016-06-07T19:53:53.000Z | 2021-05-29T09:28:11.000Z | spec/models/issue_spec.rb | technoeleganceteam/kanban_on_rails | 6f3e3900c2955d4db28cd118ea27a79c5f0e8ebd | [
"MIT"
] | 17 | 2016-06-08T15:03:19.000Z | 2016-07-13T17:19:57.000Z | spec/models/issue_spec.rb | technoeleganceteam/kanban_on_rails | 6f3e3900c2955d4db28cd118ea27a79c5f0e8ebd | [
"MIT"
] | 11 | 2016-06-08T15:06:42.000Z | 2020-01-08T07:31:05.000Z | require 'rails_helper'
RSpec.describe Issue, :type => :model do
let(:user) { create :user }
let(:issue) { create :issue }
let(:user_to_issue_connection) { create :user_to_issue_connection, :user => user, :issue => issue }
describe '#sync_to_github' do
context 'when new issue' do
before do
stub_request(:patch, 'https://api.github.com/repos/some/project/issues/').
with(:body => '{"labels":[]}', :headers => { 'Accept' => 'application/vnd.github.v3+json',
'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Authorization' => 'token token',
'Content-Type' => 'application/json', 'User-Agent' => 'Octokit Ruby Gem 4.3.0' }).
to_return(:status => 200, :body => '', :headers => {})
stub_request(:post, 'https://api.github.com/repos/some/project/issues').
with(:body => '{"labels":[],"title":"Some title"}',
:headers => { 'Accept' => 'application/vnd.github.v3+json',
'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Authorization' => 'token token', 'Content-Type' => 'application/json',
'User-Agent' => 'Octokit Ruby Gem 4.3.0' }).
to_return(:status => 200, :headers => {}, :body => '')
user.authentications.create! :uid => 123, :provider => 'github', :token => 'token'
end
it { expect(user_to_issue_connection.issue.sync_to_github(user.id)).to eq true }
end
context 'when existing issue' do
before do
stub_request(:patch, 'https://api.github.com/repos/some/project/issues/').
with(:body => '{"labels":[]}', :headers => { 'Accept' => 'application/vnd.github.v3+json',
'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3', 'Authorization' => 'token token',
'Content-Type' => 'application/json', 'User-Agent' => 'Octokit Ruby Gem 4.3.0' }).
to_return(:status => 200, :body => '', :headers => {})
stub_request(:patch, 'https://api.github.com/repos/some/project/issues/1').
with(:body => '{"title":"Some title","body":null,"labels":[],"state":"open"}',
:headers => { 'Accept' => 'application/vnd.github.v3+json',
'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Authorization' => 'token token', 'Content-Type' => 'application/json',
'User-Agent' => 'Octokit Ruby Gem 4.3.0' }).
to_return(:status => 200, :body => '', :headers => {})
user.authentications.create! :uid => 123, :provider => 'github', :token => 'token'
user_to_issue_connection.issue.update_attributes(:github_issue_number => 1)
end
it { expect(user_to_issue_connection.issue.sync_to_github(user.id)).to eq '' }
end
end
describe '#sync_to_gitlab' do
context 'when new issue' do
before do
stub_request(:post, 'https://gitlab.com/api/v3/projects//issues').
with(:body => 'title=Some%20title&description=&labels=',
:headers => { 'Accept' => 'application/json', 'Private-Token' => 'token' }).
to_return(:status => 200, :headers => {}, :body => { :id => '1' }.to_json.to_s)
user.authentications.create! :uid => 123, :provider => 'gitlab', :token => 'token',
:gitlab_private_token => 'token'
end
it { expect(user_to_issue_connection.issue.sync_to_gitlab(user.id)).to eq true }
end
context 'when existing issue' do
before do
stub_request(:put, 'https://gitlab.com/api/v3/projects//issues/1').
with(:body => 'title=Some%20title&description=&labels=',
:headers => { 'Accept' => 'application/json', 'Private-Token' => 'token' }).
to_return(:status => 200, :body => '', :headers => {})
user.authentications.create! :uid => 123, :provider => 'gitlab', :token => 'token',
:gitlab_private_token => 'token'
user_to_issue_connection.issue.update_attributes(:gitlab_issue_id => 1)
end
it { expect(user_to_issue_connection.issue.sync_to_gitlab(user.id)).to eq false }
end
end
describe '#sync_to_bitbucket' do
context 'when new issue' do
before do
stub_request(:post, 'https://api.bitbucket.org/2.0/repositories/username/slug/issues/').
with(:body => '{"title":"Some title"}',
:headers => { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Authorization' => /.*/, 'Content-Type' => 'application/json',
'User-Agent' => 'BitBucket Ruby Gem 0.1.7' }).
to_return(:status => 200, :body => {}.to_json.to_s, :headers => {})
user.authentications.create! :uid => 123, :provider => 'bitbucket', :token => 'token'
user_to_issue_connection.issue.project.update_attributes(:bitbucket_owner => 'username',
:bitbucket_slug => 'slug')
end
it { expect(user_to_issue_connection.issue.sync_to_bitbucket(user.id)).to eq nil }
end
context 'when existing issue' do
before do
stub_request(:put, 'https://api.bitbucket.org/1.0/repositories/username/slug/issues/1/').
with(:body => '{"title":"Some title","content":null}',
:headers => { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Authorization' => /.*/, 'Content-Type' => 'application/json',
'User-Agent' => 'BitBucket Ruby Gem 0.1.7' }).
to_return(:status => 200, :body => {}.to_json.to_s, :headers => {})
user.authentications.create! :uid => 123, :provider => 'bitbucket', :token => 'token'
user_to_issue_connection.issue.project.update_attributes(:bitbucket_owner => 'username',
:bitbucket_slug => 'slug')
user_to_issue_connection.issue.update_attributes(:bitbucket_issue_id => 1)
end
it { expect(user_to_issue_connection.issue.sync_to_bitbucket(user.id).size).to eq 0 }
end
context 'when BitBucket::Error::NotFound' do
before do
stub_request(:post, 'https://api.bitbucket.org/2.0/repositories/username/slug/issues/').
with(:body => '{"title":"Some title"}',
:headers => { 'Accept' => '*/*', 'Accept-Encoding' => 'gzip;q=1.0,deflate;q=0.6,identity;q=0.3',
'Authorization' => /.*/, 'Content-Type' => 'application/json',
'User-Agent' => 'BitBucket Ruby Gem 0.1.7' }).
to_return(:status => 200, :body => {}.to_json.to_s, :headers => {})
user.authentications.create! :uid => 123, :provider => 'bitbucket', :token => 'token'
user_to_issue_connection.issue.project.update_attributes(:bitbucket_owner => 'username',
:bitbucket_slug => 'slug')
allow_any_instance_of(BitBucket::Issues).to receive(:create).and_raise(BitBucket::Error::NotFound.new({}))
end
it { expect(user_to_issue_connection.issue.sync_to_bitbucket(user.id)).to eq nil }
end
end
describe '#save' do
context 'without any backlog columns' do
it { expect(issue.tap { |i| i.tags = ['new'] }.save).to eq true }
end
context 'with backlog column' do
before do
board = create :board, :projects => [issue.project]
create :section, :include_all => true, :board => board
create :column, :backlog => true, :board => board, :tags => []
end
it { expect(issue.tap { |i| i.tags = ['new'] }.save).to eq true }
end
end
describe '#url_from_provider' do
context 'when issue from github' do
before do
issue.update_attributes(:github_issue_id => 1,
:github_issue_html_url => 'https://github.com/foo/issues/1')
end
it { expect(issue.url_from_provider).to eq 'https://github.com/foo/issues/1' }
end
context 'when issue from gitlab' do
before { issue.update_attributes(:gitlab_issue_id => 1, :gitlab_issue_number => 1) }
it { expect(issue.url_from_provider).to eq 'https://gitlab.com//issues/1' }
end
context 'when issue from github' do
before do
issue.update_attributes(:bitbucket_issue_id => 1)
end
it { expect(issue.url_from_provider).to eq 'https://bitbucket.com//issues/1' }
end
end
describe '#issue_info_for_report' do
before { @issue = create :issue, :gitlab_issue_id => '1' }
it { expect(@issue.info_for_report).to eq "Some title ([#](https://gitlab.com//issues/))\n" }
end
describe '#tag_color' do
before do
@issue = create :issue, :github_labels => [[[], %w(name foo), %w(color bar)]], :tags => ['foo']
end
it 'return css rules' do
expect(@issue.tag_color('foo')).to eq 'background-color: #bar;color:black;'
end
end
end
| 41.684211 | 114 | 0.60101 |
ba99149bdb5aee74e303d589ef8dc3dbd32ad019 | 3,332 | sql | SQL | sql/wlblazers_upgrade.sql | bopopescu/Heimdallr | 793b5b0242788e7212a7b10e9e6a5bdaef7a73b2 | [
"Apache-2.0"
] | null | null | null | sql/wlblazers_upgrade.sql | bopopescu/Heimdallr | 793b5b0242788e7212a7b10e9e6a5bdaef7a73b2 | [
"Apache-2.0"
] | null | null | null | sql/wlblazers_upgrade.sql | bopopescu/Heimdallr | 793b5b0242788e7212a7b10e9e6a5bdaef7a73b2 | [
"Apache-2.0"
] | 1 | 2020-07-22T08:57:53.000Z | 2020-07-22T08:57:53.000Z | -- ------------------------------------------------------------------------------------
-- ---------------------------- Table structure modify
-- ------------------------------------------------------------------------------------
/******************************* update Date: 2019-11-04 *******************************/
alter table db_cfg_oracle_dg add(`primary_db_dest` tinyint(2));
alter table db_cfg_oracle_dg add(`standby_db_dest` tinyint(2));
/******************************* update Date: 2019-11-14 *******************************/
alter table oracle_tablespace modify (max_rate float(10,2));
alter table oracle_tablespace_his modify (max_rate float(10,2));
-- ----------------------------
-- Table structure for sqlserver_space
-- ----------------------------
DROP TABLE IF EXISTS `sqlserver_space`;
CREATE TABLE `sqlserver_space` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`server_id` smallint(4) NOT NULL DEFAULT '0',
`host` varchar(50) NOT NULL DEFAULT '0',
`port` varchar(30) NOT NULL DEFAULT '0',
`tags` varchar(50) NOT NULL DEFAULT '',
`db_name` varchar(100) NOT NULL,
`status` varchar(20) NOT NULL,
`total_size` bigint(18) NOT NULL DEFAULT '0',
`used_size` bigint(18) NOT NULL DEFAULT '0',
`max_rate` float(10,2) NOT NULL DEFAULT '0',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_server_id` (`server_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `sqlserver_session`;
CREATE TABLE `sqlserver_session` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`server_id` int(10) NOT NULL,
`snap_id` bigint(20) DEFAULT NULL,
`end_time` varchar(20) DEFAULT NULL,
`total_session` bigint(20) DEFAULT NULL,
`active_session` bigint(20) DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10000 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `sqlserver_hit`;
CREATE TABLE `sqlserver_hit` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`server_id` int(10) NOT NULL,
`snap_id` bigint(20) DEFAULT NULL,
`end_time` varchar(20) DEFAULT NULL,
`type` varchar(50) DEFAULT NULL,
`rate` float(10,2) DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10000 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `sqlserver_log`;
CREATE TABLE `sqlserver_log` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`server_id` int(10) NOT NULL,
`snap_id` bigint(20) DEFAULT NULL,
`end_time` varchar(20) DEFAULT NULL,
`cntr_value` bigint(20) DEFAULT NULL,
`incr_value` bigint(20) DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10000 DEFAULT CHARSET=utf8;
/******************************* update Date: 2019-11-17 *******************************/
alter table db_cfg_oracle_dg rename column network_card to network_card_s;
alter table db_cfg_oracle_dg add(network_card_p varchar(100));
-- ------------------------------------------------------------------------------------
-- ---------------------------- Init data modify
-- ------------------------------------------------------------------------------------ | 38.744186 | 90 | 0.598139 |
a478f75b51b8b0b9a41846bff3744ebf26a05802 | 666 | php | PHP | backend/services/SiteService.php | robert589/justgiveit | 50c6cf6728170764b14e18ddec40365d16f50156 | [
"BSD-3-Clause"
] | 1 | 2018-04-05T06:10:02.000Z | 2018-04-05T06:10:02.000Z | backend/services/SiteService.php | robert589/justgiveit | 50c6cf6728170764b14e18ddec40365d16f50156 | [
"BSD-3-Clause"
] | null | null | null | backend/services/SiteService.php | robert589/justgiveit | 50c6cf6728170764b14e18ddec40365d16f50156 | [
"BSD-3-Clause"
] | 1 | 2019-12-24T10:14:51.000Z | 2019-12-24T10:14:51.000Z | <?php
namespace backend\services;
use backend\vos\SiteVoBuilder;
use backend\daos\SiteDao;
class SiteService {
private $site_dao;
public function __construct() {
$this->site_dao = new SiteDao();
}
public function getHomeInfo() {
$builder = new SiteVoBuilder();
$builder->setPopularTags($this->site_dao->getMostPopularTags());
$builder->setItemsByCountry($this->site_dao->getItemsByCountry());
$builder->setItemsByDay($this->site_dao->getItemsByDay());
$builder->setRegisteredUserByCountry($this->site_dao->getRegisteredUserByCountry());
return $builder->build();
}
} | 30.272727 | 92 | 0.657658 |
456e3af2e6de3bd6d92f5b1c4f27afbb637bd3de | 126 | py | Python | boa3_test/test_sc/interop_test/storage/StorageDeleteStrKey.py | hal0x2328/neo3-boa | 6825a3533384cb01660773050719402a9703065b | [
"Apache-2.0"
] | 25 | 2020-07-22T19:37:43.000Z | 2022-03-08T03:23:55.000Z | boa3_test/test_sc/interop_test/storage/StorageDeleteStrKey.py | hal0x2328/neo3-boa | 6825a3533384cb01660773050719402a9703065b | [
"Apache-2.0"
] | 419 | 2020-04-23T17:48:14.000Z | 2022-03-31T13:17:45.000Z | boa3_test/test_sc/interop_test/storage/StorageDeleteStrKey.py | hal0x2328/neo3-boa | 6825a3533384cb01660773050719402a9703065b | [
"Apache-2.0"
] | 15 | 2020-05-21T21:54:24.000Z | 2021-11-18T06:17:24.000Z | from boa3.builtin import public
from boa3.builtin.interop.storage import delete
@public
def Main(key: str):
delete(key)
| 15.75 | 47 | 0.761905 |
a416f29aa071d409b9e4e32f6e17dfae9c43b7f5 | 998 | rs | Rust | binrw_derive/src/parser/types/enum_error_mode.rs | dmgolembiowski/binrw | 9779ff3749d0576a46b544373442ce9d9af2914c | [
"MIT"
] | 123 | 2020-10-31T20:30:35.000Z | 2022-03-21T12:51:43.000Z | binrw_derive/src/parser/types/enum_error_mode.rs | dmgolembiowski/binrw | 9779ff3749d0576a46b544373442ce9d9af2914c | [
"MIT"
] | 72 | 2020-10-31T20:32:34.000Z | 2022-03-30T08:42:08.000Z | binrw_derive/src/parser/types/enum_error_mode.rs | dmgolembiowski/binrw | 9779ff3749d0576a46b544373442ce9d9af2914c | [
"MIT"
] | 15 | 2021-01-24T23:59:05.000Z | 2022-03-07T13:14:31.000Z | use crate::parser::{read::attrs, KeywordToken, TrySet};
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub(crate) enum EnumErrorMode {
Default,
ReturnAllErrors,
ReturnUnexpectedError,
}
impl Default for EnumErrorMode {
fn default() -> Self {
Self::Default
}
}
impl From<attrs::ReturnAllErrors> for EnumErrorMode {
fn from(_: attrs::ReturnAllErrors) -> Self {
Self::ReturnAllErrors
}
}
impl From<attrs::ReturnUnexpectedError> for EnumErrorMode {
fn from(_: attrs::ReturnUnexpectedError) -> Self {
Self::ReturnUnexpectedError
}
}
impl<T: Into<EnumErrorMode> + KeywordToken> TrySet<EnumErrorMode> for T {
fn try_set(self, to: &mut EnumErrorMode) -> syn::Result<()> {
if *to == EnumErrorMode::Default {
*to = self.into();
Ok(())
} else {
Err(syn::Error::new(
self.keyword_span(),
"conflicting error handling keyword",
))
}
}
}
| 24.341463 | 73 | 0.596192 |
5d2ae93d56c7a02e788a2ad9a65b4c3e67236086 | 6,034 | cpp | C++ | lld/stm32f4x/rcc/hw_rcc_sys_ctrl.cpp | brandonbraun653/Thor_STM32 | 2aaba95728936b2d5784e99b96c208a94e3cb8df | [
"MIT"
] | null | null | null | lld/stm32f4x/rcc/hw_rcc_sys_ctrl.cpp | brandonbraun653/Thor_STM32 | 2aaba95728936b2d5784e99b96c208a94e3cb8df | [
"MIT"
] | 36 | 2019-03-24T14:43:25.000Z | 2021-01-11T00:05:30.000Z | lld/stm32f4x/rcc/hw_rcc_sys_ctrl.cpp | brandonbraun653/Thor | 46e022f1791c8644955135c630fdd12a4296e44d | [
"MIT"
] | null | null | null | /********************************************************************************
* File Name:
* hw_rcc_sys_ctrl.cpp
*
* Description:
* System clock controller implementation
*
* 2021 | Brandon Braun | [email protected]
*******************************************************************************/
/* Chimera Includes */
#include <Chimera/assert>
#include <Chimera/common>
#include <Chimera/clock>
/* Driver Includes */
#include <Thor/cfg>
#include <Thor/lld/common/cortex-m4/system_time.hpp>
#include <Thor/lld/interface/inc/rcc>
#include <Thor/lld/interface/inc/power>
#include <Thor/lld/interface/inc/flash>
#include <Thor/lld/interface/inc/interrupt>
#include <Thor/lld/stm32f4x/rcc/hw_rcc_prv.hpp>
namespace Thor::LLD::RCC
{
/*-------------------------------------------------------------------------------
Static Data
-------------------------------------------------------------------------------*/
static SystemClock s_system_clock;
/*-------------------------------------------------------------------------------
SystemClock Class Implementation
-------------------------------------------------------------------------------*/
SystemClock *getCoreClockCtrl()
{
return &s_system_clock;
}
SystemClock::SystemClock()
{
initialize();
}
SystemClock::~SystemClock()
{
}
void SystemClock::enableClock( const Chimera::Clock::Bus clock )
{
auto isrMask = INT::disableInterrupts();
switch ( clock )
{
case Chimera::Clock::Bus::HSE:
HSEON::set( RCC1_PERIPH, CR_HSEON );
while ( !HSERDY::get( RCC1_PERIPH ) )
{
;
}
break;
case Chimera::Clock::Bus::HSI16:
enableHSI();
break;
case Chimera::Clock::Bus::LSI:
enableLSI();
break;
default:
RT_HARD_ASSERT( false );
break;
}
INT::enableInterrupts( isrMask );
}
Chimera::Status_t SystemClock::configureProjectClocks()
{
/*-------------------------------------------------
Set flash latency to a safe value for all possible
clocks. This will slow down the configuration, but
this is only performed once at startup.
-------------------------------------------------*/
FLASH::setLatency( 15 );
/*------------------------------------------------
Not strictly necessary, but done because this
config function uses the max system clock.
------------------------------------------------*/
PWR::setOverdriveMode( true );
/*------------------------------------------------
Configure the system clocks to max performance
------------------------------------------------*/
constexpr size_t hsiClkIn = 16000000; // 16 MHz
constexpr size_t targetSysClk = 120000000; // 120 MHz
constexpr size_t targetUSBClk = 48000000; // 48 MHz
constexpr size_t targetVcoClk = 2 * targetSysClk; // 240 MHz
Chimera::Status_t cfgResult = Chimera::Status::OK;
ClockTreeInit clkCfg;
clkCfg.clear();
/* Select which clocks to turn on */
clkCfg.enabled.hsi = true; // Needed for transfer of clock source
clkCfg.enabled.lsi = true; // Allows IWDG use
clkCfg.enabled.pll_core_clk = true; // Will drive sys off PLL
clkCfg.enabled.pll_core_q = true; // USB 48 MHz clock
/* Select clock mux routing */
clkCfg.mux.pll = Chimera::Clock::Bus::HSI16;
clkCfg.mux.sys = Chimera::Clock::Bus::PLLP;
clkCfg.mux.usb48 = Chimera::Clock::Bus::PLLQ;
/* Divisors from the system clock */
clkCfg.prescaler.ahb = 1;
clkCfg.prescaler.apb1 = 4;
clkCfg.prescaler.apb2 = 2;
/* Figure out PLL configuration settings */
cfgResult |= calculatePLLBaseOscillator( PLLType::CORE, hsiClkIn, targetVcoClk, clkCfg );
cfgResult |= calculatePLLOuputOscillator( PLLType::CORE, PLLOut::P, targetVcoClk, targetSysClk, clkCfg );
cfgResult |= calculatePLLOuputOscillator( PLLType::CORE, PLLOut::Q, targetVcoClk, targetUSBClk, clkCfg );
RT_HARD_ASSERT( cfgResult == Chimera::Status::OK );
RT_HARD_ASSERT( configureClockTree( clkCfg ) );
/*-------------------------------------------------
Verify the user's target clocks have been achieved
-------------------------------------------------*/
size_t sys_clk = getSystemClock();
RT_HARD_ASSERT( sys_clk == targetSysClk );
/*-------------------------------------------------
Trim the flash latency back to a performant range
now that the high speed clock has been configured.
-------------------------------------------------*/
FLASH::setLatency( FLASH::LATENCY_AUTO_DETECT );
/*-------------------------------------------------
Make sure the rest of the system knows about the
new clock frequency.
-------------------------------------------------*/
CortexM4::Clock::updateCoreClockCache( sys_clk );
return cfgResult;
}
Chimera::Status_t SystemClock::setCoreClockSource( const Chimera::Clock::Bus src )
{
return select_system_clock_source( src );
}
size_t SystemClock::getClockFrequency( const Chimera::Clock::Bus clock )
{
return getBusFrequency( clock );
}
size_t SystemClock::getPeriphClock( const Chimera::Peripheral::Type periph, const std::uintptr_t address )
{
/*-------------------------------------------------
Input protection
-------------------------------------------------*/
auto registry = getPCCRegistry( periph );
if ( !registry || !registry->clockSource || !registry->getResourceIndex )
{
return INVALID_CLOCK;
}
/*-------------------------------------------------
Perform the lookup
-------------------------------------------------*/
size_t idx = registry->getResourceIndex( address );
if ( idx == INVALID_RESOURCE_INDEX )
{
return INVALID_CLOCK;
}
return getClockFrequency( registry->clockSource[ idx ] );
}
} // namespace Thor::LLD::RCC
| 31.427083 | 109 | 0.513755 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.