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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
58b4321075f217d265fe804613f21253003b227a | 7,331 | php | PHP | resources/views/layouts/admin-main.blade.php | alibanana/97Dev-Venidici-Laravel | d99aa53af930638e3d413cd5899174256dbe1243 | [
"MIT"
] | 1 | 2021-04-15T15:40:27.000Z | 2021-04-15T15:40:27.000Z | resources/views/layouts/admin-main.blade.php | alibanana/97Dev-Venidici-Laravel | d99aa53af930638e3d413cd5899174256dbe1243 | [
"MIT"
] | null | null | null | resources/views/layouts/admin-main.blade.php | alibanana/97Dev-Venidici-Laravel | d99aa53af930638e3d413cd5899174256dbe1243 | [
"MIT"
] | 1 | 2021-04-24T07:45:51.000Z | 2021-04-24T07:45:51.000Z | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" type="text/css" href="/css/admin.css">
<title>@yield('title')</title>
<!-- Custom fonts for this template-->
<link href="/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link
href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet">
<!-- Custom styles for this template-->
<link href="/css/sb-admin-2.min.css" rel="stylesheet">
<!-- INDEX CSS -->
<link rel="stylesheet" type="text/css" href="/css/index.css">
<!-- wow js -->
<link rel="stylesheet" href="/WOW-master/css/libs/animate.css">
<style>
#upload-button{
background-color: #fa7600;
color: white;
padding: 8px 15px;
border-radius: 0.3rem;
cursor: pointer;
}
</style>
</head>
<body id="page-top">
<!-- Page Wrapper -->
<div id="wrapper">
<x-AdminSidebar/>
<!-- Content Wrapper -->
<div id="content-wrapper" class="d-flex flex-column">
@yield('container')
<x-AdminFooter />
</div>
<!-- End of Content Wrapper -->
</div>
<!-- End of Page Wrapper -->
<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
<!-- Logout Modal-->
<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<form action="{{ route('logout') }}" method="POST">
@csrf
<button class="btn btn-primary" type="submit">Logout</button>
</form>
</div>
</div>
</div>
</div>
<!-- password Modal-->
<div class="modal fade" id="passwordModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Change password</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@if (session()->has('error_validation_on_password_modal'))
<div class="p-3 mt-2 mb-0">
<div class="alert alert-danger alert-dismissible fade show m-0" role="alert" style="font-size: 18px">
{{ session()->get('error_validation_on_password_modal') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close" style="font-size: 26px">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
@endif
<form method="POST" action="">
@csrf
{{ method_field('PUT') }}
<div class="modal-body">
<h6 class="modal-title" id="exampleModalLabel">Old password</h6>
<div class="form-group mt-2">
<input type="password" name="old_password" class="form-control form-control-user"
id="exampleInputPassword" placeholder="Insert your old password">
@error('old_password')
<span class="invalid-feedback" role="alert" style="display: block !important;">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<h6 class="modal-title" id="exampleModalLabel">New password</h6>
<div class="form-group mt-2">
<input type="password" name="password" class="form-control form-control-user"
id="exampleInputPassword" placeholder="Insert your new password">
@error('password')
<span class="invalid-feedback" role="alert" style="display: block !important;">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<h6 class="modal-title" id="exampleModalLabel">Confirm new password</h6>
<div class="form-group mt-2">
<input type="password" name="password_confirmation" class="form-control form-control-user"
id="exampleInputPassword" placeholder="Confirm your new password">
@error('password_confirmation')
<span class="invalid-feedback" role="alert" style="display: block !important;">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
<button class="btn btn-primary" type="submit">Change Password</button>
</div>
</form>
</div>
</div>
</div>
<!-- Bootstrap core JavaScript-->
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Core plugin JavaScript-->
<script src="/vendor/jquery-easing/jquery.easing.min.js"></script>
<!-- Custom scripts for all pages-->
<script src="/js/sb-admin-2.min.js"></script>
<!-- Page level plugins -->
<script src="/vendor/chart.js/Chart.min.js"></script>
<!-- Page level custom scripts -->
<script src="/js/demo/chart-area-demo.js"></script>
<script src="/js/demo/chart-pie-demo.js"></script>
<!-- wow js script -->
<script src="/WOW-master/dist/wow.min.js"></script>
<script>
new WOW().init();
</script>
@yield('additional-scripts')
</body>
</html> | 40.502762 | 124 | 0.51139 |
ff9c82677fb5a3e754e69092ed0617651e78b4f1 | 10,124 | py | Python | ldapper.py | shellster/LDAPPER | 701094d1ce6ce7bcc6eb4069d720d49ea5478a15 | [
"MIT"
] | 163 | 2017-12-02T13:15:07.000Z | 2022-03-31T09:21:06.000Z | ldapper.py | shellster/LDAPPER | 701094d1ce6ce7bcc6eb4069d720d49ea5478a15 | [
"MIT"
] | 1 | 2021-09-14T21:58:27.000Z | 2021-11-30T16:51:45.000Z | ldapper.py | shellster/LDAPPER | 701094d1ce6ce7bcc6eb4069d720d49ea5478a15 | [
"MIT"
] | 13 | 2018-03-07T13:23:59.000Z | 2021-07-09T00:39:46.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Version 1.6
import argparse
import json
import os
import re
import sys
import yaml
import colorama
from queries import custom_search
from utilities import escape_ldap
from ldap_connector import LDAP3Connector
from ldap_connector import ImpacketLDAPConnector
#Python 2 message
if sys.version_info[0] == 2:
print("Python 2 is no longer supported. Please upgrade.")
exit(-1)
colorama.init()
def get_epilog(menu, parent=''):
epilog = ''
if parent == '':
epilog = 'Custom Searches:\n'
for i, entry in enumerate(menu):
number = str(i + 1).rjust(2) if parent == '' else parent + str(i + 1)
epilog += '%s%s%s) %s\n' % (((parent.count('.') + 1) * '\t'), '*' if 'untested' in entry else ' ', number, entry['help'])
if 'children' in entry and len(entry['children']):
epilog += get_epilog(entry['children'], number + '.')
if parent == '':
epilog += '\nStarred items have never been tested in an environment where they could be verified, so please let me know if they work.'
return epilog
def get_canned_search(menu, args):
return_data = {}
if re.match('^[0-9.]*[0-9]$', args.search):
try:
if args.search.count('.') > 0:
option = [int(x) - 1 for x in args.search.split('.')]
for i,entry in enumerate(option):
if i == (len(option) - 1):
return_data = menu[entry]
else:
menu = menu[entry]['children']
else:
return_data = menu[int(args.search) - 1]
except:
pass
if return_data != {}:
if 'options' in return_data and len(return_data['options']) > 0:
answers = []
for i,option in enumerate(return_data['options']):
if args.advanced and len(args.advanced) > i and re.match(option['regex'], args.advanced[i]):
answers.append(escape_ldap(args.advanced[i]))
continue
while True:
answer = input('%s: ' % option['question'])
if re.match(option['regex'], answer):
answers.append(escape_ldap(answer))
break
return_data['ldap'] = return_data['ldap'].format(*answers)
return return_data
class OverrideParser(argparse.ArgumentParser):
def error(self, message):
if "following arguments are required" in message:
self.print_help()
sys.exit(-1)
else:
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(-1)
parser = OverrideParser(description="AD LDAP Command Line Searching that doesn't suck.", epilog=get_epilog(custom_search), formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--domain', '-D', help='Domain', required=True)
parser.add_argument('--user', '-U', help='Username', required=True)
parser.add_argument('--password', '-P', help='Password or LM:NTLM formatted hash', required=True)
parser.add_argument('--server', '-S', help='DC IP or resolvable name', required=True)
parser.add_argument('--basedn', '-b', help='Base DN should typically be "dc=", followed by the long domain name with periods replaced with ",dc=". Will attempt to derive it if not provided from the LDAP server.', default='')
parser.add_argument('--search', '-s', help='LDAP search string or number indicating custom search from "Custom Searches" list. Use "-" for read from stdin.', required=True)
parser.add_argument('--maxrecords', '-m', help='Maximum records to return (Default is 100), 0 means all.', default=100, type=int)
parser.add_argument('--pagesize', '-p', help='Number of records to return on each pull (Default is 10). Should be <= max records.', default=10, type=int)
parser.add_argument('--delay', '-d', help='Millisecond delay between paging requests (Defaults to 0).', default=0, type=int)
parser.add_argument('--format', '-f', help='Format of output (Default is "plain"), can be: plain, json. json_tiny', default='plain', choices=['plain', 'json', 'json_tiny'])
parser.add_argument('--encryption', '-n', help="3) Connect to 636 TLS (Default); 2) Connect 389 No TLS, but attempt STARTTLS and fallback as needed (not available with impacket); 1) Connect to 389, Force Plaintext", default=3, type=int, choices=[1, 2, 3])
parser.add_argument('--advanced', '-a', help="Advanced way to pass options for canned searches that prompt for additional input (for multiple prompts, pass argument in the order of prompting)", nargs='*')
parser.add_argument('--outfile', '-o', help="Output File (if specified output will be routed here instead of stdout [Can prevent encoding errors in Windows])", default=None, type=str)
parser.add_argument("--engine", "-e", help='Pick the engine to use (Defaults to "ldap3"). SEE OPSEC NOTES!', default='ldap3', choices=["ldap3", "impacket"])
parser.add_argument('attributes', metavar='attribute', nargs='*', help='Attributes to return (Defaults to all for custom query. For canned queries, pass a "*" to get all attributes instead of default ones.)')
args = parser.parse_args()
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
if args.encryption == 2 and args.engine == "impacket":
print(f'{colorama.Fore.RED}Error: Cannot section --encryption to 2 when using --engine of "impacket"{colorama.Style.RESET_ALL}', file=sys.stderr)
parser.print_help()
sys.exit(2)
if args.search == '-':
if os.isatty(0):
parser.print_help()
sys.exit(3)
args.search = sys.stdin.read()
if args.delay < 0:
print(f'{colorama.Fore.RED}Error: "delay" must be 0 or greater{colorama.Style.RESET_ALL}', file=sys.stderr)
parser.print_help()
sys.exit(4)
pagesize = 10 if args.pagesize <= 0 else args.pagesize
maxrecords = 100 if args.maxrecords < 0 else args.maxrecords
pagesize = min(maxrecords, pagesize) if maxrecords != 0 else pagesize
Engine = None
if args.engine == "ldap3":
Engine = LDAP3Connector
else:
Engine = ImpacketLDAPConnector
if re.match('[0-9.]*[0-9]', args.search):
canned_option = get_canned_search(custom_search, args)
if canned_option == {}:
parser.print_help()
print(f'{colorama.Fore.RED}Error: You attempted to select a canned search option that is not valid.{colorama.Style.RESET_ALL}', file=sys.stderr)
exit(5)
args.search = canned_option['ldap']
if 'filter' in canned_option and len(canned_option['filter']) > 1 and args.attributes == []:
args.attributes = canned_option['filter']
else:
if args.search[0] != '(' and args.search[-1] != ')':
args.search = f'({args.search})'
if len(args.attributes) > 0:
if len(args.attributes) == 1 and args.attributes[0].strip() == '*':
args.attributes = []
else:
args.attributes.append('cn')
args.attributes = set(map(str.lower, args.attributes))
if args.outfile:
try:
out = open(args.outfile, 'wb')
except Exception:
print(f'{colorama.Fore.RED}Error: Unable to open or create specified output file.{colorama.Style.RESET_ALL}', file=sys.stderr)
exit(6)
else:
out = sys.stdout.buffer
try:
records_found = False
with Engine(args.server, args.encryption, args.domain, args.user, args.password, args.basedn, pagesize, maxrecords, args.delay) as engine:
for i, record in enumerate(engine.search(args.search, args.attributes)):
records_found = True
if args.format in ['json', 'json_tiny']:
if i == 0:
out.write(b"[")
if args.format == 'json':
out.write(b"\n")
else:
out.write(b",")
if args.format == "json":
out.write(b"\n")
if args.format == 'json':
out.write(json.dumps(record, indent=4, sort_keys=True).encode("utf-8") + b"\n")
elif args.format == 'json_tiny':
out.write(json.dumps(record, ensure_ascii=False).encode("utf-8"))
else:
out.write(record['cn'].encode('utf-8') + b'\n')
for key in record:
if key != "cn":
if isinstance(record[key], list):
out.write((f" {key}:\n " + "\n ".join(record[key]) + "\n").encode("utf-8"))
else:
out.write(f" {key}: {record[key]}\n".encode("utf-8"))
out.write(b"\n")
if maxrecords > 0 and i >= maxrecords:
break
if not records_found:
print(f'{colorama.Fore.YELLOW}NOTICE: No results were returned for your query{colorama.Style.RESET_ALL}', file=sys.stderr)
elif args.format in ['json', 'json_tiny']:
out.write(b"]\n")
out.flush()
if maxrecords > 0 and i >= maxrecords:
print(f'{colorama.Fore.YELLOW}NOTICE: Search returned at least as many records as maxrecords argument allowed. You may be missing results.{colorama.Style.RESET_ALL}', file=sys.stderr)
if args.outfile:
try:
out.close()
except Exception:
pass
except Exception as ex:
import logging
logging.exception("")
print(f'{colorama.Fore.RED}Error: {ex}{colorama.Style.RESET_ALL}', file=sys.stderr) | 43.264957 | 257 | 0.575761 |
dda74c0116b212182af8a0af00619c827977711d | 472 | java | Java | server/src/main/java/com/onekki/ohmysite/module/sys/service/IUserService.java | Onekki/ohmysite | c3713476eccf9cdeb4e6f459f4d677adeac18a5f | [
"Apache-2.0"
] | null | null | null | server/src/main/java/com/onekki/ohmysite/module/sys/service/IUserService.java | Onekki/ohmysite | c3713476eccf9cdeb4e6f459f4d677adeac18a5f | [
"Apache-2.0"
] | 1 | 2022-02-09T22:16:58.000Z | 2022-02-09T22:16:58.000Z | server/src/main/java/com/onekki/ohmysite/module/sys/service/IUserService.java | Onekki/ohmysite | c3713476eccf9cdeb4e6f459f4d677adeac18a5f | [
"Apache-2.0"
] | null | null | null | package com.onekki.ohmysite.module.sys.service;
import com.onekki.ohmysite.module.sys.entity.Perm;
import com.onekki.ohmysite.module.sys.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author onekki
* @since 2019-08-30
*/
public interface IUserService extends IService<User> {
User authLogin(String username, String password);
User getByUP(String username, String password);
}
| 22.47619 | 59 | 0.741525 |
dac061b0fc7c7166d0da7e0fbe95db348fefe3a5 | 335 | ts | TypeScript | src/app/r209/r209.module.ts | mgechev/preload-all-stress-test | fb9184bfd81fb7dbd20ae493d2e679c30e396e43 | [
"MIT"
] | 6 | 2021-01-19T18:46:13.000Z | 2021-02-03T04:20:53.000Z | src/app/r209/r209.module.ts | mgechev/preload-all-stress-test | fb9184bfd81fb7dbd20ae493d2e679c30e396e43 | [
"MIT"
] | null | null | null | src/app/r209/r209.module.ts | mgechev/preload-all-stress-test | fb9184bfd81fb7dbd20ae493d2e679c30e396e43 | [
"MIT"
] | null | null | null | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { R209RoutingModule } from './r209-routing.module';
import { R209Component } from './r209.component';
@NgModule({
declarations: [R209Component],
imports: [
CommonModule,
R209RoutingModule
]
})
export class R209Module { }
| 20.9375 | 58 | 0.698507 |
27acb55fbda9ba857e5abdb41bf7393660fb9862 | 4,635 | swift | Swift | Code/FBBridge/Profile/VM/FBProfileViewModel.swift | coderYB/FBKit | 9df0f0a3dc67c17fba997170c96ce9243e18311f | [
"MIT"
] | null | null | null | Code/FBBridge/Profile/VM/FBProfileViewModel.swift | coderYB/FBKit | 9df0f0a3dc67c17fba997170c96ce9243e18311f | [
"MIT"
] | null | null | null | Code/FBBridge/Profile/VM/FBProfileViewModel.swift | coderYB/FBKit | 9df0f0a3dc67c17fba997170c96ce9243e18311f | [
"MIT"
] | 1 | 2020-08-25T12:46:23.000Z | 2020-08-25T12:46:23.000Z | //
// FBProfileViewModel.swift
// FBBridge
//
// Created by three stone 王 on 2019/8/27.
// Copyright © 2019 three stone 王. All rights reserved.
//
import Foundation
import FBViewModel
import RxCocoa
import RxSwift
import FBBean
import FBSign
import FBApi
import FBRReq
import FBCache
import FBObservableMapper
@objc public final class FBProfileBean: NSObject {
@objc public var type: FBProfileType = .space
@objc public var title: String = ""
@objc public static func createProfile(_ type: FBProfileType ,title: String) -> FBProfileBean {
let profile = FBProfileBean()
profile.type = type
profile.title = title
return profile
}
static public func createProfileTypes(_ hasSpace: Bool) -> [FBProfileBean] {
var result: [FBProfileBean] = []
if hasSpace {
for item in FBProfileType.spaceTypes {
result += [FBProfileBean.createProfile(item, title: item.title)]
}
} else {
for item in FBProfileType.types {
result += [FBProfileBean.createProfile(item, title: item.title)]
}
}
return result
}
private override init() {
}
}
@objc (FBProfileType)
public enum FBProfileType : Int{
case about
case userInfo
case setting
case contactUS
case privacy
case focus
case space
case myCircle
case order
case address
case characters
case feedBack
case favor
}
extension FBProfileType {
static var spaceTypes: [FBProfileType] {
if FBConfigure.fetchPType() == .estate {
return [.space,userInfo,.order,.address,.favor,.space,.contactUS,.privacy,.about,.space,.feedBack,.setting]
}
return [.space,userInfo,.space,.contactUS,.privacy,.about,.space,.feedBack,.setting]
}
static var types: [FBProfileType] {
if FBConfigure.fetchPType() == .estate {
return [userInfo,.order,.address,.favor,.contactUS,.privacy,.about,.feedBack,.setting]
}
return [userInfo,.contactUS,.privacy,.about,.feedBack,.setting]
}
var cellHeight: CGFloat {
switch self {
case .space: return 10
default: return 55
}
}
var title: String {
switch self {
case .about: return "关于我们"
case .contactUS: return "联系我们"
case .userInfo: return "用户资料"
case .setting: return "设置"
case .privacy: return "隐私政策"
case .focus: return "我的关注"
case .myCircle: return "我的发布"
case .address: return "地址管理"
case .order: return "订单管理"
case .characters: return "角色信息"
case .feedBack: return "意见建议"
case .favor: return "我的收藏"
default: return ""
}
}
}
struct FBProfileViewModel: FBViewModel {
var input: WLInput
var output: WLOutput
struct WLInput {
let modelSelect: ControlEvent<FBProfileBean>
let itemSelect: ControlEvent<IndexPath>
let hasSpace: Bool
}
struct WLOutput {
let zip: Observable<(FBProfileBean,IndexPath)>
let tableData: BehaviorRelay<[FBProfileBean]> = BehaviorRelay<[FBProfileBean]>(value: [])
let userInfo: Observable<FBUserBean?>
}
init(_ input: WLInput ,disposed: DisposeBag) {
self.input = input
let userInfo: Observable<FBUserBean?> = FBUserInfoCache.default.rx.observe(FBUserBean.self, "userBean")
FBUserInfoCache.default.userBean = FBUserInfoCache.default.queryUser()
FBDictResp(FBApi.fetchProfile)
.mapObject(type: FBUserBean.self)
.map({ FBUserInfoCache.default.saveUser(data: $0) })
.subscribe(onNext: { (_) in })
.disposed(by: disposed)
let zip = Observable.zip(input.modelSelect,input.itemSelect)
self.output = WLOutput(zip: zip, userInfo: userInfo)
self.output.tableData.accept(FBProfileBean.createProfileTypes(input.hasSpace))
}
}
| 22.720588 | 119 | 0.541532 |
076290ece4cda3840e4de74b9bfb252379806b08 | 1,507 | cpp | C++ | src/internal_server.cpp | cbeck88/HexWarfare | 94a70b1889afc2fbd990892ed66be874ac70d1b4 | [
"Apache-2.0"
] | null | null | null | src/internal_server.cpp | cbeck88/HexWarfare | 94a70b1889afc2fbd990892ed66be874ac70d1b4 | [
"Apache-2.0"
] | null | null | null | src/internal_server.cpp | cbeck88/HexWarfare | 94a70b1889afc2fbd990892ed66be874ac70d1b4 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2014 Kristina Simpson <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "asserts.hpp"
#include "internal_server.hpp"
namespace network
{
namespace internal
{
server::server()
{
}
void server::add_peer(std::weak_ptr<base> client)
{
clients_.emplace_back(client);
}
void server::handle_process()
{
// remove any clients which have died
clients_.erase(std::remove_if(clients_.begin(), clients_.end(), [](std::weak_ptr<base> p){ return p.lock() == nullptr; }), clients_.end());
// Take messages from our send queue and send them to each connected client.
game::Update* up = nullptr;
while((up = read_send_queue()) != nullptr) {
for(auto& c : clients_) {
LOG_DEBUG("Writing message(" << up->id() << ") to client");
auto peer = c.lock();
ASSERT_LOG(peer != nullptr, "client has gone away, peer == nullptr");
peer->write_recv_queue(new game::Update(*up));
}
delete up;
}
}
}
}
| 28.980769 | 142 | 0.681486 |
38859b672ebedd7fcb90c9c7a784ef28b8d85061 | 11,639 | swift | Swift | Pods/ZVProgressHUD/ZVProgressHUD/ZVProgressHUDExtensions.swift | Changzw/every-case-demo | 0ba08146fee2904bd2151fcea8041f03b8b86e71 | [
"Apache-2.0"
] | 31 | 2017-07-15T10:55:13.000Z | 2021-06-02T09:14:48.000Z | Pods/ZVProgressHUD/ZVProgressHUD/ZVProgressHUDExtensions.swift | Changzw/every-case-demo | 0ba08146fee2904bd2151fcea8041f03b8b86e71 | [
"Apache-2.0"
] | 11 | 2017-09-28T04:03:06.000Z | 2021-04-08T20:15:08.000Z | Pods/ZVProgressHUD/ZVProgressHUD/ZVProgressHUDExtensions.swift | Changzw/every-case-demo | 0ba08146fee2904bd2151fcea8041f03b8b86e71 | [
"Apache-2.0"
] | 11 | 2017-07-15T10:55:13.000Z | 2021-06-02T09:42:55.000Z | //
// ProgressHUD+Operations.swift
// ZVProgressHUD
//
// Created by zevwings on 2019/9/29.
// Copyright © 2019 zevwings. All rights reserved.
//
#if !os(macOS)
import UIKit
// MARK: - Configuration
public extension ZVProgressHUD {
class func setDisplayStyle(_ displayStyle: DisplayStyle) {
shared.configuration.displayStyle = displayStyle
}
class func setMaskType(_ maskType: MaskType) {
shared.configuration.maskType = maskType
}
class func setCornerRadius(_ cornerRadius: CGFloat) {
shared.configuration.cornerRadius = cornerRadius
}
class func setOffset(_ offset: UIOffset) {
shared.configuration.offset = offset
}
class func setTitleLabelFont(_ font: UIFont) {
shared.configuration.titleLabelFont = font
}
class func setTitleLabelColor(_ color: UIColor?) {
shared.configuration.titleLabelColor = color
}
class func setProgressLabelFont(_ font: UIFont) {
shared.configuration.progressLabelFont = font
}
class func setProgressLabelColor(_ color: UIColor?) {
shared.configuration.progressLabelColor = color
}
class func setProgressLabelHidden(_ isProgressLabelHidden: Bool) {
shared.configuration.isProgressLabelHidden = isProgressLabelHidden
}
class func setStrokeWidth(_ strokeWidth: CGFloat) {
shared.configuration.strokeWidth = strokeWidth
}
class func setIndicatorSize(_ size: CGSize) {
shared.configuration.indicatorSize = size
}
class func setAnimationType(_ animationType: ZVIndicatorView.AnimationType) {
shared.configuration.animationType = animationType
}
class func setContentInsets(_ indets: UIEdgeInsets) {
shared.configuration.contentInsets = indets
}
class func setTitleEdgeInsets(_ indets: UIEdgeInsets) {
shared.configuration.titleEdgeInsets = indets
}
class func setIndicatorEdgeInsets(_ indets: UIEdgeInsets) {
shared.configuration.indicatorEdgeInsets = indets
}
class func setLogo(_ logo: UIImage?) {
shared.configuration.logo = logo
}
class func setLogoSize(_ size: CGSize) {
shared.configuration.logoSize = size
}
}
// MARK: - Props
public extension ZVProgressHUD {
class func setMaxSupportedWindowLevel(_ windowLevel: UIWindow.Level) {
shared.maxSupportedWindowLevel = windowLevel
}
class func setFadeInAnimationTimeInterval(_ timeInterval: TimeInterval) {
shared.fadeInAnimationTimeInterval = timeInterval
}
class func setFadeOutAnimationTImeInterval(_ timeInterval: TimeInterval) {
shared.fadeOutAnimationTImeInterval = timeInterval
}
class func setMinimumDismissTimeInterval(_ timeInterval: TimeInterval) {
shared.minimumDismissTimeInterval = timeInterval
}
class func setMaximumDismissTimeInterval(_ timeInterval: TimeInterval) {
shared.maximumDismissTimeInterval = timeInterval
}
class func setMaximumContentSize(_ size: CGSize) {
shared.maximumContentSize = size
}
}
// MARK: - Handle
public extension ZVProgressHUD {
/// show a toast
///
/// - Parameters:
/// - text: toast content
/// - superview: super view, if superview is nil, show on main window
/// - delayTimeInterval: the view will show delay the `delayTimeInterval`
class func showText(
_ text: String,
in superview: UIView? = nil,
delay delayTimeInterval: TimeInterval = 0.0,
with configuration: Configuration? = nil
) {
shared.internalShow(
displayType: .text(value: text),
in: superview,
delay: delayTimeInterval,
with: configuration
)
}
/// show a success message
///
/// - Parameters:
/// - title: the success message remind users what you want
/// - superview: super view, if superview is nil, show on main window
/// - delayTimeInterval: the view will show delay the `delayTimeInterval`
class func showSuccess(
with title: String = "",
in superview: UIView? = nil,
delay delayTimeInterval: TimeInterval = 0.0,
with configuration: Configuration? = nil
) {
shared.internalShow(
displayType: .indicator(title: title, type: .success),
in: superview,
delay: delayTimeInterval,
with: configuration
)
}
/// show a error message
///
/// - Parameters:
/// - title: the error message remind users what you want
/// - superview: super view, if superview is nil, show on main window
/// - delayTimeInterval: the view will show delay the `delayTimeInterval`
class func showError(
with title: String = "",
in superview: UIView? = nil,
delay delayTimeInterval: TimeInterval = 0.0,
with configuration: Configuration? = nil
) {
shared.internalShow(
displayType: .indicator(title: title, type: .error),
in: superview,
delay: delayTimeInterval,
with: configuration
)
}
/// show a warning message
///
/// - Parameters:
/// - title: the warning message remind users what you want
/// - superview: super view, if superview is nil, show on main window
/// - delayTimeInterval: the view will show delay the `delayTimeInterval`
class func showWarning(
with title: String = "",
in superview: UIView? = nil,
delay delayTimeInterval: TimeInterval = 0.0,
with configuration: Configuration? = nil
) {
shared.internalShow(
displayType: .indicator(title: title, type: .warning),
in: superview,
delay: delayTimeInterval,
with: configuration
)
}
/// show a waiting alert
///
/// - Parameters:
/// - title: the message remind users what you want
/// - superview: super view, if superview is nil, show on main window
/// - delayTimeInterval: the view will show delay the `delayTimeInterval`
class func show(
with title: String = "",
in superview: UIView? = nil,
delay delayTimeInterval: TimeInterval = 0.0,
with configuration: Configuration? = nil
) {
let animationType: ZVIndicatorView.AnimationType
if let configuration = configuration {
animationType = configuration.animationType
} else {
animationType = shared.configuration.animationType
}
shared.internalShow(
displayType: .indicator(title: title, type: .indicator(style: animationType)),
in: superview,
delay: delayTimeInterval,
with: configuration
)
}
/// show the progress of some task
///
/// - Parameters:
/// - progress: the progress of your task
/// - title: the message remind users what you want
/// - superview: super view, if superview is nil, show on main window
/// - delayTimeInterval: the view will show delay the `delayTimeInterval`
class func showProgress(
_ progress: Float,
title: String = "",
in superview: UIView? = nil,
delay delayTimeInterval: TimeInterval = 0.0,
with configuration: Configuration? = nil
) {
shared.internalShow(
displayType: .indicator(title: title, type: .progress(value: progress)),
in: superview,
delay: delayTimeInterval,
with: configuration
)
}
/// show a custom image
///
/// - Parameters:
/// - image: your image
/// - title: the message remind users what you want
/// - superview: super view, if superview is nil, show on main window
/// - dismissAtomically: if `true` the `HUD` will dissmiss atomically
/// - delayTimeInterval: the view will show delay the `delayTimeInterval`
class func showImage(
_ image: UIImage,
title: String = "",
in superview: UIView? = nil,
dismissAtomically: Bool = true,
delay delayTimeInterval: TimeInterval = 0.0,
with configuration: Configuration? = nil
) {
shared.internalShow(
displayType: .indicator(title: title, type: .image(value: image, dismissAtomically: dismissAtomically)),
in: superview,
delay: delayTimeInterval,
with: configuration
)
}
/// show the animation waiting alert
///
/// - Parameters:
/// - images: animation image array
/// - duration: animation duration @see UIImage
/// - title: the message remind users what you want
/// - superview: super view, if superview is nil, show on main window
/// - delayTimeInterval: the view will show delay the `delayTimeInterval`
class func showAnimation(
_ images: [UIImage],
duration: TimeInterval = 0.0,
title: String = "",
in superview: UIView? = nil,
delay delayTimeInterval: TimeInterval = 0.0,
with configuration: Configuration? = nil
) {
if images.isEmpty { return }
let animationDuration: TimeInterval
if duration == 0 {
animationDuration = Double(images.count) * 0.1
} else {
animationDuration = duration
}
shared.internalShow(
displayType: .indicator(title: title, type: .animation(value: images, duration: animationDuration)),
in: superview,
delay: delayTimeInterval,
with: configuration
)
}
/// show the animation waiting alert
///
/// - Parameters:
/// - images: animation image array
/// - duration: animation duration @see UIImage
/// - title: the message remind users what you want
/// - superview: super view, if superview is nil, show on main window
/// - delayTimeInterval: the view will show delay the `delayTimeInterval`
class func showCustomView(
_ view: UIView,
in superview: UIView? = nil,
delay delayTimeInterval: TimeInterval = 0.0,
with configuration: Configuration? = nil
) {
shared.internalShow(
displayType: .customeView(view: view),
in: superview,
delay: delayTimeInterval,
with: configuration
)
}
/// show custom display type @see ZVProgressHUD.DisplayType
///
/// - Parameters:
/// - displayType: ZVProgressHUD.DisplayType
/// - superview: super view, if superview is nil, show on main window
/// - delayTimeInterval: the view will show delay the `delayTimeInterval`
class func show(
with displayType: DisplayType,
in superview: UIView? = nil,
delay delayTimeInterval: TimeInterval = 0.0,
with configuration: Configuration? = nil
) {
shared.internalShow(
displayType: displayType,
in: superview,
delay: delayTimeInterval,
with: configuration
)
}
/// dismiss the hud
///
/// - Parameters:
/// - delay: the view will dissmiss delay the `delayTimeInterval`
/// - completion: dismiss completion handler
class func dismiss(
delay: TimeInterval = 0.0,
completion: CompletionHandler? = nil
) {
shared.internalDismiss(with: delay, completion: completion)
}
}
#endif
| 32.240997 | 116 | 0.618352 |
e7ceba8fdc90a9bf5c3c590e43e5dc3b6ed3bc16 | 373 | asm | Assembly | oeis/106/A106487.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/106/A106487.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/106/A106487.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A106487: Number of leaves in combinatorial game trees.
; 1,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,1,2,2,3,2,3,3,4,2,3,3,4,3,4,4,5,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,2,3,3,4,3,4,4,5,3,4,4,5,4,5,5,6,3,4,4,5,4,5,5,6,4,5,5,6,5,6,6,7,3,4,4,5
mov $1,$0
mov $2,5
mov $3,$0
mov $4,$0
cmp $4,0
add $3,$4
lpb $2
div $1,2
sub $2,1
sub $3,$1
lpe
mov $0,$3
| 23.3125 | 201 | 0.541555 |
e2fdfda969fde7d41f7f8eda5de496a16cec7ed5 | 568 | py | Python | hackerearth/ALGO_Semi/E.py | akshaynagpal/competitive-programming | 0a54f43e3e0f2135c9c952400c5a628244b667d1 | [
"MIT"
] | null | null | null | hackerearth/ALGO_Semi/E.py | akshaynagpal/competitive-programming | 0a54f43e3e0f2135c9c952400c5a628244b667d1 | [
"MIT"
] | null | null | null | hackerearth/ALGO_Semi/E.py | akshaynagpal/competitive-programming | 0a54f43e3e0f2135c9c952400c5a628244b667d1 | [
"MIT"
] | null | null | null | import math
def calc_next(pressed_keys,k,m,n):
summ = 0
for i in range(1,n+1):
summ += math.pow(-1,i+1)*pressed_keys[k-i]
return summ % m
num_test = int(raw_input())
for j in range(num_test):
n,m,z = raw_input().split()
n = int(n)
m = int(m)
z = int(z)
pressed_keys = [int(j) for j in raw_input().split()]
current_length = len(pressed_keys)
while(current_length!=z+1):
pressed_keys.append(calc_next(pressed_keys,current_length,m,n))
current_length += 1
print int(pressed_keys[-1])
| 25.818182 | 71 | 0.603873 |
df2db92c40d79933030fab0cb972470052516037 | 807 | cs | C# | Packages/BaseAtoms/Runtime/Actions/SetVariableValue/SetVector3VariableValue.cs | RichLogan/unity-atoms | bf52da03a0899fe66240ecaba75ce3d567b7713b | [
"MIT"
] | 461 | 2018-10-31T09:35:09.000Z | 2021-01-21T19:58:57.000Z | Packages/BaseAtoms/Runtime/Actions/SetVariableValue/SetVector3VariableValue.cs | RichLogan/unity-atoms | bf52da03a0899fe66240ecaba75ce3d567b7713b | [
"MIT"
] | 211 | 2018-11-16T09:46:54.000Z | 2021-01-17T16:40:56.000Z | Packages/BaseAtoms/Runtime/Actions/SetVariableValue/SetVector3VariableValue.cs | RichLogan/unity-atoms | bf52da03a0899fe66240ecaba75ce3d567b7713b | [
"MIT"
] | 66 | 2018-11-25T23:36:07.000Z | 2021-01-21T15:46:40.000Z | using UnityAtoms.BaseAtoms;
using UnityEngine;
namespace UnityAtoms.BaseAtoms
{
/// <summary>
/// Set variable value Action of type `Vector3`. Inherits from `SetVariableValue<Vector3, Vector3Pair, Vector3Variable, Vector3Constant, Vector3Reference, Vector3Event, Vector3PairEvent, Vector3VariableInstancer>`.
/// </summary>
[EditorIcon("atom-icon-purple")]
[CreateAssetMenu(menuName = "Unity Atoms/Actions/Set Variable Value/Vector3", fileName = "SetVector3VariableValue")]
public sealed class SetVector3VariableValue : SetVariableValue<
Vector3,
Vector3Pair,
Vector3Variable,
Vector3Constant,
Vector3Reference,
Vector3Event,
Vector3PairEvent,
Vector3Vector3Function,
Vector3VariableInstancer>
{ }
}
| 35.086957 | 224 | 0.714994 |
e232ffe13fafff37d174e65f0c70c4170a4123f9 | 3,448 | py | Python | create_data.py | Emocial-NLP-Depression-Detection/Emocial-AI-English | 191bb3ced96cb7088b1766e0784db3cdcc1e8ed8 | [
"MIT"
] | 1 | 2021-05-05T08:52:50.000Z | 2021-05-05T08:52:50.000Z | create_data.py | Emocial-NLP-Depression-Detection/Emocial-AI-English | 191bb3ced96cb7088b1766e0784db3cdcc1e8ed8 | [
"MIT"
] | 2 | 2021-04-16T12:55:00.000Z | 2021-05-03T13:18:10.000Z | create_data.py | Emocial-NLP-Depression-Detection/Emocial-AI-English | 191bb3ced96cb7088b1766e0784db3cdcc1e8ed8 | [
"MIT"
] | null | null | null | from nltk.sentiment import SentimentIntensityAnalyzer
import twint
import pandas as pd
import os
import nltk
import re
import emoji
nltk.download('all')
c = twint.Config()
c.Search = "depression"
c.Limit = 1000
c.Store_csv = True
c.Output = "./data/raw_depressed_data.csv"
c.Lang = 'en'
p = twint.Config()
p.Search = "the"
p.Limit = 1000
p.Store_csv = True
p.Output = "./data/raw_everyday_data.csv"
p.Lang = 'en'
# try:
# os.remove("./data/raw_depressed_data.csv")
# except FileNotFoundError:
twint.run.Search(c)
twint.run.Search(p)
words = set(nltk.corpus.words.words())
def cleaner(tweet):
tweet = re.sub("@[A-Za-z0-9]+", "", tweet) # Remove @ sign
tweet = re.sub('[^a-zA-Z0-9]', ' ', tweet) # remove non-english word
tweet = re.sub('\s+', ' ', tweet)
tweet = re.sub(r"(?:\@|http?\://|https?\://|www)\S+",
"", tweet) # Remove http links
tweet = " ".join(tweet.split())
# Remove Emojis
tweet = ''.join(c for c in tweet if c not in emoji.UNICODE_EMOJI)
# Remove hashtag sign but keep the text
tweet = tweet.replace("#", "").replace("_", " ")
tweet = " ".join(w for w in nltk.wordpunct_tokenize(tweet)
if w.lower() in words or not w.isalpha())
return tweet
# def translate(x):
# return TextBlob(x).translate(to="th")
print("\nImporting Data\n")
df = pd.read_csv("./data/raw_depressed_data.csv")
pos = pd.read_csv("./data/raw_everyday_data.csv")
print("\nDone Importing Data\n")
label = []
analysed = 0
print("\n Sentiment Analysing the tweets\n")
sia = SentimentIntensityAnalyzer()
for tweets in df['tweet']:
if sia.polarity_scores(tweets)['pos'] >= 0.5:
label.append(0)
else:
label.append(1)
analysed = analysed + 1
if analysed % 100 == 0:
print(f"Analysed {analysed} so far...")
pos_label = []
for tweets in pos['tweet']:
if sia.polarity_scores(tweets)['pos'] < 0.5:
pos_label.append(0)
else:
pos_label.append(1)
analysed = analysed + 1
if analysed % 100 == 0:
print(f"Analysed {analysed} so far...")
print("\n Finished Sentiment Analysing the tweets\n")
df2 = pd.DataFrame({'Tweets': df['tweet'], 'label': label})
pos2 = pd.DataFrame({'Tweets': pos['tweet'], 'label': pos_label})
print(df2)
is_pos = pos2['label'] == 0
pos2 = pos2[is_pos]
df2 = df2.append(pos2, ignore_index=True, sort=True)
df2['Tweets'] = df2['Tweets'].map(lambda x: cleaner(x))
df2.sort_values(by=['label'], ascending=False)
df2[df2.Tweets.map(lambda x: x.isascii())]
df2.dropna(inplace=True)
df2.to_csv("./data/cleaned_data.csv", index=False)
df3 = pd.read_csv("./data/cleaned_data.csv")
print(f"Depressed Tweets: {df2.label.value_counts()[1]}")
print(f"Positive Tweets: {df2.label.value_counts()[0]}")
print("\nStart Cleaning..\n")
for index, i in df3.iterrows():
if df3.label.value_counts()[1] > df3.label.value_counts()[0] and i['label'] == 1:
df3 = df3.drop(index, errors='ignore')
# print(f"Index: {index}\n I: {i}")
elif df3.label.value_counts()[1] < df3.label.value_counts()[0] and i['label'] == 0:
df3 = df3.drop(index, errors='ignore')
print("\nDone Cleaning..\n")
print(f"Depressed Tweets: {df3.label.value_counts()[1]}")
print(f"Positive Tweets: {df3.label.value_counts()[0]}")
df3.to_csv("./data/data.csv", index=False)
os.remove("./data/raw_depressed_data.csv")
os.remove("./data/raw_everyday_data.csv")
os.remove("./data/cleaned_data.csv")
| 31.063063 | 87 | 0.647042 |
b717e9997f1ec0e2b71910905de8a9bef3b63932 | 1,535 | cs | C# | Unity/Assets/Script/FSM/StateMachine.cs | KorStrix/GGJ_2019 | d1011abae523274e0b148209adeacd976b06b3d7 | [
"MIT"
] | null | null | null | Unity/Assets/Script/FSM/StateMachine.cs | KorStrix/GGJ_2019 | d1011abae523274e0b148209adeacd976b06b3d7 | [
"MIT"
] | null | null | null | Unity/Assets/Script/FSM/StateMachine.cs | KorStrix/GGJ_2019 | d1011abae523274e0b148209adeacd976b06b3d7 | [
"MIT"
] | null | null | null | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StateMachine
{
public IState currentlyRunningState;
private IState previousState;
private Stack<IState> stateStack;
public void Awake()
{
this.currentlyRunningState = new EmptyState();
this.previousState = new EmptyState();
}
public void ExecuteStateUpdate()
{
var runningState = this.currentlyRunningState;
if (runningState != null)
{
this.currentlyRunningState.Execute();
}
}
public void SwitchToPreviousState()
{
this.currentlyRunningState.Exit();
this.currentlyRunningState = this.previousState;
this.currentlyRunningState.Enter();
}
public void PushState(IState newState)
{
if (this.currentlyRunningState == null)
{
return;
}
this.currentlyRunningState.Exit();
this.previousState = this.currentlyRunningState;
this.currentlyRunningState = newState;
this.currentlyRunningState.Enter();
stateStack.Push(newState);
}
public void PopState()
{
if (stateStack.Count == 0)
{
Debug.Log("The Stack is already Empty");
return;
}
stateStack.Pop();
if (stateStack.Count != 0)
this.previousState = stateStack.Peek();
else
this.previousState = new EmptyState();
SwitchToPreviousState();
}
}
| 22.910448 | 56 | 0.602606 |
b03b2dd7db4e8cb173e01d69d75305b5ef3ca5c0 | 1,419 | py | Python | Euler_008.py | David-boo/Euler | 6ac5620e401949b2b5a730af70e65c3ea065b363 | [
"MIT"
] | null | null | null | Euler_008.py | David-boo/Euler | 6ac5620e401949b2b5a730af70e65c3ea065b363 | [
"MIT"
] | null | null | null | Euler_008.py | David-boo/Euler | 6ac5620e401949b2b5a730af70e65c3ea065b363 | [
"MIT"
] | null | null | null | # Code on Python 3.7.4
# Working @ Dec, 2020
# david-boo.github.io
# Define both number and length (13). Then, just check every substring of length 13 and store and print maximum.
num = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
length = 13
max = 0
for i in range(0, len(num)-length+1):
sub = num[i:(i + length)]
k = 1
for j in range(0, len(sub)):
k = k * int(sub[j])
if max < k:
max = k
print(max)
| 64.5 | 1,009 | 0.868922 |
0af6208b5cd0b1074b09db3c2702f68b590268eb | 9,262 | cs | C# | src/recls.Core/Internal/BreadthFirstFileSearcher.cs | synesissoftware/recls.NET | 2dcb11af92c1a517ddb57fd9814785fcce925ac2 | [
"BSD-3-Clause"
] | null | null | null | src/recls.Core/Internal/BreadthFirstFileSearcher.cs | synesissoftware/recls.NET | 2dcb11af92c1a517ddb57fd9814785fcce925ac2 | [
"BSD-3-Clause"
] | null | null | null | src/recls.Core/Internal/BreadthFirstFileSearcher.cs | synesissoftware/recls.NET | 2dcb11af92c1a517ddb57fd9814785fcce925ac2 | [
"BSD-3-Clause"
] | null | null | null |
/* /////////////////////////////////////////////////////////////////////////
* File: Internal/BreadthFirstFileSearcher.cs
*
* Created: 5th June 2009
* Updated: 24th September 2017
*
* Home: http://recls.net/
*
* Copyright (c) 2009-2017, Matthew Wilson and Synesis Software
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name(s) of Matthew Wilson and Synesis Software nor the
* names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ////////////////////////////////////////////////////////////////////// */
namespace Recls.Internal
{
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
internal class BreadthFirstFileSearcher
: IEnumerable<IEntry>
, IDisposable
{
#region construction
internal BreadthFirstFileSearcher(string directory, string patterns, SearchOptions options, int maxDepth, IExceptionHandler exceptionHandler, IProgressHandler progressHandler, object context)
{
Debug.Assert(null != directory);
Debug.Assert(Util.HasDirEnd(directory), "path must end in terminator");
Debug.Assert(Util.IsPathAbsolute(directory), "path must be absolute");
Debug.Assert(null != patterns);
Debug.Assert(0 != ((SearchOptions.Directories | SearchOptions.Files) & options));
Debug.Assert(null != exceptionHandler);
Debug.Assert(maxDepth >= 0, "maximum depth cannot be less than 0");
Util.CheckDirectoryExistsOrThrow(directory, options, out m_stubEnumerator, out m_lockFile, out m_lockFileInfo);
m_directory = directory;
m_patterns = new Patterns(patterns);
m_options = options;
m_maxDepth = maxDepth;
m_exceptionHandler = exceptionHandler;
m_progressHandler = progressHandler;
m_context = context;
}
void IDisposable.Dispose()
{
m_lockFile.Dispose();
}
#endregion
#region IEnumerable<IEntry> members
System.Collections.Generic.IEnumerator<IEntry> System.Collections.Generic.IEnumerable<IEntry>.GetEnumerator()
{
if (null != m_stubEnumerator)
{
return m_stubEnumerator;
}
return new Enumerator(m_directory, m_patterns, m_options, m_maxDepth, m_exceptionHandler, m_progressHandler, m_context, m_lockFileInfo);
}
#endregion
#region IEnumerable members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((System.Collections.Generic.IEnumerable<IEntry>)this).GetEnumerator();
}
#endregion
#region types
private class Enumerator
: IEnumerator<IEntry>
{
#region construction
internal Enumerator(string directory, Patterns patterns, SearchOptions options, int maxDepth, IExceptionHandler exceptionHandler, IProgressHandler progressHandler, object context, FileInfo lockFileInfo)
{
Debug.Assert(null != directory);
Debug.Assert(Util.HasDirEnd(directory), "path must end in terminator");
Debug.Assert(Util.IsPathAbsolute(directory), "path must be absolute");
Debug.Assert(null != patterns);
Debug.Assert(0 != ((SearchOptions.Directories | SearchOptions.Files) & options));
Debug.Assert(maxDepth >= 0, "maximum depth cannot be less than 0");
m_directory = directory;
m_maxDepth = maxDepth;
m_di = new DirectoryInfo(directory);
m_patterns = patterns;
m_entries = new List<FileSystemInfo>();
m_subdirectories = new List<DirectoryInfo>();
m_options = options;
m_exceptionHandler = exceptionHandler;
m_progressHandler = progressHandler;
m_context = context;
m_lockFileInfo = lockFileInfo;
Reset_(false);
}
#endregion
#region IDisposable members
void IDisposable.Dispose()
{
m_currentEntry = null;
m_entries.Clear();
m_entryIndex = 0;
m_subdirectories.Clear();
GC.SuppressFinalize(this);
}
#endregion
#region IEnumerator<IEntry> members
IEntry IEnumerator<IEntry>.Current
{
get { return GetCurrent_(); }
}
#endregion
#region IEnumerator members
object System.Collections.IEnumerator.Current
{
get { return GetCurrent_(); }
}
bool System.Collections.IEnumerator.MoveNext()
{
if(!m_searchCancelled)
{
for(; 0 != m_entries.Count || 0 != m_subdirectories.Count; )
{
Debug.Assert(m_entryIndex <= m_entries.Count);
if(m_entryIndex < m_entries.Count)
{
FileSystemInfo fsi = m_entries[m_entryIndex];
FileInfo fi = fsi as FileInfo;
if(null != fi)
{
m_currentEntry = new FileEntry(fi, m_directory, m_options, m_context);
}
else
{
m_currentEntry = new DirectoryEntry((DirectoryInfo)fsi, m_directory, m_options, m_context);
}
++m_entryIndex;
return true;
}
// Descend a level
if(m_depth++ >= m_maxDepth)
{
break;
}
List<FileSystemInfo> nextEntries = new List<FileSystemInfo>();
List<DirectoryInfo> nextSubdirectories = new List<DirectoryInfo>();
foreach(DirectoryInfo di in m_subdirectories)
{
switch(m_progressHandler.OnProgress(m_context, Util.EnsureDirEnd(di.FullName), m_depth))
{
case ProgressHandlerResult.Continue:
nextEntries.AddRange(Util.GetEntriesByPatterns(m_context, m_exceptionHandler, di, m_patterns, m_options, m_lockFileInfo));
nextSubdirectories.AddRange(Util.GetSubdirectories(m_context, m_exceptionHandler, di, m_options));
break;
case ProgressHandlerResult.CancelDirectory:
break;
case ProgressHandlerResult.CancelSearch:
m_searchCancelled = true;
return false;
}
}
m_entryIndex = 0;
m_entries = nextEntries;
m_subdirectories = nextSubdirectories;
}
}
return false;
}
void System.Collections.IEnumerator.Reset()
{
Reset_(false);
}
#endregion
#region implementation
// Need a separate worker method, as cannot call System.Collections.IEnumerator.Reset() without a cast
void Reset_(bool disposing)
{
m_searchCancelled = false;
m_currentEntry = null;
m_entries.Clear();
m_entryIndex = 0;
m_subdirectories.Clear();
m_depth = 0;
if(!disposing)
{
switch(m_progressHandler.OnProgress(m_context, m_directory, m_depth))
{
case ProgressHandlerResult.Continue:
m_entries.AddRange(Util.GetEntriesByPatterns(m_context, m_exceptionHandler, m_di, m_patterns, m_options, m_lockFileInfo));
m_subdirectories.AddRange(Util.GetSubdirectories(m_context, m_exceptionHandler, m_di, m_options));
break;
case ProgressHandlerResult.CancelDirectory:
break;
case ProgressHandlerResult.CancelSearch:
m_searchCancelled = true;
break;
}
}
}
private IEntry GetCurrent_()
{
return m_currentEntry;
}
#endregion
#region fields
readonly string m_directory;
readonly DirectoryInfo m_di;
readonly Patterns m_patterns;
readonly SearchOptions m_options;
readonly int m_maxDepth;
readonly IExceptionHandler m_exceptionHandler;
readonly IProgressHandler m_progressHandler;
IEntry m_currentEntry;
List<FileSystemInfo> m_entries;
int m_entryIndex;
List<DirectoryInfo> m_subdirectories;
int m_depth;
bool m_searchCancelled;
readonly object m_context;
readonly FileInfo m_lockFileInfo;
#endregion
}
#endregion
#region fields
readonly string m_directory;
readonly Patterns m_patterns;
readonly SearchOptions m_options;
readonly int m_maxDepth;
readonly IExceptionHandler m_exceptionHandler;
readonly IProgressHandler m_progressHandler;
readonly object m_context;
readonly IDisposable m_lockFile;
readonly FileInfo m_lockFileInfo;
readonly IEnumerator<IEntry> m_stubEnumerator;
#endregion
}
}
/* ///////////////////////////// end of file //////////////////////////// */
| 30.873333 | 205 | 0.696718 |
b0a5b72c4ec8cc7ffc58bd608880624820714afe | 788 | py | Python | app/core/migrations/0017_auto_20200821_1816.py | dodge-ttu/gohan-api | bf3d4a4e7a93c699a00865c769975d6cfb3ec8cf | [
"MIT"
] | null | null | null | app/core/migrations/0017_auto_20200821_1816.py | dodge-ttu/gohan-api | bf3d4a4e7a93c699a00865c769975d6cfb3ec8cf | [
"MIT"
] | null | null | null | app/core/migrations/0017_auto_20200821_1816.py | dodge-ttu/gohan-api | bf3d4a4e7a93c699a00865c769975d6cfb3ec8cf | [
"MIT"
] | null | null | null | # Generated by Django 2.1.15 on 2020-08-21 18:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0016_auto_20200821_1503'),
]
operations = [
migrations.RemoveField(
model_name='device',
name='id',
),
migrations.RemoveField(
model_name='location',
name='id',
),
migrations.AlterField(
model_name='device',
name='device_id',
field=models.IntegerField(primary_key=True, serialize=False),
),
migrations.AlterField(
model_name='location',
name='loc_id',
field=models.IntegerField(primary_key=True, serialize=False),
),
]
| 24.625 | 73 | 0.558376 |
daa4886b661367910536135e2f80e9c3ee7a5e72 | 3,369 | php | PHP | app/Http/Controllers/Cms/ExperienceController.php | RisingStar522/serverAPP-CMS | f74bb717812af9b7fbc7ad296eee4b264876b0ba | [
"MIT"
] | null | null | null | app/Http/Controllers/Cms/ExperienceController.php | RisingStar522/serverAPP-CMS | f74bb717812af9b7fbc7ad296eee4b264876b0ba | [
"MIT"
] | null | null | null | app/Http/Controllers/Cms/ExperienceController.php | RisingStar522/serverAPP-CMS | f74bb717812af9b7fbc7ad296eee4b264876b0ba | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers\Cms;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Experience_Button;
use App\Services\ExperienceService;
use Auth;
use App\Models\Experience_Button_Image;
class ExperienceController extends Controller
{
private $experienceService = null;
public function __construct(ExperienceService $experienceService)
{
$this->experienceService = $experienceService;
}
public function index()
{
$hotel_id = auth('hotel')->user()->id;
$buttons = Experience_Button::where('hotel_id', $hotel_id)->get();
return view('cms.experience.index')->with([
'buttons' => $buttons
]);
}
public function store(Request $request)
{
$request->validate(
[
'btnTitle' => 'required',
'icon' => 'required',
'btnType' => 'required'
],
[
'btnTitle.required' => 'Title is required',
'btnType.required' => 'Button type is required',
]
);
$experience_button = null;
if ($request->input('button_id') == "-1") {
$experience_button = new Experience_Button;
} else {
$experience_button = Experience_Button::where('id', $request->input('button_id'))->first();
}
$experience_button->title = $request->input('btnTitle');
$experience_button->icon = $request->input('icon');
$experience_button->type = $request->input('btnType');
$experience_button->hotel_id = auth('hotel')->user()->id;
$type = $request->input('btnType');
if ($type == "Promotion" || $type == "Custom" || $type == "Custom_Image") {
$experience_button->data = $request->input('encoded');
} else {
$experience_button->data = "";
}
$experience_button->save();
$array = explode(",", $request->input('images_id'));
if (count($array) > 0) {
Experience_Button_Image::whereIn('id', $array)->update(['experience_button_id' => $experience_button->id]);
}
return redirect()->back()->with([
'success' => 'Button added successfull.'
]);
}
public function get($id)
{
$experience_button = Experience_Button::where('id', $id)->first();
if (!$experience_button) {
abort(404);
}
$experience_button_images = Experience_Button_Image::where('experience_button_id', $id)->get();
$experience_button->images = $experience_button_images;
return $experience_button;
}
public function uploadPromotionItemImage(Request $request)
{
//The ID of the button could be 0 or 1
$button_id = $request->input('button_id');
if ($button_id < 1) {
$button_id = null;
}
$request->validate(
[ 'images.*' => 'nullable|file|mimes:png|max:4096'],
[ 'images.*.mimes' => 'Please upload only png file.',
'images.*.max' => 'Image is too large.'
]
);
$images = $this->experienceService->uploadBtnImages($request, $button_id);
return $images;
}
public function deleteImage($id)
{
Experience_Button_Image::where('id', $id)->delete();
return "done";
}
} | 31.194444 | 119 | 0.569012 |
eb1dbdfa52992cee29e831a9c3b2ba9fc1780ad1 | 226 | css | CSS | src/themes/dark.css | linuxaddict89/luminos-starter-react-webpack | 096a5aa899cc46de8c6a0b0d2f7bfcd1e7755743 | [
"MIT"
] | null | null | null | src/themes/dark.css | linuxaddict89/luminos-starter-react-webpack | 096a5aa899cc46de8c6a0b0d2f7bfcd1e7755743 | [
"MIT"
] | null | null | null | src/themes/dark.css | linuxaddict89/luminos-starter-react-webpack | 096a5aa899cc46de8c6a0b0d2f7bfcd1e7755743 | [
"MIT"
] | null | null | null | :root {
--app-background: #212121;
--accent-color: #fff;
--primary-color: #41addd;
--navbar-height: 62px;
--navbar-background: transparent;
--footer-height: 119px;
--content-height: calc(100vh - 62px - 119px);
}
| 22.6 | 47 | 0.646018 |
831c6b5b47856a19cf19d3cf2476c492f017f4aa | 3,524 | rs | Rust | tests/test_shared/mod.rs | eucleo/proto-mav | f8b93b379e6134345d1fd58d3086798263c32367 | [
"Apache-2.0",
"MIT"
] | null | null | null | tests/test_shared/mod.rs | eucleo/proto-mav | f8b93b379e6134345d1fd58d3086798263c32367 | [
"Apache-2.0",
"MIT"
] | null | null | null | tests/test_shared/mod.rs | eucleo/proto-mav | f8b93b379e6134345d1fd58d3086798263c32367 | [
"Apache-2.0",
"MIT"
] | null | null | null | use proto_mav::*;
#[allow(dead_code)]
pub const COMMON_MSG_HEADER: MavHeader = MavHeader {
sequence: 239,
system_id: 1,
component_id: 1,
};
#[cfg(feature = "common")]
pub fn get_heartbeat_msg() -> proto::common::Heartbeat {
proto::common::Heartbeat {
custom_mode: 5,
r#type: proto::common::MavType::Quadrotor as i32,
autopilot: proto::common::MavAutopilot::Ardupilotmega as i32,
base_mode: proto::common::MavModeFlag::ManualInputEnabled as i32
| proto::common::MavModeFlag::StabilizeEnabled as i32
| proto::common::MavModeFlag::GuidedEnabled as i32
| proto::common::MavModeFlag::CustomModeEnabled as i32,
system_status: proto::common::MavState::Standby as i32,
mavlink_version: 3,
}
}
#[allow(dead_code)]
#[cfg(feature = "common")]
pub fn get_cmd_nav_takeoff_msg() -> proto::common::CommandInt {
proto::common::CommandInt {
param1: 1.0,
param2: 2.0,
param3: 3.0,
param4: 4.0,
x: 555,
y: 666,
z: 777.0,
command: proto::common::MavCmd::NavTakeoff as i32,
target_system: 42,
target_component: 84,
frame: proto::common::MavFrame::Global as i32,
current: 73,
autocontinue: 17,
}
}
#[allow(dead_code)]
#[cfg(feature = "common")]
pub fn get_hil_actuator_controls_msg() -> proto::common::HilActuatorControls {
proto::common::HilActuatorControls {
time_usec: 1234567 as u64,
flags: 0 as u64,
controls: vec![
0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0,
],
mode: proto::common::MavModeFlag::ManualInputEnabled as i32
| proto::common::MavModeFlag::StabilizeEnabled as i32
| proto::common::MavModeFlag::CustomModeEnabled as i32,
}
}
#[allow(dead_code)]
#[cfg(all(feature = "common", not(feature = "emit-extensions")))]
pub fn get_servo_output_raw_v1() -> proto::common::ServoOutputRaw {
proto::common::ServoOutputRaw {
time_usec: 1234567 as u32,
servo1_raw: 1100 as u32,
servo2_raw: 1200 as u32,
servo3_raw: 1300 as u32,
servo4_raw: 1400 as u32,
servo5_raw: 1500 as u32,
servo6_raw: 1600 as u32,
servo7_raw: 1700 as u32,
servo8_raw: 1800 as u32,
port: 123 as u32,
}
}
#[allow(dead_code)]
#[cfg(all(feature = "common", feature = "emit-extensions"))]
pub fn get_servo_output_raw_v2() -> proto::common::ServoOutputRaw {
proto::common::ServoOutputRaw {
time_usec: 1234567 as u32,
servo1_raw: 1100 as u32,
servo2_raw: 1200 as u32,
servo3_raw: 1300 as u32,
servo4_raw: 1400 as u32,
servo5_raw: 1500 as u32,
servo6_raw: 1600 as u32,
servo7_raw: 1700 as u32,
servo8_raw: 1800 as u32,
port: 123 as u32,
servo9_raw: 1110 as u32,
servo10_raw: 1220 as u32,
servo11_raw: 1330 as u32,
servo12_raw: 1440 as u32,
servo13_raw: 1550 as u32,
servo14_raw: 1660 as u32,
servo15_raw: 1770 as u32,
servo16_raw: 1880 as u32,
}
}
#[allow(dead_code)]
#[cfg(all(feature = "ardupilotmega", feature = "uavionix", feature = "icarous"))]
pub fn get_apm_mount_status() -> proto::ardupilotmega::MountStatus {
proto::ardupilotmega::MountStatus {
pointing_a: 3,
pointing_b: 4,
pointing_c: 5,
target_system: 2,
target_component: 3,
}
}
| 31.185841 | 97 | 0.609818 |
385b1b77c358618734259af0d629b50773b78c6a | 89 | php | PHP | first-install/upload/catalog/language/en-gb/extension/shipping/weight.php | mmartche/coach | 9b7241059f4b70494f9dc6227b508eba9416be0c | [
"Apache-2.0"
] | 30 | 2019-03-04T20:30:24.000Z | 2022-02-08T05:17:38.000Z | first-install/upload/catalog/language/en-gb/extension/shipping/weight.php | mmartche/coach | 9b7241059f4b70494f9dc6227b508eba9416be0c | [
"Apache-2.0"
] | 9 | 2019-09-24T10:13:40.000Z | 2021-07-28T12:23:56.000Z | first-install/upload/catalog/language/en-gb/extension/shipping/weight.php | mmartche/coach | 9b7241059f4b70494f9dc6227b508eba9416be0c | [
"Apache-2.0"
] | 38 | 2018-12-08T20:18:55.000Z | 2021-11-28T00:44:07.000Z | <?php
// Text
$_['text_title'] = 'Weight Based Shipping';
$_['text_weight'] = 'Weight:'; | 22.25 | 44 | 0.617978 |
7f2c8dcd41731b9c68dae49b2eebc0a7f287001e | 2,205 | php | PHP | models/Asignaturas.php | kaliss96/calificaciones | b51ea783d8ae627cdedf9bf66df3bd335bb536de | [
"BSD-3-Clause"
] | null | null | null | models/Asignaturas.php | kaliss96/calificaciones | b51ea783d8ae627cdedf9bf66df3bd335bb536de | [
"BSD-3-Clause"
] | null | null | null | models/Asignaturas.php | kaliss96/calificaciones | b51ea783d8ae627cdedf9bf66df3bd335bb536de | [
"BSD-3-Clause"
] | null | null | null | <?php
namespace app\models;
use Yii;
/**
* This is the model class for table "asignaturas".
*
* @property integer $id_asig
* @property string $cod_asig
* @property string $nombre_asig
* @property integer $total_horas_asig
* @property integer $creditos_asig
* @property string $especificacion_asig
*
* @property Grupos[] $grupos
* @property PlanDeEstudio $planDeEstudio
* @property Prerrequisitos[] $prerrequisitos
*/
class Asignaturas extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'asignaturas';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['cod_asig', 'nombre_asig', 'creditos_asig'], 'required', 'message'=>'Campo Obligatorio'],
[['total_horas_asig', 'creditos_asig'], 'integer'],
[['cod_asig'], 'string', 'max' => 8],
[['nombre_asig'], 'string', 'max' => 80],
[['especificacion_asig'], 'string', 'max' => 50],
[['cod_asig'], 'unique'],
[['nombre_asig'], 'unique']
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
//'id_asig' => 'Id Asig',
'cod_asig' => 'Código de Asignatura',
'nombre_asig' => 'Nombre de Asignatura',
'total_horas_asig' => 'Total de Horas de Asignatura',
'creditos_asig' => 'Creditos de Asignatura',
'especificacion_asig' => 'Especificacion de Asignatura',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getGrupos()
{
return $this->hasMany(Grupos::className(), ['id_asig' => 'id_asig']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPlanDeEstudio()
{
return $this->hasOne(PlanDeEstudio::className(), ['id_asig' => 'id_asig']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPrerrequisitos()
{
return $this->hasMany(Prerrequisitos::className(), ['prerrequisito' => 'id_asig']);
}
}
| 25.639535 | 104 | 0.537868 |
aff58bae84d31bed4ab97ea8f2d9fc9f4fd59352 | 2,250 | py | Python | thbase/thrift2/cell.py | YutSean/pythbase | add955b74c442a1eb2d11438b9a89fd3e0afe0b2 | [
"Apache-2.0"
] | 3 | 2021-12-16T02:47:23.000Z | 2022-01-28T09:03:54.000Z | thbase/thrift2/cell.py | YutSean/thbase | add955b74c442a1eb2d11438b9a89fd3e0afe0b2 | [
"Apache-2.0"
] | 1 | 2021-01-21T01:10:18.000Z | 2021-01-21T01:10:18.000Z | thbase/thrift2/cell.py | YutSean/thbase | add955b74c442a1eb2d11438b9a89fd3e0afe0b2 | [
"Apache-2.0"
] | null | null | null | """
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from typing import Union
from thbase.util.bytes import to_str
class Cell(object):
def __init__(self, table_name, # type: Union[None, bytes]
row, # type: Union[None, bytes]
family, # type: Union[None, bytes]
qualifier, # type: Union[None, bytes]
value, # type: Union[None, bytes]
timestamp, # type: Union[None, int]
):
"""
Data structure to load data from hbase. If there is no matched cell or some errors occur at hbase server,
all the attributes could be None. In python2, bytes are represented by str, so the type of value is str.
Args:
table_name: name of the table.
row: the row key.
family: the column family.
qualifier: the column qualifier.
value: the bytes stored in the cell.
timestamp: a long int.
"""
self._table_name = table_name
self._row = row
self._family = family
self._qualifier = qualifier
self._value = value
self._timestamp = timestamp
@property
def table_name(self):
return self._table_name
@property
def row(self):
return self._row
@property
def family(self):
return self._family
@property
def qualifier(self):
return self._qualifier
@property
def value(self):
return self._value
@property
def timestamp(self):
return self._timestamp
def __str__(self):
return ":".join([to_str(self.table_name), to_str(self.row), to_str(self.family), to_str(self.qualifier)]) + \
' => ' + to_str(self.value)
| 31.25 | 117 | 0.624444 |
a435efdd9cd58f6d19c77da9720b6ff30f535827 | 1,618 | php | PHP | src/Admin/AdminBundle/Entity/Carrera.php | jonny100/bedeliafceyt | 025650ce441fd2820918a0cd2cc30ee766fd85fc | [
"MIT"
] | null | null | null | src/Admin/AdminBundle/Entity/Carrera.php | jonny100/bedeliafceyt | 025650ce441fd2820918a0cd2cc30ee766fd85fc | [
"MIT"
] | null | null | null | src/Admin/AdminBundle/Entity/Carrera.php | jonny100/bedeliafceyt | 025650ce441fd2820918a0cd2cc30ee766fd85fc | [
"MIT"
] | null | null | null | <?php
namespace Admin\AdminBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Carrera
*
* @ORM\Table(name="carrera")
* @ORM\Entity
*/
class Carrera
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="nombre", type="string", length=45, nullable=true)
*/
private $nombre;
/**
* @var string
*
* @ORM\Column(name="nombre_abreviado", type="string", length=45, nullable=false)
*/
private $nombreAbreviado;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* @param string $nombre
* @return Carrera
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set nombreAbreviado
*
* @param string $nombreAbreviado
* @return Carrera
*/
public function setNombreAbreviado($nombreAbreviado)
{
$this->nombreAbreviado = $nombreAbreviado;
return $this;
}
/**
* Get nombreAbreviado
*
* @return string
*/
public function getNombreAbreviado()
{
return $this->nombreAbreviado;
}
public function __toString() {
return $this->nombre;
}
}
| 16.019802 | 85 | 0.521014 |
ea94649f186ac18bd8e43ccc7fd677902355a616 | 192 | sh | Shell | gather-deps.sh | SebastianMestre/Include-Graph | 1e3486647906e438b5b209047589f2e15fff0937 | [
"MIT"
] | null | null | null | gather-deps.sh | SebastianMestre/Include-Graph | 1e3486647906e438b5b209047589f2e15fff0937 | [
"MIT"
] | null | null | null | gather-deps.sh | SebastianMestre/Include-Graph | 1e3486647906e438b5b209047589f2e15fff0937 | [
"MIT"
] | null | null | null | FILE=$(realpath $1)
mkdir -p _graph
cpp -MM $FILE | \
cpp -P | \
tr ' ' '\n' | \
xargs realpath | \
awk '{if(NR > 2) print $0}'
| 24 | 31 | 0.354167 |
a332156862f546a13608707c23b0212d2372a8c5 | 7,195 | java | Java | hazelcast/src/main/java/com/hazelcast/jet/core/SlidingWindowPolicy.java | software-is-art/hazelcast | 7f785606f1093aa6f420147ca46dd0befe11c4b8 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2022-03-09T11:41:04.000Z | 2022-03-09T11:41:04.000Z | hazelcast/src/main/java/com/hazelcast/jet/core/SlidingWindowPolicy.java | software-is-art/hazelcast | 7f785606f1093aa6f420147ca46dd0befe11c4b8 | [
"ECL-2.0",
"Apache-2.0"
] | 355 | 2021-10-14T02:18:25.000Z | 2022-03-31T02:14:24.000Z | hazelcast/src/main/java/com/hazelcast/jet/core/SlidingWindowPolicy.java | software-is-art/hazelcast | 7f785606f1093aa6f420147ca46dd0befe11c4b8 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2022-03-01T03:24:16.000Z | 2022-03-01T03:24:16.000Z | /*
* Copyright (c) 2008-2022, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.core;
import com.hazelcast.internal.util.Preconditions;
import java.io.Serializable;
import static com.hazelcast.internal.util.Preconditions.checkNotNegative;
import static com.hazelcast.internal.util.Preconditions.checkPositive;
import static com.hazelcast.internal.util.Preconditions.checkTrue;
import static com.hazelcast.jet.impl.util.Util.addClamped;
import static com.hazelcast.jet.impl.util.Util.subtractClamped;
import static com.hazelcast.jet.impl.util.Util.sumHadOverflow;
import static java.lang.Math.floorMod;
/**
* Contains parameters that define a sliding/tumbling window over which Jet
* will apply an aggregate function. Internally, Jet computes the window
* by maintaining <em>frames</em> of size equal to the sliding step. It
* treats the frame as a "unit range" of timestamps which cannot be further
* divided and immediately applies the accumulating function to the items
* belonging to the same frame. This allows Jet to let go of the individual
* items' data, saving memory. The user-visible consequences of this are
* that the configured window length must be an integer multiple of the
* sliding step and that the memory requirements scale with the ratio
* between window size and the sliding step.
* <p>
* A frame is labelled with its timestamp, which is the first timestamp
* value beyond the range covered by the frame. That timestamp denotes the
* exact moment on the event timeline where the frame was closed.
*
* @since Jet 3.0
*/
public class SlidingWindowPolicy implements Serializable {
private static final long serialVersionUID = 1L;
private final long frameSize;
private final long frameOffset;
private final long windowSize;
SlidingWindowPolicy(long frameSize, long frameOffset, long framesPerWindow) {
checkPositive(frameSize, "frameLength must be positive");
checkNotNegative(frameOffset, "frameOffset must not be negative");
checkTrue(frameOffset < frameSize, "frameOffset must be less than frameSize, offset="
+ frameOffset + ", size=" + frameSize);
checkPositive(framesPerWindow, "framesPerWindow must be positive");
this.frameSize = frameSize;
this.frameOffset = frameOffset;
this.windowSize = frameSize * framesPerWindow;
}
/**
* Returns the length of the frame (equal to the sliding step).
*/
public long frameSize() {
return frameSize;
}
/**
* Returns the frame offset. For example, with {@code frameLength = 10} and
* {@code frameOffset = 5} the frames will start at 5, 15, 25...
*/
public long frameOffset() {
return frameOffset;
}
/**
* Returns the length of the window (the size of the timestamp range it covers).
* It is an integer multiple of {@link #frameSize()}.
*/
public long windowSize() {
return windowSize;
}
/**
* Tells whether this definition describes a tumbling window. Tumbling
* window is a special case of sliding window whose sliding step is equal
* to its size.
*/
public boolean isTumbling() {
return windowSize == frameSize;
}
/**
* Returns the highest frame timestamp less than or equal to the given
* timestamp. If there is no such {@code long} value, returns {@code
* Long.MIN_VALUE}.
*/
public long floorFrameTs(long timestamp) {
return subtractClamped(timestamp, floorMod(
(timestamp >= Long.MIN_VALUE + frameOffset ? timestamp : timestamp + frameSize) - frameOffset,
frameSize
));
}
/**
* Returns the lowest frame timestamp greater than the given timestamp. If
* there is no such {@code long} value, returns {@code Long.MAX_VALUE}.
*/
public long higherFrameTs(long timestamp) {
long tsPlusFrame = timestamp + frameSize;
return sumHadOverflow(timestamp, frameSize, tsPlusFrame)
? addClamped(floorFrameTs(timestamp), frameSize)
: floorFrameTs(tsPlusFrame);
}
/**
* Returns a new window definition where all the frames are shifted by the
* given offset. More formally, it specifies the value of the lowest
* non-negative frame timestamp.
* <p>
* Given a tumbling window of {@code windowLength = 4}, with no offset the
* windows would cover the timestamps {@code ..., [-4, 0), [0..4), ...}
* With {@code offset = 2} they will cover {@code ..., [-2, 2), [2..6),
* ...}
*/
public SlidingWindowPolicy withOffset(long offset) {
return new SlidingWindowPolicy(frameSize, offset, windowSize / frameSize);
}
/**
* Converts this definition to one defining a tumbling window of the
* same length as this definition's frame.
*/
public SlidingWindowPolicy toTumblingByFrame() {
return new SlidingWindowPolicy(frameSize, frameOffset, 1);
}
/**
* Returns the definition of a sliding window of length {@code
* windowSize} that slides by {@code slideBy}. Given {@code
* windowSize = 4} and {@code slideBy = 2}, the generated windows would
* cover timestamps {@code ..., [-2, 2), [0..4), [2..6), [4..8), [6..10),
* ...}
* <p>
* Since the window will be computed internally by maintaining {@link
* SlidingWindowPolicy frames} of size equal to the sliding step, the
* configured window length must be an integer multiple of the sliding
* step.
*
* @param windowSize the length of the window, must be a multiple of {@code slideBy}
* @param slideBy the amount to slide the window by
*/
public static SlidingWindowPolicy slidingWinPolicy(long windowSize, long slideBy) {
Preconditions.checkPositive(windowSize, "windowSize must be >= 1");
Preconditions.checkPositive(slideBy, "slideBy must be >= 1");
Preconditions.checkTrue(windowSize % slideBy == 0, "windowSize must be an integer multiple of slideBy");
return new SlidingWindowPolicy(slideBy, 0, windowSize / slideBy);
}
/**
* Returns the definition of a tumbling window of length {@code
* windowSize}. The tumbling window is a special case of the sliding
* window with {@code slideBy = windowSize}. Given {@code
* windowSize = 4}, the generated windows would cover timestamps {@code
* ..., [-4, 0), [0..4), [4..8), ...}
*/
public static SlidingWindowPolicy tumblingWinPolicy(long windowSize) {
return slidingWinPolicy(windowSize, windowSize);
}
}
| 40.421348 | 112 | 0.684086 |
413de81e07fef80a244f6e2d769c4ad99d7587a3 | 1,445 | lua | Lua | src/vGenPin.lua | dev-lab/bare-esp-iot-generic-switch | 2d6e7e8a60b6e22ed8808bb4f5d2123bbc081281 | [
"Apache-2.0"
] | null | null | null | src/vGenPin.lua | dev-lab/bare-esp-iot-generic-switch | 2d6e7e8a60b6e22ed8808bb4f5d2123bbc081281 | [
"Apache-2.0"
] | null | null | null | src/vGenPin.lua | dev-lab/bare-esp-iot-generic-switch | 2d6e7e8a60b6e22ed8808bb4f5d2123bbc081281 | [
"Apache-2.0"
] | null | null | null | local z = ...
local function cC(o, p1, v)
return require("vgpCmd")(o, p1, v, false, "Config",
function(p, m)
if m == "OP" then
pwm.setup(p, 500, 0)
pwm.start(p)
else
pwm.close(p)
gpio.mode(p, (m:sub(1,1) == "I" and gpio.INPUT or gpio.OUTPUT), (m == "I1" and gpio.PULLUP or gpio.FLOAT))
end
end,
function(p) return v end)
end
local function cD(o, p1, v)
return require("vgpCmd")(o, p1, v, true, "Digital",
function(p, v) gpio.write(p, v > 0 and gpio.HIGH or gpio.LOW) end,
function(p) return gpio.read(p) end)
end
local function cP(o, p1, v)
return require("vgpCmd")(o, p1, v, true, "PWM",
function(p, v) pwm.setduty(p, v) end,
function(p) return pwm.getduty(p) end)
end
local function cA(o, p1, v)
return require("vgpCmd")(o, p1, v, true, "Analog",
nil, function(p) return gpio.read(p) end)
end
local function cN(o, p1, v)
if o > 2 then name = p1 end
return (o == 0 and false), nil, (o == 0 and "Unknown Name command" or name)
end
local function cF(o, p1, v)
return true, nil, "Virtual"
end
local function cU(o, p1, v)
return false, nil, "Unknown Command"
end
return function(cmd, f)
package.loaded[z] = nil
z = nil
local d, t, o, p1, p2 = require("vgpParse")(cmd)
local v1 = {C = cC, D = cD, P = cP, A = cA, N = cN, F = cF}
local v = v1[t] or cU
local r, p, e = v(o, p1, p2)
v = nil
collectgarbage()
f(r and "OK "..e or (d and "ERROR at "..(e and (p..": "..e) or p) or ""))
end
| 24.913793 | 110 | 0.608997 |
0ed8b5ff0f29c96d76c851984b072df6d6d6a563 | 6,158 | ps1 | PowerShell | Source/VMware.PSDesiredStateConfiguration/Functions/Invoke-VmwDscConfiguration.ps1 | KristiyanGK/TravisTest-Repo | c213852d00783117e3efed520db562c2c04a980f | [
"BSD-2-Clause"
] | null | null | null | Source/VMware.PSDesiredStateConfiguration/Functions/Invoke-VmwDscConfiguration.ps1 | KristiyanGK/TravisTest-Repo | c213852d00783117e3efed520db562c2c04a980f | [
"BSD-2-Clause"
] | null | null | null | Source/VMware.PSDesiredStateConfiguration/Functions/Invoke-VmwDscConfiguration.ps1 | KristiyanGK/TravisTest-Repo | c213852d00783117e3efed520db562c2c04a980f | [
"BSD-2-Clause"
] | null | null | null | <#
Desired State Configuration Resources for VMware
Copyright (c) 2018-2020 VMware, Inc. All rights reserved
The BSD-2 license (the "License") set forth below applies to all parts of the Desired State Configuration Resources for VMware project. You may not use this file except in compliance with the License.
BSD-2 License
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#>
<#
.Description
Invokes the dsc resources of a configuration with 'Get' Dsc method
#>
function Get-VmwDscConfiguration {
[CmdletBinding()]
param (
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true)]
[VmwDscConfiguration]
$Configuration
)
$invokeParams = @{
DscResources = $Configuration.Resources
Method = 'Get'
}
Invoke-VmwDscResources @invokeParams
}
<#
.Description
Invokes the dsc resources of a configuration with 'Set' Dsc method
#>
function Start-VmwDscConfiguration {
[CmdletBinding()]
param (
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true)]
[VmwDscConfiguration]
$Configuration
)
$invokeParams = @{
DscResources = $Configuration.Resources
Method = 'Set'
}
Invoke-VmwDscResources @invokeParams | Out-Null
}
<#
.Description
Invokes the resources of a configuration with 'Test' Dsc method.
Returns a boolean result that shows if the current state is desired.
Use Detailed switch to return an object with state flag and information on resources and their state
#>
function Test-VmwDscConfiguration {
[CmdletBinding()]
param (
[Parameter(
Mandatory = $true,
ValueFromPipeline = $true)]
[VmwDscConfiguration]
$Configuration,
[Parameter(
Mandatory = $false)]
[Switch]
$Detailed
)
$invokeParams = @{
DscResources = $Configuration.Resources
Method = 'Test'
}
$resStateArr = Invoke-VmwDscResources @invokeParams
$result = $null
if ($Detailed) {
$result = [DscTestMethodDetailedResult]::new($Configuration.Resources, $resStateArr)
}
else {
$result = ($resStateArr | Where-Object { $_.InDesiredState -eq $false }).Count -eq 0
}
$result
}
<#
.Description
Invokes an array of dsc resource with the given method
#>
function Invoke-VmwDscResources {
param (
[Parameter(Mandatory)]
[VmwDscResource[]]
$DscResources,
[Parameter(Mandatory)]
[ValidateSet('Get', 'Set', 'Test')]
[string]
$Method
)
$result = New-Object -TypeName 'System.Collections.ArrayList'
# invoke the dsc resources
foreach ($dscResource in $DscResources) {
$invokeResult = $null
if ($dscResource.GetIsComposite()) {
$invokeVmwDscResourceParams = @{
DscResources = $dscResource.GetInnerResources()
Method = $Method
}
$invokeResult = Invoke-VmwDscResources @invokeVmwDscResourceParams
} else {
$invokeDscResourceUtilParams = @{
DscResource = $dscResource
Method = $Method
}
$invokeResult = InvokeDscResourceUtil @invokeDscResourceUtilParams
}
$result.Add($invokeResult) | Out-Null
}
$result.ToArray()
}
<#
.Description
Utility function wraper for invoking dsc resources
#>
function InvokeDscResourceUtil {
param (
[VmwDscResource]
$DscResource,
[string]
$Method
)
# parameters used for Invoke-DscResource cmdlet
# Method property gets set later on inside switch, because it's variable
$invokeSplatParams = @{
Name = $DscResource.ResourceType
ModuleName = $DscResource.ModuleName
Property = $DscResource.Property
}
$invokeResult = $null
if ($Method -eq 'Test' -or $Method -eq 'Get') {
try {
$invokeResult = Invoke-DscResource @invokeSplatParams -Method $Method
} catch {
# if an exception is thrown that means the resource is not in desired state
# due to a dependency not being in desired state
if ($Method -eq 'Test') {
$invokeResult = [PSCustomObject]@{
InDesiredState = $false
}
} else {
$invokeResult = $DscResource
}
}
}
else {
# checks if the resource is in target state
$isInDesiredState = Invoke-DscResource @invokeSplatParams -Method 'Test'
# executes 'set' method only if state is not desired
if ($isInDesiredState.InDesiredState) {
$invokeResult = $isInDesiredState
}
else {
$invokeResult = Invoke-DscResource @invokeSplatParams -Method $Method
}
}
$invokeResult
}
| 30.636816 | 755 | 0.645502 |
b07a2c953118e24e87350478c1ce858191269af6 | 48 | py | Python | config.py | ashtneoi/tantilla | 966b8d024bca46bc7279ed9889683ce308cad190 | [
"MIT"
] | null | null | null | config.py | ashtneoi/tantilla | 966b8d024bca46bc7279ed9889683ce308cad190 | [
"MIT"
] | null | null | null | config.py | ashtneoi/tantilla | 966b8d024bca46bc7279ed9889683ce308cad190 | [
"MIT"
] | null | null | null | import toml
config = toml.load("config.toml")
| 9.6 | 33 | 0.708333 |
ed0637799e3643b4d70292b30ec53865a8f7d261 | 140 | h | C | tools/blur.h | spyteamalex/CPPExercises2021 | 7dbbee4c8002448aeb83a563b09f8b447f509849 | [
"MIT"
] | null | null | null | tools/blur.h | spyteamalex/CPPExercises2021 | 7dbbee4c8002448aeb83a563b09f8b447f509849 | [
"MIT"
] | null | null | null | tools/blur.h | spyteamalex/CPPExercises2021 | 7dbbee4c8002448aeb83a563b09f8b447f509849 | [
"MIT"
] | null | null | null | #pragma once
#include <opencv2/highgui.hpp>
cv::Mat blur(cv::Mat img, double sigma, int radius);
double G(int dx, int dy, double sigma);
| 17.5 | 52 | 0.707143 |
c9a0d5bd5d9c57d0203fb9ff573fd659d87b0407 | 3,440 | ps1 | PowerShell | Get-RepositoryStatus.ps1 | SamuelEnglard/ObjectiveGit | c1aa00ab67c6a1a184f9d0d7552a2918275948c0 | [
"MIT"
] | null | null | null | Get-RepositoryStatus.ps1 | SamuelEnglard/ObjectiveGit | c1aa00ab67c6a1a184f9d0d7552a2918275948c0 | [
"MIT"
] | null | null | null | Get-RepositoryStatus.ps1 | SamuelEnglard/ObjectiveGit | c1aa00ab67c6a1a184f9d0d7552a2918275948c0 | [
"MIT"
] | null | null | null | function Get-RepositoryStatus
{
<#
.Synopsis
Gets the working tree status.
.Description
Gets paths that have differences between the index file and the current HEAD commit, paths that have differences between the working tree and the index file, and paths in the working tree that are not tracked by Git. The first are what you would commit by running git commit; the second and third are what you could commit by running git add before running git commit.
.Parameter Repository
Path to the git repository. Can be relative or absolute. If not specified defaults to the current directory
.Link
https://git-scm.com/docs/git-status
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$False,Position=1,ValueFromPipeline=$True)]
[string]$Repository = ".\"
)
process
{
$Repository = Resolve-Path -Path $Repository
Write-Verbose -Message "Getting status of $Repository"
$RepositoryData = [PSCustomObject]@{}
$Files = New-Object System.Collections.ArrayList
$RepositoryData | Add-Member -MemberType NoteProperty -Name 'RepoPath' -Value $Repository
$Output = (git -C $Repository status --porcelain=2 -b) 2>&1
if (($LASTEXITCODE -eq 128) -or($LASTEXITCODE -eq -1))
{
Write-Error -Message $Output -Category FromStdErr
return
}
if ($LASTEXITCODE -eq 129)
{
Write-Error -Message "Bug with ObjectiveGit. Please file a bug at https://github.com/SamuelEnglard/ObjectiveGit." -Category SyntaxError
return
}
$ErrorsInOutput = $Output | Where-Object -FilterScript { $_ -is [System.Management.Automation.ErrorRecord] }
if (($ErrorsInOutput | Measure-Object | Select-Object -ExpandProperty Count) -gt 0)
{
$ErrorsInOutput | ForEach-Object -Process { Write-Error -ErrorRecord $_ }
return;
}
foreach ($line in $Output)
{
if ($line.StartsWith("# branch.oid"))
{
$RepositoryData | Add-Member -MemberType NoteProperty -Name "CurrentCommit" -Value ($line.Substring(13))
}
elseif ($line.StartsWith("# branch.head"))
{
$RepositoryData | Add-Member -MemberType NoteProperty -Name "CurrentBranch" -Value ($line.Substring(14))
}
elseif ($line -cmatch '1\s([\.MADRCU\?\!][\.MDUA]?)\s(N\.\.\.)\s([0-7]{6})\s([0-7]{6})\s([0-7]{6})\s([0-9a-f]{40})\s([0-9a-f]{40})\s(\S+)')
{
# 1 2 3 4 5 6 7 8
#1 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <path>
$Files.Add([PSCustomObject]@{
Path = (Join-Path -Path $Repository -ChildPath $matches[8])
Status = $matches[1]
}) | Out-Null
}
elseif ($line -cmatch '2\s([\.MADRCU\?\!][\.MDUA]?)\s(N\.\.\.)\s([0-7]{6})\s([0-7]{6})\s([0-7]{6})\s([0-9a-f]{40})\s([0-9a-f]{40})\s([XC])(\d{3})\s(\S+)`t(\S*)')
{
# 1 2 3 4 5 6 7 8 9 10 11
#2 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <X><score> <path><sep><origPath>
$Files.Add([PSCustomObject]@{
Path = (Join-Path -Path $Repository -ChildPath $matches[10])
Status = $matches[1]
OriginalPath = (Join-Path -Path $Repository -ChildPath $matches[11])
IsMove = ($matches[8] -eq "C")
}) | Out-Null
}
elseif ($line -cmatch '\?\s(\S+)')
{
$Files.Add([PSCustomObject]@{
Path = (Join-Path -Path $Repository -ChildPath $matches[1])
Status = "??"
}) | Out-Null
}
else
{
Write-Verbose -Message "Ignoring $line"
}
}
$RepositoryData | Add-Member -MemberType NoteProperty -Name "Files" -Value $Files
Write-Output $RepositoryData
}
} | 38.222222 | 370 | 0.635174 |
133ef92bc63bab4b9adb930eb98f47154a43ff17 | 3,387 | rake | Ruby | lib/tasks/innkeeper.rake | Balavenkateswarlu22/innkeeper | aaa188a76d6614536c3ed14106997604b7ab5cf2 | [
"MIT"
] | 8 | 2019-10-21T14:21:59.000Z | 2021-02-20T11:32:16.000Z | lib/tasks/innkeeper.rake | cpoms/inkeeper | aaa188a76d6614536c3ed14106997604b7ab5cf2 | [
"MIT"
] | 6 | 2019-10-21T16:48:02.000Z | 2021-12-28T10:23:42.000Z | lib/tasks/innkeeper.rake | cpoms/inkeeper | aaa188a76d6614536c3ed14106997604b7ab5cf2 | [
"MIT"
] | 2 | 2019-10-21T16:29:11.000Z | 2021-12-28T10:32:31.000Z | require 'innkeeper/migrator'
require 'parallel'
innkeeper_namespace = namespace :innkeeper do
desc "Create all tenants"
task create: 'db:migrate' do
tenants.each do |tenant|
begin
quietly { Innkeeper::Tenant.create(tenant) }
rescue Innkeeper::TenantExists => e
puts e.message
end
end
end
desc "Migrate all tenants"
task :migrate do
warn_if_tenants_empty
each_tenant do |tenant|
begin
Innkeeper::Migrator.migrate tenant
rescue Innkeeper::TenantNotFound => e
puts e.message
end
end
end
desc "Seed all tenants"
task :seed do
warn_if_tenants_empty
each_tenant do |tenant|
begin
Innkeeper::Tenant.switch(tenant) do
Innkeeper::Tenant.seed
end
rescue Innkeeper::TenantNotFound => e
puts e.message
end
end
end
desc "Rolls the migration back to the previous version (specify steps w/ STEP=n) across all tenants."
task :rollback do
warn_if_tenants_empty
step = ENV['STEP'] ? ENV['STEP'].to_i : 1
each_tenant do |tenant|
begin
Innkeeper::Migrator.rollback tenant, step
rescue Innkeeper::TenantNotFound => e
puts e.message
end
end
end
namespace :migrate do
desc 'Runs the "up" for a given migration VERSION across all tenants.'
task :up do
warn_if_tenants_empty
version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil
raise 'VERSION is required' unless version
each_tenant do |tenant|
begin
Innkeeper::Migrator.run :up, tenant, version
rescue Innkeeper::TenantNotFound => e
puts e.message
end
end
end
desc 'Runs the "down" for a given migration VERSION across all tenants.'
task :down do
warn_if_tenants_empty
version = ENV['VERSION'] ? ENV['VERSION'].to_i : nil
raise 'VERSION is required' unless version
each_tenant do |tenant|
begin
Innkeeper::Migrator.run :down, tenant, version
rescue Innkeeper::TenantNotFound => e
puts e.message
end
end
end
desc 'Rolls back the tenant one migration and re migrate up (options: STEP=x, VERSION=x).'
task :redo do
if ENV['VERSION']
innkeeper_namespace['migrate:down'].invoke
innkeeper_namespace['migrate:up'].invoke
else
innkeeper_namespace['rollback'].invoke
innkeeper_namespace['migrate'].invoke
end
end
end
def each_tenant(&block)
Parallel.each(tenants, in_threads: Innkeeper.parallel_migration_threads) do |tenant|
block.call(tenant)
end
end
def tenants
ENV['DB'] ? ENV['DB'].split(',').map { |s| s.strip } : Innkeeper.tenant_names || []
end
def warn_if_tenants_empty
if tenants.empty?
puts <<-WARNING
[WARNING] - The list of tenants to migrate appears to be empty. This could mean a few things:
1. You may not have created any, in which case you can ignore this message
2. You've run `innkeeper:migrate` directly without loading the Rails environment
* `innkeeper:migrate` is now deprecated. Tenants will automatically be migrated with `db:migrate`
Note that your tenants currently haven't been migrated. You'll need to run `db:migrate` to rectify this.
WARNING
end
end
end
| 26.255814 | 112 | 0.645114 |
fe39a26359b08469d01c59738da62e146b4f4fbc | 92 | sql | SQL | transform/snowflake-dbt/models/staging/gitlab_dotcom/xf/gitlab_dotcom_clusters_applications_elastic_stacks_xf.sql | danieldiamond/gitlab-analytics | f99e02c95c3a964b01cb14617a43cd5f64ecd88d | [
"MIT"
] | 3 | 2021-07-22T06:44:31.000Z | 2022-01-29T05:35:12.000Z | transform/snowflake-dbt/models/staging/gitlab_dotcom/xf/gitlab_dotcom_clusters_applications_elastic_stacks_xf.sql | danieldiamond/gitlab-analytics | f99e02c95c3a964b01cb14617a43cd5f64ecd88d | [
"MIT"
] | null | null | null | transform/snowflake-dbt/models/staging/gitlab_dotcom/xf/gitlab_dotcom_clusters_applications_elastic_stacks_xf.sql | danieldiamond/gitlab-analytics | f99e02c95c3a964b01cb14617a43cd5f64ecd88d | [
"MIT"
] | null | null | null | {{ transform_clusters_applications("gitlab_dotcom_clusters_applications_elastic_stacks") }}
| 46 | 91 | 0.880435 |
0df57822535ef128658aba2778465c841a4c4a8b | 8,852 | cs | C# | CodeStructures/Assignation.cs | koaf/FocusTreeAndEventManagerJP | f473e37c8c4f8f1b61a5a12ca7ee1ce6fcba0fdf | [
"BSD-3-Clause"
] | null | null | null | CodeStructures/Assignation.cs | koaf/FocusTreeAndEventManagerJP | f473e37c8c4f8f1b61a5a12ca7ee1ce6fcba0fdf | [
"BSD-3-Clause"
] | null | null | null | CodeStructures/Assignation.cs | koaf/FocusTreeAndEventManagerJP | f473e37c8c4f8f1b61a5a12ca7ee1ce6fcba0fdf | [
"BSD-3-Clause"
] | null | null | null | using FocusTreeManager.CodeStructures.CodeExceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace FocusTreeManager.CodeStructures
{
[KnownType(typeof(Assignation))]
[KnownType(typeof(CodeBlock))]
[KnownType(typeof(CodeValue))]
[DataContract(Name = "assignation")]
public class Assignation : ICodeStruct
{
[DataMember(Name = "assignee", Order = 0)]
public string Assignee { get; set; }
[DataMember(Name = "value", Order = 1)]
public ICodeStruct Value { get; set; }
[DataMember(Name = "level", Order = 2)]
private int Level;
[DataMember(Name = "operator", Order = 3)]
public string Operator { get; set; }
[DataMember(Name = "line", Order = 4)]
public int Line { get; set; }
[DataMember(Name = "endline", Order = 5)]
public int EndLine { get; set; }
public Assignation()
{
Level = 0;
}
public Assignation(int level)
{
Level = level;
}
internal RecursiveCodeLog Analyse(SyntaxGroup code)
{
Assignee = code.Component.text;
Operator = code.Operator.text;
Line = code.Component.line;
//If we can detect at least one code block
List<SyntaxGroup> list = code.Operand as List<SyntaxGroup>;
if (list != null)
{
try
{
CodeBlock block = new CodeBlock(Level + 1);
RecursiveCodeLog log = block.Analyse(list);
if (log != null)
{
log.AddToRecursiveChain("Error during analysis chain",
Assignee, Line.ToString());
return log;
}
Value = block;
}
catch (Exception)
{
//TODO: Add language support
RecursiveCodeLog log = new RecursiveCodeLog();
log.AddToRecursiveChain("Impossible to analyze associated code",
Assignee, Line.ToString());
return log;
}
}
//If we get pure text
else if (code.Operand is Token)
{
Value = new CodeValue(((Token)code.Operand).text);
}
//If we got a list of tokens, a chain of pure text
else if (code.Operand is List<Token>)
{
Value = new CodeBlock();
((CodeBlock)Value).Analyse((List<Token>)code.Operand);
}
return null;
}
public string Parse(Dictionary<int, string> comments = null, int StartLevel = -1)
{
int BasicLevel = StartLevel == -1 ? Level : StartLevel + 1;
string tabulations = "";
for (int i = 1; i < BasicLevel; i++)
{
tabulations += "\t";
}
StringBuilder content = new StringBuilder();
string endComment = "";
//Check if comments is not null
if (comments != null)
{
//Make a copy for the loop
Dictionary<int, string> localCopy = comments.ToDictionary(t => t.Key, t => t.Value);
//Parse all comments before going further
foreach (KeyValuePair<int, string> comment in localCopy.TakeWhile(i => i.Key < Line))
{
content.Append(tabulations + comment.Value + "\n");
comments.Remove(comment.Key);
}
//Get this lines comments if any
endComment = comments.ContainsKey(Line) ? comments[Line] : "";
//Remove all added
comments.Remove(Line);
}
// If the value is nothing but it has an operator
if ((Value == null || Value is CodeBlock
&& !((CodeBlock)Value).Code.Any())
&& Operator != null)
{
//Check if there are comments in there
string comment = "";
if (comments != null)
{
comment = comments.Where(c => c.Key > Line && c.Key < EndLine)
.Aggregate(comment, (current, item) => tabulations + current + item.Value);
}
//Empty block
content.Append(tabulations + Assignee + " " + Operator + " {\n" +
comment + "\n}" + endComment);
}
//Otherwise, print as usual
else if (Value != null)
{
content.Append(tabulations + Assignee + " " + Operator + " " +
Value.Parse(comments, BasicLevel) + endComment);
}
return content.ToString();
}
public CodeValue FindValue(string TagToFind)
{
if (Assignee == TagToFind)
{
return Value as CodeValue;
}
//If we can,t run through the value, return unfound
if (!(Value is CodeBlock)) return null;
CodeValue found = Value.FindValue(TagToFind);
return found;
}
public ICodeStruct Extract(string TagToFind)
{
if (Assignee == TagToFind)
{
return this;
}
//If value cannot be ran through, return unfound
if (!(Value is CodeBlock)) return null;
ICodeStruct found = Value.Extract(TagToFind);
//Return what was found, cannot extract from an assignation,
//should extract in parent container
return found;
}
public Assignation FindAssignation(string TagToFind)
{
if (Assignee == TagToFind)
{
return this;
}
//If value cannot be ran through, return unfound.
if (!(Value is CodeBlock)) return null;
Assignation found = Value.FindAssignation(TagToFind);
return found;
}
public List<ICodeStruct> FindAllValuesOfType<T>(string TagToFind)
{
List<ICodeStruct> founds = new List<ICodeStruct>();
if (Value == null)
{
//Empty block (Paradox loves these....)
return founds;
}
if (Assignee == TagToFind
&& (Value.GetType() == typeof(T) ||
Value is T))
{
founds.Add(Value);
return founds;
}
//If we haven't found this element as our tag, search in childs
if (Value is CodeBlock)
{
founds.AddRange(Value.FindAllValuesOfType<T>(TagToFind));
}
return founds;
}
public Script GetContentAsScript(string[] except, Dictionary<int, string> Comments = null)
{
Script newScript = new Script();
if (Value is CodeBlock)
{
foreach (ICodeStruct codeStruct in ((CodeBlock)Value).Code)
{
Assignation item = (Assignation)codeStruct;
if (!except.Contains(item.Assignee))
{
newScript.Code.Add(item);
}
}
}
else
{
//TODO: Add language support
RecursiveCodeLog log = new RecursiveCodeLog();
log.AddToRecursiveChain("Impossible to obtain content, assigned value is not code",
Assignee, Line.ToString());
newScript.Logger.Errors.Add(new SyntaxError(log.Message));
}
//If no comments are given
if (Comments == null) return newScript;
Assignation firstLine = newScript.Code.Where(i => i is Assignation)
.OrderBy(i => ((Assignation)i).Line).FirstOrDefault() as Assignation;
Assignation lastLine = newScript.Code.Where(i => i is Assignation)
.OrderBy(i => ((Assignation)i).Line).LastOrDefault() as Assignation;
//If no lines were found
if (firstLine == null || lastLine == null) return newScript;
//Try to get the comments
newScript.Comments = Comments.SkipWhile(c => c.Key < firstLine.Line)
.TakeWhile(c => c.Key <= lastLine.Line)
.ToDictionary(c => c.Key, c => c.Value);
return newScript;
}
}
}
| 37.193277 | 101 | 0.489946 |
e84389bd0046cf92bbbafed4c4290d23e347066d | 1,757 | cs | C# | tests/TerraSdk.Test/ClientOld/Serialization/HexStringByteArrayConverterTest.cs | ridicoulous/terrasdk-dotnet | c586912558f5d2f20706add4e898b03884f8b69c | [
"MIT"
] | null | null | null | tests/TerraSdk.Test/ClientOld/Serialization/HexStringByteArrayConverterTest.cs | ridicoulous/terrasdk-dotnet | c586912558f5d2f20706add4e898b03884f8b69c | [
"MIT"
] | null | null | null | tests/TerraSdk.Test/ClientOld/Serialization/HexStringByteArrayConverterTest.cs | ridicoulous/terrasdk-dotnet | c586912558f5d2f20706add4e898b03884f8b69c | [
"MIT"
] | null | null | null | using System.Linq;
using TerraSdk.Common.Extensions;
using Xunit;
namespace TerraSdk.Test.ClientOld.Serialization
{
public class HexStringByteArrayConverterTest
{
[Fact]
public void ByteArrayConvertsToStringCorrectly()
{
var allBytes = Enumerable.Range(0, 256).Select(n => (byte) n).ToArray();
var str = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF";
Assert.Equal(str, allBytes.ToHexString());
}
[Fact]
public void StringConvertsToByteArrayCorrectly()
{
var allBytes = Enumerable.Range(0, 256).Select(n => (byte) n).ToArray();
var str = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9FA0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF";
Assert.Equal(allBytes, ByteArrayExtensions.ParseHexString(str));
}
}
} | 65.074074 | 537 | 0.829254 |
25a2a47cfc2dc606b6eb402ebeb3a5f1419cbcf0 | 398 | js | JavaScript | components/Item/index.js | jhta/codechallenge-sellics | 0e981e1ed79e32744247b926ccd85af9dde47081 | [
"MIT"
] | null | null | null | components/Item/index.js | jhta/codechallenge-sellics | 0e981e1ed79e32744247b926ccd85af9dde47081 | [
"MIT"
] | null | null | null | components/Item/index.js | jhta/codechallenge-sellics | 0e981e1ed79e32744247b926ccd85af9dde47081 | [
"MIT"
] | null | null | null | import React from 'react'
import PropTypes from 'prop-types'
import Meta from './Meta'
import { ItemStyled, Description } from './styled'
const Item = (props) => (
<ItemStyled>
<Meta {...props} />
<h2>{ props.title }</h2>
<Description>{ props.content }</Description>
</ItemStyled>
)
Item.propTypes = {
title: PropTypes.string,
content: PropTypes.string
}
export default Item
| 19.9 | 50 | 0.668342 |
fe14b5678ed67717d0782da9049afe38f02854a2 | 115 | sql | SQL | database/scripts/updates/fase_3/11_TerminosCondiciones/1_alter_tbl_order.sql | DecoWM/bitecm_store | f6f0a1a1dee4d8d45b89d8925f9d00c83edd3ca9 | [
"MIT"
] | null | null | null | database/scripts/updates/fase_3/11_TerminosCondiciones/1_alter_tbl_order.sql | DecoWM/bitecm_store | f6f0a1a1dee4d8d45b89d8925f9d00c83edd3ca9 | [
"MIT"
] | null | null | null | database/scripts/updates/fase_3/11_TerminosCondiciones/1_alter_tbl_order.sql | DecoWM/bitecm_store | f6f0a1a1dee4d8d45b89d8925f9d00c83edd3ca9 | [
"MIT"
] | null | null | null | USE `bitel_ecommerce`;
ALTER TABLE tbl_order ADD COLUMN terminos_condiciones TINYINT(1) DEFAULT 0 AFTER total_igv; | 38.333333 | 91 | 0.834783 |
4a34bfc3176990382053c7e7bbaaa7e45abef849 | 598 | asm | Assembly | programs/oeis/232/A232746.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/232/A232746.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/232/A232746.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A232746: n occurs A030124(n) times; a(n) = one less than the least k such that A005228(k) > n.
; 1,1,2,2,2,2,3,3,3,3,3,4,4,4,4,4,4,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10
add $0,4
mul $0,7
mov $2,7
mov $3,4
lpb $0
sub $0,1
seq $3,142 ; Factorial numbers: n! = 1*2*3*4*...*n (order of symmetric group S_n, number of permutations of n letters).
sub $0,$3
add $2,8
sub $0,$2
trn $0,1
add $0,1
mov $1,1
add $2,1
add $1,$2
mov $3,1
lpe
sub $1,17
div $1,9
add $1,1
mov $0,$1
| 23.92 | 179 | 0.573579 |
b43e6dbcdc5be2bf69a53cb6eb4d8ea289fa1a9f | 1,194 | dart | Dart | client/lib/main.dart | iberatkaya/chat_app | f24342cfe945ff0a2047442a3894a45c1bb58c9b | [
"Apache-2.0"
] | 8 | 2020-10-03T18:37:55.000Z | 2022-02-27T18:42:52.000Z | client/lib/main.dart | iberatkaya/chat_app | f24342cfe945ff0a2047442a3894a45c1bb58c9b | [
"Apache-2.0"
] | 1 | 2021-05-25T05:05:48.000Z | 2021-05-27T09:17:51.000Z | client/lib/main.dart | iberatkaya/chat_app | f24342cfe945ff0a2047442a3894a45c1bb58c9b | [
"Apache-2.0"
] | 4 | 2021-02-25T09:12:11.000Z | 2021-07-30T06:32:19.000Z | import 'dart:io';
import 'package:client/presentation/home.dart';
import 'package:flutter/material.dart';
void main() {
HttpOverrides.global = new MyHttpOverrides();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Chat App',
theme: ThemeData(
appBarTheme: AppBarTheme(
elevation: 1,
),
primarySwatch: Colors.blue,
accentColor: Colors.white,
visualDensity: VisualDensity.adaptivePlatformDensity,
buttonColor: Colors.blue,
buttonTheme: ButtonThemeData(
buttonColor: Colors.blue,
textTheme: ButtonTextTheme.accent,
padding: EdgeInsets.symmetric(vertical: 14, horizontal: 20),
shape:
RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),
),
home: HomePage(),
);
}
}
class MyHttpOverrides extends HttpOverrides {
@override
HttpClient createHttpClient(SecurityContext context) {
return super.createHttpClient(context)
..badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
}
}
| 27.767442 | 80 | 0.659966 |
732a677e2e9e040f05d47f725eb03d5fba763793 | 443 | lua | Lua | Mods/S7_Config_de8f15f2-65a2-4ee4-a25f-7a7ab0305a58/Story/RawFiles/Lua/BootstrapClient.lua | HunterGhost27/Stats-Configurator | a0394e0f3f3c5dab7d4798fa61c4d8bfaa5a1181 | [
"MIT"
] | 2 | 2020-10-01T17:17:47.000Z | 2020-10-22T11:40:35.000Z | Mods/S7_Config_de8f15f2-65a2-4ee4-a25f-7a7ab0305a58/Story/RawFiles/Lua/BootstrapClient.lua | Shresht7/Stats-Configurator | a0394e0f3f3c5dab7d4798fa61c4d8bfaa5a1181 | [
"MIT"
] | 25 | 2020-07-21T05:31:23.000Z | 2021-02-20T12:25:12.000Z | Mods/S7_Config_de8f15f2-65a2-4ee4-a25f-7a7ab0305a58/Story/RawFiles/Lua/BootstrapClient.lua | Shresht7/Stats-Configurator | a0394e0f3f3c5dab7d4798fa61c4d8bfaa5a1181 | [
"MIT"
] | null | null | null | -- =======
-- IMPORTS
-- =======
Ext.Require('Auxiliary.lua')
Ext.Require('Shared/Collections.lua')
Ext.Require('Shared/References.lua')
Ext.Require('Shared/StatsConfigurator.lua')
Ext.Require('Client/Networking.lua')
Ext.Require('Client/StatsLoader.lua')
-- UI-COMPONENTS-LIBRARY INTEGRATION
-- =================================
if Ext.IsModLoaded('b66d56c6-12f9-4abc-844f-0c30b89d32e4') then Ext.Require('Client/ContextMenu.lua') end | 29.533333 | 105 | 0.672686 |
70a7d226686764bbbac7c068868122d87d1bd3ee | 8,388 | rs | Rust | examples/circle/main.rs | jrmuizel/metal-rs | 0b04e6524b8a0426f5a2413ff824de2aab12d634 | [
"Apache-2.0",
"MIT"
] | null | null | null | examples/circle/main.rs | jrmuizel/metal-rs | 0b04e6524b8a0426f5a2413ff824de2aab12d634 | [
"Apache-2.0",
"MIT"
] | null | null | null | examples/circle/main.rs | jrmuizel/metal-rs | 0b04e6524b8a0426f5a2413ff824de2aab12d634 | [
"Apache-2.0",
"MIT"
] | null | null | null | use metal::*;
use winit::platform::macos::WindowExtMacOS;
use winit::{
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
};
use cocoa::{appkit::NSView, base::id as cocoa_id};
use objc::runtime::YES;
use std::mem;
// Declare the data structures needed to carry vertex layout to
// metal shading language(MSL) program. Use #[repr(C)], to make
// the data structure compatible with C++ type data structure
// for vertex defined in MSL program as MSL program is broadly
// based on C++
#[repr(C)]
#[derive(Debug)]
pub struct position(cty::c_float, cty::c_float);
#[repr(C)]
#[derive(Debug)]
pub struct color(cty::c_float, cty::c_float, cty::c_float);
#[repr(C)]
#[derive(Debug)]
pub struct AAPLVertex {
p: position,
c: color,
}
fn main() {
// Create a window for viewing the content
let event_loop = EventLoop::new();
let events_loop = winit::event_loop::EventLoop::new();
let size = winit::dpi::LogicalSize::new(800, 600);
let window = winit::window::WindowBuilder::new()
.with_inner_size(size)
.with_title("Metal".to_string())
.build(&events_loop)
.unwrap();
// Set up the GPU device found in the system
let device = Device::system_default().expect("no device found");
println!("Your device is: {}", device.name(),);
let library_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("examples/circle/shaders.metallib");
// Use the metallib file generated out of .metal shader file
let library = device.new_library_with_file(library_path).unwrap();
// The render pipeline generated from the vertex and fragment shaders in the .metal shader file.
let pipeline_state = prepare_pipeline_state(&device, &library);
// Set the command queue used to pass commands to the device.
let command_queue = device.new_command_queue();
// Currently, CoreAnimationLayer is the only interface that provide
// layers to carry drawable texture from GPU rendaring through metal
// library to viewable windows.
let layer = CoreAnimationLayer::new();
layer.set_device(&device);
layer.set_pixel_format(MTLPixelFormat::BGRA8Unorm);
layer.set_presents_with_transaction(false);
unsafe {
let view = window.ns_view() as cocoa_id;
view.setWantsLayer(YES);
view.setLayer(mem::transmute(layer.as_ref()));
}
let draw_size = window.inner_size();
layer.set_drawable_size(CGSize::new(draw_size.width as f64, draw_size.height as f64));
let vbuf = {
let vertex_data = create_vertex_points_for_circle();
let vertex_data = vertex_data.as_slice();
device.new_buffer_with_data(
vertex_data.as_ptr() as *const _,
(vertex_data.len() * mem::size_of::<AAPLVertex>()) as u64,
MTLResourceOptions::CPUCacheModeDefaultCache | MTLResourceOptions::StorageModeManaged,
)
};
event_loop.run(move |event, _, control_flow| {
// ControlFlow::Wait pauses the event loop if no events are available to process.
// This is ideal for non-game applications that only update in response to user
// input, and uses significantly less power/CPU time than ControlFlow::Poll.
*control_flow = ControlFlow::Wait;
match event {
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
} => {
println!("The close button was pressed; stopping");
*control_flow = ControlFlow::Exit
}
Event::MainEventsCleared => {
// Queue a RedrawRequested event.
window.request_redraw();
}
Event::RedrawRequested(_) => {
// It's preferrable to render in this event rather than in MainEventsCleared, since
// rendering in here allows the program to gracefully handle redraws requested
// by the OS.
let drawable = match layer.next_drawable() {
Some(drawable) => drawable,
None => return,
};
// Create a new command buffer for each render pass to the current drawable
let command_buffer = command_queue.new_command_buffer();
// Obtain a renderPassDescriptor generated from the view's drawable textures.
let render_pass_descriptor = RenderPassDescriptor::new();
prepare_render_pass_descriptor(&render_pass_descriptor, drawable.texture());
// Create a render command encoder.
let encoder = command_buffer.new_render_command_encoder(&render_pass_descriptor);
encoder.set_render_pipeline_state(&pipeline_state);
// Pass in the parameter data.
encoder.set_vertex_buffer(0, Some(&vbuf), 0);
// Draw the triangles which will eventually form the circle.
encoder.draw_primitives(MTLPrimitiveType::TriangleStrip, 0, 1080);
encoder.end_encoding();
// Schedule a present once the framebuffer is complete using the current drawable.
command_buffer.present_drawable(&drawable);
// Finalize rendering here & push the command buffer to the GPU.
command_buffer.commit();
}
_ => (),
}
});
}
// If we want to draw a circle, we need to draw it out of the three primitive
// types available with metal framework. Triangle is used in this case to form
// the circle. If we consider a circle to be total of 360 degree at center, we
// can form small triangle with one point at origin and two points at the
// perimeter of the circle for each degree. Eventually, if we can take enough
// triangle virtices for total of 360 degree, the triangles together will
// form a circle. This function captures the triangle vertices for each degree
// and push the co-ordinates of the vertices to a rust vector
fn create_vertex_points_for_circle() -> Vec<AAPLVertex> {
let mut v: Vec<AAPLVertex> = Vec::new();
let origin_x: f32 = 0.0;
let origin_y: f32 = 0.0;
// Size of the circle
let circle_size = 0.8f32;
for i in 0..720 {
let y = i as f32;
// Get the X co-ordinate of each point on the perimeter of circle
let position_x: f32 = y.to_radians().cos() * 100.0;
let position_x: f32 = position_x.trunc() / 100.0;
// Set the size of the circle
let position_x: f32 = position_x * circle_size;
// Get the Y co-ordinate of each point on the perimeter of circle
let position_y: f32 = y.to_radians().sin() * 100.0;
let position_y: f32 = position_y.trunc() / 100.0;
// Set the size of the circle
let position_y: f32 = position_y * circle_size;
v.push(AAPLVertex {
p: position(position_x, position_y),
c: color(0.7, 0.3, 0.5),
});
if (i + 1) % 2 == 0 {
// For each two points on perimeter, push one point of origin
v.push(AAPLVertex {
p: position(origin_x, origin_y),
c: color(0.2, 0.7, 0.4),
});
}
}
v
}
fn prepare_render_pass_descriptor(descriptor: &RenderPassDescriptorRef, texture: &TextureRef) {
let color_attachment = descriptor.color_attachments().object_at(0).unwrap();
color_attachment.set_texture(Some(texture));
color_attachment.set_load_action(MTLLoadAction::Clear);
// Setting a background color
color_attachment.set_clear_color(MTLClearColor::new(0.5, 0.5, 0.8, 1.0));
color_attachment.set_store_action(MTLStoreAction::Store);
}
fn prepare_pipeline_state(device: &Device, library: &Library) -> RenderPipelineState {
let vert = library.get_function("vs", None).unwrap();
let frag = library.get_function("ps", None).unwrap();
let pipeline_state_descriptor = RenderPipelineDescriptor::new();
pipeline_state_descriptor.set_vertex_function(Some(&vert));
pipeline_state_descriptor.set_fragment_function(Some(&frag));
pipeline_state_descriptor
.color_attachments()
.object_at(0)
.unwrap()
.set_pixel_format(MTLPixelFormat::BGRA8Unorm);
device
.new_render_pipeline_state(&pipeline_state_descriptor)
.unwrap()
}
| 38.833333 | 100 | 0.644492 |
797cf3e0aa7f153fecbfe5480633538ef4d5767e | 290 | php | PHP | site/snippets/content/tweets.php | eXpl0it3r/sfmlprojects | 99c91e45db9b12d7f021a042c308cffb3acbf3df | [
"MIT"
] | 9 | 2017-08-21T13:46:28.000Z | 2021-12-04T10:31:46.000Z | site/snippets/content/tweets.php | eXpl0it3r/SFMLProjects | 858e01b3ff3cfc297453288ed05ba5ff218c6012 | [
"MIT"
] | 8 | 2018-01-26T20:23:54.000Z | 2021-01-25T13:36:07.000Z | site/snippets/content/tweets.php | eXpl0it3r/SFMLProjects | 858e01b3ff3cfc297453288ed05ba5ff218c6012 | [
"MIT"
] | 2 | 2017-12-05T05:10:39.000Z | 2021-12-04T10:31:47.000Z | <a class="twitter-timeline" data-width="520" data-tweet-limit="3" data-dnt="true" data-link-color="#3B94D9" href="https://twitter.com/<?php echo $twitter_handle; ?>">Tweets by <?php echo $twitter_handle; ?></a> <script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> | 290 | 290 | 0.710345 |
052a2ed42eb61cc57d0e52bc2e3b6f299d576f78 | 531 | rb | Ruby | server/commands/console/guild_command_helpers.rb | bytebin/deepworld-gameserver | 429146d8b4cb845457515fddc843aed96ad1ec6b | [
"MIT"
] | 39 | 2019-09-04T06:17:08.000Z | 2022-01-16T19:35:57.000Z | server/commands/console/guild_command_helpers.rb | erauqssidlroweht-hub/deepworld-game-server | 2df85d561e75f78edc43698e4ec6fe9cf5c3be39 | [
"MIT"
] | 2 | 2019-09-14T02:51:19.000Z | 2021-01-22T23:44:25.000Z | server/commands/console/guild_command_helpers.rb | erauqssidlroweht-hub/deepworld-game-server | 2df85d561e75f78edc43698e4ec6fe9cf5c3be39 | [
"MIT"
] | 12 | 2019-09-04T22:53:54.000Z | 2022-02-07T22:39:39.000Z | module GuildCommandHelpers
def validate_guild_member
@errors << "Sorry, you are not a member of a guild." unless player.guild
end
def validate_guild_owner
unless player.guild && player.guild.leader?(player.id)
@errors << "Sorry, you are not a guild leader."
end
end
def validate_names_set
unless player.guild.name && player.guild.short_name && player.guild.name.length > 0 && player.guild.short_name.length > 0
@errors << "Please set your guilds name and shortname first."
end
end
end
| 29.5 | 125 | 0.706215 |
e4b4c1f8ff27940aab416804f9ad95792378f2c0 | 960 | rs | Rust | src/tex_the_program/section_1233.rs | crlf0710/tex-rs | 9e3950423ec57175484794904151c92ee4adaa68 | [
"Apache-2.0",
"MIT"
] | 18 | 2020-10-08T04:25:49.000Z | 2022-02-12T04:34:00.000Z | src/tex_the_program/section_1233.rs | crlf0710/tex-rs | 9e3950423ec57175484794904151c92ee4adaa68 | [
"Apache-2.0",
"MIT"
] | 2 | 2021-01-03T07:10:54.000Z | 2022-02-03T05:07:07.000Z | src/tex_the_program/section_1233.rs | crlf0710/tex-rs | 9e3950423ec57175484794904151c92ee4adaa68 | [
"Apache-2.0",
"MIT"
] | 3 | 2020-12-11T09:12:56.000Z | 2021-11-11T13:51:48.000Z | //! ` `
// @<Let |n| be the largest...@>=
pub(crate) macro Let_n_be_the_largest_legal_code_value__based_on_cur_chr($globals:expr, $n:expr, $cur_chr:expr) {
// if cur_chr=cat_code_base then n:=max_char_code
if $cur_chr.get() == cat_code_base {
$n = max_char_code as _;
use crate::section_0207::max_char_code;
}
// else if cur_chr=math_code_base then n:=@'100000
else if $cur_chr.get() == math_code_base {
$n = 0o100000;
}
// else if cur_chr=sf_code_base then n:=@'77777
else if $cur_chr.get() == sf_code_base {
$n = 0o77777;
}
// else if cur_chr=del_code_base then n:=@'77777777
else if $cur_chr.get() == del_code_base {
$n = 0o77777777;
}
// else n:=255
else {
$n = 255;
}
use crate::section_0230::cat_code_base;
use crate::section_0230::math_code_base;
use crate::section_0230::sf_code_base;
use crate::section_0236::del_code_base;
}
| 30.967742 | 113 | 0.626042 |
af55f3a7433d9ebd37b472410cde20da3e3b79df | 9,923 | py | Python | wapcli.py | mmmaaaggg/easytrader | 10bfc85fad2cbbb668a65e7633d171be9e0d7532 | [
"MIT"
] | 1 | 2017-11-07T03:26:33.000Z | 2017-11-07T03:26:33.000Z | wapcli.py | mmmaaaggg/easytrader | 10bfc85fad2cbbb668a65e7633d171be9e0d7532 | [
"MIT"
] | null | null | null | wapcli.py | mmmaaaggg/easytrader | 10bfc85fad2cbbb668a65e7633d171be9e0d7532 | [
"MIT"
] | 1 | 2020-07-28T22:32:30.000Z | 2020-07-28T22:32:30.000Z | # -*- coding: utf-8 -*-
"""
Created on 2017/9/18
@author: MG
"""
import click
import easytrader
from termcolor import cprint
import os
from datetime import datetime, timedelta
import time
import logging
import pandas as pd
from collections import OrderedDict
from easytrader.log import log
from threading import Thread
def load_stock_order():
"""加载csv文件,导入并备份为 [.yyyy-mm-dd HH_MM_SS.bak 结尾的文件"""
base_dir = './auto_order_dir'
file_name_list = os.listdir(base_dir)
if file_name_list is None:
log.info('No file')
data_df = None
for file_name in file_name_list:
file_base_name, file_extension = os.path.splitext(file_name)
if file_extension != '.csv':
continue
file_path = os.path.join(base_dir, file_name)
data_df_tmp = pd.read_csv(file_path, index_col='CodeDigit', header=0, skipinitialspace=True)
if data_df is None:
data_df_tmp.index = ['%06d' % stock_code for stock_code in data_df_tmp.index]
data_df = data_df_tmp
else:
data_df = data_df.append(data_df_tmp)
backup_file_name = file_base_name + datetime.now().strftime('%Y-%m-%d %H_%M_%S') + file_extension + '.bak'
os.rename(file_path, os.path.join(base_dir, backup_file_name))
if data_df is not None:
has_error = False
# data_df.rename(columns={k1: k2 for k1, k2 in
# zip(data_df.columns, ['final_position', 'ref_price', 'wap_mode'])}, inplace=True)
# 重复数据检测
for name, index in data_df.groupby(level=0).groups.items():
if len(index) > 1:
has_error = True
log.error('%s 存在%d条重复数据', name, len(index))
col_name_set = set(data_df.columns)
for col_name in {'Lot', 'TargetPrice', 'Algo'}:
if col_name not in col_name_set:
has_error = True
log.error('stock_target_df should has %s column', col_name)
if has_error:
raise ValueError('csv 文件存在格式或内容问题')
data_df.rename(columns={
'Lot': 'final_position',
'TargetPrice': 'ref_price',
'Algo': 'wap_mode',
}, inplace=True)
return data_df
def validate_time(ctx, param, value: str):
try:
time_obj = None if value.strip() == "" else datetime.strptime(
datetime.now().strftime('%Y-%m-%d ') + value, '%Y-%m-%d %H:%M:%S')
return time_obj
except:
raise click.BadParameter('时间格式:HH:MM:SS')
def abort_if_false(ctx, param, value):
if not value:
ctx.abort()
# @click.command()
# @click.option('--use', help='指定券商 [ht, yjb, yh, gzzq]')
# @click.option('--prepare', type=click.Path(exists=True), help='指定登录账户文件路径')
# @click.option('--debug', default=False, help='是否输出 easytrader 的 debug 日志')
def main(config_path, use, debug=False):
if config_path is not None and use in ['ht', 'yjb', 'yh', 'gf', 'xq', 'gzzq']:
user = easytrader.use(use, debug)
user.prepare(config_path)
else:
raise ValueError("prepare=%s, use=%s" % (config_path, use))
# 根据输入命令执行,相应指令
print_red = lambda x: cprint(x, 'red')
print_green = lambda x: cprint(x, 'green')
print("*" * 10, '欢迎使用广发证券版 easytrader 控制台 version:0.1', '*' * 10)
stock_target_df = None
command_num_desc_dic = OrderedDict([
(0, '退出'),
(1, '导入股票列表'),
(2, '查询目标股票列表'),
(3, '查询当前持仓'),
(4, '查询合并后交易列表'),
(5, '执行算法交易'),
(6, '对比执行结果'),
(7, '全部撤单'),
(8, '执行一次买/卖操作'),
(9, '全部对手价下单'),
(10, '监控投资组合收益变化'),
])
while True:
for command_num_desc in command_num_desc_dic.items():
print('输入 %d:%s' % command_num_desc)
try:
command_num = int(input("输入:"))
if command_num == 0:
log.info('退出')
break
elif command_num == 1:
log.info('导入列表')
stock_target_df = load_stock_order()
print(stock_target_df)
elif command_num == 2:
log.info('查询目标股票列表')
# position_df = user.position
print(stock_target_df)
elif command_num == 3:
log.info('查询当前持仓')
position_df = user.position
print(position_df)
elif command_num == 4:
log.info('查询合并后交易列表')
stock_bs_df = user.reform_order(stock_target_df)
log.info('\n%s', stock_bs_df)
elif command_num == 5:
@click.command()
@click.option('--datetime_start', callback=validate_time, prompt="起始执行时间(HH:MM:SS)(空格为当前时刻)")
@click.option('--datetime_end', callback=validate_time, prompt="结束执行时间(HH:MM:SS)",
default='9:35:00')
@click.option('--interval', type=click.INT, prompt="执行间隔时长(秒)", default=10)
@click.option('--side', type=click.IntRange(0,2), prompt="执行买卖方向 0 买卖 / 1 只买 / 2 只卖", default=0)
@click.option('--yes', is_flag=True, callback=abort_if_false, expose_value=True, default=True,
prompt='确认开始执行')
def run_auto_order(**kwargs):
config = kwargs.copy()
if 'datetime_start' not in config or config['datetime_start'] is None:
config['datetime_start'] = datetime.now()
datetime_start = config['datetime_start']
if datetime_start > datetime.now():
log.info('算法交易将于 %s 开始执行' % datetime_start.strftime('%Y-%m-%d %H:%M:%S'))
while datetime_start > datetime.now():
time.sleep(1)
log.info("执行算法交易 开始")
user.auto_order(stock_target_df, config)
log.info("执行算法交易 结束")
log.info("对比执行结果")
user.compare_result(stock_target_df)
run_auto_order(standalone_mode=False)
elif command_num == 6:
log.info(command_num_desc_dic[command_num])
user.compare_result(stock_target_df)
elif command_num == 7:
log.info(command_num_desc_dic[command_num])
is_ok = inputYN()
if is_ok:
user.cancel_all_apply()
elif command_num == 8:
log.info(command_num_desc_dic[command_num])
is_ok = inputYN()
if is_ok:
datetime_start = datetime.now()
datetime_end = datetime.now()
config = {'datetime_end': datetime_end, 'datetime_start': datetime_start,
'aggregate_auction': False, 'once': True, 'final_deal': False,
'side': 0}
user.auto_order(stock_target_df, config)
elif command_num == 9:
log.info(command_num_desc_dic[command_num])
is_ok = inputYN()
if is_ok:
datetime_start = datetime.now()
datetime_end = datetime.now()
config = {'datetime_end': datetime_end, 'datetime_start': datetime_start,
'aggregate_auction': False, 'once': True, 'final_deal': False,
'side': 0, 'keep_wap_mode': 'twap_initiative'}
user.auto_order(stock_target_df, config)
elif command_num == 10:
log.info(command_num_desc_dic[command_num])
@click.command()
@click.option('--second_interval', type=click.INT, prompt="执行间隔时长(秒)", default=60)
@click.option('--drawback_last', type=click.FLOAT, prompt="上个统计日累计回撤(%)", default=0)
@click.option('--drawback_target', type=click.FLOAT, prompt="总体目标回撤(%)", default=0)
@click.option('--yes', is_flag=True, callback=abort_if_false, expose_value=True, default=True,
prompt='确认开始执行')
def run_monitor(**kwargs):
user.monitor_running = True
# user.monitor_md(stock_target_df)
second_interval = kwargs.setdefault('second_interval', 60)
drawback_last = kwargs.setdefault('drawback_last', 0)
drawback_target = kwargs.setdefault('drawback_target', 0)
warning_line = drawback_target - drawback_last
log.info("当前组合目标回撤:%.2f%%", warning_line)
thread = Thread(target=user.monitor_md, name="monitor_md",
args=(stock_target_df, second_interval, warning_line),
daemon=True)
thread.start()
input_str = input("输入任意字符回车后退出监控退出")
if len(input_str) > 0:
user.monitor_running = False
thread.join(1)
log.info("退出监控程序")
run_monitor(standalone_mode=False)
else:
log.warning('未知命令')
except click.exceptions.Abort:
pass
except:
log.exception('command run exception')
def inputYN():
is_ok = False
for _ in range(3):
ok_str = input("确认开始执行(y/n)(默认y):")
ok_str = 'y' if ok_str == "" else ok_str
if ok_str == 'y' or ok_str == 'Y':
is_ok = True
break
elif ok_str == 'n' or ok_str == 'N':
is_ok = False
break
else:
print("%s 格式不对" % ok_str)
return is_ok
if __name__ == "__main__":
main(config_path="json/gzzq.json", use="gzzq")
# 测试文件导入
# data_df = load_stock_order()
# print(data_df)
| 40.502041 | 115 | 0.537942 |
5ede9b7b83e35a9e2f207a31f0b7f0d543d45928 | 6,494 | asm | Assembly | laser.asm | adamsmasher/bustfree | 446d6777f42d3baa57f29ec9e4613a3e5cd4afe9 | [
"MIT"
] | null | null | null | laser.asm | adamsmasher/bustfree | 446d6777f42d3baa57f29ec9e4613a3e5cd4afe9 | [
"MIT"
] | null | null | null | laser.asm | adamsmasher/bustfree | 446d6777f42d3baa57f29ec9e4613a3e5cd4afe9 | [
"MIT"
] | null | null | null | INCLUDE "laser.inc"
INCLUDE "paddle.inc"
MAX_LASERS EQU 4
ALL_LASERS_FIRED EQU %00001111
LASER_TILE EQU 4
SECTION "LaserRAM", WRAM0
LaserXs: DS MAX_LASERS
LaserYs: DS MAX_LASERS
NextLaser: DS 1
ActiveLasers: DS 1
CurrentLaser: DS 1
SECTION "Laser", ROM0
InitLaserXs: LD HL, LaserXs
LD A, -8
LD B, MAX_LASERS
.loop LD [HLI], A
DEC B
JR NZ, .loop
RET
InitLaserYs: LD HL, LaserYs
LD A, -16
LD B, MAX_LASERS
.loop LD [HLI], A
DEC B
JR NZ, .loop
RET
InitLasers:: CALL InitLaserXs
CALL InitLaserYs
XOR A
LD [ActiveLasers], A
RET
SetupLaserYsOAM: LD DE, ShadowOAM+44
LD HL, LaserYs
LD B, MAX_LASERS
.loop LD A, [HLI]
LD [DE], A
LD A, E
ADD 4
LD E, A
DEC B
JR NZ, .loop
RET
SetupLaserXsOAM: LD DE, ShadowOAM+44+1
LD HL, LaserXs
LD B, MAX_LASERS
.loop LD A, [HLI]
LD [DE], A
LD A, E
ADD 4
LD E, A
DEC B
JR NZ, .loop
RET
SetupLaserTilesOAM: LD HL, ShadowOAM+44+2
LD B, MAX_LASERS
.loop LD [HL], LASER_TILE
LD A, L
ADD 4
LD L, A
DEC B
JR NZ, .loop
RET
SetupLasersOAM:: CALL SetupLaserYsOAM
CALL SetupLaserXsOAM
CALL SetupLaserTilesOAM
RET
FindNextLaser: LD A, [ActiveLasers]
LD HL, NextLaser
LD [HL], 0
.loop RRCA
RET NC
INC [HL]
JR .loop
MarkNextLaser: LD A, [NextLaser]
LD B, 1
AND A
JR Z, .done
.loop SLA B
DEC A
JR NZ, .loop
.done LD HL, ActiveLasers
LD A, [HL]
OR B
LD [HL], A
RET
FireLaser:: LD A, [ActiveLasers]
CP ALL_LASERS_FIRED
RET Z
CALL FindNextLaser
LD A, [NextLaser]
LD HL, LaserYs
ADD L
LD L, A
LD [HL], PADDLE_Y - LASER_HEIGHT
LD A, [NextLaser]
LD HL, LaserXs
ADD L
LD L, A
LD A, [PaddleX+1]
ADD PADDLE_WIDTH/2 - 4
LD [HL], A
CALL MarkNextLaser
RET
UpdateLasers:: CALL MoveLasers
CALL CheckForCollisions
CALL ClearInactiveLasers
RET
CheckCurrentLaser: ; get X position
LD HL, LaserXs
LD A, [CurrentLaser]
ADD L
LD L, A
LD A, [HL]
; are we in bounds on the right?
CP 148
RET NC
; get column
SUB 20 ; account for OAM, padding, and the fact that we want to check the center
RET C ; return if we're not in bounds on the left
SRL A
SRL A
SRL A
LD [HitBrickCol], A
; get Y position
LD HL, LaserYs
LD A, [CurrentLaser]
ADD L
LD L, A
LD A, [HL]
; are we in bounds on the bottom?
CP 96
RET NC
; get row
SUB 32 ; return if we're not in bounds on the top
RET C
SRL A
SRL A
LD [HitBrickRow], A
XOR A
LD [Collided], A
CALL CheckForCollision
LD A, [Collided]
AND A
RET Z
; we collided, so move the laser off-screen - it'll get marked as inactive
LD HL, LaserYs
LD A, [CurrentLaser]
ADD L
LD L, A
LD [HL], -16
RET
CheckForCollisions: XOR A
LD [CurrentLaser], A
LD A, [ActiveLasers]
LD B, A
.loop BIT 0, B
JR Z, .next
PUSH BC
CALL CheckCurrentLaser
POP BC
.next SRL B
LD HL, CurrentLaser
LD A, [HL]
INC A
LD [HL], A
CP MAX_LASERS
JR NZ, .loop
RET
ClearInactiveLasers: LD HL, LaserYs + MAX_LASERS - 1
LD B, MAX_LASERS
LD C, $FF
.loop ; check to see if this laser is now off-screen
LD A, [HLD]
CP 144
JR C, .next
CP 256 - LASER_HEIGHT
JR NC, .next
; mark this laser as inactive
RES 7, C
.next RLC C
DEC B
JR NZ, .loop
; apply the mask
LD HL, ActiveLasers
LD A, [HL]
AND C
LD [HL], A
RET
MoveLasers: LD HL, LaserYs
LD B, MAX_LASERS
LD A, [ActiveLasers]
LD C, A
.loop ; check to see if this laser is active
BIT 0, C
JR Z, .next
; update laser position
LD A, [HL]
SUB 2
LD [HL], A
.next SRL C ; move ActiveLaser mask down
INC L
DEC B
JR NZ, .loop
RET
| 28.991071 | 109 | 0.356637 |
5adb38b55bd5ec9dd9c1adb154c936daef68077e | 33,337 | cs | C# | sdk/src/Services/IoTThingsGraph/Generated/ServiceEnumerations.cs | philasmar/aws-sdk-net | 64a49f18246bf903fdd1f01c5b5af36ab0fd6f94 | [
"Apache-2.0"
] | 1 | 2021-09-17T15:33:32.000Z | 2021-09-17T15:33:32.000Z | sdk/src/Services/IoTThingsGraph/Generated/ServiceEnumerations.cs | philasmar/aws-sdk-net | 64a49f18246bf903fdd1f01c5b5af36ab0fd6f94 | [
"Apache-2.0"
] | null | null | null | sdk/src/Services/IoTThingsGraph/Generated/ServiceEnumerations.cs | philasmar/aws-sdk-net | 64a49f18246bf903fdd1f01c5b5af36ab0fd6f94 | [
"Apache-2.0"
] | 1 | 2022-01-22T02:39:11.000Z | 2022-01-22T02:39:11.000Z | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the iotthingsgraph-2018-09-06.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.IoTThingsGraph
{
/// <summary>
/// Constants used for properties of type DefinitionLanguage.
/// </summary>
public class DefinitionLanguage : ConstantClass
{
/// <summary>
/// Constant GRAPHQL for DefinitionLanguage
/// </summary>
public static readonly DefinitionLanguage GRAPHQL = new DefinitionLanguage("GRAPHQL");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DefinitionLanguage(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DefinitionLanguage FindValue(string value)
{
return FindValue<DefinitionLanguage>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DefinitionLanguage(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DeploymentTarget.
/// </summary>
public class DeploymentTarget : ConstantClass
{
/// <summary>
/// Constant CLOUD for DeploymentTarget
/// </summary>
public static readonly DeploymentTarget CLOUD = new DeploymentTarget("CLOUD");
/// <summary>
/// Constant GREENGRASS for DeploymentTarget
/// </summary>
public static readonly DeploymentTarget GREENGRASS = new DeploymentTarget("GREENGRASS");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DeploymentTarget(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DeploymentTarget FindValue(string value)
{
return FindValue<DeploymentTarget>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DeploymentTarget(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type EntityFilterName.
/// </summary>
public class EntityFilterName : ConstantClass
{
/// <summary>
/// Constant NAME for EntityFilterName
/// </summary>
public static readonly EntityFilterName NAME = new EntityFilterName("NAME");
/// <summary>
/// Constant NAMESPACE for EntityFilterName
/// </summary>
public static readonly EntityFilterName NAMESPACE = new EntityFilterName("NAMESPACE");
/// <summary>
/// Constant REFERENCED_ENTITY_ID for EntityFilterName
/// </summary>
public static readonly EntityFilterName REFERENCED_ENTITY_ID = new EntityFilterName("REFERENCED_ENTITY_ID");
/// <summary>
/// Constant SEMANTIC_TYPE_PATH for EntityFilterName
/// </summary>
public static readonly EntityFilterName SEMANTIC_TYPE_PATH = new EntityFilterName("SEMANTIC_TYPE_PATH");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public EntityFilterName(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static EntityFilterName FindValue(string value)
{
return FindValue<EntityFilterName>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator EntityFilterName(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type EntityType.
/// </summary>
public class EntityType : ConstantClass
{
/// <summary>
/// Constant ACTION for EntityType
/// </summary>
public static readonly EntityType ACTION = new EntityType("ACTION");
/// <summary>
/// Constant CAPABILITY for EntityType
/// </summary>
public static readonly EntityType CAPABILITY = new EntityType("CAPABILITY");
/// <summary>
/// Constant DEVICE for EntityType
/// </summary>
public static readonly EntityType DEVICE = new EntityType("DEVICE");
/// <summary>
/// Constant DEVICE_MODEL for EntityType
/// </summary>
public static readonly EntityType DEVICE_MODEL = new EntityType("DEVICE_MODEL");
/// <summary>
/// Constant ENUM for EntityType
/// </summary>
public static readonly EntityType ENUM = new EntityType("ENUM");
/// <summary>
/// Constant EVENT for EntityType
/// </summary>
public static readonly EntityType EVENT = new EntityType("EVENT");
/// <summary>
/// Constant MAPPING for EntityType
/// </summary>
public static readonly EntityType MAPPING = new EntityType("MAPPING");
/// <summary>
/// Constant PROPERTY for EntityType
/// </summary>
public static readonly EntityType PROPERTY = new EntityType("PROPERTY");
/// <summary>
/// Constant SERVICE for EntityType
/// </summary>
public static readonly EntityType SERVICE = new EntityType("SERVICE");
/// <summary>
/// Constant STATE for EntityType
/// </summary>
public static readonly EntityType STATE = new EntityType("STATE");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public EntityType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static EntityType FindValue(string value)
{
return FindValue<EntityType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator EntityType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type FlowExecutionEventType.
/// </summary>
public class FlowExecutionEventType : ConstantClass
{
/// <summary>
/// Constant ACKNOWLEDGE_TASK_MESSAGE for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType ACKNOWLEDGE_TASK_MESSAGE = new FlowExecutionEventType("ACKNOWLEDGE_TASK_MESSAGE");
/// <summary>
/// Constant ACTIVITY_FAILED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType ACTIVITY_FAILED = new FlowExecutionEventType("ACTIVITY_FAILED");
/// <summary>
/// Constant ACTIVITY_SCHEDULED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType ACTIVITY_SCHEDULED = new FlowExecutionEventType("ACTIVITY_SCHEDULED");
/// <summary>
/// Constant ACTIVITY_STARTED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType ACTIVITY_STARTED = new FlowExecutionEventType("ACTIVITY_STARTED");
/// <summary>
/// Constant ACTIVITY_SUCCEEDED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType ACTIVITY_SUCCEEDED = new FlowExecutionEventType("ACTIVITY_SUCCEEDED");
/// <summary>
/// Constant EXECUTION_ABORTED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType EXECUTION_ABORTED = new FlowExecutionEventType("EXECUTION_ABORTED");
/// <summary>
/// Constant EXECUTION_FAILED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType EXECUTION_FAILED = new FlowExecutionEventType("EXECUTION_FAILED");
/// <summary>
/// Constant EXECUTION_STARTED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType EXECUTION_STARTED = new FlowExecutionEventType("EXECUTION_STARTED");
/// <summary>
/// Constant EXECUTION_SUCCEEDED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType EXECUTION_SUCCEEDED = new FlowExecutionEventType("EXECUTION_SUCCEEDED");
/// <summary>
/// Constant SCHEDULE_NEXT_READY_STEPS_TASK for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType SCHEDULE_NEXT_READY_STEPS_TASK = new FlowExecutionEventType("SCHEDULE_NEXT_READY_STEPS_TASK");
/// <summary>
/// Constant START_FLOW_EXECUTION_TASK for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType START_FLOW_EXECUTION_TASK = new FlowExecutionEventType("START_FLOW_EXECUTION_TASK");
/// <summary>
/// Constant STEP_FAILED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType STEP_FAILED = new FlowExecutionEventType("STEP_FAILED");
/// <summary>
/// Constant STEP_STARTED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType STEP_STARTED = new FlowExecutionEventType("STEP_STARTED");
/// <summary>
/// Constant STEP_SUCCEEDED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType STEP_SUCCEEDED = new FlowExecutionEventType("STEP_SUCCEEDED");
/// <summary>
/// Constant THING_ACTION_TASK for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType THING_ACTION_TASK = new FlowExecutionEventType("THING_ACTION_TASK");
/// <summary>
/// Constant THING_ACTION_TASK_FAILED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType THING_ACTION_TASK_FAILED = new FlowExecutionEventType("THING_ACTION_TASK_FAILED");
/// <summary>
/// Constant THING_ACTION_TASK_SUCCEEDED for FlowExecutionEventType
/// </summary>
public static readonly FlowExecutionEventType THING_ACTION_TASK_SUCCEEDED = new FlowExecutionEventType("THING_ACTION_TASK_SUCCEEDED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public FlowExecutionEventType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static FlowExecutionEventType FindValue(string value)
{
return FindValue<FlowExecutionEventType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator FlowExecutionEventType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type FlowExecutionStatus.
/// </summary>
public class FlowExecutionStatus : ConstantClass
{
/// <summary>
/// Constant ABORTED for FlowExecutionStatus
/// </summary>
public static readonly FlowExecutionStatus ABORTED = new FlowExecutionStatus("ABORTED");
/// <summary>
/// Constant FAILED for FlowExecutionStatus
/// </summary>
public static readonly FlowExecutionStatus FAILED = new FlowExecutionStatus("FAILED");
/// <summary>
/// Constant RUNNING for FlowExecutionStatus
/// </summary>
public static readonly FlowExecutionStatus RUNNING = new FlowExecutionStatus("RUNNING");
/// <summary>
/// Constant SUCCEEDED for FlowExecutionStatus
/// </summary>
public static readonly FlowExecutionStatus SUCCEEDED = new FlowExecutionStatus("SUCCEEDED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public FlowExecutionStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static FlowExecutionStatus FindValue(string value)
{
return FindValue<FlowExecutionStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator FlowExecutionStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type FlowTemplateFilterName.
/// </summary>
public class FlowTemplateFilterName : ConstantClass
{
/// <summary>
/// Constant DEVICE_MODEL_ID for FlowTemplateFilterName
/// </summary>
public static readonly FlowTemplateFilterName DEVICE_MODEL_ID = new FlowTemplateFilterName("DEVICE_MODEL_ID");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public FlowTemplateFilterName(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static FlowTemplateFilterName FindValue(string value)
{
return FindValue<FlowTemplateFilterName>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator FlowTemplateFilterName(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type NamespaceDeletionStatus.
/// </summary>
public class NamespaceDeletionStatus : ConstantClass
{
/// <summary>
/// Constant FAILED for NamespaceDeletionStatus
/// </summary>
public static readonly NamespaceDeletionStatus FAILED = new NamespaceDeletionStatus("FAILED");
/// <summary>
/// Constant IN_PROGRESS for NamespaceDeletionStatus
/// </summary>
public static readonly NamespaceDeletionStatus IN_PROGRESS = new NamespaceDeletionStatus("IN_PROGRESS");
/// <summary>
/// Constant SUCCEEDED for NamespaceDeletionStatus
/// </summary>
public static readonly NamespaceDeletionStatus SUCCEEDED = new NamespaceDeletionStatus("SUCCEEDED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public NamespaceDeletionStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static NamespaceDeletionStatus FindValue(string value)
{
return FindValue<NamespaceDeletionStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator NamespaceDeletionStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type NamespaceDeletionStatusErrorCodes.
/// </summary>
public class NamespaceDeletionStatusErrorCodes : ConstantClass
{
/// <summary>
/// Constant VALIDATION_FAILED for NamespaceDeletionStatusErrorCodes
/// </summary>
public static readonly NamespaceDeletionStatusErrorCodes VALIDATION_FAILED = new NamespaceDeletionStatusErrorCodes("VALIDATION_FAILED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public NamespaceDeletionStatusErrorCodes(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static NamespaceDeletionStatusErrorCodes FindValue(string value)
{
return FindValue<NamespaceDeletionStatusErrorCodes>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator NamespaceDeletionStatusErrorCodes(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type SystemInstanceDeploymentStatus.
/// </summary>
public class SystemInstanceDeploymentStatus : ConstantClass
{
/// <summary>
/// Constant BOOTSTRAP for SystemInstanceDeploymentStatus
/// </summary>
public static readonly SystemInstanceDeploymentStatus BOOTSTRAP = new SystemInstanceDeploymentStatus("BOOTSTRAP");
/// <summary>
/// Constant DELETED_IN_TARGET for SystemInstanceDeploymentStatus
/// </summary>
public static readonly SystemInstanceDeploymentStatus DELETED_IN_TARGET = new SystemInstanceDeploymentStatus("DELETED_IN_TARGET");
/// <summary>
/// Constant DEPLOY_IN_PROGRESS for SystemInstanceDeploymentStatus
/// </summary>
public static readonly SystemInstanceDeploymentStatus DEPLOY_IN_PROGRESS = new SystemInstanceDeploymentStatus("DEPLOY_IN_PROGRESS");
/// <summary>
/// Constant DEPLOYED_IN_TARGET for SystemInstanceDeploymentStatus
/// </summary>
public static readonly SystemInstanceDeploymentStatus DEPLOYED_IN_TARGET = new SystemInstanceDeploymentStatus("DEPLOYED_IN_TARGET");
/// <summary>
/// Constant FAILED for SystemInstanceDeploymentStatus
/// </summary>
public static readonly SystemInstanceDeploymentStatus FAILED = new SystemInstanceDeploymentStatus("FAILED");
/// <summary>
/// Constant NOT_DEPLOYED for SystemInstanceDeploymentStatus
/// </summary>
public static readonly SystemInstanceDeploymentStatus NOT_DEPLOYED = new SystemInstanceDeploymentStatus("NOT_DEPLOYED");
/// <summary>
/// Constant PENDING_DELETE for SystemInstanceDeploymentStatus
/// </summary>
public static readonly SystemInstanceDeploymentStatus PENDING_DELETE = new SystemInstanceDeploymentStatus("PENDING_DELETE");
/// <summary>
/// Constant UNDEPLOY_IN_PROGRESS for SystemInstanceDeploymentStatus
/// </summary>
public static readonly SystemInstanceDeploymentStatus UNDEPLOY_IN_PROGRESS = new SystemInstanceDeploymentStatus("UNDEPLOY_IN_PROGRESS");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public SystemInstanceDeploymentStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static SystemInstanceDeploymentStatus FindValue(string value)
{
return FindValue<SystemInstanceDeploymentStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator SystemInstanceDeploymentStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type SystemInstanceFilterName.
/// </summary>
public class SystemInstanceFilterName : ConstantClass
{
/// <summary>
/// Constant GREENGRASS_GROUP_NAME for SystemInstanceFilterName
/// </summary>
public static readonly SystemInstanceFilterName GREENGRASS_GROUP_NAME = new SystemInstanceFilterName("GREENGRASS_GROUP_NAME");
/// <summary>
/// Constant STATUS for SystemInstanceFilterName
/// </summary>
public static readonly SystemInstanceFilterName STATUS = new SystemInstanceFilterName("STATUS");
/// <summary>
/// Constant SYSTEM_TEMPLATE_ID for SystemInstanceFilterName
/// </summary>
public static readonly SystemInstanceFilterName SYSTEM_TEMPLATE_ID = new SystemInstanceFilterName("SYSTEM_TEMPLATE_ID");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public SystemInstanceFilterName(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static SystemInstanceFilterName FindValue(string value)
{
return FindValue<SystemInstanceFilterName>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator SystemInstanceFilterName(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type SystemTemplateFilterName.
/// </summary>
public class SystemTemplateFilterName : ConstantClass
{
/// <summary>
/// Constant FLOW_TEMPLATE_ID for SystemTemplateFilterName
/// </summary>
public static readonly SystemTemplateFilterName FLOW_TEMPLATE_ID = new SystemTemplateFilterName("FLOW_TEMPLATE_ID");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public SystemTemplateFilterName(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static SystemTemplateFilterName FindValue(string value)
{
return FindValue<SystemTemplateFilterName>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator SystemTemplateFilterName(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type UploadStatus.
/// </summary>
public class UploadStatus : ConstantClass
{
/// <summary>
/// Constant FAILED for UploadStatus
/// </summary>
public static readonly UploadStatus FAILED = new UploadStatus("FAILED");
/// <summary>
/// Constant IN_PROGRESS for UploadStatus
/// </summary>
public static readonly UploadStatus IN_PROGRESS = new UploadStatus("IN_PROGRESS");
/// <summary>
/// Constant SUCCEEDED for UploadStatus
/// </summary>
public static readonly UploadStatus SUCCEEDED = new UploadStatus("SUCCEEDED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public UploadStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static UploadStatus FindValue(string value)
{
return FindValue<UploadStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator UploadStatus(string value)
{
return FindValue(value);
}
}
} | 41.46393 | 149 | 0.618472 |
4f3c9887dce27214860655124622a3c643ce43e7 | 10,604 | rb | Ruby | Library/Homebrew/extend/ENV/std.rb | dserodio/homebrew | 7111d891059407ee846c1b1dbf83f766661c130f | [
"BSD-2-Clause"
] | 1 | 2019-06-22T05:55:39.000Z | 2019-06-22T05:55:39.000Z | Library/Homebrew/extend/ENV/std.rb | basvodde/homebrew | e14bd6c5003b7435ee82947b6240b25f032e31c1 | [
"BSD-2-Clause"
] | null | null | null | Library/Homebrew/extend/ENV/std.rb | basvodde/homebrew | e14bd6c5003b7435ee82947b6240b25f032e31c1 | [
"BSD-2-Clause"
] | null | null | null | require 'hardware'
require 'os/mac'
require 'extend/ENV/shared'
module Stdenv
include SharedEnvExtension
SAFE_CFLAGS_FLAGS = "-w -pipe"
DEFAULT_FLAGS = '-march=core2 -msse4'
def self.extended(base)
unless ORIGINAL_PATHS.include? HOMEBREW_PREFIX/'bin'
base.prepend_path 'PATH', "#{HOMEBREW_PREFIX}/bin"
end
end
def setup_build_environment(formula=nil)
super
if MacOS.version >= :mountain_lion
# Mountain Lion's sed is stricter, and errors out when
# it encounters files with mixed character sets
delete('LC_ALL')
self['LC_CTYPE']="C"
end
# Set the default pkg-config search path, overriding the built-in paths
# Anything in PKG_CONFIG_PATH is searched before paths in this variable
self['PKG_CONFIG_LIBDIR'] = determine_pkg_config_libdir
# make any aclocal stuff installed in Homebrew available
self['ACLOCAL_PATH'] = "#{HOMEBREW_PREFIX}/share/aclocal" if MacOS::Xcode.provides_autotools?
self['MAKEFLAGS'] = "-j#{self.make_jobs}"
unless HOMEBREW_PREFIX.to_s == '/usr/local'
# /usr/local is already an -isystem and -L directory so we skip it
self['CPPFLAGS'] = "-isystem#{HOMEBREW_PREFIX}/include"
self['LDFLAGS'] = "-L#{HOMEBREW_PREFIX}/lib"
# CMake ignores the variables above
self['CMAKE_PREFIX_PATH'] = HOMEBREW_PREFIX.to_s
end
frameworks = HOMEBREW_PREFIX.join("Frameworks")
if frameworks.directory?
append "CPPFLAGS", "-F#{frameworks}"
append "LDFLAGS", "-F#{frameworks}"
self["CMAKE_FRAMEWORK_PATH"] = frameworks.to_s
end
# Os is the default Apple uses for all its stuff so let's trust them
set_cflags "-Os #{SAFE_CFLAGS_FLAGS}"
append 'LDFLAGS', '-Wl,-headerpad_max_install_names'
send(compiler)
if cc =~ GNU_GCC_REGEXP
gcc_formula = gcc_version_formula($1)
append_path "PATH", gcc_formula.opt_bin.to_s
end
# Add lib and include etc. from the current macosxsdk to compiler flags:
macosxsdk MacOS.version
if MacOS::Xcode.without_clt?
append_path "PATH", "#{MacOS::Xcode.prefix}/usr/bin"
append_path "PATH", "#{MacOS::Xcode.toolchain_path}/usr/bin"
end
end
def determine_pkg_config_libdir
paths = []
paths << "#{HOMEBREW_PREFIX}/lib/pkgconfig"
paths << "#{HOMEBREW_PREFIX}/share/pkgconfig"
paths << "#{HOMEBREW_LIBRARY}/ENV/pkgconfig/#{MacOS.version}"
paths << "/usr/lib/pkgconfig"
paths.select { |d| File.directory? d }.join(File::PATH_SEPARATOR)
end
# Removes the MAKEFLAGS environment variable, causing make to use a single job.
# This is useful for makefiles with race conditions.
# When passed a block, MAKEFLAGS is removed only for the duration of the block and is restored after its completion.
# Returns the value of MAKEFLAGS.
def deparallelize
old = self['MAKEFLAGS']
remove 'MAKEFLAGS', /-j\d+/
if block_given?
begin
yield
ensure
self['MAKEFLAGS'] = old
end
end
old
end
alias_method :j1, :deparallelize
# These methods are no-ops for compatibility.
%w{fast O4 Og}.each { |opt| define_method(opt) {} }
%w{O3 O2 O1 O0 Os}.each do |opt|
define_method opt do
remove_from_cflags(/-O./)
append_to_cflags "-#{opt}"
end
end
def determine_cc
s = super
MacOS.locate(s) || Pathname.new(s)
end
def determine_cxx
dir, base = determine_cc.split
dir / base.to_s.sub("gcc", "g++").sub("clang", "clang++")
end
def gcc_4_0
super
set_cpu_cflags '-march=nocona -mssse3'
end
alias_method :gcc_4_0_1, :gcc_4_0
def gcc
super
set_cpu_cflags
end
alias_method :gcc_4_2, :gcc
GNU_GCC_VERSIONS.each do |n|
define_method(:"gcc-4.#{n}") do
super()
set_cpu_cflags
end
end
def llvm
super
set_cpu_cflags
end
def clang
super
replace_in_cflags(/-Xarch_#{Hardware::CPU.arch_32_bit} (-march=\S*)/, '\1')
# Clang mistakenly enables AES-NI on plain Nehalem
map = Hardware::CPU.optimization_flags
map = map.merge(:nehalem => "-march=native -Xclang -target-feature -Xclang -aes")
set_cpu_cflags "-march=native", map
end
def remove_macosxsdk version=MacOS.version
# Clear all lib and include dirs from CFLAGS, CPPFLAGS, LDFLAGS that were
# previously added by macosxsdk
version = version.to_s
remove_from_cflags(/ ?-mmacosx-version-min=10\.\d/)
delete('MACOSX_DEPLOYMENT_TARGET')
delete('CPATH')
remove 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib"
if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed?
delete('SDKROOT')
remove_from_cflags "-isysroot #{sdk}"
remove 'CPPFLAGS', "-isysroot #{sdk}"
remove 'LDFLAGS', "-isysroot #{sdk}"
if HOMEBREW_PREFIX.to_s == '/usr/local'
delete('CMAKE_PREFIX_PATH')
else
# It was set in setup_build_environment, so we have to restore it here.
self['CMAKE_PREFIX_PATH'] = HOMEBREW_PREFIX.to_s
end
remove 'CMAKE_FRAMEWORK_PATH', "#{sdk}/System/Library/Frameworks"
end
end
def macosxsdk version=MacOS.version
return unless OS.mac?
# Sets all needed lib and include dirs to CFLAGS, CPPFLAGS, LDFLAGS.
remove_macosxsdk
version = version.to_s
append_to_cflags("-mmacosx-version-min=#{version}")
self['MACOSX_DEPLOYMENT_TARGET'] = version
self['CPATH'] = "#{HOMEBREW_PREFIX}/include"
prepend 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib"
if (sdk = MacOS.sdk_path(version)) && !MacOS::CLT.installed?
# Extra setup to support Xcode 4.3+ without CLT.
self['SDKROOT'] = sdk
# Tell clang/gcc where system include's are:
append_path 'CPATH', "#{sdk}/usr/include"
# The -isysroot is needed, too, because of the Frameworks
append_to_cflags "-isysroot #{sdk}"
append 'CPPFLAGS', "-isysroot #{sdk}"
# And the linker needs to find sdk/usr/lib
append 'LDFLAGS', "-isysroot #{sdk}"
# Needed to build cmake itself and perhaps some cmake projects:
append_path 'CMAKE_PREFIX_PATH', "#{sdk}/usr"
append_path 'CMAKE_FRAMEWORK_PATH', "#{sdk}/System/Library/Frameworks"
end
end
def minimal_optimization
set_cflags "-Os #{SAFE_CFLAGS_FLAGS}"
macosxsdk unless MacOS::CLT.installed?
end
def no_optimization
set_cflags SAFE_CFLAGS_FLAGS
macosxsdk unless MacOS::CLT.installed?
end
# Some configure scripts won't find libxml2 without help
def libxml2
if MacOS::CLT.installed?
append 'CPPFLAGS', '-I/usr/include/libxml2'
else
# Use the includes form the sdk
append 'CPPFLAGS', "-I#{MacOS.sdk_path}/usr/include/libxml2"
end
end
def x11
# There are some config scripts here that should go in the PATH
append_path "PATH", MacOS::X11.bin.to_s
# Append these to PKG_CONFIG_LIBDIR so they are searched
# *after* our own pkgconfig directories, as we dupe some of the
# libs in XQuartz.
append_path "PKG_CONFIG_LIBDIR", "#{MacOS::X11.lib}/pkgconfig"
append_path "PKG_CONFIG_LIBDIR", "#{MacOS::X11.share}/pkgconfig"
append "LDFLAGS", "-L#{MacOS::X11.lib}"
append_path "CMAKE_PREFIX_PATH", MacOS::X11.prefix.to_s
append_path "CMAKE_INCLUDE_PATH", MacOS::X11.include.to_s
append_path "CMAKE_INCLUDE_PATH", "#{MacOS::X11.include}/freetype2"
append "CPPFLAGS", "-I#{MacOS::X11.include}"
append "CPPFLAGS", "-I#{MacOS::X11.include}/freetype2"
append_path "ACLOCAL_PATH", "#{MacOS::X11.share}/aclocal"
if MacOS::XQuartz.provided_by_apple? and not MacOS::CLT.installed?
append_path "CMAKE_PREFIX_PATH", "#{MacOS.sdk_path}/usr/X11"
end
append "CFLAGS", "-I#{MacOS::X11.include}" unless MacOS::CLT.installed?
end
alias_method :libpng, :x11
# we've seen some packages fail to build when warnings are disabled!
def enable_warnings
remove_from_cflags '-w'
end
def m64
append_to_cflags '-m64'
append 'LDFLAGS', "-arch #{Hardware::CPU.arch_64_bit}"
end
def m32
append_to_cflags '-m32'
append 'LDFLAGS', "-arch #{Hardware::CPU.arch_32_bit}"
end
def universal_binary
append_to_cflags Hardware::CPU.universal_archs.as_arch_flags
append 'LDFLAGS', Hardware::CPU.universal_archs.as_arch_flags
if compiler != :clang && Hardware.is_32_bit?
# Can't mix "-march" for a 32-bit CPU with "-arch x86_64"
replace_in_cflags(/-march=\S*/, "-Xarch_#{Hardware::CPU.arch_32_bit} \\0")
end
end
def cxx11
if compiler == :clang
append 'CXX', '-std=c++11'
append 'CXX', '-stdlib=libc++'
elsif compiler =~ /gcc-4\.(8|9)/
append 'CXX', '-std=c++11'
else
raise "The selected compiler doesn't support C++11: #{compiler}"
end
end
def libcxx
if compiler == :clang
append 'CXX', '-stdlib=libc++'
end
end
def libstdcxx
if compiler == :clang
append 'CXX', '-stdlib=libstdc++'
end
end
def replace_in_cflags before, after
CC_FLAG_VARS.each do |key|
self[key] = self[key].sub(before, after) if has_key?(key)
end
end
# Convenience method to set all C compiler flags in one shot.
def set_cflags val
CC_FLAG_VARS.each { |key| self[key] = val }
end
# Sets architecture-specific flags for every environment variable
# given in the list `flags`.
def set_cpu_flags flags, default=DEFAULT_FLAGS, map=Hardware::CPU.optimization_flags
cflags =~ %r{(-Xarch_#{Hardware::CPU.arch_32_bit} )-march=}
xarch = $1.to_s
remove flags, %r{(-Xarch_#{Hardware::CPU.arch_32_bit} )?-march=\S*}
remove flags, %r{( -Xclang \S+)+}
remove flags, %r{-mssse3}
remove flags, %r{-msse4(\.\d)?}
append flags, xarch unless xarch.empty?
append flags, map.fetch(effective_arch, default)
end
def effective_arch
if ARGV.build_bottle?
ARGV.bottle_arch || Hardware.oldest_cpu
elsif Hardware::CPU.intel? && !Hardware::CPU.sse4?
# If the CPU doesn't support SSE4, we cannot trust -march=native or
# -march=<cpu family> to do the right thing because we might be running
# in a VM or on a Hackintosh.
Hardware.oldest_cpu
else
Hardware::CPU.family
end
end
def set_cpu_cflags default=DEFAULT_FLAGS, map=Hardware::CPU.optimization_flags
set_cpu_flags CC_FLAG_VARS, default, map
end
def make_jobs
# '-j' requires a positive integral argument
if self['HOMEBREW_MAKE_JOBS'].to_i > 0
self['HOMEBREW_MAKE_JOBS'].to_i
else
Hardware::CPU.cores
end
end
# This method does nothing in stdenv since there's no arg refurbishment
def refurbish_args; end
end
| 30.297143 | 118 | 0.673708 |
4cea64820877a33240278424423bf63d0ac0e884 | 1,173 | py | Python | download.py | Andy0619/Crawl_3rd_party_stores | 78ce30c43f8c04a8536c567651960f26734b029d | [
"MIT"
] | 4 | 2020-06-01T09:21:54.000Z | 2021-11-30T02:39:18.000Z | download.py | PowerOlive/Crawl_3rd_party_stores | 78ce30c43f8c04a8536c567651960f26734b029d | [
"MIT"
] | null | null | null | download.py | PowerOlive/Crawl_3rd_party_stores | 78ce30c43f8c04a8536c567651960f26734b029d | [
"MIT"
] | 1 | 2020-10-31T09:06:24.000Z | 2020-10-31T09:06:24.000Z | # -*- coding: utf-8 -*-
from pymongo import MongoClient
import bson
import re
if __name__ == '__main__':
collection = MongoClient('mongodb://localhost:27017/')['scrapy']['Third_Party_apps']
regax = bson.Regex.from_native(re.compile('^Wandoujia_.*'))
wandoujia_list = collection.find({'ID':regax},{'ID':1,'Version':1,'file_urls':1})
with open("wandoujia_download.sh",'w') as f:
f.write('#!/bin/bash\n')
for item in wandoujia_list:
index = 0
if isinstance(item['file_urls'],list):
for url in item['file_urls']:
command = 'wget "'+url+'" -O '+ item['ID']+"_"+item['Version'][index]+"\n"
f.write(command)
f.write('if [ $? != 0 ];then echo "'+command+'" >> wandoujia_failed.log ;fi\n')
index=index+1
elif isinstance(item['file_urls'],str):
command = 'wget "' + url + '" -O ' + item['ID'] + "_" + item['Version'] + "\n"
f.write(command)
f.write('if [ $? != 0 ];then echo "' + command + '" >> wandoujia_failed.log ;fi\n')
else:
pass
| 36.65625 | 99 | 0.514066 |
460c76443638f87a1c671004a9cb926242b7c1cf | 97 | sql | SQL | Development/Core/TfsMigrationDBConsolidation/Tfs_Integration/Schema Objects/Tables/Keys/dbo.RUNTIME_CHANGE_GROUPS.PK_RT_ChangeGroups.pkey.sql | adamdriscoll/TfsIntegrationPlatform | 28e0f51e804423bbde61083422711113662f2710 | [
"MIT"
] | 6 | 2016-09-06T19:41:51.000Z | 2021-06-08T19:50:15.000Z | IntegrationPlatform/Core/TfsMigrationDBConsolidation/Tfs_Integration/Schema Objects/Tables/Keys/dbo.RUNTIME_CHANGE_GROUPS.PK_RT_ChangeGroups.pkey.sql | adamdriscoll/TfsIntegrationPlatform | 28e0f51e804423bbde61083422711113662f2710 | [
"MIT"
] | null | null | null | IntegrationPlatform/Core/TfsMigrationDBConsolidation/Tfs_Integration/Schema Objects/Tables/Keys/dbo.RUNTIME_CHANGE_GROUPS.PK_RT_ChangeGroups.pkey.sql | adamdriscoll/TfsIntegrationPlatform | 28e0f51e804423bbde61083422711113662f2710 | [
"MIT"
] | 6 | 2016-05-24T13:57:54.000Z | 2020-01-27T12:11:57.000Z | ALTER TABLE [dbo].[RUNTIME_CHANGE_GROUPS]
ADD CONSTRAINT [PK_RT_ChangeGroups]
PRIMARY KEY (Id) | 32.333333 | 42 | 0.793814 |
d251ec053e49e2bb96666770b7cd3aa48b283c1f | 1,517 | rs | Rust | src/usb/if_.rs | pablo-mansanet-bluefruit/efm32gg11b-hal | 61a359e544b9dac336f58e51697d248daf658d59 | [
"MIT"
] | null | null | null | src/usb/if_.rs | pablo-mansanet-bluefruit/efm32gg11b-hal | 61a359e544b9dac336f58e51697d248daf658d59 | [
"MIT"
] | null | null | null | src/usb/if_.rs | pablo-mansanet-bluefruit/efm32gg11b-hal | 61a359e544b9dac336f58e51697d248daf658d59 | [
"MIT"
] | 1 | 2021-07-08T09:54:46.000Z | 2021-07-08T09:54:46.000Z | #[doc = "Reader of register IF"]
pub type R = crate::R<u32, super::IF>;
#[doc = "Reader of field `VBUSDETH`"]
pub type VBUSDETH_R = crate::R<bool, bool>;
#[doc = "Reader of field `VBUSDETL`"]
pub type VBUSDETL_R = crate::R<bool, bool>;
#[doc = "Reader of field `ERR`"]
pub type ERR_R = crate::R<bool, bool>;
#[doc = "Reader of field `DCD`"]
pub type DCD_R = crate::R<bool, bool>;
#[doc = "Reader of field `PD`"]
pub type PD_R = crate::R<bool, bool>;
#[doc = "Reader of field `SD`"]
pub type SD_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - VBUS Detect High Interrupt Flag"]
#[inline(always)]
pub fn vbusdeth(&self) -> VBUSDETH_R { VBUSDETH_R::new((self.bits & 0x01) != 0) }
#[doc = "Bit 1 - VBUS Detect Low Interrupt Flag"]
#[inline(always)]
pub fn vbusdetl(&self) -> VBUSDETL_R { VBUSDETL_R::new(((self.bits >> 1) & 0x01) != 0) }
#[doc = "Bit 8 - Detection Error Interrupt Flag"]
#[inline(always)]
pub fn err(&self) -> ERR_R { ERR_R::new(((self.bits >> 8) & 0x01) != 0) }
#[doc = "Bit 9 - Data Contact Detection Complete Interrupt Flag"]
#[inline(always)]
pub fn dcd(&self) -> DCD_R { DCD_R::new(((self.bits >> 9) & 0x01) != 0) }
#[doc = "Bit 10 - Primary Detection Complete Interrupt Flag"]
#[inline(always)]
pub fn pd(&self) -> PD_R { PD_R::new(((self.bits >> 10) & 0x01) != 0) }
#[doc = "Bit 11 - Secondary Detection Complete Interrupt Flag"]
#[inline(always)]
pub fn sd(&self) -> SD_R { SD_R::new(((self.bits >> 11) & 0x01) != 0) }
}
| 43.342857 | 92 | 0.59855 |
2fe94e879912d14ca18912d6024587424d28ccef | 260 | py | Python | tests/tests_integration/test_three.py | drewverlee/prims-algorithm | 2d3e14dbf45b211e77d3e7aab6b5b9c5ccdc1e4c | [
"MIT"
] | null | null | null | tests/tests_integration/test_three.py | drewverlee/prims-algorithm | 2d3e14dbf45b211e77d3e7aab6b5b9c5ccdc1e4c | [
"MIT"
] | null | null | null | tests/tests_integration/test_three.py | drewverlee/prims-algorithm | 2d3e14dbf45b211e77d3e7aab6b5b9c5ccdc1e4c | [
"MIT"
] | null | null | null | """
6 11
1 2 10
1 5 -3
1 4 5
1 3 4
2 6 6
2 3 7
3 6 -10
3 4 -1
4 6 2
4 5 -8
5 6 1
"""
from prims import prims
def test_prims_should_find_cost_of_neg_16(GF3, simple_que):
v = GF3.any_vertice()
mst = prims(GF3, simple_que, v)
assert mst.cost == -16
| 11.818182 | 59 | 0.626923 |
4634e497a76a32822d6c01406324f88dd71028a1 | 2,697 | php | PHP | resources/views/reportes/frmActivosPersonal.blade.php | garevalo/inventario | 95806594b4b43b4e42956808cb0545e970100a08 | [
"MIT"
] | null | null | null | resources/views/reportes/frmActivosPersonal.blade.php | garevalo/inventario | 95806594b4b43b4e42956808cb0545e970100a08 | [
"MIT"
] | null | null | null | resources/views/reportes/frmActivosPersonal.blade.php | garevalo/inventario | 95806594b4b43b4e42956808cb0545e970100a08 | [
"MIT"
] | null | null | null | @extends('back.app')
@section('title')Módulo reporte por personal @endsection
@section('head')
@parent
<!-- DataTables -->
<link rel="stylesheet" href="{{asset('plugins/datatables/dataTables.bootstrap.css')}}">
@endsection
@section('content')
<div class="col-xs-12">
<div class="box box-danger">
<div class="box-header">
<h3 class="box-title"> Reporte de activos por personal</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<form action="{{route("reporte.personal")}}" class="form-group" method="post" target="_blank">
{{csrf_field() }}
<div class="form-group">
<label>Seleccione Personal</label>
<select class="input-sm form-control select2" name="personal">
<option value="">Seleccione Personal</option>
@foreach($personals as $personal)
<option value="{{$personal->idpersonal}}">{{$personal->nombres.' '.$personal->apellido_paterno.' '.$personal->apellido_materno }}</option>
@endforeach
</select>
</div>
<div class="form-group-sm {{ $errors->has('hasta') ? ' has-error' : '' }}">
<label>Exportar a :</label>
<div class="radio">
<label for="">
<input type="radio" name="exportar" value="1" checked > <i class="fa fa-file-excel-o" ></i> Excel
</label>
</div>
<div class="radio">
<label for="">
<input type="radio" name="exportar" value="2" > <i class="fa fa-file-pdf-o"></i> PDF
</label>
</div>
</div>
<div class="form-group-sm">
<button type="submit" class="btn btn-primary">Exportar </button>
</div>
</form>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
@endsection
@section('javascript')
@parent()
<!-- Select2 -->
<script src="{{asset('plugins/select2/select2.full.js')}}"></script>
<script>
$(function(){
//Initialize Select2 Elements
$('.select2').select2();
});
</script>
@endsection | 35.96 | 174 | 0.420838 |
9495fef5208e34e00461bcbb08a944e0813778e0 | 1,098 | dart | Dart | tests/language/null_aware/access_runtime_test.dart | omerlevran46/sdk | b1955d63ad678b651b09db3dd286136c4463f36b | [
"BSD-3-Clause"
] | 8,969 | 2015-05-16T16:49:24.000Z | 2022-03-31T19:54:40.000Z | tests/language/null_aware/access_runtime_test.dart | omerlevran46/sdk | b1955d63ad678b651b09db3dd286136c4463f36b | [
"BSD-3-Clause"
] | 30,202 | 2015-05-17T02:27:45.000Z | 2022-03-31T22:54:46.000Z | tests/language/null_aware/access_runtime_test.dart | omerlevran46/sdk | b1955d63ad678b651b09db3dd286136c4463f36b | [
"BSD-3-Clause"
] | 1,619 | 2015-05-16T21:36:42.000Z | 2022-03-29T20:36:59.000Z | // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// Verify semantics of the ?. operator when it does not appear on the LHS of an
// assignment.
import "package:expect/expect.dart";
import "conditional_access_helper.dart" as h;
class B {}
class C extends B {
int? v;
C(this.v);
static int? staticInt;
}
C? nullC() => null;
main() {
// e1?.id is equivalent to ((x) => x == null ? null : x.id)(e1).
Expect.equals(null, nullC()?.v);
C? c = new C(1) as dynamic;
Expect.equals(1, c?.v);
// C?.id is equivalent to C.id.
C.staticInt = 1;
Expect.equals(1, C?.staticInt);
h.C.staticInt = 1;
Expect.equals(1, h.C?.staticInt);
// The static type of e1?.id is the static type of e1.id.
{
int? i = c?.v;
Expect.equals(1, i);
}
{
C.staticInt = 1;
int? i = C?.staticInt;
Expect.equals(1, i);
}
{
h.C.staticInt = 1;
int? i = h.C?.staticInt;
Expect.equals(1, i);
}
}
| 20.716981 | 79 | 0.615665 |
133886e523c0cd464fe5e3edcdd571107f9c88fe | 348 | lua | Lua | MMOCoreORB/bin/scripts/object/custom_content/tangible/collection/deathtrooper_research_cracked_datapad_01.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 18 | 2017-02-09T15:36:05.000Z | 2021-12-21T04:22:15.000Z | MMOCoreORB/bin/scripts/object/custom_content/tangible/collection/deathtrooper_research_cracked_datapad_01.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 61 | 2016-12-30T21:51:10.000Z | 2021-12-10T20:25:56.000Z | MMOCoreORB/bin/scripts/object/custom_content/tangible/collection/deathtrooper_research_cracked_datapad_01.lua | V-Fib/FlurryClone | 40e0ca7245ec31b3815eb6459329fd9e70f88936 | [
"Zlib",
"OpenSSL"
] | 71 | 2017-01-01T05:34:38.000Z | 2022-03-29T01:04:00.000Z |
object_tangible_collection_deathtrooper_research_cracked_datapad_01 = object_tangible_collection_shared_deathtrooper_research_cracked_datapad_01:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_deathtrooper_research_cracked_datapad_01, "object/tangible/collection/deathtrooper_research_cracked_datapad_01.iff") | 69.6 | 171 | 0.925287 |
15c191e22ea5748aebcd0adf673d123b02db4802 | 743 | rb | Ruby | db/seeds.rb | santi-git/todoist | 6ae3e7eadf670524d26cfff457ca2fceca9ae1c8 | [
"MIT"
] | 1 | 2018-11-14T15:01:24.000Z | 2018-11-14T15:01:24.000Z | db/seeds.rb | santi-git/todoist | 6ae3e7eadf670524d26cfff457ca2fceca9ae1c8 | [
"MIT"
] | null | null | null | db/seeds.rb | santi-git/todoist | 6ae3e7eadf670524d26cfff457ca2fceca9ae1c8 | [
"MIT"
] | null | null | null | require 'faker'
private
def add_tasks(list)
[LongTask, SimpleTask, TemporaryTask].each do |klass|
p "Creating 2 #{klass} tasks"
(rand(2)+2).times do
descriptions = [
Faker::StarWars.quote,
Faker::Hacker.say_something_smart,
Faker::ChuckNorris.fact,
Faker::Hipster.sentence
]
attrs = { description: descriptions[rand(descriptions.size)], state: false, priority: (rand(3)+1), progress: 0 }
list.tasks.push(klass.create attrs)
list.save
p " Added task #{attrs[:description]} to list"
end
end
end
required_list = List.create(name: "Lista 0")
add_tasks(required_list)
5.times do
list = List.create(name: Faker::Beer.name)
p "Created list with name #{list.name}..."
add_tasks(list)
end | 21.228571 | 115 | 0.682369 |
0c0ac390d84d3d70acb23a588e0726a5941189aa | 6,753 | lua | Lua | src/camera/src/Client/CameraStackService.lua | Yuuwa0519/NevermoreEngine | 8f0a59b68ccf7c792dba3076aad982334946e1f9 | [
"MIT"
] | null | null | null | src/camera/src/Client/CameraStackService.lua | Yuuwa0519/NevermoreEngine | 8f0a59b68ccf7c792dba3076aad982334946e1f9 | [
"MIT"
] | null | null | null | src/camera/src/Client/CameraStackService.lua | Yuuwa0519/NevermoreEngine | 8f0a59b68ccf7c792dba3076aad982334946e1f9 | [
"MIT"
] | null | null | null | --[=[
Holds camera states and allows for the last camera state to be retrieved. Also
initializes an impulse and default camera as the bottom of the stack. Is a singleton.
@class CameraStackService
]=]
local require = require(script.Parent.loader).load(script)
local RunService = game:GetService("RunService")
local Workspace = game:GetService("Workspace")
local HttpService = game:GetService("HttpService")
local CustomCameraEffect = require("CustomCameraEffect")
local DefaultCamera = require("DefaultCamera")
local ImpulseCamera = require("ImpulseCamera")
local ServiceBag = require("ServiceBag")
assert(RunService:IsClient(), "[CameraStackService] - Only require CameraStackService on client")
local CameraStackService = {}
--[=[
Initializes a new camera stack. Should be done via the ServiceBag.
@param serviceBag ServiceBag
]=]
function CameraStackService:Init(serviceBag)
assert(ServiceBag.isServiceBag(serviceBag), "Not a valid service bag")
self._stack = {}
self._disabledSet = {}
-- Initialize default cameras
self._rawDefaultCamera = DefaultCamera.new()
self._impulseCamera = ImpulseCamera.new()
self._defaultCamera = (self._rawDefaultCamera + self._impulseCamera):SetMode("Relative")
if self._doNotUseDefaultCamera then
Workspace.CurrentCamera.CameraType = Enum.CameraType.Scriptable
-- TODO: Handle camera deleted too!
Workspace.CurrentCamera:GetPropertyChangedSignal("CameraType"):Connect(function()
Workspace.CurrentCamera.CameraType = Enum.CameraType.Scriptable
end)
else
self._rawDefaultCamera:BindToRenderStep()
end
-- Add camera to stack
self:Add(self._defaultCamera)
RunService:BindToRenderStep("CameraStackUpdateInternal", Enum.RenderPriority.Camera.Value + 75, function()
debug.profilebegin("CameraStackUpdate")
if next(self._disabledSet) then
return
end
local state = self:GetTopState()
if state then
state:Set(Workspace.CurrentCamera)
end
debug.profileend()
end)
end
--[=[
Prevents the default camera from being used
@param doNotUseDefaultCamera boolean
]=]
function CameraStackService:SetDoNotUseDefaultCamera(doNotUseDefaultCamera)
assert(not self._stack, "Already initialized")
self._doNotUseDefaultCamera = doNotUseDefaultCamera
end
--[=[
Pushes a disable state onto the camera stack
@return function -- Function to cancel disable
]=]
function CameraStackService:PushDisable()
assert(self._stack, "Not initialized")
local disabledKey = HttpService:GenerateGUID(false)
self._disabledSet[disabledKey] = true
return function()
self._disabledSet[disabledKey] = nil
end
end
--[=[
Outputs the camera stack. Intended for diagnostics.
]=]
function CameraStackService:PrintCameraStack()
assert(self._stack, "Stack is not initialized yet")
for _, value in pairs(self._stack) do
print(tostring(type(value) == "table" and value.ClassName or tostring(value)))
end
end
--[=[
Returns the default camera
@return SummedCamera -- DefaultCamera + ImpulseCamera
]=]
function CameraStackService:GetDefaultCamera()
assert(self._defaultCamera, "Not initialized")
return self._defaultCamera
end
--[=[
Returns the impulse camera. Useful for adding camera shake.
Shaking the camera:
```lua
self._cameraStackService:GetImpulseCamera():Impulse(Vector3.new(0.25, 0, 0.25*(math.random()-0.5)))
```
You can also sum the impulse camera into another effect to layer the shake on top of the effect
as desired.
```lua
-- Adding global custom camera shake to a custom camera effect
local customCameraEffect = ...
return (customCameraEffect + self._cameraStackService:GetImpulseCamera()):SetMode("Relative")
```
@return ImpulseCamera
]=]
function CameraStackService:GetImpulseCamera()
assert(self._impulseCamera, "Not initialized")
return self._impulseCamera
end
--[=[
Returns the default camera without any impulse cameras
@return DefaultCamera
]=]
function CameraStackService:GetRawDefaultCamera()
assert(self._rawDefaultCamera, "Not initialized")
return self._rawDefaultCamera
end
--[=[
Gets the camera current on the top of the stack
@return CameraEffect
]=]
function CameraStackService:GetTopCamera()
assert(self._stack, "Not initialized")
return self._stack[#self._stack]
end
--[=[
Retrieves the top state off the stack at this time
@return CameraState?
]=]
function CameraStackService:GetTopState()
assert(self._stack, "Stack is not initialized yet")
if #self._stack > 10 then
warn(("[CameraStackService] - Stack is bigger than 10 in camerastackService (%d)"):format(#self._stack))
end
local topState = self._stack[#self._stack]
if type(topState) == "table" then
local state = topState.CameraState or topState
if state then
return state
else
warn("[CameraStackService] - No top state!")
end
else
warn("[CameraStackService] - Bad type on top of stack")
end
end
--[=[
Returns a new camera state that retrieves the state below its set state.
@return CustomCameraEffect -- Effect below
@return (CameraState) -> () -- Function to set the state
]=]
function CameraStackService:GetNewStateBelow()
assert(self._stack, "Stack is not initialized yet")
local _stateToUse = nil
return CustomCameraEffect.new(function()
local index = self:GetIndex(_stateToUse)
if index then
local below = self._stack[index-1]
if below then
return below.CameraState or below
else
warn("[CameraStackService] - Could not get state below, found current state. Returning default.")
return self._stack[1].CameraState
end
else
warn(("[CameraStackService] - Could not get state from %q, returning default"):format(tostring(_stateToUse)))
return self._stack[1].CameraState
end
end), function(newStateToUse)
_stateToUse = newStateToUse
end
end
--[=[
Retrieves the index of a state
@param state CameraEffect
@return number? -- index
]=]
function CameraStackService:GetIndex(state)
assert(self._stack, "Stack is not initialized yet")
for index, value in pairs(self._stack) do
if value == state then
return index
end
end
end
--[=[
Returns the current stack.
:::warning
Do not modify this stack, this is the raw memory of the stack
:::
@return { CameraState<T> }
]=]
function CameraStackService:GetStack()
assert(self._stack, "Not initialized")
return self._stack
end
--[=[
Removes the state from the stack
@param state CameraState
]=]
function CameraStackService:Remove(state)
assert(self._stack, "Stack is not initialized yet")
local index = self:GetIndex(state)
if index then
table.remove(self._stack, index)
end
end
--[=[
Adds the state from the stack
@param state CameraState
]=]
function CameraStackService:Add(state)
assert(self._stack, "Stack is not initialized yet")
table.insert(self._stack, state)
end
return CameraStackService | 25.104089 | 112 | 0.757293 |
43e0c47f6e529a11d62f50beab3f3144d528cf90 | 1,848 | ts | TypeScript | packages/babel-types/src/traverse/traverse.ts | Delta-CI/babel | 6e18bc7a7882faf0a27b5f5860e791dd41f31a79 | [
"MIT"
] | 2 | 2020-03-25T21:59:21.000Z | 2020-12-28T06:02:05.000Z | packages/babel-types/src/traverse/traverse.ts | Delta-CI/babel | 6e18bc7a7882faf0a27b5f5860e791dd41f31a79 | [
"MIT"
] | 1 | 2021-01-09T07:38:55.000Z | 2021-01-09T07:38:55.000Z | packages/babel-types/src/traverse/traverse.ts | Delta-CI/babel | 6e18bc7a7882faf0a27b5f5860e791dd41f31a79 | [
"MIT"
] | null | null | null | import { VISITOR_KEYS } from "../definitions";
import type * as t from "..";
export type TraversalAncestors = Array<{
node: t.Node;
key: string;
index?: number;
}>;
export type TraversalHandler<T> = (
this: undefined,
node: t.Node,
parent: TraversalAncestors,
state: T,
) => void;
export type TraversalHandlers<T> = {
enter?: TraversalHandler<T>;
exit?: TraversalHandler<T>;
};
/**
* A general AST traversal with both prefix and postfix handlers, and a
* state object. Exposes ancestry data to each handler so that more complex
* AST data can be taken into account.
*/
export default function traverse<T>(
node: t.Node,
handlers: TraversalHandler<T> | TraversalHandlers<T>,
state?: T,
): void {
if (typeof handlers === "function") {
handlers = { enter: handlers };
}
const { enter, exit } = handlers as TraversalHandlers<T>;
traverseSimpleImpl(node, enter, exit, state, []);
}
function traverseSimpleImpl<T>(
node: any,
enter: Function | undefined | null,
exit: Function | undefined | null,
state: T | undefined | null,
ancestors: TraversalAncestors,
) {
const keys = VISITOR_KEYS[node.type];
if (!keys) return;
if (enter) enter(node, ancestors, state);
for (const key of keys) {
const subNode = node[key];
if (Array.isArray(subNode)) {
for (let i = 0; i < subNode.length; i++) {
const child = subNode[i];
if (!child) continue;
ancestors.push({
node,
key,
index: i,
});
traverseSimpleImpl(child, enter, exit, state, ancestors);
ancestors.pop();
}
} else if (subNode) {
ancestors.push({
node,
key,
});
traverseSimpleImpl(subNode, enter, exit, state, ancestors);
ancestors.pop();
}
}
if (exit) exit(node, ancestors, state);
}
| 21.741176 | 75 | 0.619589 |
d1b15060de7493fc05ed3881e13ab870c18d85c0 | 3,951 | kt | Kotlin | model/src/main/kotlin/org/eclipse/keti/acs/rest/PolicyEvaluationRequestV1.kt | anubhavi25/keti | 285400fba42c687bb42bf4e537ae6f9eca4bf4df | [
"Apache-2.0"
] | null | null | null | model/src/main/kotlin/org/eclipse/keti/acs/rest/PolicyEvaluationRequestV1.kt | anubhavi25/keti | 285400fba42c687bb42bf4e537ae6f9eca4bf4df | [
"Apache-2.0"
] | null | null | null | model/src/main/kotlin/org/eclipse/keti/acs/rest/PolicyEvaluationRequestV1.kt | anubhavi25/keti | 285400fba42c687bb42bf4e537ae6f9eca4bf4df | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright 2018 General Electric Company
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*******************************************************************************/
package org.eclipse.keti.acs.rest
import io.swagger.annotations.ApiModel
import io.swagger.annotations.ApiModelProperty
import org.apache.commons.lang.builder.EqualsBuilder
import org.apache.commons.lang.builder.HashCodeBuilder
import org.eclipse.keti.acs.model.Attribute
import java.util.LinkedHashSet
@ApiModel(description = "Policy evaluation request for V1.")
class PolicyEvaluationRequestV1 {
@get:ApiModelProperty(value = "The resource URI to be consumed", required = true)
var resourceIdentifier: String? = null
@get:ApiModelProperty(value = "The subject identifier", required = true)
var subjectIdentifier: String? = null
/**
* @return the subjectAttributes
*/
@get:ApiModelProperty(value = "Supplemental subject attributes provided by the requestor")
var subjectAttributes: Set<Attribute>? = null
@get:ApiModelProperty(value = "Supplemental resource attributes provided by the requestor")
var resourceAttributes: Set<Attribute>? = null
@get:ApiModelProperty(value = "The action on the given resource URI", required = true)
var action: String? = null
@get:ApiModelProperty(
value = "This list of policy set IDs specifies the order in which the service will evaluate policies. " + "Evaluation stops when a policy with matching target is found and the condition returns true, " + "Or all policies are exhausted."
)
var policySetsEvaluationOrder = LinkedHashSet<String?>()
override fun hashCode(): Int {
val hashCodeBuilder = HashCodeBuilder()
hashCodeBuilder.append(this.action).append(this.resourceIdentifier).append(this.subjectIdentifier)
if (null != this.subjectAttributes) {
for (attribute in this.subjectAttributes!!) {
hashCodeBuilder.append(attribute)
}
}
for (policyID in this.policySetsEvaluationOrder) {
hashCodeBuilder.append(policyID)
}
return hashCodeBuilder.toHashCode()
}
override fun equals(other: Any?): Boolean {
if (other is PolicyEvaluationRequestV1) {
val that = other as PolicyEvaluationRequestV1?
val equalsBuilder = EqualsBuilder()
// Element by element comparison may produce true negative in Sets so use built in equals. Therefore, defer
// to the underlying set's equals() implementation. For details, refer to AbstractSet's (HashSet's ancestor)
// documentation.
equalsBuilder.append(this.subjectAttributes, that?.subjectAttributes)
equalsBuilder.append(this.policySetsEvaluationOrder, that?.policySetsEvaluationOrder)
equalsBuilder.append(this.action, that?.action).append(this.resourceIdentifier, that?.resourceIdentifier)
.append(this.subjectIdentifier, that?.subjectIdentifier)
return equalsBuilder.isEquals
}
return false
}
override fun toString(): String {
return ("PolicyEvaluationRequest [resourceIdentifier=" + this.resourceIdentifier + ", subjectIdentifier=" + this.subjectIdentifier + ", action=" + this.action + "]")
}
}
| 43.417582 | 244 | 0.682106 |
b7f71c2b0589e02e4c8e83f9217e2226ae324939 | 5,637 | cs | C# | src/YS.EventBus.Impl.RabbitMQ/RabbitMQEventConsumer.cs | yscorecore/ys.event | fd09bed1c68f933992d1cbbe89224ff41b46a884 | [
"MIT"
] | 1 | 2020-08-04T01:14:50.000Z | 2020-08-04T01:14:50.000Z | src/YS.EventBus.Impl.RabbitMQ/RabbitMQEventConsumer.cs | yscorecore/ys.event | fd09bed1c68f933992d1cbbe89224ff41b46a884 | [
"MIT"
] | 26 | 2020-04-07T16:16:54.000Z | 2020-07-04T14:28:27.000Z | src/YS.EventBus.Impl.RabbitMQ/RabbitMQEventConsumer.cs | yscorecore/ys.eventbus | fd09bed1c68f933992d1cbbe89224ff41b46a884 | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Collections.Concurrent;
using YS.Knife;
namespace YS.EventBus.Impl.RabbitMQ
{
[HostedClass]
public sealed class RabbitMQEventConsumer : BackgroundService
{
private readonly RabbitOptions rabbitSettings;
private readonly EventBusOptions eventBusSettings;
private readonly IEnumerable<IEventConsumer> allConsumers;
private readonly ILogger logger;
private IDictionary<string, IEventConsumer> consumerTags = new ConcurrentDictionary<string, IEventConsumer>();
private IConnection connection;
private IModel channel;
public RabbitMQEventConsumer(ILogger<RabbitMQEventConsumer> logger, IOptions<EventBusOptions> eventBusOptions, IOptions<RabbitOptions> rabbitOptions, IEnumerable<IEventConsumer> eventConsumers)
{
_ = eventBusOptions ?? throw new ArgumentNullException(nameof(eventBusOptions));
_ = rabbitOptions ?? throw new ArgumentNullException(nameof(rabbitOptions));
this.logger = logger;
this.eventBusSettings = eventBusOptions.Value;
this.rabbitSettings = rabbitOptions.Value;
this.allConsumers = eventConsumers;
}
private IConnection InitConnection()
{
var factory = new ConnectionFactory()
{
HostName = rabbitSettings.HostName,
UserName = rabbitSettings.UserName,
Password = rabbitSettings.Password,
Port = rabbitSettings.Port,
VirtualHost = rabbitSettings.VHost,
};
return factory.CreateConnection();
}
private void InitChannel()
{
connection = InitConnection();
channel = connection.CreateModel();
channel.BasicQos(0, eventBusSettings.MaxConsumerCount, false);
}
private string GetQueueName(IEventConsumer consume)
{
//return $"{consume.Exchange}";
if (consume.EventType == EventType.Queue)
{
return $"{consume.Exchange}";
}
else
{
return $"{consume.Exchange}#{consume.GetHashCode().ToString("X", CultureInfo.InvariantCulture)}";
}
}
private void BasicConsume()
{
lock (this)
{
consumerTags.Clear();
var eventingBasicConsumer = new EventingBasicConsumer(this.channel);
eventingBasicConsumer.Received += OnConsumeDataReceived;
foreach (var consume in allConsumers)
{
channel.ExchangeDeclare(consume.Exchange, consume.EventType);
var queueName = consume.EventType == EventType.Queue ?
channel.QueueDeclareAndBind(consume.Exchange) :
channel.TemporaryQueueDeclareAndBind(consume.Exchange);
var consumeTag = channel.BasicConsume(queueName, false, eventingBasicConsumer);
consumerTags.Add(consumeTag, consume);
}
}
}
private void CancelConsume()
{
lock (this)
{
foreach (var consumerTag in consumerTags.Keys)
{
channel.BasicCancel(consumerTag);
}
consumerTags.Clear();
}
}
private void OnConsumeDataReceived(object sender, BasicDeliverEventArgs e)
{
if (logger.IsEnabled(LogLevel.Information))
{
logger.LogInformation("Message received from the exchange {exchange}", e.Exchange);
logger.LogInformation("Consumer tag: {consumerTag}", e.ConsumerTag);
logger.LogInformation("Delivery tag: {deliveryTag}", e.DeliveryTag);
logger.LogInformation("Message: {message}", Encoding.UTF8.GetString(e.Body));
}
//channelForEventing.BasicNack(basicDeliveryEventArgs.DeliveryTag, false,true);
if (consumerTags.TryGetValue(e.ConsumerTag, out var consumer))
{
if (consumer.HandlerData(e.Body).Result)
{
channel.BasicAck(e.DeliveryTag, false);
}
else
{
// requeue
channel.BasicReject(e.DeliveryTag, true);
}
}
else
{
logger.LogWarning($"Can not find consumer by tag '{e.ConsumerTag}'.");
// requeue
channel.BasicReject(e.DeliveryTag, true);
}
}
public override void Dispose()
{
channel?.Close();
connection?.Close();
base.Dispose();
}
public override Task StopAsync(CancellationToken cancellationToken)
{
this.CancelConsume();
return base.StopAsync(cancellationToken);
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
if (this.channel == null)
{
this.InitChannel();
}
this.BasicConsume();
return Task.CompletedTask;
}
}
}
| 35.23125 | 201 | 0.577435 |
dbdaf4546ec032d98d7f41688199dba24dc4f7af | 5,479 | php | PHP | admin/tables/network-users-list.php | tnchuntic/multisite-content-copier | 66fc0267e83c7df31955a7b5144c8f0f0f5001c1 | [
"BSD-3-Clause-Attribution",
"IJG",
"MTLL"
] | 9 | 2019-05-09T11:57:53.000Z | 2022-02-21T21:33:29.000Z | admin/tables/network-users-list.php | tnchuntic/multisite-content-copier | 66fc0267e83c7df31955a7b5144c8f0f0f5001c1 | [
"BSD-3-Clause-Attribution",
"IJG",
"MTLL"
] | 2 | 2020-09-04T14:37:42.000Z | 2021-02-21T18:49:02.000Z | admin/tables/network-users-list.php | tnchuntic/multisite-content-copier | 66fc0267e83c7df31955a7b5144c8f0f0f5001c1 | [
"BSD-3-Clause-Attribution",
"IJG",
"MTLL"
] | 27 | 2019-05-09T03:15:04.000Z | 2022-03-03T08:42:36.000Z | <?php
class MCC_Users_List_Table extends WP_List_Table {
private $blog_id;
private $selected;
private $enabled;
function __construct( $args = array() ) {
$args = wp_parse_args( $args, array( 'blog_id' => 1, 'enabled' => true , 'selected' => array() ) );
extract( $args );
$this->blog_id = $args['blog_id'];
$this->selected = $args['selected'];
$this->enabled = $args['enabled'];
parent::__construct( array(
'singular' => __( 'User', MULTISTE_CC_LANG_DOMAIN ),
'plural' => __( 'Users', MULTISTE_CC_LANG_DOMAIN ),
'ajax' => false
) );
}
public function prepare_items() {
$per_page = 10;
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$this->_column_headers = array(
$columns,
$hidden,
$sortable
);
$current_page = $this->get_pagenum();
switch_to_blog( $this->blog_id );
$args = array(
'number' => $per_page,
'offset' => $per_page * ( $current_page - 1 ),
'order' => 'ASC',
'orderby' => 'user_login'
);
if ( ! empty( $_REQUEST['s'] ) ) {
$args['search'] = '*' . $_REQUEST['s'] . '*';
$args['search_columns'] = array( 'user_login', 'user_email' );
}
$wp_query = new WP_User_Query( $args );
restore_current_blog();
$this->items = $wp_query->results;
$total_items = $wp_query->total_users;
$this->set_pagination_args( array(
'total_items' => $total_items,
'per_page' => $per_page,
) );
}
function display_tablenav( $which ) {
if ( 'top' == $which ) {
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>">
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
}
function get_columns() {
$blogname_columns = ( is_subdomain_install() ) ? __( 'Domain' ) : __( 'Path' );
$sites_columns = array(
'cb' => '<input type="checkbox" />',
'username' => __( 'Username' ),
'email' => __( 'Email' ),
'role' => __( 'Role' ),
);
return $sites_columns;
}
function column_cb( $item ) {
return '<input type="checkbox" name="user_id[]" ' . checked( in_array( $item->data->ID, $this->selected ), true, false ) . ' ' . disabled( $this->enabled == false, true, false ) . ' class="user_id" value="' . $item->data->ID . '">';
}
function column_username( $item ) {
$avatar = get_avatar( $item->data->ID, '32' );
return $avatar . ' ' . $item->data->user_login;
}
function column_email( $item ) {
return $item->data->user_email;
}
function column_role( $item ) {
global $wp_roles;
return translate_user_role( $wp_roles->role_names[ $item->roles[0] ] );
}
function extra_tablenav( $which ) {
?>
<div class="alignleft actions">
<input type="submit" name="" id="doaction" class="primary button action" value="<?php echo esc_attr( __( 'Add items to the list', MULTISTE_CC_LANG_DOMAIN ) ); ?>">
</div>
<div class="alignleft actions">
<span class="spinner"></span>
</div>
<?php
}
function print_column_headers( $with_id = true ) {
list( $columns, $hidden, $sortable ) = $this->get_column_info();
$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
$current_url = remove_query_arg( 'paged', $current_url );
if ( isset( $_GET['orderby'] ) )
$current_orderby = $_GET['orderby'];
else
$current_orderby = '';
if ( isset( $_GET['order'] ) && 'desc' == $_GET['order'] )
$current_order = 'desc';
else
$current_order = 'asc';
if ( ! empty( $columns['cb'] ) ) {
static $cb_counter = 1;
$columns['cb'] = '<label class="screen-reader-text" for="cb-select-all-' . $cb_counter . '">' . __( 'Select All' ) . '</label>'
. '<input id="cb-select-all-' . $cb_counter . '" ' . disabled( $this->enabled == false, true, false ) . ' type="checkbox" />';
$cb_counter++;
}
foreach ( $columns as $column_key => $column_display_name ) {
$class = array( 'manage-column', "column-$column_key" );
$style = '';
if ( in_array( $column_key, $hidden ) )
$style = 'display:none;';
$style = ' style="' . $style . '"';
if ( 'cb' == $column_key )
$class[] = 'check-column';
elseif ( in_array( $column_key, array( 'posts', 'comments', 'links' ) ) )
$class[] = 'num';
if ( isset( $sortable[$column_key] ) ) {
list( $orderby, $desc_first ) = $sortable[$column_key];
if ( $current_orderby == $orderby ) {
$order = 'asc' == $current_order ? 'desc' : 'asc';
$class[] = 'sorted';
$class[] = $current_order;
} else {
$order = $desc_first ? 'desc' : 'asc';
$class[] = 'sortable';
$class[] = $desc_first ? 'asc' : 'desc';
}
$column_display_name = '<a href="' . esc_url( add_query_arg( compact( 'orderby', 'order' ), $current_url ) ) . '"><span>' . $column_display_name . '</span><span class="sorting-indicator"></span></a>';
}
$id = $with_id ? "id='$column_key'" : '';
if ( !empty( $class ) )
$class = "class='" . join( ' ', $class ) . "'";
echo "<th scope='col' $id $class $style>$column_display_name</th>";
}
}
} | 28.989418 | 235 | 0.536959 |
82b33a02bd5b4616526bd4b6c2aee73cb868b589 | 1,467 | swift | Swift | Twitter/UserHeaderView.swift | kate2753/CodePathTwitter | 124483caa07817ad2249e60c77b8e7f45dc6b18a | [
"Apache-2.0"
] | null | null | null | Twitter/UserHeaderView.swift | kate2753/CodePathTwitter | 124483caa07817ad2249e60c77b8e7f45dc6b18a | [
"Apache-2.0"
] | null | null | null | Twitter/UserHeaderView.swift | kate2753/CodePathTwitter | 124483caa07817ad2249e60c77b8e7f45dc6b18a | [
"Apache-2.0"
] | null | null | null | //
// UserHeaderView.swift
// Twitter
//
// Created by kate_odnous on 8/19/16.
// Copyright © 2016 Kate Odnous. All rights reserved.
//
import UIKit
import AFNetworking
class UserHeaderView: UIView {
@IBOutlet private var contentView: UIView!
@IBOutlet private weak var coverPhotoImageView: UIImageView!
@IBOutlet private weak var profilePhotoImageView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var userHandleLabel: UILabel!
var user: User? {
didSet {
print("user header user set \(user)")
if let user = user {
userNameLabel.text = user.name
userHandleLabel.text = "@\(user.screenName!)"
coverPhotoImageView.setImageWithURL(user.profileBannerUrl!)
profilePhotoImageView.setImageWithURL(user.profilePhotoUrl!)
}
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initSubviews()
}
override init(frame: CGRect) {
super.init(frame: frame)
initSubviews()
}
func initSubviews() {
// standard initialization logic
let nib = UINib(nibName: "UserHeaderView", bundle: nil)
nib.instantiateWithOwner(self, options: nil)
contentView.frame = bounds
addSubview(contentView)
}
}
| 24.864407 | 77 | 0.69257 |
8dd2f58f41dd8641bf90f6fcc25024e43928a63c | 53,918 | js | JavaScript | blackswan/methods.js | stewdio/blackswan | f47d4626e54ff748280ed8ff44a4e9b2e44e18cd | [
"MIT"
] | 10 | 2020-10-06T14:47:00.000Z | 2021-11-03T18:01:10.000Z | blackswan/methods.js | stewdio/blackswan | f47d4626e54ff748280ed8ff44a4e9b2e44e18cd | [
"MIT"
] | null | null | null | blackswan/methods.js | stewdio/blackswan | f47d4626e54ff748280ed8ff44a4e9b2e44e18cd | [
"MIT"
] | 1 | 2020-10-07T21:49:41.000Z | 2020-10-07T21:49:41.000Z |
// Copyright © 2020, Stewart Smith. See LICENSE for details.
/////////////////
// //
// Helpers //
// //
/////////////////
function reset(){
document
.querySelector( 'main' )
.classList
.remove(
'tilted',
'spin'
)
forEachElement(
'.keyboards-rotator, .keyboards-translator',
resetElement
)
forEachElement(
'.keyboard',
function( el ){
el.statesReset()
el.classList.remove(
'capslock',
'long-sustain',
'push-out',
'push-in',
'tilt-complete',
'popcorn',
'popcorn-dead'
)
resetElement( el )
}
)
forEachElement(
'.key',
function( el ){
el.locksReset()
el.classList.remove(
'engage',
'disengaging',
'happening',
'blindspot',
'not-obvious',
'black',
'wtf',
'blank'// A clone for “dead” but intended to be added / removed at random.
)
resetElement( el )
}
)
Mode.switchTo( 'idle' )
tasks.updates.remove( ripple )
}
function resetElement( el ){
el.style.transition = 'none'
el.style.animation = 'none'
setTimeout( function(){
el.removeAttribute( 'style' )
el.style.removeProperty( 'transition' )
// visibility?
})
}
function boot(){
reset()
forEachElement( '.key', function( key ){
'tx ty tz'
.split( ' ' )
.forEach( function( name ){
key.setAttribute( name, getRandomBetween( -22, 22 ))
})
'rx ry rz'
.split( ' ' )
.forEach( function( name ){
key.setAttribute( name, getRandomBetween( -1, 1 ))
})
})
}
function changeKeyboardState( stateName, addOrRemove, description ){
const actionName = 'state'+ addOrRemove.charAt( 0 ).toUpperCase() + addOrRemove.slice( 1 )
append(
0,
function(){
forEachElement(
'.keyboard',
function( element ){
if( typeof element[ actionName ] === 'function') element[ actionName ]( stateName )
else console.warn( `Tried to apply state “${ stateName }” to a keyboard but ${ actionName } did not exist.`, element )
}
)
},
description
)
}
function capslockOn(){
changeKeyboardState( 'capslock', 'add', 'Caps-lock ON.' )
}
function capslockOff(){
changeKeyboardState( 'capslock', 'remove', 'Caps-lock OFF.' )
}
function pushOutOn(){
changeKeyboardState( 'push-out', 'add', 'Push-out ON.' )
}
function pushOutOff(){
changeKeyboardState( 'push-out', 'remove', 'Push-out OFF.' )
}
function dimmerOn(){
append( 0, function(){
document
.getElementById( 'fullscreen-container' )
.classList
.add( 'dim' )
})
}
function dimmerOff(){
append( 0, function(){
document
.getElementById( 'fullscreen-container' )
.classList
.remove( 'dim' )
})
}
function tiltedOn(){
append( 0, function(){
document
.querySelector( 'main' )
.classList
.add( 'tilted' )
})
}
function tiltedOff(){
append( 0, function(){
document
.querySelector( 'main' )
.classList
.remove( 'tilted' )
})
}
///////////////
// //
// Riffs //
// //
///////////////
const
insertHit = function( timeCursor, durationToOccupy, keyName, durationVisible ){
if( typeof durationVisible !== 'number' ) durationVisible = durationToOccupy
insert(
timeCursor,
0,//comp.beatsPerSecond * durationToOccupy,
function(){ keyEngage( keyName )},
'Hit ON: '+ keyName
)
insert(
timeCursor + comp.beatsPerSecond * durationVisible * 15/16,
0,
function(){ keyDisengage( keyName )},
'Hit OFF: '+ keyName
)
},
insertRiffBeat = function( timeStart, durationInBeats, skipLastHit ){
if( typeof durationInBeats !== 'number' ) durationInBeats = 4
let timeCursor = timeStart
;[
[
[ 2/4, 'space', 1/4 ],
[ 2/4, 'space' ]
],
[
[ 1/4, 'period' ],
[ 2/4, 'space' ],
],
[
[ 2/4, 'tab' ],
[ 2/4, 'period' ],
],
[
[ 1/4, 'space' ],
[ 1/4, 'period' ],
[ 2/4, 'space' ]
]
]
.filter( function( item, i ){
return i < durationInBeats
})
.flat()
.forEach( function( item ){
insertHit.call( this, timeCursor, ...item )
timeCursor += item[ 0 ] * comp.beatsPerSecond
})
if( !skipLastHit ) insertHit( timeCursor, 1/4, 'space', 1/8 )
},
insertRiffBumpBump = function( timeStart ){
let timeCursor = timeStart
;[
[ 2/4, 'option-left', 1/4 ],
[ 2/4, 'option-left', 0.4 ]
].forEach( function( item ){
insertHit.call( this, timeCursor, ...item )
timeCursor += item[ 0 ] * comp.beatsPerSecond
})
},
// insertRiffDim = function( timeStart ){
// const el = document.getElementById( 'fullscreen-container' )
// console.log( ' dim it at ', timeStart )
// insert(
// timeStart,
// 0,
// function(){
// console.log( 'dim??' )
// //el.style.backgroundColor = 'black'
// el.classList.add( 'dim' )
// },
// 'Dim Dim'
// )
// insert(
// timeStart + comp.beatsPerSecond * 2,
// 0,
// function(){
// console.log( 'dim OFF' )
// // el.style.backgroundColor = ''
// el.classList.remove( 'dim' )
// },
// 'Dim Dim'
// )
// },
insertRiffDeadOrAlive = function( timeStart ){
let timeCursor = timeStart
;[
[ 1/2, 'arrow-left' ],
[ 1/2, 'arrow-down' ],
[ 1/2, 'arrow-up' ],
[ 2/2, 'arrow-right' ]
].forEach( function( item ){
insertHit.call( this, timeCursor, ...item )
timeCursor += item[ 0 ] * comp.beatsPerSecond
})
},
insertRiffOptions = function( timeStart, options ){
if( options.includes( 'bump-bump' )) insertRiffBumpBump( timeStart )
if( options.includes( 'dim' )) insertRiffDim( timeStart )
if( options.includes( 'dead-or-alive' )) insertRiffDeadOrAlive( timeStart )
},
insertRiff = function( timeStart, durationInBeats, options ){
if( typeof timeStart !== 'number' ) timeStart = comp.findLastBeat()
if( typeof durationInBeats !== 'number' ) durationInBeats = 4
if( typeof options !== 'string' ) options = ''
let
timeCursor = timeStart,
i = 0
while( i < durationInBeats ){
const
beatsRemaining = durationInBeats - i,
beatsThisLoop = beatsRemaining >= 4
? 4
: beatsRemaining
insertRiffBeat( timeCursor, beatsThisLoop, options.includes( 'skip-last-hit' ))
insertRiffOptions( timeCursor, options )
timeCursor += beatsThisLoop * comp.beatsPerSecond
i += 4
}
},
appendRiff =function( durationInBeats, options ){
insertRiff( comp.findLastBeat(), durationInBeats, options )
append( durationInBeats )
},
appendRiffBackside = function(){
let timeCursor = comp.findLastBeat()
;[// Only TWO beats long.
[ 2/4, 'tab' ],
[ 2/4, 'period' ],
[ 1/4, 'space' ],
[ 1/4, 'period' ],
[ 2/4, 'spaces' ]
].forEach( function(){
insertHit.call( this, timeCursor, ...item )
timeCursor += item[ 0 ] * comp.beatsPerSecond
})
},
appendRiffedUp = function( text, options ){
if( typeof options !== 'string' ) options = ''
if( typeof text !== 'string' || text === 'fuckedup' ) text = 'fuckedXp'
const durationPerCharacter = comp.beatsPerSecond * 2 / text.length
let timeStart = comp.findLastBeat()
text
.split( '' )
.forEach( function( letter, i ){
insert(
timeStart + durationPerCharacter * i,
0,
function(){
// console.log( 'letter ON', letter )
if( letter === 'X' ) keyDisengage( 'U' )
else keyEngage( letter.toUpperCase() )
},
'Riffed up ON: '+ letter
)
insert(
timeStart + comp.beatsPerSecond * 4 + durationPerCharacter * i,
0,
function(){
// console.log( 'letter OFF', letter )
if( letter === 'u' ) keyEngage( 'U' )
else if( letter === 'X' ) keyDisengage( 'U' )
else keyDisengage( letter.toUpperCase() )
},
'Riffed up OFF: '+ letter
)
})
for( let i = 0; i < 2; i ++ ){
timeStart = comp.findLastBeat()
if( options.includes( 'riff' )) insertRiffBeat( timeStart, 4, options.includes( 'skip-last-hit' ))
insertRiffOptions( timeStart, options )
append( 4 )
}
}
//////////////
// //
// Type //
// //
//////////////
const
insertType = function( timeStart, durationInBeats, text, holdUntilDone ){
if( typeof durationInBeats !== 'number' ) durationInBeats = 6
text = text.replace( /\s/g, '' )
if( typeof holdUntilDone !== 'boolean' ) holdUntilDone = false
const
durationPerCharacter = durationInBeats / text.length
text
.split( '' )
.forEach( function( character, i ){
const
cssName = characterToKeyName[ character ]
? characterToKeyName[ character ]
: character.toUpperCase(),
isMajuscule = character.match( /[A-Z]/ )
if( isMajuscule ){
const side = Math.random() >= 0.5 ? 'left' : 'right'
insert(
timeStart + comp.beatsPerSecond * i * durationPerCharacter,
0,
function(){ keyEngage( 'shift-'+ side )},
'insertType() ON: Shift'
)
insert(
timeStart + comp.beatsPerSecond * i * durationPerCharacter + durationPerCharacter * 1/2,
0,
function(){ keyDisengage( 'shift-'+ side )},
'insertType() OFF: Shift'
)
}
insert(
timeStart + comp.beatsPerSecond * i * durationPerCharacter,
0,
function(){ keyEngage( cssName )},
'insertType() ON: '+ cssName
)
const releaseAfterDuration = holdUntilDone ?
durationInBeats * comp.beatsPerSecond :
comp.beatsPerSecond * i * durationPerCharacter + durationPerCharacter * 15/16
insert(
timeStart + releaseAfterDuration,
0,
function(){ keyDisengage( cssName )},
'insertType() OFF: '+ cssName
)
})
},
appendType = function( durationInBeats, text, holdUntilDone, debug ){
insertType( comp.findLastBeat(), ...arguments )
append( durationInBeats )
if( debug ) assessDuration( timeStart, comp.findLastBeat(), `Type (${ text })`, durationInBeats )
}
// 0:45
function train( durationInBeats, debug ){
const
timeStart = comp.findLastBeat(),
action = function( timeMark, durationInBeatsPerCharacter ){
if( typeof durationInBeatsPerCharacter !== 'number' ){
durationInBeatsPerCharacter = 1/16
}
return function( name, i ){
if( name.length === 1 ) name = name.toUpperCase()
insert(
timeMark + durationInBeatsPerCharacter * comp.beatsPerSecond * i,
0,
function(){
// console.log( 'ON: name', name )
keyEngage( name )
},
'Traaaaiiiin ON: '+ name
)
insert(
timeMark + durationInBeatsPerCharacter * comp.beatsPerSecond * ( i + 8 ),
0,
function(){ keyDisengage( name )},
'Traaaaiiiin OFF: '+ name
)
return name
}
},
beat = comp.beatsPerSecond
changeKeyboardState( 'long-sustain', 'add' )
insertType( timeStart, beat / 8, 'tr' )
'567890'
.split( '' )
.concat(
'minus',
'equal',
'delete'
)
.map( action( timeStart + beat * 0.50 ))
.map( action( timeStart + beat * 1.50 ))
.map( action( timeStart + beat * 2.50 ))
.map( action( timeStart + beat * 3.50, 1/32 ))
'tyuiop'
.split( '' )
.concat(
'bracket-open',
'bracket-close',
'slash-backward'
)
.map( action( timeStart + beat * 0.25 ))
.map( action( timeStart + beat * 1.00 ))
.map( action( timeStart + beat * 2.00 ))
.map( action( timeStart + beat * 3.00 ))
.map( action( timeStart + beat * 4.00, 1/32 ))
'asdfghjkl'
.split( '' )
.concat(
'semicolon',
'quote',
'return'
)
.map( action( timeStart ))
.map( action( timeStart + beat * 4.50, 1/32 ))
'nm'
.split( '' )
.concat(
'comma',
'period',
'slash-forward',
'shift-right'
)
.map( action( timeStart + beat * 5.00, 1/32 ))
append( durationInBeats )
changeKeyboardState( 'long-sustain', 'remove' )
if( debug ) assessDuration(
timeStart,
comp.findLastBeat(),
'Traaaaiiiin',
durationInBeats
)
}
function fuckedUp( durationInBeats, debug ){
if( typeof durationInBeats !== 'number' ) durationInBeats = 2/4
const
timeStart = comp.findLastBeat(),
fuckedUp = 'fuckedup',
durationPerCharacter = durationInBeats / fuckedUp.length
fuckedUp
.split( '' )
.forEach( function( letter, i ){
append(
durationPerCharacter,
function(){ keyToggle( letter.toUpperCase() )},
'Fucked up: '+ letter
)
})
if( debug ) assessDuration( timeStart, comp.findLastBeat(), 'Fucked up', durationInBeats )
}
// 1:32-ish
new Mode({
name: 'happening',
timeStart: 0,
durationInSeconds: 0,
setup: function(){
const
that = this,
text = 'hapening',// Not it’s just a single P here.
gap = comp.beatsPerSecond * 2 / text.length,
durationSeconds = comp.beatsPerSecond * 4.5
this.group = text
.split( '' )
.map( function( character, i ){
const delay = i * gap
return {
name: character,
timeStart: that.timeStart + delay,
durationSeconds: durationSeconds,// - delay,
hasEngaged: false,
hasDisengaged: false,
tx: 0,//randomWithinRangeEitherSign( 10, 20 ),
ty: 0,//randomWithinRangeEitherSign( 10, 20 ),
tz: getRandomBetween( 400, 500 ),
// Technically these should be normalized
// such that the vector length === 1.
// But the browser will fix this for us.
rx: getRandomBetweenEitherSign(),
ry: getRandomBetweenEitherSign(),
rz: 0//getRandomBetweenEitherSign()
// rx: getRandomBetweenEitherSign(),
// ry: 10 + Math.floor( Math.random( 7 )),
// rz: 0
}
})
},
update: function(){
if( comp.isPlaying ){
const that = this
this.group
.forEach( function( item, i ){
const
elapsedSeconds = comp.audio.currentTime - item.timeStart,
elapsedPercent = Math.max(
0,
Math.min(
1,
elapsedSeconds / item.durationSeconds,
)
),
sine = Math.sin( elapsedPercent * Math.PI ),
angle = elapsedPercent,
[ tx, ty, tz ] = [
item.tx,
item.ty,
item.tz
].map( function( value ){
return value * sine
})
if( elapsedPercent > 0 && item.hasEngaged === false ){
item.hasEngaged = true
keyEngage( item.name.toUpperCase() )
}
// if( elapsedPercent >= 0.5 && item.hasDisengaged === false ){
if( elapsedPercent >= 0.9999 && item.hasDisengaged === false ){
item.hasDisengaged = true
keyDisengage( item.name.toUpperCase() )
}
forEachElement(
'.key-'+ item.name.toUpperCase(),
function( element ){
// element.style.boxShadow = `
// 0 0 calc( var( --size ) * 2 * ${( 1 - sine * 0.8 )} ) white,
// 0 0 calc( var( --size ) * 4 * ${( 1 - sine * 0.8 )} ) white`
element.style.transform =
`translate3d( ${tx}px, ${ty}px, ${tz}px )`+
`rotate3d( ${item.rx}, ${item.ry}, ${item.rz}, ${angle}turn )`
// element.style.transform = `
// translate3d( ${ tx }px, ${ ty }px, ${ tz }px )
// rotateX( ${ item.rx * elapsedPercent * 360 }deg )
// rotateY( ${ item.ry * elapsedPercent * 360 }deg )`
}
)
})
}
if( comp.audio.currentTime >= this.timeStart + this.durationInSeconds ){
Mode.switchTo( 'idle' )
}
},
teardown: function(){
this.group
.forEach( function( character, i ){
forEachElement(
'.key-'+ character.name.toUpperCase(),
function( element ){
element.style.transition = 'none'
element.style.transform = ''
// element.style.boxShadow = ''
setTimeout( function(){
element.style.transition = ''
})
}
)
})
}
})
function blindSpot( durationInBeats, debug ){
if( typeof durationInBeats !== 'number' ) durationInBeats = 8
const
timeStart = comp.findLastBeat(),
text = 'blindspot',
durationPerCharacter = ( comp.beatsPerSecond * 2 ) / text.length
text
.split( '' )
.forEach( function( letter, i ){
insert(
timeStart + durationPerCharacter * i,
0,
function(){
forEachElement(
'.key-'+ letter.toUpperCase(),
function( key ){
key.classList.add( 'blindspot' )
}
)
},
'Blind spot ON: '+ letter.toUpperCase()
)
insert(
timeStart + comp.beatsPerSecond * 4 + durationPerCharacter * i,
0,
function(){
forEachElement(
'.key-'+ letter.toUpperCase(),
function( key ){
key.classList.remove( 'blindspot' )
}
)
},
'Blind spot OFF: '+ letter.toUpperCase()
)
})
insertRiffBeat( timeStart, 4 )
insertRiffBeat( timeStart + 4 * comp.beatsPerSecond, 4 )
append( durationInBeats )
if( debug ) assessDuration( timeStart, comp.findLastBeat(), 'Blind spot', durationInBeats )
}
function obvious( durationInBeats, debug ){
// yes, type out the words/
// but at the same time flip all the tiles over
// except for 'obvious'
const
timeStart = comp.findLastBeat(),
text = 'OBVIOUS'.split( '' )
forEachElement(
'.key',
function( element ){
if( text.includes( element.getAttribute( 'data-name' )) === false ){
const x = parseFloat( element.getAttribute( 'x' ))
insert(
timeStart + x * 0.07,
0,
function(){
element.classList.add( 'not-obvious' )
}
)
insert(
timeStart + comp.beatsPerSecond * 6 + x * 0.07,
0,
function(){
const cleanup = function(){
// console.log( 'finished cleanup', element.getAttribute( 'data-name' ), element.classList )
element.removeEventListener( 'transitionend', cleanup )
element.classList.remove( 'not-obvious-release' )
}
element.addEventListener( 'transitionend', cleanup )
element.classList.add( 'not-obvious-release' )
element.classList.remove( 'not-obvious' )
}
)
}
}
)
insert(
timeStart + comp.beatsPerSecond * 3,
0,
function(){
forEachElement( '.keyboard', ( e ) => { e.classList.remove( 'push-out' )})
}
)
insert(
timeStart + comp.beatsPerSecond * 6,
0,
function(){
forEachElement( '.keyboard', ( e ) => { e.classList.add( 'push-out' )})
}
)
const durationPerCharacter = comp.beatsPerSecond / ( text.length + 2 )
text
.forEach( function( character, i ){
insert(
timeStart + comp.beatsPerSecond * 4 + durationPerCharacter * i,
0,
function(){
keyEngage( character.toUpperCase() )
}
)
insert(
timeStart + comp.beatsPerSecond * 5 + durationPerCharacter * i,
0,
function(){
keyDisengage( character.toUpperCase() )
}
)
})
append( durationInBeats )
if( debug ) assessDuration( timeStart, comp.findLastBeat(), 'Obvious', durationInBeats )
}
// 2:18 – 2:36 “NO IT ISN’T”
function noitisnt( timeStart, durationInBeats ){
let timeCursor = timeStart
timeCursor += 0.25
// Notice, no captial letters here.
// The Shift key flash is too distracting at this point
// in the subtle ease-in to the keyboard breakup.
insertType( timeCursor, 1.25, 'no it isnt', false )
timeCursor += 1.25
insertType( timeCursor, 1.00, 'but it isnt', false )
timeCursor += 1.25
insertType( timeCursor, 3.00, 'but it isnt woa this is from stew', false )
timeCursor += 2.25
insertType( timeCursor, 1.50, 'self unemployed', false )
timeCursor += 1.50
insertType( timeCursor, 3.00, 'but its too much fun to stop.', false )
timeCursor += 2.25
// But by here the keyboard is an exploded nebula
// so it’s ok to flash it up.
insertType( timeCursor, 3.50, 'Much love to Pilot and Atlas.', false )
timeCursor += 2.50
insertType( timeCursor, 3.25, 'Much love to Meredith, Charlie, and Dexter.', false )
timeCursor += 2.50
insertType( timeCursor, 3.00, 'What do you sing here, Thom?', true )
timeCursor += 2.25
insertType( timeCursor, 3.00, 'Now lets get back to it, eh.', true )
}
new Mode({
name: 'noitisnt',
setup: function(){
const
that = this,
keyboardWidth = 99,
beatToNorm = function( beats ){
return beats / that.durationInBeats
},
keyboardsTranslator = document.querySelector( '.keyboards-translator' ),
keyboardsRotator = document.querySelector( '.keyboards-rotator' ),
moveKeys = function(){
const that = this
forEachElement( '.key', function( key ){
const [ tx, ty, tz ] = 'tx ty tz'
.split( ' ' )
.map( function( attribute ){
// console.log( attribute, parseFloat( key.getAttribute( attribute )) )
return lerp(
0,
parseFloat( key.getAttribute( attribute )),
that.n
)
})
const [ rx, ry, rz ] = 'rx ry rz'
.split( ' ' )
.map( function( attribute ){
return parseFloat( key.getAttribute( attribute ))
})
key.style.transition = 'none'
key.style.transform = `translate3d(
calc( var( --size ) * ${ tx } ),
calc( var( --size ) * ${ ty } ),
calc( var( --size ) * ${ tz } )
)
rotate3d( ${ rx }, ${ ry }, ${ rz }, ${ that.n * 45 }deg )`
})
}
keyboardsRotator.style.transform = `rotate3d( 0, 0, 0, 0turn )`
this.tweens = [
// Explode the keys out.
new TWEEN.Tween({ n: 0 })
.to({ n: 1 }, beatToNorm( 24 ))
.easing( TWEEN.Easing.Cubic.InOut )
.onUpdate( moveKeys )
.start( 0 ),
// Translate the keyboard.
new TWEEN.Tween({
tx: 0,
ty: 0,
tz: 0
})
.to({
tx: -5,
ty: 5,
tz: -5
}, beatToNorm( that.durationInBeats - 8 ))
.easing( TWEEN.Easing.Cubic.InOut )
.onUpdate( function(){
keyboardsTranslator.style.transform = `
translate3d(
calc( var( --size ) * ${ this.tx } ),
calc( var( --size ) * ${ this.ty } ),
calc( var( --size ) * ${ this.tz } )
)`
})
.start( beatToNorm( 8 )),
// Rotate the keyboard.
new TWEEN.Tween({
rx: 0,
ry: 0
})
.to({
rx: 45,
ry: -373
}, beatToNorm( that.durationInBeats - 12 ))
.easing( TWEEN.Easing.Cubic.InOut )
.onUpdate( function(){
keyboardsRotator.style.transform = `
rotateX( ${ this.rx }deg )
rotateY( ${ this.ry }deg )`
})
.onComplete( function(){
document
.querySelector( 'main' )
.classList
.add( 'tilted' )
})
.start( beatToNorm( 12 )),
// Contract the keys in.
new TWEEN.Tween({ n: 1 })
.to({ n: 0 }, beatToNorm( 1 ))
.easing( TWEEN.Easing.Cubic.InOut )
.onUpdate( moveKeys )
.start( beatToNorm( that.durationInBeats - 1 ))
]
document.querySelector( 'main' ).classList.add( 'spin' )
},
update: function(){
if( comp.isPlaying ){
const
elapsedSeconds = comp.audio.currentTime - this.timeStart,
elapsedPercent = elapsedSeconds / this.durationInSeconds
this.tweens
.forEach( function( tween ){
tween.update( elapsedPercent )
})
}
if( comp.audio.currentTime >= this.timeStart + this.durationInSeconds ){
Mode.switchTo( 'idle' )
}
},
teardown: function(){
const
that = this,
keyboardsTranslator = document.querySelector( '.keyboards-translator' ),
keyboardsRotator = document.querySelector( '.keyboards-rotator' )
keyboardsTranslator.style.transition = 'none'
keyboardsRotator.style.transition = 'none'
setTimeout( function(){
keyboardsTranslator.style.removeProperty( 'transform' )
keyboardsTranslator.style.removeProperty( 'transition' )
keyboardsRotator.style.removeProperty( 'transform' )
keyboardsRotator.style.removeProperty( 'transition' )
})
forEachElement( '.key', function( key ){
key.style.transition = 'none'
setTimeout( function(){
key.style.removeProperty( 'transform' )
key.style.removeProperty( 'transition' )
})
})
document
.querySelector( 'main' )
.classList
.remove( 'spin' )
}
})
new Mode({
name: 'dimmerOn',
setup: function(){
this.el = document.getElementById( 'fullscreen-container' )
this.el.classList.remove( 'dim' )
},
update: function(){
if( comp.isPlaying ){
const
elapsedSeconds = comp.audio.currentTime - this.timeStart,
elapsedPercent = elapsedSeconds / this.durationInSeconds
// this.el.style.backgroundColor = `hsl( 0, 90%, ${ 40 - elapsedPercent * 30 }% )`
}
if( comp.audio.currentTime >= this.timeStart + this.durationInSeconds ){
Mode.switchTo( 'idle' )
}
},
teardown: function(){
this.el.style.backgroundColor = ''
// this.el.classList.add( 'dim' )
}
})
// 2:58 you can touch meeeeeeeeeeee
new Mode({
name: 'me',
setup: function(){
this.el = document.getElementById( 'fullscreen-container' )
this.el.classList.remove( 'dim' )
},
update: function(){
if( comp.isPlaying ){
const
elapsedSeconds = comp.audio.currentTime - this.timeStart,
elapsedPercent = elapsedSeconds / this.durationInSeconds,
elapsedX3 = elapsedPercent * 3 - 1,
gaus = createGaussianFunction( elapsedX3, 0.1, 1 ),
lightnessGain = constrain( norm( elapsedPercent, 0.2, 0.4 ), 0, 1 )
// this.el.style.backgroundColor = `hsl( 0, 90%, ${ 10 + lightnessGain * 30 }% )`
forEachElement( '.key', function( key, i ){
const
x = parseFloat( key.getAttribute( 'x-normalized' )),
amp = 80 * gaus( x ) * elapsedX3 * ( 0.2 + 0.8 * x ),
rotation = x < elapsedX3
? gaus( x )
: 0
if( amp > 0.5 ){
key.style.transform = 'translate3d( 0px, 0px, calc( var( --size ) * '+ amp +' )) rotateY( '+ rotation +'turn )'
if( rotation > 0.7 ) key.classList.add( 'engaged' )
if( rotation < 0.3 ) key.classList.remove( 'engaged' )
}
else key.style.transform = ''
})
}
if( comp.audio.currentTime >= this.timeStart + this.durationInSeconds ){
Mode.switchTo( 'idle' )
}
},
teardown: function(){
this.el.style.backgroundColor = ''
forEachElement( '.key', function( key ){
key.style.transition = 'none'
key.style.transform = ''
setTimeout( function(){
key.style.transition = ''
})
})
}
})
// 3:05 – 3:24,
// 3:24 – 3:44.
new Mode({
name: 'curtain',
setup: function(){
const
that = this,
container = document
.getElementById( 'fullscreen-container' )
let
curtainLeft = 0,
curtainRight = 0
// Ok. We’re going to tween some background gradients.
// And this is frustrating because we *should* be able to
// just change the values of the CSS variables, like so:
// container.style.setProperty( '--curtain-right', curtainRight +'%' )
// But that doesn’t seem to trigger redraws!
// So instead we have to actually reassign the whole gradient.
this.tweens = [
// Shoot out the right side first.
new TWEEN.Tween({ x: 0 })
.to({ x: 100 }, 0.125 )
.easing( TWEEN.Easing.Cubic.Out )
.onUpdate( function(){
curtainRight = this.x
container.style.background = `
linear-gradient(
to ${ that.direction },
var( --color-background ) ${ curtainLeft }%,
#000 ${ curtainLeft }%,
#000 ${ curtainRight }%,
var( --color-background ) ${ curtainRight }%
)`
})
.start( 0 ),
// Pull the left edge out to say hi.
new TWEEN.Tween({ x: 0 })
.to({ x: 33.3333 }, 0.125 )
.easing( TWEEN.Easing.Cubic.InOut )
.onUpdate( function(){
curtainLeft = this.x
container.style.background = `
linear-gradient(
to ${ that.direction },
var( --color-background ) ${ curtainLeft }%,
#000 ${ curtainLeft }%,
#000 ${ curtainRight }%,
var( --color-background ) ${ curtainRight }%
)`
})
.start( 0 ),
// Then put it back.
new TWEEN.Tween({ x: 33.3333 })
.to({ x: 0 }, 0.25 )
.easing( TWEEN.Easing.Cubic.InOut )
.onUpdate( function(){
curtainLeft = this.x
container.style.background = `
linear-gradient(
to ${ that.direction },
var( --color-background ) ${ curtainLeft }%,
#000 ${ curtainLeft }%,
#000 ${ curtainRight }%,
var( --color-background ) ${ curtainRight }%
)`
})
.start( 0.125 ),
// Finally, push the right edge all the way.
new TWEEN.Tween({ x: 0 })
.to({ x: 50 }, 0.125 )
.easing( TWEEN.Easing.Cubic.Out )
//.easing( TWEEN.Easing.Linear.None )
.onUpdate( function(){
curtainLeft = this.x
container.style.background = `
linear-gradient(
to ${ that.direction },
var( --color-background ) ${ curtainLeft }%,
#000 ${ curtainLeft }%,
#000 ${ curtainRight }%,
var( --color-background ) ${ curtainRight }%
)`
})
.start( 0.5 ),
new TWEEN.Tween({ x: 50 })
.to({ x: 100 }, 0.125 )
.easing( TWEEN.Easing.Cubic.In )
//.easing( TWEEN.Easing.Linear.None )
.onUpdate( function(){
curtainLeft = this.x
container.style.background = `
linear-gradient(
to ${ that.direction },
var( --color-background ) ${ curtainLeft }%,
#000 ${ curtainLeft }%,
#000 ${ curtainRight }%,
var( --color-background ) ${ curtainRight }%
)`
})
.start( 0.625 ),
]
},
update: function(){
if( comp.isPlaying ){
const
elapsedSeconds = comp.audio.currentTime - this.timeStart,
elapsedPercent = elapsedSeconds / this.durationInSeconds
this.tweens
.forEach( function( tween ){
tween.update( elapsedPercent )
})
}
if( comp.audio.currentTime >= this.timeStart + this.durationInSeconds ){
Mode.switchTo( 'idle' )
}
},
teardown: function(){
const container = document
.getElementById( 'fullscreen-container' )
container.style.removeProperty( 'background' )
}
})
// 3:44 – 4:03
new Mode({
name: 'popcorn',
setup: function(){
// console.log('~~~~~~~~~~ POPCORN TIME')
const
that = this,
beatToNorm = function( beats ){
return beats / that.durationInBeats
},
keyboardsTranslator = document.querySelector( '.keyboards-translator' ),
keyboardsRotator = document.querySelector( '.keyboards-rotator' ),
keyboard = document.querySelector( '.keyboard' ),
keyboardWidth = 99// `calc( var( --size ) * ${ keyboardWidth })`
let
translation = getCssTranslation( keyboardsTranslator )
// Now we can zero out the translation on our original keyboard
// and further prep for running in a series.
// Remove our “tilt-complete” CSS class
// as we’re about to move things manually.
// tiltedOff()
keyboard.classList.add( 'popcorn' )
keyboard.isOriginal = true
keyboard.index = 0
this.keyboards = [ keyboard ]
// Create our clone keyboard.
// This will clone all the HTMLElement bits of it
// but *NOT* the raw properties we’ve globbed on
// so we’ll need to do that for each clone.
for( let i = 0; i < 2; i ++ ){
const clone = keyboard.cloneNode( true )
clone.isClone = true
clone.index = i + 1
appendKeyAbilitiesToAllKeys( clone )
appendKeyboardAbilitiesTo( clone )
keyboard.parentNode.appendChild( clone )
clone.style.opacity = 0
setTimeout( function(){
clone.style.transform = `translate3d( calc( var( --size ) * ${ keyboardWidth * ( i + 1 )} ), 0, 0 )`
})
this.keyboards.push( clone )
}
// Setup our tweens.
this.keyboardOffsets = 0
this.tweens = [
// Rotate the keyboards into place.
new TWEEN.Tween({
rx: 45,
ry: -13,
rz: 0
})
.to({
rx: 80,
ry: 0,
rz: -90
}, beatToNorm( 16 ))
.easing( TWEEN.Easing.Cubic.InOut )
.onUpdate( function(){
keyboardsRotator.style.transform = `
rotateX( ${ this.rx }deg )
rotateY( ${ this.ry }deg )
rotateZ( ${ this.rz }deg )`
})
.start( beatToNorm( 0 )),
// Raise up the camera high.
new TWEEN.Tween({ tz: -5 })
.to({ tz: -50 }, beatToNorm( 8 ))
.easing( TWEEN.Easing.Cubic.InOut )
.onUpdate( function(){
translation = getCssTranslation( keyboardsTranslator )
keyboardsTranslator.style.transform = `
translate3d(
${ translation.x }px,
${ translation.y }px,
calc( var( --size ) * ${ this.tz } )
)`
translation = getCssTranslation( keyboardsTranslator )
})
.start( beatToNorm( 0 )),
// Fade in our keyboard clones.
new TWEEN.Tween({ opacity: 0 })
.to({ opacity: 1 }, beatToNorm( 6 ))
.easing( TWEEN.Easing.Cubic.In )
.onUpdate( function(){
that.keyboards[ 1 ].style.opacity = this.opacity
})
.start( beatToNorm( 8 )),
new TWEEN.Tween({ opacity: 0 })
.to({ opacity: 1 }, beatToNorm( 6 ))
.easing( TWEEN.Easing.Cubic.In )
.onUpdate( function(){
that.keyboards[ 2 ].style.opacity = this.opacity
})
.start( beatToNorm( 12 )),
// Now pull the camera down close to the keyboards.
new TWEEN.Tween({ tz: -50 })
.to({ tz: -2 }, beatToNorm( 12 ))
.easing( TWEEN.Easing.Cubic.InOut )
.onStart( function(){
document
.querySelector( 'main' )
.classList
.remove( 'tilted' )
})
.onUpdate( function(){
translation = getCssTranslation( keyboardsTranslator )
keyboardsTranslator.style.transform = `
translate3d(
${ translation.x }px,
${ translation.y }px,
calc( var( --size ) * ${ this.tz } )
)`
translation = getCssTranslation( keyboardsTranslator )
})
.start( beatToNorm( 8 ))
]
////////////////
// //
// Glide! //
// //
////////////////
this.messagesReady = []
this.messagesSpent = [ '', '', '' ]
const
keyboardGlide = function(){
// if( this.n > 0 && this.n < 1 ){
translation = getCssTranslation( keyboardsTranslator )
keyboardsTranslator.style.transform = `
translate3d(
calc( var( --size ) * ${ this.tx } ),
${ translation.y }px,
${ translation.z }px
)`
translation = getCssTranslation( keyboardsTranslator )
// Do we need to pick a keyboard up from behind us
// and lay it down at the head of the line?
if( this.tx + that.keyboardOffsets * keyboardWidth <=
keyboardWidth * -1.5 ){
// console.log( '██████████████████████ New keyboard', Math.random() )
that.keyboardOffsets ++
forEachElement( '.keyboard', function( keyboard ){
keyboard.classList.remove( 'fade-in')
})
that.keyboards[ 0 ].style.transform = `
translate3d( calc( var( --size ) * ${( that.keyboardOffsets + 2 ) * keyboardWidth } ), 0, 0 )`
// that.keyboards[ 0 ].classList.add( 'fade-in' )
that.keyboards.push( that.keyboards.shift())
that.keyboards
.forEach( function( keyboard, i ){
keyboard.index = i
})
// Do we have messages to erase?
if( that.messagesSpent.length ){
const message = that.messagesSpent.shift()
if( message.length ){
drawGlyph( glyphs[ message[ 0 ]], {
rootElement: that.keyboards[ 2 ],
offset: 4,
shouldErase: true
})
drawGlyph( glyphs[ message[ 1 ]], {
rootElement: that.keyboards[ 2 ],
offset: 11,
shouldErase: true
})
}
}
// Do we have messages to draw?
if( that.messagesReady.length ){
const message = that.messagesReady.shift()
drawGlyph( glyphs[ message[ 0 ]], {
rootElement: that.keyboards[ 2 ],
offset: 4
})
drawGlyph( glyphs[ message[ 1 ]], {
rootElement: that.keyboards[ 2 ],
offset: 11
})
that.messagesSpent.push( message )
}
else {
that.messagesSpent.push( '' )
}
}
// }
}
var
glideCursorInBeats = 13,
glideCursorX = -5,//translation.x / window.size,
glideSpeed = 49.5// 1 beat = 1/2 keyboard.
// console.log( 'PRIOR TO TWEEN CREATION translation', translation )
function createGlideTween(
cursorInBeats,
segmentDurationInBeats,
fromX,
tweenMethod,
description ){
const toX = fromX - segmentDurationInBeats * glideSpeed * (
tweenMethod === TWEEN.Easing.Linear.None
? 1 : 1/4
)
that.tweens.push(
new TWEEN.Tween(
{ n: 0, tx: fromX }
)
.to(
{ n: 1, tx: toX },
beatToNorm( segmentDurationInBeats )
)
.easing( tweenMethod )
.onStart( function(){
// console.log( '\n\n\n\nSTARTED!', description )
translation = getCssTranslation( keyboardsTranslator )
// console.log( 'translation', translation, '\n\n\n\n' )
})
.onUpdate( keyboardGlide )
.onComplete( function(){
// The fact that this would print for ever is very alarming to me.
// console.log( 'FINISHED w GLIDE TWEEN', description )
})
.start( beatToNorm( cursorInBeats ))
)
return {
glideCursorX: toX,
glideCursorInBeats: cursorInBeats + segmentDurationInBeats
}
}
var { glideCursorInBeats, glideCursorX } = createGlideTween(
glideCursorInBeats,
8,
glideCursorX,
TWEEN.Easing.Cubic.In,
'Ramp it up.'
)
var { glideCursorInBeats, glideCursorX } = createGlideTween(
glideCursorInBeats,
56,
glideCursorX,
TWEEN.Easing.Linear.None,
'Keep it steady'
)
var { glideCursorInBeats, glideCursorX } = createGlideTween(
glideCursorInBeats,
16,
glideCursorX,
TWEEN.Easing.Cubic.Out,
'Slow it down.'
)
// Angle shit so we can see the text better.
this.tweens.push(
new TWEEN.Tween({
rx: 80,
ry: 0,
rz: -90
})
.to({
rx: 60,
ry: 0,
rz: -90
}, beatToNorm( 16 ))
.easing( TWEEN.Easing.Cubic.InOut )
.onUpdate( function(){
keyboardsRotator.style.transform = `
rotateX( ${ this.rx }deg )
rotateY( ${ this.ry }deg )
rotateZ( ${ this.rz }deg )`
})
.start( beatToNorm( 24 ))
)
// Now put it back.
this.tweens.push(
new TWEEN.Tween({
rx: 60,
ry: 0,
rz: -90
})
.to({
rx: 80,
ry: 0,
rz: -90
}, beatToNorm( 16 ))
.easing( TWEEN.Easing.Cubic.InOut )
.onUpdate( function(){
keyboardsRotator.style.transform = `
rotateX( ${ this.rx }deg )
rotateY( ${ this.ry }deg )
rotateZ( ${ this.rz }deg )`
})
.start( beatToNorm( 64 ))
)
// Rotate back into place.
this.tweens.push(
new TWEEN.Tween({
rx: 80,
ry: 0,
rz: -90
})
.to({
rx: 0,
ry: 0,
rz: 0
}, beatToNorm( 16 ))
.easing( TWEEN.Easing.Cubic.InOut )
.onUpdate( function(){
keyboardsRotator.style.transform = `
rotateX( ${ this.rx }deg )
rotateY( ${ this.ry }deg )
rotateZ( ${ this.rz }deg )`
})
.start( 1 - beatToNorm( 24 ))
)
// Fade keyboard clones out.
this.tweens.push(
new TWEEN.Tween({ opacity: 1 })
.to({ opacity: 0 }, beatToNorm( 6 ))
.easing( TWEEN.Easing.Cubic.In )
.onUpdate( function(){
that.keyboards[ 2 ].style.opacity = this.opacity
})
.start( 1 - beatToNorm( 22 ))
)
this.tweens.push(
new TWEEN.Tween({ opacity: 1 })
.to({ opacity: 0 }, beatToNorm( 6 ))
.easing( TWEEN.Easing.Cubic.In )
.onUpdate( function(){
that.keyboards[ 1 ].style.opacity = this.opacity
})
.start( 1 - beatToNorm( 20 ))
)
// x
this.tweens.push(
new TWEEN.Tween({
tx: ( glideCursorX % keyboardWidth ),// * -1,
ty: 5,
tz: 2
})
.to({
tx: 0,
ty: 0,
tz: 0
}, beatToNorm( 4 ))
.easing( TWEEN.Easing.Cubic.InOut )
.onStart( function(){
// console.log( 'ABOUT TO TRANSLATE BACK INTO PLACE' )
// console.log( 'glideCursorX', glideCursorX )
// console.log( 'keyboardWidth', keyboardWidth )
// console.log( 'glideCursorX % keyboardWidth', glideCursorX % keyboardWidth )
translation = getCssTranslation( keyboardsTranslator )
// console.log( '!! translation', translation )
that.keyboards
.forEach( function( keyboard, i ){
// console.log( keyboard.isOriginal, i, i * keyboardWidth, keyboard )
keyboard.style.transform = `
translate3d(
calc( var( --size ) * ${ i * keyboardWidth } ),
0px,
0px
)`
const t = getCssTranslation( keyboard )
// console.log( 'keyboard', i, t )
})
})
.onUpdate( function(){
// console.log( this.tx )
keyboardsTranslator.style.transform = `
translate3d(
calc( var( --size ) * ${ this.tx } ),
calc( var( --size ) * ${ this.ty } ),
calc( var( --size ) * ${ this.tz } )
)`
translation = getCssTranslation( keyboardsTranslator )
})
.start( 1 - beatToNorm( 20 ))
// .start( 1 - beatToNorm( 12 ))
)
},
update: function(){
if( comp.isPlaying ){
const
elapsedSeconds = comp.audio.currentTime - this.timeStart,
elapsedPercent = elapsedSeconds / this.durationInSeconds
this.tweens
.forEach( function( tween ){
tween.update( elapsedPercent )
})
}
if( comp.audio.currentTime >= this.timeStart + this.durationInSeconds ){
Mode.switchTo( 'idle' )
}
},
teardown: function(){
const that = this
// console.log(
// '\n\n\n TURNING OFF “POPCORN”',
// '\nthis.keyboards[ 0 ].styletransform', this.keyboards[ 0 ].style.transform,
// '\n'
// )
const
keyboardsTranslator = document.querySelector( '.keyboards-translator' ),
keyboardsRotator = document.querySelector( '.keyboards-rotator' ),
keyboard = this.keyboards[ 0 ]
this.tweens
.forEach( TWEEN.remove )
while( this.keyboards.length > 1 ){
const clone = this.keyboards[ this.keyboards.length - 1 ]
clone.parentNode.removeChild( clone )
this.keyboards.pop()
}
keyboardsTranslator.style.transition = 'none'
keyboardsRotator.style.transition = 'none'
keyboard.style.transition = 'none'
keyboard.classList.remove(
'popcorn',
'fade-in'
)
setTimeout( function(){
keyboardsTranslator.style.removeProperty( 'transform' )
keyboardsTranslator.style.removeProperty( 'transition' )
keyboardsRotator.style.removeProperty( 'transform' )
keyboardsRotator.style.removeProperty( 'transition' )
keyboard.style.removeProperty( 'transform' )
keyboard.style.removeProperty( 'transition' )
})
}
})
function insertRowStream( timeStart, keyboard, rowIndex, engageDelay ){
let timeCursor = timeStart
if( keyboard instanceof HTMLElement !== true ){
keyboard = document.querySelector( '.keyboard' )
}
if( typeof rowIndex !== 'number' ) rowIndex = 1
if( typeof engageDelay !== 'number' ) engageDelay = 0.01
Array
.from(
keyboard
.querySelectorAll( `.key[y='${ rowIndex }']` )
)
.forEach( function( key, i ){
timeCursor += i * engageDelay
insert(
timeCursor,
0,
function(){
key.engage()
}
)
insert(
timeCursor + 1,
0,
function(){
key.disengage()
}
)
})
return timeCursor
}
function insertRowStreamAllKeyboards( timeStart, rowIndex ){
let timeCursor = timeStart
Array
.from(
document
.querySelectorAll( `.keyboard` )
)
.sort( function( a, b ){
// console.log( getCssTranslation( a ).x, getCssTranslation( b ).x )
return (
getCssTranslation( a ).x - getCssTranslation( b ).x
)
})
.forEach( function( keyboard, i ){
// console.log( keyboard, i )
timeCursor = insertRowStream( timeCursor, keyboard, rowIndex )
})
}
function insertStreamFun( timeStart ){
insert(
timeStart,
0,
function(){
for( let i = 0; i < 5; i ++ ){
insertRowStreamAllKeyboards(
timeStart + i * 1,
i
)
}
}
)
}
const glyphs = {
' ':`
`,
A:`
███
█ █
█ █
███
█ █
`,
B:`
███
█ █
██
█ █
███
`,
C:`
███
█
█
█
██
`,
D:`
██
█ █
█ █
█ █
██
`,
E:`
███
█
███
█
███
`,
F:`
███
█
█
███
█
`,
//G
//H
//I
//J
K:`
█ █
█ █
██
██
█ █
`,
L:`
█
█
█
█
███
`,
//M
N:`
██
█ █
█ █
█ █
█ █
`,
O:`
███
█ █
█ █
█ █
███
`,
P:`
███
█ █
█ █
███
█
`,
//Q
R:`
███
█ █
█ █
██
█ █
`,
S:`
███
█
███
█
███
`,
T:`
███
█
█
█
█
`,
U:`
█ █
█ █
█ █
█ █
██
`,
V:`
█ █
█ █
█ █
█ █
█
`,
W:`
██
█
█
█
██
`,// yikes. W is the W-orst.
//X
//Y
//Z
'0':`
█
█ █
█ █
█ █
█
`,
//1
'2':`
█
█ █
█
█
███
`,
//3
//4
//5
//6
//7
//8
//9
}
function composeStringOfGlyphs( text ){
return (
text
.split( '' )
.reduce( function( lines, character ){
glyphs[ character.toUpperCase() ]
.split( '\n' )
.forEach( function( c, i ){
lines[ i ] += c.padEnd( 4 )
})
return lines
}, new Array( 7 ).fill( '' ))
.join( '\n' )
)
}
console.log(
'\n\n\n',
composeStringOfGlyphs( 'BLACK SWAN' ),
'\n\nFriday, 02 October 2020.',
'\n\nLive: https://stewartsmith.io/blackswan',
'\nRepo: https://github.com/stewdio/blackswan',
'\n\n\n\n\n'
)
// Highest “reliable” offset is 11.
// Lowest “reliable” offset is 5.
/*
drawGlyphMessage(){
// Start on the most distant keyboard,
// keyboards[ 2 ]
// Each time a keyboard gets
// shuffled to the head of the line,
// shift a message off the stack
// and write it to that keyboard
// until there are no messages left.
queuedMessages = [
[ 'FU' ],
[ 'CK' ],
[ 'ED' ],
[ 'UP' ]
]
queuedMessages = [
[ 'BL' ],
[ 'CK' ],
[ 'SW' ],
[ 'AN' ]
]
queuedMessages = [
[ 'SP' ],
[ 'AR' ],
[ 'EP' ],
[ 'AR' ],
[ 'TS' ]
]
}
drawGlyph( glyphs.F, { offset: 5 })
drawGlyph( glyphs.U, { offset: 11 })
drawGlyph( glyphs.C, { offset: 5 })
drawGlyph( glyphs.K, { offset: 11 })
drawGlyph( glyphs.E, { offset: 5 })
drawGlyph( glyphs.D, { offset: 11 })
drawGlyph( glyphs.U, { offset: 5 })
drawGlyph( glyphs.P, { offset: 11 })
*/
function drawGlyph( glyph, params ){
if( typeof glyph !== 'string' ){
console.warn( 'Hey! That’s not a glyph!!', glyph, params )
return
}
if( params === undefined ) params = {}
if( params.rootElement === undefined ) params.rootElement = document.body
if( typeof params.offset !== 'number' ) params.offset = 7
if( typeof params.shouldErase !== 'boolean' ) params.shouldErase = !!params.shouldErase
glyph
.substring( 1, glyph.length - 1 )
.split( '\n' )
.forEach( function( row, r ){
row
.split( '' )
.forEach( function( column, c ){
const
x = params.offset - r,
y = c
if( column === '█' ){
forEachElement(
params.rootElement,
`.key[x='${ x }'][y='${ y }']`,
function( key ){
if( params.shouldErase ){
key.style.transition = 'none'
key.style.animation = 'none'
key.disengage( 'drawGlyph' )
setTimeout( function(){
key.style.removeProperty( 'transition' )
key.style.removeProperty( 'animation' )
})
}
else key.engage( 'drawGlyph' )
}
)
}
})
})
}
function blackSwanOn( durationInBeats, debug ){
if( typeof durationInBeats !== 'number' ) durationInBeats = 2/4
const
timeStart = comp.findLastBeat(),
text = [ ...new Set( 'blackswan'.split( '' ))],
durationPerCharacter = durationInBeats / text.length
append( 0, function(){ forEachElement( '.keyboard', (e)=>{e.stateAdd( 'capslock' )})}, 'caps-lock ON' )
text.forEach( function( letter, i ){
append(
durationPerCharacter,
function(){
//const key = document.querySelector( '.key-'+ letter.toUpperCase() )
//key.classList.add( 'black' )
forEachElement( '.key-'+ letter.toUpperCase(), function( e ){
e.classList.add( 'black' )
})
},
'Black ON: '+ letter
)
})
if( debug ) assessDuration( timeStart, comp.findLastBeat(), 'Black swan ON', durationInBeats )
}
function blackSwanOff( durationInBeats, debug ){
if( typeof durationInBeats !== 'number' ) durationInBeats = 2/4
const
timeStart = comp.findLastBeat(),
text = [ ...new Set( 'blackswan'.split( '' ))],
durationPerCharacter = durationInBeats / text.length
append( 0, function(){ forEachElement( '.keyboard', (e)=>{e.stateAdd( 'capslock' )})}, 'caps-lock ON' )
text.forEach( function( letter, i ){
append(
durationPerCharacter,
function(){
// const key = document.querySelector( '.key-'+ letter.toUpperCase() )
// key.classList.remove( 'black' )
forEachElement( '.key-'+ letter.toUpperCase(), function( e ){
e.classList.remove( 'black' )
})
},
'Black OFF: '+ letter
)
})
append( 0, function(){ forEachElement( '.keyboard', (e)=>{e.stateRemove( 'capslock' )})}, 'caps-lock OFF' )
if( debug ) assessDuration( timeStart, comp.findLastBeat(), 'Black swan OFF', durationInBeats )
}
function surfRider( durationInBeats ){
const
timeStart = comp.findLastBeat()
insert(
timeStart,
0,
function(){
//keyboard.classList.add( 'surf-rider' )
}
)
// assessDuration( timeStart, comp.findLastBeat(), 'Blind spot', durationInBeats )
}
function ekg( durationInBeats ){// Jed reference.
if( typeof durationInBeats !== 'number' ) durationInBeats = 1
const
text = ` ASDFT6YJM .;' `,
// text = ` ASDR5THNKL;' `,
timeStart = comp.findLastBeat(),
durationPerCharacter = durationInBeats / text.length
text.split( '' ).forEach( function( character, i ){
let cssName = character.toUpperCase()
if( character === ' ' ){
if( i === 0 ) cssName = 'caps-lock'
else if( i === text.length - 1 ) cssName = 'return'
else cssName = 'command-right'
}
else if( character === '.' ){
cssName = 'period'
}
else if( character === ';' ){
cssName = 'semicolon'
}
else if( character === "'" ){
cssName = 'quote'
}
const key = document.querySelector( '.key-'+ cssName )
insert(
timeStart + i * durationPerCharacter * comp.beatsPerSecond,
comp.beatsPerSecond * durationPerCharacter,
function(){
//key.classList.add( 'press' )
keyEngage( key )
}
)
insert(
timeStart + durationInBeats / 2 + i * durationPerCharacter * comp.beatsPerSecond,
0,// durationPerCharacter,
function(){
//key.classList.remove( 'press' )
keyDisengage( key )
}
)
})
// assessDuration( timeStart, comp.findLastBeat(), 'EKG', durationInBeats )
}
function ripple( x, y ){
// if( typeof x !== 'number' ) x = 0.2
// if( typeof y !== 'number' ) y = 0.5
if( typeof x !== 'number' ) x = Math.sin( performance.now() / 1000 )
if( typeof y !== 'number' ) y = Math.sin( performance.now() / 100000 )
forEachElement( '.key', function( key ){
const distance = Math.sqrt(
Math.pow( x - parseFloat( key.getAttribute( 'x-normalized' )), 2 ) +
Math.pow( y - parseFloat( key.getAttribute( 'y-normalized' )), 2 )
)
//console.log( key.getAttribute( 'data-name' ), distance )
const
sine = Math.sin( distance ),
sign = Math.sign( sine )
key.style.transform = 'translate3d( 0px, 0px, '+
Math.pow( sine * 20, 2 )
+'px )'
})
}
// window.setInterval( ripple, 100 )
// OR
// tasks.updates.add( ripple )
/////////////////
// //
// Posters //
// //
/////////////////
// From a default state
// remove the labels from all keys
// aside from the keys for B, L, A, C, K, S, W, and N.
function makePosterArt1(){
reset()
const keyboard = document.querySelector( '.keyboard' )
keyboard.classList.add( 'capslock' )
const keysToRemain =
'BLACKSWAN'.split( '' )
.map( function( letter ){
return 'key-'+ letter
})
keyboard.querySelectorAll( '.key' )
.forEach( function( key ){
const found = keysToRemain.some( e => Array.from( key.classList ).includes( e ))
if( !found ) key.classList.add( 'blank' )
})
}
// From a default state
// highlight all the keys for B, L, A, C, K, S, W, and N.
function makePosterArt2(){
reset()
const keyboard = document.querySelector( '.keyboard' )
keyboard.classList.add( 'capslock' )
const keysToRemain =
'BLACKSWAN'.split( '' )
.map( function( letter ){
return 'key-'+ letter
})
keyboard.querySelectorAll( '.key' )
.forEach( function( key ){
key.classList.add( 'blank' )
const found = keysToRemain.some( e => Array.from( key.classList ).includes( e ))
if( found ){
//key.classList.add( 'press' )
keyEngage( key.getAttribute( 'data-name' ) )
}
})
}
// From a default state
// remove all keys
// aside from the keys for B, L, A, C, K, S, W, and N.
function makePosterArt3(){
reset()
const keyboard = document.querySelector( '.keyboard' )
keyboard.classList.add( 'capslock' )
const keysToRemain =
'BLACKSWAN'.split( '' )
.map( function( letter ){
return 'key-'+ letter
})
keyboard.querySelectorAll( '.key' )
.forEach( function( key ){
const found = keysToRemain.some( e => Array.from( key.classList ).includes( e ))
if( !found ) key.style.visibility = 'hidden'
})
}
// From a default state
// remove all keys
// aside from the keys for B, L, A, C, K, S, W, N,
// and F, U, C, K, E, D, and P.
// Highlight the keys for “FUCKEDUP”.
function makePosterArt4(){
reset()
const keyboard = document.querySelector( '.keyboard' )
keyboard.classList.add( 'capslock' )
const keysToRemain =
'BLACKSWANFUCKEDUP'.split( '' )
.map( function( letter ){
return 'key-'+ letter
})
keyboard.querySelectorAll( '.key' )
.forEach( function( key ){
const found = keysToRemain.some( e => Array.from( key.classList ).includes( e ))
if( !found ) key.style.visibility = 'hidden'
})
const fuckedUpkeysToRemain =
'FUCKEDUP'.split( '' )
.map( function( letter ){
return 'key-'+ letter
})
keyboard.querySelectorAll( '.key' )
.forEach( function( key ){
const found = fuckedUpkeysToRemain.some( e => Array.from( key.classList ).includes( e ))
if( found ){
//key.classList.add( 'press' )
keyEngage( key.getAttribute( 'data-name' ))
}
})
}
// From a default state
// highlight all the keys for B, L, A, C, K, S, W, and N.
function makePosterArt5(){
reset()
const keyboard = document.querySelector( '.keyboard' )
keyboard.classList.add( 'capslock' )
const keysToRemain =
'FUCKEDP'.split( '' )
.map( function( letter ){
return 'key-'+ letter
})
keyboard.querySelectorAll( '.key' )
.forEach( function( key ){
key.classList.add( 'blank' )
const found = keysToRemain.some( e => Array.from( key.classList ).includes( e ))
if( found ){
//key.classList.add( 'press' )
keyEngage( key.getAttribute( 'data-name' ) )
}
})
}
// From a default state
// remove all keys
// aside from the key for B.
// Remove its background.
// Change the color and weight of the text.
function makeFavicon1(){
reset()
const keyboard = document.querySelector( '.keyboard' )
keyboard.classList.add( 'capslock' )
forEachElement( '.key', function( key ){
const name = key.getAttribute( 'data-name' )
if( name === 'B' ){
key.style.backgroundColor = 'transparent'
key.style.color = 'white'
key.style.fontWeight = '700'
}
else {
key.style.visibility = 'hidden'
}
})
}
| 18.780216 | 123 | 0.595682 |
7a877025ed54f09ebb586ee7020b5fc08020cc19 | 11,752 | go | Go | stringer/typestring.go | thallgren/dgo | 658c96cf0b729ef29f5e49fe5ef021017e59b9fa | [
"Apache-2.0"
] | 7 | 2019-09-13T10:09:50.000Z | 2021-04-07T00:52:56.000Z | stringer/typestring.go | thallgren/dgo | 658c96cf0b729ef29f5e49fe5ef021017e59b9fa | [
"Apache-2.0"
] | 5 | 2019-09-11T12:01:01.000Z | 2021-01-12T18:59:55.000Z | stringer/typestring.go | thallgren/dgo | 658c96cf0b729ef29f5e49fe5ef021017e59b9fa | [
"Apache-2.0"
] | 7 | 2019-09-04T08:16:37.000Z | 2021-08-25T15:13:52.000Z | package stringer
import (
"io"
"math"
"strconv"
"strings"
"github.com/lyraproj/dgo/internal"
"github.com/lyraproj/dgo/dgo"
"github.com/lyraproj/dgo/util"
)
const (
commaPrio = iota
orPrio
xorPrio
andPrio
typePrio
)
type typeToString func(typ dgo.Type, prio int)
type typeBuilder struct {
io.Writer
complexTypes map[dgo.TypeIdentifier]typeToString
aliasMap dgo.AliasMap
seen []dgo.Value
}
// TypeString produces a string with the go-like syntax for the given type.
func TypeString(typ dgo.Type) string {
return TypeStringWithAliasMap(typ, internal.DefaultAliases())
}
// TypeStringWithAliasMap produces a string with the go-like syntax for the given type.
func TypeStringWithAliasMap(typ dgo.Type, am dgo.AliasMap) string {
s := strings.Builder{}
newTypeBuilder(&s, am).buildTypeString(typ, 0)
return s.String()
}
func (sb *typeBuilder) anyOf(typ dgo.Type, prio int) {
sb.writeTernary(typ, typeAsType, prio, `|`, orPrio)
}
func (sb *typeBuilder) oneOf(typ dgo.Type, prio int) {
sb.writeTernary(typ, typeAsType, prio, `^`, xorPrio)
}
func (sb *typeBuilder) allOf(typ dgo.Type, prio int) {
sb.writeTernary(typ, typeAsType, prio, `&`, andPrio)
}
func (sb *typeBuilder) allOfValue(typ dgo.Type, prio int) {
sb.writeTernary(typ, valueAsType, prio, `&`, andPrio)
}
func (sb *typeBuilder) array(typ dgo.Type, _ int) {
at := typ.(dgo.ArrayType)
if at.Unbounded() {
util.WriteString(sb, `[]`)
} else {
util.WriteByte(sb, '[')
sb.writeSizeBoundaries(int64(at.Min()), int64(at.Max()))
util.WriteByte(sb, ']')
}
sb.buildTypeString(at.ElementType(), typePrio)
}
func (sb *typeBuilder) arrayExact(typ dgo.Type, _ int) {
util.WriteByte(sb, '{')
sb.joinValueTypes(typ.(dgo.ExactType).ExactValue().(dgo.Iterable), `,`, commaPrio)
util.WriteByte(sb, '}')
}
func (sb *typeBuilder) binary(typ dgo.Type, _ int) {
st := typ.(dgo.BinaryType)
util.WriteString(sb, `binary`)
if !st.Unbounded() {
util.WriteByte(sb, '[')
sb.writeSizeBoundaries(int64(st.Min()), int64(st.Max()))
util.WriteByte(sb, ']')
}
}
func (sb *typeBuilder) binaryExact(typ dgo.Type, _ int) {
util.WriteString(sb, `binary "`)
util.WriteString(sb, typ.(dgo.ExactType).ExactValue().(dgo.Binary).Encode())
util.WriteByte(sb, '"')
}
func (sb *typeBuilder) exactValue(typ dgo.Type, _ int) {
util.WriteString(sb, typ.(dgo.ExactType).ExactValue().String())
}
func (sb *typeBuilder) tuple(typ dgo.Type, _ int) {
sb.writeTupleArgs(typ.(dgo.TupleType), '{', '}')
}
func (sb *typeBuilder) _map(typ dgo.Type, _ int) {
at := typ.(dgo.MapType)
util.WriteString(sb, `map[`)
sb.buildTypeString(at.KeyType(), commaPrio)
if !at.Unbounded() {
util.WriteByte(sb, ',')
sb.writeSizeBoundaries(int64(at.Min()), int64(at.Max()))
}
util.WriteByte(sb, ']')
sb.buildTypeString(at.ValueType(), typePrio)
}
func (sb *typeBuilder) mapExact(typ dgo.Type, _ int) {
util.WriteByte(sb, '{')
sb.joinValueTypes(typ.(dgo.ExactType).ExactValue().(dgo.Map), `,`, commaPrio)
util.WriteByte(sb, '}')
}
func (sb *typeBuilder) _struct(typ dgo.Type, _ int) {
util.WriteByte(sb, '{')
st := typ.(dgo.StructMapType)
sb.joinStructMapEntries(st)
if st.Additional() {
if st.Len() > 0 {
util.WriteByte(sb, ',')
}
util.WriteString(sb, `...`)
}
util.WriteByte(sb, '}')
}
func (sb *typeBuilder) mapEntryExact(typ dgo.Type, _ int) {
me := typ.(dgo.ExactType).ExactValue().(dgo.MapEntry)
sb.buildTypeString(me.Key().Type(), commaPrio)
util.WriteByte(sb, ':')
sb.buildTypeString(me.Value().Type(), commaPrio)
}
func (sb *typeBuilder) floatRange(typ dgo.Type, _ int) {
st := typ.(dgo.FloatType)
sb.writeFloatRange(st.Min(), st.Max(), st.Inclusive())
}
func (sb *typeBuilder) integerRange(typ dgo.Type, _ int) {
st := typ.(dgo.IntegerType)
sb.writeIntRange(st.Min(), st.Max(), st.Inclusive())
}
func (sb *typeBuilder) regexpExact(typ dgo.Type, _ int) {
util.WriteString(sb, typ.TypeIdentifier().String())
util.WriteByte(sb, '[')
util.WriteString(sb, strconv.Quote(typ.(dgo.ExactType).ExactValue().String()))
util.WriteByte(sb, ']')
}
func (sb *typeBuilder) timeExact(typ dgo.Type, _ int) {
util.WriteString(sb, typ.TypeIdentifier().String())
util.WriteByte(sb, '[')
util.WriteString(sb, strconv.Quote(typ.(dgo.ExactType).ExactValue().String()))
util.WriteByte(sb, ']')
}
func (sb *typeBuilder) sensitive(typ dgo.Type, prio int) {
util.WriteString(sb, `sensitive`)
if op := typ.(dgo.UnaryType).Operand(); internal.DefaultAnyType != op {
util.WriteByte(sb, '[')
sb.buildTypeString(op, prio)
util.WriteByte(sb, ']')
}
}
func (sb *typeBuilder) stringExact(typ dgo.Type, _ int) {
util.WriteString(sb, strconv.Quote(typ.(dgo.ExactType).ExactValue().String()))
}
func (sb *typeBuilder) stringPattern(typ dgo.Type, _ int) {
internal.RegexpSlashQuote(sb, typ.(dgo.ExactType).ExactValue().String())
}
func (sb *typeBuilder) stringSized(typ dgo.Type, _ int) {
st := typ.(dgo.StringType)
util.WriteString(sb, `string`)
if !st.Unbounded() {
util.WriteByte(sb, '[')
sb.writeSizeBoundaries(int64(st.Min()), int64(st.Max()))
util.WriteByte(sb, ']')
}
}
func (sb *typeBuilder) ciString(typ dgo.Type, _ int) {
util.WriteByte(sb, '~')
util.WriteString(sb, strconv.Quote(typ.(dgo.ExactType).ExactValue().String()))
}
func (sb *typeBuilder) native(typ dgo.Type, _ int) {
rt := typ.(dgo.NativeType).GoType()
util.WriteString(sb, `native`)
if rt != nil {
util.WriteByte(sb, '[')
util.WriteString(sb, strconv.Quote(rt.String()))
util.WriteByte(sb, ']')
}
}
func (sb *typeBuilder) not(typ dgo.Type, _ int) {
nt := typ.(dgo.UnaryType)
util.WriteByte(sb, '!')
sb.buildTypeString(nt.Operand(), typePrio)
}
func (sb *typeBuilder) meta(typ dgo.Type, prio int) {
nt := typ.(dgo.UnaryType)
util.WriteString(sb, `type`)
if op := nt.Operand(); internal.DefaultAnyType != op {
if op == nil {
util.WriteString(sb, `[type]`)
} else {
util.WriteByte(sb, '[')
sb.buildTypeString(op, prio)
util.WriteByte(sb, ']')
}
}
}
func (sb *typeBuilder) function(typ dgo.Type, prio int) {
ft := typ.(dgo.FunctionType)
util.WriteString(sb, `func`)
sb.writeTupleArgs(ft.In(), '(', ')')
out := ft.Out()
if out.Len() > 0 {
util.WriteByte(sb, ' ')
if out.Len() == 1 && !out.Variadic() {
sb.buildTypeString(out.Element(0), prio)
} else {
sb.writeTupleArgs(ft.Out(), '(', ')')
}
}
}
func (sb *typeBuilder) errorExact(typ dgo.Type, _ int) {
util.WriteString(sb, `error[`)
util.WriteString(sb, strconv.Quote(typ.(dgo.ExactType).ExactValue().String()))
util.WriteByte(sb, ']')
}
func (sb *typeBuilder) named(typ dgo.Type, _ int) {
nt := typ.(dgo.NamedType)
util.WriteString(sb, nt.Name())
if params := nt.Parameters(); params != nil {
util.WriteByte(sb, '[')
sb.joinValueTypes(params, `,`, commaPrio)
util.WriteByte(sb, ']')
}
}
func newTypeBuilder(w io.Writer, am dgo.AliasMap) *typeBuilder {
sb := &typeBuilder{Writer: w, aliasMap: am}
sb.complexTypes = map[dgo.TypeIdentifier]typeToString{
dgo.TiAnyOf: sb.anyOf,
dgo.TiOneOf: sb.oneOf,
dgo.TiAllOf: sb.allOf,
dgo.TiAllOfValue: sb.allOfValue,
dgo.TiArray: sb.array,
dgo.TiArrayExact: sb.arrayExact,
dgo.TiBinary: sb.binary,
dgo.TiBinaryExact: sb.binaryExact,
dgo.TiBooleanExact: sb.exactValue,
dgo.TiTuple: sb.tuple,
dgo.TiMap: sb._map,
dgo.TiMapExact: sb.mapExact,
dgo.TiMapEntryExact: sb.mapEntryExact,
dgo.TiStruct: sb._struct,
dgo.TiFloatExact: sb.exactValue,
dgo.TiFloatRange: sb.floatRange,
dgo.TiIntegerExact: sb.exactValue,
dgo.TiIntegerRange: sb.integerRange,
dgo.TiRegexpExact: sb.regexpExact,
dgo.TiTimeExact: sb.timeExact,
dgo.TiSensitive: sb.sensitive,
dgo.TiStringExact: sb.stringExact,
dgo.TiStringPattern: sb.stringPattern,
dgo.TiStringSized: sb.stringSized,
dgo.TiCiString: sb.ciString,
dgo.TiNative: sb.native,
dgo.TiNot: sb.not,
dgo.TiMeta: sb.meta,
dgo.TiFunction: sb.function,
dgo.TiErrorExact: sb.errorExact,
dgo.TiNamed: sb.named,
dgo.TiNamedExact: sb.exactValue,
}
return sb
}
func (sb *typeBuilder) joinTypes(v dgo.Iterable, s string, prio int) {
sb.joinX(v, typeAsType, s, prio)
}
func (sb *typeBuilder) joinValueTypes(v dgo.Iterable, s string, prio int) {
sb.joinX(v, valueAsType, s, prio)
}
func (sb *typeBuilder) joinX(v dgo.Iterable, tc func(dgo.Value) dgo.Type, s string, prio int) {
first := true
v.Each(func(v dgo.Value) {
if first {
first = false
} else {
util.WriteString(sb, s)
}
sb.buildTypeString(tc(v), prio)
})
}
func (sb *typeBuilder) joinStructMapEntries(v dgo.StructMapType) {
first := true
v.Each(func(e dgo.StructMapEntry) {
if first {
first = false
} else {
util.WriteByte(sb, ',')
}
sb.buildTypeString(e.Key().(dgo.Type), commaPrio)
if !e.Required() {
util.WriteByte(sb, '?')
}
util.WriteByte(sb, ':')
sb.buildTypeString(e.Value().(dgo.Type), commaPrio)
})
}
func (sb *typeBuilder) writeSizeBoundaries(min, max int64) {
util.WriteString(sb, strconv.FormatInt(min, 10))
if max != math.MaxInt64 {
util.WriteByte(sb, ',')
util.WriteString(sb, strconv.FormatInt(max, 10))
}
}
func (sb *typeBuilder) writeIntRange(min, max int64, inclusive bool) {
if min != math.MinInt64 {
util.WriteString(sb, strconv.FormatInt(min, 10))
}
op := `...`
if inclusive {
op = `..`
}
util.WriteString(sb, op)
if max != math.MaxInt64 {
util.WriteString(sb, strconv.FormatInt(max, 10))
}
}
func (sb *typeBuilder) writeFloatRange(min, max float64, inclusive bool) {
if min != -math.MaxFloat64 {
util.WriteString(sb, util.Ftoa(min))
}
op := `...`
if inclusive {
op = `..`
}
util.WriteString(sb, op)
if max != math.MaxFloat64 {
util.WriteString(sb, util.Ftoa(max))
}
}
func (sb *typeBuilder) writeTupleArgs(tt dgo.TupleType, leftSep, rightSep byte) {
es := tt.ElementTypes()
if tt.Variadic() {
n := es.Len() - 1
sep := leftSep
for i := 0; i < n; i++ {
util.WriteByte(sb, sep)
sep = ','
sb.buildTypeString(es.Get(i).(dgo.Type), commaPrio)
}
util.WriteByte(sb, sep)
util.WriteString(sb, `...`)
sb.buildTypeString(es.Get(n).(dgo.Type), commaPrio)
util.WriteByte(sb, rightSep)
} else {
util.WriteByte(sb, leftSep)
sb.joinTypes(es, `,`, commaPrio)
util.WriteByte(sb, rightSep)
}
}
func (sb *typeBuilder) writeTernary(typ dgo.Type, tc func(dgo.Value) dgo.Type, prio int, op string, opPrio int) {
if prio >= orPrio {
util.WriteByte(sb, '(')
}
sb.joinX(typ.(dgo.TernaryType).Operands(), tc, op, opPrio)
if prio >= orPrio {
util.WriteByte(sb, ')')
}
}
func (sb *typeBuilder) buildTypeString(typ dgo.Type, prio int) {
if tn := sb.aliasMap.GetName(typ); tn != nil {
util.WriteString(sb, tn.GoString())
return
}
ti := typ.TypeIdentifier()
if f, ok := sb.complexTypes[ti]; ok {
if util.RecursionHit(sb.seen, typ) {
util.WriteString(sb, `<recursive self reference to `)
util.WriteString(sb, ti.String())
util.WriteString(sb, ` type>`)
return
}
os := sb.seen
sb.seen = append(sb.seen, typ)
f(typ, prio)
sb.seen = os
} else {
util.WriteString(sb, ti.String())
}
}
func typeAsType(v dgo.Value) dgo.Type {
return v.(dgo.Type)
}
func valueAsType(v dgo.Value) dgo.Type {
return v.Type()
}
// The use of an init() function is motivated by the internal package's need to call the TypeString function
// and the stringer package's need to use the internal package. The only way to break that dependency would be
// to merge the two packages. There's however no way to use the internal package without the stringer package
// being initialized first so the circularity between them is harmless.
func init() {
internal.TypeString = TypeString
}
| 26.83105 | 113 | 0.670354 |
01340c0ff99ea90e8daba41a27f63a06397459fe | 1,448 | sql | SQL | corehq/warehouse/transforms/sql/form_fact.sql | kkrampa/commcare-hq | d64d7cad98b240325ad669ccc7effb07721b4d44 | [
"BSD-3-Clause"
] | 1 | 2020-05-05T13:10:01.000Z | 2020-05-05T13:10:01.000Z | corehq/warehouse/transforms/sql/form_fact.sql | kkrampa/commcare-hq | d64d7cad98b240325ad669ccc7effb07721b4d44 | [
"BSD-3-Clause"
] | 1 | 2019-12-09T14:00:14.000Z | 2019-12-09T14:00:14.000Z | corehq/warehouse/transforms/sql/form_fact.sql | MaciejChoromanski/commcare-hq | fd7f65362d56d73b75a2c20d2afeabbc70876867 | [
"BSD-3-Clause"
] | 5 | 2015-11-30T13:12:45.000Z | 2019-07-01T19:27:07.000Z | INSERT INTO {{ form_fact }} (
form_id,
domain,
domain_dim_id,
app_id,
xmlns,
user_id,
user_dim_id,
received_on,
deleted_on,
edited_on,
build_id,
state,
last_modified,
batch_id,
time_end,
time_start,
commcare_version,
app_version
)
SELECT
form_id,
domain_table.domain,
domain_table.id,
app_id,
xmlns,
user_table.user_id,
user_table.id,
received_on,
deleted_on,
edited_on,
build_id,
state,
GREATEST(received_on, deleted_on, edited_on) AT TIME ZONE default_timezone,
'{{ batch_id }}',
time_end,
time_start,
commcare_version,
app_version
FROM
{{ form_staging }} AS form_table
JOIN {{ domain_dim }} AS domain_table ON form_table.domain = domain_table.domain
-- Allow forms to be inserted that do not have users in the UserDim
LEFT OUTER JOIN {{ user_dim }} AS user_table ON form_table.user_id = user_table.user_id
ON CONFLICT (form_id) DO UPDATE
SET domain = EXCLUDED.domain,
domain_dim_id = EXCLUDED.domain_dim_id,
app_id = EXCLUDED.app_id,
xmlns = EXCLUDED.xmlns,
user_id = EXCLUDED.user_id,
user_dim_id = EXCLUDED.user_dim_id,
received_on = EXCLUDED.received_on,
deleted_on = EXCLUDED.deleted_on,
edited_on = EXCLUDED.edited_on,
build_id = EXCLUDED.build_id,
state = EXCLUDED.state,
last_modified = EXCLUDED.last_modified,
batch_id = EXCLUDED.batch_id;
| 24.542373 | 87 | 0.688536 |
64431f9669d3489afa834ce7abed1f2c6d512729 | 369 | py | Python | backend/tv_show/migrations/0003_rename_description_tvshow_footer.py | sysopmatt/py-schedule | c087b6e5ca162481394de0d5e8c7b41a74092f99 | [
"MIT"
] | null | null | null | backend/tv_show/migrations/0003_rename_description_tvshow_footer.py | sysopmatt/py-schedule | c087b6e5ca162481394de0d5e8c7b41a74092f99 | [
"MIT"
] | null | null | null | backend/tv_show/migrations/0003_rename_description_tvshow_footer.py | sysopmatt/py-schedule | c087b6e5ca162481394de0d5e8c7b41a74092f99 | [
"MIT"
] | null | null | null | # Generated by Django 3.2.10 on 2021-12-13 02:00
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tv_show', '0002_auto_20211213_0156'),
]
operations = [
migrations.RenameField(
model_name='tvshow',
old_name='description',
new_name='footer',
),
]
| 19.421053 | 48 | 0.590786 |
dfaff813cc60f715396e05830e24ab1505f785cd | 254 | asm | Assembly | libsrc/_DEVELOPMENT/target/yaz180/driver/time/c/sccz80/clock_getres_callee.asm | Frodevan/z88dk | f27af9fe840ff995c63c80a73673ba7ee33fffac | [
"ClArtistic"
] | 640 | 2017-01-14T23:33:45.000Z | 2022-03-30T11:28:42.000Z | libsrc/_DEVELOPMENT/target/yaz180/driver/time/c/sccz80/clock_getres_callee.asm | Frodevan/z88dk | f27af9fe840ff995c63c80a73673ba7ee33fffac | [
"ClArtistic"
] | 1,600 | 2017-01-15T16:12:02.000Z | 2022-03-31T12:11:12.000Z | libsrc/_DEVELOPMENT/target/yaz180/driver/time/c/sccz80/clock_getres_callee.asm | Frodevan/z88dk | f27af9fe840ff995c63c80a73673ba7ee33fffac | [
"ClArtistic"
] | 215 | 2017-01-17T10:43:03.000Z | 2022-03-23T17:25:02.000Z | SECTION code_driver
PUBLIC clock_getres_callee
EXTERN asm_clock_getres
; get the the system time resolution
.clock_getres_callee
pop af
pop hl
pop bc ; ignore the enum clock_id
push af
jp asm_clock_getres
| 16.933333 | 62 | 0.681102 |
e158463ceb87581f76ffc7c6d4a2ef6f176ee59b | 1,174 | go | Go | goroutines/State.go | wsabc/GoByExamples | 43b54c787b6020714ac6b138cbfa0010055b0369 | [
"BSD-3-Clause"
] | null | null | null | goroutines/State.go | wsabc/GoByExamples | 43b54c787b6020714ac6b138cbfa0010055b0369 | [
"BSD-3-Clause"
] | null | null | null | goroutines/State.go | wsabc/GoByExamples | 43b54c787b6020714ac6b138cbfa0010055b0369 | [
"BSD-3-Clause"
] | null | null | null | package main
import (
"fmt"
"math/rand"
"sync"
"sync/atomic"
"time"
)
func main() {
// atomic counter
var ops uint64
for i := 0; i < 50; i++ {
go func() {
for {
atomic.AddUint64(&ops, 1)
time.Sleep(time.Millisecond)
}
}()
}
time.Sleep(time.Second)
opsFinal := atomic.LoadUint64(&ops)
fmt.Println("ops final", opsFinal)
var state = make(map[int]int)
// same as java
var mutex = &sync.Mutex{}
var rOps uint64
var wOps uint64
for r := 0; r < 100; r++ {
go func() {
total := 0
for {
key := rand.Intn(5)
mutex.Lock()
total += state[key]
mutex.Unlock()
atomic.AddUint64(&rOps, 1)
time.Sleep(time.Millisecond)
}
}()
}
for w := 0; w < 10; w++ {
go func() {
for {
key := rand.Intn(5)
val := rand.Intn(100)
mutex.Lock()
state[key] = val
mutex.Unlock()
atomic.AddUint64(&wOps, 1)
time.Sleep(time.Millisecond)
}
}()
}
time.Sleep(time.Second)
rOpsFinal := atomic.LoadUint64(&rOps)
wOpsFinal := atomic.LoadUint64(&wOps)
fmt.Println("read state", rOpsFinal)
fmt.Println("write state", wOpsFinal)
mutex.Lock()
fmt.Println("state", state)
mutex.Unlock()
}
| 15.447368 | 38 | 0.59029 |
b0cc4349e7a5fb47d2c20b5a65e3109ce43dcdea | 317 | py | Python | src/skip.py | timm/duo | b05025d21abb26c9d56050efe7a9aa30796d02e1 | [
"Unlicense"
] | null | null | null | src/skip.py | timm/duo | b05025d21abb26c9d56050efe7a9aa30796d02e1 | [
"Unlicense"
] | null | null | null | src/skip.py | timm/duo | b05025d21abb26c9d56050efe7a9aa30796d02e1 | [
"Unlicense"
] | null | null | null | # vim: filetype=python ts=2 sw=2 sts=2 et :
# (c) 2021, tim menzies ([email protected]) unlicense.org
"""Columns that we will not summarize."""
from col import Col
class Skip(Col):
def __init__(i,**kw): super().__init__(**kw)
def add1(i,x,n=1) : return x
def mid(i): return "?"
def spread(i): return "?"
| 24.384615 | 53 | 0.630915 |
f6efb66a565d5467d48ecbfb13c7539335027032 | 865 | sh | Shell | examples/pxScene2d/external/libnode-v6.9.0/tools/make-v8.sh | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 46 | 2017-09-07T14:59:22.000Z | 2020-10-31T20:34:12.000Z | examples/pxScene2d/external/libnode-v6.9.0/tools/make-v8.sh | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,432 | 2017-06-21T04:08:48.000Z | 2020-08-25T16:21:15.000Z | examples/pxScene2d/external/libnode-v6.9.0/tools/make-v8.sh | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 317 | 2017-06-20T19:57:17.000Z | 2020-09-16T10:28:30.000Z | #!/bin/bash
git_origin=$(git config --get remote.origin.url | sed 's/.\+[\/:]\([^\/]\+\/[^\/]\+\)$/\1/')
git_branch=$(git rev-parse --abbrev-ref HEAD)
v8ver=${1:-v8} #default v8
svn_prefix=https://github.com
svn_path="$svn_prefix/$git_origin/branches/$git_branch/deps/$v8ver"
#svn_path="$git_origin/branches/$git_branch/deps/$v8ver"
gclient_string="solutions = [{'name': 'v8', 'url': '$svn_path', 'managed': False}]"
# clean up if someone presses ctrl-c
trap cleanup INT
function cleanup() {
trap - INT
rm .gclient || true
rm .gclient_entries || true
rm -rf _bad_scm/ || true
#if v8ver isn't v8, move the v8 folders
#back to what they were
if [ "$v8ver" != "v8" ]; then
mv v8 $v8ver
mv .v8old v8
fi
exit 0
}
cd deps
echo $gclient_string > .gclient
if [ "$v8ver" != "v8" ]; then
mv v8 .v8old
mv $v8ver v8
fi
gclient sync
cleanup
| 22.179487 | 92 | 0.643931 |
850211ad8cc5ff82c60dc9723c1f8b7574ab0e04 | 1,213 | cs | C# | Tracker/Tools.cs | ddieffen/YellowBrickV6Plotter | ee29e0eda6c3b0d878312a1292c738b283074191 | [
"MIT"
] | null | null | null | Tracker/Tools.cs | ddieffen/YellowBrickV6Plotter | ee29e0eda6c3b0d878312a1292c738b283074191 | [
"MIT"
] | null | null | null | Tracker/Tools.cs | ddieffen/YellowBrickV6Plotter | ee29e0eda6c3b0d878312a1292c738b283074191 | [
"MIT"
] | null | null | null | using System.Xml;
using System.Drawing;
namespace Tracker
{
public static class Tools
{
public static XmlAttribute CreateAttr(this XmlDocument xmlDoc, string name, object value)
{
XmlAttribute attribute = xmlDoc.CreateAttribute(name);
if (value == null)
attribute.Value = "";
else
attribute.Value = value.ToString();
return attribute;
}
public static XmlNode CreateNode(this XmlDocument xmlDoc, string name, params XmlNode[] children)
{
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, xmlDoc.NamespaceURI);
foreach (XmlNode child in children)
{
if (child is XmlAttribute)
node.Attributes.Append(child as XmlAttribute);
else
node.AppendChild(child);
}
return node;
}
const int RGBMAX = 255;
public static Color InvertMeAColour(Color ColourToInvert)
{
return Color.FromArgb(RGBMAX - ColourToInvert.R,
RGBMAX - ColourToInvert.G, RGBMAX - ColourToInvert.B);
}
}
}
| 31.102564 | 105 | 0.563891 |
be8cb5b9667c7d5f659b5d226a8938109aaf66f2 | 435 | ts | TypeScript | src/common/utils/random.ts | wingsico/i-music | d6c2c1ce32778d20b4df77ddaf5b5f41cd9c8df5 | [
"MIT"
] | null | null | null | src/common/utils/random.ts | wingsico/i-music | d6c2c1ce32778d20b4df77ddaf5b5f41cd9c8df5 | [
"MIT"
] | null | null | null | src/common/utils/random.ts | wingsico/i-music | d6c2c1ce32778d20b4df77ddaf5b5f41cd9c8df5 | [
"MIT"
] | null | null | null | type Parser = (n: number, ...rest: any[]) => number;
export function nextInt(min?: number, max?: number): number {
return nextNumber(min, max, Math.floor, true);
}
export function nextNumber(min?: number, max?:number, parser?: Parser, needAdd ?: boolean) {
min = min ?? 0;
max = max ?? 1;
parser = parser ?? (n => n);
needAdd = needAdd ?? false;
return parser(Math.random() * (max - min +( needAdd ? 1 : 0)) + min);
} | 25.588235 | 92 | 0.609195 |
b8dbd023407f37bc4d6832c36d681e3f7942aeff | 5,080 | py | Python | src/simmate/toolkit/base_data_types/_to_do/lattice.py | laurenmm/simmate-1 | c06b94c46919b01cda50f78221ad14f75c100a14 | [
"BSD-3-Clause"
] | 9 | 2021-12-21T02:58:21.000Z | 2022-01-25T14:00:06.000Z | src/simmate/toolkit/base_data_types/_to_do/lattice.py | laurenmm/simmate-1 | c06b94c46919b01cda50f78221ad14f75c100a14 | [
"BSD-3-Clause"
] | 51 | 2022-01-01T15:59:58.000Z | 2022-03-26T21:25:42.000Z | src/simmate/toolkit/base_data_types/_to_do/lattice.py | laurenmm/simmate-1 | c06b94c46919b01cda50f78221ad14f75c100a14 | [
"BSD-3-Clause"
] | 7 | 2022-01-01T03:44:32.000Z | 2022-03-29T19:59:27.000Z | # -*- coding: utf-8 -*-
# OPTIMIZE: using caching improves speed significantly at the cost of memory. I
# need to see which is preferable in higher-level tests.
from functools import cached_property
import numpy
from numba import njit as numba_speedup
class Lattice:
"""
This class is for 3D crystal lattices, which are represented by a 3x3 matrix.
This class provides a bunch of tools to pull out common values like vector
lengths and angles, and also allows for lattice conversions.
For some basic formulas and introduction, see here:
http://gisaxs.com/index.php/Unit_cell
http://gisaxs.com/index.php/Lattices
"""
def __init__(self, matrix):
"""
Create a lattice from a 3x3 matrix. Each vector is defined via xyz on
one row of the matrix. For example, a cubic lattice where all vectors
are 1 Angstrom and 90deg from eachother would be defined as
matrix = [[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]
"""
# Convert the matrix to a numpy array and store it
self.matrix = numpy.array(matrix)
@cached_property
def lengths(self):
"""
Gives the lengths of the lattice as (a, b, c).
"""
# The easiest way to do this is with numpy via...
# lengths = numpy.linalg.norm(matrix, axis=1)
# However, we instead write a super-optimized numba function to make this
# method really fast. This is defined below as a static method.
# The length of a 3D vector (xyz) is defined by...
# length = sqrt(a**2 + b**2 + c**2)
# and we are doing this for all three vectors at once.
return self._lengths_fast(self.matrix)
@staticmethod
@numba_speedup(cache=True)
def _lengths_fast(matrix):
# NOTE: users should not call this method! Use lattice.lengths instead
# OPTIMIZE: is there an alternative way to write this that numba will
# run faster?
# numpy.linalg.norm(matrix, axis=1) --> doesn't work with numba
return numpy.sqrt(numpy.sum(matrix**2, axis=1))
@property
def a(self):
"""
The length of the lattice vector "a" (in Angstroms)
"""
return self.lengths[0]
@property
def b(self):
"""
The length of the lattice vector "b" (in Angstroms)
"""
return self.lengths[1]
@property
def c(self):
"""
The length of the lattice vector "c" (in Angstroms)
"""
return self.lengths[2]
@cached_property
def angles(self):
"""
The angles of the lattice as (alpha, beta, gamma).
"""
# The angle between two 3D vectors (xyz) is defined by...
# angle_radians = arccos(dot(vector1, vector2)/(vector1.length*vector2.length))
# And alpha, beta, gamma are just the angles between the b&c, a&c, and a&b
# vectors, respectively. We cacluate all of these at once here. We also
# write a super-optimized numba function to make this method really fast.
# This is defined below as a static method.
return self._angles_fast(self.matrix, self.lengths)
@staticmethod
@numba_speedup(cache=True)
def _angles_fast(matrix, lengths):
# NOTE: users should not call this method! Use lattice.angles instead
# OPTIMIZE: is there an alternative way to write this that numba will
# run faster?
# keep a list of the angles
angles = []
# this establishes the three angles we want to calculate
# alpha --> angle between b and c
# beta --> angle between a and c
# gamma --> angle between a and b
# So the numbers below are indexes of the matrix!
# (for example, vector b has index 1)
vector_pairs = [(1, 2), (0, 2), (0, 1)]
# The angle between two 3D vectors (xyz) is defined by...
# angle_radians = arccos(dot(vector1, vector2)/(vector1.length*vector2.length))
for vector_index_1, vector_index_2 in vector_pairs:
# calculate single angle using formula
unit_vector_1 = matrix[vector_index_1] / lengths[vector_index_1]
unit_vector_2 = matrix[vector_index_2] / lengths[vector_index_2]
dot_product = numpy.dot(unit_vector_1, unit_vector_2)
angle = numpy.arccos(dot_product)
# convert to degrees before saving
angles.append(numpy.degrees(angle))
# return the list as a numpy array
return numpy.array(angles)
@property
def alpha(self):
"""
The angle between the lattice vectors b and c (in degrees).
"""
return self.angles[0]
@property
def beta(self):
"""
The angle between the lattice vectors a and c (in degrees).
"""
return self.angles[1]
@property
def gamma(self):
"""
The angle between the lattice vectors a and b (in degrees).
"""
return self.angles[2]
| 34.09396 | 89 | 0.61063 |
24968791a0454d541fe5f9fb9b9d0b2f5a7b6557 | 3,127 | php | PHP | src/Driver/ArrayDriver.php | iwyg/cache | 9ee3d7350d201e191f354198b535162a887bb705 | [
"MIT"
] | null | null | null | src/Driver/ArrayDriver.php | iwyg/cache | 9ee3d7350d201e191f354198b535162a887bb705 | [
"MIT"
] | null | null | null | src/Driver/ArrayDriver.php | iwyg/cache | 9ee3d7350d201e191f354198b535162a887bb705 | [
"MIT"
] | null | null | null | <?php
/*
* This File is part of the Lucid\Cache package
*
* (c) iwyg <[email protected]>
*
* For full copyright and license information, please refer to the LICENSE file
* that was distributed with this package.
*/
namespace Lucid\Cache\Driver;
use ArrayObject;
/**
* @class ArrayDriver
* @see AbstractDriver
*
* @package Lucid\Cache
* @version $Id$
* @author iwyg <[email protected]>
*/
class ArrayDriver extends AbstractDriver
{
/**
* storage
*
* @var ArrayObject
*/
protected $storage;
/**
* persist
*
* @var bool
*/
protected $persist;
/**
* persistPath
*
* @var string
*/
protected $persistPath;
/**
* @param mixed $persist
* @param string $path
*
*/
public function __construct($persist = false, $path = '')
{
$this->persistPath = $path;
$this->persist = (bool)$persist;
$this->setUpStorage();
}
/**
* @return void
*/
public function __destruct()
{
//$this->persistStorage();
}
/**
* {@inheritdoc}
*/
public function exists($key)
{
return isset($this->storage[$key]);
}
/**
* {@inheritdoc}
*/
public function read($key)
{
if ($this->exists($key)) {
return $this->storage[$key];
}
}
/**
* {@inheritdoc}
*/
public function write($key, $data, $expires = 60, $compressed = false)
{
$this->storage[$key] = $data;
return true;
}
/**
* {@inheritdoc}
*/
public function saveForever($key, $data, $compressed = false)
{
return $this->write($key, $data, 0, $compressed);
}
/**
* {@inheritdoc}
*/
public function delete($key)
{
unset($this->storage[$key]);
}
/**
* {@inheritdoc}
*/
public function flush()
{
unset($this->storage);
$this->storage = new \ArrayObject;
$this->persistStorage();
}
/**
* {@inheritdoc}
*/
protected function incrementValue($key, $value)
{
return $this->storage[$key] = (int)$this->storage[$key] + (int)$value;
}
/**
* {@inheritdoc}
*/
protected function decrementValue($key, $value)
{
return $this->storage[$key] = (int)$this->storage[$key] - (int)$value;
}
/**
* setUpStorage
*
* @return void
*/
private function setUpStorage()
{
if ($this->persist and file_exists($this->persistPath)) {
try {
$this->storage = unserialize(file_get_contents($this->persistPath));
} catch (\Exception $e) {
$this->storage = new ArrayObject;
}
return;
}
$this->storage = new ArrayObject;
}
/**
* persistStorage
*
*
* @return mixed
*/
private function persistStorage()
{
if ($this->persist) {
file_put_contents($this->persistPath, serialize($this->storage), LOCK_EX);
}
}
}
| 18.28655 | 86 | 0.507195 |
25ac311b2a7ecdab4944c7401585693fee3a5729 | 324 | js | JavaScript | packages/fractal-charts/dist/components/QuadrantChart/Dot.js | BrandonMA/fractal | af4511de030a9b23d1a28349743eb9120ff2b91b | [
"MIT"
] | 1 | 2021-07-16T21:45:40.000Z | 2021-07-16T21:45:40.000Z | packages/fractal-charts/dist/components/QuadrantChart/Dot.js | BrandonMA/fractal | af4511de030a9b23d1a28349743eb9120ff2b91b | [
"MIT"
] | null | null | null | packages/fractal-charts/dist/components/QuadrantChart/Dot.js | BrandonMA/fractal | af4511de030a9b23d1a28349743eb9120ff2b91b | [
"MIT"
] | null | null | null | import React from 'react';
import { Layer } from '@bma98/fractal-ui';
const SIZE = 8;
export function Dot({ color, addSpacing }) {
return React.createElement(Layer, { backgroundColor: color, width: SIZE, height: SIZE, borderRadius: SIZE / 2, marginBottom: addSpacing ? 4 : undefined });
}
//# sourceMappingURL=Dot.js.map | 46.285714 | 159 | 0.716049 |
db9db9655774d48154254722c3de5078c20370b1 | 568 | php | PHP | app/Http/Controllers/Controller.php | kirstine78/EzyHirePrototype | bc852f3fef843bbe8aef15554e2164ac63056f32 | [
"MIT"
] | null | null | null | app/Http/Controllers/Controller.php | kirstine78/EzyHirePrototype | bc852f3fef843bbe8aef15554e2164ac63056f32 | [
"MIT"
] | null | null | null | app/Http/Controllers/Controller.php | kirstine78/EzyHirePrototype | bc852f3fef843bbe8aef15554e2164ac63056f32 | [
"MIT"
] | null | null | null | <?php
/**
* Student name: Kirstine Brørup Nielsen
* Student id: 100527988
* Date: 18.10.2016
* Assignment: EzyHire
* Version: Prototype
* File: Controller.php
*/
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
| 24.695652 | 62 | 0.734155 |
a1547811509f489e325e64cbfa7cbd392562433d | 1,460 | ts | TypeScript | src/stores/Rune/RuneStore.ts | mikemartincode/sw-assistant | c8cd9f25258aa85a1c98b0b7618723dcf53fe92b | [
"MIT"
] | null | null | null | src/stores/Rune/RuneStore.ts | mikemartincode/sw-assistant | c8cd9f25258aa85a1c98b0b7618723dcf53fe92b | [
"MIT"
] | null | null | null | src/stores/Rune/RuneStore.ts | mikemartincode/sw-assistant | c8cd9f25258aa85a1c98b0b7618723dcf53fe92b | [
"MIT"
] | null | null | null | import { action, observable } from "mobx";
import { persist } from "mobx-persist";
import { IRootStore } from "..";
//import { UnitList } from "../types";
import CalcModel from "./CalcModel";
class RuneList {
rootStore: IRootStore;
constructor(rootStore: IRootStore) {
this.rootStore = rootStore;
}
@persist("object")
@observable
Runes: CalcModel[] = [];
@action.bound
parseJson = (fileName: string) => {
// empty Runes before starting
this.Runes = [];
debugger;
const file = require("../../Utils/test.json");
const unitList = file.unit_list;
console.log(unitList);
unitList.map(k => {
console.log(k);
});
// Object.values(unitList).map((k: UnitList) => {
// }
// if (k.runes.length > 0) {
// k.runes.map(a => {
// // Create instance of class CalcModel
// const calc = new CalcModel(
// a,
// this.rootStore.config,
// this.rootStore.debug("CalcModel")
// );
// // Add rune to the observable array Runes
// this.Runes.push(calc);
// });
// }
// });
// const runeList = file.runes;
// Object.values(runeList).map((x: IUnparsedRune) => {
// const calc = new CalcModel(
// x,
// this.rootStore.config,
// this.rootStore.debug("CalcModel")
// );
// this.Runes.push(calc);
// });
// )
};
}
export default RuneList;
| 25.614035 | 58 | 0.541096 |
c8da1ec5fc9c6c258b76e12451c155642537c1e7 | 12,806 | lua | Lua | volume/data/npc/scripts/Gregor.lua | patsadow2/Tibia | b3aebbc5aea78cc2a238584c767c5c7315bab4dd | [
"MIT"
] | 2 | 2018-10-30T19:19:27.000Z | 2019-04-05T08:18:11.000Z | volume/data/npc/scripts/Gregor.lua | patsadow2/Tibia | b3aebbc5aea78cc2a238584c767c5c7315bab4dd | [
"MIT"
] | 1 | 2019-04-05T18:53:52.000Z | 2019-04-10T10:53:04.000Z | volume/data/npc/scripts/Gregor.lua | patsadow2/Tibia | b3aebbc5aea78cc2a238584c767c5c7315bab4dd | [
"MIT"
] | 2 | 2019-12-11T04:13:15.000Z | 2020-02-15T14:42:13.000Z | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local voices = { {text = 'Gather around me, young knights! I\'m going to teach you some spells!'} }
npcHandler:addModule(VoiceModule:new(voices))
local function creatureSayCallback(cid, type, msg)
if not npcHandler:isFocused(cid) then
return false
end
local player = Player(cid)
local addonProgress = player:getStorageValue(Storage.OutfitQuest.Knight.AddonHelmet)
if msgcontains(msg, 'task') then
if not player:isPremium() then
npcHandler:say('Sorry, but our tasks are only for premium warriors.', cid)
return true
end
if addonProgress < 1 then
npcHandler:say('You mean you would like to prove that you deserve to wear such a helmet?', cid)
npcHandler.topic[cid] = 1
elseif addonProgress == 1 then
npcHandler:say('Your current task is to bring me 100 perfect behemoth fangs, |PLAYERNAME|.', cid)
elseif addonProgress == 2 then
npcHandler:say('Your current task is to retrieve the helmet of Ramsay the Reckless from Banuta, |PLAYERNAME|.', cid)
elseif addonProgress == 3 then
npcHandler:say('Your current task is to obtain a flask of warrior\'s sweat, |PLAYERNAME|.', cid)
elseif addonProgress == 4 then
npcHandler:say('Your current task is to bring me royal steel, |PLAYERNAME|.', cid)
elseif addonProgress == 5 then
npcHandler:say('Please talk to Sam and tell him I sent you. I\'m sure he will be glad to refine your helmet, |PLAYERNAME|.', cid)
else
npcHandler:say('You\'ve already completed the task and can consider yourself a mighty warrior, |PLAYERNAME|.', cid)
end
elseif msgcontains(msg, 'behemoth fang') then
if addonProgress == 1 then
npcHandler:say('Have you really managed to fulfil the task and brought me 100 perfect behemoth fangs?', cid)
npcHandler.topic[cid] = 3
else
npcHandler:say('You\'re not serious asking that, are you? They come from behemoths, of course. Unless there are behemoth rabbits. Duh.', cid)
end
elseif msgcontains(msg, 'ramsay') then
if addonProgress == 2 then
npcHandler:say('Did you recover the helmet of Ramsay the Reckless?', cid)
npcHandler.topic[cid] = 4
else
npcHandler:say('These pesky apes steal everything they can get their dirty hands on.', cid)
end
elseif msgcontains(msg, 'sweat') then
if addonProgress == 3 then
npcHandler:say('Were you able to get hold of a flask with pure warrior\'s sweat?', cid)
npcHandler.topic[cid] = 5
else
npcHandler:say('Warrior\'s sweat can be magically extracted from headgear worn by a true warrior, but only in small amounts. Djinns are said to be good at magical extractions.', cid)
end
elseif msgcontains(msg, 'royal steel') then
if addonProgress == 4 then
npcHandler:say('Ah, have you brought the royal steel?', cid)
npcHandler.topic[cid] = 6
else
npcHandler:say('Royal steel can only be refined by very skilled smiths.', cid)
end
elseif npcHandler.topic[cid] == 1 then
if msgcontains(msg, 'yes') then
npcHandler:say({
'Well then, listen closely. First, you will have to prove that you are a fierce and restless warrior by bringing me 100 perfect behemoth fangs. ...',
'Secondly, please retrieve a helmet for us which has been lost a long time ago. The famous Ramsay the Reckless wore it when exploring an ape settlement. ...',
'Third, we need a new flask of warrior\'s sweat. We\'ve run out of it recently, but we need a small amount for the show battles in our arena. ...',
'Lastly, I will have our smith refine your helmet if you bring me royal steel, an especially noble metal. ...',
'Did you understand everything I told you and are willing to handle this task?'
}, cid)
npcHandler.topic[cid] = 2
elseif msgcontains(msg, 'no') then
npcHandler:say('Bah. Then you will have to wait for the day these helmets are sold in shops, but that will not happen before hell freezes over.', cid)
npcHandler.topic[cid] = 0
end
elseif npcHandler.topic[cid] == 2 then
if msgcontains(msg, 'yes') then
player:setStorageValue(Storage.OutfitQuest.Ref, math.max(0, player:getStorageValue(Storage.OutfitQuest.Ref)) + 1)
player:setStorageValue(Storage.OutfitQuest.Knight.AddonHelmet, 1)
player:setStorageValue(Storage.OutfitQuest.Knight.MissionHelmet, 1)
npcHandler:say('Alright then. Come back to me once you have collected 100 perfect behemoth fangs.', cid)
npcHandler.topic[cid] = 0
elseif msgcontains(msg, 'no') then
npcHandler:say('Would you like me to repeat the task requirements then?', cid)
npcHandler.topic[cid] = 1
end
elseif npcHandler.topic[cid] == 3 then
if msgcontains(msg, 'yes') then
if not player:removeItem(5893, 100) then
npcHandler:say('Lying is not exactly honourable, |PLAYERNAME|. Shame on you.', cid)
return true
end
player:setStorageValue(Storage.OutfitQuest.Knight.AddonHelmet, 2)
player:setStorageValue(Storage.OutfitQuest.Knight.MissionHelmet, 2)
player:setStorageValue(Storage.OutfitQuest.Knight.RamsaysHelmetDoor, 1)
npcHandler:say('I\'m deeply impressed, brave Knight |PLAYERNAME|. I expected nothing less from you. Now, please retrieve Ramsay\'s helmet.', cid)
elseif msgcontains(msg, 'no') then
npcHandler:say('There is no need to rush anyway.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 4 then
if msgcontains(msg, 'yes') then
if not player:removeItem(5924, 1) then
npcHandler:say('Lying is not exactly honourable, |PLAYERNAME|. Shame on you.', cid)
return true
end
player:setStorageValue(Storage.OutfitQuest.Knight.AddonHelmet, 3)
player:setStorageValue(Storage.OutfitQuest.Knight.MissionHelmet, 3)
npcHandler:say('Good work, brave Knight |PLAYERNAME|! Even though it is damaged, it has a lot of sentimental value. Now, please bring me warrior\'s sweat.', cid)
elseif msgcontains(msg, 'no') then
npcHandler:say('There is no need to rush anyway.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 5 then
if msgcontains(msg, 'yes') then
if not player:removeItem(5885, 1) then
npcHandler:say('Lying is not exactly honourable, |PLAYERNAME|. Shame on you.', cid)
return true
end
player:setStorageValue(Storage.OutfitQuest.Knight.AddonHelmet, 4)
player:setStorageValue(Storage.OutfitQuest.Knight.MissionHelmet, 4)
npcHandler:say('Now that is a pleasant surprise, brave Knight |PLAYERNAME|! There is only one task left now: Obtain royal steel to have your helmet refined.', cid)
elseif msgcontains(msg, 'no') then
npcHandler:say('There is no need to rush anyway.', cid)
end
npcHandler.topic[cid] = 0
elseif npcHandler.topic[cid] == 6 then
if msgcontains(msg, 'yes') then
if not player:removeItem(5887, 1) then
npcHandler:say('Lying is not exactly honourable, |PLAYERNAME|. Shame on you.', cid)
return true
end
player:setStorageValue(Storage.OutfitQuest.Knight.AddonHelmet, 5)
player:setStorageValue(Storage.OutfitQuest.Knight.MissionHelmet, 5)
npcHandler:say('You truly deserve to wear an adorned helmet, brave Knight |PLAYERNAME|. Please talk to Sam and tell him I sent you. I\'m sure he will be glad to refine your helmet.', cid)
elseif msgcontains(msg, 'no') then
npcHandler:say('There is no need to rush anyway.', cid)
end
npcHandler.topic[cid] = 0
end
return true
end
keywordHandler:addSpellKeyword({'find', 'person'}, {npcHandler = npcHandler, spellName = 'Find Person', price = 80, level = 8, vocation = 4})
keywordHandler:addSpellKeyword({'light'}, {npcHandler = npcHandler, spellName = 'Light', price = 0, level = 8, vocation = 4})
keywordHandler:addSpellKeyword({'cure', 'poison'}, {npcHandler = npcHandler, spellName = 'Cure Poison', price = 150, level = 10, vocation = 4})
keywordHandler:addSpellKeyword({'wound', 'cleansing'}, {npcHandler = npcHandler, spellName = 'Wound Cleansing', price = 0, level = 8, vocation = 4})
keywordHandler:addSpellKeyword({'great', 'light'}, {npcHandler = npcHandler, spellName = 'Great Light', price = 500, level = 13, vocation = 4})
keywordHandler:addKeyword({'healing', 'spells'}, StdModule.say, {npcHandler = npcHandler, text = "In this category I have '{Wound Cleansing}' and '{Cure Poison}'."})
keywordHandler:addKeyword({'support', 'spells'}, StdModule.say, {npcHandler = npcHandler, text = "In this category I have '{Light}', '{Find Person}' and '{Great Light}'."})
keywordHandler:addKeyword({'spells'}, StdModule.say, {npcHandler = npcHandler, text = 'I can teach you {healing spells} and {support spells}. What kind of spell do you wish to learn? You can also tell me for which level you would like to learn a spell, if you prefer that.'})
keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = "I am the first knight. I trained some of the greatest heroes of Tibia."})
keywordHandler:addKeyword({'heroes'}, StdModule.say, {npcHandler = npcHandler, text = "Of course, you heard of them. Knights are the best fighters in Tibia."})
keywordHandler:addKeyword({'king'}, StdModule.say, {npcHandler = npcHandler, text = "Hail to our King!"})
keywordHandler:addKeyword({'name'}, StdModule.say, {npcHandler = npcHandler, text = "You are joking, eh? Of course, you know me. I am Gregor, the first knight."})
keywordHandler:addKeyword({'gregor'}, StdModule.say, {npcHandler = npcHandler, text = "A great name, isn't it?"})
keywordHandler:addKeyword({'tibia'}, StdModule.say, {npcHandler = npcHandler, text = "Beautiful Tibia. And with our help everyone is save."})
keywordHandler:addKeyword({'time'}, StdModule.say, {npcHandler = npcHandler, text = "It is time to join the Knights!"})
keywordHandler:addKeyword({'knights'}, StdModule.say, {npcHandler = npcHandler, text = "Knights are the warriors of Tibia. Without us, no one would be safe. Every brave and strong man or woman can join us."})
keywordHandler:addKeyword({'bozo'}, StdModule.say, {npcHandler = npcHandler, text = "Some day someone will make something happen to him..."})
keywordHandler:addKeyword({'elane'}, StdModule.say, {npcHandler = npcHandler, text = "A bow might be a fine weapon for someone not strong enough to wield a REAL weapon."})
keywordHandler:addKeyword({'frodo'}, StdModule.say, {npcHandler = npcHandler, text = "I and my students often share a cask of beer or wine at Frodo's hut."})
keywordHandler:addKeyword({'gorn'}, StdModule.say, {npcHandler = npcHandler, text = "Always concerned with his profit. What a loss! He was adventuring with baxter in the old days."})
keywordHandler:addKeyword({'baxter'}, StdModule.say, {npcHandler = npcHandler, text = "He was an adventurer once."})
keywordHandler:addKeyword({'lynda'}, StdModule.say, {npcHandler = npcHandler, text = "Before she became a priest she won the Miss Tibia contest three times in a row."})
keywordHandler:addKeyword({'mcronald'}, StdModule.say, {npcHandler = npcHandler, text = "Peaceful farmers."})
keywordHandler:addKeyword({'ferumbras'}, StdModule.say, {npcHandler = npcHandler, text = "A fine game to hunt. But be careful, he cheats!"})
keywordHandler:addKeyword({'muriel'}, StdModule.say, {npcHandler = npcHandler, text = "Bah, go away with these sorcerer tricks. Only cowards use tricks."})
keywordHandler:addKeyword({'oswald'}, StdModule.say, {npcHandler = npcHandler, text = "What an idiot."})
keywordHandler:addKeyword({'quentin'}, StdModule.say, {npcHandler = npcHandler, text = "I will never understand this peaceful monks and priests."})
keywordHandler:addKeyword({'sam'}, StdModule.say, {npcHandler = npcHandler, text = "He has the muscles, but lacks the guts."})
keywordHandler:addKeyword({'tibianus'}, StdModule.say, {npcHandler = npcHandler, text = "Hail to our King!"})
keywordHandler:addKeyword({'outfit'}, StdModule.say, {npcHandler = npcHandler, text = "Only the bravest warriors may wear adorned helmets. They are traditionally awarded after having completed a difficult task for our guild."})
keywordHandler:addKeyword({'helmet'}, StdModule.say, {npcHandler = npcHandler, text = "Only the bravest warriors may wear adorned helmets. They are traditionally awarded after having completed a difficult task for our guild."})
npcHandler:setMessage(MESSAGE_GREET, "Greetings, |PLAYERNAME|. What do you want?")
npcHandler:setMessage(MESSAGE_FAREWELL, "Be careful on your journeys.")
npcHandler:setMessage(MESSAGE_WALKAWAY, "Be careful on your journeys.")
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
| 62.165049 | 275 | 0.741527 |
2d1f98140355af94595dd87cc3c7197265408bf3 | 5,198 | css | CSS | public/css/page/home.css | umntv-dev/gen8 | dfc6921646a83b2580299f464d0087948fcf3ae2 | [
"MIT"
] | null | null | null | public/css/page/home.css | umntv-dev/gen8 | dfc6921646a83b2580299f464d0087948fcf3ae2 | [
"MIT"
] | null | null | null | public/css/page/home.css | umntv-dev/gen8 | dfc6921646a83b2580299f464d0087948fcf3ae2 | [
"MIT"
] | null | null | null | :root {
--swiper-navigation-color: white;
}
.sec1{
min-height: 100vh;
display: flex;
border-radius: 0 0 51px 51px;;
background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.29) 100%);
filter: drop-shadow(0px 11px 18px rgba(0, 0, 0, 0.25));
}
.mySwiper{
width: 100%;
height: 100%;
}
.mySwiper2{
width: 100%;
padding-top: 50px;
padding-bottom: 50px;
}
.swiper-slide .row{
width: 90%;
}
.s1 {
text-align: center;
font-size: 18px;
/* Center slide text vertically */
display: -webkit-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-box-pack: center;
-ms-flex-pack: center;
-webkit-justify-content: center;
justify-content: center;
-webkit-box-align: center;
-ms-flex-align: center;
-webkit-align-items: center;
align-items: center;
}
.s1 img{
max-width: 500px;
}
.s2{
background-position: center;
background-size: cover;
width: 300px;
height: 300px;
}
.s2 img {
display: block;
width: 100%;
}
.img-program{
min-width: 100%;
}
.title-program{
color: white;
font-weight: 800;
text-align: left;
/* width: 150%; */
font-size: 5rem;
/* margin-left: 2.5rem; */
}
.detail-program{
color: white;
text-align: left;
font-size: 1.5rem;
padding-right: 1.2rem;
margin-bottom: 1rem;
}
.btn{
background-color: none;
border: 1px solid white;
box-sizing: border-box;
border-radius: 47px;
min-width: 244px;
font-size: 1.7rem;
color: white;
margin: 1rem 1rem 0 0;
}
.btn a{
color: #fff;
text-decoration: none;
}
.btn a:hover{
background-color: white;
color: black;
}
.btn:hover{
background-color: white;
color: none;
}
p{
margin: 0;
}
.title h1{
color: white;
font-size: 4rem;
padding-top: 3rem;
}
hr{
color: white;
height: 1rem;
opacity: 1;
}
@media (max-width:1400px){
.title-program{
font-size: 4rem;
}
.detail-program{
font-size: 1.3rem;
}
.img-program{
max-width: 80%;
}
.btn{
min-width: 230px;
}
}
@media (max-width:990px){
.title-program{
text-align: center;
}
.detail-program{
text-align: center;
}
.btn-program{
text-align: center;
}
}
@media (max-width:500px){
.title-program{
font-size: 3rem;
text-align: center;
}
.detail-program{
font-size: 1rem;
text-align: center;
}
.img-program{
max-width: 70%;
}
.btn{
min-width: 220px;
font-size: 1.5rem;
}
.btn-program{
text-align: center;
}
}
/* hover */
figure.hover-img {
color: #fff;
position: relative;
overflow: hidden;
margin: 10px;
width: 100%;
text-align: left;
}
figure.hover-img * {
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
figure.hover-img img {
max-width: 100%;
opacity: 1;
width: 100%;
-webkit-transition: opacity 0.35s;
transition: opacity 0.35s;
}
figure.hover-img figcaption {
position: absolute;
bottom: 0;
left: 0;
padding: 30px 3em;
width: 100%;
height: 100%;
}
figure.hover-img figcaption::before {
position: absolute;
top: 30px;
right: 30px;
bottom: 30px;
left: 100%;
border-left: 4px solid rgba(255, 255, 255, 0.8);
content: '';
opacity: 0;
background-color: rgba(255, 255, 255, 0.5);
-webkit-transition: all 0.5s;
transition: all 0.5s;
-webkit-transition-delay: 0.6s;
transition-delay: 0.6s;
}
figure.hover-img h2,
figure.hover-img p {
margin: 0 0 5px;
opacity: 0;
-webkit-transition: opacity 0.35s, -webkit-transform 0.35s;
transition: opacity 0.35s,-webkit-transform 0.35s,-moz-transform 0.35s,-o-transform 0.35s,transform 0.35s;
}
figure.hover-img h2 {
word-spacing: -0.15em;
font-weight: 300;
text-transform: uppercase;
-webkit-transform: translate3d(30%, 0%, 0);
transform: translate3d(30%, 0%, 0);
-webkit-transition-delay: 0.3s;
transition-delay: 0.3s;
font-weight: 800;
}
figure.hover-img p {
font-weight: 500;
-webkit-transform: translate3d(0%, 30%, 0);
transform: translate3d(0%, 30%, 0);
-webkit-transition-delay: 0s;
transition-delay: 0s;
}
figure.hover-img:hover img {
opacity: 0.2;
}
figure.hover-img:hover figcaption h2 {
opacity: 1;
-webkit-transform: translate3d(0%, 0%, 0);
transform: translate3d(0%, 0%, 0);
-webkit-transition-delay: 0.4s;
transition-delay: 0.4s;
}
figure.hover-img:hover figcaption p {
opacity: 0.9;
-webkit-transform: translate3d(0%, 0%, 0);
transform: translate3d(0%, 0%, 0);
-webkit-transition-delay: 0.6s;
transition-delay: 0.6s;
}
figure.hover-img:hover figcaption::before {
background: rgba(255, 255, 255, 0);
left: 30px;
opacity: 1;
-webkit-transition-delay: 0s;
transition-delay: 0s;
}
| 19.251852 | 110 | 0.572143 |
b8d64f0d046b77099499920bf86d1f4dc5c5e73e | 826 | sql | SQL | db/schema.sql | dagreatcode/barbara-api | 55dcc0a77829a1ad73457c444ee7f8527b0db32f | [
"MIT"
] | 1 | 2021-04-06T04:07:09.000Z | 2021-04-06T04:07:09.000Z | db/schema.sql | dagreatcode/barbara-api | 55dcc0a77829a1ad73457c444ee7f8527b0db32f | [
"MIT"
] | null | null | null | db/schema.sql | dagreatcode/barbara-api | 55dcc0a77829a1ad73457c444ee7f8527b0db32f | [
"MIT"
] | null | null | null | DROP DATABASE retroluxe_db;
CREATE DATABASE retroluxe_db;
USE retroluxe_db;
USE `rl3zojbpssol3ahj`;
-- Create the table actors.
-- Create the table actors.
CREATE TABLE `poohmadeit` (
`id` INT AUTO_INCREMENT,
`name` VARCHAR (30) NOT NULL,
`bin_location` INT NOT NULL,
`description` VARCHAR (60) NOT NULL,
`img` LONGBLOB,
`created_at` DATETIME NOT NULL,
PRIMARY KEY(`id`)
);
CREATE TABLE retroluxe (
id int AUTO_INCREMENT,
name varchar(30) NOT NULL,
bin_location int NOT NULL,
description varchar(60) NOT NULL,
img LONGBLOB,
timestamp int,
PRIMARY KEY(id)
);
CREATE TABLE poohmadeit (
id int AUTO_INCREMENT,
name varchar(30) NOT NULL,
bin_location int NOT NULL,
description varchar(60) NOT NULL,
img LONGBLOB,
PRIMARY KEY(id)
);
select
*
from
retroluxe;
select
*
from
poohmadeit; | 20.65 | 38 | 0.720339 |
4951f4dd0bb9dd7897a5719b630e1ba4c44100e2 | 2,168 | py | Python | Lib/site-packages/mysqlx/dbdoc.py | jmsnur/mytaxi-test | eb7f70d0ac1c4df32aaebaab118a25c83683ce13 | [
"bzip2-1.0.6"
] | 7 | 2022-03-10T07:03:14.000Z | 2022-03-24T09:42:46.000Z | Lib/site-packages/mysqlx/dbdoc.py | jmsnur/mytaxi-test | eb7f70d0ac1c4df32aaebaab118a25c83683ce13 | [
"bzip2-1.0.6"
] | 7 | 2019-12-04T22:51:59.000Z | 2022-02-10T08:28:35.000Z | Lib/site-packages/mysqlx/dbdoc.py | jmsnur/mytaxi-test | eb7f70d0ac1c4df32aaebaab118a25c83683ce13 | [
"bzip2-1.0.6"
] | 3 | 2020-07-22T23:41:29.000Z | 2020-09-02T16:40:32.000Z | # MySQL Connector/Python - MySQL driver written in Python.
# Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
# MySQL Connector/Python is licensed under the terms of the GPLv2
# <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
# MySQL Connectors. There are special exceptions to the terms and
# conditions of the GPLv2 as it is applied to this software, see the
# FOSS License Exception
# <http://www.mysql.com/about/legal/licensing/foss-exception.html>.
#
# 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.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
"""Implementation of the DbDoc."""
import json
import uuid
from .compat import STRING_TYPES
class DbDoc(object):
"""Represents a generic document in JSON format.
Args:
value (object): The value can be a JSON string or a dict.
Raises:
ValueError: If ``value`` type is not a basestring or dict.
"""
def __init__(self, value):
# TODO: Handle exceptions. What happens if it doesn't load properly?
if isinstance(value, dict):
self.__dict__ = value
elif isinstance(value, STRING_TYPES):
self.__dict__ = json.loads(value)
else:
raise ValueError("Unable to handle type: {0}".format(type(value)))
def __getitem__(self, index):
return self.__dict__[index]
def keys(self):
return self.__dict__.keys()
def ensure_id(self):
if "_id" not in self.__dict__:
self.__dict__["_id"] = uuid.uuid4().hex
return self.__dict__["_id"]
def __str__(self):
return json.dumps(self.__dict__)
| 34.412698 | 78 | 0.697417 |
d64fcc3ada5c859c37272f4cee51963ed22d86d8 | 493 | cs | C# | SummonerNameChecker/Models/Dto/SummonerDto.cs | GeorgeGee/league-summoner-name-checker | c11bb16c3046088a89c5199416a9a2d3d91e7c9c | [
"MIT"
] | 6 | 2019-05-28T06:20:10.000Z | 2022-01-22T02:45:03.000Z | SummonerNameChecker/Models/Dto/SummonerDto.cs | GeorgeGee/league-summoner-name-checker | c11bb16c3046088a89c5199416a9a2d3d91e7c9c | [
"MIT"
] | 2 | 2020-07-14T00:59:02.000Z | 2022-01-07T02:42:56.000Z | SummonerNameChecker/Models/Dto/SummonerDto.cs | GeorgeGee/league-summoner-name-checker | c11bb16c3046088a89c5199416a9a2d3d91e7c9c | [
"MIT"
] | 1 | 2020-11-22T01:24:43.000Z | 2020-11-22T01:24:43.000Z | namespace SummonerNameChecker.Models.Dto
{
/// <summary>
/// Represents a Summoner returned from Riot Games API
/// </summary>
public class SummonerDto
{
public int ProfileIconId { get; set; }
public string Name { get; set; }
public string Puuid { get; set; }
public long SummonerLevel { get; set; }
public long RevisionDate { get; set; }
public string Id { get; set; }
public string AccountId { get; set; }
}
}
| 29 | 58 | 0.59432 |
795f1a71ce1722bf4c1023ff06004a2c4f8d31c8 | 4,422 | php | PHP | modules/example/models/Kpihosp.php | wirote/educate | 349746d90f8f6f73b235e59230a32a499fd5f554 | [
"BSD-3-Clause"
] | null | null | null | modules/example/models/Kpihosp.php | wirote/educate | 349746d90f8f6f73b235e59230a32a499fd5f554 | [
"BSD-3-Clause"
] | null | null | null | modules/example/models/Kpihosp.php | wirote/educate | 349746d90f8f6f73b235e59230a32a499fd5f554 | [
"BSD-3-Clause"
] | null | null | null | <?php
namespace app\modules\example\models;
use Yii;
/**
* This is the model class for table "kpihosp".
*
* @property string $chapter ชือ Chapter
* @property int $chapcode รหัส Chapter
* @property string $grp ชือ Group
* @property int $grpcode รหัส Group
* @property int $id
* @property string $Roadmap
* @property string $kpiname ชือดัชนี
* @property string $targetname เป้าหมาย
* @property string $target เป้าหมาย (ตัวเลข)
* @property int $compare เปรียบเทียบ
* @property int $multiple อัตรา
* @property string $template มี Template ?
* @property string $strategic KPI ยุทธศาสตร์ ?
* @property string $thip KPI ของ THIP ?
* @property string $hdc KPI ของ HDC ?
* @property string $pa_moph KPI ของ PA กระทรวงฯ ?
* @property string $inspec KPI ของ ตรวจราชการ ?
* @property string $servplan KPI ของ Service Plan ?
* @property string $ssj KPI ของ สสจ.กาญจนบุรี ?
* @property string $y157 ตัวตั้ง ปี 2557
* @property string $y257 ตัวหาร ปี 2557
* @property string $y158 ตัวตั้ง ปี 2558
* @property string $y258 ตัวหาร ปี 2558
* @property string $y159 ตัวตั้ง ปี 2559
* @property string $y259 ตัวหาร ปี 2559
* @property string $y160 ตัวตั้ง ปี 2560
* @property string $y260 ตัวหาร ปี 2560
* @property string $y161 ตัวตั้ง ปี 2561
* @property string $y261 ตัวหาร ปี 2561
* @property string $y162 ตัวตั้ง ปี 2562
* @property string $y262 ตัวหาร ปี 2562
* @property string $y163 ตัวตั้ง ปี 2563
* @property string $y263 ตัวหาร ปี 2563
* @property string $y164 ตัวตั้ง ปี 2564
* @property string $y264 ตัวหาร ปี 2564
* @property string $y165 ตัวตั้ง ปี 2565
* @property string $y265 ตัวหาร ปี 2565
* @property string $owner เจ้าภาพ
* @property string $source แหล่งมา
* @property string $used ใช้งาน KPI นี้ ?
* @property string $remark หมายเหตุ
*/
class Kpihosp extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'kpihosp';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['chapcode', 'grpcode', 'id', 'compare', 'multiple'], 'integer'],
[['id'], 'required'],
[['target', 'y157', 'y257', 'y158', 'y258', 'y159', 'y259', 'y160', 'y260', 'y161', 'y261', 'y162', 'y262', 'y163', 'y263', 'y164', 'y264', 'y165', 'y265'], 'number'],
[['template', 'strategic', 'thip', 'hdc', 'pa_moph', 'inspec', 'servplan', 'ssj', 'used', 'remark'], 'string'],
[['chapter', 'grp', 'Roadmap', 'kpiname', 'targetname', 'owner', 'source'], 'string', 'max' => 255],
[['id'], 'unique'],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'chapter' => 'ชือ Chapter',
'chapcode' => 'รหัส Chapter',
'grp' => 'ชือ Group',
'grpcode' => 'รหัส Group',
'id' => 'ID',
'Roadmap' => 'Roadmap',
'kpiname' => 'ชือดัชนี',
'targetname' => 'เป้าหมาย',
'target' => 'เป้าหมาย (ตัวเลข)',
'compare' => 'เปรียบเทียบ',
'multiple' => 'อัตรา',
'template' => 'มี Template ?',
'strategic' => 'KPI ยุทธศาสตร์ ?',
'thip' => 'KPI ของ THIP ?',
'hdc' => 'KPI ของ HDC ?',
'pa_moph' => 'KPI ของ PA กระทรวงฯ ?',
'inspec' => 'KPI ของ ตรวจราชการ ?',
'servplan' => 'KPI ของ Service Plan ?',
'ssj' => 'KPI ของ สสจ.กาญจนบุรี ?',
'y157' => 'ตัวตั้ง ปี 2557',
'y257' => 'ตัวหาร ปี 2557',
'y158' => 'ตัวตั้ง ปี 2558',
'y258' => 'ตัวหาร ปี 2558',
'y159' => 'ตัวตั้ง ปี 2559',
'y259' => 'ตัวหาร ปี 2559',
'y160' => 'ตัวตั้ง ปี 2560',
'y260' => 'ตัวหาร ปี 2560',
'y161' => 'ตัวตั้ง ปี 2561',
'y261' => 'ตัวหาร ปี 2561',
'y162' => 'ตัวตั้ง ปี 2562',
'y262' => 'ตัวหาร ปี 2562',
'y163' => 'ตัวตั้ง ปี 2563',
'y263' => 'ตัวหาร ปี 2563',
'y164' => 'ตัวตั้ง ปี 2564',
'y264' => 'ตัวหาร ปี 2564',
'y165' => 'ตัวตั้ง ปี 2565',
'y265' => 'ตัวหาร ปี 2565',
'owner' => 'เจ้าภาพ',
'source' => 'แหล่งมา',
'used' => 'ใช้งาน KPI นี้ ?',
'remark' => 'หมายเหตุ',
];
}
}
| 34.818898 | 179 | 0.508141 |
464ef74c75f33dcd7f47dce8af2ecbe0edcf0898 | 6,343 | php | PHP | application/views/models/Expense_model.php | kevalj/ims1 | 0f8d61b58ccd2092f6fddae3486281bdab5404ff | [
"MIT"
] | null | null | null | application/views/models/Expense_model.php | kevalj/ims1 | 0f8d61b58ccd2092f6fddae3486281bdab5404ff | [
"MIT"
] | null | null | null | application/views/models/Expense_model.php | kevalj/ims1 | 0f8d61b58ccd2092f6fddae3486281bdab5404ff | [
"MIT"
] | null | null | null | <?php
class Expense_model extends CI_Model {
public function __construct()
{
$this->load->database();
$this->load->library('session');
$this->load->helper('date');
}
public function get_vehicle_data($id)
{
$condition = "vehicle_type_id = " . $this->db->escape($id) . " and company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])."";
$this->db->select('*');
$this->db->from('vehicle_details');
$this->db->where($condition);
$query = $this->db->get();
return $query->result_array();
}
public function get_expense_category()
{
$condition = "company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])."";
$this->db->select('*');
$this->db->from('expense_details');
$this->db->where($condition);
return $query = $this->db->get();
}
public function save_expense_data()
{
$data = array(
'expense_details_id' => $this->input->post('expense_details_id'),
'expense_date' => $this->dateconvert($this->input->post('expense_date')),
'expense_amount' => str_replace( ',', '',$this->input->post('amount')),
'trailer_id' => $this->input->post('trailer_id'),
'truck_id' => $this->input->post('truck_id'),
'expense_description' => $this->input->post('description'),
'gallons' => $this->input->post('gallons'),
'customer_id' => $this->input->post('fuel_vendor_id'),
'state_id' => $this->input->post('state'),
'status' =>'Y',
'inserted_by'=>$this->session->userdata['logged_in']['login_id'],
'company_detail_id'=>$this->session->userdata['logged_in']['company_detail_id']
);
$this->db->set('inserted_date', 'NOW()', FALSE);
$this->db->insert('category_expense_details', $data);
return $this->db->insert_id();
}
public function getexpenseData()
{
$query="select category_expense_details_id,DATE_FORMAT(expense_date,'%m-%d-%Y') expense_date,expense_amount,expense_description,gallons,expense_name,vd.vehicle_no truck,vd1.vehicle_no trailer,customer_name,state_name
from category_expense_details ced
inner join expense_details ed on ed.expense_details_id=ced.expense_details_id
left join vehicle_details vd on vd.vehicle_id=ced.truck_id
left join vehicle_details vd1 on vd1.vehicle_id=ced.trailer_id
left join customer_details cd on cd.customer_id=ced.customer_id
left join states s on s.state_id=ced.state_id
where ced.status='Y' and ced.company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])." and ed.company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])." and vd.company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])." and vd1.company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])." and cd.company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])."
order by category_expense_details_id desc";
return $query = $this->db->query($query);
//return $query->result_array();
}
public function save_expense_category_data()
{
$data = array(
'expense_name' => $this->input->post('exp_expense_category'),
'status' =>'Y',
'inserted_by'=>$this->session->userdata['logged_in']['login_id'],
'company_detail_id'=>$this->session->userdata['logged_in']['company_detail_id']
);
$this->db->set('inserted_date', 'NOW()', FALSE);
$this->db->insert('expense_details', $data);
return $this->db->insert_id();
}
public function getselexpenseData($id)
{
$query="select category_expense_details_id,DATE_FORMAT(expense_date,'%m-%d-%Y') expense_date,expense_amount,expense_description,gallons,expense_name,ed.expense_details_id,vd.vehicle_no truck,vd.vehicle_id truck_id,vd1.vehicle_no trailer,vd1.vehicle_id trailer_id,customer_name,cd.customer_id,state_name,s.state_id,ced.status
from category_expense_details ced
inner join expense_details ed on ed.expense_details_id=ced.expense_details_id
left join vehicle_details vd on vd.vehicle_id=ced.truck_id
left join vehicle_details vd1 on vd1.vehicle_id=ced.trailer_id
left join customer_details cd on cd.customer_id=ced.customer_id
left join states s on s.state_id=ced.state_id where category_expense_details_id=".$this->db->escape($id)." and ced.status='Y' and ced.company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])." and ed.company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])." and vd.company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])." and vd1.company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])." and cd.company_detail_id=".$this->db->escape($this->session->userdata['logged_in']['company_detail_id'])."";
$query = $this->db->query($query);
return $query->result_array();
}
public function edit_expense_data()
{
$data = array(
'expense_details_id' => $this->input->post('expense_details_id'),
'expense_date' => $this->dateconvert($this->input->post('expense_date')),
'expense_amount' => str_replace( ',', '',$this->input->post('amount')),
'trailer_id' => $this->input->post('trailer_id'),
'truck_id' => $this->input->post('truck_id'),
'expense_description' => $this->input->post('description'),
'gallons' => $this->input->post('gallons'),
'customer_id' => $this->input->post('fuel_vendor_id'),
'state_id' => $this->input->post('state'),
'status' =>$this->input->post('status'),
'modified_by'=>$this->session->userdata['logged_in']['login_id'],
'company_detail_id'=>$this->session->userdata['logged_in']['company_detail_id']
);
$this->db->set('modified_date', 'NOW()', FALSE);
$this->db->where('category_expense_details_id', $this->input->post('category_expense_details_id'));
$this->db->update('category_expense_details', $data);
return $this->db->insert_id();
}
public function dateconvert($date){
$oldDate = $date;
if($date!=''){
$arr1 = explode('-', $oldDate);
return $newDate = $arr1[2].'-'.$arr1[0].'-'.$arr1[1];
} else{
return $date;
}
}
} | 44.669014 | 664 | 0.685007 |
dd916d850dccd3cbabfaec2a908e8f00018f943f | 335 | java | Java | bootx-services/service-payment/src/main/java/cn/bootx/payment/core/paymodel/voucher/dao/VoucherMapper.java | xxm1995/bootx-platform | 45aa11011fb142dbfad5e741d30fec6b0a1f2052 | [
"Apache-2.0"
] | null | null | null | bootx-services/service-payment/src/main/java/cn/bootx/payment/core/paymodel/voucher/dao/VoucherMapper.java | xxm1995/bootx-platform | 45aa11011fb142dbfad5e741d30fec6b0a1f2052 | [
"Apache-2.0"
] | null | null | null | bootx-services/service-payment/src/main/java/cn/bootx/payment/core/paymodel/voucher/dao/VoucherMapper.java | xxm1995/bootx-platform | 45aa11011fb142dbfad5e741d30fec6b0a1f2052 | [
"Apache-2.0"
] | 1 | 2022-03-19T13:44:47.000Z | 2022-03-19T13:44:47.000Z | package cn.bootx.payment.core.paymodel.voucher.dao;
import cn.bootx.payment.core.paymodel.voucher.entity.Voucher;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
*
* @author xxm
* @date 2022/3/14
*/
@Mapper
public interface VoucherMapper extends BaseMapper<Voucher> {
}
| 22.333333 | 61 | 0.773134 |
3fee65eb91697f7a6bff1fbfebc8c6f14672a346 | 962 | gemspec | Ruby | to_xls-rails.gemspec | czchen88/to_xls-rails | a883e62f233ccba886c7e05ed3510ff2c627dc7d | [
"MIT"
] | 40 | 2015-01-10T09:55:11.000Z | 2021-12-14T06:25:03.000Z | to_xls-rails.gemspec | czchen88/to_xls-rails | a883e62f233ccba886c7e05ed3510ff2c627dc7d | [
"MIT"
] | 9 | 2015-06-11T15:33:07.000Z | 2018-04-26T18:41:07.000Z | to_xls-rails.gemspec | czchen88/to_xls-rails | a883e62f233ccba886c7e05ed3510ff2c627dc7d | [
"MIT"
] | 10 | 2015-09-12T04:56:43.000Z | 2019-12-02T15:27:15.000Z | # encoding: utf-8
version = File.read(File.expand_path("../VERSION", __FILE__)).strip
Gem::Specification.new do |spec|
spec.name = 'to_xls-rails'
spec.version = version
spec.author = "Mike Liang"
spec.email = "[email protected]"
spec.homepage = "http://github.com/liangwenke/to_xls-rails"
spec.summary = "Export Rails ActiveRecord data to excel file"
spec.description = "This simple plugin gives you the ability to call to_xls to a collection of activerecords for Rails."
spec.files = Dir["{lib,test}/**/*", "[a-zA-Z]*", "init.rb"] - ["Gemfile.lock"]
spec.require_path = "lib"
spec.license = 'MIT'
spec.add_dependency('spreadsheet', '>= 0.8.5')
spec.platform = Gem::Platform::RUBY
spec.required_rubygems_version = ">= 1.3.4"
end
| 41.826087 | 136 | 0.553015 |
592d9bf14a58be4af18b1e0004a85eba8628744d | 1,882 | dart | Dart | app/lib/widgets/user_avatar.dart | schultek/jufa | 96a683c53c421211c2de913e662a14de584e2ae3 | [
"MIT"
] | 1 | 2022-01-19T12:14:03.000Z | 2022-01-19T12:14:03.000Z | app/lib/widgets/user_avatar.dart | schultek/jufa | 96a683c53c421211c2de913e662a14de584e2ae3 | [
"MIT"
] | 1 | 2022-01-19T12:55:45.000Z | 2022-01-19T12:55:45.000Z | app/lib/widgets/user_avatar.dart | schultek/jufa | 96a683c53c421211c2de913e662a14de584e2ae3 | [
"MIT"
] | null | null | null | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../core/core.dart';
import '../modules/thebutton/thebutton_provider.dart';
import '../modules/thebutton/widgets/thebutton_shape.dart';
import '../providers/trips/selected_trip_provider.dart';
class UserAvatar extends StatelessWidget {
final String id;
const UserAvatar({Key? key, required this.id}) : super(key: key);
@override
Widget build(BuildContext context) {
return ThemedSurface(
preference: const ColorPreference(useHighlightColor: true),
builder: (context, color) => Consumer(
builder: (context, ref, _) {
var user = ref.watch(tripUserByIdProvider(id));
var showButtonLevel = ref.watch(theButtonProvider.select((v) => v.value?.showInAvatars ?? false));
var userLevel = ref.watch(theButtonUserLevelProvider(id));
return CircleAvatar(
backgroundColor: color,
foregroundColor: context.onSurfaceColor,
backgroundImage: user?.profileUrl != null ? CachedNetworkImageProvider(user!.profileUrl!) : null,
child: Stack(
clipBehavior: Clip.none,
children: [
if (user?.profileUrl == null)
if (user?.nickname != null)
Center(child: Text(user!.nickname!.substring(0, 1)))
else
const Center(child: Icon(Icons.account_circle_outlined, size: 25)),
if (showButtonLevel)
if (userLevel != null && userLevel >= 0 && userLevel < theButtonLevelsCount)
Positioned(right: -13, bottom: -13, child: StarPaint(color: getColorForLevel(userLevel, context)))
],
),
);
},
),
);
}
}
| 40.913043 | 118 | 0.622742 |
b02dd391dcc239987a7c0b28dce3ec174d826c04 | 2,706 | lua | Lua | RobloxModule/PackagedFiles/encode.module.lua | Madonox/Roblox-RPM | d96e0782c38f558abae83562e9cf5a0e07b46576 | [
"MIT"
] | null | null | null | RobloxModule/PackagedFiles/encode.module.lua | Madonox/Roblox-RPM | d96e0782c38f558abae83562e9cf5a0e07b46576 | [
"MIT"
] | null | null | null | RobloxModule/PackagedFiles/encode.module.lua | Madonox/Roblox-RPM | d96e0782c38f558abae83562e9cf5a0e07b46576 | [
"MIT"
] | 1 | 2022-01-19T07:34:51.000Z | 2022-01-19T07:34:51.000Z | -- Madonox
return function(inst)
if inst:FindFirstChild("package.rpm") then
local pack = require(inst["package.rpm"])
if pack then
local baseScript = "if not game.ServerScriptService:FindFirstChild('RPMPackages') then Instance.new('Folder',game.ServerScriptService).Name='RPMPackages'; end; Instance.new('Folder',game.ServerScriptService.RPMPackages).Name='"..pack.packageName.."'; Instance.new('Folder',game.ServerScriptService.RPMPackages."..pack.packageName..").Name='Modules';"
for i,v in ipairs(inst:GetChildren()) do
if v:IsA("Script") then
local compressedScript = "local "..tostring("_script"..i).." = Instance.new('Script');"
local scriptBlankSource = v.Source
scriptBlankSource = string.gsub(scriptBlankSource,"--","")
compressedScript = compressedScript..tostring("_script"..i)..".Name='"..v.Name.."';"
compressedScript = compressedScript..tostring("_script"..i)..".Source=[["..string.gsub(scriptBlankSource,'"',"'").."]];"
compressedScript = compressedScript..tostring("_script"..i)..".Parent=game.ServerScriptService.RPMPackages."..pack.packageName..";"
baseScript = baseScript.." "..compressedScript
elseif v:IsA("ModuleScript") then
local compressedScript = "local "..tostring("_Modulescript"..i).." = Instance.new('ModuleScript');"
local scriptBlankSource = v.Source
scriptBlankSource = string.gsub(scriptBlankSource,"--","")
compressedScript = compressedScript..tostring("_Modulescript"..i)..".Name='"..v.Name.."';"
compressedScript = compressedScript..tostring("_Modulescript"..i)..".Source=[["..string.gsub(scriptBlankSource,'"',"'").."]];"
compressedScript = compressedScript..tostring("_Modulescript"..i)..".Parent=game.ServerScriptService.RPMPackages."..pack.packageName..";"
baseScript = baseScript.." "..compressedScript
elseif v.Name == "Modules" then
for i2,v2 in ipairs(v:GetChildren()) do
if v2:IsA("ModuleScript") then
local compressedScript = "local "..tostring("_ModulescriptE"..i).." = Instance.new('ModuleScript');"
local scriptBlankSource = v.Source
scriptBlankSource = string.gsub(scriptBlankSource,"--","")
compressedScript = compressedScript..tostring("_ModulescriptE"..i)..".Name='"..v.Name.."';"
compressedScript = compressedScript..tostring("_ModulescriptE"..i)..".Source=[["..string.gsub(scriptBlankSource,'"',"'").."]];"
compressedScript = compressedScript..tostring("_ModulescriptE"..i)..".Parent=game.ServerScriptService.RPMPackages."..pack.packageName..".Modules;"
baseScript = baseScript.." "..compressedScript
end
end
end
end
return {
["source"] = baseScript;
}
end
end
end
| 60.133333 | 353 | 0.68847 |
5aed54e4ab3bcfaa4291f9ec273d8da31e7a62cd | 1,771 | cshtml | C# | src/SoarBeyond.Web/Pages/Shared/_Layout.cshtml | CalebABG/SoarBeyond | f4cb5e5e5076b8f65621bb7393859bb878a5bf36 | [
"MIT"
] | 2 | 2021-11-18T18:27:29.000Z | 2021-11-18T19:01:36.000Z | src/SoarBeyond.Web/Pages/Shared/_Layout.cshtml | CalebABG/SoarBeyond | f4cb5e5e5076b8f65621bb7393859bb878a5bf36 | [
"MIT"
] | 53 | 2021-11-20T09:54:57.000Z | 2022-03-31T03:07:58.000Z | src/SoarBeyond.Web/Pages/Shared/_Layout.cshtml | CalebABG/SoarBeyond | f4cb5e5e5076b8f65621bb7393859bb878a5bf36 | [
"MIT"
] | null | null | null | @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>@ViewData["Title"] - SoarBeyond</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/lib/bootstrap/bootstrap.min.css" />
<link rel="stylesheet" href="/css/identity.css" />
</head>
<body>
<nav class="navbar navbar-expand-sm navbar-dark bg-dark fixed-top">
<div class="container-fluid">
<a class="navbar-brand" href="~/">SoarBeyond</a>
<button type="button"
class="navbar-toggler"
data-bs-toggle="collapse"
data-bs-target=".navbar-collapse"
aria-controls="navbarSupportedContent"
aria-expanded="false"
aria-label="Toggle navigation">
<i class="fas fa-bars"></i>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">
@{
await Html.RenderPartialAsync("_LoginPartial");
}
</div>
</div>
</nav>
<div class="container py-3">
@RenderBody()
</div>
<script src="/lib/jquery/jquery-3.6.0.min.js"></script>
<script src="/lib/bootstrap/bootstrap.bundle.min.js"></script>
<script src="~/Identity/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
| 36.895833 | 116 | 0.58611 |
0da2c556662baddd9bbd919eb64857a749990264 | 1,230 | rb | Ruby | test/functional/ct_0_concurrence.rb | maestrodev/ruote | bea93f568800dc704d79bdff833307a804a3f427 | [
"MIT"
] | null | null | null | test/functional/ct_0_concurrence.rb | maestrodev/ruote | bea93f568800dc704d79bdff833307a804a3f427 | [
"MIT"
] | null | null | null | test/functional/ct_0_concurrence.rb | maestrodev/ruote | bea93f568800dc704d79bdff833307a804a3f427 | [
"MIT"
] | 1 | 2019-12-23T17:05:08.000Z | 2019-12-23T17:05:08.000Z |
#
# testing ruote
#
# Wed Jul 8 15:30:55 JST 2009
#
require File.join(File.dirname(__FILE__), 'concurrent_base')
#require 'ruote/part/hash_participant'
class CtConcurrenceTest < Test::Unit::TestCase
include ConcurrentBase
# A collision between two workers replying to the same concurrence expression.
#
# Worker 0 replies for echo 'a' while worker 1 replies for echo 'b'.
#
def test_collision
pdef = Ruote.process_definition do
concurrence do
echo 'a'
echo 'b'
end
end
noisy if ARGV.include?('-N')
wfid = @engine0.launch(pdef)
replies = []
while replies.size < 2
msg = @engine0.next_msg
if msg['action'] == 'reply'
replies << msg
else
@engine0.do_process(msg)
end
end
replies.sort! { |a, b| a['put_at'] <=> b['put_at'] }
#replies.each { |r| p r }
t0 = Thread.new { @engine1.do_process(replies[0]) }
t1 = Thread.new { @engine0.do_process(replies[1]) }
t0.join
t1.join
msgs = @engine0.gather_msgs
assert_equal 1, msgs.size, 'exactly 1 message was expected'
msg = msgs.first
assert_equal 'reply', msg['action']
assert_equal '0', msg['fei']['expid']
end
end
| 18.636364 | 80 | 0.618699 |
a15c7a85f211b88cffbf63fdfb7f4cc5d4fe8635 | 346 | ts | TypeScript | packages/core/src/contracts.ts | superchargejs/framework | 16f3a764ffba81371e763380187d483c74320b24 | [
"MIT"
] | 9 | 2019-02-03T12:07:42.000Z | 2019-11-16T22:30:15.000Z | packages/core/src/contracts.ts | superchargejs/framework | 16f3a764ffba81371e763380187d483c74320b24 | [
"MIT"
] | 32 | 2019-02-25T09:15:54.000Z | 2019-11-08T12:42:24.000Z | packages/core/src/contracts.ts | superchargejs/framework | 16f3a764ffba81371e763380187d483c74320b24 | [
"MIT"
] | 5 | 2019-03-04T22:19:06.000Z | 2019-10-30T21:37:28.000Z | 'use strict'
import { Server } from '@supercharge/http'
import { Application, ConfigStore, EnvStore, HttpKernel } from '@supercharge/contracts'
export interface ContainerBindings {
'app': Application
'container': Application
'env': EnvStore
'config': ConfigStore
'http.kernel': HttpKernel
'http.server': Server
Server: Server
}
| 20.352941 | 87 | 0.728324 |
d8e33829a9ebd8b9f79689b7188ef084b3bf72dd | 5,814 | sql | SQL | docs/misc/Query-pgsql-json.sql | i-victor/Smart.DevScripts | b69c4fa7438900d51efa78d6411d16ea3d016900 | [
"BSD-3-Clause"
] | null | null | null | docs/misc/Query-pgsql-json.sql | i-victor/Smart.DevScripts | b69c4fa7438900d51efa78d6411d16ea3d016900 | [
"BSD-3-Clause"
] | null | null | null | docs/misc/Query-pgsql-json.sql | i-victor/Smart.DevScripts | b69c4fa7438900d51efa78d6411d16ea3d016900 | [
"BSD-3-Clause"
] | 3 | 2020-11-04T07:33:57.000Z | 2021-12-18T13:51:42.000Z |
-- #START :: v.161006
SELECT id, data#>>'{extra,os,0}' FROM public.test_tbl ORDER BY data->>'pad_urls_id' ASC
SELECT * FROM distrib.apps WHERE json_data#>>'{pad_data,downloads}' ILIKE '%play.google%';
SELECT * FROM distrib.apps WHERE json_data#>'{extra,os}' ? 'mac'
SELECT * FROM distrib.apps WHERE json_data#>>'{pad_data,downloads}' ILIKE '%play.google%'
CREATE INDEX apps__idx__json_data_progr_name ON distrib.apps USING btree (((json_data #>> '{pad_data,program,name}')));
CREATE INDEX apps__idx__json_data_progr_categ ON distrib.apps USING btree (((json_data #>> '{pad_data,program,category}')));
CREATE INDEX apps__idx__json_data_progr_scateg ON distrib.apps USING btree (((json_data #>> '{pad_data,program,sub_category}')));
CREATE INDEX apps__idx__json_data_progr_os ON website.apps USING btree (((json_data #> '{extra,os}')));
CREATE INDEX apps__idx__json_data_progr_os ON website.apps USING btree (COALESCE((json_data #> '{extra,os}'::jsonb),'[]'::jsonb));
CREATE INDEX apps__idx__json_data_progr_cost ON website.apps USING btree (CAST(('0' || COALESCE((json_data #>> '{pad_data,cost,dollars}'),'0')) AS NUMERIC));
CREATE INDEX apps__idx__json_data_progr_fsize ON website.apps USING btree (CAST(('0' || COALESCE((json_data #>> '{pad_data,program,file_size}'),'0')) AS BIGINT));
CREATE INDEX apps__idx__json_data_progr_review_rating ON website.apps USING btree (CAST(('0' || COALESCE(("review_json"#>>'{rating}'),'0')) AS NUMERIC));
CREATE INDEX apps__idx__json_data_progr_review_pdate ON website.apps USING btree (((review_json ->> 'publish_date')));
SELECT * FROM distrib.apps WHERE json_data#>'{extra,os}' ? 'linux'
UPDATE "apps" SET "scateg_id" = (json_data #>> '{pad_data,program,sub_category}')
UPDATE "apps" SET "scateg_id" = ( SELECT "categs"."id" FROM "categs" WHERE ("categs"."name" = "apps"."scateg_id" AND "categs"."parent_id" = "apps"."categ_id") LIMIT 1 OFFSET 0)
SELECT slug, CAST(('0' || COALESCE((json_data #>> '{pad_data,program,file_size}'),'0')) AS BIGINT) as fsize FROM apps WHERE (json_data #>> '{pad_data,program,file_size}') LIKE '%.%'
ORDER BY CAST(('0' || COALESCE((json_data #>> '{pad_data,program,file_size}'),'0')) AS BIGINT) ASC LIMIT 10 OFFSET 0
UPDATE "apps" SET os_win = TRUE WHERE ("json_data"#>'{extra,os}' ? 'windows')
UPDATE "apps" SET os_mac = TRUE WHERE ("json_data"#>'{extra,os}' ? 'mac')
UPDATE "apps" SET os_lin = TRUE WHERE ("json_data"#>'{extra,os}' ? 'linux');
UPDATE "apps" SET os_and = TRUE WHERE ("json_data"#>'{extra,os}' ? 'android');
UPDATE "apps" SET os_ios = TRUE WHERE ("json_data"#>'{extra,os}' ? 'ios');
--
CREATE TABLE test_url (url varchar NOT NULL, url_tsvector tsvector NOT NULL);
CREATE OR REPLACE FUNCTION generate_url_tsvector(varchar)
RETURNS tsvector
LANGUAGE sql
AS $_$
SELECT to_tsvector(regexp_replace($1, '[^\w]+', ' ', 'gi'));
$_$;
CREATE OR REPLACE FUNCTION before_insert_test_url()
RETURNS TRIGGER
LANGUAGE plpgsql AS $_$
BEGIN
NEW.url_tsvector := generate_url_tsvector(NEW.url);
RETURN NEW;
END
$_$;
CREATE TRIGGER before_insert_test_url_trig
BEFORE INSERT ON test_url
FOR EACH ROW EXECUTE PROCEDURE before_insert_test_url();
--
SELECT DISTINCT jsonb_array_elements_text(topics)::text FROM quotes;
SELECT (jsonb_array_elements(authors)::jsonb #> '{id}')::jsonb FROM quotes;
SELECT (jsonb_array_elements(authors)::jsonb #>> '{id}')::text FROM quotes;
SELECT * FROM ( SELECT *, (jsonb_array_elements(authors)::jsonb #>> '{id}')::text AS author_id FROM quotes ) a WHERE a.author_id = '0000000002';
SELECT * FROM quotes WHERE topics ? 'T000000001';
SELECT * FROM quotes WHERE topics ?| ARRAY(SELECT id FROM topics WHERE slug = 'topic-one'); -- inneficient !!!
SELECT a.id, b.* FROM topics a INNER JOIN quotes b ON (b.topics ? a.id) LIMIT 25 OFFSET 0 -- a better solution
SELECT a.dom, b.pad_urls_id, b.source FROM blacklist_domains a INNER JOIN radix_urls b ON (b.dom_data ? a.dom) LIMIT 25 OFFSET 0
SELECT to_tsvector('english', 'a fat cat sat on a mat - it ate a fat rats');
SELECT to_tsvector('a fat cat sat on a mat - it ate a fat rats');
UPDATE "quotes" SET "fts_quote" = to_tsvector("quote")
UPDATE "quotes" SET "fts_quote" = to_tsvector(smart_deaccent_string("quote"))
SELECT * FROM quotes WHERE fts_quote @@ to_tsquery('days')
SELECT * FROM quotes WHERE fts_quote @@ to_tsquery(smart_deaccent_string('days & quote'))
INSERT INTO quotes VALUES ('ABCDEF1230', 'some-quote', '0000000000', '["0000000001", "0000000002"]', '["topic1", "topic2"]', 'Some Quote of the day
by Räksmörgås Jösefsson', '["some", "quote", "day"]', '''day'':5 ''josefsson'':8 ''quot'':2 ''raksmorga'':7', '[]');
--
SELECT COALESCE(token, '') as host FROM ts_debug('http://example.com/stuff/index.html') WHERE alias = 'host';
SELECT ('["' || COALESCE(token, '') || '"]')::jsonb AS host FROM ts_debug('http://www.example.com/stuff/index.html'
UPDATE radix_urls a SET dom_data = ( SELECT ('["' || COALESCE(token, '') || '"]')::jsonb FROM ts_debug(a.value) WHERE alias = 'host' LIMIT 1 OFFSET 0 );
-- select substring( 'http://www.arandomsite.co.uk' from '^[^:]*://(?:[^/:]*:[^/@]*@)?(?:[^/:.]*\.)+([^:/]+)' ) as tld;
-- select substring( 'http://www.arandomsite.com' from '^[^:]*://(?:[^/:]*:[^/@]*@)?(?:[^/:.]*\.)+((?:[^/:.]*\.)+)' ) as tld;
SELECT * FROM tmp.test_url WHERE url_data ? 'www.google.com'
-- SELECT COALESCE(token, '') as host FROM ts_debug('http://example.com/stuff/index.html') WHERE alias = 'host';
UPDATE radix_urls a SET dom_data = COALESCE(( SELECT ('["' || COALESCE(token, '') || '"]')::jsonb FROM ts_debug(a.value) WHERE alias = 'host' LIMIT 1 OFFSET 0 ), '[]');
UPDATE blacklist_domains a SET dom_info = COALESCE(( SELECT radix_info FROM radix_subdomains b WHERE a.dom = b.radix LIMIT 1 OFFSET 0 ), '')
-- View Sizes
SELECT relname, relpages FROM pg_class ORDER BY relpages DESC;
-- #END
| 51 | 181 | 0.695734 |
7acaf39e4227e3d4b2f12583287ba5c7947904a0 | 11,007 | cs | C# | test/ElasticSearch.Prototyping/ElasticSearch_Indexing.cs | pmario71/DesktopSearch | b8d3addfba227e4f2b40889a631441e4fc828cfe | [
"Apache-2.0"
] | 1 | 2021-04-13T01:25:51.000Z | 2021-04-13T01:25:51.000Z | test/ElasticSearch.Prototyping/ElasticSearch_Indexing.cs | pmario71/DesktopSearch | b8d3addfba227e4f2b40889a631441e4fc828cfe | [
"Apache-2.0"
] | null | null | null | test/ElasticSearch.Prototyping/ElasticSearch_Indexing.cs | pmario71/DesktopSearch | b8d3addfba227e4f2b40889a631441e4fc828cfe | [
"Apache-2.0"
] | null | null | null | using DesktopSearch.Core.DataModel;
using DesktopSearch.Core.DataModel.Code;
using DesktopSearch.Core.Extractors.Roslyn;
using DesktopSearch.Core.Tests.Helper;
using ElasticSearch.Prototyping.Utils;
using Nest;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElasticSearch.Prototyping
{
public class ElasticSearch_Indexing
{
private readonly string testDataPath = @"D:\Projects\GitHub\DesktopSearch\test\DesktopSearch.Core.Tests\TestData\IndexExtractors\Roslyn\APIClass.cs";
const string indexName = "test_docsearch";
public void Index_CaseInsensitive()
{
const string indexName = "test_codesearch";
InstanceDescriptor instance = DockerControlClient.Start("elasticsearch", "-p 9200:9200").Result;
try
{
var settings = new ConnectionSettings(new Uri(Configuration.ElasticSearchUri));
settings.DefaultIndex(indexName);
settings.DisableDirectStreaming()
.OnRequestCompleted(details =>
{
Console.WriteLine("### ES REQEUST ###");
if (details.RequestBodyInBytes != null) Console.WriteLine(Encoding.UTF8.GetString(details.RequestBodyInBytes));
Console.WriteLine("### ES RESPONSE ###");
if (details.ResponseBodyInBytes != null) Console.WriteLine(Encoding.UTF8.GetString(details.ResponseBodyInBytes));
})
.PrettyJson();
var elastic = new ElasticClient(settings);
if (!elastic.IndexExists(indexName).Exists)
{
var indexDescriptor = new CreateIndexDescriptor(indexName)
.Mappings(ms => ms
.Map<TypeDescriptor>(m => m.AutoMap())
.Map<MethodDescriptor>(m => m.AutoMap())
.Map<FieldDescriptor>(m => m.AutoMap()));
elastic.CreateIndex(indexName, i => indexDescriptor);
var parser = new RoslynParser();
var extractedTypes = parser.ExtractTypes(File.ReadAllText(testDataPath));
var index = elastic.IndexMany(extractedTypes);
Console.WriteLine(index);
}
// dump indices
// -----------------------------------------------
//DumpIndices(elastic);
var searchResults = elastic.Search<TypeDescriptor>(x => x.Query(q => q.Wildcard("name", "api*")));
//.MultiMatch(m => m
// .Query("Mart")
// .Fields(f => f
// .Fields(f1 => f1.Lastname, f2 => f2.Firstname)))));
Console.WriteLine("Searching ...");
Console.WriteLine($"{searchResults.DebugInformation}");
Console.WriteLine("-------------------------------------------");
if (searchResults.Documents.Any())
{
searchResults.Documents.Dump();
}
else
{
Console.WriteLine("<no results found!>");
}
//Assert.Equal(1, searchResults.Hits.Count());
//Assert.NotNull(searchResults.Documents.FirstOrDefault(f => string.Compare(f.Lastname, "Laarman", StringComparison.OrdinalIgnoreCase) == 0));
//Assert.False(true, "Just to see the output!");
Console.ReadLine();
}
finally
{
//await DockerControlClient.Stop(instance);
}
}
public void SearchOnly()
{
ConnectionSettings settings = InitializeSettings(indexName);
var elastic = new ElasticClient(settings);
var searchResults = elastic.Search<DocDescriptor>(x => x.Query(q => q.QueryString(q2 => q2.Query("telefon"))));
Console.WriteLine("Searching ...");
Console.WriteLine("-------------------------------------------");
if (searchResults.Documents.Any())
{
//searchResults.Documents.Dump();
var d = searchResults.Documents.First();
Console.WriteLine($"Hits: {searchResults.Hits.Count()}");
Console.WriteLine($"Path: {searchResults.Hits.First().Source.Path}");
}
else
{
Console.WriteLine("<no results found!>");
}
Console.ReadLine();
}
public void Document()
{
bool useStatic = false;
string path = @"D:\Downloads\ct.15.22.126-129.pdf";
const string staticContent = "e1xydGYxXGFuc2kNCkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0DQpccGFyIH0=";
var base64Content = (useStatic) ? staticContent : Convert.ToBase64String(File.ReadAllBytes(path));
try
{
ConnectionSettings settings = InitializeSettings(indexName);
var elastic = new ElasticClient(settings);
if (!elastic.IndexExists(indexName).Exists)
{
CreateIndex(indexName, elastic);
}
// --------------------------------------------------------------------
// store content
// --------------------------------------------------------------------
var docs = new[]
{
new DocDescriptor()
{
Path = "static content",
Content = staticContent
},
new DocDescriptor()
{
Path = "normal text file",
Content = Convert.ToBase64String(File.ReadAllBytes(@"D:\Projects\GitHub\DesktopSearch\test\ElasticSearch.Prototyping\ElasticSearch_Indexing.cs")),
},
new DocDescriptor()
{
Path = "pdf file",
Content = base64Content
}
};
var index = elastic.Bulk(b => b.IndexMany(docs));
Console.WriteLine(index);
// dump indices
// -----------------------------------------------
//DumpIndices(elastic);
// examples
// https://www.elastic.co/guide/en/elasticsearch/plugins/master/mapper-attachments-helloworld.html
//var searchResults = elastic.Search<DocDescriptor>(x => x.Query(q => q.Wildcard("path", "*")));
var searchResults = elastic.Search<DocDescriptor>(x => x.Query(q => q.QueryString(q2 => q2.Query("ipsum"))));
Console.WriteLine("Searching ...");
//Console.WriteLine($"{searchResults.DebugInformation}");
Console.WriteLine("-------------------------------------------");
//TODO: Plugin seems not to be installed!
if (searchResults.Documents.Any())
{
//searchResults.Documents.Dump();
var d = searchResults.Documents.First();
var areEqual = string.Compare(d.Content, base64Content) == 0;
var c = Console.ForegroundColor;
Console.ForegroundColor = (areEqual) ? c : ConsoleColor.Red;
Console.WriteLine($"Documents are the same: {areEqual}");
Console.ForegroundColor = c;
}
else
{
Console.WriteLine("<no results found!>");
}
Console.ReadLine();
}
finally
{
//await DockerControlClient.Stop(instance);
}
}
private static ConnectionSettings InitializeSettings(string indexName)
{
var settings = new ConnectionSettings(new Uri(Configuration.ElasticSearchUri));
settings.DefaultIndex(indexName);
settings.DisableDirectStreaming()
.OnRequestCompleted(details =>
{
Console.WriteLine("### ES REQEUST ###");
if (details.RequestBodyInBytes != null)
Console.WriteLine(Encoding.UTF8.GetString(details.RequestBodyInBytes));
// Console.WriteLine("### ES RESPONSE ###");
// if (details.ResponseBodyInBytes != null) Console.WriteLine(Encoding.UTF8.GetString(details.ResponseBodyInBytes));
})
.PrettyJson();
return settings;
}
private static void CreateIndex(string indexName, ElasticClient elastic)
{
// --------------------------------------------------------------------
// setup index
// --------------------------------------------------------------------
var indexDescriptor = new CreateIndexDescriptor(indexName);
indexDescriptor.Mappings(mp => mp.Map<DocDescriptor>(m => m
.AutoMap()
.Properties(ps => ps
.String(s => s
.Name(f => f.Path)
.Index(FieldIndexOption.Analyzed)
.Store(true))
.Attachment(atm => atm
.Name(p => p.Content)
.FileField(f => f
.Name(p => p.Content)
.Index(FieldIndexOption.Analyzed)
.Store(true)
.TermVector(TermVectorOption.WithPositionsOffsets))))));
elastic.CreateIndex(indexName, i => indexDescriptor);
}
private static void DumpIndices(ElasticClient elastic)
{
var stats = elastic.IndicesStats(Indices.All);
foreach (var idx in stats.Indices)
{
Console.WriteLine($"{idx.Key} -> Docs: {idx.Value.Total.Documents.Count}");
}
}
}
public class DocDescriptor
{
public string Path { get; set; }
[Attachment(Store = true)]
public string Content { get; set; }
public override string ToString()
{
return $"{Path} -- {Content.Length}";
}
}
public static class MyClass
{
public static void Dump(this IEnumerable enumerable)
{
foreach (var item in enumerable)
{
Console.WriteLine(item.ToString());
}
}
}
}
| 38.486014 | 170 | 0.481058 |
391e9423844512ff23869238ea0a564943c3002c | 8,136 | py | Python | uuv_evaluation/src/bag_evaluation/recording.py | Abhi10arora/uuv_simulator | bfcd8bb4b05f14c8d5ec0f3431223f654d4b1441 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | uuv_evaluation/src/bag_evaluation/recording.py | Abhi10arora/uuv_simulator | bfcd8bb4b05f14c8d5ec0f3431223f654d4b1441 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | uuv_evaluation/src/bag_evaluation/recording.py | Abhi10arora/uuv_simulator | bfcd8bb4b05f14c8d5ec0f3431223f654d4b1441 | [
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2018-10-18T15:11:01.000Z | 2018-10-18T15:11:01.000Z | # Copyright (c) 2016 The UUV Simulator Authors.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import rospy
import logging
import sys
import rosbag
import numpy as np
from uuv_trajectory_generator import TrajectoryGenerator, TrajectoryPoint
class Recording:
__instance = None
def __init__(self, filename):
# Setting up the log
self._logger = logging.getLogger('read_rosbag')
if len(self._logger.handlers) == 0:
out_hdlr = logging.StreamHandler(sys.stdout)
out_hdlr.setFormatter(logging.Formatter('%(asctime)s | %(levelname)s | %(module)s | %(message)s'))
out_hdlr.setLevel(logging.INFO)
self._logger.addHandler(out_hdlr)
self._logger.setLevel(logging.INFO)
# Bag filename
self._filename = filename
self._bag = rosbag.Bag(filename)
self._thruster_prefix = None
self._topics = dict()
for x in self._bag.get_type_and_topic_info():
for k in x:
if 'reference' in k:
self._topics['trajectory'] = k
self._logger.info('Trajectory topic found <%s>' % k)
if 'nav_msgs/Odometry' in x[k][0]:
self._topics['odometry'] = k
self._logger.info('Odometry topic found <%s>' % k)
if 'current_velocity' in k:
self._topics['current_velocity'] = k
self._logger.info('Current velocity topic found <%s>' % k)
if 'wrench_perturbation' in k:
self._topics['wrench_perturbation'] = k
self._logger.info('Wrench perturbation topic found <%s>' % k)
if self._thruster_prefix is None:
if 'thrusters' in k:
self._logger.info('Thruster output topic found <%s>' % k)
i = len('thrusters')
i_max = k.find('thrusters') + i
self._thruster_prefix = k[:i_max]
self._is_init = False
self._trajectories = dict(desired=None,
actual=None)
self._thrusters = dict()
self._current_vel = dict(time=list(),
vel=list())
self._disturbance_wrench = dict(time=list(),
force=list(),
torque=list())
self._read_data()
if not self._is_init:
self._logger.error('Error reading bag, filename=' + self._filename)
Recording.__instance = self
@classmethod
def get_instance(cls):
if cls.__instance is None:
cls.__instance = Recording()
return cls.__instance
@property
def is_init(self):
return self._is_init
@property
def start_time(self):
return self._trajectories['desired'].points[0].t
@property
def end_time(self):
return self._trajectories['desired'].points[-1].t
@property
def desired(self):
return self._trajectories['desired']
@property
def actual(self):
return self._trajectories['actual']
@property
def n_thrusters(self):
return len(self._thrusters.keys())
def _read_data(self):
try:
self._trajectories['desired'] = TrajectoryGenerator()
for topic, msg, time in self._bag.read_messages(self._topics['trajectory']):
self._trajectories['desired'].add_trajectory_point_from_msg(msg)
self._trajectories['actual'] = TrajectoryGenerator()
if 'odometry' in self._topics:
for topic, msg, time in self._bag.read_messages(self._topics['odometry']):
t = msg.header.stamp.to_sec()
p = msg.pose.pose.position
q = msg.pose.pose.orientation
v = msg.twist.twist.linear
w = msg.twist.twist.angular
point = TrajectoryPoint(
t, np.array([p.x, p.y, p.z]),
np.array([q.x, q.y, q.z, q.w]),
np.array([v.x, v.y, v.z]),
np.array([w.x, w.y, w.z]),
np.array([0, 0, 0]),
np.array([0, 0, 0]))
# Store sampled trajectory point
self._trajectories['actual'].add_trajectory_point(point)
# Find all thruster topics
for i in range(16):
for topic, msg, time in self._bag.read_messages('%s/%d/thrust' % (self._thruster_prefix, i)):
if i not in self._thrusters:
self._thrusters[i] = dict(time=list(), values=list())
t = msg.header.stamp.to_sec()
self._thrusters[i]['time'].append(t)
self._thrusters[i]['values'].append(float(msg.data))
if 'current_velocity' in self._topics:
for topic, msg, time in self._bag.read_messages(self._topics['current_velocity']):
time = msg.header.stamp.to_sec()
v = msg.twist.linear
self._current_vel['time'].append(time)
self._current_vel['vel'].append([v.x, v.y, v.z])
if 'wrench_perturbation' in self._topics:
for topic, msg, time in self._bag.read_messages(self._topics['wrench_perturbation']):
time = msg.header.stamp.to_sec()
self._disturbance_wrench['time'].append(time)
self._disturbance_wrench['force'].append([msg.wrench.force.x,
msg.wrench.force.y,
msg.wrench.force.z])
self._disturbance_wrench['torque'].append([msg.wrench.torque.x,
msg.wrench.torque.y,
msg.wrench.torque.z])
self._is_init = True
except Exception, e:
self._logger.error('Error retrieving data from rosbag, message=' + str(e))
self._is_init = False
def get_time(self):
if not self._is_init:
return list()
return self._trajectories['actual'].times
def get_thruster_data(self, index):
if not self._is_init:
print self.__class__.__name__, '- Thruster data has not been parsed'
return None, None
if index not in self._thrusters:
print self.__class__.__name__, '- Invalid thruster index, value=', index
return None, None
return self._thrusters[index]['time'], self._thrusters[index]['values']
def get_trajectory_coord(self, tag):
assert tag in self._trajectories, 'Invalid trajectory tag'
x = [p.p[0] for p in self._trajectories[tag].points]
y = [p.p[1] for p in self._trajectories[tag].points]
z = [p.p[2] for p in self._trajectories[tag].points]
return x, y, z
def get_thruster_data(self, idx):
assert idx in self._thrusters, 'Invalid thruster index, idx=' + str(idx)
return self._thrusters[idx]['time'], self._thrusters[idx]['values']
def get_current_vel(self):
return self._current_vel['time'], self._current_vel['vel']
def get_wrench_dist(self):
return self._disturbance_wrench['time'], self._disturbance_wrench['force'], self._disturbance_wrench['torque']
| 39.882353 | 118 | 0.555064 |
4d0852a87cc2cf70a07e8a3922147e39f954f00a | 4,719 | cs | C# | test/NuGet.Core.Tests/NuGet.Packaging.Test/Core/comparers/PackageDependencyInfoComparerTests.cs | huangqinjin/NuGet.Client | 680f9bd4e97db7cd7482584276886764de69d3cb | [
"Apache-2.0"
] | 654 | 2015-03-15T15:53:07.000Z | 2022-03-25T18:16:49.000Z | test/NuGet.Core.Tests/NuGet.Packaging.Test/Core/comparers/PackageDependencyInfoComparerTests.cs | huangqinjin/NuGet.Client | 680f9bd4e97db7cd7482584276886764de69d3cb | [
"Apache-2.0"
] | 2,611 | 2015-09-30T18:03:24.000Z | 2022-03-31T23:55:33.000Z | test/NuGet.Core.Tests/NuGet.Packaging.Test/Core/comparers/PackageDependencyInfoComparerTests.cs | huangqinjin/NuGet.Client | 680f9bd4e97db7cd7482584276886764de69d3cb | [
"Apache-2.0"
] | 765 | 2015-04-06T14:53:51.000Z | 2022-03-30T22:36:38.000Z | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Linq;
using NuGet.Packaging.Core;
using NuGet.Shared;
using NuGet.Versioning;
using Xunit;
namespace NuGet.Packaging.Tests
{
public class PackageDependencyInfoComparerTests
{
private static readonly PackageDependencyInfoComparer Comparer = PackageDependencyInfoComparer.Default;
private static readonly NuGetVersion Version100 = NuGetVersion.Parse("1.0.0");
private static readonly PackageIdentity PackageIdentity = new PackageIdentity(id: "a", Version100);
private static readonly PackageDependencyInfo DependencyInfoA = new PackageDependencyInfo(
PackageIdentity,
new PackageDependency[] { new PackageDependency(id: "c") });
[Fact]
public void Constructor_WhenIdentityComparerIsNull_Throws()
{
ArgumentNullException exception = Assert.Throws<ArgumentNullException>(
() => new PackageDependencyInfoComparer(
identityComparer: null,
PackageDependencyComparer.Default));
Assert.Equal("identityComparer", exception.ParamName);
}
[Fact]
public void Constructor_WhenDependencyComparerIsNull_Throws()
{
ArgumentNullException exception = Assert.Throws<ArgumentNullException>(
() => new PackageDependencyInfoComparer(
PackageIdentityComparer.Default,
dependencyComparer: null));
Assert.Equal("dependencyComparer", exception.ParamName);
}
[Fact]
public void Default_Always_ReturnsSameInstance()
{
PackageDependencyInfoComparer instance0 = PackageDependencyInfoComparer.Default;
PackageDependencyInfoComparer instance1 = PackageDependencyInfoComparer.Default;
Assert.Same(instance0, instance1);
}
[Fact]
public void Equals_WhenArgumentsAreNull_ReturnsTrue()
{
Assert.True(Comparer.Equals(x: null, y: null));
}
[Fact]
public void Equals_WhenArgumentsAreSame_ReturnsTrue()
{
Assert.True(Comparer.Equals(DependencyInfoA, DependencyInfoA));
}
[Fact]
public void Equals_WhenArgumentsAreEqual_ReturnsTrue()
{
var dependencyInfoA1 = new PackageDependencyInfo(PackageIdentity, DependencyInfoA.Dependencies);
Assert.True(Comparer.Equals(DependencyInfoA, dependencyInfoA1));
}
[Fact]
public void Equals_WhenOneArgumentIsNull_ReturnsFalse()
{
Assert.False(Comparer.Equals(DependencyInfoA, y: null));
Assert.False(Comparer.Equals(x: null, DependencyInfoA));
}
[Fact]
public void Equals_WhenArgumentsHaveUnequalVersion_ReturnsFalse()
{
var dependencyInfoA1 = new PackageDependencyInfo(
new PackageIdentity(DependencyInfoA.Id, NuGetVersion.Parse("2.0.0")),
DependencyInfoA.Dependencies);
Assert.False(Comparer.Equals(DependencyInfoA, dependencyInfoA1));
}
[Fact]
public void Equals_WhenArgumentsHaveUnequalDependencies_ReturnsFalse()
{
var dependencyInfoA1 = new PackageDependencyInfo(
PackageIdentity,
new[] { new PackageDependency(id: "d") });
Assert.False(Comparer.Equals(DependencyInfoA, dependencyInfoA1));
}
[Fact]
public void Equals_WhenArgumentsHaveUnequalPackageIds_ReturnsFalse()
{
var dependencyInfoB = new PackageDependencyInfo(
new PackageIdentity(id: "b", DependencyInfoA.Version),
DependencyInfoA.Dependencies);
Assert.False(Comparer.Equals(DependencyInfoA, dependencyInfoB));
}
[Fact]
public void GetHashCode_WhenArgumentIsNull_ReturnsZero()
{
int hashCode = Comparer.GetHashCode(obj: null);
Assert.Equal(0, hashCode);
}
[Fact]
public void GetHashCode_WhenArgumentIsValid_ReturnsHashCode()
{
var combiner = new HashCodeCombiner();
combiner.AddObject(PackageIdentityComparer.Default.GetHashCode(DependencyInfoA));
combiner.AddObject(DependencyInfoA.Dependencies.First());
int expectedResult = combiner.CombinedHash;
int actualResult = Comparer.GetHashCode(DependencyInfoA);
Assert.Equal(expectedResult, actualResult);
}
}
}
| 35.481203 | 111 | 0.652045 |
2d36f6ed0036caf6848cb3e49f55501979d85700 | 1,969 | css | CSS | in_class/week_3/homework/style.css | stasysiia/SMC_WEBDES3_SPRING21 | 15280f2a4943b7ebc03d48a9eb48a7434a2c0e69 | [
"CC0-1.0"
] | 2 | 2021-03-22T17:46:33.000Z | 2022-02-10T07:11:43.000Z | in_class/week_3/homework/style.css | stasysiia/SMC_WEBDES3_SPRING21 | 15280f2a4943b7ebc03d48a9eb48a7434a2c0e69 | [
"CC0-1.0"
] | null | null | null | in_class/week_3/homework/style.css | stasysiia/SMC_WEBDES3_SPRING21 | 15280f2a4943b7ebc03d48a9eb48a7434a2c0e69 | [
"CC0-1.0"
] | 1 | 2021-04-01T07:58:25.000Z | 2021-04-01T07:58:25.000Z | .fr {
float: right;
}
h1,h2{
text-align: center;
padding-top: 16px;
}
h1{
color: rgb(255, 255, 245);
}
.featurette-heading, .lead {
padding: 16px;
}
.navbar-brand {
font-size: 1.9em;
}
.catcafe{
position: relative;
background: url(img/coffeecats.jpg) 100% -400px;
background-position-x: center;
height: 100vh;
}
.row{
--bs-gutter-x: 0rem;
background: #fff;
}
.table{
margin: 30px 0 110px 0;
}
.table-dark {
--bs-table-bg: #343a40;
--bs-table-striped-bg: #3e444a;
--bs-table-striped-color: #fff;
--bs-table-active-bg: #484e53;
--bs-table-active-color: #fff;
--bs-table-hover-bg: #43494e;
--bs-table-hover-color: #fff;
color: #fff;
border-color: #484e53;
}
#monmon, #boosboos {
background: url(img/catcup.jpg) repeat-x;
padding: 80px 16px 0 16px;
max-width: 1470px !important;
}
.socials {
display: block;
margin: 8px !important;
}
.socials li {
display: inline-block;
margin-right: 1.8rem;
}
#steams {
width: 1470px !important;
max-width: 1470px;
right: 2%;
top: 40%;
position: relative;
}
.steam {
width: 2px;
height: 120px;
background: white;
position: absolute;
top: 50%;
animation: waft 2.2s linear infinite;
filter: blur(6px);
}
.steam-1 {
right: 0px;
}
.steam-2 {
right: 40px;
}
.steam-3 {
right: 80px;
}
@keyframes waft {
0% {
transform: translate3d(0, 0, 0) scale(1);
opacity: 1;
}
100% {
transform: translate3d(0, -240px, 0) scale(3);
opacity: 0;
}
}
@media (min-width:1680px) {
#steams {
max-width: 1670px;
right: unset;
left: 7%;
top: 40%;
position: relative;
}
}
@media (max-width:1679px) {
#steams {
width: 1470px;
max-width: 1470px;
right: 2%;
top: 40%;
position: relative;
}
}
@media (max-width:1299px) {
#steams {
display: none;
}
}
@media (max-width:600px) {
.catcafe{
background-position-x: 860px !important;
}
#monmon, #boosboos {
background-position-x: -30px;
}
} | 16.408333 | 50 | 0.610462 |
8ede0f1af16fa031492510a84b8fc8b8db25c916 | 3,562 | rs | Rust | src/main.rs | tstellanova/rusty_rpi_powerbutt | 622545f57a7d2199b002143d44368f25b57bf8cb | [
"BSD-3-Clause"
] | null | null | null | src/main.rs | tstellanova/rusty_rpi_powerbutt | 622545f57a7d2199b002143d44368f25b57bf8cb | [
"BSD-3-Clause"
] | null | null | null | src/main.rs | tstellanova/rusty_rpi_powerbutt | 622545f57a7d2199b002143d44368f25b57bf8cb | [
"BSD-3-Clause"
] | null | null | null | extern crate pigrust;
extern crate runas;
extern crate rpi3_firmware_access;
use pigrust::board_control::*;
use std::thread::sleep;
use std::time::Duration;
use runas::Command;
// We use pigpio to generate and monitor signals on GPIO pins
// the pins where the power LED and switch are attached
const LED_GPIO_PIN: u32 = 18;
const BUTT_IN_PIN: u32 = 17;
const PWM_FULL_RANGE: u32 = 1000;
const LED_PWM_FREQ_HZ: u32 = 2000;
const FADE_STEP_DELAY_MS: u64 = 100;
const FADE_STEPS: u32 = 12;
const FADE_STEP_VAL: u32 = (PWM_FULL_RANGE / FADE_STEPS);
trait GpioLedTricks {
fn setup_led_pin(&self);
fn led_on(&self, duration_secs: u32);
fn led_off(&self, duration_secs: u32);
fn fade_led_down(&self, pin: u32 );
fn fade_led_up(&self, pin: u32 );
fn led_fade_cycle(&self, count: u32);
}
impl GpioLedTricks for BoardController {
fn setup_led_pin(&self) {
self.set_gpio_mode(LED_GPIO_PIN, GpioMode::Output);
}
fn led_on(&self, duration_secs: u32) {
// the LED safety switch we're using is already tied to +VDC: set GPIO pin low to turn on
self.gpio_write(LED_GPIO_PIN, 0);
sleep(Duration::from_secs(duration_secs as u64));
}
fn led_off(&self, duration_secs: u32) {
// the LED safety switch I'm using is already tied to +VDC: set GPIO pin high to turn off
self.gpio_write(LED_GPIO_PIN, 1);
sleep(Duration::from_secs(duration_secs as u64));
}
fn fade_led_down(&self, pin: u32 ) {
self.set_pwm_frequency(pin, LED_PWM_FREQ_HZ);
self.set_pwm_range(pin, PWM_FULL_RANGE); // Set range to 1000. 1 range = 2 us;
for x in 0..FADE_STEPS {
let duty_cycle = x * FADE_STEP_VAL;
self.set_pwm_dutycycle(pin, duty_cycle);
sleep(Duration::from_millis(FADE_STEP_DELAY_MS))
}
}
fn fade_led_up(&self, pin: u32) {
self.set_pwm_frequency(pin, LED_PWM_FREQ_HZ);
self.set_pwm_range(pin, PWM_FULL_RANGE); // Set range to 1000. 1 range = 2 us;
for x in 0..FADE_STEPS {
let duty_cycle = PWM_FULL_RANGE - x * FADE_STEP_VAL;
self.set_pwm_dutycycle(pin, duty_cycle);
sleep(Duration::from_millis(FADE_STEP_DELAY_MS))
}
}
fn led_fade_cycle(&self, count: u32) {
for _x in 0..count {
self.fade_led_up( LED_GPIO_PIN);
self.fade_led_down( LED_GPIO_PIN);
}
}
}//GpioLedTricks for BoardController
fn perform_shutdown() {
println!("shutting down...");
let status = Command::new("shutdown").arg("-h").arg("now").status().expect("failed to shut down!");
//it's unlikely the following will ever be printed
println!("shutdown exited with: {}", status);
}
#[no_mangle]
pub extern fn butt_press_cb_fn(_daemon_id: i32, gpio: u32, _level: u32, _tick: u32, _userdata: u32 ) {
if BUTT_IN_PIN == gpio {
println!("Shutdown button pressed!");
perform_shutdown();
}
}
fn main() {
let bc = BoardController::new();
println!("Initialized pigpiod. ");
// GPIO 17 set up as an input, pulled down, connected to 3V3 on button press
bc.set_gpio_mode(BUTT_IN_PIN, GpioMode::Input);
bc.set_pull_up_down(BUTT_IN_PIN, GpioPullOption::Down);
// setup pigpio waiting for the input GPIO pin to change
bc.add_edge_detector_closure(BUTT_IN_PIN, GpioEdgeDetect::FallingEdge,
|gpio, level| {
println!("main closure! with {} {} ", gpio, level);
perform_shutdown();
}
);
bc.setup_led_pin();
loop {
bc.led_fade_cycle(1);
let val = rpi3_firmware_access::utils::get_power_status();
if 1 != val {
println!("shutting down on low power!");
perform_shutdown();
}
}
}
| 27.4 | 102 | 0.686131 |
f441934cdc0a609c6f75b9b2e30d76b9d19d3f0c | 45 | ts | TypeScript | src/domain/medical-record/controllers/index.ts | vinhmai159/BookingCare | ff1d2e034f37ed8162a2aaa3ccf7fd1d9bc7a81c | [
"MIT"
] | 1 | 2020-11-11T14:31:05.000Z | 2020-11-11T14:31:05.000Z | src/domain/medical-record/controllers/index.ts | vinhmai159/BookingCare | ff1d2e034f37ed8162a2aaa3ccf7fd1d9bc7a81c | [
"MIT"
] | 2 | 2021-08-31T04:31:51.000Z | 2022-01-22T12:50:29.000Z | src/domain/medical-record/controllers/index.ts | vinhmai159/BookingCare | ff1d2e034f37ed8162a2aaa3ccf7fd1d9bc7a81c | [
"MIT"
] | null | null | null | export * from './medical-record.controller';
| 22.5 | 44 | 0.733333 |
57e4ed4b34fcfac6ec6183cb5693acd50d9917fe | 1,118 | php | PHP | resources/views/admin/user.blade.php | Sefira09/EAS_PTW_0149-0180 | fea0645e2697d664642ca6d9ce606c1fd1766d37 | [
"MIT"
] | null | null | null | resources/views/admin/user.blade.php | Sefira09/EAS_PTW_0149-0180 | fea0645e2697d664642ca6d9ce606c1fd1766d37 | [
"MIT"
] | null | null | null | resources/views/admin/user.blade.php | Sefira09/EAS_PTW_0149-0180 | fea0645e2697d664642ca6d9ce606c1fd1766d37 | [
"MIT"
] | null | null | null | @extends('admin.layout')
@section('badan')
<div id="konten">
<div class="col-12 col-m-12">
<h2>User</h2>
<table class="table table-striped" style="width: 100%">
<thead>
<tr>
<th scope="col">No</th>
<th scope="col">Nama</th>
<th scope="col">Email</th>
<th scope="col">Alamat</th>
<th scope="col">Telepon</th>
<th scope="col">Opsi</th>
</tr>
</thead>
<tbody>
<?php $no = 1; ?>
@foreach($user as $u)
<tr>
<td>{{$no++}}</td>
<td>{{$u->name}}</td>
<td>{{$u->email}}</td>
<td>{{$u->alamat}}</td>
<td>{{$u->telp}}</td>
<td><a href="/admin/user/hapus/{{$u->id}}"><button type="button" class="btn btn-danger">Hapus</button></a></td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
@endsection | 32.882353 | 131 | 0.360465 |
daa89212ce9ab153efb205d65aef26fd04c0255e | 1,472 | php | PHP | src/Ray/SoapWatcher.php | baueri/Soap | 8b14a922b48cbf627dff98954ebf0c34b653ad19 | [
"MIT"
] | 316 | 2020-12-02T17:08:02.000Z | 2022-03-25T08:27:20.000Z | src/Ray/SoapWatcher.php | baueri/Soap | 8b14a922b48cbf627dff98954ebf0c34b653ad19 | [
"MIT"
] | 29 | 2021-03-23T06:05:32.000Z | 2022-03-25T03:21:26.000Z | src/Ray/SoapWatcher.php | baueri/Soap | 8b14a922b48cbf627dff98954ebf0c34b653ad19 | [
"MIT"
] | 21 | 2021-03-25T16:55:01.000Z | 2022-02-15T10:07:20.000Z | <?php
namespace RicorocksDigitalAgency\Soap\Ray;
use RicorocksDigitalAgency\Soap\Facades\Soap;
use RicorocksDigitalAgency\Soap\Request\Request;
use RicorocksDigitalAgency\Soap\Response\Response;
use Spatie\LaravelRay\Ray;
use Spatie\LaravelRay\Watchers\Watcher;
use Spatie\Ray\Ray as SpatieRay;
class SoapWatcher extends Watcher
{
public function register(): void
{
SpatieRay::macro('showSoapRequests', fn () => app(SoapWatcher::class)->enable());
SpatieRay::macro('stopShowingSoapRequests', fn () => app(SoapWatcher::class)->disable());
Soap::afterRequesting(
function ($request, $response) {
if (!app(SoapWatcher::class)->enabled()) {
return;
}
$this->handleRequest($request, $response);
}
);
}
protected function handleRequest(Request $request, Response $response)
{
app(Ray::class)->table(
[
'Endpoint' => $request->getEndpoint(),
'Method' => $request->getMethod(),
'Headers' => $this->headers($request),
'Request' => $request->getBody(),
'Response' => $response->response,
],
'SOAP'
);
}
protected function headers(Request $request)
{
return $request->getHeaders()
? collect($request->getHeaders())->map->toArray()->toArray()
: [];
}
}
| 28.862745 | 97 | 0.568614 |
ed517b06af6e2d956cba8be63617201741826133 | 495 | swift | Swift | ObjectiveCBridgeableExample/ObjectiveCBridgeableExample/AppDelegate.swift | dmoroz0v/ObjectiveCBridgeableExample | 418a058da699fb537e5ad68900fb237f57777ec7 | [
"MIT"
] | null | null | null | ObjectiveCBridgeableExample/ObjectiveCBridgeableExample/AppDelegate.swift | dmoroz0v/ObjectiveCBridgeableExample | 418a058da699fb537e5ad68900fb237f57777ec7 | [
"MIT"
] | null | null | null | ObjectiveCBridgeableExample/ObjectiveCBridgeableExample/AppDelegate.swift | dmoroz0v/ObjectiveCBridgeableExample | 418a058da699fb537e5ad68900fb237f57777ec7 | [
"MIT"
] | null | null | null | //
// AppDelegate.swift
// ObjectiveCBridgeableExample
//
// Created by Denis Morozov on 02.10.17.
// Copyright © 2017 Denis Morozov. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let a = ModelA(s: "1")
Helper.foo(a as DMZModelA)
return true
}
}
| 19.8 | 141 | 0.743434 |
57f33304791d0195055d434ad0fbefcb593c90b7 | 186 | php | PHP | app/deliveryplace.php | mrwho95/vegefoodsProject | 82222ac23365ee5ec823586a8d10f1ec50a59689 | [
"MIT"
] | null | null | null | app/deliveryplace.php | mrwho95/vegefoodsProject | 82222ac23365ee5ec823586a8d10f1ec50a59689 | [
"MIT"
] | 6 | 2021-02-02T19:26:45.000Z | 2022-02-27T06:22:57.000Z | app/deliveryplace.php | mrwho95/vegefoodsProject | 82222ac23365ee5ec823586a8d10f1ec50a59689 | [
"MIT"
] | null | null | null | <?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class deliveryplace extends Model
{
//
protected $fillable = ['city', 'state', 'postcode', 'country', 'price'];
}
| 15.5 | 76 | 0.672043 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.