hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
a9fda78a974b10f3cebe9b0768c1cf5953e90f7d
18,530
php
PHP
src/Kernel/Support/AcpService.php
ileapy/upsdk
0e3d02ab38a2037eb2d77672480a6fe5809b051d
[ "MIT" ]
12
2021-08-16T13:23:57.000Z
2022-03-15T07:12:49.000Z
src/Kernel/Support/AcpService.php
ileapy/upsdk
0e3d02ab38a2037eb2d77672480a6fe5809b051d
[ "MIT" ]
null
null
null
src/Kernel/Support/AcpService.php
ileapy/upsdk
0e3d02ab38a2037eb2d77672480a6fe5809b051d
[ "MIT" ]
1
2021-08-23T12:28:22.000Z
2021-08-23T12:28:22.000Z
<?php /** * User: cfn <cfn@leapy.cn> * Datetime: 2021/8/18 9:02 * Copyright: php */ namespace unionpay\Kernel\Support; /** * Class AcpService * * @package unionpay\Kernel\Support */ class AcpService { /** * 取得备份文件名 * @param string $path 文件地址 * @return string * @author cfn <cfn@leapy.cn> * @date 2021/8/18 10:33 */ public static function getBackupFileName($path) { $i = strrpos($path, "."); $leftFileName = substr($path, 0, $i); $rightFileName = substr($path, $i + 1); return $leftFileName . '_backup.' . $rightFileName; } /** * 对数组排序 * @param array $params * @return array * @author cfn <cfn@leapy.cn> * @date 2021/8/18 10:49 */ public static function argSort($params) { ksort ($params); reset ($params); return $params; } /** * 将数组转换为 string * @param array $params 待转换数组 * @param bool $sort 是否需要排序 * @param bool $encode 是否需要URL编码 * @return string */ public static function createLinkString($params, $sort, $encode) { if($params == NULL || !is_array($params)) return ""; $linkString = ""; if ($sort) $params = self::argSort($params); foreach ($params as $key => $value) { if ($encode) $value = urlencode($value); $linkString .= $key . "=" . $value . "&"; } return substr($linkString,0,-1); } /** * @param $temp * @param $isKey * @param $key * @param $result * @param $needUrlDecode * @return false|void * @author cfn <cfn@leapy.cn> * @date 2021/8/18 11:27 */ static function putKeyValueToDictionary($temp, $isKey, $key, &$result, $needUrlDecode) { if ($isKey) { $key = $temp; if (strlen ( $key ) == 0) { return false; } $result [$key] = ""; } else { if (strlen ( $key ) == 0) { return false; } if ($needUrlDecode) $result [$key] = urldecode ( $temp ); else $result [$key] = $temp; } } /** * key1=value1&key2=value2转array * @param string $str key1=value1&key2=value2的字符串 * @param bool $needUrlDecode 是否需要解url编码,默认不需要 * @return array */ static function parseQString($str, $needUrlDecode = false) { $result = array(); $len = strlen($str); $temp = ""; $key = ""; $isKey = true; $isOpen = false; $openName = "\0"; for($i=0; $i<$len; $i++){ $curChar = $str[$i]; if($isOpen){ if($curChar == $openName){ $isOpen = false; } $temp .= $curChar; } elseif ($curChar == "{"){ $isOpen = true; $openName = "}"; $temp .= $curChar; } elseif ($curChar == "["){ $isOpen = true; $openName = "]"; $temp .= $curChar; } elseif ($isKey && $curChar == "="){ $key = $temp; $temp = ""; $isKey = false; } elseif ($curChar == "&"){ self::putKeyValueToDictionary($temp, $isKey, $key, $result, $needUrlDecode); $temp = ""; $isKey = true; } else { $temp .= $curChar; } } self::putKeyValueToDictionary($temp, $isKey, $key, $result, $needUrlDecode); return $result; } /** * 更新证书 * @param array $params 报文参数 * @param string $encryptCertPath 加密证书路径 * @return int * @author cfn <cfn@leapy.cn> * @date 2021/8/18 10:35 * @throws \Exception */ public static function updateEncryptCert(&$params, $encryptCertPath) { // 取得证书 $strCert = $params['encryptPubKeyCert']; $certType = $params['certType']; openssl_x509_read($strCert); $certInfo = openssl_x509_parse($strCert); if($certType === "01") { // 更新敏感信息加密公钥 if (CertUtil::getEncryptCertId($encryptCertPath) != $certInfo['serialNumber']) { $newFileName = self::getBackupFileName($encryptCertPath); // 将原证书备份重命名 备份失败返回 -1 if(!copy($encryptCertPath, $newFileName)) return -1; // 更新证书 失败返回 -1 if(!file_put_contents($encryptCertPath, $strCert)) return -1; // 更新成功 return 1; } // 无需更新 return 0; } else if($certType === "02") { // 无需更新 return 0; } else { // 未知证书状态 return -1; } } /** * 签名 * @param array $params 待签名数据 * @param string $signCertPath 签名证书路径 * @param string $signCertPwd 签名证书密码 * @param string $secureKey 使用密钥签名 * @return bool * @throws \Exception */ static function sign(&$params, $signCertPath = "", $signCertPwd = "", $secureKey = "") { return $params['signMethod'] =='01' ? AcpService::signByCertInfo($params, $signCertPath, $signCertPwd) : AcpService::signBySecureKey($params, $secureKey); } /** * 证书加签 * @param array $params 待签名数据 * @param string $certPath 签名证书路径 * @param string $certPwd 签名证书密码 * @return bool * @throws \Exception * @author cfn <cfn@leapy.cn> * @date 2021/8/18 10:47 */ static function signByCertInfo(&$params, $certPath, $certPwd) { if(isset($params['signature'])) unset($params['signature']); if($params['signMethod']=='01') { //证书ID $params['certId'] = CertUtil::getSignCertIdFromPfx($certPath, $certPwd); $private_key = CertUtil::getSignKeyFromPfx($certPath, $certPwd ); // 转换成key=val&串 $params_str = self::createLinkString($params, true, false); if($params['version']=='5.0.0') { $params_sha1x16 = sha1($params_str,FALSE); // 签名 $result = openssl_sign($params_sha1x16,$signature, $private_key,OPENSSL_ALGO_SHA1); if ($result) { $signature_base64 = base64_encode($signature); $params['signature'] = $signature_base64; return true; } } else if($params['version']=='5.1.0') { //sha256签名摘要 $params_sha256x16 = hash('sha256', $params_str); // 签名 $result = openssl_sign($params_sha256x16,$signature, $private_key,'sha256'); if ($result) { $signature_base64 = base64_encode($signature); $params['signature'] = $signature_base64; return true; } } } return false; } /** * 密钥加签 * @param array $params 待签名数据 * @param string $secureKey 签名证书路径 * @return bool * @throws \Exception * @author cfn <cfn@leapy.cn> * @date 2021/8/18 10:58 */ static function signBySecureKey(&$params, $secureKey) { if($secureKey == null || trim($secureKey) == '') throw new \Exception('未配置密钥,签名失败'); if($params['signMethod']=='11') { // 转换成key=val&串 $params_str = self::createLinkString($params,true,false); $params_before_sha256 = hash('sha256', $secureKey); $params_before_sha256 = $params_str.'&'.$params_before_sha256; $params_after_sha256 = hash('sha256',$params_before_sha256); $params ['signature'] = $params_after_sha256; return true; } else if($params['signMethod']=='12') { //TODO SM3 throw new \Exception('signMethod=12未实现'); } else { throw new \Exception("signMethod不正确"); } } /** * 验签 * @param array $params 验签报文数据 * @param string $certDir 证书目录 * @param string $middleCertPath 验签中级证书 * @param string $rootCertPath * @param bool $ifValidateCNName 是否验证验签证书的CN * @param string $secureKey 密钥 * @return bool|int * @author cfn <cfn@leapy.cn> * @date 2021/8/18 11:22 * @throws \Exception */ static function validate($params, $certDir = "", $middleCertPath = "", $rootCertPath = "", $ifValidateCNName = true, $secureKey = "") { $signature_str = $params['signature']; unset($params['signature']); if($params['signMethod']=='01') { $params_str = self::createLinkString($params,true,false ); if($params['version']=='5.0.0') { // 公钥 $public_key = CertUtil::getVerifyCertByCertId($params['certId'], $certDir); $signature = base64_decode($signature_str); $params_sha1x16 = sha1($params_str,FALSE); $isSuccess = openssl_verify($params_sha1x16, $signature, $public_key,OPENSSL_ALGO_SHA1); } else if($params['version']=='5.1.0') { $strCert = $params['signPubKeyCert']; $strCert = CertUtil::verifyAndGetVerifyCert($strCert, $middleCertPath, $rootCertPath, $ifValidateCNName); if($strCert == null) throw new \Exception("validate cert err: " . $params["signPubKeyCert"]); else { $params_sha256x16 = hash('sha256', $params_str); $signature = base64_decode($signature_str); $isSuccess = openssl_verify($params_sha256x16, $signature, $strCert,"sha256"); } } else { $isSuccess = false; } } else { $isSuccess = AcpService::validateBySecureKey($params, $secureKey); } return $isSuccess; } /** * @param array $params * @param string $secureKey * @return bool * @throws \Exception * @author cfn <cfn@leapy.cn> * @date 2021/8/18 11:24 */ static function validateBySecureKey($params, $secureKey) { if($secureKey == null || trim($secureKey) == '') throw new \Exception('密钥没配,验签失败'); $signature_str = $params['signature']; unset($params['signature']); $params_str = self::createLinkString($params,true,false ); if($params['signMethod']=='11') { $params_before_sha256 = hash('sha256', $secureKey); $params_before_sha256 = $params_str.'&'.$params_before_sha256; $params_after_sha256 = hash('sha256',$params_before_sha256); return $params_after_sha256 == $signature_str; } else if($params['signMethod']=='12') { //TODO SM3 throw new \Exception('signMethod=12未实现'); } else { throw new \Exception("signMethod不正确"); } } /** * @param string $jsonData json格式数据,例如:{"sign" : "J6rPLClQ64szrdXCOtV1ccOMzUmpiOKllp9cseBuRqJ71pBKPPkZ1FallzW18gyP7CvKh1RxfNNJ66AyXNMFJi1OSOsteAAFjF5GZp0Xsfm3LeHaN3j/N7p86k3B1GrSPvSnSw1LqnYuIBmebBkC1OD0Qi7qaYUJosyA1E8Ld8oGRZT5RR2gLGBoiAVraDiz9sci5zwQcLtmfpT5KFk/eTy4+W9SsC0M/2sVj43R9ePENlEvF8UpmZBqakyg5FO8+JMBz3kZ4fwnutI5pWPdYIWdVrloBpOa+N4pzhVRKD4eWJ0CoiD+joMS7+C0aPIEymYFLBNYQCjM0KV7N726LA==", "data" : "pay_result=success&tn=201602141008032671528&cert_id=68759585097"} * @param string $certDir 证书目录 * @throws \Exception * @deprecated 5.1.0开发包已删除此方法,请直接参考5.1.0开发包中的VerifyAppData.php验签 对控件支付成功返回的结果信息中data域进行验签 * @return false|int * @author cfn <cfn@leapy.cn> * @date 2021/8/18 11:32 * @throws \Exception */ static function validateAppResponse($jsonData, $certDir) { $data = json_decode($jsonData); $sign = $data->sign; $data = $data->data; $dataMap = self::parseQString($data); $public_key = CertUtil::getVerifyCertByCertId($dataMap['cert_id'], $certDir); $signature = base64_decode($sign); $params_sha1x16 = sha1($data,FALSE ); return openssl_verify($params_sha1x16, $signature, $public_key,OPENSSL_ALGO_SHA1); } /** * @param array $params 参数 * @param string $reqUrl 提交地址 * @return string * @author cfn <cfn@leapy.cn> * @date 2021/8/18 11:34 */ static function createAutoFormHtml($params, $reqUrl) { $encodeType = isset($params['encoding']) ? $params['encoding'] : 'UTF-8'; $html = <<<eot <html> <head> <meta http-equiv="Content-Type" content="text/html; charset={$encodeType}" /> </head> <body onload="javascript:document.pay_form.submit();"> <form id="pay_form" name="pay_form" action="{$reqUrl}" method="post"> eot; foreach ($params as $key => $value) { $html .= " <input type=\"hidden\" name=\"{$key}\" id=\"{$key}\" value=\"{$value}\" />\n"; } $html .= <<<eot </form> </body> </html> eot; return $html; } /** * @param array $customerInfo * @return string * @author cfn <cfn@leapy.cn> * @date 2021/8/18 11:35 */ static function getCustomerInfo($customerInfo) { if($customerInfo == null || count($customerInfo) == 0) return ""; return base64_encode("{" . self::createLinkString($customerInfo,false,false ) . "}"); } /** * map转换string,敏感信息加密 * @param array $customerInfo * @param string $encryptCertPath * @return string * @author cfn <cfn@leapy.cn> * @date 2021/8/18 11:36 * @throws \Exception */ static function getCustomerInfoWithEncrypt($customerInfo, $encryptCertPath) { if($customerInfo == null || count($customerInfo) == 0) return ""; $encryptedInfo = array(); foreach ($customerInfo as $key => $value) { if ($key == 'phoneNo' || $key == 'cvn2' || $key == 'expired') { $encryptedInfo[$key] = $value; unset ($customerInfo[$key]); } } if(count($encryptedInfo) > 0) { $encryptedInfo = self::createLinkString($encryptedInfo,false,false); $encryptedInfo = AcpService::encryptData($encryptedInfo, $encryptCertPath); $customerInfo['encryptedInfo'] = $encryptedInfo; } return base64_encode("{" . self::createLinkString($customerInfo,false,false) . "}"); } /** * 解析customerInfo。 为方便处理,encryptedInfo下面的信息也均转换为customerInfo子域一样方式处理, * @param string $customerInfostr * @return array 形式ParseCustomerInfo * @return mixed * @author cfn <cfn@leapy.cn> * @date 2021/8/18 11:39 * @throws \Exception */ static function parseCustomerInfo($customerInfostr, $certPath, $certPwd) { $customerInfostr = base64_decode($customerInfostr); $customerInfostr = substr($customerInfostr,1,strlen($customerInfostr) - 2); $customerInfo = self::parseQString($customerInfostr); if(array_key_exists("encryptedInfo", $customerInfo)) { $encryptedInfoStr = $customerInfo["encryptedInfo"]; unset($customerInfo["encryptedInfo"] ); $encryptedInfoStr = AcpService::decryptData($encryptedInfoStr, $certPath, $certPwd); $encryptedInfo = self::parseQString($encryptedInfoStr); foreach ($encryptedInfo as $key => $value) $customerInfo[$key] = $value; } return $customerInfo; } /** * @param string $encryptCertPath * @return false * @author cfn <cfn@leapy.cn> * @date 2021/8/18 11:42 * @throws \Exception */ static function getEncryptCertId($encryptCertPath) { return CertUtil::getEncryptCertId($encryptCertPath); } /** * 加密数据 * @param string $data 待加密数据 * @param string $certPath 加密证书配置路径 * @return string * @throws \Exception */ static function encryptData($data, $certPath) { $public_key = CertUtil::getEncryptKey($certPath); openssl_public_encrypt($data,$crypted, $public_key); return base64_encode ($crypted); } /** * 解密数据 * @param $data 待解密数据 * @param $certPath 签名证书路径 * @param $certPwd 签名证书密码 * @return mixed * @throws \Exception */ static function decryptData($data, $certPath, $certPwd) { $data = base64_decode($data); $private_key = CertUtil::getSignKeyFromPfx($certPath, $certPwd); openssl_private_decrypt($data,$crypted, $private_key); return $crypted; } /** * 报文中的文件保存 * @param $params 原始报文 * @param $fileDirectory 要保存的文件路径 * @return bool * @author cfn <cfn@leapy.cn> * @date 2021/8/18 9:17 * @throws \Exception */ static function decodeFileContent($params, $fileDirectory) { if (!isset($params['fileContent'])) throw new \Exception('文件内容为空'); $fileContent = $params ['fileContent']; if (empty($fileContent)) throw new \Exception('文件内容为空'); // 解压缩 $content = gzuncompress(base64_decode($fileContent)); if (empty($params['fileName'])) { $filePath = $fileDirectory . $params ['merId'] . '_' . $params ['batchNo'] . '_' . $params ['txnTime'] . '.txt'; } else { $filePath = $fileDirectory . $params ['fileName']; } $handle = fopen($filePath, "w+"); if (!is_writable($filePath)) throw new \Exception("文件:" . $filePath . "不可写,请检查!"); file_put_contents ($filePath, $content); fclose ($handle); return true; } /** * 功能:将批量文件内容使用DEFLATE压缩算法压缩,Base64编码生成字符串并返回 * 适用到的交易:批量代付,批量代收,批量退货 * @param $path 文件路径 * @return string * @author cfn <cfn@leapy.cn> * @date 2021/8/18 9:09 * @throws \Exception */ static function encodeFileContent($path) { if(!file_exists($path)) throw new \Exception('文件不存在'); $file_content = file_get_contents ($path); //UTF8 去掉文本中的 bom头 $BOM = chr(239).chr(187).chr(191); $file_content = str_replace($BOM,'',$file_content); $file_content_deflate = gzcompress($file_content); return base64_encode ($file_content_deflate); } }
32.85461
477
0.543335
6b675464114bf535783173571ce91c5f7d5bcc85
1,699
cpp
C++
PackageManager/L3dPackageInstaller/PackageSearch.cpp
Loksim3D/loksim3d-source
f36ca426522326fe1befcf5dab932157b1d2d191
[ "MIT" ]
2
2018-02-03T16:06:54.000Z
2019-07-12T09:04:12.000Z
PackageManager/L3dPackageInstaller/PackageSearch.cpp
Loksim3D/loksim3d-source
f36ca426522326fe1befcf5dab932157b1d2d191
[ "MIT" ]
null
null
null
PackageManager/L3dPackageInstaller/PackageSearch.cpp
Loksim3D/loksim3d-source
f36ca426522326fe1befcf5dab932157b1d2d191
[ "MIT" ]
2
2019-04-30T21:06:24.000Z
2019-12-06T09:38:04.000Z
#include "StdAfx.h" #include "PackageSearch.h" #include <KompexSQLiteException.h> #include "DBHelper.h" namespace l3d { namespace packageinstaller { namespace db { using namespace std; using namespace Kompex; PackageSearch::PackageSearch(void) : db(DBHelper::instance().GetOwnDbConnection()) { dbStmt.reset(new SQLiteStatement(db.get())); } PackageSearch::~PackageSearch(void) { } std::vector<DBPackageEntry> PackageSearch::GetAllPackages() { std::vector<DBPackageEntry> ret; try { dbStmt->Sql("SELECT ID, Filename, InstallTimestamp, Readme, Checksum FROM Packages ORDER BY Filename"); while (dbStmt->FetchRow()) { ret.emplace_back(DBPackageEntry(*dbStmt)); } } catch (const SQLiteException& ex) { OutputDebugStringA(ex.GetString().c_str()); } dbStmt->FreeQuery(); return ret; } std::vector<DBPackageEntry> PackageSearch::SearchByText(const std::wstring& txt) { std::vector<DBPackageEntry> ret; dbStmt->Sql( "SELECT ID, Filename, InstallTimestamp, Readme, Checksum FROM Packages " "WHERE Filename LIKE @filename OR Readme LIKE @readme ORDER BY Filename"); dbStmt->BindString16(1, txt.c_str()); dbStmt->BindString16(2, txt.c_str()); while (dbStmt->FetchRow()) { ret.emplace_back(DBPackageEntry(*dbStmt)); } dbStmt->FreeQuery(); return ret; } // Suche anhand GUID std::vector<DBPackageEntry> PackageSearch::GetByGuid(const std::wstring& guid) { dbStmt->Sql("SELECT ID, Filename, InstallTimestamp, Readme, Checksum FROM Packages " "WHERE Checksum = @guid"); dbStmt->BindString16(1, guid.c_str()); std::vector<DBPackageEntry> ret; if (dbStmt->FetchRow()) { ret.emplace_back(DBPackageEntry(*dbStmt)); } dbStmt->FreeQuery(); return ret; } } } }
22.064935
105
0.727487
6a446f0d82e432fe3802226ababee4c68567b091
1,461
swift
Swift
iOS/Circles/View/CircleShape.swift
JacopoMangiavacchi/SwiftUICircle
4ffd2b980f2c4938444abf3b188bf5c4b262906a
[ "MIT" ]
2
2020-02-02T16:32:24.000Z
2021-03-09T09:34:24.000Z
iOS/Circles/View/CircleShape.swift
JacopoMangiavacchi/SwiftUICircle
4ffd2b980f2c4938444abf3b188bf5c4b262906a
[ "MIT" ]
null
null
null
iOS/Circles/View/CircleShape.swift
JacopoMangiavacchi/SwiftUICircle
4ffd2b980f2c4938444abf3b188bf5c4b262906a
[ "MIT" ]
2
2020-06-02T14:09:07.000Z
2020-12-24T08:40:41.000Z
// // CircleShape.swift // Circles // // Created by Jacopo Mangiavacchi on 9/21/19. // Copyright © 2019 Jacopo Mangiavacchi. All rights reserved. // import SwiftUI struct CircleShape: Shape { var pct: Double var circleState: CircleState let speed: (x: Int, y: Int) func drawFigure(scaleX: Double, scaleY: Double) -> Path { return Path { p in p.move(to: CGPoint(x: circleState.x_cos[359] * scaleX, y: circleState.y_sin[359] * scaleY)) var (x, y) = (0.0, 0.0) let pctPositive = pct > 0.0 ? pct : 1.0 for i in 0..<Int(pctPositive*360) { x = circleState.x_cos[(i * speed.x) % 360] * scaleX y = circleState.y_sin[(i * speed.y) % 360] * scaleY p.addLine(to: CGPoint(x: x, y: y)) } if pctPositive < 1.0 { p.addEllipse(in: CGRect(x: x, y: y, width: 5, height: 5)) p.addEllipse(in: CGRect(x: x, y: y, width: 10, height: 10)) } } } func path(in rect: CGRect) -> Path { let bounds = CGRect(x: 0, y: 0, width: 2, height: 2) let scaleX = rect.size.width/bounds.size.width let scaleY = rect.size.height/bounds.size.height return drawFigure(scaleX: Double(scaleX), scaleY: Double(scaleY)) } var animatableData: Double { get { return pct } set { pct = newValue } } }
29.22
103
0.533881
e060eaa115e493697a3a6e1cb8c609ffb6b2917f
1,163
cs
C#
src/IxMilia.Dxf/Entities/Generated/DxfEntityTypeGenerated.cs
oholloway/Dxf
dc0ee1d7f1c2a3c7f7960caeaa35acc9ced7e77f
[ "Apache-2.0" ]
null
null
null
src/IxMilia.Dxf/Entities/Generated/DxfEntityTypeGenerated.cs
oholloway/Dxf
dc0ee1d7f1c2a3c7f7960caeaa35acc9ced7e77f
[ "Apache-2.0" ]
null
null
null
src/IxMilia.Dxf/Entities/Generated/DxfEntityTypeGenerated.cs
oholloway/Dxf
dc0ee1d7f1c2a3c7f7960caeaa35acc9ced7e77f
[ "Apache-2.0" ]
null
null
null
// Copyright (c) IxMilia. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // The contents of this file are automatically generated by a tool, and should not be directly modified. using System; using System.Collections.Generic; using System.Linq; using IxMilia.Dxf.Collections; namespace IxMilia.Dxf.Entities { public enum DxfEntityType { Arc, ArcAlignedText, Attribute, AttributeDefinition, Body, Circle, DgnUnderlay, Dimension, DwfUnderlay, Ellipse, Face, Helix, Image, Insert, Leader, Light, Line, LwPolyline, MLine, ModelerGeometry, MText, Ole2Frame, OleFrame, PdfUnderlay, Point, Polyline, ProxyEntity, Ray, Region, RText, Section, Seqend, Shape, Solid, Spline, Text, Tolerance, Trace, Underlay, Vertex, WipeOut, XLine } }
20.051724
158
0.548581
a3cbbaa652afc8fc2b624e0a5d4fcbb57d259da1
2,098
java
Java
styx-service-common/src/test/java/com/spotify/styx/state/EventConsumerTest.java
Bug-hunting-github/styx
3943c2149f9290e7c130c36df84bc657fc6c7c22
[ "Apache-2.0" ]
254
2016-11-25T16:13:50.000Z
2022-03-31T16:07:01.000Z
styx-service-common/src/test/java/com/spotify/styx/state/EventConsumerTest.java
kunal-kushwaha/styx
817cdc3f95382c4e4e11232e3a2de484de8a2bea
[ "Apache-2.0" ]
889
2016-11-25T16:28:49.000Z
2022-03-30T17:56:51.000Z
styx-service-common/src/test/java/com/spotify/styx/state/EventConsumerTest.java
kunal-kushwaha/styx
817cdc3f95382c4e4e11232e3a2de484de8a2bea
[ "Apache-2.0" ]
46
2016-12-04T00:47:42.000Z
2022-03-18T09:01:40.000Z
/*- * -\-\- * Spotify Styx Service Common * -- * Copyright (C) 2019 Spotify AB * -- * 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.spotify.styx.state; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.verify; import com.spotify.styx.model.SequenceEvent; import java.lang.reflect.Proxy; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class EventConsumerTest { @Mock private EventConsumer eventConsumer1; @Mock private EventConsumer eventConsumer2; @Mock private SequenceEvent event; @Mock private RunState runState; @Test public void fanEvent() { var eventConsumer = EventConsumer.fanEvent(List.of(eventConsumer1, eventConsumer2)); eventConsumer.accept(event, runState); verify(eventConsumer1).accept(event, runState); verify(eventConsumer2).accept(event, runState); } @Test public void tracing() { var eventConsumers = EventConsumer.tracing(List.of(eventConsumer1, eventConsumer2)); assertThat(eventConsumers.size(), is(2)); assertThat(Proxy.isProxyClass(eventConsumers.get(0).getClass()), is(true)); assertThat(Proxy.isProxyClass(eventConsumers.get(1).getClass()), is(true)); eventConsumers.get(0).accept(event, runState); verify(eventConsumer1).accept(event, runState); eventConsumers.get(1).accept(event, runState); verify(eventConsumer2).accept(event, runState); } }
33.301587
88
0.745949
f80afad5f34ddaebc7cfde9e1c7177042b2c037d
171
kt
Kotlin
app/src/main/java/com/shaunhossain/bornomala/ViewModel/AlphabatSelectionViewModel.kt
shaunhossain/Bornomala
948d71cd2be09f8a5f1af479a42a12d6d0c9f830
[ "Apache-2.0" ]
1
2022-01-07T03:55:34.000Z
2022-01-07T03:55:34.000Z
app/src/main/java/com/shaunhossain/bornomala/ViewModel/AlphabatSelectionViewModel.kt
shaunhossain/Bornomala
948d71cd2be09f8a5f1af479a42a12d6d0c9f830
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/shaunhossain/bornomala/ViewModel/AlphabatSelectionViewModel.kt
shaunhossain/Bornomala
948d71cd2be09f8a5f1af479a42a12d6d0c9f830
[ "Apache-2.0" ]
null
null
null
package com.shaunhossain.bornomala.ViewModel import androidx.lifecycle.ViewModel class AlphabatSelectionViewModel : ViewModel() { // TODO: Implement the ViewModel }
21.375
48
0.80117
2495845701056be30fa482f9a39dde15800facca
1,993
php
PHP
app/Services/Translations/JavaScript.php
Redish101/blessing-skin-server
e37891350e5abd83c475ad39291275d6e0723e81
[ "MIT" ]
522
2018-12-05T03:42:30.000Z
2022-03-31T11:52:05.000Z
app/Services/Translations/JavaScript.php
Redish101/blessing-skin-server
e37891350e5abd83c475ad39291275d6e0723e81
[ "MIT" ]
278
2019-02-28T01:28:52.000Z
2022-03-31T04:10:15.000Z
app/Services/Translations/JavaScript.php
Redish101/blessing-skin-server
e37891350e5abd83c475ad39291275d6e0723e81
[ "MIT" ]
123
2019-03-17T03:29:56.000Z
2022-03-30T16:40:06.000Z
<?php namespace App\Services\Translations; use App\Services\Plugin; use App\Services\PluginManager; use Illuminate\Cache\Repository; use Illuminate\Filesystem\Filesystem; class JavaScript { protected Filesystem $filesystem; protected Repository $cache; protected PluginManager $plugins; protected $prefix = 'front-end-trans-'; public function __construct( Filesystem $filesystem, Repository $cache, PluginManager $plugins ) { $this->filesystem = $filesystem; $this->cache = $cache; $this->plugins = $plugins; } public function generate(string $locale): string { $plugins = $this->plugins->getEnabledPlugins(); $sourceFiles = $plugins ->map(fn (Plugin $plugin) => $plugin->getPath()."/lang/$locale/front-end.yml") ->filter(fn ($path) => $this->filesystem->exists($path)); $sourceFiles->push(resource_path("lang/$locale/front-end.yml")); $sourceModified = $sourceFiles->max(fn ($path) => $this->filesystem->lastModified($path)); $compiled = public_path("lang/$locale.js"); $compiledModified = (int) $this->cache->get($this->prefix.$locale, 0); if ($sourceModified > $compiledModified || !$this->filesystem->exists($compiled)) { $translations = trans('front-end'); foreach ($plugins as $plugin) { $translations[$plugin->name] = trans($plugin->namespace.'::front-end'); } $content = 'blessing.i18n = '.json_encode($translations, JSON_UNESCAPED_UNICODE); $this->filesystem->put($compiled, $content); $this->cache->put($this->prefix.$locale, $sourceModified); return url()->asset("lang/$locale.js?t=$sourceModified"); } return url()->asset("lang/$locale.js?t=$compiledModified"); } public function resetTime(string $locale): void { $this->cache->put($this->prefix.$locale, 0); } }
31.634921
98
0.613648
07c76bd4e5bb73f501962fe0b8a1301653ca6036
1,145
sql
SQL
conf/evolutions/default/1.sql
gteranUTC/Producto2acevallo
6275f32224736b901f90ae1153ffeb3ef4bd6270
[ "Apache-2.0" ]
null
null
null
conf/evolutions/default/1.sql
gteranUTC/Producto2acevallo
6275f32224736b901f90ae1153ffeb3ef4bd6270
[ "Apache-2.0" ]
null
null
null
conf/evolutions/default/1.sql
gteranUTC/Producto2acevallo
6275f32224736b901f90ae1153ffeb3ef4bd6270
[ "Apache-2.0" ]
null
null
null
# --- First database schema # --- !Ups create table cliente ( id bigint not null, nombre varchar(255), apellido varchar(255), direccion varchar(255), telefono varchar(255), constraint pk_cliente primary key (id)) ; create table plato ( id bigint not null, nombre varchar(255), tipo varchar(250), precio varchar(250), ingrediente varchar(250), cliente_id bigint, constraint pk_plato primary key (id)) ; create sequence cliente_seq start with 1000; create sequence plato_seq start with 1000; alter table cliente add constraint fk_plato_cliente_1 foreign key (cliente_id) references clinete (id) on delete restrict on update restrict; create index ix_plato_company_1 on plato (cliente_id); # --- !Downs SET REFERENTIAL_INTEGRITY FALSE; drop table if exists cliente; drop table if exists plato; SET REFERENTIAL_INTEGRITY TRUE; drop sequence if exists cliente_seq; drop sequence if exists plato_seq;
26.022727
141
0.619214
ef91168fcf57cd1b6cc1f831fbfaa3ca7a3d02ef
149
lua
Lua
src/main/resources/lua/keys_renewal.lua
luoxn28/redis-lock
77a3bbc2425be9364c7961047902d4ed2d5bc61c
[ "Apache-2.0" ]
4
2018-12-04T01:17:10.000Z
2019-10-09T02:19:47.000Z
src/main/resources/lua/keys_renewal.lua
luoxn28/redis-lock
77a3bbc2425be9364c7961047902d4ed2d5bc61c
[ "Apache-2.0" ]
null
null
null
src/main/resources/lua/keys_renewal.lua
luoxn28/redis-lock
77a3bbc2425be9364c7961047902d4ed2d5bc61c
[ "Apache-2.0" ]
1
2019-07-17T01:08:14.000Z
2019-07-17T01:08:14.000Z
if (redis.call('get', KEYS[1]) == ARGV[1]) then for i, key in pairs(KEYS) do redis.call('expire', key, ARGV[2]) end return true end return false
21.285714
47
0.657718
80c56283bb0445cd18373fef5ef32a623c66a753
40
sql
SQL
src/test/binary_swap/sql/diff_dumps.sql
wapache-org/greenplum-gpdb
79e2bd251c1d27054846f630acd52e7903854829
[ "PostgreSQL", "Apache-2.0" ]
5,535
2015-10-28T01:05:40.000Z
2022-03-30T13:46:53.000Z
src/test/binary_swap/sql/diff_dumps.sql
wapache-org/greenplum-gpdb
79e2bd251c1d27054846f630acd52e7903854829
[ "PostgreSQL", "Apache-2.0" ]
9,369
2015-10-28T07:48:01.000Z
2022-03-31T23:56:42.000Z
src/test/binary_swap/sql/diff_dumps.sql
wapache-org/greenplum-gpdb
79e2bd251c1d27054846f630acd52e7903854829
[ "PostgreSQL", "Apache-2.0" ]
1,800
2015-10-28T01:08:25.000Z
2022-03-29T13:29:36.000Z
\! diff dump_other.sql dump_current.sql
20
39
0.8
383dc5ce6216825f29e6e9dd85007e76d21e7f33
1,929
php
PHP
application/views/admin/includes/sidenav.php
N00bie-to-Github/cheryl_site
03b1c68a9439389645008381ab0351cdd4d95b36
[ "MIT" ]
null
null
null
application/views/admin/includes/sidenav.php
N00bie-to-Github/cheryl_site
03b1c68a9439389645008381ab0351cdd4d95b36
[ "MIT" ]
null
null
null
application/views/admin/includes/sidenav.php
N00bie-to-Github/cheryl_site
03b1c68a9439389645008381ab0351cdd4d95b36
[ "MIT" ]
null
null
null
<div id="layoutSidenav_nav"> <nav class="sb-sidenav accordion sb-sidenav-dark" id="sidenavAccordion"> <div class="sb-sidenav-menu"> <div class="nav"> <div class="sb-sidenav-menu-heading">Navigation</div> <a class="nav-link" href="/admin/home"> <div class="sb-nav-link-icon"><i class="fas fa-tachometer-alt"></i></div> Dashboard </a> <a class="nav-link" href="/" target="_blank"> <div class="sb-nav-link-icon"><i class="fas fa-home"></i></div> Homepage </a> <div class="sb-sidenav-menu-heading">Management</div> <a class="nav-link" href="/admin/users"> <div class="sb-nav-link-icon"><i class="fas fa-users"></i></div> Users </a> <a class="nav-link" href="/admin/images"> <div class="sb-nav-link-icon"><i class="fas fa-image"></i></div> Images </a> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapsePages" aria-expanded="false" aria-controls="collapsePages"> <div class="sb-nav-link-icon"><i class="fas fa-book-open"></i></div> Pages <div class="sb-sidenav-collapse-arrow"><i class="fas fa-angle-down"></i></div> </a> <div class="collapse" id="collapsePages" aria-labelledby="headingTwo" data-parent="#sidenavAccordion"> <nav class="sb-sidenav-menu-nested nav"> <a class="nav-link" href="/admin/pages/home">Home</a> <a class="nav-link" href="/admin/pages/about">About Us</a> </nav> </div> </div> </div> </nav> </div>
50.763158
159
0.479005
1b9fd1903f67cb7546b3b2191194c1484846056a
133
rb
Ruby
spec/support/factories.rb
Ricardonacif/banking_app
c4b68c780aa43c185d4bb827f0df80fb47287080
[ "MIT" ]
null
null
null
spec/support/factories.rb
Ricardonacif/banking_app
c4b68c780aa43c185d4bb827f0df80fb47287080
[ "MIT" ]
null
null
null
spec/support/factories.rb
Ricardonacif/banking_app
c4b68c780aa43c185d4bb827f0df80fb47287080
[ "MIT" ]
null
null
null
FactoryGirl.define do factory :account_repository, class: BankingApp::Repositories::AccountRepository do balance 445 end end
22.166667
84
0.796992
39613a52008ca795e2aa71ff67d9153bfc4fe701
1,619
rs
Rust
src/lexer.rs
aleph-oh/yali-rs
7e589abde49ff17d6c7135ee73d5499756879a42
[ "MIT" ]
null
null
null
src/lexer.rs
aleph-oh/yali-rs
7e589abde49ff17d6c7135ee73d5499756879a42
[ "MIT" ]
null
null
null
src/lexer.rs
aleph-oh/yali-rs
7e589abde49ff17d6c7135ee73d5499756879a42
[ "MIT" ]
null
null
null
//! This module contains a lexer which supports single-line comments. /// Lexes a provided string into individual separated tokens. pub(crate) fn lex<S>(src: S) -> Vec<String> where S: AsRef<str>, { let no_comments = src .as_ref() .replace('(', " ( ") .replace(')', " ) ") .lines() .map(|line| line.split(';').next().unwrap_or("")) .fold(String::new(), |mut acc, next| { acc.push_str(next); acc }); no_comments .split_whitespace() .map(&str::to_string) .collect() } #[cfg(test)] mod tests { use crate::lexer::lex; use serde::{Deserialize, Serialize}; use serde_json; use std::fs::File; use std::path::Path; #[derive(Serialize, Deserialize)] struct LexTestData { input: String, expected: Vec<String>, } fn check<P>(file: P) where P: AsRef<Path>, { let test_file = File::open(file).expect("Failed to open test data file"); let test_data: Vec<LexTestData> = serde_json::from_reader(test_file).expect("Could not parse test data file"); for example in test_data { assert_eq!(lex(example.input), example.expected); } } #[test] fn atom() { assert_eq!(lex("1"), vec!["1"]) } #[test] fn s_expression() { assert_eq!(vec!["(", "+", "1", "1", ")"], lex("(+ 1 1)")) } #[test] fn multiline() { check("./lex_examples/multiline.json") } #[test] fn comments() { check("./lex_examples/comments.json") } }
23.128571
88
0.528721
0a5d6ef6e8a234fcda7ff4bad13d9ce6e604ff64
305
cs
C#
src/WinTenDev.Zizi.Models/Configs/DataDogConfig.cs
WinTenDev/ZiziBot.NET
ddf93262ee633bc51ca25a10e4b9e02595d637cd
[ "MIT" ]
11
2021-05-11T12:56:42.000Z
2021-09-17T14:47:16.000Z
src/WinTenDev.Zizi.Models/Configs/DataDogConfig.cs
WinTenDev/ZiziBot.NET
ddf93262ee633bc51ca25a10e4b9e02595d637cd
[ "MIT" ]
null
null
null
src/WinTenDev.Zizi.Models/Configs/DataDogConfig.cs
WinTenDev/ZiziBot.NET
ddf93262ee633bc51ca25a10e4b9e02595d637cd
[ "MIT" ]
2
2021-06-09T20:22:20.000Z
2021-09-23T00:51:48.000Z
using System.Collections.Generic; namespace WinTenDev.Zizi.Models.Configs; public class DataDogConfig { public bool IsEnabled { get; set; } public string ApiKey { get; set; } public string Host { get; set; } public string Source { get; set; } public List<string> Tags { get; set; } }
25.416667
42
0.685246
8cecb7a0af3e6ce77ab6a5d6aa1d32305eaa242b
1,264
swift
Swift
Ladybug/UiLabelExtension.swift
langyx/Ladybug-Epitech-Intranet-iOS-App
7513df402e4b98ed3d90de1fbf3fb50307578727
[ "Apache-2.0" ]
null
null
null
Ladybug/UiLabelExtension.swift
langyx/Ladybug-Epitech-Intranet-iOS-App
7513df402e4b98ed3d90de1fbf3fb50307578727
[ "Apache-2.0" ]
null
null
null
Ladybug/UiLabelExtension.swift
langyx/Ladybug-Epitech-Intranet-iOS-App
7513df402e4b98ed3d90de1fbf3fb50307578727
[ "Apache-2.0" ]
null
null
null
// // UiLabelExtension.swift // Ladybug // // Created by Yannis Lang on 24/12/2016. // Copyright © 2016 Yannis. All rights reserved. // import Foundation import UIKit extension UILabel { func ApplyGradeColor() -> Void { if self.text != nil { switch self.text! { case "Acquis": self.textColor = UIColor.green break case "A": self.textColor = UIColor.green break case "B": self.textColor = UIColor.yellow break case "C": self.textColor = UIColor.orange break case "D": self.textColor = UIColor.red break case "E": self.textColor = UIColor.red break case "-": self.textColor = UIColor.white self.text = "En cours" default: self.textColor = UIColor.white break } } } func badgeIt(bg_color : UIColor) -> Void { self.sizeToFit() self.backgroundColor = bg_color self.clipsToBounds = true self.layer.cornerRadius = 3 } }
24.784314
49
0.469146
e461e1dbc94f27e0e3fca561035490ac110afd94
2,357
sh
Shell
tests/bash-bats/eosio_uninstall.sh
armoniax/amax.meta.chain
5c16d2b5a520b69e8544c6920c102f208ba69552
[ "MIT" ]
null
null
null
tests/bash-bats/eosio_uninstall.sh
armoniax/amax.meta.chain
5c16d2b5a520b69e8544c6920c102f208ba69552
[ "MIT" ]
null
null
null
tests/bash-bats/eosio_uninstall.sh
armoniax/amax.meta.chain
5c16d2b5a520b69e8544c6920c102f208ba69552
[ "MIT" ]
null
null
null
#!/usr/bin/env bats load helpers/general SCRIPT_LOCATION="scripts/amax_uninstall.sh" TEST_LABEL="[amax_uninstall]" mkdir -p $SRC_DIR mkdir -p $OPT_DIR mkdir -p $VAR_DIR mkdir -p $BIN_DIR mkdir -p $VAR_DIR/log mkdir -p $ETC_DIR mkdir -p $LIB_DIR mkdir -p $MONGODB_LOG_DIR mkdir -p $MONGODB_DATA_DIR # A helper function is available to show output and status: `debug` @test "${TEST_LABEL} > Testing user prompts" { ## No y or no warning and re-prompt run bash -c "echo -e \"\nx\nx\nx\" | ./$SCRIPT_LOCATION" ( [[ "${lines[${#lines[@]}-1]}" == "Please type 'y' for yes or 'n' for no." ]] && [[ "${lines[${#lines[@]}-2]}" == "Please type 'y' for yes or 'n' for no." ]] ) || exit ## All yes pass run bash -c "printf \"y\n%.0s\" {1..100} | ./$SCRIPT_LOCATION" [[ $output =~ " - AMAX Removal Complete" ]] || exit ## First no shows "Cancelled..." run bash -c "echo \"n\" | ./$SCRIPT_LOCATION" [[ "${output##*$'\n'}" =~ "Cancelled AMAX Removal!" ]] || exit ## What would you like to do?" run bash -c "echo \"\" | ./$SCRIPT_LOCATION" [[ "${output##*$'\n'}" =~ "What would you like to do?" ]] || exit } @test "${TEST_LABEL} > Testing executions" { run bash -c "printf \"y\n%.0s\" {1..100} | ./$SCRIPT_LOCATION" [[ "${output[*]}" =~ "Executing: rm -rf" ]] || exit if [[ $ARCH == "Darwin" ]]; then [[ "${output}" =~ "Executing: brew uninstall cmake --force" ]] || exit fi } @test "${TEST_LABEL} > Usage is visible with right interaction" { run ./$SCRIPT_LOCATION -h [[ $output =~ "Usage:" ]] || exit } @test "${TEST_LABEL} > -y" { run ./$SCRIPT_LOCATION -y [[ $output =~ " - AMAX Removal Complete" ]] || exit } @test "${TEST_LABEL} > -i" { run ./$SCRIPT_LOCATION -y -i amaxtest [[ $output =~ .*/amaxtest ]] || exit ([[ ! $output =~ "Library/Application\ Support/amax" ]] && [[ ! $output =~ ".local/share/amax" ]]) || exit [[ ! $output =~ "AMAX Removal Complete" ]] || exit } @test "${TEST_LABEL} > -f" { run bash -c "printf \"y\n%.0s\" {1..100} | ./$SCRIPT_LOCATION -f" ([[ "${output[*]}" =~ "Library/Application\ Support/amax" ]] && [[ "${output[*]}" =~ ".local/share/amax" ]]) && exit [[ $output =~ "AMAX Removal Complete" ]] || exit } rm -rf $SRC_DIR rm -rf $OPT_DIR rm -rf $VAR_DIR rm -rf $BIN_DIR rm -rf $VAR_DIR/log rm -rf $ETC_DIR rm -rf $LIB_DIR rm -rf $MONGODB_LOG_DIR rm -rf $MONGODB_DATA_DIR
32.287671
170
0.588884
8e87d580974dce6e3f7dc6d2561f5d92de48a731
651
js
JavaScript
server.js
Tejaswika/Web-Development
d66aa20cfa289bf6411fd56261deeb7f21cbc2e0
[ "MIT" ]
2
2021-05-29T22:17:28.000Z
2021-06-15T10:37:04.000Z
server.js
shubhagrawal123456/Web-Development
22d57cfdc369aa1db17f06327454c236776e3b8e
[ "MIT" ]
1
2020-10-21T12:59:15.000Z
2020-10-21T12:59:15.000Z
server.js
shubhagrawal123456/Web-Development
22d57cfdc369aa1db17f06327454c236776e3b8e
[ "MIT" ]
null
null
null
const express = require('express'); const bodyParser = require('body-parser'); const port = 8080; const app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.use((req,res,next)=>{ res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PATCH,PUT,DELETE'); res.setHeader('Access-Control-Allow-Headers','Content-Type,Authorization'); next(); }) app.get('/', (req, res) => { res.send('GameOfSource!!!') }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
28.304348
80
0.632873
8d422a7b4648672c3d48248e5c503871542cee6a
61
sh
Shell
doc/manuales/permisos.sh
saltares/grannys-bloodbath
6c124ec77c19d81e81b2325bb633fd0d9c236c60
[ "MIT" ]
1
2018-12-31T12:44:57.000Z
2018-12-31T12:44:57.000Z
doc/manuales/permisos.sh
saltares/grannys-bloodbath
6c124ec77c19d81e81b2325bb633fd0d9c236c60
[ "MIT" ]
null
null
null
doc/manuales/permisos.sh
saltares/grannys-bloodbath
6c124ec77c19d81e81b2325bb633fd0d9c236c60
[ "MIT" ]
1
2018-12-31T12:45:02.000Z
2018-12-31T12:45:02.000Z
cd nombre de la carpeta del juego chmod 777 grannysbloodbath
20.333333
33
0.836066
a3675abd3cb84bc875e96968f30253ec5dd9b4b6
1,512
java
Java
common-dataformat/src/main/java/org/group/jcommon/protobuf/jackson/buildin/deserializers/DurationDeserializer.java
GroupServices/jcommon
157c13444ff061f7001783cfab81f001cee91e92
[ "Unlicense" ]
null
null
null
common-dataformat/src/main/java/org/group/jcommon/protobuf/jackson/buildin/deserializers/DurationDeserializer.java
GroupServices/jcommon
157c13444ff061f7001783cfab81f001cee91e92
[ "Unlicense" ]
null
null
null
common-dataformat/src/main/java/org/group/jcommon/protobuf/jackson/buildin/deserializers/DurationDeserializer.java
GroupServices/jcommon
157c13444ff061f7001783cfab81f001cee91e92
[ "Unlicense" ]
null
null
null
package org.group.jcommon.protobuf.jackson.buildin.deserializers; import java.io.IOException; import java.text.ParseException; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import com.google.protobuf.Duration; import com.google.protobuf.util.Durations; public class DurationDeserializer extends StdDeserializer<Duration> { /** * */ private static final long serialVersionUID = 1L; public DurationDeserializer() { super(Duration.class); } @Override public Duration deserialize(final JsonParser parser, final DeserializationContext context) throws IOException { switch (parser.getCurrentToken()) { case VALUE_STRING: try { return Durations.parse(parser.getText()); } catch (final ParseException e) { throw context.weirdStringException(parser.getText(), Duration.class, e.getMessage()); } default: context.reportWrongTokenException(Duration.class, JsonToken.VALUE_STRING, wrongTokenMessage(context)); // the previous method should have thrown throw new AssertionError(); } } // TODO share this? private static String wrongTokenMessage(final DeserializationContext context) { return "Can not deserialize instance of com.google.protobuf.Duration out of " + context.getParser().currentToken() + " token"; } }
32.869565
118
0.738757
88790f75d3467df2bbef7476dc7d866e855d5f4e
5,003
swift
Swift
C-VIP-S_ArchitectureExample/Base/Implementations/BaseRouter.swift
kingsleyawak/C-VIP-S_ArchitectureExample
77043e730f59490bdd2ff737e75a90ff88b18376
[ "Unlicense" ]
1
2019-04-09T13:20:50.000Z
2019-04-09T13:20:50.000Z
C-VIP-S_ArchitectureExample/Base/Implementations/BaseRouter.swift
kingsleyawak/C-VIP-S_ArchitectureExample
77043e730f59490bdd2ff737e75a90ff88b18376
[ "Unlicense" ]
null
null
null
C-VIP-S_ArchitectureExample/Base/Implementations/BaseRouter.swift
kingsleyawak/C-VIP-S_ArchitectureExample
77043e730f59490bdd2ff737e75a90ff88b18376
[ "Unlicense" ]
null
null
null
// // BaseRouter.swift // C-VIP-S_ArchitectureExample // // Created by Kingsley Edem Awak on 3/27/19. // Copyright © 2019 Kingsley Edem Awak. All rights reserved. // import UIKit class BaseRouter:Router { var rootNavigationController:UINavigationController var activeModules: Set<ModuleReference> = [] private var completions: [UIViewController : BaseCompletion] init(rootNavigationController: UINavigationController) { self.rootNavigationController = rootNavigationController completions = [:] } func present(_ module: Module) { present(module, animated: true) } func present(_ module: Module, animated: Bool) { guard let controller = module.viewToPresent() as? UIViewController else { return } DispatchQueue.main.async { [weak self] in self?.rootNavigationController.present(controller, animated: animated, completion: nil) } addModuleToActiveModules(module: module) } func dismiss(completion: BaseCompletion?) { dismiss(animated: true, completion: nil) } func dismiss(animated: Bool, completion: BaseCompletion?) { DispatchQueue.main.async { [weak self] in self?.rootNavigationController.dismiss(animated: animated, completion: completion) } removeAllActiveModules() } func setAsRoot(_ module: Module) { setAsRoot(module, animated: false, hideNavigationBar: false) } func setAsRoot(_ module: Module, animated: Bool, hideNavigationBar: Bool) { guard let controller = module.viewToPresent() as? UIViewController else { return } DispatchQueue.main.async { [weak self] in self?.rootNavigationController.setViewControllers([controller], animated: animated) self?.rootNavigationController.isNavigationBarHidden = hideNavigationBar } addModuleToActiveModules(module: module) } func push(_ module: Module, completion: BaseCompletion?) { push(module, animated: true, hideBottomBar: false, completion: completion) } func push(_ module: Module, animated: Bool, hideBottomBar: Bool, completion: BaseCompletion?) { guard let controller = module.viewToPresent() as? UIViewController, (controller is UINavigationController == false) else { return } if let completion = completion { completions[controller] = completion } DispatchQueue.main.async { [weak self] in controller.hidesBottomBarWhenPushed = hideBottomBar self?.rootNavigationController.pushViewController(controller, animated: animated) } addModuleToActiveModules(module: module) } func popModule() { popModule(animated: true) } func popModule(animated: Bool) { DispatchQueue.main.async { [weak self] in if let removedController = self?.rootNavigationController.popViewController(animated: animated) { self?.runCompletion(for: removedController) self?.removeModuleFromActiveModules(viewController: removedController) } } } func popToRootModule() { popToRootModule(animated: true) } func popToRootModule(animated: Bool) { DispatchQueue.main.async { [weak self] in if let removedControllers = self?.rootNavigationController.popToRootViewController(animated: animated) { removedControllers.forEach { controller in self?.runCompletion(for: controller) self?.removeModuleFromActiveModules(viewController: controller) } } } } private func runCompletion(for controller: UIViewController) { guard let completion = completions[controller] else { return } completion() completions.removeValue(forKey: controller) } //MARK: Memory Management // Adding module to active modules set to keep it in memory private func addModuleToActiveModules(module:Module) { guard let controller = module.viewToPresent() as? UIViewController, let identifier = controller.restorationIdentifier else { return } let moduleReference = ModuleReference(identifier: identifier, module: module) activeModules.insert(moduleReference) } // Removing module from active modules set to release it from memory private func removeModuleFromActiveModules(viewController:UIViewController) { guard let identifier = viewController.restorationIdentifier else { return } let moduleReference = ModuleReference(identifier: identifier) activeModules.remove(moduleReference) } private func removeAllActiveModules() { activeModules.removeAll() } }
34.034014
138
0.651409
4ce484ecc38278ecea33be0cfb19f3c9f0983e12
18,650
py
Python
src/scripts/alchi-web.py
milahu/alchi
6484d4a877d47204e28cf1a32a5d9da8705aff25
[ "CC0-1.0" ]
3
2020-08-12T16:57:23.000Z
2021-03-15T18:39:48.000Z
src/scripts/alchi-web.py
milahu/alchi
6484d4a877d47204e28cf1a32a5d9da8705aff25
[ "CC0-1.0" ]
4
2020-09-22T19:25:43.000Z
2022-02-14T20:51:16.000Z
src/scripts/alchi-web.py
milahu/alchi
6484d4a877d47204e28cf1a32a5d9da8705aff25
[ "CC0-1.0" ]
1
2021-04-06T11:18:17.000Z
2021-04-06T11:18:17.000Z
#!/usr/bin/python3 """ the web of sixteen types the nunu matrix two power four latin square of order four """ # definitions names = [ None, 'F1', 'M2', 'M3', 'F4', # left = matriarchy None, 'M1', 'F2', 'F3', 'M4', # right = patriarchy ] names_long = [ None, # 0 'female fire', # 1 'male earth', # 2 'male air', # 3 'female water', # 4 None, # 5 'male fire', # 6 'female earth', # 7 'female air', # 8 'male water', # 9 ] # congruence of gender gl = [1, 2, 3, 4] # left = matriarchy gr = [6, 7, 8, 9] # right = patriarchy # gender gm = [2, 3, 6, 9] # male = penis gf = [1, 4, 7, 8] # female = vagina # tempo tp = [1, 4, 6, 9] # psychotic = phlegmatic tn = [2, 3, 7, 8] # neurotic = choleric # mood me = [1, 3, 6, 8] # extravert = sanguinic mi = [2, 4, 7, 9] # introvert = melancholic # class cc = [1, 2, 6, 7] # classic cr = [3, 4, 8, 9] # romantic # bond signs: first, second, third, last # convert to natlist later #B = ['I', 'U', 'E', 'A'] # 1 2 3 4, self is dott B = ['U', 'E', 'A', 'O'] # 2 3 4 5, first bond is to self = body # helper functions # string translation def tl(s, a, b): return s.translate(s.maketrans(a, b)) # list intersection def lx(*a): a = list(a) # convert tuple to list z = a.pop(0) for b in a: z = [c for c in z if c in b] if len(z) == 1: return z[0] return z # print without newline import sys def _print(*a): sys.stdout.write(*a) # natural list in python # first index is one # slice stop is inclusive # copy from https://stackoverflow.com/a/48873374/10440128 class natlist(dict): def __init__(self, *items: any) -> None: # two constructors: # natlist(1, 2, 3, 4) # natlist( [1, 2, 3, 4] ) # convert one list to natlist if len(items) == 1 and type(items[0]) == list: items = items[0] self.__dict__ = dict(zip( range(1, 1+len(items)), items)) def __repr__(self) -> str: return '{}({})'.format( self.__class__.__name__, repr(list(self.__dict__.values()))[1:-1]) def __contains__(self, item: any) -> bool: return item in self.__dict__.values() def __len__(self) -> int: return len(self.__dict__.values()) # note: key.stop is inclusive # so natlist(1, 2, 3, 4)[2:3] is [2, 3] def __getitem__(self, key: any) -> any: if type(key) == slice: a = key.start and key.start or 1 b = key.stop and key.stop or None # inclusive stop #b = key.stop and key.stop - 1 or None # exclusive stop return list(self.__dict__.values())[a-1:b:key.step] return self.__dict__[key] def __setitem__(self, key: int, value: any) -> None: self.__dict__[key] = value def __delitem__(self, key: int) -> None: del self.__dict__[key] def __iter__(self) -> iter: return iter(self.__dict__.values()) def items(self): return self.__dict__.items() # get slice as list of (key, value) tuples # left slice: sliceitems(None, key_stop) # right slice: sliceitems(key_start, None) # note: key.stop is inclusive def sliceitems(self, *key: slice) -> any: key = slice(*key) a = key.start and key.start or 1 b = key.stop and key.stop or len(self) # inclusive stop #b = key.stop and key.stop - 1 or len(self) # exclusive stop b = (b < 0) and len(self)+b return dict(zip( range(a, b+1), list(self.__dict__.values())[a-1:b:key.step] )).items() L = natlist B = L(B) # convert list to natlist matrix = {} """ matrix['null'] = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], ] 4 elements: 1. fire 2. earth 3. air 4. water 2 sides: left. F1 F4 M3 M2. fem psych + male neur right. M1 M4 F3 F2. male psych + fem neur 2 ages: old. top half = matrix[0:1] young. bottom half = matrix[2:3] first order: same class + other tempo + other sex. """ matrix['fire center + sanguinic center'] = [ [4, 3, 3, 4], [2, 1, 1, 2], [2, 1, 1, 2], [4, 3, 3, 4], ] matrix['web-rc-top-go-left'] = [ [2, 3, 4, 1], [1, 4, 3, 2], [3, 2, 1, 4], [4, 1, 2, 3], ] matrix['web-rc-left-go-top'] = [ [2, 1, 3, 4], [3, 4, 2, 1], [4, 3, 1, 2], [1, 2, 4, 3], ] gender = [ [None, 'F', 'M', 'M', 'F'], # left side [None, 'F', 'M', 'M', 'F'], # left side [None, 'M', 'F', 'F', 'M'], # right side [None, 'M', 'F', 'F', 'M'], # right side ] lines_x_16 = [ [' ', '─\u252C─', ' ', '─\u252C─'], [' ', '─\u2534─', ' │ ', '─\u2534─'], [' ', '─\u252C─', ' │ ', '─\u252C─'], [' ', '─\u2534─', ' ', '─\u2534─'], ] lines_y_16 = [ ' Old \n', ' \u251C────\u252C────\u2524 \n', 'L \u253C R\n', ' \u251C────\u2534────\u2524 \n', ' Young ' ] lines_x_8 = [ [' ', '─\u252C─', ' ', '─\u252C─'], [' ', '─\u2534─', ' ', '─\u2534─'], ] lines_y_8 = [ '', 'L \u251C─────────\u2524 R\n', '', ] lines_x_4 = [ ['', '─\u252C─'], ['', '─\u2534─'], ] lines_y_4 = [ '', ' │\n', '', ] # box drawing characters # --- = '─' # | = '│' # |- = '\u251C' # -| = '\u2524' # T = '\u252C' # _|_ = '\u2534' # + = '\u253C' # serialize 16 elements def str_16(matrix): s = '' for y in range(0, 4): s += lines_y_16[y] for x in range(0, 4): e = matrix[y][x] g = gender[x][e] s += lines_x_16[y][x] + g + str(e) s += '\n' s += lines_y_16[4] return s # serialize 8 elements def str_8(matrix): s = '' for y in range(0, 2): s += lines_y_8[y] for x in range(0, 4): e = matrix[y][x] g = gender[x][e] s += lines_x_8[y][x] + g + str(e) s += '\n' s += lines_y_8[2] return s # serialize 4 elements def str_4(matrix): s = '' for y in range(0, 2): s += lines_y_4[y] for x in range(0, 2): e = matrix[y][x] g = gender[x][e] s += lines_x_4[y][x] + g + str(e) s += '\n' s += lines_y_4[2] return s # web of types def web_16(matrix): s = '' L = [] # line buffer for y in range(-1, 5): y0 = y y = y % 4 for x in range(-1, 5): x = x % 4 L.append(str(matrix[y][x])) if y0 in [-1, 4]: s += '{0} {1} {2} {3} {4} {5}\n'.format(*L) else: s += '{0} │ {1} {2} {3} {4} │ {5}\n'.format(*L) if y == 1: s += ' │ │\n' # with center cross: #s += ' │ \u253C │\n' if y0 == -1: s += ' ┌' + '─'*11 + '┐\n' if y0 == 3: s += ' └' + '─'*11 + '┘\n' L = [] return s # verbose web of types #todo move gender outside of matrix, to left or top # left: # M: .... # F: .... # M: .... # F: .... # top: # M F M F # ¨ ¨ ¨ ¨ # : : : : # : : : : def web_16_v(matrix): s = '' L = [] # line buffer web_gender = ['M', 'F'] for y in range(-1, 5): y0 = y y = y % 4 g = web_gender[y % 2] # gender switch with every line for x in range(-1, 5): x = x % 4 L.append(g + str(matrix[y][x])) if y0 in [-1, 4]: s += '{0} {1} {2} {3} {4} {5}\n'.format(*L) else: s += '{0} │ {1} {2} {3} {4} │ {5}\n'.format(*L) if y == 1: s += ' │ │\n' # with center cross: #s += ' │ \u253C │\n' if y0 in [0, 2]: s += ' │ │ │ │ │ │\n' if y0 == -1: s += ' ┌' + '─'*15 + '┐\n' if y0 == 3: s += ' └' + '─'*15 + '┘\n' L = [] return s # web of 16 types, diagonal mirror def web_16_2_v(matrix): s = '' L = [] # line buffer web_gender = ['M', 'F'] for y in range(-1, 5): y0 = y y = y % 4 for x in range(-1, 5): g = web_gender[x % 2] # gender switch with every delta x x = x % 4 L.append(g + str(matrix[y][x])) if y0 in [-1, 4]: s += '{0} {1} {2} {3} {4} {5}\n'.format(*L) else: #s += '{0} │ {1} {2} {3} {4} │ {5}\n'.format(*L) s += '{0} │ {1}─{2} {3}─{4} │ {5}\n'.format(*L) if y == 1: s += ' │ │\n' # with center cross: #s += ' │ \u253C │\n' if y0 in [0, 2]: #s += ' │ │ │ │ │ │\n' s += ' │ │\n' if y0 == -1: s += ' ┌' + '─'*15 + '┐\n' if y0 == 3: s += ' └' + '─'*15 + '┘\n' L = [] return s #print(web_16(matrix['web-rc-top-go-left'])) #print(web_16_v(matrix['web-rc-top-go-left'])) ##print(web_16_2(matrix['web-rc-left-go-top'])) print(web_16_2_v(matrix['web-rc-left-go-top'])) #for key in matrix: if False: print('%s:' % key) print('16:') print(str_16(matrix[key])) print('8 top:') print(str_8(matrix[key][0:2])) print('8 bot:') print(str_8(matrix[key][2:4])) print('4 top left:') print(str_4(matrix[key])) """ view = construct one of sixteen views i = eye = top left number v = vertical "last bond" [age, time] True if "first bond" is horizontal False if "first bond" is vertical """ import copy def view(i, v=True): m = L( L(0, 0, 0, 0), L(0, 0, 0, 0), L(0, 0, 0, 0), L(0, 0, 0, 0), ) # it starts with eye m[1][1] = i # let us assume "v is True" for now, # and later transform the matrix, according to h. # so, for now, first bond is horizontal. # first bond to you m[1][2] = lx( (i in gl) and gl or gr, # same congruence (i in me) and mi or me, # other mood (i in tn) and tn or tp # same tempo ) # second bond to het m[2][1] = lx( (i in gl) and gl or gr, # same congruence (i in me) and mi or me, # other mood (i in tp) and tn or tp # other tempo ) # opposite type is "het of you" m[2][2] = lx( (i in gl) and gl or gr, # same congruence (i in mi) and mi or me, # same mood (i in tp) and tn or tp # other tempo ) # mirror to the right = other congruence d = (i in gl) and +5 or -5 m[2][4] = m[1][1] + d m[2][3] = m[1][2] + d m[1][4] = m[2][1] + d m[1][3] = m[2][2] + d # mirror to the bottom = other age m[3][1] = m[1][2] m[4][1] = m[2][2] m[3][2] = m[1][1] m[4][2] = m[2][1] m[3][3] = m[1][4] m[4][3] = m[2][4] m[3][4] = m[1][3] m[4][4] = m[2][3] # flip diagonal if v == False: t = copy.deepcopy(m) for y in range(1, 5): for x in range(1, 5): m[y][x] = t[x][y] return m ___lines_x_16_new = L( L('', '', '', ' ', ' ', ' ', '', ''), L('', '', '', ' ', ' ', ' ', '', ''), L('', '', '', ' U ', ' ', ' U ', '', ''), L('', '', '│', ' U ', ' │ ', ' U ', '│', '', ''), L('', '', '│', ' U ', ' │ ', ' U ', '│', '', ''), L('', '', '', ' U ', ' ', ' U ', '', ''), L('', '', '', ' ', ' ', ' ', '', ''), L('', '', '', ' ', ' ', ' ', '', ''), ) ___lines_y_16_new = L( '', '', ' ─────────\n', ' E───A───E \n', ' O\n', ' E───A───E \n', ' ─────────\n', '', '', '', ) __lines_x_16_new = L( L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' │ ', ' I ', ' ', ' I ', ' │ ', ' '), L('', ' ', ' │ ', ' I ', ' │ ', ' I ', ' │ ', ' '), L('', ' ', ' │ ', ' I ', ' │ ', ' I ', ' │ ', ' '), L('', ' ', ' │ ', ' I ', ' ', ' I ', ' │ ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), ) ____lines_y_16_new = L( '', '\n', ' ┌───────────────┐\n', ' │ U───E───U │\n', ' │ A │\n', ' │ U───E───U │\n', ' └───────────────┘\n', '\n', '', '', '', ) __lines_y_16_new = L( '', '\n', ' ╒═══════════════╕\n', ' │ U───E───U │\n', ' │ A │\n', ' │ U───E───U │\n', ' ╘═══════════════╛\n', '\n', '', '', '', ) __lines_x_16_new = L( L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' │ ', '───', ' │ ', '───', ' │ ', ' '), L('', ' ', ' │ ', '───', ' │ ', '───', ' │ ', ' '), L('', ' ', ' │ ', '───', ' │ ', '───', ' │ ', ' '), L('', ' ', ' │ ', '───', ' │ ', '───', ' │ ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), ) __lines_y_16_new = L( '', '\n', ' ╒═══════╤═══════╕\n', ' │ U E U │\n', ' ╞═══════A═══════╡\n', ' │ U E U │\n', ' ╘═══════╧═══════╛\n', '\n', '', '', '', ) lines_x_16_new = L( L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' │ ', ' U ', ' │ ', ' U ', ' │ ', ' '), L('', ' ', ' │ ', ' U ', ' │ ', ' U ', ' │ ', ' '), L('', ' ', ' │ ', ' U ', ' │ ', ' U ', ' │ ', ' '), L('', ' ', ' │ ', ' U ', ' │ ', ' U ', ' │ ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), ) lines_y_16_new = L( '', '\n', ' ╒═══════╤═══════╕\n', ' │ E A E │\n', ' ╞═══════O═══════╡\n', ' │ E A E │\n', ' ╘═══════╧═══════╛\n', '\n', '', '', '', ) __lines_y_16_new_v0 = L( '', '\n', ' ┌───────────────┐\n', ' │ I U I I U I │\n', ' │ E───A───E │\n', ' │ I U I I U I │\n', ' └───────────────┘\n', '\n', '', '', '', ) lines_x_16_new_v0 = L( L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' ║ ', ' ', ' ║ ', ' ', ' ║ ', ' '), L('', ' ', ' ║ ', ' ', ' ║ ', ' ', ' ║ ', ' '), L('', ' ', ' ║ ', ' ', ' ║ ', ' ', ' ║ ', ' '), L('', ' ', ' ║ ', ' ', ' ║ ', ' ', ' ║ ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), L('', ' ', ' ', ' ', ' ', ' ', ' ', ' '), ) lines_y_16_new_v0 = L( '', '\n', ' ╓───────╥───────╖\n', ' ║ U E U ║ U E U ║\n', ' ╟───A───O───A───╢\n', ' ║ U E U ║ U E U ║\n', ' ╙───────╨───────╜\n', '\n', '', '', '', ) # serialize 16 elements # C: compact? print only 4x4 "core" of matrix, without near-field frame #todo: generalize to accept "frame size", fs=0 --> no frame # .... so we can produce larger fields, like fs=4 --> 1 core + 8 "next cores" # --> show "minor lines" as dash- / dot-lines ┈┊ ┄┆ ╌╎ def str_16_new(m, C=False): # detect the value of v # v is True, # if the "last bond" is vertical # = the "first bond" is horizontal i = m[1][1] # first bond to you v = (m[1][2] == lx( (i in gl) and gl or gr, # same congruence (i in me) and mi or me, # other mood (i in tn) and tn or tp # same tempo )) #print('v is '+str(v)) xy_min = C and 3 or 1 xy_max = C and 6 or 8 s = '' #todo write this shorter --> move the (v == True)? branch into the loops if v: #for y in range(1, 5): for y in range(xy_min, 1+xy_max): t = lines_y_16_new[y] if C: t = t.strip() + '\n' s += t #for x in range(1, 5): #for x in range(1, 9): for x in range(xy_min, 1+xy_max): #i = m[y][x] #i = m[(y-2)%4][(x-2)%4] i = m[(y-3)%4+1][(x-3)%4+1] if y in [1, 2, 7, 8] and x in [1, 2, 7, 8]: i = ' ' #g = (i in gm) and 'M' or 'F' #s += lines_x_16_new[y][x] + g + str(i) #s += lines_x_16_new[y][x] + str(i) t = lines_x_16_new[y][x] + str(i) if C and x == 3: t = t.lstrip() s += t if C and x == 6: s += lines_x_16_new[y][7] s += '\n' if C and y == 6: s += lines_y_16_new[7].strip() + '\n' #s += lines_y_16_new[5] else: #for y in range(1, 5): #for y in [-1, 0, 1, 2, 3, 4, 5, 6]: #for y in range(1, 9): # 8 lines for y in range(xy_min, 1+xy_max): t = lines_y_16_new_v0[y] if C: t = t.strip() + '\n' s += t #for x in range(1, 5): #for x in range(1, 9): for x in range(xy_min, 1+xy_max): #i = m[y][x] i = m[(y-3)%4+1][(x-3)%4+1] if y in [1, 2, 7, 8] and x in [1, 2, 7, 8]: i = ' ' #g = (i in gm) and 'M' or 'F' #s += lines_x_16_new[y][x] + g + str(i) #s += lines_x_16_new_v0[y][x] + str(i) t = lines_x_16_new_v0[y][x] + str(i) if C and x == 3: t = t.lstrip() s += t if C and x == 6: s += lines_x_16_new_v0[y][7] s += '\n' if C and y == 6: s += lines_y_16_new_v0[7].strip() + '\n' #s += lines_y_16_new_v0[5] # rename bonds. UEAO --> IUEA if v: s = tl(s, 'UEAO', '─UEA') else: s = tl(s, 'UEAO', 'IUEA') #replace('U', '─').replace('E', 'U').replace(' return s def str_cross(m): i = m[1][1] # detect the value of v v = (m[1][2] == lx( (i in gl) and gl or gr, # same congruence (i in me) and mi or me, # other mood (i in tn) and tn or tp # same tempo )) s = '' if v: t = (m[1][3], m[1][4], B[3], m[1][1], B[1], m[1][2], m[1][3]) s += ' %i\n' % m[3][1] s += '\n' s += ' %i\n' % m[4][1] s += ' %s\n' % B[4] s += '%i %i %s %i %s %i %i\n' % t s += ' %s\n' % B[2] s += ' %i\n' % m[2][1] s += '\n' s += ' %i\n' % m[3][1] return s def hide_gender(m): for y in range(1, 5): for x in range(1, 5): i = m[y][x] if i > 5: m[y][x] = i - 5 return m # main #for x in [1, 2, 3, 4, 6, 7, 8, 9]: for x in [1, 2, 3, 4]: for i in [True, False]: #for i in [True]: si = i and 'I' or 'H' m = view(x, i) m2 = hide_gender(copy.deepcopy(m)) #print('m = '+repr(m)) #print(str_16_new(m)) #print(str_16_new(m2)) #print('iter = '+repr(m.__iter__)) # serialize matrix to string sm = '' for y in m: sm += ''.join(map(str, y)) #sm += ' '.join(map(str, y)) + '\n' sm2 = '' for y in m2: sm2 += ''.join(map(str, y)) sma = tl(sm, '12346789', 'ABCDFGHI') sma2 = tl(sm2, '1234', 'ABCD') #print('%s%i = %s = %s' % (si, x, sm, sm2)) #print('%s%i:\n%s' % (si, x, sm)) #print('%s%i:\n%s\n%s' % (si, x, sm, sm2)) #print('%s%i:\n%s\n%s\n%s\n%s' % (si, x, sm, sm2, sma, sma2)) #print('%s%i:\n%s\n%s\n%s\n%s' % (si, x, sm, sm2, sma, sma2)) print(si + str(x) + 'N4 = ' + sm2) print(si + str(x) + 'L4 = ' + tl(sm2, '1234', 'ABCD')) print(si + str(x) + 'N8F = ' + sm) print(si + str(x) + 'L8F = ' + tl(sm, '12346789', 'ABCDFGHI')) print(si + str(x) + 'N8R = ' + tl(sm, '12346789', '67891234')) print(si + str(x) + 'L8R = ' + tl(sm, '12346789', 'FGHIABCD')) # print compact matrix if False: sm3 = '' for y in m: sm3 += ' '.join(map(str, y)) + '\n' print(si + str(x) + 'N8:\n' + sm3) print(si + str(x) + 'L8:\n' + tl(sm3, '12346789', 'ABCDFGHI')) sm4 = '' for y in m2: sm4 += ' '.join(map(str, y)) + '\n' print(si + str(x) + 'N4:\n' + sm4) print(si + str(x) + 'L4:\n' + tl(sm4, '1234', 'ABCD')) #print('%s%i = %s' % (si, x, sm)) #print(sm) #_print(sm + ' ') #print(str_16_new(m)) #print(str_16_new(m2)) #print(str_16_new(m2, C=True)) print(tl(str_16_new(m2, C=True), '─IUEA', 'BBDHP').replace('BBBBBBB', '───────').replace('BBB', '───')) #print(tl(str_16_new(m2, C=True), '─IUEA1234', 'BBDHPAAAA')) # with gender, coded as number #print(str_16_new(view(( x + 5 ), i), C=True)) #print(str_cross(m2)) print(tl(str_cross(m2), 'UEAO', 'BDHP'))
21.560694
105
0.418713
04150c6c2f663f34c5226c52cc401950a95477ed
15,989
lua
Lua
src/TestTree.lua
chess123mate/TestRunnerPlugin
1a9515cfd56c3858a1378ff4aeccd3a9dbdbfbb6
[ "MIT" ]
null
null
null
src/TestTree.lua
chess123mate/TestRunnerPlugin
1a9515cfd56c3858a1378ff4aeccd3a9dbdbfbb6
[ "MIT" ]
null
null
null
src/TestTree.lua
chess123mate/TestRunnerPlugin
1a9515cfd56c3858a1378ff4aeccd3a9dbdbfbb6
[ "MIT" ]
null
null
null
--[[TestTree monitors all module scripts for testing purposes. It runs tests on startup and whenever any of the following change: testSettings (user settings) testConfigTree (any TestConfig ModuleScript) moduleScript.Source for any test or dependency When a test is run, a report is printed automatically. ]] local modules = script.Parent local GetModuleName = require(modules.Descriptions).GetModuleName local Results = require(modules.Results) local RequireTracker = require(modules.RequireTracker) local SystemRun = require(modules.SystemRun) local Config = require(modules.Config.Config) local baseShouldRecurse = require(modules.Config.BaseSearchShouldRecurse) local TestConfigTree = require(modules.Config.TestConfigTree) local TestSettingsMonitor = require(modules.Settings.TestSettingsMonitor) local Variant = require(modules.Variant) local Utils = modules.Utils local ExploreServices = require(Utils.ExploreServices) local Freezer = require(Utils.Freezer) local TestService = game:GetService("TestService") local testRunner = TestService.TestRunner local StudioService = game:GetService("StudioService") local stepped = game:GetService("RunService").Stepped local TestTree = {} TestTree.__index = TestTree local allServiceNames = { -- that show up in explorer where you could add ModuleScripts "Workspace", "Players", "Lighting", "ReplicatedFirst", "ReplicatedScriptService", "ReplicatedStorage", "ServerScriptService", "ServerStorage", "StarterGui", "StarterPack", "StarterPlayer", "Teams", "SoundService", "Chat", "LocalizationService", "TestService" } -- Test run types: --local NOT_QUEUED = false local QUEUED_TESTS = 1 local ALL_TESTS = 2 function TestTree.new(testSettings, Report, reInit) local self = setmetatable({ testSettings = testSettings, queue = {}, -- list (and set) of moduleScripts that need to be retested -- queued:false/a constant above, representing the type of testing that is currently queued -- lastResults = nil -- lastReport = nil moduleScriptCons = {}, testVariants = {}, -- moduleScript -> variant for valid tests only (ie they return a function without erroring) testSetupFunc = {}, -- moduleScript -> setup function (for tests only) Report = Report, requireTracker = RequireTracker.new(), testRunNum = 0, allowFreezer = false, -- We disable the freezer until all tests/configs have been required for the first time -- We need to do this in case the user is looking at a script when they press Run (allowing configs to be read correctly) freezer = Freezer.new(false), }, TestTree) self.moduleScriptToVariant = Variant.Storage.new(nil, function(moduleScript) return self:isModuleScriptTemporary(moduleScript) end) self.testSettingsMonitor = TestSettingsMonitor.new(testSettings, self) local function updateFreezer() self.freezer:SetEnabled(self.allowFreezer and testSettings.preventRunWhileEditingScripts) end self.testSettingsCon = testSettings:GetPropertyChangedSignal("preventRunWhileEditingScripts"):Connect(updateFreezer) local testConfigTree local MayBeTest local function sourceChanged(moduleScript, variant) -- also works for name changes -- May yield -- Require might yield. As it yields, we don't want it to be considered a test. self:notATest(moduleScript) if moduleScript.Name == "TestConfig" or not MayBeTest(moduleScript) then return end local config = testConfigTree:GetFor(moduleScript) self.requireTracker:Start(moduleScript) local success, value = variant:TryRequire(config.requireTimeout) if success then local configScript = testConfigTree:GetConfigScriptFor(moduleScript, "GetSetupFunc") success, value = pcall(function() return config.GetSetupFunc(moduleScript, value) end) local function problem(msg) if configScript then warn(configScript:GetFullName() .. msg) else self.requireTracker:Finish(moduleScript) error("Default config" .. msg) end end if not success then problem((".GetSetupFunc(%s, requiredValue) errored with: %s"):format( GetModuleName(moduleScript), value)) elseif value then if type(value) ~= "function" then problem((".GetSetupFunc(%s, requiredValue) returned '%s' instead of the setup function"):format( GetModuleName(moduleScript), tostring(value))) else self:thisIsATest(moduleScript, value) end end end -- otherwise, variant:TryRequire will have already emitted the problem via PluginErrHandler self.requireTracker:Finish(moduleScript) end -- Create testConfigTree local function onConfigChange(testConfig, old, new) -- could do: if Config.AnyTimeoutChanged local shouldFreeze = self.freezer:ShouldFreeze() local function analyze() if testConfig.Parent == TestService then local function mayHaveChanged(key) return not Config.IsDefault(old, key) or not Config.IsDefault(new, key) end if mayHaveChanged("SearchShouldRecurse") then reInit() return elseif mayHaveChanged("GetSearchArea") then local a = Config.GetSearchArea(old) local b = Config.GetSearchAreaFromModule(testConfig) local same = #a == #b if same then for i, v in ipairs(a) do if v ~= b[i] then same = false break end end end if not same then reInit() return end end if mayHaveChanged("GetSetupFunc") or mayHaveChanged("MayBeTest") then -- We need to re-analyze all scripts as if their source changed MayBeTest = new.MayBeTest for moduleScript, variant in pairs(self.moduleScriptToVariant) do sourceChanged(moduleScript, variant) end end end self:considerStartTestRun(ALL_TESTS, shouldFreeze) end if shouldFreeze then self.freezer:Freeze("TestConfigChanged", analyze) else analyze() end --[[In response to each config change, could do... timeout - run all* skip/focus - anything added to focus that wasn't run before? run it. - everything removed from focus? run all* * run all that this config affects ]] end local topLevelConfig = Config.GetConfigFromModule(TestService:FindFirstChild("TestConfig")) local listenServiceNames = Config.GetSearchArea(topLevelConfig) testConfigTree = TestConfigTree.new(listenServiceNames, topLevelConfig.SearchShouldRecurse, Config, onConfigChange, self.freezer) self.testConfigTree = testConfigTree -- Setup connections MayBeTest = topLevelConfig.MayBeTest local SearchShouldRecurse = topLevelConfig.SearchShouldRecurse self.serviceConCleanup = ExploreServices(listenServiceNames, function(obj) if obj:IsA("ModuleScript") and not obj:IsDescendantOf(testRunner) and MayBeTest(obj) then local variant = self:GetVariant(obj) coroutine.wrap(sourceChanged)(obj, variant) variant.Invalidated:Connect(function() if self.destroyed then return end -- variants can invalidate each other before they are destroyed if variant:IsDestroyed() then self:notATest(obj) self.requireTracker:RemoveModuleScript(obj) elseif self:isModuleScriptTemporary(obj) then return elseif self.freezer:ShouldFreeze() then self.freezer:Freeze(obj, function() sourceChanged(obj, variant) end) else sourceChanged(obj, variant) end end) variant.SourceChanged:Connect(function() -- Promote this to a non-temporary script if self.moduleScriptsAtStartOfRun then self.moduleScriptsAtStartOfRun[obj] = true end end) end return SearchShouldRecurse(obj, baseShouldRecurse) end) local moduleScriptExists = {} self.moduleScriptExists = moduleScriptExists self.moduleScriptCleanup = ExploreServices(allServiceNames, function(obj) if obj:IsA("ModuleScript") then local con local function cleanup() con:Disconnect() moduleScriptExists[obj] = nil end con = obj.AncestryChanged:Connect(function(child, parent) if not parent then cleanup() end end) moduleScriptExists[obj] = cleanup end return true end) self:considerStartTestRun(ALL_TESTS) return self end function TestTree:Destroy() self.destroyed = true self.freezer:Destroy() self.testConfigTree:Destroy() self.serviceConCleanup() if self.queuedCon then self.queuedCon:Disconnect() end self.testRunNum += 1 self.moduleScriptToVariant:Destroy() self.requireTracker:Destroy() self.testSettingsMonitor:Destroy() self.moduleScriptCleanup() for _, cleanup in pairs(self.moduleScriptExists) do cleanup() end end function TestTree:GetVariant(moduleScript) return self.moduleScriptToVariant:Get(moduleScript) end function TestTree:isModuleScriptTemporary(moduleScript) -- It's temporary if we're in a run and the moduleScript didn't exist before the run started -- Note that it's removed from moduleScriptsAtStartOfRun if its source changes, even during a run return self.moduleScriptsAtStartOfRun and not self.moduleScriptsAtStartOfRun[moduleScript] end function TestTree:notATest(moduleScript) self.testVariants[moduleScript] = nil self.testSetupFunc[moduleScript] = nil self:removeFromQueue(moduleScript) end function TestTree:thisIsATest(moduleScript, setupFunc) if self.testVariants[moduleScript] then return end -- already known to be a test self.testVariants[moduleScript] = self.moduleScriptToVariant[moduleScript] self.testSetupFunc[moduleScript] = setupFunc self:addToQueue(moduleScript) end function TestTree:addToQueue(moduleScript) if self.queued == ALL_TESTS then return end local queue = self.queue if not queue[moduleScript] then queue[moduleScript] = true queue[#queue + 1] = moduleScript self:considerStartTestRun(QUEUED_TESTS) end end function TestTree:removeFromQueue(moduleScript) local queue = self.queue if queue[moduleScript] then queue[moduleScript] = nil table.remove(queue, table.find(queue, moduleScript)) end end function TestTree:considerStartTestRun(level, suppressMandatoryWait) -- Guaranteed to not yield if not self.queued then self.testRunNum += 1 elseif level <= self.queued then -- nothing to be done return end local wasQueued = self.queued self.queued = level -- We often want to wait at least a moment before running tests to allow all script edits to be registered if wasQueued then return end -- we already have a thread in continueQueue if level == ALL_TESTS and next(self.queue) then -- reset queue since we'll be testing all of them self.queue = {} end if suppressMandatoryWait then coroutine.wrap(self.waitForTests)(self) else self.queuedCon = stepped:Connect(function() self.queuedCon:Disconnect() self.queuedCon = nil self:waitForTests() end) end end function TestTree:waitForTests() -- Wait until the tests that we want to run have finished being required while self.queued == QUEUED_TESTS and self.requireTracker:WaitOnList(self.queue, function() return self.queue ~= QUEUED_TESTS end) do -- WaitOnList returns whether we waited, so we keep waiting on 'queue' in case more are added over time -- We provide a cancel function for WaitOnList so that if we switch to ALL_TESTS, we can just use the :Wait() function (which is more efficient) end -- self.queued could be upgraded during WaitOnList if self.queued == ALL_TESTS then self.requireTracker:Wait() end local queued = self.queued self.queued = false if queued == ALL_TESTS then self:runAllTests() else self:runQueuedTests() end end function TestTree:runAllTests() self:performRun(function(addTest) for moduleScript, variant in pairs(self.testVariants) do addTest(moduleScript) end end) end function TestTree:runQueuedTests() local queue = self.queue self.queue = {} self:performRun(function(addTest) for _, moduleScript in ipairs(queue) do addTest(moduleScript) end end) end function TestTree:startTest(moduleScript) self.currentRun:AddTest( self.testConfigTree:GetFor(moduleScript), self:GetVariant(moduleScript)) end local function cloneMSE(t) local new = {} for k, con in pairs(t) do new[k] = true end return new end local function filterResultsForNonTests(results, testVariants) local new = Results.new() local n = 0 for _, m in ipairs(results) do if testVariants[m.moduleScript] then -- Only keep it if it's still a valid test n += 1 new[n] = m end end return new end local function newLastResults(lastResults, results, testVariants) if lastResults then -- Merge results into lastResults local new = Results.new() local n = 0 local moduleScriptToResult = {} -- Store results in moduleScriptToResult -- Then use that to update the "new" lastResults -- Remove it from moduleScriptToResult if it's been dealt with -- Add any remaining moduleScriptToResult to "new" in the order they appear in results for _, m in ipairs(results) do moduleScriptToResult[m.moduleScript] = m end for _, m in ipairs(lastResults) do if testVariants[m.moduleScript] then -- Only keep it if it's still a valid test n += 1 local updated = moduleScriptToResult[m.moduleScript] if updated then new[n] = updated moduleScriptToResult[m.moduleScript] = nil else new[n] = m end end end for _, m in ipairs(results) do if moduleScriptToResult[m.moduleScript] then n += 1 new[n] = m end end return new else return results end end function TestTree:performRun(setupTests) if self.destroyed then return end local num = self.testRunNum print("\n-----------Starting Tests-----------") self.allowFreezer = true -- see allowFreezer initialization for explanation local start = os.clock() self.moduleScriptsAtStartOfRun = cloneMSE(self.moduleScriptExists) local currentRun = SystemRun.new(self.testSettings) self.currentRun = currentRun local testConfigTree = self.testConfigTree setupTests(function(moduleScript) currentRun:AddTest(testConfigTree:GetFor(moduleScript), self:GetVariant(moduleScript)) end) local requiringTime = os.clock() - start local s = os.clock() currentRun:WaitForLoadingComplete() local setupTime = os.clock() - s s = os.clock() currentRun:WaitForTestsComplete() local runTime = os.clock() - s if num ~= self.testRunNum then return end -- Already queueing for or running new test run, so don't print the results of this run local results = currentRun:GetResults() local lastResults = self.lastResults if lastResults then lastResults = filterResultsForNonTests(lastResults, self.testVariants) end local report = self.Report.new(self.testSettings, results, lastResults, requiringTime, setupTime, runTime, os.clock() - start) report:FullPrint() self.lastReport = report self.lastResults = newLastResults(lastResults, results, self.testVariants) self.currentRun = nil self.moduleScriptsAtStartOfRun = nil end function TestTree:RunAllTests() self:considerStartTestRun(ALL_TESTS, true) end function TestTree:ReprintReport() if self.lastReport then self.lastReport:FullPrint() elseif not self.currentRun then self:considerStartTestRun(ALL_TESTS, true) end -- else first report will print soon end -- function TestTree:RunTests(moduleScripts) -- commented out because not used -- for _, moduleScript in ipairs(moduleScripts) do -- if self.testVariants[moduleScript] then -- self:addToQueue(moduleScript) -- end -- end -- end function TestTree:PrintDependencyTree() -- TODO Add a button to print this out? --[[TODO Could do better tree analysis ex: a>b, b>c, c>d say we start at b>c, then we see c>d, but later we find a>b so since 'a' is not a descendant of 'b', we can add it as a parent and merge the trees What if we see c>d first, then we see a>b>c? at this point, we could say "hey, we saw 'c' before" Then we ask "was a/b a descendant of c?" Since no, we connect them (otherwise they would already have been connected) > similarly we can ask if there was any overlap Is it possible that only one overlaps but others still need to be connected? ]] print("\nDependency Tree") local seen = {} for _, v in pairs(self.moduleScriptToVariant) do v:PrintDependencies(seen) end end return TestTree
35.452328
146
0.756395
8db686790f6b0e022da4bee67729e41c5777e5b3
3,561
js
JavaScript
src/js/modules/projectPage.projectSettings.js
mkoeppen/frontend-checker-chrome-extension
949203d39ecef2c143e529adddfbe93083980077
[ "MIT" ]
null
null
null
src/js/modules/projectPage.projectSettings.js
mkoeppen/frontend-checker-chrome-extension
949203d39ecef2c143e529adddfbe93083980077
[ "MIT" ]
null
null
null
src/js/modules/projectPage.projectSettings.js
mkoeppen/frontend-checker-chrome-extension
949203d39ecef2c143e529adddfbe93083980077
[ "MIT" ]
null
null
null
'use strict' export default class ProjectSettings { constructor(projectHandler, project) { this.element = undefined; this.project = project; this.projectHandler = projectHandler; this.whitelistInput = undefined; this.blacklistInput = undefined; this.matchingInfo = undefined; } generate() { this.element = document.createElement("form"); this.element.classList.add("k-form"); this.element.classList.add("k-project-details__form"); this.element.innerHTML = ` <input name="id" type="hidden" value="${this.project.id || ""}"> <div class="k-form__row"><label for="name">Name:</label><input id="name" name="name" type="text" value="${this.project.name || ""}"></div> <div class="k-form__row"><label for="whitelistUrls">Urls:</label><textarea id="whitelistUrls" name="whitelistUrls">${this.project.whitelistUrls || ""}</textarea></div> <div class="k-form__row"><label for="blacklistUrls">Blacklist Urls:</label><textarea id="blacklistUrls" name="blacklistUrls">${this.project.blacklistUrls || ""}</textarea></div> <div class="k-project-details__maching-info"></div> <div class="k-form__row k-form__row--center"> <button class="k-button k-project-details__cancel-button" type="button">Cancel</button> <button class="k-button" type="submit">Save</button> </div> `; this.whitelistInput = this.element.querySelector('textarea[name="whitelistUrls"]'); this.whitelistInput.addEventListener('keyup', () => { this.refreshMatchingInfo() }); this.blacklistInput = this.element.querySelector('textarea[name="blacklistUrls"]'); this.blacklistInput.addEventListener('keyup', () => { this.refreshMatchingInfo() }); this.matchingInfo = this.element.querySelector('.k-project-details__maching-info'); this.element.addEventListener("submit", (e) => { e.preventDefault(); var currentForm = e.target; var project = { id: currentForm.querySelector("input[name='id']").value, name: currentForm.querySelector("input[name='name']").value, blacklistUrls: currentForm.querySelector("textarea[name='blacklistUrls']").value, whitelistUrls: currentForm.querySelector("textarea[name='whitelistUrls']").value, } document.dispatchEvent(new CustomEvent('project-save', { detail: project })); return false; }); this.element.querySelector(".k-project-details__cancel-button").addEventListener("click", (e) => { document.dispatchEvent(new CustomEvent('project-edit-cancel')); }) this.refreshMatchingInfo(); return this.element; } refreshMatchingInfo() { var isMatching = this.projectHandler.checkMatchingUrlRegex(this.whitelistInput.value, this.blacklistInput.value); if(isMatching) { this.matchingInfo.innerHTML = `<i class="fa fa-check-circle-o" aria-hidden="true"></i>Current tab url is matching rules`; this.matchingInfo.classList.add('k-project-details__maching-info--is-matching'); } else { this.matchingInfo.innerHTML = `<i class="fa fa-times-circle-o" aria-hidden="true"></i>Current tab url is not matching rules` this.matchingInfo.classList.remove('k-project-details__maching-info--is-matching'); } } }
49.458333
189
0.629318
133f59cce862d8200b17f0c7cc149550030f0c57
1,685
lua
Lua
scripts/movement.lua
luis-dbdev/Game-1
2ccfc0416e81ae2e01cb417f9e4712496e889ae6
[ "MIT" ]
null
null
null
scripts/movement.lua
luis-dbdev/Game-1
2ccfc0416e81ae2e01cb417f9e4712496e889ae6
[ "MIT" ]
null
null
null
scripts/movement.lua
luis-dbdev/Game-1
2ccfc0416e81ae2e01cb417f9e4712496e889ae6
[ "MIT" ]
null
null
null
-- movement.lua -- Performance bindings local print = print local bit = bit local table = table local ipairs = ipairs -- Return table move = {} move.direction = 0 move.buffer = {} move.jumping = false -- Script global locals local speedX = 0 -- Abstracted away from main.lua local speedY = 0 -- Abstracted away from main.lua local gravity = 1800 -- Self explanatory local hAcc = 5000 -- Horizontal acceleration (for moving) local vAcc = 7000-- Vertical acceleration (for jumping) -- Update function function move:update(dt) move.direction = 0 if love.keyboard.isDown('right') then -- 0x0001 self.direction = 1 end if love.keyboard.isDown('up') then -- 0x0010 self.direction = bit.bor(move.direction, bit.lshift(1,1)) end if love.keyboard.isDown('left') then -- 0x0100 self.direction = bit.bor(move.direction, bit.lshift(1,2)) end if love.keyboard.isDown('down') then -- 0x1000 self.direction = bit.bor(move.direction, bit.lshift(1, 3)) end -- Select animation based on: -- 0x0001 (1) - Moving right -- 0x0010 (2) - Looking up -- 0x0100 (4) - Moving left -- 0x1000 (8) - Looking down -- 0x0011 (3) - Moving right looking up -- 0x0110 (6) - Moving left looking up -- 0x1100 (12)- Moving left looking down -- 0x1001 (9) - Moving right looking down end function move:keypressed(key) table.insert(self.buffer, key) if table.getn(self.buffer) > 2 then table.remove(self.buffer, 1) end if key == "space" then self.jumping = true end if key == "lctrl" then self.crouching = true end end function move:grounded() self.jumping = false end return move
24.42029
68
0.661128
2fa77995f771d0026d97fecc96a2146bcbb0ce25
7,115
kt
Kotlin
LeMoinCoinAndroid/app/src/main/java/lemoin/lemoincoinandroid/SendCoin.kt
SpamAndEgg/LeMoinCoin
6a0742cc4c72ce21ee856322283ea0a3f6db1d90
[ "MIT" ]
2
2018-03-17T13:33:33.000Z
2018-04-03T12:02:50.000Z
LeMoinCoinAndroid/app/src/main/java/lemoin/lemoincoinandroid/SendCoin.kt
SpamAndEgg/LeMoinCoin
6a0742cc4c72ce21ee856322283ea0a3f6db1d90
[ "MIT" ]
6
2018-03-17T13:25:59.000Z
2018-09-11T09:41:22.000Z
LeMoinCoinAndroid/app/src/main/java/lemoin/lemoincoinandroid/SendCoin.kt
SpamAndEgg/LeMoinCoin
6a0742cc4c72ce21ee856322283ea0a3f6db1d90
[ "MIT" ]
null
null
null
package lemoin.lemoincoinandroid import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.Handler import android.support.v7.app.AppCompatActivity import com.android.volley.Request import com.android.volley.Response import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley import kotlinx.android.synthetic.main.send_coin.* import kotlinx.android.synthetic.main.toolbar.* import org.json.JSONObject import com.android.volley.DefaultRetryPolicy import com.android.volley.RetryPolicy import javax.xml.datatype.DatatypeConstants.SECONDS import android.text.Editable import android.text.TextWatcher import java.math.BigInteger import java.text.DecimalFormat import java.text.NumberFormat import java.util.* class SendCoin : AppCompatActivity() { // Define request codes for private and public key. private var CODE_PUB_KEY = 2 private lateinit var sharedFun: SharedFun private var sDb: StoredDataBase? = null private lateinit var sDbWorkerThread: DbWorkerThread private val sUiHandler = Handler() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.send_coin) setSupportActionBar(toolbar_page) sharedFun = SharedFun(this, this@SendCoin, savedInstanceState) sharedFun.setDrawer() sDbWorkerThread = DbWorkerThread("dbWorkerThread") sDbWorkerThread.start() sDb = StoredDataBase.getInstance(this) // Get address from address book (if one was sent). val sendToAdd = intent.getStringExtra("contactAddress") if(sendToAdd != null) { txt_receiver_address.setText(sendToAdd) txt_send_to_name.text = ("Send coins to " + intent.getStringExtra("contactName")) } txt_receiver_address.setText(sendToAdd) send_coin_amount.addTextChangedListener(onTextChangedListener()) // Define action for "Send Coin" button. btn_send_coin.setOnClickListener{ if (txt_receiver_address.text.matches("^0x[0-9a-fA-F]{40}".toRegex())){ transferCoin() } else { txt_send_to_name.text = "Invalid address format ('x0' + 40 Hex)" } } btn_qr_pubkey_sc.setOnClickListener{ val intent = Intent(this@SendCoin, QrCodeScanner::class.java) // Start the QR code scanner to get a key. The request code defines weather the qr scanner // scans the private key or the public key of the receiver. startActivityForResult(intent, CODE_PUB_KEY) } } // Overriding the "onActivityResult" allows to catch results that come back when the QR code // scanner is called. override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == Activity.RESULT_OK) { if (requestCode == CODE_PUB_KEY) { txt_receiver_address.setText(data?.getStringExtra("Key")) } } } // Function to transfer coins from an account defined by the private key to another account. private fun transferCoin() { val task = Runnable { // First get the private key from the database. val privateKey = sDb?.storedDataDao()?.getPrivateKey() // Then make the transfer request. sUiHandler.post { // Create new queue for HTTP requests. val queue = Volley.newRequestQueue(this) // Get the URL of the server to transfer coins. val serverUrl: String = getString(R.string.server_url) val url = serverUrl.plus("/transfer") // While the amount of coins is entered with two decimal points but is handled by // the smart contract as an int, it has to be converted. var amountOfCoin = send_coin_amount.text.toString() amountOfCoin = amountOfCoin.replace("[.,]".toRegex(), "") // Remove starting zeros from the amount of coin string. amountOfCoin = amountOfCoin.replace("^0+".toRegex(), "") println("The amount of coins to send issssssssssssssssssssssssssssssssssssssssss") println(amountOfCoin) // Create a JSON object containing the private key of the account to send money from, the // public key of the account to send money to and the amount of coins to transfer. val reqParam = JSONObject() reqParam.put("pri_key", privateKey) reqParam.put("send_to", txt_receiver_address.text) reqParam.put("amount", amountOfCoin) // Create the request object. val req = JsonObjectRequest(Request.Method.POST, url, reqParam, Response.Listener{ response -> // Write the status in the text box as feedback for the user. txt_send_status.hint = response.getString("status") }, Response.ErrorListener { txt_send_status.hint = "Transaction failed :(" }) req.setRetryPolicy(DefaultRetryPolicy(100000, 0, 1f)) // Add the request object to the queue. queue.add(req) } } sDbWorkerThread.postTask(task) } private fun onTextChangedListener(): TextWatcher { return object : TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { // Display input numbers always in the format "#.##". send_coin_amount.removeTextChangedListener(this) try { var originalString = s.toString().replace("[,.]".toRegex(), "") val parsed = originalString.toDouble() val numberToFormat: NumberFormat val formattedString: String if (parsed == 0.0) { formattedString = "0.00" } else { numberToFormat = NumberFormat.getNumberInstance() numberToFormat.minimumFractionDigits = 2 formattedString = numberToFormat.format(parsed/100) } // Setting formatted text in text box. send_coin_amount.setText(formattedString) send_coin_amount.setSelection(formattedString.length) } catch (nfe: NumberFormatException) { nfe.printStackTrace() } send_coin_amount.addTextChangedListener(this) } override fun afterTextChanged(s: Editable) { } } } }
38.879781
105
0.614055
b08e4eaab9e1eded174a9cd46d798f84311d0495
10,807
py
Python
swarms/lib/space.py
aadeshnpn/swarm
873e5d90de4a3b3f69d4edc8de55eb9311226c2e
[ "MIT" ]
9
2018-03-26T22:22:08.000Z
2021-08-30T20:45:27.000Z
swarms/lib/space.py
aadeshnpn/swarm
873e5d90de4a3b3f69d4edc8de55eb9311226c2e
[ "MIT" ]
1
2021-05-06T12:45:11.000Z
2021-05-12T07:21:53.000Z
swarms/lib/space.py
aadeshnpn/swarm
873e5d90de4a3b3f69d4edc8de55eb9311226c2e
[ "MIT" ]
1
2019-04-22T00:27:09.000Z
2019-04-22T00:27:09.000Z
# -*- coding: utf-8 -*- """ The grid class for swarm framework. Grid: base grid, a simple dictionary. """ import math import numpy as np import re class Grid: """Grid class. Class that defines grid strucutre having attribute Width, height and grid size. """ # pylint: disable=too-many-instance-attributes # Nine is reasonable in this grid class def __init__(self, width, height, grid_size=10): """Constructors for grid. Args: width: total width height: total height grid_size: granularity of the size of grid Attributes: x_limit: x-axis length in both direction y_limit: y-axis length in both direction grid: dictionary object which value is adjacent points of grid and its value is the grid name grid_objects: dictionary object which value is the grid name and its value is the list of environment objects """ self.width = width self.height = height self.x_limit = width / 2 self.y_limit = height / 2 self.grid_size = grid_size self.grid = dict() self.grid_reverse = dict() self.grid_objects = dict() # self.width_fix = int(self.x_limit % self.grid_size) # self.height_fix = int(self.y_limit % self.grid_size) # If the width or height is not comptiable with grid size if self.x_limit % self.grid_size != 0 \ or self.y_limit % self.grid_size != 0: print("Grid size invalid") exit(1) # Create list for x cordinate & y cordinate to create grid list_xcords = np.arange( -self.width / 2, self.width / 2, self.grid_size).tolist() list_ycords = np.arange( -self.height / 2, self.height / 2, self.grid_size).tolist() indx = 1 for ycord in list_ycords: for xcord in list_xcords: x_1 = xcord y_1 = ycord x_2 = xcord + self.grid_size y_2 = ycord + self.grid_size self.grid[(x_1, y_1), (x_2, y_2)] = indx self.grid_reverse[indx] = (x_1, y_1), (x_2, y_2) self.grid_objects[indx] = [] indx += 1 self.grid_len = indx - 1 def modify_points(self, point): """Modify poitns if the location line in the grid line.""" x, y = point[0], point[1] if point[0] % self.grid_size == 0: x = point[0] + 1 if point[1] % self.grid_size == 0: y = point[1] + 1 if point[0] >= self.x_limit: x = point[0] - self.grid_size + 1 if point[1] >= self.y_limit: y = point[1] - self.grid_size + 1 return (x, y) def find_lowerbound(self, point): """Find the lower bound from the point.""" point = self.find_upperbound(point) return (point[0] - self.grid_size, point[1] - self.grid_size) def find_upperbound(self, point): """Find the upper bound from the point.""" point = self.modify_points(point) return (point[0] + self.grid_size - 1 * ( point[0] % self.grid_size), point[1] + self.grid_size - 1 * ( point[1] % self.grid_size)) def find_grid(self, point): """Find the grid based on the point passed.""" grid_key = (self.find_lowerbound(point), self.find_upperbound(point)) try: return grid_key, self.grid[grid_key] except KeyError: print('KeyError', 'No grid key for ', grid_key) exit() def get_horizontal_neighbours(self, center_grid, scale, width_scale): """Get the neighboring horizontal grids.""" valid_horizontal_start = (math.floor( (center_grid - 1) / width_scale) * width_scale) + 1 valid_horizontal_end = math.ceil( center_grid / width_scale) * width_scale if(center_grid - scale) < valid_horizontal_start: horizontal_start = valid_horizontal_start else: horizontal_start = center_grid - scale if(center_grid + scale + 1) > valid_horizontal_end: horizontal_end = valid_horizontal_end + 1 else: horizontal_end = center_grid + scale + 1 horizontal_grid = list(range(horizontal_start, horizontal_end, 1)) return horizontal_grid # Find the adjacent grid based on radius def get_neighborhood(self, point, radius): """Get the neighboring grids.""" all_grid = [] center_grid_key, center_grid = self.find_grid(point) if self.grid_size >= radius: return [center_grid] else: scale = int(radius / self.grid_size) width_scale = int(self.width / self.grid_size) horizontal_grid = self.get_horizontal_neighbours( center_grid, scale, width_scale) vertical_grid = list(range( center_grid - scale * width_scale, center_grid + 1 + scale * width_scale, width_scale)) h_v_grid = [] for grid in vertical_grid: h_v_grid += self.get_horizontal_neighbours( grid, scale, width_scale) all_grid = h_v_grid + horizontal_grid all_grid = [grid for grid in all_grid if grid > 0 and grid <= self.grid_len] return list(set(all_grid)) def add_object_to_grid(self, point, objects): """Add object to a given grid.""" grid_values = self.get_neighborhood(point, objects.radius) # print('add object to grid',grid_values, objects) for grid in grid_values: # gridobjects = self.get_objects(None, grid) # for gobject in gridobjects: # if not re.match('.*Agent.*' , type(gobject).__name__): # if gobject.deathable and re.match('.*Agent.*' , type(objects).__name__): # objects.dead = True # print(grid, objects) self.grid_objects[grid].append(objects) # Remove object to the given grid def remove_object_from_grid(self, point, objects): """Remove object from the given grid.""" grid_values = self.get_neighborhood(point, objects.radius) for grid in grid_values: self.grid_objects[grid].remove(objects) def move_object(self, point, objects, newpoint): """Move object from the give grid to new grid.""" grid_key, grid_value = self.find_grid(point) new_grid_key, new_grid_value = self.find_grid(newpoint) # print('move object', point, newpoint, grid_value, new_grid_value) if grid_value != new_grid_value: if re.match('.*Agent.*' , type(objects).__name__) and objects.dead: return False elif re.match('.*Agent.*' , type(objects).__name__) and not objects.dead: # print(point, newpoint, grid_value, new_grid_value) if self.check_grid_deathable_constraints(new_grid_value): objects.dead = True objects.moveable = False self.remove_object_from_grid(point, objects) self.add_object_to_grid(newpoint, objects) return True else: if self.check_grid_objects_constraints(new_grid_value): self.remove_object_from_grid(point, objects) self.add_object_to_grid(newpoint, objects) return True else: return False else: if self.check_grid_objects_constraints(new_grid_value): self.remove_object_from_grid(point, objects) self.add_object_to_grid(newpoint, objects) return True else: return False else: return True # Check limits for the environment boundary def check_limits(self, i, d): """Check the location is valid.""" x, y = i if x > (self.width / 2): x = x - (x - self.x_limit) - 2 d = np.pi + d elif x < (self.width / 2) * -1: x = x - (x + self.x_limit) + 2 d = np.pi + d if y > (self.height / 2): y = y - (y - self.y_limit) - 2 d = np.pi + d elif y < (self.height / 2) * -1: y = y - (y + self.y_limit) + 2 d = np.pi + d return ((int(x), int(y)), d % (2*np.pi)) def check_grid_objects_constraints(self, new_grid_value): """Check the constraints on the next location.""" # grid_key, grid_value = self.find_grid(source_obj.location) # new_grid_key, new_grid_value = self.find_grid(next_loc) passable = True objects_in_next_grid = self.get_objects(None, new_grid_value) for obj in objects_in_next_grid: if not obj.passable: passable = False break return passable def check_grid_deathable_constraints(self, new_grid_value): """Check the constraints on the next location.""" # grid_key, grid_value = self.find_grid(source_obj.location) # new_grid_key, new_grid_value = self.find_grid(next_loc) dead = False objects_in_next_grid = self.get_objects(None, new_grid_value) # print('dead const', objects_in_next_grid) for obj in objects_in_next_grid: try: if obj.deathable: dead = True break except: pass return dead # Using fancy search to find the object in the particular grid def get_objects(self, object_name, grid_value): """Use fancy search to find objects in a grid.""" if object_name is not None: return list(filter( lambda x: type(x).__name__ == object_name, self.grid_objects[grid_value])) else: return list(filter( lambda x: type(x).__name__ != 'list', self.grid_objects[grid_value])) def get_objects_from_grid(self, object_name, point): """Get objects from grid given a location.""" grid_key, grid_value = self.find_grid(point) return self.get_objects(object_name, grid_value) def get_objects_from_list_of_grid(self, object_name, grid_list): """Get list of objects from grid list.""" object_list = [] for grid in grid_list: object_list += self.get_objects(object_name, grid) return object_list
38.459075
94
0.570371
ed14b926e7ef05c30861a9d253b65ddbefa889c2
11,080
c
C
ubsan.c
uli/allwinner-bare-metal
ea55715ac31942d7af3a6babba29514c8a2f0d49
[ "MIT" ]
5
2019-04-25T20:03:19.000Z
2021-12-29T23:28:17.000Z
ubsan.c
uli/allwinner-bare-metal
ea55715ac31942d7af3a6babba29514c8a2f0d49
[ "MIT" ]
null
null
null
ubsan.c
uli/allwinner-bare-metal
ea55715ac31942d7af3a6babba29514c8a2f0d49
[ "MIT" ]
1
2021-12-31T01:33:02.000Z
2021-12-31T01:33:02.000Z
/*- * Copyright (c) 2017 The FreeBSD Foundation * All rights reserved. * * As a reference, this code uses the software from the contrib/compiler-rt * implementation of the userspace UBSAN runtime, which is developed as part * of the LLVM project under the University of Illinois Open Source License. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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. * * $FreeBSD$ */ /* * Adapted from (unmerged?) FreeBSD patch for allwinner-bare-metal * Copyright (c) 2021 Ulrich Hecht */ // Avoid using stdio. Enable this if stuff goes wrong really early. //#define EARLY_PRINTF #include <sys/cdefs.h> #include <stdint.h> #include <stdio.h> #include <string.h> enum type_kinds { TK_INTEGER = 0x0000, TK_FLOAT = 0x0001, TK_UNKNOWN = 0xffff }; struct type_descriptor { uint16_t type_kind; uint16_t type_info; char type_name[1]; }; struct source_location { char *filename; uint32_t line; uint32_t column; }; struct overflow_data { struct source_location loc; struct type_descriptor *type; }; struct shift_out_of_bounds_data { struct source_location loc; struct type_descriptor *lhs_type; struct type_descriptor *rhs_type; }; struct out_of_bounds_data { struct source_location loc; struct type_descriptor *array_type; struct type_descriptor *index_type; }; struct non_null_return_data { struct source_location attr_loc; }; struct type_mismatch_data { struct source_location loc; struct type_descriptor *type; unsigned char log_alignment; unsigned char type_check_kind; }; struct vla_bound_data { struct source_location loc; struct type_descriptor *type; }; struct invalid_value_data { struct source_location loc; struct type_descriptor *type; }; struct unreachable_data { struct source_location loc; }; const char *type_check_kinds[] = { "load of", "store to", "reference binding to", "member access within", "member call on", "constructor call on", "downcast of", "downcast of", "upcast of", "cast to virtual base of", "_Nonnull binding to" }; void __ubsan_handle_add_overflow(struct overflow_data *data, uintptr_t lhs, uintptr_t rhs); void __ubsan_handle_sub_overflow(struct overflow_data *data, uintptr_t lhs, uintptr_t rhs); void __ubsan_handle_mul_overflow(struct overflow_data *data, uintptr_t lhs, uintptr_t rhs); void __ubsan_handle_divrem_overflow(struct overflow_data *data, uintptr_t lhs, uintptr_t rhs); void __ubsan_handle_negate_overflow(struct overflow_data *data, uintptr_t old); void __ubsan_handle_shift_out_of_bounds(struct shift_out_of_bounds_data *data, uintptr_t lhs, uintptr_t rhs); void __ubsan_handle_out_of_bounds(struct out_of_bounds_data *data, uintptr_t index); void __ubsan_handle_nonnull_return(struct non_null_return_data *data, struct source_location *loc); void __ubsan_handle_type_mismatch_v1(struct type_mismatch_data *data, uintptr_t ptr); void __ubsan_handle_vla_bound_not_positive(struct vla_bound_data *data, uintptr_t bound); void __ubsan_handle_load_invalid_value(struct invalid_value_data *data, uintptr_t val); void __ubsan_handle_builtin_unreachable(struct unreachable_data *data); #ifdef EARLY_PRINTF #include "uart.h" #define printf(x...) do { char foo[256]; sprintf(foo, x); uart_print(foo); } while (0) #endif static unsigned bit_width(struct type_descriptor *type) { return (1 << (type->type_info >> 1)); } static int is_inline_int(struct type_descriptor *type) { return (bit_width(type) <= 8*sizeof(uintptr_t)); } static int is_signed(struct type_descriptor *type) { return (type->type_info & 1); } static intmax_t signed_val(struct type_descriptor *type, uintptr_t val) { if (is_inline_int(type)) { unsigned extra_bits = 8*sizeof(intmax_t) - bit_width(type); return ((intmax_t)val << extra_bits >> extra_bits); } return (*(intmax_t *)val); } static uintmax_t unsigned_val(struct type_descriptor *type, uintptr_t val) { if (is_inline_int(type)) return (val); return (*(uintmax_t *)val); } static void format_value(char *dest, size_t size, struct type_descriptor *type, uintptr_t value) { if (type->type_kind == TK_INTEGER) { if (is_signed(type)) { snprintf(dest, size, "%lld", (int64_t)signed_val(type, value)); } else { snprintf(dest, size, "%llu", (uint64_t)unsigned_val(type, value)); } } else { snprintf(dest, size, "<unknown>"); } } static int ubsan_init(struct source_location *loc) { uint32_t old_column; old_column = loc->column; loc->column = 0xffffffff; if (old_column == 0xffffffff) return (0); printf("%s:%lu:%lu: runtime error: ", strrchr(loc->filename, '/') + 1, loc->line, old_column); return (1); } static void handle_overflow(struct overflow_data *data, uintptr_t lhs, const char *operator, uintptr_t rhs) { char lhs_str[20]; char rhs_str[20]; int data_signed; if (!ubsan_init(&data->loc)) return; data_signed = is_signed(data->type); format_value(lhs_str, sizeof(lhs_str), data->type, lhs); format_value(rhs_str, sizeof(rhs_str), data->type, rhs); printf("%s integer overflow: %s %s %s cannot be represented" "in type %s\n", data_signed ? "signed" : "unsigned", lhs_str, operator, rhs_str, data->type->type_name); } void __ubsan_handle_add_overflow(struct overflow_data *data, uintptr_t lhs, uintptr_t rhs) { handle_overflow(data, lhs, "+", rhs); } void __ubsan_handle_sub_overflow(struct overflow_data *data, uintptr_t lhs, uintptr_t rhs) { handle_overflow(data, lhs, "-", rhs); } void __ubsan_handle_mul_overflow(struct overflow_data *data, uintptr_t lhs, uintptr_t rhs) { handle_overflow(data, lhs, "*", rhs); } void __ubsan_handle_divrem_overflow(struct overflow_data *data, uintptr_t lhs, uintptr_t rhs) { struct type_descriptor *type = data->type; if (!ubsan_init(&data->loc)) return; if (is_signed(type) && signed_val(type, rhs) == -1) printf("division of %lld by -1 cannot be represented" "in type %s\n", signed_val(data->type, lhs), data->type->type_name); else printf("division by zero\n"); } void __ubsan_handle_negate_overflow(struct overflow_data *data, uintptr_t old) { struct type_descriptor *type = data->type; if (!ubsan_init(&data->loc)) return; if (is_signed(type)) printf("negation of %lld cannot be represented in type %s; " "cast to an unsigned type to negate this value to itself\n", signed_val(type, old), data->type->type_name); else printf("negation of %lld cannot be represented in type %s\n", unsigned_val(type, old), data->type->type_name); } void __ubsan_handle_shift_out_of_bounds(struct shift_out_of_bounds_data *data, uintptr_t lhs, uintptr_t rhs) { if (!ubsan_init(&data->loc)) return; if (is_signed(data->rhs_type) && signed_val(data->rhs_type, rhs) < 0) { printf("shift exponent %lld is negative\n", signed_val(data->rhs_type, rhs)); } else if (unsigned_val(data->rhs_type, rhs) >= bit_width(data->lhs_type)) { printf("shift exponent %llu is too large for %u-bit type %s\n", unsigned_val(data->rhs_type, rhs), bit_width(data->rhs_type), data->lhs_type->type_name); } else if (is_signed(data->lhs_type) && signed_val(data->lhs_type, lhs) < 0) { printf("left shift of negative value %lld\n", signed_val(data->lhs_type, lhs)); } else { printf("left shift of %llu by %llu places cannot be represented" "in type %s\n", unsigned_val(data->lhs_type, lhs), unsigned_val(data->rhs_type, rhs), data->lhs_type->type_name); } } void __ubsan_handle_out_of_bounds(struct out_of_bounds_data *data, uintptr_t index) { char index_str[20]; if (!ubsan_init(&data->loc)) return; format_value(index_str, sizeof(index_str), data->index_type, index); printf("index %s out of bounds for type %s\n", index_str, data->array_type->type_name); } void __ubsan_handle_nonnull_return(struct non_null_return_data *data, struct source_location *loc) { struct source_location attr_loc = data->attr_loc; if (!ubsan_init(loc)) return; printf("null pointer returned from function declared" "to never return null\n"); if (attr_loc.filename) { printf("%s:%lu:%lu: note: returns_nonnull attribute" "specified here\n", strrchr(attr_loc.filename, '/') + 1, attr_loc.line, attr_loc.column); } } void __ubsan_handle_type_mismatch_v1(struct type_mismatch_data *data, uintptr_t ptr) { unsigned alignment; if (!ubsan_init(&data->loc)) return; alignment = 1 << data->log_alignment; if (!ptr) printf("%s null pointer of type %s\n", type_check_kinds[data->type_check_kind], data->type->type_name); else if (ptr & (alignment - 1)) printf("%s misaligned address %p for type %s, " "which requires %u byte alignment\n", type_check_kinds[data->type_check_kind], (void *)ptr, data->type->type_name, alignment); else printf("%s address %p with insufficient space " "for an object of type %s\n", type_check_kinds[data->type_check_kind], (void *)ptr, data->type->type_name); } void __ubsan_handle_vla_bound_not_positive(struct vla_bound_data *data, uintptr_t bound) { char bound_str[20]; if (!ubsan_init(&data->loc)) return; format_value(bound_str, sizeof(bound_str), data->type, bound); printf("variable length array bound evaluates" "to non-positive value %s\n", bound_str); } void __ubsan_handle_load_invalid_value(struct invalid_value_data *data, uintptr_t val) { char val_str[20]; if (!ubsan_init(&data->loc)) return; format_value(val_str, sizeof(val_str), data->type, val); printf("load of value %s, which is not a valid value for type %s\n", val_str, data->type->type_name); } void __ubsan_handle_builtin_unreachable(struct unreachable_data *data) { if (!ubsan_init(&data->loc)) return; printf("execution reached a __builtin_unreachable() call\n"); }
26.070588
86
0.72843
2fdc13976fdfd81b965611c8c806d706ebb39b7e
2,214
py
Python
comparison/count_trees.py
J-Moravec/pairtree
91cbba628b78aea31034efb080976fdb47d83976
[ "MIT" ]
15
2021-01-19T21:13:50.000Z
2022-02-02T00:01:33.000Z
comparison/count_trees.py
J-Moravec/pairtree
91cbba628b78aea31034efb080976fdb47d83976
[ "MIT" ]
17
2020-11-25T09:41:03.000Z
2022-03-28T04:52:14.000Z
comparison/count_trees.py
J-Moravec/pairtree
91cbba628b78aea31034efb080976fdb47d83976
[ "MIT" ]
6
2021-01-01T06:00:31.000Z
2021-06-29T15:03:11.000Z
import argparse import pickle import numpy as np from numba import njit @njit def count_trees(tau, phi, order, traversal): assert traversal == 'dfs' or traversal == 'bfs' K = len(tau) expected_colsum = np.ones(K) expected_colsum[0] = 0 first_partial = np.copy(tau) np.fill_diagonal(first_partial, 0) first_delta = np.copy(phi) partial_trees = [(1, first_partial, first_delta)] completed_trees = 0 while len(partial_trees) > 0: if traversal == 'dfs': to_resolve, P, delta = partial_trees.pop() else: to_resolve, P, delta = partial_trees.pop(0) #to_resolve, P, delta = partial_trees[0] #partial_trees = partial_trees[1:] if to_resolve == K: assert np.all(expected_colsum == np.sum(P, axis=0)) assert np.all(0 <= delta) and np.all(delta <= 1) np.fill_diagonal(P, 1) completed_trees += 1 continue R = order[to_resolve] parents = np.nonzero(P[:,R])[0] for parent in parents: P_prime = np.copy(P) P_prime[:,R] = 0 P_prime[parent,R] = 1 if np.any(delta[parent] - phi[R] < 0): continue delta_prime = np.copy(delta) delta_prime[parent] -= phi[R] partial_trees.append((to_resolve + 1, P_prime, delta_prime)) return completed_trees @njit def make_order(phi): phisum = np.sum(phi, axis=1) order = np.argsort(-phisum) assert order[0] == 0 return order @njit def make_tau(phi, order): K, S = phi.shape tau = np.eye(K) for I in range(K): for J in range(I + 1, K): I_prime = order[I] J_prime = order[J] assert not np.all(phi[I_prime] == phi[J_prime]) if np.all(phi[I_prime] >= phi[J_prime]): tau[I_prime,J_prime] = 1 return tau def main(): parser = argparse.ArgumentParser( description='LOL HI THERE', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('sim_data_fn') args = parser.parse_args() with open(args.sim_data_fn, 'rb') as dataf: simdata = pickle.load(dataf) phi, true_tree = simdata['phi'], simdata['adjm'] order = make_order(phi) tau = make_tau(phi, order) num_trees = count_trees(tau, phi, order, 'dfs') print(args.sim_data_fn, num_trees) main()
25.744186
66
0.646793
da67074c722817fdecdfdb2e4751c711b418f500
5,816
php
PHP
app/Http/Controllers/Rapports/PoudreTestController.php
SimonLou-Dev/rescue-panel
43932779de1a8e1120811710f1b41c9bb8ab0a54
[ "RSA-MD" ]
1
2022-03-12T19:35:38.000Z
2022-03-12T19:35:38.000Z
app/Http/Controllers/Rapports/PoudreTestController.php
SimonLou-Dev/rescue-panel
43932779de1a8e1120811710f1b41c9bb8ab0a54
[ "RSA-MD" ]
null
null
null
app/Http/Controllers/Rapports/PoudreTestController.php
SimonLou-Dev/rescue-panel
43932779de1a8e1120811710f1b41c9bb8ab0a54
[ "RSA-MD" ]
1
2022-03-13T20:27:15.000Z
2022-03-13T20:27:15.000Z
<?php namespace App\Http\Controllers\Rapports; use App\Enums\DiscordChannel; use App\Events\Notify; use App\Http\Controllers\Controller; use App\Http\Controllers\LogsController; use App\Http\Controllers\Patient\PatientController; use App\Jobs\ProcessEmbedPosting; use App\Jobs\ProcesTestPoudrePDFGenerator; use App\Models\Intervention; use App\Models\Patient; use App\Models\TestPoudre; use App\Models\User; use Barryvdh\DomPDF\Facade\Pdf; use Illuminate\Http\Request; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Storage; use PHPUnit\Util\Test; class PoudreTestController extends Controller { public function __construct() { $this->middleware('auth'); } public function postTest(request $request){ $this->authorize('create', TestPoudre::class); $request->validate([ 'name'=>['required','regex:/[a-zA-Z.+_]+\s[a-zA-Z.+_]/'], 'ddn'=>['required'], 'tel'=>['tel'=> 'required','regex:/5{3}-\d\d/'], 'liveplace'=>['required', 'string'], 'place'=>["required", 'string'], 'clothPresence'=>['boolean'], 'skinPresence'=>['boolean'], ]); $test = new TestPoudre(); $Patient = PatientController::PatientExist($request->name); if(is_null($Patient)) { $Patient = new Patient(); $Patient->name = $request->name; $Patient->tel = $request->tel; $Patient->naissance = $request->ddn; $Patient->living_place = $request->liveplace; $Patient->save(); event(new Notify('Nouveau patient créé',1)); }else { $Patient->tel = $request->tel; $Patient->naissance = $request->ddn; $Patient->living_place = $request->liveplace; $Patient->save(); } $test->patient_id = $Patient->id; $test->user_id = Auth::id(); $test->lieux_prelevement = $request->place; $test->on_skin_positivity = $request->skinPresence; $test->on_clothes_positivity = $request->clothPresence; $service = \Session::get('service')[0]; $test->service = $service; $test->save(); $tester = User::where('id', Auth::id())->first(); $path = storage_path('app/public/test/poudre/') . "/pouder_".$test->id.'.pdf'; $this->dispatch(new ProcesTestPoudrePDFGenerator($test, $path)); $embed = [ [ 'title'=>"Résultat d\'un tes de poudre {$service} :", 'color'=>'1285790', 'fields'=>[ [ 'name'=>'Patient : ', 'value'=>$Patient->name, 'inline'=>true ],[ 'name'=>'Contact patient : ', 'value'=> $Patient->tel, 'inline'=>true ],[ 'name'=>'Date de naissance : ', 'value'=>date('d/m/Y', strtotime($request->DDN)), 'inline'=>true ],[ 'name'=>'Lieux de résidence : ', 'value'=>($Patient->living_place), 'inline'=>false ],[ 'name'=>'Reaction sur la peau : ', 'value'=>($request->peau ? 'Positif :white_check_mark: ': 'Négatif :x:'), 'inline'=>false ],[ 'name'=>'Reaction sur les vetements : ', 'value'=>($request->vetements ? 'Positif :white_check_mark: ' : 'Négatif :x:'), 'inline'=>false ],[ 'name'=>'Date et heure du test : ', 'value'=>date('d/m/Y à H:i'), 'inline'=>false ],[ 'name'=>'Lieux de prise en charge : ', 'value'=>$request->place, 'inline'=>true ],[ 'name'=>'Personnel en charge : ', 'value'=>$tester->name, 'inline'=>true ],[ 'name'=>'PDF', 'value'=>":link: [`PDF`](".env('APP_URL').'/storage/test/poudre/'.$test->id . ".pdf)" ] ], 'footer'=>[ 'text' => "Service de Biologie ({$service})", ] ] ]; \Discord::postMessage(DiscordChannel::Poudre, $embed, null); $logs = new LogsController(); $logs->TestDePoudreLogging($test->id, $tester->id); event(new Notify('Test enregistré',1,Auth::user()->id)); return response()->json(['status'=>'OK'],201); } public function exportTest($id){ $test = TestPoudre::where('id', $id)->first(); $user = $test->GetPersonnel; $path = storage_path('app/public/test/poudre/') . "/pouder_".$test->id.'.pdf'; if(!file_exists($path)){ $pdf = Pdf::loadView('PDF.TDP',['test'=>$test, 'user'=>$user]); $pdf->save($path); return $pdf->stream(); } return response()->file($path); } public function getAllTests(Request $request): \Illuminate\Http\JsonResponse { $this->authorize('viewAny', TestPoudre::class); $tests = TestPoudre::search($request->query('query'))->paginate(); foreach ($tests as $test) $test->GetPatient; return response()->json(['status'=>'OK', 'tests'=>$tests]); } }
36.35
109
0.485557
8fb165546dab0ab922f001ad1b365141fb628add
1,582
swift
Swift
SimulationFramework/SmartSimulationFramework/SmartSimulationFramework/Groups/Religious.swift
mrommel/SmartSimulation
19ee89102a514933fa7007dd3a21bdaf28ff24e3
[ "MIT" ]
null
null
null
SimulationFramework/SmartSimulationFramework/SmartSimulationFramework/Groups/Religious.swift
mrommel/SmartSimulation
19ee89102a514933fa7007dd3a21bdaf28ff24e3
[ "MIT" ]
null
null
null
SimulationFramework/SmartSimulationFramework/SmartSimulationFramework/Groups/Religious.swift
mrommel/SmartSimulation
19ee89102a514933fa7007dd3a21bdaf28ff24e3
[ "MIT" ]
null
null
null
// // Religious.swift // SmartSimulationFramework // // Created by Michael Rommel on 19.10.18. // Copyright © 2018 Michael Rommel. All rights reserved. // import Foundation public class Religious: Group { init() { super.init( identifier: "Religious", image: nil, name: "Religious", summary: "Although there is a wide range of different religions, most of the larger organized groups can agree on a few basic principles. Religious voters support religious teaching in schools, specialized 'faith' schools, and are also pro marriage. Religious groups may also be concerned by abortion and organ donation, and are unlikely to be pro-science.", moodValue: 0.7, frequencyValue: 0.2) } override func setup(with global: GlobalSimulation) { // Liberals are 20% less likely to be religious and 10% more likely to be environmentalist. self.groupFrequenceInfluences.append(GroupFrequenceInfluence(group: global.groups.religious, influence: -0.2)) //self.groupFrequenceInfluences.append(GroupFrequenceInfluence(group: global.groups.environmentalist, influence: 0.1)) self.mood.add(simulation: self.mood, formula: "x") // keep self value self.frequency.add(simulation: self.frequency, formula: "x") // keep self value self.frequency.add(simulation: global.simulations.povertyRate, formula: "0+(0.5*x)") self.frequency.add(simulation: global.simulations.equality, formula: "0-(0.1*x)", delay: 30) global.groups.add(group: self) } }
41.631579
370
0.69469
b5c3ac2133b9b09a61f192d962990f24c9861c18
257
swift
Swift
TheMeal/Features/Meals/MealsFeature.swift
gsobrevilla/the-meal-ios
3b5134a30205de7f737c36adcaf718e61bf3716b
[ "MIT" ]
null
null
null
TheMeal/Features/Meals/MealsFeature.swift
gsobrevilla/the-meal-ios
3b5134a30205de7f737c36adcaf718e61bf3716b
[ "MIT" ]
null
null
null
TheMeal/Features/Meals/MealsFeature.swift
gsobrevilla/the-meal-ios
3b5134a30205de7f737c36adcaf718e61bf3716b
[ "MIT" ]
null
null
null
// // MealsFeature.swift // TheMeal // // Created by Gastón on 07/01/2021. // Copyright © 2021 Gastón Sobrevilla. All rights reserved. // import Foundation class MealsFeature { static let storyboard = AppStoryboard(storyboardName: "Meals") }
17.133333
66
0.696498
6849f872e41bba5ed7e2a68ee5d574b8c4ff2bcd
10,863
swift
Swift
FIOSDK/FIOSDK/External/Libraries/AbiSerialization/abiSerializer.swift
mghnmtt/fiosdk_ios
fcc3c2918d284cc36a609500668fa8ed797acf40
[ "MIT" ]
null
null
null
FIOSDK/FIOSDK/External/Libraries/AbiSerialization/abiSerializer.swift
mghnmtt/fiosdk_ios
fcc3c2918d284cc36a609500668fa8ed797acf40
[ "MIT" ]
5
2020-05-05T22:26:34.000Z
2020-06-09T21:34:40.000Z
FIOSDK/FIOSDK/External/Libraries/AbiSerialization/abiSerializer.swift
mghnmtt/fiosdk_ios
fcc3c2918d284cc36a609500668fa8ed797acf40
[ "MIT" ]
2
2020-04-29T15:55:30.000Z
2021-12-02T09:49:28.000Z
// // abiSerializer.swift // FIOSDK // // Created by shawn arney on 8/12/19. // Copyright © 2019 Dapix, Inc. All rights reserved. // /* let abieos: EosioAbieosSerializationProvider? = EosioAbieosSerializationProvider() let hex = "1686755CA99DE8E73E1200" // some binary data let json = "{"name": "John"}" // some JSON let jsonToBinaryTransaction = try? abieos?.serializeTransaction(json: json) let binaryToJsonTransaction = try? abieos?.deserializeTransaction(hex: hex) */ import Foundation class abiSerializer { private var context = abieos_create() private var abiJsonString = "" /// Getter to return error as a String. public var error: String? { return String(validatingUTF8: abieos_get_error(context)) } /// Default init. required public init() { } deinit { abieos_destroy(context) } /// Convert ABIEOS String data to UInt64 value. /// /// - Parameter string: String data to convert. /// - Returns: A UInt64 value. public func name64(string: String?) -> UInt64 { guard let string = string else { return 0 } return abieos_string_to_name(context, string) } /// Convert ABIEOS UInt64 data to String value. /// /// - Parameter name64: A UInt64 value to convert. /// - Returns: A string value. public func string(name64: UInt64) -> String? { return String(validatingUTF8: abieos_name_to_string(context, name64)) } private func refreshContext() { if context != nil { abieos_destroy(context) } context = abieos_create() } private func getAbiJsonFile(fileName: String) throws -> String { var abiString = "" let bundle = Bundle(for: type(of: self)) let path = bundle.url(forResource: fileName, withExtension: nil)?.path ?? "" abiString = try NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String guard abiString != "" else { // throw // throw Error(.serializationProviderError, reason: "Json to hex -- No ABI file found for \(fileName)") throw NSError(domain: "com.fiosdk.error", code: 1, userInfo: [NSLocalizedDescriptionKey: "getAbiJsonFile"]) } return abiString } /// Convert JSON Transaction data representation to ABIEOS binary representation of Transaction data. /// /// - Parameter json: The JSON representation of Transaction data to serialize. /// - Returns: A binary String of Transaction data. /// - Throws: If the data cannot be serialized for any reason. public func serializeTransaction(json: String) throws -> String { let transactionJson = try getAbiJsonFile(fileName: "transaction.abi.json") return try serialize(contract: nil, name: "", type: "transaction", json: json, abi: transactionJson) } /// Convert JSON ABI data representation to ABIEOS binary of data. /// /// - Parameter json: The JSON data String to serialize. /// - Returns: A String of binary data. /// - Throws: If the data cannot be serialized for any reason. public func serializeAbi(json: String) throws -> String { let abiJson = try getAbiJsonFile(fileName: "abi.abi.json") return try serialize(contract: nil, name: "error_message", type: "abi_def", json: json, abi: abiJson) } /// Convert JSON ABI data representation to ABIEOS binary of data. /// /// - Parameter json: The JSON data String to serialize. /// - Returns: A String of binary data. /// - Throws: If the data cannot be serialized for any reason. public func serializeContent(contentType: FIOAbiContentType, json: String) throws -> String { let abiJson = try getAbiJsonFile(fileName: "fio.abi.json") return try serialize(contract: nil, name: "", type: contentType.rawValue, json: json, abi: abiJson) } /// Calls ABIEOS to carry out JSON to binary conversion using ABIs. /// /// - Parameters: /// - contract: An optional String representing contract name for the serialize action lookup for this ABIEOS conversion. /// - name: An optional String representing an action name that is used in conjunction with contract (above) to derive the serialize type name. /// - type: An optional string representing the type name for the serialize action lookup for this serialize conversion. /// - json: The JSON data String to serialize to binary. /// - abi: A String representation of the ABI to use for conversion. /// - Returns: A String of binary serialized data. /// - Throws: If the data cannot be serialized for any reason. //shawn notes #warning("I could pass in the raw abi for this here") public func serialize(contract: String?, name: String = "", type: String? = nil, json: String, abi: String) throws -> String { refreshContext() let contract64 = name64(string: contract) abiJsonString = abi // set the abi let setAbiResult = abieos_set_abi(context, contract64, abiJsonString) guard setAbiResult == 1 else { throw NSError(domain: "com.fiosdk.error", code: 1, userInfo: [NSLocalizedDescriptionKey: "json to hex"]) } // get the type name for the action guard let type = type ?? getType(action: name, contract: contract64) else { throw NSError(domain: "com.fiosdk.error", code: 1, userInfo: [NSLocalizedDescriptionKey: "unable to find type for action"]) } var jsonToBinResult: Int32 = 0 jsonToBinResult = abieos_json_to_bin_reorderable(context, contract64, type, json) guard jsonToBinResult == 1 else { throw NSError(domain: "com.fiosdk.error", code: 1, userInfo: [NSLocalizedDescriptionKey: "unable to pack json to bin"]) } guard let hex = String(validatingUTF8: abieos_get_bin_hex(context)) else { throw NSError(domain: "com.fiosdk.error", code: 1, userInfo: [NSLocalizedDescriptionKey: "unable to convert binary to hex"]) } return hex } /// Converts a binary string of ABIEOS Transaction data to JSON string representation of Transaction data. /// /// - Parameter hex: The binary Transaction data String to deserialize. /// - Returns: A String of JSON Transaction data. /// - Throws: If the data cannot be deserialized for any reason. public func deserializeTransaction(hex: String) throws -> String { let transactionJson = try getAbiJsonFile(fileName: "transaction.abi.json") return try deserialize(contract: nil, name: "", type: "transaction", hex: hex, abi: transactionJson) } /// Converts a binary string of ABIEOS data to JSON string data. /// /// - Parameter hex: The binary data String to deserialize. /// - Returns: A String of JSON data. /// - Throws: If the data cannot be deserialized for any reason. public func deserializeAbi(hex: String) throws -> String { let abiJson = try getAbiJsonFile(fileName: "abi.abi.json") return try deserialize(contract: nil, name: "", type: "abi_def", hex: hex, abi: abiJson) } /// Converts a binary string of ABIEOS data to JSON string data. /// /// - Parameter hex: The binary data String to deserialize. /// - Returns: A String of JSON data. /// - Throws: If the data cannot be deserialized for any reason. public func deserializeContent(contentType: FIOAbiContentType, hexString: String) throws -> String { let abiJson = try getAbiJsonFile(fileName: "fio.abi.json") return try deserialize(contract: nil, name: "", type: contentType.rawValue, hex: hexString, abi: abiJson) } /// Calls ABIEOS to carry out binary to JSON conversion using ABIs. /// /// - Parameters: /// - contract: An optional String representing contract name for the ABIEOS action lookup for this ABIEOS conversion. /// - name: An optional String representing an action name that is used in conjunction with contract (above) to derive the ABIEOS type name. /// - type: An optional string representing the type name for the ABIEOS action lookup for this ABIEOS conversion. /// - hex: The binary data String to deserialize to a JSON String. /// - abi: A String representation of the ABI to use for conversion. /// - Returns: A String of JSON data. /// - Throws: If the data cannot be deserialized for any reason. public func deserialize(contract: String?, name: String = "", type: String? = nil, hex: String, abi: String) throws -> String { refreshContext() let contract64 = name64(string: contract) abiJsonString = abi // set the abi let setAbiResult = abieos_set_abi(context, contract64, abiJsonString) guard setAbiResult == 1 else { // throw Error(.serializationProviderError, reason: "Hex to json -- Unable to set ABI. \(self.error ?? "")") throw NSError(domain: "com.fiosdk.error", code: 1, userInfo: [NSLocalizedDescriptionKey: "hex to json - unable to set abi"]) } // get the type name for the action guard let type = type ?? getType(action: name, contract: contract64) else { // throw Error(.serializationProviderError, reason: "Unable find type for action \(name). \(self.error ?? "")") throw NSError(domain: "com.fiosdk.error", code: 1, userInfo: [NSLocalizedDescriptionKey: "unable to find type for action"]) } if let json = abieos_hex_to_json(context, contract64, type, hex) { if let string = String(validatingUTF8: json) { return string } else { throw NSError(domain: "com.fiosdk.error", code: 1, userInfo: [NSLocalizedDescriptionKey: "unable to convert c string json to String"]) } } else { throw NSError(domain: "com.fiosdk.error", code: 1, userInfo: [NSLocalizedDescriptionKey: "unable to unpack hex to string"]) } } // Get the type name for the action and contract. private func getType(action: String, contract: UInt64) -> String? { let action64 = name64(string: action) if let type = abieos_get_type_for_action(context, contract, action64) { return String(validatingUTF8: type) } else { return nil } } private func jsonString(dictionary: [String: Any]) -> String? { if let data = try? JSONSerialization.data(withJSONObject: dictionary, options: []) { return String(data: data, encoding: .utf8) } else { return nil } } }
44.158537
150
0.644205
8ee1c11dc766357a64e6748be712f04d7b3e78c5
4,102
rb
Ruby
app/models/user_swimmer_confirmation.rb
steveoro/goggles_core
fc1f6a8cc346faf75665dcb551ca212045ebc53a
[ "MIT" ]
1
2016-10-05T13:46:47.000Z
2016-10-05T13:46:47.000Z
app/models/user_swimmer_confirmation.rb
steveoro/goggles_core
fc1f6a8cc346faf75665dcb551ca212045ebc53a
[ "MIT" ]
null
null
null
app/models/user_swimmer_confirmation.rb
steveoro/goggles_core
fc1f6a8cc346faf75665dcb551ca212045ebc53a
[ "MIT" ]
null
null
null
# frozen_string_literal: true # # = UserSwimmerConfirmation model # # - version: 6.200 # - author: Steve A. # # Holds confirmations received by a user about its association with a # swimmer_id. # class UserSwimmerConfirmation < ApplicationRecord # XXX [Steve, 20170130] We don't care anymore (so much) about these updates: commented out # after_create UserContentLogger.new('user_swimmer_confirmations') # after_update UserContentLogger.new('user_swimmer_confirmations') # before_destroy UserContentLogger.new('user_swimmer_confirmations') # [Steve, 20140930] We don't need to keep around NULL'ed UserSwimmerConfirmations if a user is deleted: belongs_to :user, dependent: :destroy belongs_to :swimmer validates_associated :swimmer belongs_to :confirmator, class_name: 'User', foreign_key: 'confirmator_id' # FIXME: for Rails 4+, move required/permitted check to the controller using the model # attr_accessible :user_id, :swimmer_id, :confirmator_id scope :find_for_user, ->(user) { where(user_id: user.id) } scope :find_for_confirmator, ->(confirmator) { where(confirmator_id: confirmator.id) } scope :find_any_between, ->(user, confirmator) { where(confirmator_id: confirmator.id, user_id: user.id) } #-- ------------------------------------------------------------------------- #++ # Confirms the association for a user to a swimmer, given another # user that acts as a "confirmator". # # The parameters can either be model instances or simple IDs. # Returns the confirmation row on success, +nil+ otherwise. # def self.confirm_for(user, swimmer, confirmator) user_id, swimmer_id, confirmator_id = parse_parameters(user, swimmer, confirmator) return nil unless validate_parameters(user_id, swimmer_id, confirmator_id) begin UserSwimmerConfirmation.create!( user_id: user_id, swimmer_id: swimmer_id, confirmator_id: confirmator_id ) rescue StandardError nil end end #-- ------------------------------------------------------------------------- #++ # Removes the single confirmation row for the association between a user and a swimmer, # given another user that acts as a "confirmator" (in this case, the "un-confirmator"). # # Only coherent tuples can be deleted. That is, only the rows having the same ID values # as the specified parameters will be removed. # # The parameters can either be model instances or simple IDs (Fixnum). # Returns +true+ on success, +false+ otherwise. # def self.unconfirm_for(user, swimmer, confirmator) user_id, swimmer_id, confirmator_id = parse_parameters(user, swimmer, confirmator) return false unless validate_parameters(user_id, swimmer_id, confirmator_id) unconfirmable_row = UserSwimmerConfirmation.where( user_id: user_id, swimmer_id: swimmer_id, confirmator_id: confirmator_id ).first if unconfirmable_row begin unconfirmable_row.destroy rescue StandardError false end else false end end #-- ------------------------------------------------------------------------- #++ private # Parses the parameters for self.confirm_for() or self.unconfirm_for(). # Returns the array of parameters. def self.parse_parameters(user, swimmer, confirmator) user_id = user.instance_of?(User) ? user.id : user swimmer_id = swimmer.instance_of?(Swimmer) ? swimmer.id : swimmer confirmator_id = confirmator.instance_of?(User) ? confirmator.id : confirmator [user_id, swimmer_id, confirmator_id] end # Returns true if all the parameters are valid for a self.confirm_for/() or # self.unconfirm_for() call. def self.validate_parameters(user_id, swimmer_id, confirmator_id) ( user_id.is_a?(Fixnum) && user_id.to_i > 0 && swimmer_id.is_a?(Fixnum) && swimmer_id.to_i > 0 && confirmator_id.is_a?(Fixnum) && confirmator_id.to_i > 0 ) end #-- ------------------------------------------------------------------------- #++ end
35.982456
113
0.657972
8f4e6cad7748b9037eb980f14b78da7a0c00de76
1,087
dart
Dart
lib/models/countriesData.g.dart
hiteshgarg123/COVID-19-TRACKER
67bc0b7ad014d1477f4dc7b2f5b12fc14ce2862b
[ "MIT" ]
7
2020-04-28T10:49:51.000Z
2021-07-30T08:18:43.000Z
lib/models/countriesData.g.dart
hiteshgarg123/COVID-19-TRACKER
67bc0b7ad014d1477f4dc7b2f5b12fc14ce2862b
[ "MIT" ]
5
2020-09-07T13:31:37.000Z
2021-05-12T05:51:37.000Z
lib/models/countriesData.g.dart
hiteshgarg123/COVID-19-TRACKER
67bc0b7ad014d1477f4dc7b2f5b12fc14ce2862b
[ "MIT" ]
2
2020-10-28T18:06:45.000Z
2021-05-05T16:18:10.000Z
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'countriesData.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class CountriesDataAdapter extends TypeAdapter<CountriesData> { @override final int typeId = 4; @override CountriesData read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return CountriesData( countriesData: (fields[0] as List).cast<CountryData>(), ); } @override void write(BinaryWriter writer, CountriesData obj) { writer ..writeByte(1) ..writeByte(0) ..write(obj.countriesData); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is CountriesDataAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
25.880952
77
0.556578
bfbda67fd63098e0ea2ba835b07a5ec61a0c6bdf
2,288
rb
Ruby
app/models/wechat/model/template.rb
work-design/rails_wechat
c68776133dfc1909f2f5623ea25e0b990dac74a1
[ "MIT" ]
6
2019-11-19T05:38:34.000Z
2022-01-27T12:08:53.000Z
app/models/wechat/model/template.rb
work-design/rails_wechat
c68776133dfc1909f2f5623ea25e0b990dac74a1
[ "MIT" ]
19
2019-06-22T05:03:35.000Z
2022-03-31T07:00:48.000Z
app/models/wechat/model/template.rb
work-design/rails_wechat
c68776133dfc1909f2f5623ea25e0b990dac74a1
[ "MIT" ]
1
2019-09-29T02:17:48.000Z
2019-09-29T02:17:48.000Z
module Wechat module Model::Template extend ActiveSupport::Concern included do attribute :template_id, :string attribute :title, :string attribute :content, :string attribute :example, :string attribute :template_type, :integer attribute :appid, :string, index: true belongs_to :app, foreign_key: :appid, primary_key: :appid, optional: true belongs_to :template_config, optional: true has_many :notices, dependent: :delete_all has_many :msg_requests, ->(o){ where(appid: o.appid) }, foreign_key: :body, primary_key: :template_id before_save :sync_from_template_config, if: -> { template_config_id_changed? || template_config } before_save :sync_to_wechat, if: -> { template_id_changed? && template_id.present? } after_destroy_commit :del_to_wechat end def init_template_config if app.is_a?(PublicApp) config = TemplatePublic.find_or_initialize_by(content: content) config.title = title self.template_config = config self.save end end def sync_from_template_config self.template_id ||= template_config.tid end def sync_to_wechat sync_from_wechat return if content.present? r = app.api.add_template(template_config.tid, template_config.kid_list) if r['errcode'] == 0 self.template_id = r['priTmplId'] || r['template_id'] else logger.debug(" =========> Error is #{r['errmsg']}") return end sync_from_wechat end def sync_from_wechat r_content = app.api.templates.find do |i| tid = app.is_a?(PublicApp) ? i['template_id'] : i['priTmplId'] tid == self.template_id end return if r_content.blank? self.template_type = r_content['type'] self.assign_attributes r_content.slice('title', 'content', 'example') self end def sync_to_wechat! sync_to_wechat save end def del_to_wechat r = app.api.del_template(template_id) logger.debug(r['errmsg']) end def data_keys content.gsub(/(?<={{)\w+(?=.DATA}})/).to_a end def data_mappings if template_config template_config.data_hash else {} end end end end
27.238095
107
0.642045
a9db7d1560cc01114715f9216558145ad97d0933
2,546
php
PHP
src/View/Renderer/YamlRenderer.php
samsonasik/ZF2-AcYaml
954cc906b27de64d5f29d3d56b3852118373dcca
[ "MIT" ]
null
null
null
src/View/Renderer/YamlRenderer.php
samsonasik/ZF2-AcYaml
954cc906b27de64d5f29d3d56b3852118373dcca
[ "MIT" ]
null
null
null
src/View/Renderer/YamlRenderer.php
samsonasik/ZF2-AcYaml
954cc906b27de64d5f29d3d56b3852118373dcca
[ "MIT" ]
null
null
null
<?php namespace Acelaya\Yaml\View\Renderer; use Acelaya\Yaml\View\Exception\DomainException; use Acelaya\Yaml\View\Model\YamlModel; use Symfony\Component\Yaml\Yaml; use Zend\Stdlib\ArrayUtils; use Zend\View\Model\ModelInterface; use Zend\View\Renderer\JsonRenderer; /** * Class YamlStrategy * @author Alejandro Celaya Alastrué * @link http://www.alejandrocelaya.com */ class YamlRenderer extends JsonRenderer { /** * This method is not applicable * * @param string $callback * @return JsonRenderer */ public function setJsonpCallback($callback) { // Do nothing return $this; } /** * This method is not applicable * * @return bool */ public function hasJsonpCallback() { // Do nothing return false; } /** * Processes a view script and returns the output. * * @param string|ModelInterface $nameOrModel The script/resource process, or a view model * @param null|array|\ArrayAccess $values Values to use during rendering * @return string The script output. */ public function render($nameOrModel, $values = null) { // use case 1: View Models // Serialize variables in view model if ($nameOrModel instanceof ModelInterface) { if ($nameOrModel instanceof YamlModel) { $children = $this->recurseModel($nameOrModel, false); $this->injectChildren($nameOrModel, $children); $values = $nameOrModel->serialize(); } else { $values = $this->recurseModel($nameOrModel); $values = Yaml::dump($values); } return $values; } // use case 2: $nameOrModel is populated, $values is not // Serialize $nameOrModel if (null === $values) { if (! is_object($nameOrModel)) { $return = Yaml::dump($nameOrModel); } elseif ($nameOrModel instanceof \Traversable) { $nameOrModel = ArrayUtils::iteratorToArray($nameOrModel); $return = Yaml::dump($nameOrModel); } else { $return = Yaml::dump(get_object_vars($nameOrModel)); } return $return; } // use case 3: Both $nameOrModel and $values are populated throw new DomainException(sprintf( '%s: Do not know how to handle operation when both $nameOrModel and $values are populated', __METHOD__ )); } }
29.604651
103
0.588767
46d738c1f9ab330200160168283d43dff76c8e9b
804
py
Python
skaben/alert/admin.py
skaben/server_core
46ba0551459790dda75abc9cf0ff147fae6d62e8
[ "MIT" ]
null
null
null
skaben/alert/admin.py
skaben/server_core
46ba0551459790dda75abc9cf0ff147fae6d62e8
[ "MIT" ]
12
2020-08-14T12:43:04.000Z
2021-09-01T00:22:26.000Z
skaben/alert/admin.py
skaben/server_core
46ba0551459790dda75abc9cf0ff147fae6d62e8
[ "MIT" ]
null
null
null
from django.contrib import admin from skaben.admin import base_site from .models import AlertCounter, AlertState class AlertStateCustomAdmin(admin.ModelAdmin): list_display = ('current', 'name', 'info', 'order', 'threshold', 'modifier') list_filter = [ 'current', ] fieldsets = ( ('Параметры уровня тревоги', { 'classes': ('none',), 'fields': ( ('name', 'current'), ('info', 'order'), 'modifier', 'threshold', ) }), ) class AlertCounterCustomAdmin(admin.ModelAdmin): readonly_fields = ('timestamp',) admin.site.register(AlertCounter, AlertCounterCustomAdmin, site=base_site) admin.site.register(AlertState, AlertStateCustomAdmin, site=base_site)
23.647059
80
0.599502
dd8d71a1bac98d6f0c73a2f1046cc1358e3d9821
988
java
Java
backend/services/reverse-geocoding-service/src/main/java/com/navigation/reversegeocodingapi/infrastructure/database/DatabaseMapper.java
Nalhin/Navigation
df918e86183a1cdb24b247de44ae9fda5fa19cc1
[ "MIT" ]
null
null
null
backend/services/reverse-geocoding-service/src/main/java/com/navigation/reversegeocodingapi/infrastructure/database/DatabaseMapper.java
Nalhin/Navigation
df918e86183a1cdb24b247de44ae9fda5fa19cc1
[ "MIT" ]
null
null
null
backend/services/reverse-geocoding-service/src/main/java/com/navigation/reversegeocodingapi/infrastructure/database/DatabaseMapper.java
Nalhin/Navigation
df918e86183a1cdb24b247de44ae9fda5fa19cc1
[ "MIT" ]
null
null
null
package com.navigation.reversegeocodingapi.infrastructure.database; import com.navigation.reversegeocodingapi.domain.Address; import com.navigation.reversegeocodingapi.domain.Location; import org.springframework.data.mongodb.core.geo.GeoJsonPoint; import org.springframework.stereotype.Component; @Component class DatabaseMapper { Address toDomain(AddressEntity entity) { return new Address.AddressBuilder() .setCity(entity.getCity()) .setHouseNumber(entity.getHouseNumber()) .setId(entity.getId()) .setStreet(entity.getStreet()) .setCountry(entity.getCountry()) .setLocation( new Location( entity.getLocation().getCoordinates().get(1), entity.getLocation().getCoordinates().get(0))) .setPostCode(entity.getPostCode()) .createAddress(); } GeoJsonPoint toEntity(Location location) { return new GeoJsonPoint(location.getLongitude(), location.getLatitude()); } }
32.933333
77
0.710526
6b3c39590b75be24bad0befcc075f7035995a976
407
swift
Swift
SwiftDI/Sources/Resolver.swift
robertofrontado/SwiftDI
a03b2c6e48a57d533777cf5f97dc5ca8ffbeb719
[ "MIT" ]
8
2020-04-20T09:22:55.000Z
2021-06-25T11:05:08.000Z
SwiftDI/Sources/Resolver.swift
robertofrontado/SwiftDI
a03b2c6e48a57d533777cf5f97dc5ca8ffbeb719
[ "MIT" ]
null
null
null
SwiftDI/Sources/Resolver.swift
robertofrontado/SwiftDI
a03b2c6e48a57d533777cf5f97dc5ca8ffbeb719
[ "MIT" ]
null
null
null
// // Resolver.swift // SwiftDI // // Created by Roberto Frontado on 23/02/2020. // Copyright © 2020 Roberto Frontado. All rights reserved. // internal enum Resolver { case single(object: Any) case factory(block: () -> Any) func resolve() -> Any { switch self { case .single(let object): return object case .factory(let block): return block() } } }
20.35
59
0.594595
4430c8cf6acabc19030dc504a9134803814effae
476
py
Python
Python/questions/UniquePaths/unique-paths.py
udcymen/leetcode
7c7c4085e6a8cea7106dd8bca86b370ca53e3ddd
[ "MIT" ]
null
null
null
Python/questions/UniquePaths/unique-paths.py
udcymen/leetcode
7c7c4085e6a8cea7106dd8bca86b370ca53e3ddd
[ "MIT" ]
null
null
null
Python/questions/UniquePaths/unique-paths.py
udcymen/leetcode
7c7c4085e6a8cea7106dd8bca86b370ca53e3ddd
[ "MIT" ]
null
null
null
def uniquePaths(m: int, n: int) -> int: dp = [[0 for _ in range(m)] for _ in range(n)] for i in range(m): dp[0][i] = 1 for j in range(n): dp[j][0] = 1 for i in range(1, n): for j in range(1, m): dp[i][j] = dp[i - 1][j] + dp[i][j - 1] return dp[-1][-1] if __name__ == "__main__": print(uniquePaths(3, 7)) print(uniquePaths(3, 2)) print(uniquePaths(7, 3)) print(uniquePaths(3, 3))
22.666667
50
0.47479
5803bdbc0dc6b07f120c5b873b70afea3847abc3
2,345
swift
Swift
Example/ZHLRouter/ZHLPDFViewController.swift
Tang-Hai/ZHLRouter
c424f952ff580eb71532f7a2434af60117f94c47
[ "MIT" ]
null
null
null
Example/ZHLRouter/ZHLPDFViewController.swift
Tang-Hai/ZHLRouter
c424f952ff580eb71532f7a2434af60117f94c47
[ "MIT" ]
null
null
null
Example/ZHLRouter/ZHLPDFViewController.swift
Tang-Hai/ZHLRouter
c424f952ff580eb71532f7a2434af60117f94c47
[ "MIT" ]
null
null
null
// // ZHLPDFViewController.swift // ZHLRouter_Example // // Created by MAC on 2021/6/9. // Copyright © 2021 tanghai. All rights reserved. // import UIKit class ZHLPDFViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! var name: String = "" override func viewDidLoad() { super.viewDidLoad() self.pdf() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(false, animated: true) } func pdf() { // Create a URL for the PDF file. guard let path = Bundle.main.path(forResource: self.name, ofType: "pdf") else { return } let url = URL(fileURLWithPath: path) // Instantiate a `CGPDFDocument` from the PDF file's URL. guard let document = CGPDFDocument(url as CFURL) else { return } // Get the first page of the PDF document. Note that page indices start from 1 instead of 0. guard let page = document.page(at: 1) else { return } print(document.numberOfPages); // Fetch the page rect for the page we want to render. let pageRect = page.getBoxRect(.mediaBox) // Optionally, specify a cropping rect. Here, we don’t want to crop so we keep `cropRect` equal to `pageRect`. let cropRect = pageRect if #available(iOS 10.0, *) { let renderer = UIGraphicsImageRenderer(size: cropRect.size) let img = renderer.image { ctx in // Set the background color. UIColor.white.set() ctx.fill(CGRect(x: 0, y: 0, width: cropRect.width, height: cropRect.height)) // Translate the context so that we only draw the `cropRect`. ctx.cgContext.translateBy(x: -cropRect.origin.x, y: pageRect.size.height - cropRect.origin.y) // Flip the context vertically because the Core Graphics coordinate system starts from the bottom. ctx.cgContext.scaleBy(x: 1.0, y: -1.0) // Draw the PDF page. ctx.cgContext.drawPDFPage(page) } self.imageView.image = img; } else { // Fallback on earlier versions } } }
32.123288
118
0.593603
ff761144fdb405559153f7ec1ffedb9d9e57923b
102
py
Python
declaraciones/translator_gdl/apps.py
rafaelhn2021/proyecto
97d01a0524df782985342bf07671ab60e318657f
[ "MIT" ]
null
null
null
declaraciones/translator_gdl/apps.py
rafaelhn2021/proyecto
97d01a0524df782985342bf07671ab60e318657f
[ "MIT" ]
null
null
null
declaraciones/translator_gdl/apps.py
rafaelhn2021/proyecto
97d01a0524df782985342bf07671ab60e318657f
[ "MIT" ]
2
2021-07-15T17:20:10.000Z
2022-03-18T10:26:38.000Z
from django.apps import AppConfig class TranslatorGdlConfig(AppConfig): name = 'translator_gdl'
17
37
0.784314
9c056d9dd2905e24c0fd626626f4d4619b8f986c
620
rs
Rust
src/block.rs
arucil/bittyset
ee8cf9f7068c576f3314a4929803327afd08c331
[ "MIT" ]
null
null
null
src/block.rs
arucil/bittyset
ee8cf9f7068c576f3314a4929803327afd08c331
[ "MIT" ]
null
null
null
src/block.rs
arucil/bittyset
ee8cf9f7068c576f3314a4929803327afd08c331
[ "MIT" ]
null
null
null
use std::ops::{BitOrAssign, BitAndAssign, BitXorAssign}; use std::hash::Hash; use num_traits::int::PrimInt; /// A trait for representing elements of the underlying bit vector of `BitSet`. pub trait BitBlock: Default + Eq + Hash + PrimInt + BitOrAssign + BitAndAssign + BitXorAssign { #[doc(hidden)] const NUM_BITS: usize; } macro_rules! impl_bit_block { ($type:ty) => { impl BitBlock for $type { const NUM_BITS: usize = std::mem::size_of::<$type>() * 8; } } } impl_bit_block!(u8); impl_bit_block!(u16); impl_bit_block!(u32); impl_bit_block!(u64); impl_bit_block!(u128); impl_bit_block!(usize);
23.846154
79
0.693548
74302f6fe1bdd9605c85a7c7f9b7efa4c25e6ef5
9,620
css
CSS
css/sea_atlas_explorer.css
HarvardMapCollection/seaAtlasExplorer
c8979681691905f1710522be30ac976f92e6eb3b
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
3
2015-07-20T11:49:00.000Z
2015-11-05T00:34:10.000Z
css/sea_atlas_explorer.css
HarvardMapCollection/seaAtlasExplorer
c8979681691905f1710522be30ac976f92e6eb3b
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
css/sea_atlas_explorer.css
HarvardMapCollection/seaAtlasExplorer
c8979681691905f1710522be30ac976f92e6eb3b
[ "Apache-2.0", "BSD-2-Clause", "MIT" ]
null
null
null
/* Page-wide */ @import url(http://fonts.googleapis.com/css?family=Cinzel:400,700|Lusitana:400,700); body { margin: 0; font-family: 'Lusitana', Georgia, serif; } a { color: #000; } a:visited { color: #000; } #map { width: 100%; height: 100vh; } /* style to highlight/flash */ .flash-add { color: #FFFF00; transition: color 200ms; } .flash-remove { color: #FF0000; transition: color 200ms; } /* breadcrumbs */ .leaflet-top { top: 2em; } #breadcrumb-wrapper { position: absolute; top: 0px; left: 0px; background-color: rgba(94, 0, 0, 0.6); width: 100%; } #breadcrumb-wrapper a { color: #fff; } #breadcrumb-wrapper a:visited { color: #fff; } #breadcrumb { color: #fff; font-size: .9em; padding: 0.25em 0.5em 0.25em 0.5em; } /* Sidebar general styling */ #sidebar { opacity: 0.9; top: 2em; overflow: visible; } .sidebar-tabs { background-color: rgba(100,100,100,0.5); width: 100%; } .sidebar-tabs i { transition: 200ms; } .sidebar-tabs > li { position: relative; display: block; width: 40px; overflow: visible; float: left; background-color: rgba(249, 244, 238, 0.4); border-radius: 5px 5px 0 0; box-shadow: 5px 5px 5px #6E6E6E; transition: all 200ms; } .sidebar-tabs > li.active { width: 200px; background-color: rgba(249, 244, 238, 0.9); color: #333; border-radius: 5px 5px 0px 0px; transition: all 200ms; } .sidebar-tabs > li.active > a { text-align: left; } .sidebar-tabs > li:hover { border-radius: 5px 5px 0px 0px; } .sidebar-tabs > li i { padding: 12px; } .tab-description { display: none; overflow: hidden; } .sidebar-content { background-color: rgba(249, 244, 238, 0.9); left: 0px; right: 0; top: 40px; bottom: 0; } .sidebar-pane { width: 460px; } li.active .tab-description { display: inline; } .collapsed .sidebar-pane { display:none; } .collapsed .sidebar-content { position: relative; } .collapsed .sidebar-tabs li { width: 100%; box-shadow: none; } .collapsed .sidebar-tabs { background-color: rgba(249, 244, 238, 0.9); } /* Sidebar Contents */ #sidebar .chart-scope { border-bottom: 1px dotted black; margin: 0; padding-top: .3em; padding-bottom: .3em; } #sidebar .chart-scope:last-child { border-bottom: none; } .view-chart-column-label { margin: 0; text-align: right; } #sidebar .add-to-map { float: right; margin-right: 2.5em; } .id-link { padding-left: .3em; cursor: pointer; font-weight: normal; font-size: 18px; } #currentView .id-link { width: 87%; display: inline-block; } #currentView .awesome-marker, #bigList .awesome-marker { margin: 5px 3px 0; } #bigList .id-link { width: 87%; display: inline-block; } .id-link i.fa { color: #467176; } .iconBG { background-color: #467176; border: 1px solid #3a5964; border-radius: 20px; color: white; padding:.5em .2em .2em .2em; width: 1.4em; height: 1.1em; float: left; margin-right: .2em; text-align: center; } .starredScope { margin-top: .2em; } .selected-chart { margin-bottom: 1em; } .selected-chart .id-link { margin-top: 0px; margin-bottom: 0px; } .transparency-slider label { float: left; font-size: 14px; } .selection-checkbox { float: right; padding-top: 10px; } .id-link:visited { color: rgb(215, 71, 71); } /* Controls next to sidebar */ .side-icon { background-color: white; padding: .8em 0 .8em 0; cursor: pointer; width: 26px; text-align: center; } #marker-switch { color: #888; } #marker-switch.active { color: #D43E2A; } #bookmark-link-text { position: absolute; top: 5px; left: 35px; display: none; } #bookmark-link-text.active { display: inline-block; } #bookmark-link input { border-color: white; border-style: solid; border-radius: 3px; padding: 0.25em; } #bookmark-link-text::before { background-color: white; content: "\00a0"; display: block; height: 8px; width: 8px; position: absolute; bottom: 6.5px; left: -3px; transform: rotate(47deg) skew(5deg); -moz-transform: rotate(47deg) skew(5deg); -ms-transform: rotate(47deg) skew(5deg); -o-transform: rotate(47deg) skew(5deg); -webkit-transform: rotate(47deg) skew(5deg); box-shadow: 2px 2px 2px 0 rgba( 178, 178, 178, .4 ); z-index: -1; } .counter { font-size: 14px; } /* Collapsible menus CSS */ .arrow { float: left; padding-top: 0.4em; padding-right: 0.2em; } .collapseL1 { background-color: rgba(178, 132, 49, 0.25); border-radius: 5px; margin-top: .25em; margin-bottom: .25em; } .collapseL1>:nth-child(odd) { /* Header */ padding: 5px; background-color: rgba(0,0,0,0); margin: auto; font-family: 'Cinzel', Georgia, serif; } .collapseL1>:nth-child(odd) h1 { font-weight: normal; font-size: 24px; margin-top: .2em; margin-bottom: .2em; } .collapseL1>:nth-child(odd) h2 { font-weight: normal; font-size: 22px; margin: 0px 0px 0px 52px; } .collapseL1>:nth-child(odd) h3 { font-weight: normal; font-size: 12px; margin: 0px 0px 0px 52px; } .collapseL1>:nth-child(odd) h3 + span { margin-left: 52px; } .collapseL1>:nth-child(odd):hover { cursor: pointer; -moz-user-select: none; /* mozilla browsers */ -khtml-user-select: none; /* webkit browsers */ } .collapseL1>:nth-child(even) { /* Inner content section */ background-color: rgba(0,0,0,0); display: none; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .collapseL1>:nth-child(even) p { padding: 0px 5px; } .collapseL1>:first-child { /* First header in list */ } .collapseL1>:nth-last-child(2) { /* Last header in list */ } /* Infobox (bottom right) */ #infobox-container { position: absolute; bottom: 18px; right: 10px; border-radius: 5px; max-width: 20%; background-position: bottom 160px right 390px; background-attachment: fixed; } #infobox { background-color: rgba(255,255,255,0.9); padding-top:1px; border-radius: 5px; } #infobox div h3 { margin-top: .9em; margin-bottom: 0; font-family: "Cinzel", Georgia, serif; font-weight: normal; font-size: 18px; } #infobox-metadata { font-family: "Cinzel", Georgia, serif; font-size: 13px; } .infobox-left-box { width: 1.2em; } #infobox div p { margin-top: .2em; margin-bottom: .2em; } #infobox div p.collectionName { text-decoration: underline; } #infobox div p.authorName { } #infobox div p#reset-highlight { cursor: pointer; text-decoration: underline; font-size: 80%; } #reset-highlight { position: absolute; top: -12px; right: -12px; background-color: #C34E4C; border-radius: 10px; padding: .2em; height: 1em; width: 1em; text-align: center; color: white; cursor: pointer; } #chartCount { font-size: 14px; text-align: right; padding: .3em; } #hoverInfobox { position: relative; margin: .3em; padding:.3em; border: solid 2px #53868B; border-radius: 5px; } #hoverInfobox .infobox-title { color: #3a5d60; border: 2px solid #53868B; } #highlightInfobox { position: relative; margin: .3em; padding:.3em; border: solid 2px #C34E4C; border-radius: 5px; } #highlightInfobox .infobox-title { color: #be4240; border: 2px solid #C34E4C; } .infobox-title { position: absolute; top: -2px; left: -2px; padding: 0px 0.3em; border-radius: 5px 0 5px 0; font-size: 14px; } /* Chart added popup box */ #chartAddedNotification { position: absolute; top: 48px; left: -32px; width: 13em; background-color: white; border-radius: 5px; padding-top: 0.2em; padding-bottom: 0.2em; padding-right: .5em; padding-left: .5em; opacity: 0; z-index: -1000; transition: all 400ms; box-shadow: 2px 2px 2px 0 rgba( 178, 178, 178, .4 ); } #chartAddedNotification::before { background-color: white; content: "\00a0"; display: block; height: 8px; width: 8px; position: absolute; top: -4px; left: 46px; transform: rotate(47deg) skew(5deg); -moz-transform: rotate(47deg) skew(5deg); -ms-transform: rotate(47deg) skew(5deg); -o-transform: rotate(47deg) skew(5deg); -webkit-transform: rotate(47deg) skew(5deg); z-index: -1; } #chartAddedNotification p { margin: 0; } #chartAddedNotification.active { opacity: 90; z-index: 1000; transition: all 400ms; } /* Interface buttons */ .button { cursor: pointer; border: 2px solid #D43E2A; border-radius: 4px; box-shadow: 2px 2px 2px 0 rgba(110,110,110,0.6); padding: 0 .2em 0 .2em; background-color: #eba49b; } .button.disabled { cursor: default; border-color: #666; background-color: #777; color: #999; box-shadow: none; } /* Replaceing checkboxes with FontAwesome Icons */ input[type=checkbox] { display:none; } /* to hide the checkbox itself */ input[type=checkbox] + label:before { font-family: FontAwesome; display: inline-block; } /* Label after checkbox, place icon before */ input[type=checkbox] + label:before { content: "\f096"; } /* unchecked icon */ input[type=checkbox] + label:before { width:1.2em; font-weight:normal; font-size:initial; } /* space between checkbox and label */ input[type=checkbox]:checked + label:before { content: "\f046"; } /* checked icon */ #allAtlasesCheckboxContainer { text-align: right; } #allAtlasesCheckboxContainer label:before { float:right; width: 1.2em; text-align: left; padding-left: 0.3em; } /* Contact Form */ #form1 input[type=text] { border: 1px solid #555; font-size: 9pt; padding: 0.5em; } input#name, input#from, input#subject { width: 200px; } input#verif_box { width:75px; } textarea#message { width: 350px; } #form1 input[type=submit] { background:rgba(30,32,30,0.8); border: none; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; color: #fff; cursor: pointer; font-family: 'Cinzel', Georgia, serif; margin: 2em auto 1.5em; padding: 0.5em; text-transform: lowercase; width: 150px; }
18.254269
130
0.674324
6d8c616fc0463a622172481f905b649e0f4d44e6
5,555
tsx
TypeScript
frontend/src/pages/IstioConfigNew/AuthorizationPolicyForm/To/OperationBuilder.tsx
kiali/swscore
8ec112b86eaa27e91a7be74ddaf07284d4eef455
[ "Apache-2.0" ]
null
null
null
frontend/src/pages/IstioConfigNew/AuthorizationPolicyForm/To/OperationBuilder.tsx
kiali/swscore
8ec112b86eaa27e91a7be74ddaf07284d4eef455
[ "Apache-2.0" ]
17
2018-03-12T22:07:37.000Z
2018-03-23T14:48:52.000Z
frontend/src/pages/IstioConfigNew/AuthorizationPolicyForm/To/OperationBuilder.tsx
kiali/swscore
8ec112b86eaa27e91a7be74ddaf07284d4eef455
[ "Apache-2.0" ]
2
2018-03-13T08:25:26.000Z
2018-03-21T11:13:54.000Z
import * as React from 'react'; import { cellWidth, ICell, Table, TableBody, TableHeader } from '@patternfly/react-table'; // Use TextInputBase like workaround while PF4 team work in https://github.com/patternfly/patternfly-react/issues/4072 import { Button, ButtonVariant, FormSelect, FormSelectOption, TextInputBase as TextInput } from '@patternfly/react-core'; import { PlusCircleIcon } from '@patternfly/react-icons'; type Props = { onAddTo: (operation: { [key: string]: string[] }) => void; }; type State = { operationFields: string[]; operation: { [key: string]: string[]; }; newOperationField: string; newValues: string; }; const INIT_OPERATION_FIELDS = [ 'hosts', 'notHosts', 'ports', 'notPorts', 'methods', 'notMethods', 'paths', 'notPaths' ].sort(); const headerCells: ICell[] = [ { title: 'Operation Field', transforms: [cellWidth(20) as any], props: {} }, { title: 'Values', transforms: [cellWidth(80) as any], props: {} }, { title: '', props: {} } ]; class OperationBuilder extends React.Component<Props, State> { constructor(props: Props) { super(props); this.state = { operationFields: Object.assign([], INIT_OPERATION_FIELDS), operation: {}, newOperationField: INIT_OPERATION_FIELDS[0], newValues: '' }; } onAddNewOperationField = (value: string, _) => { this.setState({ newOperationField: value }); }; onAddNewValues = (value: string, _) => { this.setState({ newValues: value }); }; onAddOperation = () => { this.setState(prevState => { const i = prevState.operationFields.indexOf(prevState.newOperationField); if (i > -1) { prevState.operationFields.splice(i, 1); } prevState.operation[prevState.newOperationField] = prevState.newValues.split(','); return { operationFields: prevState.operationFields, operation: prevState.operation, newOperationField: prevState.operationFields[0], newValues: '' }; }); }; onAddOperationToList = () => { const toItem = this.state.operation; this.setState( { operationFields: Object.assign([], INIT_OPERATION_FIELDS), operation: {}, newOperationField: INIT_OPERATION_FIELDS[0], newValues: '' }, () => { this.props.onAddTo(toItem); } ); }; // @ts-ignore actionResolver = (rowData, { rowIndex }) => { const removeAction = { title: 'Remove Field', // @ts-ignore onClick: (event, rowIndex, rowData, extraData) => { // Fetch sourceField from rowData, it's a fixed string on children const removeOperationField = rowData.cells[0].props.children.toString(); this.setState(prevState => { prevState.operationFields.push(removeOperationField); delete prevState.operation[removeOperationField]; const newOperationFields = prevState.operationFields.sort(); return { operationFields: newOperationFields, operation: prevState.operation, newOperationField: newOperationFields[0], newValues: '' }; }); } }; if (rowIndex < Object.keys(this.state.operation).length) { return [removeAction]; } return []; }; rows = () => { const operatorRows = Object.keys(this.state.operation).map((operationField, i) => { return { key: 'operationKey' + i, cells: [<>{operationField}</>, <>{this.state.operation[operationField].join(',')}</>, <></>] }; }); if (this.state.operationFields.length > 0) { return operatorRows.concat([ { key: 'operationKeyNew', cells: [ <> <FormSelect value={this.state.newOperationField} id="addNewOperationField" name="addNewOperationField" onChange={this.onAddNewOperationField} > {this.state.operationFields.map((option, index) => ( <FormSelectOption isDisabled={false} key={'operation' + index} value={option} label={option} /> ))} </FormSelect> </>, <> <TextInput value={this.state.newValues} type="text" id="addNewValues" key="addNewValues" aria-describedby="add new operation values" name="addNewValues" onChange={this.onAddNewValues} /> </>, <> {this.state.operationFields.length > 0 && ( <Button variant={ButtonVariant.link} icon={<PlusCircleIcon />} onClick={this.onAddOperation} /> )} </> ] } ]); } return operatorRows; }; render() { return ( <> <Table aria-label="Operation Builder" cells={headerCells} rows={this.rows()} // @ts-ignore actionResolver={this.actionResolver} > <TableHeader /> <TableBody /> </Table> <Button variant={ButtonVariant.link} icon={<PlusCircleIcon />} isDisabled={Object.keys(this.state.operation).length === 0} onClick={this.onAddOperationToList} > Add Operation to To List </Button> </> ); } } export default OperationBuilder;
26.578947
118
0.561296
d64ab659470ffe02d152be5361d9ebecce8a2f21
738
cs
C#
src/Cecilia/ModuleParameters.cs
teo-tsirpanis/Cecilia
fee9b40914dde56b931aad14f842b00876324b95
[ "MIT" ]
null
null
null
src/Cecilia/ModuleParameters.cs
teo-tsirpanis/Cecilia
fee9b40914dde56b931aad14f842b00876324b95
[ "MIT" ]
2
2022-02-02T13:17:54.000Z
2022-03-30T20:23:05.000Z
src/Cecilia/ModuleParameters.cs
teo-tsirpanis/Cecilia
fee9b40914dde56b931aad14f842b00876324b95
[ "MIT" ]
null
null
null
// This file is part of Cecilia. // Licensed under the MIT License. #nullable enable namespace Cecilia { public sealed class ModuleParameters { public ModuleKind Kind { get; set; } = ModuleKind.Dll; public TargetRuntime Runtime { get; set; } = TargetRuntime.Net_4_0; public uint? Timestamp { get; set; } public TargetArchitecture Architecture { get; set; } = TargetArchitecture.I386; public IAssemblyResolver? AssemblyResolver { get; set; } public IMetadataResolver? MetadataResolver { get; set; } public IMetadataImporterProvider? MetadataImporterProvider { get; set; } public IReflectionImporterProvider? ReflectionImporterProvider { get; set; } } }
27.333333
87
0.688347
8ddcaaf29ebc7cc2663669954d9b5b3d2bf9f7fb
2,328
js
JavaScript
src/components/Xgt/Afh.js
Godi13/Answer-react
b89aa8f96ca86f0b9dd4683ee9d45b43dbef5dbb
[ "CC0-1.0" ]
null
null
null
src/components/Xgt/Afh.js
Godi13/Answer-react
b89aa8f96ca86f0b9dd4683ee9d45b43dbef5dbb
[ "CC0-1.0" ]
null
null
null
src/components/Xgt/Afh.js
Godi13/Answer-react
b89aa8f96ca86f0b9dd4683ee9d45b43dbef5dbb
[ "CC0-1.0" ]
null
null
null
import React from 'react'; import Nav from '../Nav'; import Head from '../Jz/Head'; import Table from '../Jz/Table'; import Ddwh from '../Jz/Ddwh'; import Gnsj from '../Jz/Gnsj'; import Jt from '../Jz/Jt'; export default class Afh extends React.Component { render() { var headers = [ 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_01.png', 'http://7xoblm.com1.z0.glb.clouddn.com/AFH/afuhan_02.png', 'http://7xoblm.com1.z0.glb.clouddn.com/AFH/afuhan_03.png', 'http://7xoblm.com1.z0.glb.clouddn.com/images/cpdh_01_05.png' ] var tables = [ 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_04.jpg', 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_05.jpg', 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_06.jpg' ] var ddwhs = [ 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_07.jpg', 'http://7xoblm.com1.z0.glb.clouddn.com/AFH/afuhan_08.png', 'http://7xoblm.com1.z0.glb.clouddn.com/AFH/afuhan_09.png', 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_10.jpg' ] var gnsjs = [ 'http://7xoblm.com1.z0.glb.clouddn.com/AFH/afuhan_11.png', 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_12.jpg', 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_13.jpg', 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_14.jpg', ] var jts = [ 'http://7xoblm.com1.z0.glb.clouddn.com/images/cpdh_01_05.png', 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_15.jpg', 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_16.jpg', 'http://7xoblm.com1.z0.glb.clouddn.com/images/cpdh_01_05.png', 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_17.jpg', 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_18.jpg', 'http://7xoblm.com1.z0.glb.clouddn.com/images/cpdh_01_05.png', 'http://7xoblm.com1.z0.glb.clouddn.com/afh/afuhan_19.jpg', 'http://7xoblm.com1.z0.glb.clouddn.com/images/cpdh_01_05.png', ] return ( <div> <Nav style="nav-light nav-xgt"/> <div className="tc"></div> <Head data={headers} style="xgt"/> <Table data={tables} style="afh"/> <Ddwh data={ddwhs} style="ddwh-afh"/> <Gnsj data={gnsjs} style="gnsj-afh"/> <Jt data={jts} style="jt-afh"/> </div> ) } }
36.375
68
0.629296
4cf3abf20c70d70dfc33abae625f9ece15844f46
2,304
py
Python
sam_rest/sam_endpoints.py
puruckertom/sam_app
bb06ccc94a117131a1dc76d849412cdc4f3f7ddd
[ "Unlicense" ]
1
2016-03-20T21:15:52.000Z
2016-03-20T21:15:52.000Z
sam_rest/sam_endpoints.py
puruckertom/sam_app
bb06ccc94a117131a1dc76d849412cdc4f3f7ddd
[ "Unlicense" ]
null
null
null
sam_rest/sam_endpoints.py
puruckertom/sam_app
bb06ccc94a117131a1dc76d849412cdc4f3f7ddd
[ "Unlicense" ]
null
null
null
import os import random import shutil import string import sam_input_generator # Generate a random ID for file save def id_generator(size=6, chars=string.ascii_uppercase + string.digits): return ''.join(random.choice(chars) for x in range(size)) def read_sam_input_file(file): with open(file, 'r') as f: file_contents = f.read() return file_contents def delete_sam_input_files(path): shutil.rmtree(path) def sam_input_prep(no_of_processes, name_temp, temp_sam_run_path, args): """ Helper function to create temporary directory and generate the SAM.inp file(s) for SAM run. :param no_of_processes: int, number of sections the list of HUCs for the SAM run will be divided into :param temp_sam_run_path: str, absolute path of the temporary directory to place the SAM input file(s) and, if necessary, the output files :param args: dict, the input values POSTed by the user :return: list, list containing the number of 'rows'/HUC12s for each worker/process, which is passed to SuperPRZM """ if name_temp is None: name_temp = id_generator() if temp_sam_run_path is None: temp_sam_run_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.pardir, 'sam', 'bin', 'Outputs', name_temp) if not os.path.exists(temp_sam_run_path): print("Creating SAM run temporary directory: ", str(temp_sam_run_path)) os.makedirs(temp_sam_run_path) print("Creating SAM run temporary sub-directory: ", str(os.path.join(temp_sam_run_path, 'output'))) os.makedirs(os.path.join(temp_sam_run_path, 'output')) sam_input_file_path = os.path.join(temp_sam_run_path, 'SAM.inp') # Generate "SAM.inp" file and return list of 'Julian' days for the simulation list_of_julian_days = sam_input_generator.generate_sam_input_file(args, sam_input_file_path) sam_input_file = read_sam_input_file(sam_input_file_path) delete_sam_input_files(temp_sam_run_path) return sam_input_file # TODO: Remove leftovers from copy-paste # for x in range(no_of_processes): # shutil.copyfile(sam_input_file_path, os.path.join(temp_sam_run_path, 'SAM' + two_digit(x) + '.inp')) # return list_of_julian_days
36
142
0.711806
758e32ef42fa5bddb009410a16f571ce84f04f44
456
css
CSS
ASYA-SYSTEM/css/morris.css
IekoMolina/SYSTIMP-ASYA
3f5216d612155d1ac95c1ac2ec16829d16268554
[ "MIT" ]
null
null
null
ASYA-SYSTEM/css/morris.css
IekoMolina/SYSTIMP-ASYA
3f5216d612155d1ac95c1ac2ec16829d16268554
[ "MIT" ]
null
null
null
ASYA-SYSTEM/css/morris.css
IekoMolina/SYSTIMP-ASYA
3f5216d612155d1ac95c1ac2ec16829d16268554
[ "MIT" ]
null
null
null
.morris-hover{ position:absolute; z-index:1000 } .morris-hover.morris-default-style{ border-radius:10px; padding:6px; color:#666; background:rgba(255,255,255,0.8); border:solid 2px rgba(230,230,230,0.8); font-family:sans-serif; font-size:12px; text-align:center } .morris-hover.morris-default-style .morris-hover-row-label{ font-weight:bold; margin:0.25em 0 } .morris-hover.morris-default-style .morris-hover-point{ white-space:nowrap; margin:0.1em 0 }
17.538462
59
0.758772
feb3d99179f615ad849ea2ff5d1ab5f57d31f422
1,050
rs
Rust
src/rust/src/denormalize.rs
anonymokata/72F97953-5697-403B-9E58-C069EB13574B
beea2decdf103e93264dbf0468e8f46499367b9b
[ "MIT" ]
1
2017-02-28T01:34:14.000Z
2017-02-28T01:34:14.000Z
src/rust/src/denormalize.rs
ben--/kata-rnc
4011c5a513e9c10bcfd923b9430a303b1d6891b0
[ "MIT" ]
null
null
null
src/rust/src/denormalize.rs
ben--/kata-rnc
4011c5a513e9c10bcfd923b9430a303b1d6891b0
[ "MIT" ]
null
null
null
pub fn denormalize(num: &str) -> String { let num = num.replace("IV", "IIII"); let num = num.replace("IX", "VIIII"); let num = num.replace("XL", "XXXX"); let num = num.replace("XC", "LXXXX"); let num = num.replace("CD", "CCCC"); let num = num.replace("CM", "DCCCC"); num } #[cfg(test)] mod tests { use super::denormalize; #[test] fn denormalize_iv() { assert_eq!("IIII", denormalize("IV")); } #[test] fn denormalize_ix() { assert_eq!("VIIII", denormalize("IX")); } #[test] fn denormalize_xiv_performs_a_partial_denormalization_on_tail() { assert_eq!("XIIII", denormalize("XIV")); } #[test] fn denormalize_xl() { assert_eq!("XXXX", denormalize("XL")); } #[test] fn denormalize_xc() { assert_eq!("LXXXX", denormalize("XC")); } #[test] fn denormalize_cd() { assert_eq!("CCCC", denormalize("CD")); } #[test] fn denormalize_cm() { assert_eq!("DCCCC", denormalize("CM")); } }
21
69
0.54381
a7e251c26835161fbeb3afedab7cd77921e499a0
275
css
CSS
app/admin/widgets/dashboardcontainer/assets/css/dashboardcontainer.css
nishwan-abbas/TastyIgniter
f18192b0c22f6e1f5d72293a439f0751f9611d7e
[ "MIT" ]
2,398
2015-10-03T14:28:08.000Z
2022-03-31T08:15:54.000Z
app/admin/widgets/dashboardcontainer/assets/css/dashboardcontainer.css
nishwan-abbas/TastyIgniter
f18192b0c22f6e1f5d72293a439f0751f9611d7e
[ "MIT" ]
745
2015-09-28T18:04:35.000Z
2022-03-31T11:52:42.000Z
app/admin/widgets/dashboardcontainer/assets/css/dashboardcontainer.css
MinjaMiladinovic/TastyIgniter
14c26bebbc9a24b50e6cf71dac532871455d59e6
[ "MIT" ]
908
2015-10-03T18:20:04.000Z
2022-03-31T13:32:08.000Z
.dashboard-widgets { margin-top: -15px; } .dashboard-toolbar { padding: 0 0 20px; } .widget-item-action { position: absolute; right: 0; top: 0; display: none; } .widget-item:hover .widget-item-action { display: block; } .widget-title { padding-bottom: 10px; }
15.277778
40
0.661818
ea725d57b4504f79ad58ffa45c0914a59e6c3371
1,225
go
Go
internal/gateway/hub.go
n7down/iot-core
e0d14d2ca843d77beb04531bdb14f188c5558e3c
[ "MIT" ]
null
null
null
internal/gateway/hub.go
n7down/iot-core
e0d14d2ca843d77beb04531bdb14f188c5558e3c
[ "MIT" ]
null
null
null
internal/gateway/hub.go
n7down/iot-core
e0d14d2ca843d77beb04531bdb14f188c5558e3c
[ "MIT" ]
null
null
null
package gateway import ( "fmt" log "github.com/sirupsen/logrus" ) // Hub maintains the set of active clients and broadcasts messages to the // clients. type Hub struct { // Registered clients. clients map[string]*Client // Register requests from the clients. register chan *Client // Unregister requests from clients. unregister chan *Client } func NewHub() *Hub { return &Hub{ register: make(chan *Client, 10), unregister: make(chan *Client, 10), clients: make(map[string]*Client), } } func (h *Hub) Send(deviceID string, message string) { if _, ok := h.clients[deviceID]; ok { h.clients[deviceID].Send <- []byte(message) } } func (h *Hub) Run() { for { select { case client := <-h.register: //if _, ok := h.clients[client.ID]; ok { //delete(h.clients, client.ID) //close(client.Send) //log.Info(fmt.Sprintf("Client disconnected: %v", client)) //} h.clients[client.ID] = client log.Info(fmt.Sprintf("Device connected: %v", client)) case client := <-h.unregister: if _, ok := h.clients[client.ID]; ok { delete(h.clients, client.ID) close(client.Send) // TODO: call detach? log.Info(fmt.Sprintf("Device disconnected: %v", client)) } } } }
21.12069
73
0.648163
5c7605bbf5c17433febcfdbd9d27cea909d870e9
122
lua
Lua
fn/cadr/cadr.lua
aiq/luazdf
4f23aa7c6c9ce38f72b361b5a7c067480a97a178
[ "0BSD" ]
48
2018-02-14T08:28:58.000Z
2021-12-08T02:06:43.000Z
fn/cadr/cadr.lua
aiq/luazdf
4f23aa7c6c9ce38f72b361b5a7c067480a97a178
[ "0BSD" ]
10
2018-02-23T11:55:20.000Z
2019-09-03T19:08:02.000Z
fn/cadr/cadr.lua
aiq/luazdf
4f23aa7c6c9ce38f72b361b5a7c067480a97a178
[ "0BSD" ]
2
2018-02-26T11:57:12.000Z
2018-03-06T18:37:43.000Z
--ZFUNC-cadr-v1 local function cadr( arr ) --> val if not arr then return nil end return arr[ 2 ] end return cadr
13.555556
34
0.663934
5dc04855bd8ddedfd58cc73ff07656b9fcc9f8ac
882
cpp
C++
leetcode/Hashmap/49.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
leetcode/Hashmap/49.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
leetcode/Hashmap/49.cpp
codehuanglei/-
933a55b5c5a49163f12e0c39b4edfa9c4f01678f
[ "MIT" ]
null
null
null
#include<iostream> #include<unordered_map> #include<vector> #include<algorithm> using namespace std; class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> res; unordered_map<string,vector<string>> map; for(string s : strs){ string key = s; sort(key.begin(),key.end()); map[key].push_back(s); } // 想要拷贝元素:for(auto x : range) // 想要修改元素 : for(auto&& x : range) // 想要只读元素:for(const auto& x : range) for(const auto& p : map){ res.push_back(p.second); } return res; } }; void print_vec(vector<vector<string>>& s){ for(vector<string> vec : s){ for(string c : vec){ cout<<c<<' '; } cout<<endl; } } int main(){ }
23.837838
65
0.510204
4cc99cb7ccaf3799ef9775abe3573dd0a256e3c0
2,574
py
Python
csng_invariances/_dnn_blocks/script_2.py
Leeeeon4/csng_invariances
48ce94bcc424292e260b82bb081411cd55da4aef
[ "MIT" ]
null
null
null
csng_invariances/_dnn_blocks/script_2.py
Leeeeon4/csng_invariances
48ce94bcc424292e260b82bb081411cd55da4aef
[ "MIT" ]
13
2021-09-08T12:42:37.000Z
2021-09-30T13:41:08.000Z
csng_invariances/_dnn_blocks/script_2.py
Leeeeon4/csng_invariances
48ce94bcc424292e260b82bb081411cd55da4aef
[ "MIT" ]
1
2022-01-13T10:48:05.000Z
2022-01-13T10:48:05.000Z
import sys sys.path.append("/home/baroni/reconstruct_images/") import wandb from datamodules import * from models import * from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import EarlyStopping import pytorch_lightning as pl # Set up your default hyperparameters default = { 'loss' : 'mse', "input_size": 5000, "output_size": 64, "resize_stim": False, "h_1_size": 1000, "intermediate_img_channels": 64, "conv_1_ch": 256, "conv_2_ch": 256, "conv_3_ch": 256, # "conv_4_ch": 256, "conv_1_ks": 7, "conv_2_ks": 5, "conv_3_ks": 3, # "conv_4_ks": 3, "dropout_FC": 0.2, "dropout_CE": 0, "dropout_CD": 0, "act_f": "relu", # "last_layer_act_f": "sigm", "batchnorm": True, "order_FC": "bda", "order_CE": "bda", "order_CD": "bda", "lr": 0.01, "batch_size": 210, "max_epochs": 500, } # Pass your defaults to wandb.init run = wandb.init(config=default, entity="csng-cuni", project="Zhang_img_rec") # Access all hyperparameter values through wandb.config config = wandb.config # Set up model model = Zhang_ImgReconstructor(config) print(model) file = "/home/baroni/reconstruct_images/data/stim_size=64/randomly_selecting/n_neurons=5000.pickle" dm = StimRespDataModule(file, config) # define logger for trainer wandb_logger = WandbLogger() early_stop = EarlyStopping(monitor="val/loss", patience=10) class WandbImageCallback(pl.Callback): def __init__(self, dm, num_img=32): super().__init__() self.num_imgs = num_img def on_test_end(self, trainer, pl_module): imgs = next(iter(dm.test_dataloader()))[0][: self.num_imgs].to( device=pl_module.device ) recs = pl_module( next(iter(dm.test_dataloader()))[1][: self.num_imgs] .to(device=pl_module.device) .float() ) mosaics = torch.cat([imgs, recs], dim=-2) caption = "Top: stimuli, Bottom: reconstructions" trainer.logger.experiment.log( { "images and reconstructions": [ wandb.Image(mosaic, caption=caption) for mosaic in mosaics ], "global_step": trainer.global_step, } ) rec_callback = WandbImageCallback(dm) trainer = pl.Trainer( callbacks=[early_stop, rec_callback], max_epochs=config["max_epochs"], gpus=[0], logger=wandb_logger, log_every_n_steps=1, ) trainer.fit(model, dm) # test results: x = trainer.test(ckpt_path="best", datamodule=dm)
27.382979
99
0.642968
da989fe8fe60ddb588215bd5e6120d38866f1779
1,960
php
PHP
src/Sulu/Bundle/CategoryBundle/Tests/Unit/DependencyInjection/DeprecationCompilerPassTest.php
Tactics/sulu-old
1716bbd13a3e8b8363cb6e2a14267c6eb2d20868
[ "MIT" ]
null
null
null
src/Sulu/Bundle/CategoryBundle/Tests/Unit/DependencyInjection/DeprecationCompilerPassTest.php
Tactics/sulu-old
1716bbd13a3e8b8363cb6e2a14267c6eb2d20868
[ "MIT" ]
null
null
null
src/Sulu/Bundle/CategoryBundle/Tests/Unit/DependencyInjection/DeprecationCompilerPassTest.php
Tactics/sulu-old
1716bbd13a3e8b8363cb6e2a14267c6eb2d20868
[ "MIT" ]
null
null
null
<?php /* * This file is part of Sulu. * * (c) MASSIVE ART WebServices GmbH * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Sulu\Bundle\CategoryBundle\Tests\Unit\DependencyInjection; use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase; use Sulu\Bundle\CategoryBundle\DependencyInjection\DeprecationCompilerPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; /** * Test the deprecation transformation compiler pass. */ class DeprecationCompilerPassTest extends AbstractCompilerPassTestCase { /** * {@inheritdoc} */ protected function registerCompilerPass(ContainerBuilder $container) { $container->addCompilerPass(new DeprecationCompilerPass()); } public function testDeprecatedEntityParameters() { $this->setParameter('sulu.model.category.class', 'path-to-category-entity'); $this->setParameter('sulu.model.keyword.class', 'path-to-keyword-entity'); $this->compile(); $this->assertContainerBuilderHasParameter('sulu_category.entity.category', 'path-to-category-entity'); $this->assertContainerBuilderHasParameter('sulu_category.entity.keyword', 'path-to-keyword-entity'); } public function testDeprecatedRepositoryServices() { $categoryRepositoryDefinition = new Definition(); $this->setDefinition('sulu.repository.category', $categoryRepositoryDefinition); $keywordRepositoryDefinition = new Definition(); $this->setDefinition('sulu.repository.keyword', $keywordRepositoryDefinition); $this->compile(); $this->assertContainerBuilderHasAlias('sulu_category.category_repository', 'sulu.repository.category'); $this->assertContainerBuilderHasAlias('sulu_category.keyword_repository', 'sulu.repository.keyword'); } }
35
111
0.742857
f4b71ab53769e335d4870feeef6d4a486c4ffe64
4,770
ts
TypeScript
ide/src/tests/slice/util/slice_helpers.ts
willcrichton/flowistry
3363441c10646621cf656cc8e80d162a77b5b03a
[ "MIT" ]
933
2021-08-21T10:46:54.000Z
2022-03-31T08:24:33.000Z
ide/src/tests/slice/util/slice_helpers.ts
willcrichton/rust-slicer
2f70b97f9ec9a9bc5e2e5b74a25873a22963e913
[ "MIT" ]
44
2021-09-20T20:11:48.000Z
2022-03-28T19:05:07.000Z
ide/src/tests/slice/util/slice_helpers.ts
willcrichton/rust-slicer
2f70b97f9ec9a9bc5e2e5b74a25873a22963e913
[ "MIT" ]
19
2021-08-18T17:38:39.000Z
2022-03-25T22:22:11.000Z
import _ from "lodash"; import vscode from "vscode"; import { exec_notify, flowistry_cmd, get_flowistry_opts } from "../../../setup"; import { SliceOutput } from "../../../types"; import { to_vsc_range } from "../../../vsc_utils"; import { TestSlice } from "../mock_data/slices"; import { MOCK_PROJECT_DIRECTORY } from "../../constants"; type TestSliceResult = { test: string; expected_selections: vscode.Selection[]; actual_selections: vscode.Selection[]; }; /** * Returns the output of `cargo flowistry <direction>_slice <file> <slice information>`. * @param param0 Title passed to a VSCode notification and arguments passed to `cargo flowistry`. * @returns Output from `cargo flowistry`. */ export const get_slice = async ({ test, file, direction, slice_on }: TestSlice): Promise<string> => { const doc = vscode.window.activeTextEditor?.document!; const start = doc.offsetAt(new vscode.Position(...slice_on[0])); const end = doc.offsetAt(new vscode.Position(...slice_on[1])); const slice_command = `${flowistry_cmd} ${direction}_slice ${file} ${start} ${end}`; const command_opts = await get_flowistry_opts(MOCK_PROJECT_DIRECTORY); const output = await exec_notify(slice_command, test, command_opts); return output; }; /** * Highlights and performs a slice on a range in a VSCode text document. * @param direction Slice direction. * @param position Zero-based positions for the beginning and end of the range to slice on. * @param filename Filename of the VSCode text document containing the range to slice on. */ const slice = async ( direction: TestSlice['direction'], position: TestSlice['slice_on'], filename: string, ): Promise<void> => { const file = vscode.Uri.parse(filename); await vscode.window.showTextDocument(file); const start_position = new vscode.Position(...position[0]); const end_position = new vscode.Position(...position[1]); vscode.window.activeTextEditor!.selection = new vscode.Selection( start_position, end_position ); await vscode.commands.executeCommand(`flowistry.${direction}_select`); }; /** * Merge overlapping VSCode Ranges. * @param ranges Array of ranges to merge. * @returns Array of merged ranges. */ const merge_ranges = (ranges: vscode.Range[]): vscode.Range[] => { const merged_ranges = [ranges[0]]; ranges.slice(1).forEach((range) => { const last_range = _.last(merged_ranges)!; const intersection = last_range.intersection(range); // If the current and previous ranges have no overlap if (!intersection) { // Add the current range to `merged_ranges` merged_ranges.push(range); } else { // Set the previous range to the union of the current and previous ranges const union = last_range.union(range); merged_ranges[merged_ranges.length - 1] = union; } }); return merged_ranges; }; /** * Get the expected and actual selections of a slice on a value in a VSCode text document. * @param test_slice Title for the slice and arguments passed to the slice command. * @returns The slice's expected selections, actual selections, and `test_slice`. */ export const get_slice_selections = async (test_slice: TestSlice): Promise<TestSliceResult> => { await slice(test_slice.direction, test_slice.slice_on, test_slice.file); const raw_slice_data = await get_slice(test_slice); const slice_data: SliceOutput = JSON.parse(raw_slice_data).fields[0]; const unique_ranges = _.uniqWith(slice_data.ranges, _.isEqual); const sorted_ranges = _.sortBy(unique_ranges, (range) => [range.start]); const vscode_ranges = sorted_ranges.map((range) => to_vsc_range(range, vscode.window.activeTextEditor?.document!)); const merged_ranges = merge_ranges(vscode_ranges); const expected_selections = merged_ranges.map((range) => new vscode.Selection(range.start, range.end)); const actual_selections = vscode.window.activeTextEditor?.selections!; return { ...test_slice, expected_selections, actual_selections, }; }; /** * Sequentially maps an array of values using a Promise-like `resolver` function. * @param items Array of items to pass to `resolver`. * @param resolver Function which resolves a new value from an element of `items`. * @returns A new array of `items` where each element is the result of `await resolver(<element>)`. */ export const resolve_sequentially = async <T, R>(items: T[], resolver: (arg0: T) => PromiseLike<R>): Promise<R[]> => { const results: R[] = []; for (const item of items) { const result = await resolver(item); results.push(result); } return results; };
37.857143
119
0.690776
e258ebff932f5f582b131328ec2c78af026fb9cb
2,086
py
Python
robo_trade/api/get_positions.py
gnelabs/EpithyRoboTrader
45698dc56d1253c823ea2c2b5484d85b1d949263
[ "Apache-2.0" ]
3
2020-06-01T21:10:37.000Z
2021-07-29T12:33:35.000Z
robo_trade/api/get_positions.py
gnelabs/EpithyRoboTrader
45698dc56d1253c823ea2c2b5484d85b1d949263
[ "Apache-2.0" ]
null
null
null
robo_trade/api/get_positions.py
gnelabs/EpithyRoboTrader
45698dc56d1253c823ea2c2b5484d85b1d949263
[ "Apache-2.0" ]
1
2020-07-03T06:52:03.000Z
2020-07-03T06:52:03.000Z
__author__ = "Nathan Ward" import json import logging import robin_stocks.helper as helper import robin_stocks.urls as urls import robin_stocks from views import register_view from api.utils import LambdaMessageEncoder from trade_lambda.get_credentials import robinhood_creds _LOGGER = logging.getLogger() _LOGGER.setLevel(logging.INFO) @register_view('/api/get_positions') def lambda_handler(event, context): """ Lambda function to return the current positions held in the Robinhood account. Using this to test functionality of this whole shebang before I go further. This is a stripped down version of the robin_stocks.authentication.login function. Lambda only allows writing to /tmp directory, so the concept of pickling a file into the home directory won't work. Using SSM securestring for non-ephemeral replacement because its free (to 40 TPS), encrypted, and SSM is backed by dynamodb so its fast. """ robinhood_credentials = robinhood_creds() #Trick robin_stocks into thinking login was successful. helper.set_login_state(True) #Set the JWT. helper.update_session('Authorization', '{0} {1}'.format(robinhood_credentials['token_type'], robinhood_credentials['access_token'])) #Skip verification. Can handle this here if needed. #result = robin_stocks.account.get_current_positions() result = robin_stocks.get_name_by_symbol('aapl') try: return { 'statusCode': 200, 'body': json.dumps( result, cls=LambdaMessageEncoder ), 'headers': {'Content-Type': 'application/json'} } except Exception as e: _LOGGER.error('Something went wrong querying Robinhood account. {0}'.format(e)) return { 'statusCode': 500, 'body': json.dumps( {'message': 'Something went wrong querying Robinhood account. {0}'.format(e)}, cls=LambdaMessageEncoder ), 'headers': {'Content-Type': 'application/json'} }
36.596491
136
0.678811
a3402147362405558d481af3ada435eb448a4bb1
1,098
c
C
c03/ex02/ft_strcat.c
irnabern/dealBEY
966d4e988a7e324e577fd0de60be00fde41cdda0
[ "Apache-2.0" ]
null
null
null
c03/ex02/ft_strcat.c
irnabern/dealBEY
966d4e988a7e324e577fd0de60be00fde41cdda0
[ "Apache-2.0" ]
null
null
null
c03/ex02/ft_strcat.c
irnabern/dealBEY
966d4e988a7e324e577fd0de60be00fde41cdda0
[ "Apache-2.0" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strcat.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bbatumik <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/17 18:21:15 by bbatumik #+# #+# */ /* Updated: 2019/09/17 18:27:20 by bbatumik ### ########.fr */ /* */ /* ************************************************************************** */ char *ft_strcat(char *dest, char *src) { int i; int j; i = 0; while (dest[i] != '\0') i++; j = 0; while (src[j] != '\0') { dest[i + j] = src[j]; j++; } dest[i + j] = '\0'; return (dest); }
36.6
80
0.167577
57f328c796ff07a4787fe68d3f128816a99da627
1,077
php
PHP
database/migrations/2020_10_14_095100_create_delivery_man_township_table.php
minpikemhmu/inventory
a086839c5a266175a2a09f0f906192505bced505
[ "MIT" ]
null
null
null
database/migrations/2020_10_14_095100_create_delivery_man_township_table.php
minpikemhmu/inventory
a086839c5a266175a2a09f0f906192505bced505
[ "MIT" ]
null
null
null
database/migrations/2020_10_14_095100_create_delivery_man_township_table.php
minpikemhmu/inventory
a086839c5a266175a2a09f0f906192505bced505
[ "MIT" ]
null
null
null
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateDeliverymanTownshipTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('delivery_man_township', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('delivery_men_id'); $table->unsignedBigInteger('township_id'); $table->softDeletes(); $table->timestamps(); $table->foreign('delivery_men_id') ->references('id')->on('delivery_men') ->onDelete('cascade'); $table->foreign('township_id') ->references('id')->on('townships') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('delivery_man_townships'); } }
23.933333
77
0.545032
43964a86226671ad25e74207e590cc5934e20da6
5,698
ts
TypeScript
packages/titumir/src/auth/guards/jwt-auth.guard.ts
KRTirtho/veschool
d57ebc831889b59d4a46de0b593410efd8bbb9f8
[ "MIT" ]
3
2021-05-07T13:27:04.000Z
2021-12-12T17:53:14.000Z
packages/titumir/src/auth/guards/jwt-auth.guard.ts
KRTirtho/veschool
d57ebc831889b59d4a46de0b593410efd8bbb9f8
[ "MIT" ]
null
null
null
packages/titumir/src/auth/guards/jwt-auth.guard.ts
KRTirtho/veschool
d57ebc831889b59d4a46de0b593410efd8bbb9f8
[ "MIT" ]
null
null
null
import { ExecutionContext, HttpException, Injectable, Logger } from "@nestjs/common"; import { Reflector } from "@nestjs/core"; import { AuthGuard } from "@nestjs/passport"; import { Request } from "express"; import User from "../../database/entity/users.entity"; import { USER_ROLE } from "@veschool/types"; import { EXTEND_USER_RELATION_KEY } from "../../decorator/extend-user-relation.decorator"; import { VERIFY_GRADE_KEY } from "../../decorator/verify-grade.decorator"; import { VERIFY_SCHOOL_KEY } from "../../decorator/verify-school.decorator"; import { VERIFY_SECTION_KEY } from "../../decorator/verify-section.decorator"; import { GradeService } from "../../grade/grade.service"; import { StudentSectionGradeService } from "../../student-section-grade/student-section-grade.service"; import { TeacherSectionGradeService } from "../../teacher-section-grade/teacher-section-grade.service"; import { UserService } from "../../user/user.service"; import { isAdministrative, isGradeAdministrative, } from "../../utils/helper-functions.util"; export const IS_PUBLIC_KEY = "isPublic"; type RequestWithParams = Request<{ school?: string; grade?: number; section?: number; }>; @Injectable() export default class JwtAuthGuard extends AuthGuard("jwt") { logger = new Logger(JwtAuthGuard.name); constructor( private readonly reflector: Reflector, private readonly userService: UserService, private readonly gradeService: GradeService, private readonly studentSGService: StudentSectionGradeService, private readonly teacherSGService: TeacherSectionGradeService, ) { super(); } async canActivate(context: ExecutionContext): Promise<boolean> { try { const request = context.switchToHttp().getRequest<RequestWithParams>(); const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [ context.getHandler(), context.getClass(), ]); const verifySchool = this.reflector.getAllAndOverride<boolean>( VERIFY_SCHOOL_KEY, [context.getHandler(), context.getClass()], ); // this used to increase the relationship of user incase extra // relational data is needed const extendUserRelations = this.reflector.getAllAndOverride<string[]>( EXTEND_USER_RELATION_KEY, [context.getHandler(), context.getClass()], ); const verifyGrade = this.reflector.getAllAndOverride<boolean>( VERIFY_GRADE_KEY, [context.getHandler(), context.getClass()], ); const verifySection = this.reflector.getAllAndOverride<boolean>( VERIFY_SECTION_KEY, [context.getHandler(), context.getClass()], ); if (isPublic) { return true; } const superActivate: boolean = (await super.canActivate(context)) as boolean; const roles = this.reflector.get<string[]>( "roles", context.getHandler(), ) as USER_ROLE[]; const user = request.user as User; if (extendUserRelations) { request.user = await this.userService.findOne( { _id: user._id }, { relations: ["school", ...extendUserRelations], }, ); } if (verifySchool && superActivate) { const isSameSchool = user?.school?.short_name === request.params.school; if (isSameSchool && verifyGrade) { return this.verifyGrade(request, user, roles); } return isSameSchool; } return superActivate; } catch (error) { this.logger.error(error); if (error instanceof HttpException) throw error; return false; } } async verifyGrade(request: RequestWithParams, user: User, roles: USER_ROLE[]) { const leaderField = user.role === USER_ROLE.gradeExaminer ? "examiner" : "moderator"; const grade = await this.gradeService.findOne( { standard: request.params.grade, }, { relations: [leaderField] }, ); if (isAdministrative(user.role)) { Object.assign(request.user, { grade }); return true; } else if ( (roles.includes(USER_ROLE.gradeExaminer) || roles.includes(USER_ROLE.gradeModerator)) && isGradeAdministrative(user.role) ) { Object.assign(request.user, { grade }); return grade[leaderField]?._id === user._id; } else { // for general student/teacher/class-teacher(s) // in here user.role can be anything because a grade-moderator // or grade-examiner might not belong to current grade but // might belong as a regular teacher. That's why except student // everyone here is a teacher & we've to verify that const serviceField = user.role === USER_ROLE.student ? "studentSGService" : "teacherSGService"; const usg = await this[serviceField].findOneUnsafe({ grade, user, }); Object.assign(request.user, { grade }); return !!usg; } } async verifySection(request: RequestWithParams, user: User, roles: USER_ROLE[]) { // verifying class teacher } }
39.296552
103
0.588101
a33ed1cb1d29281cf93f8933b1bad8d7e00c8f4e
523
h
C
cxJsonModelDetection/detection330/Xfscim330-2.h
267368312/cxJsonModel
52c7c40b0abc1d3788a470dd5473a41a88af3dad
[ "Unlicense" ]
5
2018-06-15T00:06:46.000Z
2021-08-06T23:42:19.000Z
cxJsonModelDetection/detection330/Xfscim330-2.h
267368312/cxJsonModel
52c7c40b0abc1d3788a470dd5473a41a88af3dad
[ "Unlicense" ]
null
null
null
cxJsonModelDetection/detection330/Xfscim330-2.h
267368312/cxJsonModel
52c7c40b0abc1d3788a470dd5473a41a88af3dad
[ "Unlicense" ]
3
2020-02-03T04:24:43.000Z
2021-12-12T18:01:20.000Z
WFSCIMPOWERSAVECONTROL, WFSCIMREPTARGET, WFSCIMREP, WFSCIMREPTARGETRES, WFSCIMREPRES, WFSCIMAMOUNTLIMIT, WFSCIMCASHINLIMIT, WFSCIMCOUNT, WFSCIMUNITLOCKCONTROL, WFSCIMDEVICELOCKCONTROL, WFSCIMSETMODE, WFSCIMPRESENT, WFSCIMDEPSOURCE, WFSCIMDEP, WFSCIMDEPSOURCERES, WFSCIMDEPRES, WFSCIMBLACKLISTELEMENT, WFSCIMBLACKLIST, WFSCIMSYNCHRONIZECOMMAND, WFSCIMCUERROR, WFSCIMCOUNTSCHANGED, WFSCIMPOSITIONINFO, WFSCIMDEVICEPOSITION, WFSCIMPOWERSAVECHANGE, WFSCIMINCOMPLETEREPLENISH, WFSCIMINCOMPLETEDEPLETE, WFSCIMSHUTTERSTATUSCHANGED
19.37037
26
0.900574
0ae5678b827520e8f9b34c0ad8c8cbf1770e8970
30,532
cs
C#
VkNet/Categories/AudioCategory.cs
slay9090/vk
1fea63e75989f78434c083a2051bae62f4fb3811
[ "MIT" ]
null
null
null
VkNet/Categories/AudioCategory.cs
slay9090/vk
1fea63e75989f78434c083a2051bae62f4fb3811
[ "MIT" ]
null
null
null
VkNet/Categories/AudioCategory.cs
slay9090/vk
1fea63e75989f78434c083a2051bae62f4fb3811
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Newtonsoft.Json.Linq; using VkNet.Enums; using VkNet.Model; using VkNet.Model.Attachments; using VkNet.Model.RequestParams; using VkNet.Utils; namespace VkNet.Categories { /// <summary> /// Методы для работы с аудиозаписями. /// </summary> public class AudioCategory { private readonly VkApi _vk; /// <summary> /// Методы для работы с аудиозаписями. /// </summary> /// <param name="vk"> Api vk.com </param> public AudioCategory(VkApi vk) { _vk = vk; } /// <summary> /// Возвращает количество аудиозаписей пользователя или сообщества. /// </summary> /// <param name="ownerId"> /// Идентификатор владельца аудиозаписей (пользователь или сообщество). Обратите /// внимание, /// идентификатор сообщества в параметре owner_id необходимо указывать со знаком /// "-" — например, owner_id=-1 /// соответствует идентификатору сообщества ВКонтакте API (club1) целое число, /// обязательный параметр (Целое число, /// обязательный параметр). /// </param> /// <returns> /// После успешного выполнения возвращает число, равное количеству аудиозаписей на /// странице пользователя или /// сообщества. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.getCount /// </remarks> public long GetCount(long ownerId) { var parameters = new VkParameters { { "owner_id", ownerId } }; return _vk.Call(methodName: "audio.getCount", parameters: parameters); } /// <summary> /// Возвращает текст аудиозаписи. /// </summary> /// <param name="lyricsId"> /// Идентификатор текста аудиозаписи, информацию о котором необходимо вернуть. /// целое число, /// обязательный параметр (Целое число, обязательный параметр). /// </param> /// <returns> /// После успешного выполнения возвращает объект lyrics c полями lyrics_id — /// идентификатор текста и text — текст /// аудиозаписи. /// В качестве переводов строк в тексте используется /n. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.getLyrics /// </remarks> public Lyrics GetLyrics(long lyricsId) { var parameters = new VkParameters { { "lyrics_id", lyricsId } }; return _vk.Call(methodName: "audio.getLyrics", parameters: parameters); } /// <summary> /// Возвращает информацию об аудиозаписях. /// </summary> /// <param name="audios"> /// Идентификаторы аудиозаписей, информацию о которых необходимо вернуть, в виде /// {owner_id}_{audio_id}. список строк, разделенных через запятую, обязательный /// параметр (Список строк, разделенных /// через запятую, обязательный параметр). /// </param> /// <returns> /// После успешного выполнения возвращает массив объектов audio. Обратите внимание, /// что ссылки на аудиозаписи привязаны /// к ip адресу. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.getById /// </remarks> public ReadOnlyCollection<Audio> GetById(IEnumerable<string> audios) { if (!audios.Any()) { throw new ArgumentNullException(paramName: nameof(audios)); } var parameters = new VkParameters { { "audios", audios } }; VkResponseArray response = _vk.Call(methodName: "audio.getById", parameters: parameters); return response.ToReadOnlyCollectionOf<Audio>(selector: x => x); } /// <summary> /// Возвращает информацию об аудиозаписях. /// </summary> /// <param name="audios"> /// Идентификаторы аудиозаписей, информацию о которых необходимо вернуть, в виде /// {owner_id}_{audio_id}. список строк, разделенных через запятую, обязательный /// параметр (Список строк, разделенных /// через запятую, обязательный параметр). /// </param> /// <returns> /// После успешного выполнения возвращает массив объектов audio. Обратите внимание, /// что ссылки на аудиозаписи привязаны /// к ip адресу. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.getById /// </remarks> public ReadOnlyCollection<Audio> GetById(params string[] audios) { return GetById(audios: (IEnumerable<string>) audios); } /// <summary> /// Возвращает список аудиозаписей пользователя или сообщества. /// </summary> /// <param name="user"> Данные о пользователе. </param> /// <param name="params"> Параметры запроса. </param> /// <returns> /// После успешного выполнения возвращает список объектов audio. /// Если был задан параметр need_user=1, дополнительно возвращается объект user, /// содержащий поля: /// id — идентификатор пользователя; /// photo — url фотографии профиля; /// name — имя и фамилия пользователя; /// name_gen — имя пользователя в родительном падеже. /// Обратите внимание, что ссылки на mp3 привязаны к ip-адресу. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.get /// </remarks> public ReadOnlyCollection<Audio> Get(out User user, AudioGetParams @params) { VkResponseArray response = _vk.Call(methodName: "audio.get", parameters: @params); IEnumerable<VkResponse> items = response.ToList(); user = null; if (@params.NeedUser.HasValue && @params.NeedUser.Value && items.Any()) { user = items.First(); items = items.Skip(count: 1); } return items.ToReadOnlyCollectionOf<Audio>(selector: r => r); } /// <summary> /// Возвращает адрес сервера для загрузки аудиозаписей. /// </summary> /// <returns> /// После успешного выполнения возвращает объект с единственным полем upload_url. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.getUploadServer /// </remarks> public Uri GetUploadServer() { var response = _vk.Call(methodName: "audio.getUploadServer", parameters: VkParameters.Empty); return response[key: "upload_url"]; } /// <summary> /// Возвращает список аудиозаписей в соответствии с заданным критерием поиска. /// </summary> /// <param name="params"> Критерии поиска </param> /// <returns> /// Список объектов класса Audio. /// </returns> /// <exception cref="System.ArgumentNullException"> Query is null or empty.;query </exception> /// <remarks> /// Для вызова этого метода Ваше приложение должно иметь права с битовой маской, /// содержащей Settings.Audio /// Страница документации ВКонтакте http://vk.com/dev/audio.search /// </remarks> public VkCollection<Audio> Search(AudioSearchParams @params) { if (string.IsNullOrWhiteSpace(value: @params.Query)) { throw new ArgumentNullException(paramName: nameof(@params.Query), message: "Query is null or empty."); } return _vk.Call(methodName: "audio.search", parameters: @params).ToVkCollectionOf<Audio>(selector: r => r); } /// <summary> /// Копирует аудиозапись на страницу пользователя или группы. /// </summary> /// <param name="audioId"> /// Идентификатор аудиозаписи. положительное число, обязательный параметр /// (Положительное число, /// обязательный параметр). /// </param> /// <param name="ownerId"> /// Идентификатор владельца аудиозаписи (пользователь или сообщество). целое число, /// обязательный /// параметр (Целое число, обязательный параметр). /// </param> /// <param name="groupId"> /// Идентификатор сообщества (если аудиозапись необходимо скопировать в список /// сообщества). целое /// число (Целое число). /// </param> /// <param name="albumId"> /// Идентификатор альбома, в который нужно переместить аудиозапись. положительное /// число /// (Положительное число). /// </param> /// <param name="captchaSid"> /// Id капчи (только если для вызова метода необходимо /// ввести капчу) /// </param> /// <param name="captchaKey"> /// Текст капчи (только если для вызова метода необходимо /// ввести капчу) /// </param> /// <returns> /// После успешного выполнения возвращает идентификатор созданной аудиозаписи. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.add /// </remarks> public long Add(long audioId , long ownerId , long? groupId = null , long? albumId = null , long? captchaSid = null , string captchaKey = null) { var parameters = new VkParameters { { "audio_id", audioId } , { "owner_id", ownerId } , { "group_id", groupId } , { "album_id", albumId } , { "captcha_sid", captchaSid } , { "captcha_key", captchaKey } }; return _vk.Call(methodName: "audio.add", parameters: parameters); } /// <summary> /// Удаляет аудиозапись со страницы пользователя или сообщества. /// </summary> /// <param name="audioId"> /// Идентификатор аудиозаписи. положительное число, обязательный параметр /// (Положительное число, /// обязательный параметр). /// </param> /// <param name="ownerId"> /// Идентификатор владельца аудиозаписи (пользователь или сообщество). целое число, /// обязательный /// параметр (Целое число, обязательный параметр). /// </param> /// <returns> /// После успешного выполнения возвращает <c> true </c>. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.delete /// </remarks> public bool Delete(long audioId, long ownerId) { var parameters = new VkParameters { { "audio_id", audioId } , { "owner_id", ownerId } }; return _vk.Call(methodName: "audio.delete", parameters: parameters); } /// <summary> /// Редактирует данные аудиозаписи на странице пользователя или сообщества. /// </summary> /// <param name="params"> Параметры запроса. </param> /// <returns> /// После успешного выполнения возвращает id текста, введенного пользователем /// (lyrics_id), если текст не был введен, /// вернет 0. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.edit /// </remarks> public long Edit(AudioEditParams @params) { if (@params.Artist == null) { throw new ArgumentNullException(paramName: nameof(@params.Artist), message: "Artist parameter can not be null."); } if (@params.Title == null) { throw new ArgumentNullException(paramName: nameof(@params.Title), message: "Title parameter can not be null."); } if (@params.Text == null) { throw new ArgumentNullException(paramName: nameof(@params.Text), message: "Text parameter can not be null."); } return _vk.Call(methodName: "audio.edit", parameters: @params); } /// <summary> /// Восстанавливает аудиозапись после удаления. /// </summary> /// <param name="audioId"> /// Идентификатор аудиозаписи. положительное число, обязательный параметр /// (Положительное число, /// обязательный параметр). /// </param> /// <param name="ownerId"> /// Идентификатор владельца аудиозаписи (пользователь или сообщество). По умолчанию /// — идентификатор /// текущего пользователя. целое число, по умолчанию идентификатор текущего /// пользователя (Целое число, по умолчанию /// идентификатор текущего пользователя). /// </param> /// <returns> /// В случае успешного восстановления аудиозаписи возвращает объект аудиозаписи. /// Если время хранения удаленной аудиозаписи истекло (обычно это 20 минут), сервер /// вернет ошибку 202 (Cache expired). /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.restore /// </remarks> public Audio Restore(long audioId, long? ownerId = null) { var parameters = new VkParameters { { "audio_id", audioId } , { "owner_id", ownerId } }; return _vk.Call(methodName: "audio.restore", parameters: parameters); } /// <summary> /// Изменяет порядок аудиозаписи, перенося ее между аудиозаписями, идентификаторы /// которых переданы параметрами after и /// before. /// </summary> /// <param name="audioId"> /// Идентификатор аудиозаписи, которую нужно переместить. положительное число, /// обязательный параметр /// (Положительное число, обязательный параметр). /// </param> /// <param name="ownerId"> /// Идентификатор владельца аудиозаписи (пользователь или сообщество). По умолчанию /// — идентификатор /// текущего пользователя. целое число, по умолчанию идентификатор текущего /// пользователя (Целое число, по умолчанию /// идентификатор текущего пользователя). /// </param> /// <param name="before"> /// Идентификатор аудиозаписи, перед которой нужно поместить композицию aid. целое /// число (Целое /// число). /// </param> /// <param name="after"> /// Идентификатор аудиозаписи, после которой нужно поместить композицию aid. целое /// число (Целое /// число). /// </param> /// <returns> /// После успешного выполнения возвращает <c> true </c>. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.reorder /// </remarks> public bool Reorder(long audioId, long? ownerId, long? before, long? after) { var parameters = new VkParameters { { "audio_id", audioId } , { "owner_id", ownerId } , { "before", before } , { "after", after } }; return _vk.Call(methodName: "audio.reorder", parameters: parameters); } /// <summary> /// Создает пустой альбом аудиозаписей. /// </summary> /// <param name="groupId"> /// Идентификатор сообщества (если альбом нужно создать в сообществе). /// положительное число /// (Положительное число). /// </param> /// <param name="title"> /// Название альбома. строка, обязательный параметр (Строка, /// обязательный параметр). /// </param> /// <returns> /// После успешного выполнения возвращает идентификатор (album_id) созданного /// альбома. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.addAlbum /// </remarks> [Obsolete(message: "5.65 Методы audio.getAlbums, audio.addAlbum, audio.editAlbum, audio.addAlbum, audio.deleteAlbum и audio.moveToAlbum устарели. ")] public long AddAlbum(string title, long? groupId = null) { VkErrors.ThrowIfNullOrEmpty(expr: () => title); VkErrors.ThrowIfNumberIsNegative(expr: () => groupId); var parameters = new VkParameters { { "group_id", groupId } , { "title", title } }; var response = _vk.Call(methodName: "audio.addAlbum", parameters: parameters); return response[key: "album_id"]; } /// <summary> /// Редактирует название альбома аудиозаписей. /// </summary> /// <param name="groupId"> /// Идентификатор сообщества, которому принадлежит альбом. положительное число /// (Положительное число). /// </param> /// <param name="albumId"> /// Идентификатор альбома. положительное число, обязательный параметр /// (Положительное число, /// обязательный параметр). /// </param> /// <param name="title"> /// Новое название для альбома. строка, обязательный параметр (Строка, обязательный /// параметр). /// </param> /// <returns> /// После успешного выполнения возвращает <c> true </c>. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.editAlbum /// </remarks> [Obsolete(message: "5.65 Методы audio.getAlbums, audio.addAlbum, audio.editAlbum, audio.addAlbum, audio.deleteAlbum и audio.moveToAlbum устарели. ")] public bool EditAlbum(string title, long albumId, long? groupId = null) { VkErrors.ThrowIfNullOrEmpty(expr: () => title); var parameters = new VkParameters { { "title", title } , { "group_id", groupId } , { "album_id", albumId } }; return _vk.Call(methodName: "audio.editAlbum", parameters: parameters); } /// <summary> /// Удаляет альбом аудиозаписей. /// </summary> /// <param name="groupId"> /// Идентификатор сообщества, которому принадлежит альбом. положительное число /// (Положительное число). /// </param> /// <param name="albumId"> /// Идентификатор альбома. положительное число, обязательный параметр /// (Положительное число, /// обязательный параметр). /// </param> /// <returns> /// После успешного выполнения возвращает <c> true </c>. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.deleteAlbum /// </remarks> [Obsolete(message: "5.65 Методы audio.getAlbums, audio.addAlbum, audio.editAlbum, audio.addAlbum, audio.deleteAlbum и audio.moveToAlbum устарели. ")] public bool DeleteAlbum(long albumId, long? groupId = null) { var parameters = new VkParameters { { "group_id", groupId } , { "album_id", albumId } }; return _vk.Call(methodName: "audio.deleteAlbum", parameters: parameters); } /// <summary> /// Возвращает список аудиозаписей из раздела "Популярное". /// </summary> /// <param name="onlyEng"> /// 1 – возвращать только зарубежные аудиозаписи. 0 – возвращать все аудиозаписи. /// (по умолчанию) /// флаг, может принимать значения 1 или 0 (Флаг, может принимать значения 1 или /// 0). /// </param> /// <param name="genre"> /// Идентификатор жанра из списка жанров. положительное число /// (Положительное число). /// </param> /// <param name="offset"> /// Смещение, необходимое для выборки определенного подмножества аудиозаписей. /// положительное число /// (Положительное число). /// </param> /// <param name="count"> /// Количество возвращаемых аудиозаписей. положительное число, максимальное /// значение 1000, по умолчанию /// 100 (Положительное число, максимальное значение 1000, по умолчанию 100). /// </param> /// <returns> /// После успешного выполнения возвращает список объектов audio. Обратите внимание, /// что ссылки на аудиозаписи привязаны /// к ip адресу. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.getPopular /// </remarks> public ReadOnlyCollection<Audio> GetPopular(bool onlyEng = false, AudioGenre? genre = null, uint? count = null, uint? offset = null) { var parameters = new VkParameters { { "only_eng", onlyEng } , { "genre_id", genre } , { "offset", offset } }; if (count <= 1000) { parameters.Add(name: "count", nullableValue: count); } VkResponseArray response = _vk.Call(methodName: "audio.getPopular", parameters: parameters); return response.ToReadOnlyCollectionOf<Audio>(selector: x => x); } /// <summary> /// Возвращает список альбомов аудиозаписей пользователя или группы. /// </summary> /// <param name="ownerId"> /// Идентификатор пользователя или сообщества, у которого необходимо получить /// список альбомов с /// аудио. целое число, по умолчанию идентификатор текущего пользователя (Целое /// число, по умолчанию идентификатор /// текущего пользователя). /// </param> /// <param name="offset"> /// Смещение, необходимое для выборки определенного подмножества альбомов. /// положительное число /// (Положительное число). /// </param> /// <param name="count"> /// Количество альбомов, которое необходимо вернуть. положительное число, по /// умолчанию 50, максимальное /// значение 100 (Положительное число, по умолчанию 50, максимальное значение 100). /// </param> /// <returns> /// После успешного выполнения возвращает общее количество альбомов с аудиозаписями /// и массив объектов album, каждый из /// которых содержит следующие поля: /// id — идентификатор альбома; /// owner_id — идентификатор владельца альбома; /// title — название альбома. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.getAlbums /// </remarks> [Obsolete(message: "5.65 Методы audio.getAlbums, audio.addAlbum, audio.editAlbum, audio.addAlbum, audio.deleteAlbum и audio.moveToAlbum устарели. ")] public VkCollection<AudioAlbum> GetAlbums(long ownerId, uint? count = null, uint? offset = null) { var parameters = new VkParameters { { "owner_id", ownerId } , { "offset", offset } , { "count", count } }; return _vk.Call(methodName: "audio.getAlbums", parameters: parameters).ToVkCollectionOf<AudioAlbum>(selector: x => x); } /// <summary> /// Перемещает аудиозаписи в альбом. /// </summary> /// <param name="groupId"> /// Идентификатор сообщества, в котором размещены аудиозаписи. Если параметр не /// указан, работа /// ведется с аудиозаписями текущего пользователя. положительное число /// (Положительное число). /// </param> /// <param name="albumId"> /// Идентификатор альбома, в который нужно переместить аудиозаписи. положительное /// число /// (Положительное число). /// </param> /// <param name="audioIds"> /// Идентификаторы аудиозаписей, которые требуется переместить. список /// положительных чисел, /// разделенных запятыми, обязательный параметр (Список положительных чисел, /// разделенных запятыми, обязательный /// параметр). /// </param> /// <returns> /// После успешного выполнения возвращает <c> true </c>. /// Обратите внимание, в одном альбоме не может быть более 1000 аудиозаписей. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.moveToAlbum /// </remarks> [Obsolete(message: "5.65 Методы audio.getAlbums, audio.addAlbum, audio.editAlbum, audio.addAlbum, audio.deleteAlbum и audio.moveToAlbum устарели. ")] public bool MoveToAlbum(long albumId, IEnumerable<long> audioIds, long? groupId = null) { var parameters = new VkParameters { { "album_id", albumId } , { "group_id", groupId } , { "audio_ids", audioIds } }; return _vk.Call(methodName: "audio.moveToAlbum", parameters: parameters); } /// <summary> /// Возвращает список рекомендуемых аудиозаписей на основе списка воспроизведения /// заданного пользователя или на основе /// одной выбранной аудиозаписи. /// </summary> /// <param name="targetAudio"> /// Идентификатор аудиозаписи, на основе которой будет строиться список /// рекомендаций. /// Используется вместо параметра uid. Идентификатор представляет из себя /// разделённые знаком подчеркивания id /// пользователя, которому принадлежит аудиозапись, и id самой аудиозаписи. Если /// аудиозапись принадлежит сообществу, то /// в качестве первого параметра используется -id сообщества. строка (Строка). /// </param> /// <param name="userId"> /// Идентификатор пользователя для получения списка рекомендаций на основе его /// набора аудиозаписей (по /// умолчанию — идентификатор текущего пользователя). положительное число /// (Положительное число). /// </param> /// <param name="offset"> /// Смещение относительно первой найденной аудиозаписи для выборки определенного /// подмножества. /// положительное число (Положительное число). /// </param> /// <param name="count"> /// Количество возвращаемых аудиозаписей. положительное число, максимальное /// значение 1000, по умолчанию /// 100 (Положительное число, максимальное значение 1000, по умолчанию 100). /// </param> /// <param name="shuffle"> /// 1 — включен случайный порядок. флаг, может принимать значения 1 или 0 (Флаг, /// может принимать /// значения 1 или 0). /// </param> /// <returns> /// После успешного выполнения возвращает список объектов audio. Обратите внимание, /// что ссылки на аудиозаписи привязаны /// к ip адресу. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.getRecommendations /// </remarks> public ReadOnlyCollection<Audio> GetRecommendations(long? userId = null , uint? count = null , uint? offset = null , bool shuffle = true , string targetAudio = "") { var parameters = new VkParameters { { "target_audio", targetAudio } , { "user_id", userId } , { "offset", offset } , { "count", count } , { "shuffle", shuffle } }; VkResponseArray response = _vk.Call(methodName: "audio.getRecommendations", parameters: parameters); return response.ToReadOnlyCollectionOf<Audio>(selector: x => x); } /// <summary> /// Транслирует аудиозапись в статус пользователю или сообществу. /// </summary> /// <param name="audio"> /// Идентификатор аудиозаписи, которая будет отображаться в статусе, в формате /// owner_id_audio_id. /// Например, 1_190442705. Если параметр не указан, аудиостатус указанных сообществ /// и пользователя будет удален. строка /// (Строка). /// </param> /// <param name="targetIds"> /// Перечисленные через запятую идентификаторы сообществ и пользователя, которым /// будет /// транслироваться аудиозапись. Идентификаторы сообществ должны быть заданы в /// формате "-gid", где gid - идентификатор /// сообщества. Например, 1,-34384434. По умолчанию аудиозапись транслируется /// текущему пользователю. список целых /// чисел, разделенных запятыми, количество элементов должно составлять не более 20 /// (Список целых чисел, разделенных /// запятыми, количество элементов должно составлять не более 20). /// </param> /// <returns> /// В случае успешного выполнения возвращает массив идентификаторов сообществ и /// пользователя, которым был установлен /// или удален аудиостатус. /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.setBroadcast /// </remarks> public ReadOnlyCollection<long> SetBroadcast(string audio, IEnumerable<long> targetIds) { VkErrors.ThrowIfNullOrEmpty(expr: () => audio); var parameters = new VkParameters { { "audio", audio } , { "target_ids", targetIds } }; VkResponseArray response = _vk.Call(methodName: "audio.setBroadcast", parameters: parameters); return response.ToReadOnlyCollectionOf<long>(selector: x => x); } /// <summary> /// Сохраняет аудиозаписи после успешной загрузки. /// </summary> /// <param name="response"> /// Параметр, возвращаемый в результате загрузки аудиофайла /// на сервер. /// </param> /// <param name="artist"> Автор композиции. По умолчанию берется из ID3 тегов. </param> /// <param name="title"> Название композиции. По умолчанию берется из ID3 тегов. </param> /// <returns> Возвращает массив из объектов с загруженными аудиозаписями. </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.save /// </remarks> public Audio Save(string response, string artist = null, string title = null) { VkErrors.ThrowIfNullOrEmpty(expr: () => response); var responseJson = JObject.Parse(json: response); var server = responseJson[propertyName: "server"].ToString(); var hash = responseJson[propertyName: "hash"].ToString(); var audio = responseJson[propertyName: "audio"].ToString(); var parameters = new VkParameters { { "server", server } , { "audio", Uri.EscapeDataString(stringToEscape: audio) } , { "hash", hash } , { "artist", artist } , { "title", title } }; return _vk.Call(methodName: "audio.save", parameters: parameters); } /// <summary> /// Возвращает список друзей, которые транслируют музыку в статус. /// </summary> /// <param name="active"> /// <c> true </c> — будут возвращены только друзья и сообщества, которые /// транслируют музыку в данный /// момент. По умолчанию возвращаются все. /// </param> /// <returns> /// После успешного выполнения возвращает список объектов друзей с дополнительным /// полем status_audio — объект /// аудиозаписи, /// установленной в статус (если аудиозапись транслируется в текущей момент). /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.getBroadcastList /// </remarks> public ReadOnlyCollection<User> GetBroadcastListFriends(bool active = false) { var parameters = new VkParameters { { "filter", "friends" } , { "active", active } }; VkResponseArray response = _vk.Call(methodName: "audio.getBroadcastList", parameters: parameters); return response.ToReadOnlyCollectionOf<User>(selector: x => x); } /// <summary> /// Возвращает список друзей и сообществ пользователя, которые транслируют музыку в /// статус. /// </summary> /// <param name="filter"> /// Определяет, какие типы объектов необходимо получить. Возможны следующие /// значения параметра: /// friends — только друзья; /// groups — только сообщества; /// all — друзья и сообщества. строка, по умолчанию all (Строка, по умолчанию all). /// </param> /// <param name="active"> /// 1 — будут возвращены только друзья и сообщества, которые транслируют музыку в /// данный момент. По /// умолчанию возвращаются все. флаг, может принимать значения 1 или 0 (Флаг, может /// принимать значения 1 или 0). /// </param> /// <returns> /// После успешного выполнения возвращает список объектов друзей и сообществ с /// дополнительным полем status_audio — /// объект аудиозаписи, установленной в статус (если аудиозапись транслируется в /// текущей момент). /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.getBroadcastList /// </remarks> public UserOrGroup GetBroadcastList(string filter = null, bool? active = null) { var parameters = new VkParameters { { "filter", filter } , { "active", active } }; return _vk.Call(methodName: "audio.getBroadcastList", parameters: parameters); } /// <summary> /// Возвращает список сообществ пользователя, которые транслируют музыку в статус. /// </summary> /// <param name="active"> /// <c> true </c> — будут возвращены только друзья и сообщества, которые /// транслируют музыку в данный /// момент. По умолчанию возвращаются все. /// </param> /// <returns> /// После успешного выполнения возвращает список объектов сообществ с /// дополнительным полем status_audio — объект /// аудиозаписи, /// установленной в статус (если аудиозапись транслируется в текущей момент). /// </returns> /// <remarks> /// Страница документации ВКонтакте http://vk.com/dev/audio.getBroadcastList /// </remarks> public ReadOnlyCollection<Group> GetBroadcastListGroup(bool active = false) { var parameters = new VkParameters { { "filter", "groups" } , { "active", active } }; VkResponseArray response = _vk.Call(methodName: "audio.getBroadcastList", parameters: parameters); return response.ToReadOnlyCollectionOf<Group>(selector: x => x); } } }
34.2287
134
0.675521
a00b5e1c4223abb528f17d20e56af1fe5f9b0a95
3,461
ts
TypeScript
src/lib/elements/GroupName.ts
stringsync/musicxml
e5b365d69fdd283d019f64227d50156e2a2f4f79
[ "MIT" ]
2
2022-03-02T16:31:12.000Z
2022-03-02T17:20:07.000Z
src/lib/elements/GroupName.ts
stringsync/musicxml
e5b365d69fdd283d019f64227d50156e2a2f4f79
[ "MIT" ]
1
2022-03-02T20:29:44.000Z
2022-03-05T11:53:29.000Z
src/lib/elements/GroupName.ts
stringsync/musicxml
e5b365d69fdd283d019f64227d50156e2a2f4f79
[ "MIT" ]
null
null
null
import * as dataTypes from '../dataTypes'; import { schema, t } from '../schema'; /** * The `<group-name>` element * * Parent element: `<part-group>` * * The `<group-name>` element describes the name of a <part-group> element. The formatting attributes are deprecated as * of Version 2.0 in favor of the new `<group-name-display>` element. * * {@link https://www.w3.org/2021/06/musicxml40/musicxml-reference/elements/group-name/} */ export const GroupName = schema( 'group-name', { /** * Indicates the color of an element. */ color: t.optional(dataTypes.color()), /** * Changes the computation of the default horizontal position. The origin is changed relative to the start of the * entire current measure, at either the left barline or the start of the system. Positive x is right and negative * x is left. * * This attribute provides higher-resolution positioning data than the `<offset>` element. Applications reading a * MusicXML file that can understand both features should generally rely on this attribute for its greater * accuracy. */ ['default-x']: t.label({ label: 'default-x', value: t.optional(dataTypes.tenths()) }), /** * Changes the computation of the default vertical position. The origin is changed relative to the top line of the * staff. Positive y is up and negative y is down. * * This attribute provides higher-resolution positioning data than the placement attribute. Applications reading a * MusicXML file that can understand both attributes should generally rely on this attribute for its greater * accuracy. */ ['default-y']: t.label({ label: 'default-y', value: t.optional(dataTypes.tenths()) }), /** * A comma-separated list of font names. */ ['font-family']: t.optional(dataTypes.fontFamily()), /** * One of the CSS sizes or a numeric point size. */ ['font-size']: t.optional(dataTypes.fontSize()), /** * Normal or italic style. */ ['font-style']: t.optional(dataTypes.fontStyle()), /** * Normal or bold weight. */ ['font-weight']: t.optional(dataTypes.fontWeight()), /** * Indicates left, center, or right justification. The default value varies for different elements. For elements * where the justify attribute is present but the halign attribute is not, the justify attribute indicates * horizontal alignment as well as justification. */ justify: t.optional(dataTypes.leftCenterRight()), /** * Changes the horizontal position relative to the default position, either as computed by the individual program, * or as overridden by the default-x attribute. Positive x is right and negative x is left. It should be * interpreted in the context of the `<offset>` element or directive attribute if those are present. */ ['relative-x']: t.label({ label: 'relative-x', value: t.optional(dataTypes.tenths()) }), /** * Changes the vertical position relative to the default position, either as computed by the individual program, * or as overridden by the default-y attribute. Positive y is up and negative y is down. It should be interpreted * in the context of the placement attribute if that is present. */ ['relative-y']: t.label({ label: 'relative-y', value: t.optional(dataTypes.tenths()) }), }, [t.required(dataTypes.string())] as const );
40.244186
119
0.676105
b5d08c1dd7609457fb66c6c38910a31aa653feb5
236
rb
Ruby
spec/factories/csv_uploads.rb
Vizzuality/emissions-scenario-portal
551c52807a5569c0c70a5be41d51043183fda793
[ "MIT" ]
2
2018-10-04T20:58:33.000Z
2019-07-07T16:34:07.000Z
spec/factories/csv_uploads.rb
Vizzuality/emissions-scenario-portal
551c52807a5569c0c70a5be41d51043183fda793
[ "MIT" ]
61
2017-05-12T06:25:58.000Z
2022-03-30T22:14:01.000Z
spec/factories/csv_uploads.rb
Vizzuality/emissions-scenario-portal
551c52807a5569c0c70a5be41d51043183fda793
[ "MIT" ]
1
2018-12-05T16:17:30.000Z
2018-12-05T16:17:30.000Z
FactoryBot.define do factory :csv_upload do job_id 1 user nil model nil service_type 'UploadIndicators' finished_at '2017-07-28 16:24:19' success false message 'MyText' errors_and_warnings {} end end
18.153846
37
0.686441
0a40dba725cfe4565dc27453643693a243fd220a
8,259
rs
Rust
libaoc/geom/src/neighbors.rs
BartMassey/advent-of-code-2020
47074dcd86ef8ecb7ecab605304eb6fe55a11fde
[ "MIT" ]
1
2020-12-07T01:36:58.000Z
2020-12-07T01:36:58.000Z
libaoc/geom/src/neighbors.rs
BartMassey/advent-of-code-2020
47074dcd86ef8ecb7ecab605304eb6fe55a11fde
[ "MIT" ]
null
null
null
libaoc/geom/src/neighbors.rs
BartMassey/advent-of-code-2020
47074dcd86ef8ecb7ecab605304eb6fe55a11fde
[ "MIT" ]
null
null
null
//! To use this, make a new `GridBox` to set clipping bounds, //! then call its methods to get iterators over coordinates. //! //! # Examples //! //! ``` //! # use aoc_geom::*; //! let clip_box = GridBox::new(4, 4); //! let mut neighbors = clip_box //! .neighbors((2, 0), 1) //! .collect::<Vec<_>>(); //! neighbors.sort(); //! let desired = vec![ //! (1, 0), (1, 1), //! (2, 1), //! (3, 0), (3, 1), //! ]; //! assert_eq!(neighbors, desired); //! ``` use std::marker::PhantomData; use aoc::convert::ConvertInto; use crate::dirns; /// Description of the grid, for possible clipping. #[derive(Copy, Clone)] pub enum GridBox { /// Grid is clipped on bottom and right. ClipBox((i64, i64)), /// Grid is unclipped. Unclipped, } use self::GridBox::*; impl GridBox { /// Create a clip box for neighbor calculations. pub fn new<T>(row_size: T, col_size: T) -> GridBox where T: ConvertInto<i64>, { ClipBox((row_size.convert_into(), col_size.convert_into())) } /// Create an "unbounded clip box" for neighbor /// calculations. **Negative locations will still be /// clipped.** pub fn new_grid() -> GridBox { Unclipped } /// Return an iterator that will produce the neighbors /// of the given location, clipped as needed. pub fn neighbors<T, U>( &self, location: (T, T), dist: U, ) -> Neighbors<T> where T: ConvertInto<i64>, i64: ConvertInto<T>, U: ConvertInto<i64>, { let r = location.0.convert_into(); let c = location.1.convert_into(); assert!(r >= 0 && c >= 0); if let ClipBox((row_size, col_size)) = *self { assert!(r < row_size && c < col_size); }; Neighbors::new(self, (r, c), dist.convert_into()) } /// Return an iterator that will a beam from the /// given location in the given direction, stopping /// at a grid boundary. pub fn beam<T, U>( &self, location: (T, T), step: (U, U), ) -> Beam<'_, T> where T: ConvertInto<i64>, i64: ConvertInto<T>, U: ConvertInto<i64>, { let r = location.0.convert_into(); let c = location.1.convert_into(); let dr = step.0.convert_into(); let dc = step.1.convert_into(); Beam::new(self, (r, c), (dr, dc)) } /// Return the source location adjusted by the given offset /// iff the dest location is in-bounds. This is useful when /// "manual" clipping is needed. pub fn clip<T, U>(&self, loc: (T, T), off: (U, U)) -> Option<(T, T)> where T: ConvertInto<i64>, i64: ConvertInto<T>, U: ConvertInto<i64>, { let r = loc.0.convert_into(); let c = loc.1.convert_into(); let dr = off.0.convert_into(); let dc = off.1.convert_into(); let nr = r + dr; let nc = c + dc; if nr < 0 || nc < 0 { return None; } if let ClipBox((row_size, col_size)) = *self { if nr >= row_size || nc >= col_size { return None; } }; Some((nr.convert_into(), nc.convert_into())) } } /// Iterator over the neighbors of a point in the four cardinal /// directions, clipped as appropriate. pub struct Neighbors<T> { // Origin. orig: (i64, i64), // Current location. loc: (i64, i64), // Upper-left corner. start: (i64, i64), // Lower-right corner. end: (i64, i64), // Phantom type for iterator. phantom: PhantomData<T>, } impl<T> Neighbors<T> { /// Return an iterator over the neighbors of /// the given grid box starting at the given location. pub fn new( bounds: &GridBox, orig: (i64, i64), dist: i64, ) -> Self { assert!(dist > 0); let (r, c) = orig; let start = (0.max(r - dist), 0.max(c - dist)); let end = if let ClipBox((rows, cols)) = *bounds { (rows.min(r + dist + 1), cols.min(c + dist + 1)) } else { (r + dist + 1, c + dist + 1) }; Neighbors { orig, loc: start, start, end, phantom: PhantomData, } } } impl<T> Iterator for Neighbors<T> where i64: ConvertInto<T>, { type Item = (T, T); /// Return the next neighbor of the source point. fn next(&mut self) -> Option<Self::Item> { if self.loc == self.orig { self.loc.1 += 1; return self.next(); } if self.loc.0 >= self.end.0 { return None; } if self.loc.1 >= self.end.1 { self.loc = (self.loc.0 + 1, self.start.1); return self.next(); } let result = (self.loc.0.convert_into(), self.loc.1.convert_into()); self.loc.1 += 1; Some(result) } } // Low case is taken care of by doctest above. #[test] fn test_neighbors_hi() { let clip_box = GridBox::new(4, 4); let mut neighbors = clip_box .neighbors((3, 3), 1) .collect::<Vec<_>>(); neighbors.sort(); let desired = vec![ (2, 2), (2, 3), (3, 2), ]; assert_eq!(neighbors, desired); } /// Beam iterator in a given direction until edge-of-grid is /// reached. pub struct Beam<'a, T> { // Clipper. clip: &'a GridBox, // Current location. loc: (i64, i64), // Step direction. step: (i64, i64), // Phantom type for iterator. phantom: PhantomData<T>, } impl<'a, T> Beam<'a, T> { /// Return an iterator stepping in the given direction /// until edge-of-grid is reached. pub fn new( clip: &'a GridBox, loc: (i64, i64), step: (i64, i64), ) -> Self { assert!(step != (0, 0)); Beam { clip, loc, step, phantom: PhantomData, } } } impl<'a, T> Iterator for Beam<'a, T> where i64: ConvertInto<T>, { type Item = (T, T); fn next(&mut self) -> Option<Self::Item> { self.clip .clip::<i64, i64>(self.loc, self.step) .map(|l| { self.loc = l; (l.0.convert_into(), l.1.convert_into()) }) } } #[test] fn test_beam_infinite() { let grid = GridBox::new_grid(); let beam: Vec<(u8, u8)> = grid .beam((5, 2), (1i8, 1)) .take(4) .collect(); let expected = vec![(6, 3), (7, 4), (8, 5), (9, 6)]; assert_eq!(beam, expected); let beam: Vec<(u8, u8)> = grid .beam((5, 2), (1i8, -1)) .collect(); let expected = vec![(6, 1), (7, 0)]; assert_eq!(beam, expected); } #[test] fn test_beam_finite() { let grid = GridBox::new(6, 6); let beam: Vec<(u8, u8)> = grid.beam((3, 2), (1i8, -1)).collect(); let expected = vec![(4, 1), (5, 0)]; assert_eq!(beam, expected); } pub fn neighbors4<T>() -> impl Iterator<Item = (T, T)> where i64: ConvertInto<T>, { dirns::DIRNS .iter() .map(|&(r, c)| (r.convert_into(), c.convert_into())) } pub fn neighbors8<T, U>(dist: T) -> impl Iterator<Item = (U, U)> where T: ConvertInto<i64>, i64: ConvertInto<U>, { let dist = dist.convert_into(); assert!(dist > 0); (-dist ..= dist) .flat_map(move |r| (-dist ..= dist).map(move |c| (r, c))) .filter(|&p| p != (0, 0)) .map(|(r, c)| (r.convert_into(), c.convert_into())) } #[test] fn test_neighbors8() { let mut v: Vec<(i8, i8)> = neighbors8(1u8).collect(); v.sort(); let desired = vec![ (-1, -1), (-1, 0), (-1, 1), ( 0, -1), ( 0, 1), ( 1, -1), ( 1, 0), ( 1, 1), ]; assert_eq!(v, desired); } /// The ["Manhattan Distance"][1] between two points. /// /// [1]: http://en.wikipedia.org/wiki/Taxicab_geometry pub fn manhattan_distance<T, U>((r1, c1): (T, T), (r2, c2): (T, T)) -> U where T: ConvertInto<i64>, i64: ConvertInto<U>, { let r1 = r1.convert_into(); let c1 = c1.convert_into(); let r2 = r2.convert_into(); let c2 = c2.convert_into(); let dr = (r1 - r2).abs(); let dc = (c1 - c2).abs(); (dr + dc).convert_into() }
25.256881
72
0.511321
979f6627ac97d33949f2aeacae0ca5f63b7d0b31
3,083
swift
Swift
Tests/TestWebServer.swift
Envative/JavaScriptCoreBrowserObjectModel
320e1d78ea97e43b34e72cb21ac5f9d1ca03a9a8
[ "MIT" ]
5
2017-12-13T09:33:19.000Z
2021-05-12T08:52:23.000Z
Tests/TestWebServer.swift
Envative/JavaScriptCoreBrowserObjectModel
320e1d78ea97e43b34e72cb21ac5f9d1ca03a9a8
[ "MIT" ]
null
null
null
Tests/TestWebServer.swift
Envative/JavaScriptCoreBrowserObjectModel
320e1d78ea97e43b34e72cb21ac5f9d1ca03a9a8
[ "MIT" ]
1
2019-10-01T18:55:16.000Z
2019-10-01T18:55:16.000Z
// // TestWebServer.swift // JavaScriptCoreBrowserObjectModel // // Created by Connor Grady on 12/12/17. // Copyright © 2017 Connor Grady. All rights reserved. // import XCTest import GCDWebServer typealias TestWebServerMatchBlock = (_ method: String, _ url: URL, _ headers: [AnyHashable: Any], _ path: String, _ query: [AnyHashable: Any]) -> Bool public class TestWebServerExpectation: XCTestExpectation { var matcher: TestWebServerMatchBlock! override init(description expectationDescription: String) { super.init(description: expectationDescription) } //convenience init(path: String) { // self.init(description: "") //} convenience init(method: String? = nil, path: String) { self.init(description: "Request: [\(method ?? "ALL")] \(path)") matcher = { (reqMethod, reqUrl, reqHeaders, reqPath, reqQuery) -> Bool in return (method == nil || method!.uppercased() == reqMethod.uppercased()) && (path.lowercased() == reqPath.lowercased()) } } } private class TestWebServerRequest: GCDWebServerRequest { var expectation: TestWebServerExpectation! //override init() {} //override init(method: String, url: URL, headers: [AnyHashable : Any], path: String, query: [AnyHashable : Any]?) {} init(method: String, url: URL, headers: [AnyHashable : Any], path: String, query: [AnyHashable : Any]?, expectation: TestWebServerExpectation) { super.init(method: method, url: url, headers: headers, path: path, query: query) self.expectation = expectation } } public class TestWebServer: GCDWebServer { private(set) var expectations = [TestWebServerExpectation]() override init() { super.init() addHandler(match: { (method, url, headers, path, query) -> GCDWebServerRequest?/*TestWebServerRequest?*/ in if let expectation = self.expectations.first(where: { $0.matcher(method, url, headers, path, query) }) { return TestWebServerRequest(method: method, url: url, headers: headers, path: path, query: query, expectation: expectation) } else { return nil //return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query) } }) { (request) in var response: GCDWebServerResponse? = nil if let request = request as? TestWebServerRequest { //request.expectation.fulfill() defer { request.expectation.fulfill() } response = GCDWebServerResponse(statusCode: 200) //response = GCDWebServerDataResponse(text: "") } return response } } @discardableResult func expect(method: String? = nil, path: String) -> TestWebServerExpectation { let expectation = TestWebServerExpectation(method: method, path: path) expectations.append(expectation) return expectation } func removeAllExpectations() { expectations.removeAll() } }
39.025316
150
0.638988
f450f23c079eaad263c82413a1f1c0f74ea0f89e
158
ts
TypeScript
docs/fonts/icons/PowerSolidBadged.d.ts
boazblake/presenter
90fa56602a982561fd1b097a7beacfc2c4c819b0
[ "CC0-1.0" ]
null
null
null
docs/fonts/icons/PowerSolidBadged.d.ts
boazblake/presenter
90fa56602a982561fd1b097a7beacfc2c4c819b0
[ "CC0-1.0" ]
null
null
null
docs/fonts/icons/PowerSolidBadged.d.ts
boazblake/presenter
90fa56602a982561fd1b097a7beacfc2c4c819b0
[ "CC0-1.0" ]
null
null
null
import m from 'mithril'; import { SVGAttributes } from '../svg'; declare const PowerSolidBadged: m.Component<SVGAttributes>; export default PowerSolidBadged;
31.6
59
0.78481
fde7df7ebaa187b9c222c6cfa19a78945952411d
797
css
CSS
public/fonts.css
malinajs/repl
a680b7781f79e9e773bcaeaf625076d8d1c57af6
[ "MIT" ]
6
2020-07-06T05:38:28.000Z
2022-03-27T14:25:13.000Z
public/fonts.css
malinajs/repl
a680b7781f79e9e773bcaeaf625076d8d1c57af6
[ "MIT" ]
5
2020-07-10T18:07:40.000Z
2022-02-26T02:00:01.000Z
public/fonts.css
malinajs/repl
a680b7781f79e9e773bcaeaf625076d8d1c57af6
[ "MIT" ]
3
2020-07-08T12:41:19.000Z
2020-07-16T21:24:09.000Z
@font-face { font-family: 'Ubuntu'; font-style: normal; font-weight: 300; src: local('Ubuntu Light '), local('Ubuntu-Light'), url('font/ubuntu-light.woff2') format('woff2'); } @font-face { font-family: 'Ubuntu'; font-style: normal; font-weight: 400; src: local('Ubuntu '), local('Ubuntu Regular '), local('Ubuntu-Regular'), url('font/ubuntu.woff2') format('woff2'); } @font-face { font-family: 'Ubuntu'; font-style: normal; font-weight: 600; src: local('Ubuntu Bold '), local('Ubuntu-Bold'), url('font/ubuntu-bold.woff2') format('woff2'); } @font-face { font-family: 'Source Code Pro'; font-weight: 400; font-style: normal; src: local('Source Code Pro'), local('SourceCodePro-Regular'), url('font/Sourcecodepro.woff2') format('woff2'); }
19.925
50
0.641154
f1d151d0ac375ae484b2d51e6474b8163cb9e5a0
2,209
dart
Dart
lib/pages/home_screen/widgets/control/category_item_widget.dart
wugq/watch_tv_app
a0d30a9b27895e57a5c46dd5fb5955e81c73356f
[ "MIT" ]
null
null
null
lib/pages/home_screen/widgets/control/category_item_widget.dart
wugq/watch_tv_app
a0d30a9b27895e57a5c46dd5fb5955e81c73356f
[ "MIT" ]
null
null
null
lib/pages/home_screen/widgets/control/category_item_widget.dart
wugq/watch_tv_app
a0d30a9b27895e57a5c46dd5fb5955e81c73356f
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:tv/data/channel.dart'; import 'package:tv/pages/home_screen/controller/home_screen_controller.dart'; class CategoryItemWidget extends StatelessWidget { final Channel channel; const CategoryItemWidget({Key? key, required this.channel}) : super(key: key); Future<bool> confirmDismissFn(BuildContext context, Channel channel) async { return await showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: const Text("Confirm"), content: Text("Are you sure you wish to delete ${channel.name} ?"), actions: <Widget>[ TextButton( onPressed: () => Navigator.of(context).pop(true), child: const Text("DELETE")), TextButton( onPressed: () => Navigator.of(context).pop(false), child: const Text("CANCEL"), ), ], ); }, ); } @override Widget build(BuildContext context) { var controller = Get.find<HomeScreenController>(); return Dismissible( key: Key(channel.key), onDismissed: (DismissDirection direction) { controller.deleteChannel(channel); }, confirmDismiss: (DismissDirection direction) async { return confirmDismissFn(context, channel); }, child: InkWell( onTap: () { controller.switchChannel(channel); }, child: Container( margin: const EdgeInsets.all(1.0), padding: const EdgeInsets.only(right: 20, left: 20), decoration: const BoxDecoration( color: Color(0xFF373542), borderRadius: BorderRadius.all( Radius.circular(5), ), ), child: Align( alignment: Alignment.centerLeft, child: Text( channel.name, style: const TextStyle( fontSize: 20.0, color: Color(0xFFfdfef5), ), maxLines: 1, overflow: TextOverflow.ellipsis, ), ), ), ), ); } }
29.851351
80
0.563603
8536ffa1ecfec41371b7b0796acc5c73b177f970
3,855
cs
C#
AltFormatter.Tests/Formatter/AltFormatter/AltFormatterTests.Restore.Enumerables.cs
pavelchai/AltFormatter
9e6d01df9c2ab75337d63d3d193999ed5a53fb1b
[ "MIT" ]
null
null
null
AltFormatter.Tests/Formatter/AltFormatter/AltFormatterTests.Restore.Enumerables.cs
pavelchai/AltFormatter
9e6d01df9c2ab75337d63d3d193999ed5a53fb1b
[ "MIT" ]
null
null
null
AltFormatter.Tests/Formatter/AltFormatter/AltFormatterTests.Restore.Enumerables.cs
pavelchai/AltFormatter
9e6d01df9c2ab75337d63d3d193999ed5a53fb1b
[ "MIT" ]
null
null
null
/* * AltFormatter. * Licensed under MIT License. * Copyright © 2017 Pavel Chaimardanov. */ using AltFormatter.Utils; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; namespace AltFormatter.Formatter { public sealed partial class AltFormatterTests { [Test, TestCaseSource("CollectionTypeGTD")] public void Restore_EmptyCollection_EmptyCollection(Type collectionGTD) { ConvertRestore_CollectionX_CollectionY_Test(false, collectionGTD, collectionGTD); } [Test, TestCaseSource("CollectionTypeGTD")] public void Restore_Collection_Collection(Type collectionGTD) { ConvertRestore_CollectionX_CollectionY_Test(true, collectionGTD, collectionGTD); } [Test, TestCaseSource("DictionaryTypeGTD")] public void Restore_EmptyDictionary_EmptyDictionary(Type dictionaryGTD) { ConvertRestore_DictionaryX_DictionaryY_Test(false, dictionaryGTD, dictionaryGTD); } [Test, TestCaseSource("DictionaryTypeGTD")] public void Restore_Dictionary_Dictionary(Type dictionaryGTD) { ConvertRestore_DictionaryX_DictionaryY_Test(true, dictionaryGTD, dictionaryGTD); } [Test, TestCaseSource("RankSource")] public void Restore_EmptyArray_EmptyArray(int rank) { Restore_Array_Array(false, rank); } [Test, TestCaseSource("RankSource")] public void Restore_Array_Array(int rank) { Restore_Array_Array(true, rank); } [Test, TestCaseSource("DictionaryTypeGTD")] public void Restore_CollectionWithDictionaryItem_CollectionWithDictionaryItem(Type dictionaryGTD) { var dictionary = ReflectionUtils.CreateDictionary(dictionaryGTD, typeof(int), typeof(int), 0).Invoke(new int[]{0}) as IDictionary<int, int>; dictionary.Add(1, 10); dictionary.Add(2, 20); var list = new List<IDictionary<int, int>>(); list.Add(dictionary); var deserialized = SerializeDeserialize(list); Assert.AreEqual(list.Count, deserialized.Count); Assert.True(list[0].SequenceEqual(dictionary)); } [Test, TestCaseSource("CollectionTypeGTD")] public void Restore_DictionaryWithCollectionItem_DictionaryWithCollectionItem(Type collectionGTD) { var collection = CreateCollection(collectionGTD, 1, 2); var dictionary = new Dictionary<IEnumerable<int>, IEnumerable<int>>(); dictionary.Add(collection, collection); var deserialized = SerializeDeserialize(dictionary); Assert.AreEqual(dictionary.Count, deserialized.Count); Assert.True(dictionary.First().Key.SequenceEqual(collection)); Assert.True(dictionary.First().Value.SequenceEqual(collection)); } private void Restore_Array_Array(bool fill, int rank) { var elementType = typeof(int); var arrayType = elementType.MakeArrayType(rank); var indexes = ArrayUtils.CreateArray(0, rank); var sizes = (fill) ? ArrayUtils.CreateArray(1, rank): ArrayUtils.CreateArray(0, rank); var array = ReflectionUtils.CreateMDArray(elementType, rank).Invoke(sizes); if(fill) { array.SetValue(1, indexes); } var deserialized = SerializeDeserialize(arrayType, array) as Array; if(fill) { Assert.AreEqual(1, deserialized.Length); Assert.AreEqual(1, deserialized.GetValue(indexes)); } else { Assert.AreEqual(0, deserialized.Length); } } } }
34.72973
149
0.637873
8765b44056a2608689ead79b00a9f2c792bc5632
189
rb
Ruby
app/components/application_component.rb
z456789/ruby-chinad
5bce1fc40ea5bac73f21d3f91114c1618a71a59b
[ "MIT" ]
1,802
2016-10-20T09:06:17.000Z
2022-03-31T04:45:23.000Z
app/components/application_component.rb
z456789/ruby-chinad
5bce1fc40ea5bac73f21d3f91114c1618a71a59b
[ "MIT" ]
429
2016-10-20T10:15:18.000Z
2022-03-29T07:54:30.000Z
app/components/application_component.rb
z456789/ruby-chinad
5bce1fc40ea5bac73f21d3f91114c1618a71a59b
[ "MIT" ]
619
2016-10-20T13:22:05.000Z
2022-03-30T09:45:33.000Z
# frozen_string_literal: true class ApplicationComponent < ViewComponent::Base delegate :user_avatar_tag, :user_name_tag, :icon_tag, :icon_bold_tag, :owner?, :main_app, to: :helpers end
31.5
104
0.78836
238b31c2a5c754e0e0e3507e3cc946b7e6a52999
4,380
sql
SQL
sql/yjbb/603316.sql
liangzi4000/grab-share-info
4dc632442d240c71955bbf927ecf276d570a2292
[ "MIT" ]
null
null
null
sql/yjbb/603316.sql
liangzi4000/grab-share-info
4dc632442d240c71955bbf927ecf276d570a2292
[ "MIT" ]
null
null
null
sql/yjbb/603316.sql
liangzi4000/grab-share-info
4dc632442d240c71955bbf927ecf276d570a2292
[ "MIT" ]
null
null
null
EXEC [EST].[Proc_yjbb_Ins] @Code = N'603316',@CutoffDate = N'2017-09-30',@EPS = N'0.3',@EPSDeduct = N'0',@Revenue = N'5.20亿',@RevenueYoy = N'27.38',@RevenueQoq = N'-11.96',@Profit = N'4556.15万',@ProfitYoy = N'16.98',@ProfiltQoq = N'-25.28',@NAVPerUnit = N'3.8225',@ROE = N'8.29',@CashPerUnit = N'-0.5868',@GrossProfitRate = N'23.23',@Distribution = N'-',@DividenRate = N'-',@AnnounceDate = N'2017-10-30' EXEC [EST].[Proc_yjbb_Ins] @Code = N'603316',@CutoffDate = N'2017-06-30',@EPS = N'0.22',@EPSDeduct = N'0.22',@Revenue = N'3.36亿',@RevenueYoy = N'17.53',@RevenueQoq = N'63.51',@Profit = N'3353.17万',@ProfitYoy = N'26.82',@ProfiltQoq = N'11.83',@NAVPerUnit = N'3.7633',@ROE = N'7.59',@CashPerUnit = N'-0.4178',@GrossProfitRate = N'22.63',@Distribution = N'不分配不转增',@DividenRate = N'-',@AnnounceDate = N'2017-08-29' EXEC [EST].[Proc_yjbb_Ins] @Code = N'603316',@CutoffDate = N'2016-12-31',@EPS = N'0.4',@EPSDeduct = N'0.4',@Revenue = N'6.31亿',@RevenueYoy = N'58.65',@RevenueQoq = N'82.81',@Profit = N'6068.28万',@ProfitYoy = N'92.84',@ProfiltQoq = N'81.19',@NAVPerUnit = N'2.7861',@ROE = N'15.38',@CashPerUnit = N'0.3054',@GrossProfitRate = N'22.97',@Distribution = N'-',@DividenRate = N'-',@AnnounceDate = N'2017-05-08' EXEC [EST].[Proc_yjbb_Ins] @Code = N'603316',@CutoffDate = N'2016-09-30',@EPS = N'0.26',@EPSDeduct = N'0',@Revenue = N'4.08亿',@RevenueYoy = N'-',@RevenueQoq = N'-34.64',@Profit = N'3894.96万',@ProfitYoy = N'-',@ProfiltQoq = N'-33.62',@NAVPerUnit = N'0.0000',@ROE = N'10.15',@CashPerUnit = N'0.0000',@GrossProfitRate = N'22.71',@Distribution = N'-',@DividenRate = N'-',@AnnounceDate = N'2017-10-30' EXEC [EST].[Proc_yjbb_Ins] @Code = N'603316',@CutoffDate = N'2017-03-31',@EPS = N'0',@EPSDeduct = N'0',@Revenue = N'1.28亿',@RevenueYoy = N'28.37',@RevenueQoq = N'-42.80',@Profit = N'1582.99万',@ProfitYoy = N'89.12',@ProfiltQoq = N'-27.16',@NAVPerUnit = N'2.8900',@ROE = N'-',@CashPerUnit = N'-0.3756',@GrossProfitRate = N'24.56',@Distribution = N'-',@DividenRate = N'-',@AnnounceDate = N'2017-06-16' EXEC [EST].[Proc_yjbb_Ins] @Code = N'603316',@CutoffDate = N'2014-12-31',@EPS = N'0.25',@EPSDeduct = N'0.25',@Revenue = N'4.63亿',@RevenueYoy = N'-6.25',@RevenueQoq = N'-',@Profit = N'3868.78万',@ProfitYoy = N'-17.87',@ProfiltQoq = N'-',@NAVPerUnit = N'2.1817',@ROE = N'12.35',@CashPerUnit = N'-0.5101',@GrossProfitRate = N'27.47',@Distribution = N'-',@DividenRate = N'-',@AnnounceDate = N'2017-05-08' EXEC [EST].[Proc_yjbb_Ins] @Code = N'603316',@CutoffDate = N'2013-12-31',@EPS = N'0.31',@EPSDeduct = N'0.3',@Revenue = N'4.94亿',@RevenueYoy = N'0.45',@RevenueQoq = N'-',@Profit = N'4710.42万',@ProfitYoy = N'34.21',@ProfiltQoq = N'-',@NAVPerUnit = N'1.9320',@ROE = N'17.38',@CashPerUnit = N'0.0634',@GrossProfitRate = N'25.82',@Distribution = N'-',@DividenRate = N'-',@AnnounceDate = N'2015-07-03' EXEC [EST].[Proc_yjbb_Ins] @Code = N'603316',@CutoffDate = N'2016-06-30',@EPS = N'0.17',@EPSDeduct = N'0.17',@Revenue = N'2.86亿',@RevenueYoy = N'-',@RevenueQoq = N'87.83',@Profit = N'2644.05万',@ProfitYoy = N'-',@ProfiltQoq = N'115.89',@NAVPerUnit = N'0.0000',@ROE = N'6.98',@CashPerUnit = N'0.0000',@GrossProfitRate = N'22.26',@Distribution = N'-',@DividenRate = N'-',@AnnounceDate = N'2017-08-29' EXEC [EST].[Proc_yjbb_Ins] @Code = N'603316',@CutoffDate = N'2015-12-31',@EPS = N'0.21',@EPSDeduct = N'0.21',@Revenue = N'3.98亿',@RevenueYoy = N'-14.08',@RevenueQoq = N'-',@Profit = N'3146.80万',@ProfitYoy = N'-18.66',@ProfiltQoq = N'-',@NAVPerUnit = N'2.3881',@ROE = N'9.03',@CashPerUnit = N'0.3072',@GrossProfitRate = N'26.47',@Distribution = N'-',@DividenRate = N'-',@AnnounceDate = N'2017-05-08' EXEC [EST].[Proc_yjbb_Ins] @Code = N'603316',@CutoffDate = N'2016-03-31',@EPS = N'0',@EPSDeduct = N'0',@Revenue = N'9933.99万',@RevenueYoy = N'-',@RevenueQoq = N'-',@Profit = N'837.03万',@ProfitYoy = N'-',@ProfiltQoq = N'-',@NAVPerUnit = N'0.0000',@ROE = N'-',@CashPerUnit = N'0.0000',@GrossProfitRate = N'24.81',@Distribution = N'-',@DividenRate = N'-',@AnnounceDate = N'2017-06-16' EXEC [EST].[Proc_yjbb_Ins] @Code = N'603316',@CutoffDate = N'2012-12-31',@EPS = N'0.23',@EPSDeduct = N'0.22',@Revenue = N'4.91亿',@RevenueYoy = N'-',@RevenueQoq = N'-',@Profit = N'3509.82万',@ProfitYoy = N'-',@ProfiltQoq = N'-',@NAVPerUnit = N'1.6231',@ROE = N'18.93',@CashPerUnit = N'-0.4428',@GrossProfitRate = N'21.48',@Distribution = N'-',@DividenRate = N'-',@AnnounceDate = N'2015-07-03'
398.181818
410
0.636758
dad722f803ab9d536dab37e32ef3777690e844aa
2,735
sql
SQL
db/cruise_one_system/cruise_one_system_v_c_voyage_boarding_recode.sql
vin120/vcos
b86df6c888c3e37c3d33ff26088d9d6b48a24495
[ "BSD-3-Clause" ]
null
null
null
db/cruise_one_system/cruise_one_system_v_c_voyage_boarding_recode.sql
vin120/vcos
b86df6c888c3e37c3d33ff26088d9d6b48a24495
[ "BSD-3-Clause" ]
null
null
null
db/cruise_one_system/cruise_one_system_v_c_voyage_boarding_recode.sql
vin120/vcos
b86df6c888c3e37c3d33ff26088d9d6b48a24495
[ "BSD-3-Clause" ]
null
null
null
CREATE DATABASE IF NOT EXISTS `cruise_one_system` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `cruise_one_system`; -- MySQL dump 10.13 Distrib 5.7.9, for osx10.9 (x86_64) -- -- Host: bisheng.8800.org Database: cruise_one_system -- ------------------------------------------------------ -- Server version 5.5.17-log /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `v_c_voyage_boarding_recode` -- DROP TABLE IF EXISTS `v_c_voyage_boarding_recode`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `v_c_voyage_boarding_recode` ( `id` int(11) NOT NULL AUTO_INCREMENT, `voyage_code` varchar(32) DEFAULT NULL, `voyage_port_id` int(11) DEFAULT NULL, `passport_number` varchar(32) DEFAULT NULL, `boarding_time` datetime DEFAULT NULL, `create_by` varchar(32) DEFAULT NULL, `person_type` enum('3','2','1') DEFAULT '1' COMMENT '1会员,2船员,3访客', `gangway_type` enum('2','1') DEFAULT '1' COMMENT '1登船,2下船', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COMMENT='航线登船记录表'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `v_c_voyage_boarding_recode` -- LOCK TABLES `v_c_voyage_boarding_recode` WRITE; /*!40000 ALTER TABLE `v_c_voyage_boarding_recode` DISABLE KEYS */; INSERT INTO `v_c_voyage_boarding_recode` VALUES (1,'12',21,'12','2016-05-10 18:16:01','1','1','1'),(2,'1461981295',1,'888888','2016-05-09 18:17:37',NULL,'1','1'),(4,'1461981295',1,'888888','2016-05-09 18:17:38',NULL,'1','1'),(6,'1461981295',1,'888888','2016-05-09 18:17:39',NULL,'1','1'); /*!40000 ALTER TABLE `v_c_voyage_boarding_recode` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2016-05-16 10:58:07
45.583333
288
0.715905
f4f2e043658b3cd4abdcf70f037d8dff83c23aa6
554
ts
TypeScript
src/utils.ts
hjrt/react-quick-pinch-zoom
988044e65f731db8a9f4728e5be4815e255480b8
[ "MIT" ]
62
2019-04-25T04:34:40.000Z
2022-03-08T13:56:22.000Z
src/utils.ts
hjrt/react-quick-pinch-zoom
988044e65f731db8a9f4728e5be4815e255480b8
[ "MIT" ]
39
2019-06-17T15:55:28.000Z
2022-03-21T12:01:46.000Z
src/utils.ts
hjrt/react-quick-pinch-zoom
988044e65f731db8a9f4728e5be4815e255480b8
[ "MIT" ]
23
2019-04-30T17:55:05.000Z
2022-02-16T01:48:28.000Z
import { UpdateAction } from './PinchZoom/types'; export const isTouch = () => 'ontouchstart' in window || navigator.maxTouchPoints > 0; export const make2dTransformValue = ({ x, y, scale }: UpdateAction) => `scale(${scale}) translate(${x}px, ${y}px)`; export const make3dTransformValue = ({ x, y, scale }: UpdateAction) => `scale3d(${scale},${scale}, 1) translate3d(${x}px, ${y}px, 0)`; export const hasTranslate3DSupport = () => { const css = window.CSS; return css && css.supports && css.supports('transform', 'translate3d(0,0,0)'); };
32.588235
80
0.65343
051cff7ac0159f4d9cb6006b689e2f35021202a6
1,281
rb
Ruby
app/models/result.rb
lgarron/cube_trainer
d4cddc9fb097b219c14ee5527f03b4bb95c62f24
[ "MIT" ]
null
null
null
app/models/result.rb
lgarron/cube_trainer
d4cddc9fb097b219c14ee5527f03b4bb95c62f24
[ "MIT" ]
null
null
null
app/models/result.rb
lgarron/cube_trainer
d4cddc9fb097b219c14ee5527f03b4bb95c62f24
[ "MIT" ]
null
null
null
# frozen_string_literal: true # Result of giving one task to the user and judging their performance. # E.g. the time it took to execute one algorithm for a case shown to them. class Result < ApplicationRecord POSITIVE_INTEGER = { only_integer: true, greater_than_or_equal_to: 0 }.freeze belongs_to :mode attribute :case_key, :input_representation validates :time_s, presence: true, numericality: { greater_than: 0 } validates :failed_attempts, numericality: POSITIVE_INTEGER validates :success, inclusion: [true, false] validates :num_hints, numericality: POSITIVE_INTEGER validates :case_key, presence: true validates :mode_id, presence: true def to_simple { id: id, case_key: InputRepresentationType.new.serialize(case_key), case_name: mode.maybe_apply_letter_scheme(case_key).to_s, time_s: time_s, failed_attempts: failed_attempts, word: word, success: success, num_hints: num_hints, created_at: created_at } end def to_dump { case_key: case_key.to_s, time_s: time_s, failed_attempts: failed_attempts, word: word, success: success, num_hints: num_hints, created_at: created_at } end def time time_s&.seconds end end
25.117647
74
0.704137
1792c6026eb7c478ec5463125ce822e95de10788
463
dart
Dart
lib/ui/view/select_category/select_category_viewmodel.dart
sumithpdd/Sub-Track
e65ba454b4b8d6df17ad70cc4180b7cf56c193ba
[ "MIT" ]
26
2021-05-11T20:51:34.000Z
2022-02-05T04:41:54.000Z
lib/ui/view/select_category/select_category_viewmodel.dart
sumithpdd/Sub-Track
e65ba454b4b8d6df17ad70cc4180b7cf56c193ba
[ "MIT" ]
2
2021-05-12T01:53:54.000Z
2021-05-25T00:21:21.000Z
lib/ui/view/select_category/select_category_viewmodel.dart
sumithpdd/Sub-Track
e65ba454b4b8d6df17ad70cc4180b7cf56c193ba
[ "MIT" ]
1
2021-05-13T20:27:52.000Z
2021-05-13T20:27:52.000Z
import 'package:stacked/stacked.dart'; import 'package:stacked_services/stacked_services.dart'; import 'package:sub_track/app/app.locatorx.dart'; import 'package:sub_track/ui/models/category.dart'; import 'package:sub_track/ui/shared/mixins.dart'; class SelectCategoryViewModel extends BaseViewModel with $SharedVariables { List<Category> get categories => Category.categories; pop({String? category}) => $navigationService.back(id: 2, result: category); }
38.583333
78
0.792657
96d477e64e10cc205028aea3ed4e9c3514d5a1a2
1,487
cs
C#
FairCastleOwnershipVoteSubModule.cs
samlbest/FairCastleOwnershipVote
956aaae2265e9fe31c08fe555be28d27c8ff55b3
[ "MIT" ]
null
null
null
FairCastleOwnershipVoteSubModule.cs
samlbest/FairCastleOwnershipVote
956aaae2265e9fe31c08fe555be28d27c8ff55b3
[ "MIT" ]
null
null
null
FairCastleOwnershipVoteSubModule.cs
samlbest/FairCastleOwnershipVote
956aaae2265e9fe31c08fe555be28d27c8ff55b3
[ "MIT" ]
null
null
null
using System; using System.Linq; using FairCastleOwnershipVote.Models; using HarmonyLib; using TaleWorlds.CampaignSystem; using TaleWorlds.Core; using TaleWorlds.MountAndBlade; namespace FairCastleOwnershipVote { public class FairCastleOwnershipVoteSubModule : MBSubModuleBase { internal static FairCastleOwnershipVoteSubModule Current => Module.CurrentModule.SubModules.OfType<FairCastleOwnershipVoteSubModule>().FirstOrDefault(); protected override void OnBeforeInitialModuleScreenSetAsRoot() { try { var harmony = new Harmony(nameof(FairCastleOwnershipVoteSubModule)); harmony.PatchAll(typeof(FairCastleOwnershipVoteSubModule).Assembly); } catch (Exception ex) { FileLog.Log($"Error on PatchAll: {ex}"); throw; } } protected override void OnGameStart(Game game, IGameStarter gameStarterObject) { base.OnGameStart(game, gameStarterObject); try { AddModels(gameStarterObject as CampaignGameStarter); } catch (Exception ex) { FileLog.Log($"Error on AddModels: {ex}"); throw; } } private void AddModels(CampaignGameStarter gameStarter) { gameStarter.AddModel(new FairPartySpeedCalculatingModel()); } } }
29.74
160
0.610625
2df12cd20b49426ffd233dfef516055fda745ce3
1,659
cc
C++
tfjs-backend-wasm/src/cc/kernels/Max.cc
carlosorochi/tfjs
677bd69e00077dc834af1614c19d7e9288458416
[ "Apache-2.0" ]
1
2019-11-02T00:57:01.000Z
2019-11-02T00:57:01.000Z
tfjs-backend-wasm/src/cc/kernels/Max.cc
carlosorochi/tfjs
677bd69e00077dc834af1614c19d7e9288458416
[ "Apache-2.0" ]
null
null
null
tfjs-backend-wasm/src/cc/kernels/Max.cc
carlosorochi/tfjs
677bd69e00077dc834af1614c19d7e9288458416
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 Google 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. * ===========================================================================*/ #ifdef __EMSCRIPTEN__ #include <emscripten.h> #endif #include "src/cc/backend.h" namespace tfjs { namespace wasm { // We use C-style API to interface with Javascript. extern "C" { #ifdef __EMSCRIPTEN__ EMSCRIPTEN_KEEPALIVE #endif void Max(int x_id, int reduce_size, int out_id) { const auto x_info = backend::get_tensor_info(x_id); const auto out_info = backend::get_tensor_info(out_id); float* x_buf = x_info.buf.f32; int x_size = x_info.size; float* out_buf = out_info.buf.f32; int out_size = out_info.size; float* x_offset = x_info.buf.f32; for (int i = 0; i < out_size; ++i) { int offset = i * reduce_size; float max = x_buf[offset]; float* x_iter_end = x_offset + reduce_size; for (float* x = x_offset; x < x_iter_end; ++x) { float value = *x; if (value > max) { max = value; } } x_offset += reduce_size; out_buf[i] = max; } } } // extern "C" } // namespace wasm } // namespace tfjs
26.333333
80
0.653406
43b42f28f93f9aba1a74447a707ef50b8e73a83b
83
ts
TypeScript
dist/version.d.ts
Catalyst-Video/catalyst-lk-client
c68179a4450534d22dbd95ea16b0de08661121a3
[ "Apache-2.0" ]
null
null
null
dist/version.d.ts
Catalyst-Video/catalyst-lk-client
c68179a4450534d22dbd95ea16b0de08661121a3
[ "Apache-2.0" ]
null
null
null
dist/version.d.ts
Catalyst-Video/catalyst-lk-client
c68179a4450534d22dbd95ea16b0de08661121a3
[ "Apache-2.0" ]
null
null
null
export declare const version = "0.12.2"; export declare const protocolVersion = 3;
27.666667
41
0.759036
a19ca849a936540a3f0f203b1c446ba63234b887
125
ts
TypeScript
server/src/models/client.model.ts
joserosa33/calendar
80c1aa4083937598ed0814d8ed9c9e5836269546
[ "MIT" ]
null
null
null
server/src/models/client.model.ts
joserosa33/calendar
80c1aa4083937598ed0814d8ed9c9e5836269546
[ "MIT" ]
null
null
null
server/src/models/client.model.ts
joserosa33/calendar
80c1aa4083937598ed0814d8ed9c9e5836269546
[ "MIT" ]
null
null
null
export class ClientModel { public name: String; constructor({name}: ClientModel) { this.name = name; } }
17.857143
38
0.608
d74742feeaa0b71f2f8d2535a5559323819596c8
7,922
swift
Swift
Sources/Odeum/Classes/PlayControlView.swift
hainayanda/Odeum
e723624e9e3e0018df8646677667a07f4d0ef00f
[ "MIT" ]
1
2021-08-17T19:48:39.000Z
2021-08-17T19:48:39.000Z
Sources/Odeum/Classes/PlayControlView.swift
hainayanda/Odeum
e723624e9e3e0018df8646677667a07f4d0ef00f
[ "MIT" ]
null
null
null
Sources/Odeum/Classes/PlayControlView.swift
hainayanda/Odeum
e723624e9e3e0018df8646677667a07f4d0ef00f
[ "MIT" ]
null
null
null
// // PlayControlView.swift // Odeum // // Created by Nayanda Haberty on 23/01/21. // import Foundation #if canImport(UIKit) import UIKit // MARK: Delegate public protocol PlayControlViewDelegate: AnyObject { func playControl(_ view: PlayControlView, audioDidChangeStateTo state: AudioState) func playControl(_ view: PlayControlView, playDidChangeStateTo state: PlayState) func playControl(_ view: PlayControlView, fullScreenDidChangeStateTo state: FullScreenState) func playControl(_ view: PlayControlView, didTapForward step: ForwardStep) func playControl(_ view: PlayControlView, didTapReplay step: ReplayStep) } // MARK: PlayControlView public class PlayControlView: UIView { // MARK: Views public private(set) lazy var blurEffectView: UIVisualEffectView = { let blurEffect = UIBlurEffect(style: .light) let effect = UIVisualEffectView(effect: blurEffect) effect.autoresizingMask = [.flexibleWidth, .flexibleHeight] return effect }() public private(set) lazy var buttonStack: UIStackView = { let stack = UIStackView( arrangedSubviews: [ audioButton, replayButton, playButton, forwardButton, fullScreenButton ] ) stack.alignment = .fill stack.axis = .horizontal stack.distribution = .fillEqually stack.spacing = 0 stack.layoutMargins = .zero stack.isLayoutMarginsRelativeArrangement = true return stack }() public private(set) lazy var audioButton: UIButton = createButton( with: audioState.icon, selector: #selector(didTapAudio(_:)) ) public private(set) lazy var replayButton: UIButton = createButton( with: replayStep.icon, selector: #selector(didTapReplay(_:)) ) public private(set) lazy var playButton: UIButton = createButton( with: playState.icon, selector: #selector(didTapPlay(_:)) ) public private(set) lazy var forwardButton: UIButton = createButton( with: forwardStep.icon, selector: #selector(didTapForward(_:)) ) public private(set) lazy var fullScreenButton: UIButton = createButton( with: fullScreenState.icon, selector: #selector(didTapFullScreen(_:)) ) // MARK: State public var audioState: AudioState = .unmute { didSet { audioButton.setImage(icon(for: audioState), for: .normal) } } public var replayStep: ReplayStep = .fiveSecond { didSet { replayButton.setImage(icon(for: replayStep), for: .normal) } } public var playState: PlayState = .played { didSet { playButton.setImage(icon(for: playState), for: .normal) } } public var forwardStep: ForwardStep = .fiveSecond { didSet { forwardButton.setImage(icon(for: forwardStep), for: .normal) } } public var fullScreenState: FullScreenState = .minimize { didSet { fullScreenButton.setImage(icon(for: fullScreenState), for: .normal) } } // MARK: Icons var customIcons: [AnyHashable: UIImage] = [:] // MARK: Delegate public weak var delegate: PlayControlViewDelegate? // MARK: Initializer public override init(frame: CGRect) { super.init(frame: frame) buildView() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func buildView() { setupBlurEffectView() setupButtonStack() } func setupBlurEffectView() { blurEffectView.translatesAutoresizingMaskIntoConstraints = false addSubview(blurEffectView) NSLayoutConstraint.activate([ blurEffectView.leftAnchor.constraint(equalTo: leftAnchor), blurEffectView.topAnchor.constraint(equalTo: topAnchor), blurEffectView.rightAnchor.constraint(equalTo: rightAnchor), blurEffectView.bottomAnchor.constraint(equalTo: bottomAnchor), ]) } func setupButtonStack() { buttonStack.translatesAutoresizingMaskIntoConstraints = false addSubview(buttonStack) NSLayoutConstraint.activate([ buttonStack.leftAnchor.constraint(equalTo: leftAnchor), buttonStack.topAnchor.constraint(equalTo: topAnchor), buttonStack.rightAnchor.constraint(equalTo: rightAnchor), buttonStack.bottomAnchor.constraint(equalTo: bottomAnchor), buttonStack.widthAnchor.constraint(equalTo: buttonStack.heightAnchor, multiplier: 5) ]) } func createButton( with icon: UIImage, selector: Selector) -> UIButton { let button = UIButton() button.backgroundColor = .clear button.setImage(icon, for: .normal) button.imageView?.contentMode = .scaleAspectFit button.addTarget(self, action: selector, for: .touchUpInside) return button } public override func layoutSubviews() { super.layoutSubviews() let insets = bounds.height / 3 let playInsets = insets / 3 let buttonInsets: UIEdgeInsets = .init(top: insets, left: insets, bottom: insets, right: insets) let playButtonInsets: UIEdgeInsets = .init(top: playInsets, left: playInsets, bottom: playInsets, right: playInsets) audioButton.imageEdgeInsets = buttonInsets replayButton.imageEdgeInsets = buttonInsets playButton.imageEdgeInsets = playButtonInsets forwardButton.imageEdgeInsets = buttonInsets fullScreenButton.imageEdgeInsets = buttonInsets } // MARK: Public public func icon(for audioState: AudioState) -> UIImage { customIcons[audioState] ?? audioState.icon } public func icon(for replayState: ReplayStep) -> UIImage { customIcons[replayState] ?? replayState.icon } public func icon(for playState: PlayState) -> UIImage { customIcons[playState] ?? playState.icon } public func icon(for forwardState: ForwardStep) -> UIImage { customIcons[forwardState] ?? forwardState.icon } public func icon(for fullScreenState: FullScreenState) -> UIImage { customIcons[fullScreenState] ?? fullScreenState.icon } public func set(icon: UIImage, for audioState: AudioState) { customIcons[audioState] = icon } public func set(icon: UIImage, for replayState: ReplayStep) { customIcons[replayState] = icon } public func set(icon: UIImage, for playState: PlayState) { customIcons[playState] = icon } public func set(icon: UIImage, for forwardState: ForwardStep) { customIcons[forwardState] = icon } public func set(icon: UIImage, for fullScreenState: FullScreenState) { customIcons[fullScreenState] = icon } // MARK: Delegate @objc func didTapAudio(_ sender: UIButton) { audioState = audioState == .mute ? .unmute : .mute delegate?.playControl(self, audioDidChangeStateTo: audioState) } @objc func didTapReplay(_ sender: UIButton) { delegate?.playControl(self, didTapReplay: replayStep) } @objc func didTapPlay(_ sender: UIButton) { playState = playState == .played ? .paused : .played delegate?.playControl(self, playDidChangeStateTo: playState) } @objc func didTapForward(_ sender: UIButton) { delegate?.playControl(self, didTapForward: forwardStep) } @objc func didTapFullScreen(_ sender: UIButton) { fullScreenState = fullScreenState == .minimize ? .fullScreen : .minimize delegate?.playControl(self, fullScreenDidChangeStateTo: fullScreenState) } } #endif
33.008333
124
0.648195
85a786cc2d3d62b7fe5f801c43025f49918f8f5c
19,990
swift
Swift
Sources/Soto/Services/Billingconductor/Billingconductor_API.swift
swift-aws/aws-sdk-swift
778b1eda58da7fa233e5e1880e0ec6263be2a8e4
[ "Apache-2.0" ]
349
2018-07-28T09:39:30.000Z
2020-09-12T02:03:11.000Z
Sources/Soto/Services/Billingconductor/Billingconductor_API.swift
swift-aws/aws-sdk-swift
778b1eda58da7fa233e5e1880e0ec6263be2a8e4
[ "Apache-2.0" ]
163
2018-08-04T02:28:39.000Z
2020-09-12T18:42:39.000Z
Sources/Soto/Services/Billingconductor/Billingconductor_API.swift
swift-aws/aws-sdk-swift
778b1eda58da7fa233e5e1880e0ec6263be2a8e4
[ "Apache-2.0" ]
51
2018-08-08T11:12:01.000Z
2020-09-13T07:27:09.000Z
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2021 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto-codegenerator. // DO NOT EDIT. @_exported import SotoCore /// Service object for interacting with AWS Billingconductor service. /// /// Amazon Web Services Billing Conductor is a fully managed service that you can use to customize a pro forma version of your billing data each month, to accurately show or chargeback your end customers. Amazon Web Services Billing Conductor doesn't change the way you're billed by Amazon Web Services each month by design. Instead, it provides you with a mechanism to configure, generate, and display rates to certain customers over a given billing period. You can also analyze the difference between the rates you apply to your accounting groupings relative to your actual rates from Amazon Web Services. As a result of your Amazon Web Services Billing Conductor configuration, the payer account can also see the custom rate applied on the billing details page of the Amazon Web Services Billing console, or configure a cost and usage report per billing group. This documentation shows how you can configure Amazon Web Services Billing Conductor using its API. For more information about using the Amazon Web Services Billing Conductor user interface, see the Amazon Web Services Enterprise Billing Console User Guide. public struct Billingconductor: AWSService { // MARK: Member variables /// Client used for communication with AWS public let client: AWSClient /// Service configuration public let config: AWSServiceConfig // MARK: Initialization /// Initialize the Billingconductor client /// - parameters: /// - client: AWSClient used to process requests /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(), options: AWSServiceConfig.Options = [] ) { self.client = client self.config = AWSServiceConfig( region: nil, partition: partition, service: "billingconductor", serviceProtocol: .restjson, apiVersion: "2021-07-30", endpoint: endpoint, serviceEndpoints: ["aws-global": "billingconductor.us-east-1.amazonaws.com"], partitionEndpoints: [.aws: (endpoint: "aws-global", region: .useast1)], errorType: BillingconductorErrorType.self, timeout: timeout, byteBufferAllocator: byteBufferAllocator, options: options ) } // MARK: API Calls /// Connects an array of account IDs in a consolidated billing family to a predefined billing group. The account IDs must be a part of the consolidated billing family during the current month, and not already associated with another billing group. The maximum number of accounts that can be associated in one call is 30. public func associateAccounts(_ input: AssociateAccountsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AssociateAccountsOutput> { return self.client.execute(operation: "AssociateAccounts", path: "/associate-accounts", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Connects an array of PricingRuleArns to a defined PricingPlan. The maximum number PricingRuleArn that can be associated in one call is 30. public func associatePricingRules(_ input: AssociatePricingRulesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AssociatePricingRulesOutput> { return self.client.execute(operation: "AssociatePricingRules", path: "/associate-pricing-rules", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Associates a batch of resources to a percentage custom line item. public func batchAssociateResourcesToCustomLineItem(_ input: BatchAssociateResourcesToCustomLineItemInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchAssociateResourcesToCustomLineItemOutput> { return self.client.execute(operation: "BatchAssociateResourcesToCustomLineItem", path: "/batch-associate-resources-to-custom-line-item", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Disassociates a batch of resources from a percentage custom line item. public func batchDisassociateResourcesFromCustomLineItem(_ input: BatchDisassociateResourcesFromCustomLineItemInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<BatchDisassociateResourcesFromCustomLineItemOutput> { return self.client.execute(operation: "BatchDisassociateResourcesFromCustomLineItem", path: "/batch-disassociate-resources-from-custom-line-item", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a billing group that resembles a consolidated billing family that Amazon Web Services charges, based off of the predefined pricing plan computation. public func createBillingGroup(_ input: CreateBillingGroupInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateBillingGroupOutput> { return self.client.execute(operation: "CreateBillingGroup", path: "/create-billing-group", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a custom line item that can be used to create a one-time fixed charge that can be applied to a single billing group for the current or previous billing period. The one-time fixed charge is either a fee or discount. public func createCustomLineItem(_ input: CreateCustomLineItemInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateCustomLineItemOutput> { return self.client.execute(operation: "CreateCustomLineItem", path: "/create-custom-line-item", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a pricing plan that is used for computing Amazon Web Services charges for billing groups. public func createPricingPlan(_ input: CreatePricingPlanInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreatePricingPlanOutput> { return self.client.execute(operation: "CreatePricingPlan", path: "/create-pricing-plan", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a pricing rule can be associated to a pricing plan, or a set of pricing plans. public func createPricingRule(_ input: CreatePricingRuleInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreatePricingRuleOutput> { return self.client.execute(operation: "CreatePricingRule", path: "/create-pricing-rule", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes a billing group. public func deleteBillingGroup(_ input: DeleteBillingGroupInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteBillingGroupOutput> { return self.client.execute(operation: "DeleteBillingGroup", path: "/delete-billing-group", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the custom line item identified by the given ARN in the current, or previous billing period. public func deleteCustomLineItem(_ input: DeleteCustomLineItemInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteCustomLineItemOutput> { return self.client.execute(operation: "DeleteCustomLineItem", path: "/delete-custom-line-item", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes a pricing plan. The pricing plan must not be associated with any billing groups to delete successfully. public func deletePricingPlan(_ input: DeletePricingPlanInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeletePricingPlanOutput> { return self.client.execute(operation: "DeletePricingPlan", path: "/delete-pricing-plan", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the pricing rule identified by the input Amazon Resource Name (ARN). public func deletePricingRule(_ input: DeletePricingRuleInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeletePricingRuleOutput> { return self.client.execute(operation: "DeletePricingRule", path: "/delete-pricing-rule", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Removes the specified list of account IDs from the given billing group. public func disassociateAccounts(_ input: DisassociateAccountsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DisassociateAccountsOutput> { return self.client.execute(operation: "DisassociateAccounts", path: "/disassociate-accounts", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Disassociates a list of pricing rules from a pricing plan. public func disassociatePricingRules(_ input: DisassociatePricingRulesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DisassociatePricingRulesOutput> { return self.client.execute(operation: "DisassociatePricingRules", path: "/disassociate-pricing-rules", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Amazon Web Services Billing Conductor is in beta release and is subject to change. Your use of Amazon Web Services Billing Conductor is subject to the Beta Service Participation terms of the Amazon Web Services Service Terms (Section 1.10). This is a paginated call to list linked accounts that are linked to the payer account for the specified time period. If no information is provided, the current billing period is used. The response will optionally include the billing group associated with the linked account. public func listAccountAssociations(_ input: ListAccountAssociationsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListAccountAssociationsOutput> { return self.client.execute(operation: "ListAccountAssociations", path: "/list-account-associations", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// A paginated call to retrieve a summary report of actual Amazon Web Services charges and the calculated Amazon Web Services charges based on the associated pricing plan of a billing group. public func listBillingGroupCostReports(_ input: ListBillingGroupCostReportsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListBillingGroupCostReportsOutput> { return self.client.execute(operation: "ListBillingGroupCostReports", path: "/list-billing-group-cost-reports", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// A paginated call to retrieve a list of billing groups for the given billing period. If you don't provide a billing group, the current billing period is used. public func listBillingGroups(_ input: ListBillingGroupsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListBillingGroupsOutput> { return self.client.execute(operation: "ListBillingGroups", path: "/list-billing-groups", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// A paginated call to get a list of all custom line items (FFLIs) for the given billing period. If you don't provide a billing period, the current billing period is used. public func listCustomLineItems(_ input: ListCustomLineItemsInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListCustomLineItemsOutput> { return self.client.execute(operation: "ListCustomLineItems", path: "/list-custom-line-items", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// A paginated call to get pricing plans for the given billing period. If you don't provide a billing period, the current billing period is used. public func listPricingPlans(_ input: ListPricingPlansInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPricingPlansOutput> { return self.client.execute(operation: "ListPricingPlans", path: "/list-pricing-plans", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// A list of the pricing plans associated with a pricing rule. public func listPricingPlansAssociatedWithPricingRule(_ input: ListPricingPlansAssociatedWithPricingRuleInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPricingPlansAssociatedWithPricingRuleOutput> { return self.client.execute(operation: "ListPricingPlansAssociatedWithPricingRule", path: "/list-pricing-plans-associated-with-pricing-rule", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Describes a pricing rule that can be associated to a pricing plan, or set of pricing plans. public func listPricingRules(_ input: ListPricingRulesInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPricingRulesOutput> { return self.client.execute(operation: "ListPricingRules", path: "/list-pricing-rules", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the pricing rules associated with a pricing plan. public func listPricingRulesAssociatedToPricingPlan(_ input: ListPricingRulesAssociatedToPricingPlanInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPricingRulesAssociatedToPricingPlanOutput> { return self.client.execute(operation: "ListPricingRulesAssociatedToPricingPlan", path: "/list-pricing-rules-associated-to-pricing-plan", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// List the resources associated to a custom line item. public func listResourcesAssociatedToCustomLineItem(_ input: ListResourcesAssociatedToCustomLineItemInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListResourcesAssociatedToCustomLineItemOutput> { return self.client.execute(operation: "ListResourcesAssociatedToCustomLineItem", path: "/list-resources-associated-to-custom-line-item", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// A list the tags for a resource. public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListTagsForResourceResponse> { return self.client.execute(operation: "ListTagsForResource", path: "/tags/{ResourceArn}", httpMethod: .GET, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Associates the specified tags to a resource with the specified resourceArn. If existing tags on a resource are not specified in the request parameters, they are not changed. public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<TagResourceResponse> { return self.client.execute(operation: "TagResource", path: "/tags/{ResourceArn}", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes specified tags from a resource. public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UntagResourceResponse> { return self.client.execute(operation: "UntagResource", path: "/tags/{ResourceArn}", httpMethod: .DELETE, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// This updates an existing billing group. public func updateBillingGroup(_ input: UpdateBillingGroupInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateBillingGroupOutput> { return self.client.execute(operation: "UpdateBillingGroup", path: "/update-billing-group", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Update an existing custom line item in the current or previous billing period. public func updateCustomLineItem(_ input: UpdateCustomLineItemInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdateCustomLineItemOutput> { return self.client.execute(operation: "UpdateCustomLineItem", path: "/update-custom-line-item", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// This updates an existing pricing plan. public func updatePricingPlan(_ input: UpdatePricingPlanInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdatePricingPlanOutput> { return self.client.execute(operation: "UpdatePricingPlan", path: "/update-pricing-plan", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates an existing pricing rule. public func updatePricingRule(_ input: UpdatePricingRuleInput, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdatePricingRuleOutput> { return self.client.execute(operation: "UpdatePricingRule", path: "/update-pricing-rule", httpMethod: .PUT, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } extension Billingconductor { /// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public /// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead. public init(from: Billingconductor, patch: AWSServiceConfig.Patch) { self.client = from.client self.config = from.config.with(patch: patch) } }
88.844444
1,122
0.752226
d0496f8337a0e95da8a1d22831111358380bbbea
4,270
hpp
C++
third_party/omr/gc/base/standard/ConfigurationStandard.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/gc/base/standard/ConfigurationStandard.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/gc/base/standard/ConfigurationStandard.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 1991, 2017 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at https://www.eclipse.org/legal/epl-2.0/ * or the Apache License, Version 2.0 which accompanies this distribution and * is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following * Secondary Licenses when the conditions for such availability set * forth in the Eclipse Public License, v. 2.0 are satisfied: GNU * General Public License, version 2 with the GNU Classpath * Exception [1] and GNU General Public License, version 2 with the * OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ /** * @file * @ingroup GC_Modron_Standard */ #if !defined(CONFIGURATIONSTANDARD_HPP_) #define CONFIGURATIONSTANDARD_HPP_ #include "omrcfg.h" #include "Configuration.hpp" #include "EnvironmentBase.hpp" #if defined(OMR_GC_MODRON_STANDARD) class MM_GlobalCollector; class MM_Heap; class MM_MemoryPool; class MM_ConfigurationStandard : public MM_Configuration { /* Data members / Types */ public: protected: /* Create Memory Pool(s) * @param appendCollectorLargeAllocateStats - if true, configure the pool to append Collector allocates to Mutator allocates (default is to gather only Mutator) */ virtual MM_MemoryPool* createMemoryPool(MM_EnvironmentBase* env, bool appendCollectorLargeAllocateStats); virtual void tearDown(MM_EnvironmentBase* env); bool createSweepPoolManagerAddressOrderedList(MM_EnvironmentBase* env); bool createSweepPoolManagerSplitAddressOrderedList(MM_EnvironmentBase* env); bool createSweepPoolManagerHybrid(MM_EnvironmentBase* env); static const uintptr_t STANDARD_REGION_SIZE_BYTES = 64 * 1024; static const uintptr_t STANDARD_ARRAYLET_LEAF_SIZE_BYTES = UDATA_MAX; private: /* Methods */ public: virtual MM_GlobalCollector* createGlobalCollector(MM_EnvironmentBase* env); virtual MM_Heap* createHeapWithManager(MM_EnvironmentBase* env, uintptr_t heapBytesRequested, MM_HeapRegionManager* regionManager); virtual MM_HeapRegionManager* createHeapRegionManager(MM_EnvironmentBase* env); virtual J9Pool* createEnvironmentPool(MM_EnvironmentBase* env); MM_ConfigurationStandard(MM_EnvironmentBase* env, MM_GCPolicy gcPolicy, uintptr_t regionSize) : MM_Configuration(env, gcPolicy, mm_regionAlignment, regionSize, STANDARD_ARRAYLET_LEAF_SIZE_BYTES, getWriteBarrierType(env), gc_modron_allocation_type_tlh) { _typeId = __FUNCTION__; }; protected: virtual bool initialize(MM_EnvironmentBase* env); virtual MM_EnvironmentBase* allocateNewEnvironment(MM_GCExtensionsBase* extensions, OMR_VMThread* omrVMThread); /** * Sets the number of gc threads * * @param env[in] - the current environment */ virtual void initializeGCThreadCount(MM_EnvironmentBase* env); private: static MM_GCWriteBarrierType getWriteBarrierType(MM_EnvironmentBase* env) { MM_GCWriteBarrierType writeBarrierType = gc_modron_wrtbar_none; MM_GCExtensionsBase* extensions = env->getExtensions(); if (extensions->isScavengerEnabled()) { if (extensions->isConcurrentMarkEnabled()) { if (extensions->configurationOptions._forceOptionWriteBarrierSATB) { writeBarrierType = gc_modron_wrtbar_satb_and_oldcheck; } else { writeBarrierType = gc_modron_wrtbar_cardmark_and_oldcheck; } } else { writeBarrierType = gc_modron_wrtbar_oldcheck; } } else if (extensions->isConcurrentMarkEnabled()) { if (extensions->configurationOptions._forceOptionWriteBarrierSATB) { writeBarrierType = gc_modron_wrtbar_satb; } else { writeBarrierType = gc_modron_wrtbar_cardmark; } } return writeBarrierType; } }; #endif /* OMR_GC_MODRON_STANDARD */ #endif /* CONFIGURATIONSTANDARD_HPP_ */
37.130435
161
0.759016
4cee35fe07cf6e9ad82b67f12a5f7f5d9b1c31c4
7,544
py
Python
nmt/vocab.py
logan0czy/nlp-practice
3cdfcc45be95aec71a4f8225eaaa227ced545c70
[ "MIT" ]
null
null
null
nmt/vocab.py
logan0czy/nlp-practice
3cdfcc45be95aec71a4f8225eaaa227ced545c70
[ "MIT" ]
null
null
null
nmt/vocab.py
logan0czy/nlp-practice
3cdfcc45be95aec71a4f8225eaaa227ced545c70
[ "MIT" ]
null
null
null
"""NMT task reconstruct produced by: Zhiyu inspired by Stanford CS224n assignment4 """ import json from typing import List, Dict, Tuple from collections import Counter from itertools import chain import torch class VocabEntry(object): """construct source or target vocabulary. """ def __init__(self, word2id: Dict=None): if word2id: self.word2id = word2id else: self.word2id = {} self.word2id['<pad>'] = 0 self.word2id['<s>'] = 1 self.word2id['</s>'] = 2 self.word2id['<unk>'] = 3 self.pad_token = '<pad>' self.start_token = '<s>' self.end_token = '</s>' self.pad_id = self.word2id['<pad>'] self.start_id = self.word2id['<s>'] self.end_id = self.word2id['</s>'] self.unk_id = self.word2id['<unk>'] self.id2word = {v: k for k, v in self.word2id.items()} def __setitem__(self, word): """vocabulary can't set new items by indexing keys. """ raise ValueError("Vocabulary is only readable, if you want to set new k-v pair, use vocab.add()") def __getitem__(self, word: str): return self.word2id[word] def __contains__(self, word:str): return word in self.word2id def __len__(self): return len(self.word2id) def add(self, word: str): if word not in self: current_id = len(self) self.word2id[word] = current_id self.id2word[current_id] = word else: raise ValueError('warning: word [%s] to be added already exists, something might wrong'%word) def word_from_id(self, idx: int) -> str: """get corresponding word from id. :return word (str) """ try: word = self.id2word[idx] except: raise KeyError("invalid index to get corresponding word...") return word def get_pad_info(self, index): """return represent and index of vocabulary's pad token """ if index == 0: return self.pad_token elif index == 1: return self.pad_id else: raise ValueError("Wrong index for get pad token information......") def get_eos_info(self, index): if index == 0: return self.start_id elif index == 1: return self.end_id else: raise ValueError("Wrong index for get information......") def get_words(self): """get all of the words in VocabEntry. :return List[str] """ return [self.id2word[idx] for idx in range(len(self))] @staticmethod def build(corpus: List[List[str]], size=5000, freq_cutoff=5): """construct vocabulary from corpus. :param corpus list[list[str]]: list of sentences of one language :param size (int): vocabulary size :param freq_cutoff (int): ignore the words whose frequency is less than freq_cutoff :return vocab (VocabEntry): constructed vocabulary """ vocab = VocabEntry() word2freq = Counter(chain(*corpus)) word2freq = {word: freq for word, freq in word2freq.items() if freq > freq_cutoff} words_selected = sorted(word2freq.keys(), key=lambda w: word2freq[w], reverse=True)[:size] for w in words_selected: vocab.add(w) print("vocabulary constructing completed, %d/%d words included......" % (len(words_selected), len(word2freq))) return vocab def pad_sents(self, sents: List[List[int]], resource: str) -> List[List[int]]: """pad batch of sentences to its maximum length. :param sents (List[List[int]]): sentences to be padded :param resource (str): 'src' or 'tgt', source which sentences come from :return sents_padded (List[List[int]]): sentences padded, and is not arranged by decreasing length. :return sents_len (List[int]): length of each sentence, including <s>/</s> if exist """ assert resource in ['src', 'tgt'], "wrong resource choice, only 'src' or 'tgt'" max_length = max(len(s) for s in sents) if resource == 'tgt': max_length += 2 # sents = sorted(sents, key=lambda s: len(s), reverse=True) sents_padded = [] sents_len = [] for s in sents: if resource == 'tgt': s = [self.word2id['<s>']] + s + [self.word2id['</s>']] sents_len.append(len(s)) s_padded = s[:] + [self.pad_id]*(max_length-len(s)) sents_padded.append(s_padded) return sents_padded, sents_len def to_tensor(self, sents: List[List[str]], resource: str) -> torch.tensor: """transform sentences to tensor. :param sents (List[List[str]]): original sentences without padding :param resource (str): sentence come from, 'src' or 'tgt' :return sents_tensor (batch, max_sent_length): the sentences' each element is word's corresponding index :return sents_len (torch.tensor): length of each sentence """ sents_id = [] for s in sents: s_id = [self.word2id.get(word, self.unk_id) for word in s] sents_id.append(s_id) sents_id, sents_len = self.pad_sents(sents_id, resource) sents_tensor = torch.tensor(sents_id, dtype=torch.long) sents_len = torch.tensor(sents_len, dtype=torch.int) return sents_tensor, sents_len def to_sentences(self, sents_id: List[List[int]]) -> List[List[str]]: """transform id back to strings. """ sents = [] for s_id in sents_id: s = [] for w_id in s_id: s.append(self.word_from_id(w_id)) sents.append(s) return sents class Vocab(object): """absorb both src and tgt VocabEntry into a single class. """ def __init__(self, src: VocabEntry, tgt: VocabEntry): self.src = src self.tgt = tgt def __repr__(self): """Vocab entity representation. """ return "vocabulary: source -- %d words; target -- %d words" % (len(self.src), len(self.tgt)) def save(self, fpath='./vocab.json'): json.dump(dict(src_word2id=self.src.word2id, tgt_word2id=self.tgt.word2id), open(fpath, 'w'), indent=2) @staticmethod def load(fpath='./vocab.json'): entry = json.load(open(fpath, 'r')) src_word2id = entry['src_word2id'] tgt_word2id = entry['tgt_word2id'] return Vocab(VocabEntry(src_word2id), VocabEntry(tgt_word2id)) if __name__ == '__main__': print("sanity check for VocabEntry class......") sentences = ["I have a dream".split(), "I need to be faster".split(), "I need to be strong and healthy".split()] print("source sentence:") print(sentences) print("generate vocab 0 for cutoff 1...") vocab = VocabEntry.build(sentences, size=100, freq_cutoff=1) print(vocab.get_words()) print("generate vocab 1 for cutoff 0...") vocab = VocabEntry.build(sentences, size=100, freq_cutoff=0) print(vocab.get_words()) sents_tensor, sents_len = vocab.to_tensor(sentences, 'tgt') print("padded sents_tensor:\n", sents_tensor, "\nsize:", sents_tensor.size()) print("true length:", sents_len) print("transform back to original sentence......") print(vocab.to_sentences(sents_tensor.numpy()))
37.909548
118
0.591596
a622c505173ab990fdec8eae61517c29562cea09
1,379
lua
Lua
src/client/ui/common/UpdateAlert.lua
mystydev/Pioneers
7c4e43f5535818ee73beac782f7094c0d3251111
[ "MIT" ]
14
2019-07-05T13:23:33.000Z
2020-08-01T21:56:17.000Z
src/client/ui/common/UpdateAlert.lua
mystydev/Pioneers
7c4e43f5535818ee73beac782f7094c0d3251111
[ "MIT" ]
null
null
null
src/client/ui/common/UpdateAlert.lua
mystydev/Pioneers
7c4e43f5535818ee73beac782f7094c0d3251111
[ "MIT" ]
2
2019-09-11T12:23:57.000Z
2020-02-06T09:25:08.000Z
local Roact = require(game.ReplicatedStorage.Roact) local TweenService = game:GetService("TweenService") local UpdateAlert = Roact.Component:extend("UpdateAlert") local fade = TweenInfo.new(1, Enum.EasingStyle.Quint, Enum.EasingDirection.Out) function UpdateAlert:init() self.updateRef = Roact.createRef() self:setState({ updating = true, }) end function UpdateAlert:render() return Roact.createElement("ImageLabel", { Name = "UpdateAlert", BackgroundTransparency = 1, Position = UDim2.new(0, 20, 0, -50), Size = UDim2.new(0, 343, 0, 217), AnchorPoint = Vector2.new(0, 0), Image = self.state.updating and "rbxassetid://3606598190" or "rbxassetid://3606598062", [Roact.Ref] = self.updateRef, }) end function UpdateAlert:didMount() TweenService:Create(self.updateRef.current, fade, {Position = UDim2.new(0, 20, 0, 35)}):Play() self.running = true spawn(function() while self.running do self:setState(function(state) return { updating = self.props.updating:getValue() } end) wait(0.5) end end) end function UpdateAlert:willUnmount() self.running = false end return UpdateAlert
28.729167
112
0.591733
587be9dd6eb54172a048a19e86b60ee2847cb624
527
css
CSS
src/Styles/App.css
ferontv/boilerplate-react-redux-firebase
1c4751d0b6db4c3764938f3b3942a050798822a6
[ "MIT" ]
null
null
null
src/Styles/App.css
ferontv/boilerplate-react-redux-firebase
1c4751d0b6db4c3764938f3b3942a050798822a6
[ "MIT" ]
null
null
null
src/Styles/App.css
ferontv/boilerplate-react-redux-firebase
1c4751d0b6db4c3764938f3b3942a050798822a6
[ "MIT" ]
null
null
null
.footer-title { height: 100% !important; width: 15% !important; padding: 1rem 1rem !important; } .footer-button { height: 100% !important; width: 10% !important; padding: 1rem 1rem !important; border-radius: 0; background-color: #2D7DD2; color: whitesmoke; } .footer-body { height: 100% !important; width: 75% !important; padding: 1rem 1rem !important; } .post { margin-bottom: 1rem; margin-top: 1rem; } html { margin-bottom: 65px; } body { background-color: #474647; } form { width: 100%; }
15.969697
32
0.656546
a3110402224571cf2ec5a809dcae7ca17a024c7e
775
c
C
posixcat.c
csitd/posix-c-utils
8e663430efe105482b4f3bea2cbead5a437a95aa
[ "MIT" ]
null
null
null
posixcat.c
csitd/posix-c-utils
8e663430efe105482b4f3bea2cbead5a437a95aa
[ "MIT" ]
null
null
null
posixcat.c
csitd/posix-c-utils
8e663430efe105482b4f3bea2cbead5a437a95aa
[ "MIT" ]
null
null
null
#include <stdio.h> #include <fcntl.h> #include <unistd.h> /* C 2014, MIT license, "posixcat.c" csitd */ void concatenate(int, int); int main(int argc, char *argv[]) { int o, u; o = u = 0; while ((o = getopt (argc, argv, "u")) != -1) switch (o) { case 'u': u = 1; break; case '?': break; default: break; } argv += optind; argc -= optind; if ( argc == 0 ) concatenate(STDIN_FILENO, u); while (*argv) concatenate(open(*argv++, O_RDONLY), u); return 0; } void concatenate(int source, int u) { int n = 0; char buf[BUFSIZ]; if ( u != 1 ) u = BUFSIZ; while ((n = read(source, buf, u)) > 0) write(STDOUT_FILENO, buf, n); }
16.847826
52
0.486452
a7cdb64f0fdbc2b1eb4e74cda9bbc727d5e8bfc1
839
css
CSS
app/ViewItems/CSS/ReaderStrip.css
CSteinmuller/MangoBango
c0ee7dc1c7d8f53d934365f6482c13f13ce40889
[ "MIT" ]
13
2018-07-08T04:22:21.000Z
2022-02-12T07:20:27.000Z
app/ViewItems/CSS/ReaderStrip.css
CSteinmuller/MangoBango
c0ee7dc1c7d8f53d934365f6482c13f13ce40889
[ "MIT" ]
55
2018-04-07T16:52:28.000Z
2019-02-27T22:20:16.000Z
app/ViewItems/CSS/ReaderStrip.css
CSteinmuller/MangoBango
c0ee7dc1c7d8f53d934365f6482c13f13ce40889
[ "MIT" ]
1
2018-07-12T17:30:43.000Z
2018-07-12T17:30:43.000Z
/* Styling for ReaderStripView page view. */ .strip_wrap { margin: 0 auto; width: 1200px; max-width: 100%; background-color: #fff; box-shadow: 0 0 25px 20px rgba(0, 0, 0, 0.3); } .strip_wrap img { margin: 0 auto; max-width: 100%; display: block; } .strip_wrap .placeholder { height: 100vh; text-align: center; } .strip_wrap .placeholder::before { width: 0; height: 100%; display: inline-block; vertical-align: middle; content: ''; } .strip_wrap .placeholder img { display: inline-block; vertical-align: middle; } .strip_wrap .continue_btn { display: block; background-color: #d68100; } .strip_wrap .continue_btn:hover { background-color: #ffbb54; } .strip_wrap .continue_btn a { padding: 20px; display: block; color: #000; text-align: center; text-decoration: none; font-family: Arial; font-size: 2em; }
15.537037
46
0.690107
df6e5891e4d3fd247a350cba01bac4ccb6f25400
1,038
rb
Ruby
spec/controllers/main_controller_spec.rb
FDA/precisionFDA
96ea6494b58c08cd7fdbef12fd2922a4cca7a643
[ "CC0-1.0" ]
57
2016-01-15T21:29:49.000Z
2022-03-06T22:51:31.000Z
spec/controllers/main_controller_spec.rb
FDA/precisionFDA
96ea6494b58c08cd7fdbef12fd2922a4cca7a643
[ "CC0-1.0" ]
26
2019-09-10T15:14:25.000Z
2022-02-27T07:45:43.000Z
spec/controllers/main_controller_spec.rb
FDA/precisionFDA
96ea6494b58c08cd7fdbef12fd2922a4cca7a643
[ "CC0-1.0" ]
24
2016-03-18T05:57:26.000Z
2021-07-09T05:29:34.000Z
require "rails_helper" RSpec.describe MainController, type: :controller do let!(:user) { create(:user, dxuser: "test") } let!(:attachments) do [ create(:user_file), create(:asset), create(:app), ] end let!(:discussion) { create(:discussion, :with_attachments, user: user, attachments: attachments) } describe "POST publish" do before { authenticate!(user) } it "doesn't raise an exception" do post :publish, params: { id: discussion.uid, scope: "public" } end end describe "GET return_from_login" do it "doesn't flash an error" do get :return_from_login, params: { code: "123" } expect(flash[:error]).to be_falsey end context "when reached the limit of sessions" do before do SESSIONS_LIMIT.times do authenticate!(user) reset_session end end it "flashes an error" do get :return_from_login, params: { code: "123" } expect(flash[:error]).to be_present end end end end
23.590909
100
0.620424
8ecb533eb873890199e71affc55f093d2b68c286
2,344
js
JavaScript
src/utils/build.js
dengnan123/high-rollup
449c439ae52e8c52404e41e6bd0615d57c1d4f25
[ "MIT" ]
null
null
null
src/utils/build.js
dengnan123/high-rollup
449c439ae52e8c52404e41e6bd0615d57c1d4f25
[ "MIT" ]
null
null
null
src/utils/build.js
dengnan123/high-rollup
449c439ae52e8c52404e41e6bd0615d57c1d4f25
[ "MIT" ]
null
null
null
const fs = require("fs-extra") const path = require("path") const hasChildHash = { ECharts: 1, Material: 1, Table: 1, Target: 1, } function buildUmd(params) { let skipFiles = [] const outUmdFolderName = "umd-dist" const distPath = path.resolve(__dirname, `../${outUmdFolderName}`) if (fs.existsSync(distPath)) { skipFiles = fs.readdirSync(distPath) } const filePath = path.resolve(__dirname, "../src/libs") const files = fs.readdirSync(filePath).filter((v) => { if (v.includes("js") || v.includes(".DS_Store")) { return false } return true }) const pushPath = (pre, next, filePath) => { let arr = pre const libPath = `${filePath}/${next}/lib` const configPath = `${filePath}/${next}/config` const dataPath = `${filePath}/${next}/data.js` if (!skipFiles.includes(next)) { if (fs.existsSync(dataPath)) { arr = [ ...arr, { input: dataPath, output: { file: `${outUmdFolderName}/${next}/data.js`, name: `${next}Data`, }, modalKey: next, }, ] } if (fs.existsSync(libPath)) { arr = [ ...arr, { input: libPath, output: { file: `${outUmdFolderName}/${next}/lib.js`, name: `${next}Lib`, }, modalKey: next, }, ] } if (fs.existsSync(configPath)) { arr = [ ...arr, { input: configPath, output: { file: `${outUmdFolderName}/${next}/config.js`, name: `${next}Config`, }, modalKey: next, }, ] } } return arr } const inputAndOutputList = files.reduce((pre, next) => { if (hasChildHash[next]) { const baseFilePath = `${filePath}/${next}` const childFileNames = fs.readdirSync(baseFilePath).filter((v) => { if (v.includes("js") || v.includes(".DS_Store")) { return false } return true }) return childFileNames.reduce((pre, next) => { return pushPath(pre, next, baseFilePath) }, pre) } return pushPath(pre, next, filePath) }, []) return inputAndOutputList } module.exports = buildUmd
23.676768
73
0.503413
f329ec828b8ad78aa0aca3a3c493fb8952d94adb
535
kt
Kotlin
plugins/ksp/testData/api/errorTypes.kt
LaudateCorpus1/kotlin
74126637a097f5e6b099a7b7a4263468ecfda144
[ "ECL-2.0", "Apache-2.0" ]
337
2020-05-14T00:40:10.000Z
2022-02-16T23:39:07.000Z
plugins/ksp/testData/api/errorTypes.kt
yanghuadong-Mobile-Researcher/kotlin
74126637a097f5e6b099a7b7a4263468ecfda144
[ "ECL-2.0", "Apache-2.0" ]
92
2020-06-10T23:17:42.000Z
2020-09-25T10:50:13.000Z
plugins/ksp/testData/api/errorTypes.kt
yanghuadong-Mobile-Researcher/kotlin
74126637a097f5e6b099a7b7a4263468ecfda144
[ "ECL-2.0", "Apache-2.0" ]
44
2020-05-17T10:11:11.000Z
2022-03-11T02:37:20.000Z
// WITH_RUNTIME // TEST PROCESSOR: ErrorTypeProcessor // EXPECTED: // ERROR TYPE // kotlin.collections.Map // kotlin.String // ERROR TYPE // errorInComponent is assignable from errorAtTop: false // errorInComponent is assignable from class C: false // Any is assignable from errorInComponent: false // class C is assignable from errorInComponent: false // Any is assignable from class C: true // END // FILE: a.kt class C { val errorAtTop = mutableMapOf<String, NonExistType>() val errorInComponent: Map<String, NonExistType> }
29.722222
57
0.751402
212408b0d150c119c4d897853c99a37cfe3ed38f
8,202
swift
Swift
Flicks/MoviesViewController.swift
nishantnisonko/flicks
bb07160f0da6adad0456255e8950364cb560c2b0
[ "Apache-2.0" ]
null
null
null
Flicks/MoviesViewController.swift
nishantnisonko/flicks
bb07160f0da6adad0456255e8950364cb560c2b0
[ "Apache-2.0" ]
1
2017-04-03T15:13:34.000Z
2017-04-03T15:13:34.000Z
Flicks/MoviesViewController.swift
nishantnisonko/flicks
bb07160f0da6adad0456255e8950364cb560c2b0
[ "Apache-2.0" ]
null
null
null
// // MoviesViewController.swift // Flicks // // Created by Nishant nishanko on 3/30/17. // Copyright © 2017 Nishant nishanko. All rights reserved. // import UIKit import AFNetworking import MBProgressHUD class MoviesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate{ @IBOutlet weak var movieCollectinView: UICollectionView! @IBOutlet weak var moviesSegmentedControl: UISegmentedControl! @IBOutlet weak var errorView: UIView! @IBOutlet weak var tableView: UITableView! var movies: [NSDictionary]? var endPoint: String! func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{ if let movies = movies{ return movies.count }else{ return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{ let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MovieCollectionViewCell", for: indexPath) as! MovieCollectionViewCell let movie = movies![indexPath.row] let title = movie["title"] as! String let baseurl = "https://image.tmdb.org/t/p/w500" if let posterPath = movie["poster_path"] as? String{ let imageUrl = URL(string: baseurl+posterPath) cell.posterView.setImageWith(imageUrl!) } cell.titleView.text = title return cell; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let movies = movies{ return movies.count }else{ return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MovieCell", for: indexPath) as! MovieCell let movie = movies![indexPath.row] let title = movie["title"] as! String let overview = movie["overview"] as! String let baseurl = "https://image.tmdb.org/t/p/w500" if let posterPath = movie["poster_path"] as? String{ let imageUrl = URL(string: baseurl+posterPath) cell.posterView.setImageWith(imageUrl!) } cell.titleLabel.text = title cell.overviewLabel.text = overview // cell.overviewLabel.sizeToFit() return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated:true) } func moviesSegmentControl (_ moviesSegmentedControl: UISegmentedControl){ print(moviesSegmentedControl.selectedSegmentIndex) if( moviesSegmentedControl.selectedSegmentIndex == 0){ self.tableView.isHidden = false; self.movieCollectinView.isHidden = true; }else{ self.tableView.isHidden = true; self.movieCollectinView.isHidden = false; } } override func viewDidLoad() { super.viewDidLoad() print(moviesSegmentedControl.selectedSegmentIndex) tableView.dataSource = self tableView.delegate = self movieCollectinView.dataSource = self movieCollectinView.delegate = self errorView.isHidden = true if( moviesSegmentedControl.selectedSegmentIndex == 0){ self.tableView.isHidden = false; self.movieCollectinView.isHidden = true; }else{ self.tableView.isHidden = true; self.movieCollectinView.isHidden = false; } let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: #selector(refreshControlAction(_:)), for: UIControlEvents.valueChanged) moviesSegmentedControl.addTarget(self, action: #selector(moviesSegmentControl(_:)), for: UIControlEvents.valueChanged) tableView.insertSubview(refreshControl, at: 0) let urlString = "https://api.themoviedb.org/3/movie/"+endPoint+"?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed" let url = URL(string:urlString) let request = URLRequest(url: url!) let session = URLSession( configuration: URLSessionConfiguration.default, delegate:nil, delegateQueue:OperationQueue.main ) MBProgressHUD.showAdded(to: self.view, animated: true) let task : URLSessionDataTask = session.dataTask( with: request as URLRequest, completionHandler: { (data, response, error) in if (error != nil){ self.errorView.isHidden = false; self.tableView.isHidden = true; self.moviesSegmentedControl.isHidden = true; MBProgressHUD.hide(for: self.view, animated: true) }else{ let when = DispatchTime.now() + 1 // delay to simulate loading wait time to show loader DispatchQueue.main.asyncAfter(deadline: when) { if let data = data { if let responseDictionary = try! JSONSerialization.jsonObject( with: data, options:[]) as? NSDictionary { self.movies = responseDictionary["results"] as? [NSDictionary] self.tableView.reloadData() self.movieCollectinView.reloadData() MBProgressHUD.hide(for: self.view, animated: true) } } } } }); task.resume() // Do any additional setup after loading the view. } func refreshControlAction(_ refreshControl: UIRefreshControl){ let urlString = "https://api.themoviedb.org/3/movie/"+self.endPoint+"?api_key=a07e22bc18f5cb106bfe4cc1f83ad8ed" let url = URL(string:urlString) let request = URLRequest(url: url!) let session = URLSession( configuration: URLSessionConfiguration.default, delegate:nil, delegateQueue:OperationQueue.main ) let task : URLSessionDataTask = session.dataTask( with: request as URLRequest, completionHandler: { (data, response, error) in let when = DispatchTime.now() + 1 // delay to simulate loading wait time to show loader DispatchQueue.main.asyncAfter(deadline: when) { if let data = data { if let responseDictionary = try! JSONSerialization.jsonObject( with: data, options:[]) as? NSDictionary { self.movies = responseDictionary["results"] as? [NSDictionary] self.tableView.reloadData() refreshControl.endRefreshing() } } } }); task.resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { var indexPath: IndexPath! if moviesSegmentedControl.selectedSegmentIndex == 0 { let cell = sender as! UITableViewCell indexPath = tableView.indexPath(for: cell) } else { let cell = sender as! UICollectionViewCell indexPath = movieCollectinView.indexPath(for: cell) } let movie = movies?[(indexPath?.row)!] let destinationViewController = segue.destination as! DetailViewController destinationViewController.movie = movie } }
37.113122
145
0.586686
5861759ca6c302ae1dfb391d9c66db68ed31e982
3,593
css
CSS
static/css/estilo_suministro_productos.css
JanPol2000/bodyfit
5af625353e69f39cff19d0f0164e4e47b9ac07cd
[ "MIT" ]
null
null
null
static/css/estilo_suministro_productos.css
JanPol2000/bodyfit
5af625353e69f39cff19d0f0164e4e47b9ac07cd
[ "MIT" ]
17
2021-04-29T16:53:49.000Z
2021-05-26T01:04:10.000Z
static/css/estilo_suministro_productos.css
developer-s-eye/bodyfit
5af625353e69f39cff19d0f0164e4e47b9ac07cd
[ "MIT" ]
null
null
null
.form-register{ position: absolute; top: 15%; left: 0; right: 0; bottom: 0; margin: auto; width: 460px; height: fit-content; background: none; padding: 15px; border-radius: 2px; font-family: "bahnschrift"; color: whitesmoke; justify-content: center; align-items: center; box-shadow: 5px 10px 30px rgb(46, 46, 46); } .form-register h1{ font-size: 36px; margin-bottom: 20px; text-align: center; font-family: "amazon"; } .form-register h2{ font-size: 28px; margin-bottom: 5px; text-align: center; font-family: "amazon"; } .controls{ width: 99%; background: none; padding: 10px; border-radius: 4px; margin-bottom: 16px; border: 1px solid rgb(116, 0, 0); font-family: "bahnschrift"; color: whitesmoke; font-size: 18px; } .controls-a{ width: 48%; background: none; padding: 10px; border-radius: 4px; margin-bottom: 16px; border: 1px solid rgb(116, 0, 0); font-family: "bahnschrift"; color: whitesmoke; font-size: 18px; } .controls-b{ width: 48%; background: none; padding: 10px; border-radius: 4px; margin-bottom: 16px; margin-left: 5px; border: 1px solid rgb(116, 0, 0); font-family: "bahnschrift"; color: whitesmoke; font-size: 18px; } .form-register .boton{ width: 47%; outline: none; background: none; border-radius: 5px; border: 2px solid rgb(116, 0, 0); padding: 12px; color: whitesmoke; margin: 1%; cursor: pointer; transition: 0.5s; font-family: "bahnschrift"; font-size: 20px; } .radio { width: auto; display: flex; justify-content: center; align-items: center; margin: 3%; } .option { position: relative; width: 400px; height: 30px; padding: 10px; display: flex; align-items: center; } .option input { display: none; } .option label{ font-family: "bahnschrift"; font-size: 20px; cursor: pointer; margin-left: 17%; } .option label::after { content: ""; position: absolute; right: 85%; width: 19px; height: 19px; border: 2px solid rgb(116, 0, 0); border-radius: 50%; box-shadow: 0 0 3px rgba(0, 0, 0, 0.8); } .option label::before { content: ""; position: absolute; top: 47%; right: 87%; transform: translateY(-50%); width: 15px; height: 15px; background: rgb(116, 0, 0); border-radius: 50%; box-shadow: 0 0 3px rgba(0, 0, 0, 0.8); opacity: 0; transition: opacity 0.4s; } .option input:checked ~ label::before { opacity: 1; } caption { font-family: "amazon"; font-size: 25px; margin-bottom: 10px; } .tabla{ position: absolute; width: 410px; height: fit-content; background: none; padding: 15px; margin: 12% 70%; border-radius: 5px; font-family: "bahnschrift"; color: whitesmoke; box-shadow: 5px 10px 30px rgb(46, 46, 46); } .tabla table{ margin: auto; padding: 5px; background: none; border: 5px; font-family: "bahnschrift"; font-size: 18px; color:whitesmoke; width: 90%; } th, td { border: solid 1px rgb(116, 0, 0); padding: 10px; } .boton:hover{ content: ""; border-radius: 5px; background: rgb(116, 0, 0); text-transform: uppercase; } .fondo_izq img{ position: fixed; display: block; margin: 15% 0%; height: 60%; width: 35%; } .ropa img{ position: fixed; display: block; margin: 6% -5%; height: 88%; width: 30%; }
17.965
46
0.587253
c984cdd4509e5d229fc4cd9b5c1955cc10d2d200
322
ts
TypeScript
src/__tests__/app.spec.ts
urielscola/music-discovery-api
1bfe8d1a6974e9b2040945e7e8db7c4ac3c1847a
[ "MIT" ]
1
2020-10-29T17:04:32.000Z
2020-10-29T17:04:32.000Z
src/__tests__/app.spec.ts
urielscola/music-discovery-api
1bfe8d1a6974e9b2040945e7e8db7c4ac3c1847a
[ "MIT" ]
null
null
null
src/__tests__/app.spec.ts
urielscola/music-discovery-api
1bfe8d1a6974e9b2040945e7e8db7c4ac3c1847a
[ "MIT" ]
null
null
null
import request from 'supertest' import app from '../../src/app' describe('Route testing', () => { it('Should return an http 404 and a "message" property (route: GET /)', async () => { const res = await request(app).get('/') expect(res.status).toEqual(404) expect(res.body).toHaveProperty('message') }) })
29.272727
87
0.636646
bf399d0db7123d0af8429d01d052fe5478e73ee0
2,471
go
Go
utils.go
MiranaZJXLSQ/lrmf
ad87693f034652547cc8fbd38c449323aac3af84
[ "Apache-2.0" ]
null
null
null
utils.go
MiranaZJXLSQ/lrmf
ad87693f034652547cc8fbd38c449323aac3af84
[ "Apache-2.0" ]
null
null
null
utils.go
MiranaZJXLSQ/lrmf
ad87693f034652547cc8fbd38c449323aac3af84
[ "Apache-2.0" ]
null
null
null
package lrmf import ( "context" "encoding/json" "fmt" "strconv" "strings" "time" "github.com/coreos/etcd/clientv3" "github.com/pkg/errors" ) // 先干活,在进入周期运行 func doAndLoop(ctx context.Context, duration time.Duration, fn func(ctx context.Context) error, caller string) { var err error err = fn(ctx) if err != nil { Logger.Printf("%+v", err) } for { select { case <-ctx.Done(): Logger.Printf("%s exit", caller) return case <-time.After(duration): err = fn(ctx) if err != nil { Logger.Printf("%+v", err) } } } } type stateValue string func (v stateValue) StateAndLeaseID() (string, int64) { arr := strings.Split(string(v), "_") state := arr[0] leaseID, _ := strconv.ParseInt(arr[1], 10, 64) return state, leaseID } func (v stateValue) String() string { return string(v) } func formatStateValue(state string, leaseID clientv3.LeaseID) string { return fmt.Sprintf("%s_%d", state, leaseID) } // unit test type taskTest struct { K string `json:"k"` V string `json:"v"` } func (t *taskTest) Key(ctx context.Context) string { return t.K } func (t *taskTest) Value(ctx context.Context) string { return t.V } type testAssignmentParser struct{} func (p *testAssignmentParser) Unmarshal(ctx context.Context, assignment string) ([]Task, error) { var tasks []*taskTest if err := json.Unmarshal([]byte(assignment), &tasks); err != nil { return nil, errors.Wrapf(err, "FAILED to unmarshal assignment %s", assignment) } var r []Task for _, task := range tasks { r = append(r, task) } return r, nil } // unit test type testTaskProvider struct{} func (config *testTaskProvider) Tasks(ctx context.Context) ([]Task, error) { var tasks []Task task1 := &taskTest{K: "key1", V: "value1"} task2 := &taskTest{K: "key2", V: "value2"} task3 := &taskTest{K: "key3", V: "value3"} tasks = append(tasks, task1) tasks = append(tasks, task2) tasks = append(tasks, task3) return tasks, nil } func (config *testTaskProvider) Tenancy() string { return "default" } type testWorker struct { // 区分不同的instance InstanceId string } func (w *testWorker) Revoke(ctx context.Context, tasks []Task) error { for _, task := range tasks { Logger.Printf("instance %s revoke task %s", w.InstanceId, task.Key(ctx)) } return nil } func (w *testWorker) Assign(ctx context.Context, tasks []Task) error { for _, task := range tasks { Logger.Printf("instance %s assign task %s", w.InstanceId, task.Key(ctx)) } return nil }
20.254098
112
0.671388
eb3b685f4165a846c4aeeedab5d40641005a73c7
1,203
css
CSS
public/css/provider.css
letranhuudanh0030/doan-3-new
51ffd0baf676c0ee91d01f5904f242d17d7e201a
[ "MIT" ]
null
null
null
public/css/provider.css
letranhuudanh0030/doan-3-new
51ffd0baf676c0ee91d01f5904f242d17d7e201a
[ "MIT" ]
1
2022-02-19T03:59:00.000Z
2022-02-19T03:59:00.000Z
public/css/provider.css
letranhuudanh0030/doan3
ffd857e482b3e5eca1d7df88e3267422c97454c5
[ "MIT" ]
null
null
null
#hd-provider { /* the slides */ /* the parent */ } #hd-provider .nb-categories { box-shadow: 10px 10px 5px 0px rgba(183, 183, 183, 0.75); } #hd-provider .nb-categories .nb-category { padding: 1% 1.5%; display: inline-block; text-decoration: none; text-transform: uppercase; font-weight: bold; border-right: 1px solid #ccc; color: black; } #hd-provider .nb-categories .nb-category:hover { background: #0f5fb1; color: #ffffff; } #hd-provider .nb-categories .nb-category-title { padding: 1% 1.5%; display: inline-block; text-decoration: none; background: #0f5fb1; text-transform: uppercase; font-weight: bold; color: white; border-right: 1px solid #ccc; } #hd-provider .nb-categories .nb-category-title span { font-weight: bold; width: 30px; height: 30px; border: 1px solid; border-radius: 50%; margin-right: 15px; padding: 5px 10px; background: white; color: #0f5fb1; box-shadow: 0px 0px 10px 0px #fffcff; } @media (max-width: 767.98px) { #hd-provider .nb-categories .nb-category-title span { padding: 0px 4px; } } #hd-provider .slick-slide { margin: 0 15px; padding: 10px; } #hd-provider .slick-list { margin: 0 -15px; }
18.796875
58
0.66251
f433251eefbfa448489037c599fe45cd89e9ef6e
2,876
tsx
TypeScript
src/app/index.tsx
tracycollins/art47
b5ed624041a4389b99f0a3c411d0aa43e5395273
[ "MIT" ]
null
null
null
src/app/index.tsx
tracycollins/art47
b5ed624041a4389b99f0a3c411d0aa43e5395273
[ "MIT" ]
36
2021-04-16T15:25:38.000Z
2022-02-27T13:16:01.000Z
src/app/index.tsx
tracycollins/art47
b5ed624041a4389b99f0a3c411d0aa43e5395273
[ "MIT" ]
null
null
null
import React, { useEffect } from 'react'; import { useDispatch } from 'react-redux'; import { useUserSlice } from 'app/pages/UserPage/slice'; import { useArtworksSlice } from 'app/pages/ArtworksPage/slice'; import { Helmet } from 'react-helmet-async'; import { Switch, Route, BrowserRouter } from 'react-router-dom'; import { useAuth0 } from '@auth0/auth0-react'; import { GlobalStyle } from 'styles/global-styles'; import { ArtworksPage } from './pages/ArtworksPage/Loadable'; import { ArtistsPage } from './pages/ArtistsPage/Loadable'; import { UserPage } from './pages/UserPage/Loadable'; import { HomePage } from './pages/HomePage/Loadable'; import { InfoPage } from './pages/InfoPage/Loadable'; import { ThanksPage } from './pages/ThanksPage/Loadable'; import { StatsPage } from './pages/StatsPage/Loadable'; import { Header } from './components/Header'; import { NotFoundPage } from './components/NotFoundPage/Loadable'; import { useTranslation } from 'react-i18next'; export function App() { const dispatch = useDispatch(); const { i18n } = useTranslation(); const { actions } = useUserSlice(); const artworksActions = useArtworksSlice().actions; const { isLoading, user, isAuthenticated } = useAuth0(); useEffect(() => { console.log( `app | auth0` + ` | isLoading: ${isLoading}` + ` | isAuthenticated: ${isAuthenticated}` + ` | USER: ${user ? user.sub : 'UNDEFINED'}`, ); if (!isLoading) { dispatch(artworksActions.getArtworks()); if (isAuthenticated && user) { dispatch(actions.authenticatedUser(user)); } else { dispatch(actions.setUser(user)); } } // eslint-disable-next-line react-hooks/exhaustive-deps }, [isLoading, isAuthenticated]); return ( <BrowserRouter> <Helmet titleTemplate="%s - art 47" defaultTitle="art 47" htmlAttributes={{ lang: i18n.language }} > <meta name="description" content="art recommendation app" /> </Helmet> <Header /> <Switch> <Route path="/artists/:id" component={ArtistsPage} /> <Route path="/artists" component={ArtistsPage} /> <Route path="/artworks/:id" component={ArtworksPage} /> <Route path="/artworks" component={ArtworksPage} /> <Route path="/authorize" component={HomePage} /> <Route path="/login/callback" component={HomePage} /> <Route path="/login" component={HomePage} /> <Route path="/profile" component={UserPage} /> <Route path="/info" component={InfoPage} /> <Route path="/thanks" component={ThanksPage} /> <Route path="/stats" component={StatsPage} /> <Route path="/logout" /> <Route path="/" component={HomePage} /> <Route path="" component={NotFoundPage} /> </Switch> <GlobalStyle /> </BrowserRouter> ); }
36.405063
68
0.637344
fdc6351bc0a593e044fab8de5b5c8e3990232ddc
1,381
css
CSS
site/icons/style.css
lazd/covid19heat
6784f3660087c3df9c973d805e245f841a11611d
[ "BSD-2-Clause" ]
5
2020-03-02T04:02:30.000Z
2020-05-20T06:24:45.000Z
site/icons/style.css
lazd/covid19heat
6784f3660087c3df9c973d805e245f841a11611d
[ "BSD-2-Clause" ]
13
2020-03-01T23:57:00.000Z
2022-01-27T16:09:30.000Z
site/icons/style.css
lazd/covid19heat
6784f3660087c3df9c973d805e245f841a11611d
[ "BSD-2-Clause" ]
6
2020-03-02T04:02:31.000Z
2021-11-22T09:35:25.000Z
@font-face { font-family: 'icomoon'; src: url('fonts/icomoon.ttf?mvh2u') format('truetype'), url('fonts/icomoon.woff?mvh2u') format('woff'), url('fonts/icomoon.svg?mvh2u#icomoon') format('svg'); font-weight: normal; font-style: normal; font-display: block; } .gt_icon { /* use !important to prevent issues with browser extensions that change fonts */ font-family: 'icomoon' !important; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; /* Better Font Rendering =========== */ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .gt_icon--choropleth:before { content: "\e90c"; } .gt_icon--heatmap:before { content: "\e90d"; } .gt_icon--globe:before { content: "\e90a"; } .gt_icon--chevron-down:before { content: "\e908"; } .gt_icon--close:before { content: "\e90b"; } .gt_icon--search:before { content: "\e90e"; } .gt_icon--paper:before { content: "\e909"; } .gt_icon--list:before { content: "\e906"; } .gt_icon--cog:before { content: "\e907"; } .gt_icon--info:before { content: "\e901"; } .gt_icon--location:before { content: "\e902"; } .gt_icon--menu:before { content: "\e903"; } .gt_icon--pause:before { content: "\e904"; } .gt_icon--play:before { content: "\e905"; } .gt_icon--spinner:before { content: "\e900"; }
19.180556
82
0.645185
c6f65b9e07b7ff6559f5cbe3f6a12a8cdd142ab6
353
py
Python
tests/route_decorator/test_route_decorator.py
Bakhtiyar-Garashov/flake8-fastapi
81e774defcae377e77c1986ca780a922b27d2757
[ "MIT" ]
20
2021-06-01T20:53:46.000Z
2022-01-29T21:35:46.000Z
tests/route_decorator/test_route_decorator.py
Bakhtiyar-Garashov/flake8-fastapi
81e774defcae377e77c1986ca780a922b27d2757
[ "MIT" ]
13
2021-06-02T15:26:22.000Z
2021-07-25T13:27:59.000Z
tests/route_decorator/test_route_decorator.py
Bakhtiyar-Garashov/flake8-fastapi
81e774defcae377e77c1986ca780a922b27d2757
[ "MIT" ]
3
2021-06-01T21:16:58.000Z
2022-01-29T21:39:29.000Z
from flake8_plugin_utils import assert_error, assert_not_error from flake8_fastapi.errors import RouteDecoratorError from flake8_fastapi.visitors import RouteDecorator def test_code_with_error(code: str): assert_error(RouteDecorator, code, RouteDecoratorError) def test_code_without_error(code: str): assert_not_error(RouteDecorator, code)
27.153846
62
0.844193