hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
sequencelengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
sequencelengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
sequencelengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
06e10dbcb81ebd9d673434ada2234174489a5f89 | 1,704 | py | Python | src/hammer-vlsi/hammer_vlsi/hooks.py | XiaoSanchez/hammer | 87a2ee26b0912df39973a35632970a47a31ca22a | [
"BSD-3-Clause"
] | 138 | 2017-08-15T18:56:55.000Z | 2022-03-29T05:23:37.000Z | src/hammer-vlsi/hammer_vlsi/hooks.py | XiaoSanchez/hammer | 87a2ee26b0912df39973a35632970a47a31ca22a | [
"BSD-3-Clause"
] | 444 | 2017-09-11T01:15:37.000Z | 2022-03-31T17:30:33.000Z | src/hammer-vlsi/hammer_vlsi/hooks.py | XiaoSanchez/hammer | 87a2ee26b0912df39973a35632970a47a31ca22a | [
"BSD-3-Clause"
] | 33 | 2017-10-30T14:23:53.000Z | 2022-03-25T01:36:13.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# hooks.py
# Classes and functions related to Hammer hooks.
#
# See LICENSE for licence details.
from enum import Enum
from typing import Callable, NamedTuple, Optional, TYPE_CHECKING
__all__ = ['HammerStepFunction', 'HammerToolStep', 'HookLocation', 'HammerToolHookAction']
# Necessary for mypy to learn about HammerTool.
if TYPE_CHECKING:
from .hammer_tool import HammerTool # pylint: disable=unused-import
HammerStepFunction = Callable[['HammerTool'], bool]
HammerToolStep = NamedTuple('HammerToolStep', [
# Function to call to execute this step
('func', HammerStepFunction),
# Name of the step
('name', str)
])
# Specify step to start/stop
HammerStartStopStep = NamedTuple('HammerStartStopStep', [
# Name of the step
('step', Optional[str]),
# Whether it is inclusive
('inclusive', bool)
])
# Where to insert/replace the given step.
# Persistent steps always execute depending on from/after/to/until steps.
class HookLocation(Enum):
InsertPreStep = 1
InsertPostStep = 2
ReplaceStep = 10
ResumePreStep = 20
ResumePostStep = 21
PausePreStep = 30
PausePostStep = 31
PersistentStep = 40
PersistentPreStep = 41
PersistentPostStep = 42
# An hook action. Actions can insert new steps before or after an existing one,
# or replace an existing stage.
# Note: hook actions are executed in the order provided.
HammerToolHookAction = NamedTuple('HammerToolHookAction', [
# Where/what to do
('location', HookLocation),
# Target step to insert before/after or replace
('target_name', str),
# Step to insert/replace
('step', Optional[HammerToolStep])
])
| 28.4 | 90 | 0.712441 |
38c77c50e005d9b42db6360162f8524a39c3d1e4 | 769 | php | PHP | app/Modules/Dashboards/Controllers/DashboardsController.php | alissonphp/rent-clothes-api | d337776e0362a14463a05282a7b6f4f8581cbe5d | [
"MIT"
] | 3 | 2018-01-10T11:21:16.000Z | 2020-06-19T12:31:54.000Z | app/Modules/Dashboards/Controllers/DashboardsController.php | alissonphp/rent-clothes-api | d337776e0362a14463a05282a7b6f4f8581cbe5d | [
"MIT"
] | null | null | null | app/Modules/Dashboards/Controllers/DashboardsController.php | alissonphp/rent-clothes-api | d337776e0362a14463a05282a7b6f4f8581cbe5d | [
"MIT"
] | null | null | null | <?php
namespace App\Modules\Dashboards\Controllers;
use App\Modules\Clients\Models\Client;
use App\Modules\Items\Models\Item;
use App\Modules\Orders\Models\Order;
class DashboardsController
{
public function admin()
{
try {
$items = Item::all()->count();
$clients = Client::all()->count();
$orders = Order::all()->count();
$cancels = Order::where('status','Cancelada')->count();
return response([
'items' => $items,
'clients' => $clients,
'orders' => $orders,
'cancels' => $cancels
],200);
} catch (\Exception $ex) {
return response(['error' => $ex->getMessage()], 500);
}
}
} | 22.617647 | 67 | 0.508453 |
423aca60be104a6174ba747c451d8e6182caaae3 | 5,229 | ps1 | PowerShell | Full_Scripts/Run-PS1Script/Run-PS1Script.ps1 | JayDeuce/POSH_Script_Work | 6babb45ecca8d7bf3b84f021706c647643e7ea18 | [
"MIT"
] | 1 | 2019-02-12T13:56:59.000Z | 2019-02-12T13:56:59.000Z | Full_Scripts/Run-PS1Script/Run-PS1Script.ps1 | JayDeuce/POSH_Script_Work | 6babb45ecca8d7bf3b84f021706c647643e7ea18 | [
"MIT"
] | null | null | null | Full_Scripts/Run-PS1Script/Run-PS1Script.ps1 | JayDeuce/POSH_Script_Work | 6babb45ecca8d7bf3b84f021706c647643e7ea18 | [
"MIT"
] | null | null | null | <#
.SYNOPSIS
Pushes and runs script on listed machines useing PSExec remote administration tool.
.DESCRIPTION
Using passed parameters for the Computer name and and script Name; this script
will copy the script to the designated Computer or Computers, run the script,
and return the exit/error code of the powershell.exe command.
!! THIS SCRIPT MUST BE RUN WITH ADMINISTRATOR RIGHTS !!
.PARAMETER computers
(Required, No Default)
This parameter is the active directory/workstation name or IP Address of the Computer that will receive the script. This designation
can be a single Computer name, IP Address, or a function to read in a listing of Computers names, such as
EX: "Workstation1"
"192.168.1.24"
"(Get-Content "Computers.txt")" //File is located in same directory as the script//
"(Get-Content "C:\Temp\List\Computers.txt")"
.PARAMETER scriptName
(Required, No Default)
This parameter is the Name of the script file you wish to push, including the file extension. To ensure
filename is read correctly due to spaces in the names, wrap the name in quotation marks.
EX: "ScriptToRun.ps1"
.PARAMETER scriptPath
(Not Required, Defaulted)
This parameter is the directory location of the script file, exlcuding the filename and extension. (Just the file path
up to the folder the file is located in.) This parameter is defaulted to the standard DAHC sys admin folder for
scripts to run. No entry is required unless you are loading an update from a seperate folder location
than the default.
Default Path: "C:\Scripts"
.PARAMETER psexecFilePath
(Not Required, Defaulted)
This parameter is the directory location of the PSExec.exe file, exlcuding the filename and extension. (Just the file path
up to the folder the file is located in.) This parameter is defaulted to the standard DAHC sys admin folder for
the PSExec.exe file. No entry is required unless you are loading the PSExec.exe file from a seperate folder location
than the default.
Default Path: "C:\Scripts\PSExec.exe"
.EXAMPLE
.\Run-PS1Script.ps1 -computers Workstation1 -scriptName "ScriptToRun.ps1"
Description:
Runs the script "ScriptToRun.ps1" on the computer named "Workstation1"
.EXAMPLE
.\Run-PS1Script.ps1 -computers 192.168.112.125 -scriptName "ScriptToRun.ps1"
Description:
Runs the script "ScriptToRun.ps1" on the computer with IP "192.168.112.125"
.EXAMPLE
.\Run-PS1Script.ps1 -computers (Get-Content "Computers.txt") -scriptName "ScriptToRun.ps1"
Description:
Using the powershell cmdlet "Get-Content" this example is reading a list of computers
from the "computers.txt" file located in the current folder and loading them into a
Powershell Object Array for processing. The script will then cycle through each object
and run the "ScriptToRun.ps1" script on each one.
.EXAMPLE
.\Run-PS1Script.ps1 -computers (Get-Content "c:\temp\computers.txt") -scriptName "ScriptToRun.ps1" -scriptPath "c:\scripts\ms\windows\version\7" -psexecFilePath "c:\psexecfolder"
Description:
Using the powershell cmdlet "Get-Content" this example is reading a list of computers
from the "computers.txt" file located in the c:\temp folder and loading them into a
Powershell Object Array for processing. This will use the script located in the
c:\scripts\ms\windows\version\7 folder, and use the PSExec.exe
file located in the c:\psexecfolder Folder.
.NOTES
Name: Run-PS1Script.ps1
Author: Jonathan Durant
Version: 1.0
DateUpdated: 2016-04-20
.INPUTS
Computer names, Script Names, file paths
.OUTPUTS
Error/Exit codes to show completion status.
#>
[cmdletbinding()]
Param (
[Parameter(mandatory = $true, Position = 0)]
[array]$computers = "",
[Parameter(mandatory = $true, Position = 1)]
[string]$scriptName = "",
[Parameter(mandatory = $false, Position = 2)]
[string]$scriptPath = "C:\ScriptsToRun",
[Parameter(mandatory = $false, Position = 3)]
[String]$psexecFilePath = "C:\Scripts\PSExec.exe"
)
process {
foreach ($computer in $computers) {
Write-Host "`nProcessing $computer..."
if (!(test-connection -count 1 -Quiet -ComputerName $computer)) {
Write-Host "`n$computer could not be contacted, please check make sure its online. Moving on...`n"
Write-Host "+++++++++++++++++++"
}
else {
if (!(Test-Path -Path "\\$computer\c$\Temp")) {
new-item -Path "\\$computer\c$\Temp" -ItemType directory | Out-Null
}
Copy-Item $scriptPath\$scriptName "\\$computer\c$\Temp"
& $psexecFilepath -s \\$computer powershell.exe -noprofile -command "C:\Temp\$scriptName"
}
# Delete local copy of update package
Remove-Item "\\$computer\c$\Temp\$scriptName"
Write-Host "`n$computer Complete, Check error code file for explanation of results...`n"
Write-Host "+++++++++++++++++++"
}
} | 40.534884 | 183 | 0.674699 |
05cb412874d2f82a5f9e4db9636e8edff4a47c4f | 1,527 | py | Python | graphexporter.py | YoongiKim/Rider-PPO | fd7f44288293f600972a9d039967ee84e0e692c0 | [
"MIT"
] | 14 | 2018-04-11T14:37:49.000Z | 2020-04-12T06:15:56.000Z | graphexporter.py | YoongiKim/Rider-PPO | fd7f44288293f600972a9d039967ee84e0e692c0 | [
"MIT"
] | null | null | null | graphexporter.py | YoongiKim/Rider-PPO | fd7f44288293f600972a9d039967ee84e0e692c0 | [
"MIT"
] | 4 | 2018-04-11T15:10:15.000Z | 2019-08-03T00:06:10.000Z | import csv
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
import scipy.signal
import matplotlib
plt.style.use('dark_background')
# with open('csv/run_PPO_summary-tag-Info_cumulative_reward.csv', newline='') as csvfile:
with open('csv/run_PPO_summary-tag-Info_episode_length.csv', newline='') as csvfile:
# with open('csv/run_PPO_summary-tag-Info_value_loss.csv', newline='') as csvfile:
# with open('csv/run_PPO_summary-tag-Info_policy_loss.csv', newline='') as csvfile:
csvreader = csv.reader(csvfile)
csvlist = np.array(list(csvreader))
steplist = csvlist[1:, 1].astype(np.int32)
datalist = csvlist[1:, 2].astype(np.float) * 6
datalist = scipy.signal.medfilt(datalist, kernel_size=15)
fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], animated=True)
plt.xlabel('timesteps')
plt.ylabel('frames') # <-----
plt.title('episode length') # <-----
def init():
ax.set_ylim(0, 700) # <-----
ax.set_xlim(0, 15e6)
return ln,
def update(i):
j = int(i / 10)
delta = (i % 10) / 10
print(i, j)
xdata.append(steplist[j] + delta * (steplist[j + 1] - steplist[j]))
ydata.append(datalist[j] + delta * (datalist[j + 1] - datalist[j]))
ln.set_data(xdata, ydata)
return ln,
ani = FuncAnimation(fig, update, repeat=False, frames=(len(steplist) - 1) * 10,
init_func=init, blit=True, interval=1 / 60 * 1000)
ani.save('episode_length.mp4', dpi=120, writer='ffmpeg') # <-----
# plt.show()
| 29.941176 | 89 | 0.662737 |
e753e294f4e5f9c1dd7ea35ea28585713132305b | 10,439 | php | PHP | src/table/Column.php | krepver/yii2-migration | 66c6271fb6c7d3440cd11dd7c6ff87f768534d81 | [
"Apache-2.0"
] | 1 | 2020-05-27T18:33:23.000Z | 2020-05-27T18:33:23.000Z | src/table/Column.php | krepver/yii2-migration | 66c6271fb6c7d3440cd11dd7c6ff87f768534d81 | [
"Apache-2.0"
] | null | null | null | src/table/Column.php | krepver/yii2-migration | 66c6271fb6c7d3440cd11dd7c6ff87f768534d81 | [
"Apache-2.0"
] | null | null | null | <?php
declare(strict_types=1);
namespace bizley\migration\table;
use bizley\migration\Schema;
use function in_array;
use function preg_replace;
use function str_ireplace;
use function str_replace;
use function stripos;
use function trim;
abstract class Column
{
/** @var string */
private $name;
/** @var string */
private $type;
/** @var bool|null */
private $notNull;
/** @var int|string|null */
private $size;
/** @var int|string|null */
private $precision;
/** @var int|string|null */
private $scale;
/** @var bool */
private $unique = false;
/** @var bool */
private $unsigned = false;
/** @var mixed */
private $default;
/** @var bool */
private $primaryKey = false;
/** @var bool */
private $autoIncrement = false;
/** @var string|null */
private $append;
/** @var string|null */
private $comment;
/** @var string|null */
private $after;
/** @var bool */
private $first = false;
/**
* Returns name of the column.
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* Sets name for the column.
* @param string $name
*/
public function setName(string $name): void
{
$this->name = $name;
}
/**
* Returns type of the column.
* @return string
*/
public function getType(): string
{
return $this->type;
}
/**
* Sets type for the column.
* @param string $type
*/
public function setType(string $type): void
{
$this->type = $type;
}
/**
* Checks whether the column can not be null.
* @return bool|null
*/
public function isNotNull(): ?bool
{
return $this->notNull;
}
/**
* Sets the column to not be null.
* @param bool|null $notNull
*/
public function setNotNull(?bool $notNull): void
{
$this->notNull = $notNull;
}
/**
* Returns size of the column.
* @return int|string|null
*/
public function getSize()
{
return $this->size;
}
/**
* Sets size for the column.
* @param int|string|null $size
*/
public function setSize($size): void
{
$this->size = $size;
}
/**
* Returns precision of the column.
* @return int|string|null
*/
public function getPrecision()
{
return $this->precision;
}
/**
* Sets precision for the column.
* @param int|string|null $precision
*/
public function setPrecision($precision): void
{
$this->precision = $precision;
}
/**
* Returns scale of the column.
* @return int|string|null
*/
public function getScale()
{
return $this->scale;
}
/**
* Sets scale for the column.
* @param int|string|null $scale
*/
public function setScale($scale): void
{
$this->scale = $scale;
}
/**
* Checks whether the column is unique.
* @return bool
*/
public function isUnique(): bool
{
return $this->unique;
}
/**
* Sets the uniqueness of the column.
* @param bool $unique
*/
public function setUnique(bool $unique): void
{
$this->unique = $unique;
}
/**
* Checks whether the column is unsigned.
* @return bool
*/
public function isUnsigned(): bool
{
return $this->unsigned;
}
/**
* Sets the unsigned flag for the column.
* @param bool $unsigned
*/
public function setUnsigned(bool $unsigned): void
{
$this->unsigned = $unsigned;
}
/**
* Returns default value of the column.
* @return mixed
*/
public function getDefault()
{
return $this->default;
}
/**
* Sets default value for the column.
* @param mixed $default
*/
public function setDefault($default): void
{
$this->default = $default;
}
/**
* Checks whether the column is a primary key.
* @return bool
*/
public function isPrimaryKey(): bool
{
return $this->primaryKey;
}
/**
* Sets the primary key flag for the column.
* @param bool|null $primaryKey
*/
public function setPrimaryKey(?bool $primaryKey): void
{
$this->primaryKey = (bool)$primaryKey;
}
/**
* Checks whether the column has autoincrement flag.
* @return bool
*/
public function isAutoIncrement(): bool
{
return $this->autoIncrement;
}
/**
* Sets the autoincrement flag for the column.
* @param bool $autoIncrement
*/
public function setAutoIncrement(bool $autoIncrement): void
{
$this->autoIncrement = $autoIncrement;
}
/**
* Returns the value of append statement of the column.
* @return string|null
*/
public function getAppend(): ?string
{
return $this->append;
}
/**
* Sets the value for append statement for the column.
* @param string|null $append
*/
public function setAppend(?string $append): void
{
$this->append = $append;
}
/**
* Returns the value for comment statement for the column.
* @return string|null
*/
public function getComment(): ?string
{
return $this->comment;
}
/**
* Sets the value for comment statement for the column.
* @param string|null $comment
*/
public function setComment(?string $comment): void
{
$this->comment = $comment;
}
/**
* Returns the value for after statement for the column.
* @return string|null
*/
public function getAfter(): ?string
{
return $this->after;
}
/**
* Sets the value for after statement for the column.
* @param string|null $after
*/
public function setAfter(?string $after): void
{
$this->after = $after;
}
/**
* Checks whether the column has first statement.
* @return bool
*/
public function isFirst(): bool
{
return $this->first;
}
/**
* Sets the column for the first statement.
* @param bool $first
*/
public function setFirst(bool $first): void
{
$this->first = $first;
}
/**
* Checks if column is a part of the primary key.
* @param PrimaryKeyInterface $primaryKey
* @return bool
*/
public function isColumnInPrimaryKey(PrimaryKeyInterface $primaryKey): bool
{
return in_array($this->name, $primaryKey->getColumns(), true);
}
/**
* Checks if information of primary key is set in append statement.
* @param string|null $schema
* @return bool
*/
public function isPrimaryKeyInfoAppended(?string $schema): bool
{
$append = $this->getAppend();
if (empty($append)) {
return false;
}
if (stripos($append, 'PRIMARY KEY') !== false) {
return !($schema === Schema::MSSQL && stripos($append, 'IDENTITY') === false);
}
return false;
}
/**
* Prepares append statement based on the schema.
* @param bool $primaryKey whether the column is primary key
* @param bool $autoIncrement whether the column has autoincrement flag
* @param string|null $schema
* @return string|null
*/
public function prepareSchemaAppend(bool $primaryKey, bool $autoIncrement, string $schema = null): ?string
{
switch ($schema) {
case Schema::MSSQL:
$append = $primaryKey ? 'IDENTITY PRIMARY KEY' : '';
break;
case Schema::OCI:
case Schema::PGSQL:
$append = $primaryKey ? 'PRIMARY KEY' : '';
break;
case Schema::SQLITE:
$append = trim(($primaryKey ? 'PRIMARY KEY ' : '') . ($autoIncrement ? 'AUTOINCREMENT' : ''));
break;
case Schema::CUBRID:
case Schema::MYSQL:
default:
$append = trim(($autoIncrement ? 'AUTO_INCREMENT ' : '') . ($primaryKey ? 'PRIMARY KEY' : ''));
}
return empty($append) ? null : $append;
}
/**
* Escapes single quotes.
* @param string $value
* @return string
*/
public function escapeQuotes(string $value): string
{
return str_replace('\'', '\\\'', $value);
}
/**
* Removes information of primary key in append statement and returns what is left.
* @param string|null $schema
* @return null|string
*/
public function removeAppendedPrimaryKeyInfo(?string $schema): ?string
{
if ($this->append === null || $this->isPrimaryKeyInfoAppended($schema) === false) {
return $this->append;
}
switch ($schema) {
case Schema::MSSQL:
$cleanedAppend = str_ireplace(['PRIMARY KEY', 'IDENTITY'], '', $this->append);
break;
case Schema::OCI:
case Schema::PGSQL:
$cleanedAppend = str_ireplace('PRIMARY KEY', '', $this->append);
break;
case Schema::SQLITE:
$cleanedAppend = str_ireplace(['PRIMARY KEY', 'AUTOINCREMENT'], '', $this->append);
break;
case Schema::CUBRID:
case Schema::MYSQL:
default:
$cleanedAppend = str_ireplace(['PRIMARY KEY', 'AUTO_INCREMENT'], '', $this->append);
}
$cleanedAppend = preg_replace('/\s+/', ' ', $cleanedAppend);
if ($cleanedAppend !== null) {
$cleanedAppend = trim($cleanedAppend);
}
return !empty($cleanedAppend) ? $cleanedAppend : null;
}
/**
* Returns length of the column.
* @param string|null $schema
* @param string|null $engineVersion
* @return string|int|null
*/
abstract public function getLength(string $schema = null, string $engineVersion = null);
/**
* Sets length for the column.
* @param string|int|array<string|int>|null $value
* @param string|null $schema
* @param string|null $engineVersion
*/
abstract public function setLength($value, string $schema = null, string $engineVersion = null): void;
}
| 22.742919 | 111 | 0.550053 |
b71cf5aa3a1ad13edd2b94907a242590f5330a84 | 12,318 | cs | C# | OperationManager/Controllers/ADController.cs | buyongfeng521/SmallBelief | f4ed4859aa98c372b9a72bb7ec2e3007fc352248 | [
"MIT"
] | 1 | 2017-04-03T08:57:57.000Z | 2017-04-03T08:57:57.000Z | OperationManager/Controllers/ADController.cs | buyongfeng521/SmallBelief | f4ed4859aa98c372b9a72bb7ec2e3007fc352248 | [
"MIT"
] | null | null | null | OperationManager/Controllers/ADController.cs | buyongfeng521/SmallBelief | f4ed4859aa98c372b9a72bb7ec2e3007fc352248 | [
"MIT"
] | null | null | null | using HelperCommon;
using Model;
using Model.CommonModel;
using Model.FormatModel;
using OperationManager.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace OperationManager.Controllers
{
[LoginCheck]
public class ADController : Controller
{
public ActionResult ADList(string keywords = "")
{
List<t_ad> listAD = OperateContext.EFBLLSession.t_adBLL.GetListBy(a => a.ad_name.Contains(keywords), a => a.sort);
ViewBag.Keywords = keywords;
return View(listAD);
}
[HttpGet]
public ActionResult ADAdd()
{
ViewBag.ListADType = SelectHelper.GetEnumSelectListItem(Enums.ADType.首页广告);
//ViewBag.ListClickType = SelectHelper.GetEnumSelectListItem(Enums.ClickType.不可点击);
//ViewBag.ListCat = SelectHelper.GetCategorySelList();
return View();
}
[HttpPost]
public ActionResult ADAdd(string ad_name, int ad_type, HttpPostedFileBase ad_img, int sort = 0, int click_type = 0, string hideClickValue = "")
{
AjaxMsg ajax = new AjaxMsg();
//1.0 check
if (string.IsNullOrWhiteSpace(ad_name))
{
ajax.Msg = "广告名称不能为空";
return Json(ajax);
}
if (ad_img == null)
{
ajax.Msg = "广告图片不能为空";
return Json(ajax);
}
if (OperateContext.EFBLLSession.t_adBLL.GetCountBy(a => a.ad_name == ad_name.Trim()) > 0)
{
ajax.Msg = "已存在的广告名称";
return Json(ajax);
}
//2.0 do
string strImg = UploadHelper.UploadImage(ad_img);
if(string.IsNullOrEmpty(strImg))
{
ajax.Msg = CommonBasicMsg.UploadImgFail;
return Json(ajax);
}
t_ad addModel = new t_ad()
{
ad_name = ad_name.Trim(),
ad_type = (byte)ad_type,
ad_img = strImg,
click_type = (byte)click_type,
click_value = hideClickValue,
sort = (byte)sort
};
if (OperateContext.EFBLLSession.t_adBLL.Add(addModel))
{
ajax.Msg = CommonBasicMsg.AddSuc;
ajax.Status = "ok";
}
else
{
ajax.Msg = CommonBasicMsg.AddFail;
}
return Json(ajax);
}
[HttpGet]
public ActionResult ADEdit(int? id)
{
if (id != null)
{
t_ad editModel = OperateContext.EFBLLSession.t_adBLL.GetModelBy(a=>a.ad_id == id);
if (editModel != null)
{
ViewBag.ListADType = SelectHelper.GetEnumSelectListItem(Enums.ADType.首页广告, editModel.ad_type.ToString());
//ViewBag.ListClickType = SelectHelper.GetEnumSelectListItem(Enums.ClickType.不可点击,editModel.click_type.ToString());
//ViewBag.ListCat = SelectHelper.GetCategorySelList();
return View(editModel);
}
}
return Redirect("ADList");
}
[HttpPost]
public ActionResult ADEdit(int? ad_id, string ad_name, int ad_type, HttpPostedFileBase ad_img, int sort = 0, int click_type = 0, string hideClickValue = "")
{
AjaxMsg ajax = new AjaxMsg();
//1.0 check
if (ad_id == null)
{
ajax.Msg = CommonBasicMsg.VoidID;
return Json(ajax);
}
t_ad editModel = OperateContext.EFBLLSession.t_adBLL.GetModelBy(a=>a.ad_id == ad_id);
if (editModel == null)
{
ajax.Msg = CommonBasicMsg.VoidModel;
return Json(ajax);
}
if (string.IsNullOrWhiteSpace(ad_name))
{
ajax.Msg = "广告名称不能为空";
return Json(ajax);
}
if (OperateContext.EFBLLSession.t_adBLL.GetCountBy(a =>a.ad_id != ad_id && a.ad_name == ad_name.Trim()) > 0)
{
ajax.Msg = "已存在的广告名称";
return Json(ajax);
}
//2.0 do
string strImg = "";
if (ad_img != null)
{
strImg = UploadHelper.UploadImage(ad_img);
}
editModel.ad_name = ad_name.Trim();
editModel.ad_type = (byte)ad_type;
editModel.click_type = (byte)click_type;
editModel.click_value = hideClickValue;
if (!string.IsNullOrEmpty(strImg))
{
editModel.ad_img = strImg;
}
if (OperateContext.EFBLLSession.t_adBLL.Modify(editModel))
{
ajax.Msg = CommonBasicMsg.EditSuc;
ajax.Status = "ok";
}
else
{
ajax.Msg = CommonBasicMsg.EditFail;
}
return Json(ajax);
}
[HttpPost]
public ActionResult ADDel(int? id)
{
AjaxMsg ajax = new AjaxMsg();
if (id != null)
{
if (OperateContext.EFBLLSession.t_adBLL.GetCountBy(a => a.ad_id == id) > 0)
{
if (OperateContext.EFBLLSession.t_adBLL.DeleteBy(a => a.ad_id == id))
{
ajax.Msg = CommonBasicMsg.DelSuc;
ajax.Status = "ok";
}
else
{
ajax.Msg = CommonBasicMsg.DelFail;
}
}
}
return Json(ajax);
}
#region Banner
[HttpGet]
public ActionResult BannerList(string keywords = "")
{
List<t_banner> listBanner = OperateContext.EFBLLSession.t_bannerBLL.GetListBy(b => b.banner_name.Contains(keywords), b => b.banner_type);
ViewBag.Keywords = keywords;
return View(listBanner);
}
[HttpGet]
public ActionResult BannerAdd()
{
ViewBag.ListBannerType = SelectHelper.GetEnumSelectListItem(Enums.BannerType.首页Banner);
//ViewBag.ListClickType = SelectHelper.GetEnumSelectListItem(Enums.ClickType.不可点击);
//ViewBag.ListCat = SelectHelper.GetCategorySelList();
return View();
}
[HttpPost]
public ActionResult BannerAdd(string banner_name, int banner_type, HttpPostedFileBase banner_img,int sort = 0, int click_type = 0, string hideClickValue = "")
{
AjaxMsg ajax = new AjaxMsg();
//1.0 check
if (string.IsNullOrWhiteSpace(banner_name))
{
ajax.Msg = "Banner名称不能为空";
return Json(ajax);
}
if (OperateContext.EFBLLSession.t_bannerBLL.GetCountBy(b => b.banner_name == banner_name.Trim()) > 0)
{
ajax.Msg = "Banner名称已存在";
return Json(ajax);
}
if (banner_img == null)
{
ajax.Msg = "Banner图片不能为空";
return Json(ajax);
}
//2.0 do
string strImg = UploadHelper.UploadImage(banner_img);
if (string.IsNullOrEmpty(strImg))
{
ajax.Msg = CommonBasicMsg.UploadImgFail;
return Json(ajax);
}
t_banner addModel = new t_banner()
{
banner_name = banner_name.Trim(),
banner_type = (byte)banner_type,
banner_img = strImg,
click_type = (byte)click_type,
click_value = hideClickValue,
sort = (byte)sort
};
if (OperateContext.EFBLLSession.t_bannerBLL.Add(addModel))
{
ajax.Msg = CommonBasicMsg.AddSuc;
ajax.Status = "ok";
}
else
{
ajax.Msg = CommonBasicMsg.AddFail;
}
//3.0 result
return Json(ajax);
}
[HttpGet]
public ActionResult BannerEdit(int? id)
{
if (id != null)
{
t_banner banner = OperateContext.EFBLLSession.t_bannerBLL.GetModelBy(b => b.banner_id == id);
if (banner != null)
{
ViewBag.ListBannerType = SelectHelper.GetEnumSelectListItem(Enums.BannerType.首页Banner, banner.banner_type.ToString());
ViewBag.ListClickType = SelectHelper.GetEnumSelectListItem(Enums.ClickType.不可点击, banner.click_type.ToString());
ViewBag.ListCat = SelectHelper.GetCategorySelList();
ViewBag.ListCatSel = SelectHelper.GetCategorySelListBy(banner.click_value);
return View(banner);
}
}
return Redirect("BannerList");
}
[HttpPost]
public ActionResult BannerEdit(t_banner model, HttpPostedFileBase new_banner_img, int click_type = 0, string hideClickValue = "")
{
AjaxMsg ajax = new AjaxMsg();
//1.0 check
if (model == null)
{
ajax.Msg = CommonBasicMsg.VoidModel;
return Json(ajax);
}
t_banner editModel = OperateContext.EFBLLSession.t_bannerBLL.GetModelBy(b => b.banner_id == model.banner_id);
if (editModel == null)
{
ajax.Msg = CommonBasicMsg.VoidModel;
return Json(ajax);
}
if (string.IsNullOrWhiteSpace(editModel.banner_name))
{
ajax.Msg = "Banner名称不能为空";
return Json(ajax);
}
if (OperateContext.EFBLLSession.t_bannerBLL.GetCountBy(b => b.banner_id != model.banner_id && b.banner_name == model.banner_name.Trim()) > 0)
{
ajax.Msg = "Banner名称已存在";
return Json(ajax);
}
//2.0 do
string strImg = "";
if (new_banner_img != null)
{
strImg = UploadHelper.UploadImage(new_banner_img);
if (string.IsNullOrEmpty(strImg))
{
ajax.Msg = CommonBasicMsg.UploadImgFail;
return Json(ajax);
}
}
editModel.banner_name = model.banner_name.Trim();
editModel.banner_type = model.banner_type;
if (!string.IsNullOrEmpty(strImg))
{
editModel.banner_img = strImg;
}
editModel.sort = model.sort;
editModel.click_type = model.click_type;
editModel.click_value = hideClickValue;
if (OperateContext.EFBLLSession.t_bannerBLL.Modify(editModel))
{
ajax.Msg = CommonBasicMsg.EditSuc;
ajax.Status = "ok";
}
else
{
ajax.Msg = CommonBasicMsg.EditFail;
}
return Json(ajax);
}
[HttpPost]
public ActionResult BannerDel(int? id)
{
AjaxMsg ajax = new AjaxMsg();
if (id != null)
{
if (OperateContext.EFBLLSession.t_bannerBLL.GetCountBy(b => b.banner_id == id) > 0)
{
if (OperateContext.EFBLLSession.t_bannerBLL.DeleteBy(b => b.banner_id == id))
{
ajax.Msg = CommonBasicMsg.DelSuc;
ajax.Status = "ok";
}
else
{
ajax.Msg = CommonBasicMsg.DelFail;
}
}
else
{
ajax.Msg = CommonBasicMsg.VoidModel;
}
}
else
{
ajax.Msg = CommonBasicMsg.VoidID;
}
return Json(ajax);
}
#endregion
}
} | 32.415789 | 166 | 0.492694 |
d12b28891d8281c2a351634e1f7ff4e855146fa1 | 5,122 | lua | Lua | libs/containers/User.lua | Tigerism/Discordia | bdcdc53f682b64ca609c9a1f2522ac704adaacb2 | [
"MIT"
] | null | null | null | libs/containers/User.lua | Tigerism/Discordia | bdcdc53f682b64ca609c9a1f2522ac704adaacb2 | [
"MIT"
] | null | null | null | libs/containers/User.lua | Tigerism/Discordia | bdcdc53f682b64ca609c9a1f2522ac704adaacb2 | [
"MIT"
] | null | null | null | --[=[
@c User x Snowflake
@d Represents a single user of Discord, either a human or a bot, outside of any
specific guild's context.
]=]
local Snowflake = require('containers/abstract/Snowflake')
local FilteredIterable = require('iterables/FilteredIterable')
local constants = require('constants')
local format = string.format
local DEFAULT_AVATARS = constants.DEFAULT_AVATARS
local User, get = require('class')('User', Snowflake)
function User:__init(data, parent)
Snowflake.__init(self, data, parent)
end
--[=[
@m getAvatarURL
@op size number
@op ext string
@r string
@d Returns a URL that can be used to view the user's full avatar. If provided, the
size must be a power of 2 while the extension must be a valid image format. If
the user does not have a custom avatar, the default URL is returned.
]=]
function User:getAvatarURL(size, ext)
local avatar = self._avatar
if avatar then
ext = ext or avatar:find('a_') == 1 and 'gif' or 'png'
if size then
return format('https://cdn.discordapp.com/avatars/%s/%s.%s?size=%s', self._id, avatar, ext, size)
else
return format('https://cdn.discordapp.com/avatars/%s/%s.%s', self._id, avatar, ext)
end
else
return self:getDefaultAvatarURL(size)
end
end
--[=[
@m getDefaultAvatarURL
@op size number
@r string
@d Returns a URL that can be used to view the user's default avatar.
]=]
function User:getDefaultAvatarURL(size)
local avatar = self.defaultAvatar
if size then
return format('https://cdn.discordapp.com/embed/avatars/%s.png?size=%s', avatar, size)
else
return format('https://cdn.discordapp.com/embed/avatars/%s.png', avatar)
end
end
--[=[
@m getPrivateChannel
@r PrivateChannel
@d Returns a private channel that can be used to communicate with the user. If the
channel is not cached an HTTP request is made to open one.
]=]
function User:getPrivateChannel()
local id = self._id
local client = self.client
local channel = client._private_channels:find(function(e) return e._recipient._id == id end)
if channel then
return channel
else
local data, err = client._api:createDM({recipient_id = id})
if data then
return client._private_channels:_insert(data)
else
return nil, err
end
end
end
--[=[
@m send
@p content string/table
@r Message
@d Equivalent to `User:getPrivateChannel():send(content)`
]=]
function User:send(content)
local channel, err = self:getPrivateChannel()
if channel then
return channel:send(content)
else
return nil, err
end
end
--[=[
@m sendf
@p content string
@r Message
@d Equivalent to `User:getPrivateChannel():sendf(content)`
]=]
function User:sendf(content, ...)
local channel, err = self:getPrivateChannel()
if channel then
return channel:sendf(content, ...)
else
return nil, err
end
end
--[=[@p bot boolean Whether this user is a bot.]=]
function get.bot(self)
return self._bot or false
end
--[=[@p name string Equivalent to `User.username`.]=]
function get.name(self)
return self._username
end
--[=[@p username string The name of the user. This should be between 2 and 32 characters in length.]=]
function get.username(self)
return self._username
end
--[=[@p discriminator number The discriminator of the user. This is a 4-digit string that is used to
discriminate the user from other users with the same username.]=]
function get.discriminator(self)
return self._discriminator
end
--[=[@p tag string The user's username and discriminator concatenated by an `#`.]=]
function get.tag(self)
return self._username .. '#' .. self._discriminator
end
function get.fullname(self)
self.client:_deprecated(self.__name, 'fullname', 'tag')
return self._username .. '#' .. self._discriminator
end
--[=[@p avatar string/nil The hash for the user's custom avatar, if one is set.]=]
function get.avatar(self)
return self._avatar
end
--[=[@p defaultAvatar number The user's default avatar. See the `defaultAvatar` enumeration for a
human-readable representation.]=]
function get.defaultAvatar(self)
return self._discriminator % DEFAULT_AVATARS
end
--[=[@p avatarURL string Equivalent to the result of calling `User:getAvatarURL()`.]=]
function get.avatarURL(self)
return self:getAvatarURL()
end
--[=[@p defaultAvatarURL string Equivalent to the result of calling `User:getDefaultAvatarURL()`.]=]
function get.defaultAvatarURL(self)
return self:getDefaultAvatarURL()
end
--[=[@p mentionString string A string that, when included in a message content, may resolve as user
notification in the official Discord client.]=]
function get.mentionString(self)
return format('<@%s>', self._id)
end
--[=[@p mutualGuilds FilteredIterable A iterable cache of all guilds where this user shares a membership with the
current user. The guild must be cached on the current client and the user's
member object must be cached in that guild in order for it to appear here.]=]
local _mutual_guilds = setmetatable({}, {__mode = 'v'})
function get.mutualGuilds(self)
if not _mutual_guilds[self] then
local id = self._id
_mutual_guilds[self] = FilteredIterable(self.client._guilds, function(g)
return g._members:get(id)
end)
end
return _mutual_guilds[self]
end
return User
| 27.989071 | 113 | 0.742679 |
149760ad826262dac47f7b1e83e2507f2487165e | 688 | ts | TypeScript | src/modules/carRental/interfaces/interfaceRepository/ICarRentalRepository.ts | mviniciusgc/SEIDOR | 0995a71d7246548b135e392979467680f0288452 | [
"MIT"
] | null | null | null | src/modules/carRental/interfaces/interfaceRepository/ICarRentalRepository.ts | mviniciusgc/SEIDOR | 0995a71d7246548b135e392979467680f0288452 | [
"MIT"
] | null | null | null | src/modules/carRental/interfaces/interfaceRepository/ICarRentalRepository.ts | mviniciusgc/SEIDOR | 0995a71d7246548b135e392979467680f0288452 | [
"MIT"
] | null | null | null | import { IAutomobile } from '@modules/automobiles/interfaces/interfaceDTO/IAutomobileDTO'
import { IDriver } from '@modules/driver/interfaces/interfaceDTO/IDriverDTO'
import { CarRentalEntitie } from '../../models/CarRentalEntitie'
interface ICarRentalRepository {
create(motorista: IDriver, carro: IAutomobile, descricaoUtilizacao: string): CarRentalEntitie;
// update(data: IDriver): DriverEntitie;
// findList(data: IFilterDriver): Array<DriverEntitie>;
// delete(id: string): Array<DriverEntitie>;
findByIdDriver(id: string): CarRentalEntitie | undefined;
findByIdAutomobile(id: string): CarRentalEntitie | undefined;
}
export { ICarRentalRepository } | 49.142857 | 98 | 0.758721 |
e29d638218eafcab69b16c81241ef7e528c063ee | 7,951 | py | Python | openstackclient/shell.py | dreamhost/python-openstackclient | fd8197de6d8178ded323fd6e0bcc0c0b59ff30f3 | [
"Apache-2.0"
] | null | null | null | openstackclient/shell.py | dreamhost/python-openstackclient | fd8197de6d8178ded323fd6e0bcc0c0b59ff30f3 | [
"Apache-2.0"
] | null | null | null | openstackclient/shell.py | dreamhost/python-openstackclient | fd8197de6d8178ded323fd6e0bcc0c0b59ff30f3 | [
"Apache-2.0"
] | null | null | null | # Copyright 2012 OpenStack LLC.
# 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.
#
# vim: tabstop=4 shiftwidth=4 softtabstop=4
"""
Command-line interface to the OpenStack APIs
"""
import logging
import os
import sys
from cliff.app import App
from cliff.commandmanager import CommandManager
from openstackclient.common import clientmanager
from openstackclient.common import exceptions as exc
from openstackclient.common import utils
VERSION = '0.1'
def env(*vars, **kwargs):
"""Search for the first defined of possibly many env vars
Returns the first environment variable defined in vars, or
returns the default defined in kwargs.
"""
for v in vars:
value = os.environ.get(v, None)
if value:
return value
return kwargs.get('default', '')
class OpenStackShell(App):
CONSOLE_MESSAGE_FORMAT = '%(levelname)s: %(name)s %(message)s'
log = logging.getLogger(__name__)
def __init__(self):
super(OpenStackShell, self).__init__(
description=__doc__.strip(),
version=VERSION,
command_manager=CommandManager('openstack.cli'),
)
# This is instantiated in initialize_app() only when using
# password flow auth
self.auth_client = None
def build_option_parser(self, description, version):
parser = super(OpenStackShell, self).build_option_parser(
description,
version,
)
# Global arguments
parser.add_argument('--os-auth-url', metavar='<auth-url>',
default=env('OS_AUTH_URL'),
help='Authentication URL (Env: OS_AUTH_URL)')
parser.add_argument('--os-tenant-name', metavar='<auth-tenant-name>',
default=env('OS_TENANT_NAME'),
help='Authentication tenant name (Env: OS_TENANT_NAME)')
parser.add_argument('--os-tenant-id', metavar='<auth-tenant-id>',
default=env('OS_TENANT_ID'),
help='Authentication tenant ID (Env: OS_TENANT_ID)')
parser.add_argument('--os-username', metavar='<auth-username>',
default=utils.env('OS_USERNAME'),
help='Authentication username (Env: OS_USERNAME)')
parser.add_argument('--os-password', metavar='<auth-password>',
default=utils.env('OS_PASSWORD'),
help='Authentication password (Env: OS_PASSWORD)')
parser.add_argument('--os-region-name', metavar='<auth-region-name>',
default=env('OS_REGION_NAME'),
help='Authentication region name (Env: OS_REGION_NAME)')
parser.add_argument('--os-identity-api-version',
metavar='<identity-api-version>',
default=env('OS_IDENTITY_API_VERSION', default='2.0'),
help='Identity API version, default=2.0 '\
'(Env: OS_IDENTITY_API_VERSION)')
parser.add_argument('--os-compute-api-version',
metavar='<compute-api-version>',
default=env('OS_COMPUTE_API_VERSION', default='2'),
help='Compute API version, default=2 '\
'(Env: OS_COMPUTE_API_VERSION)')
parser.add_argument('--os-image-api-version',
metavar='<image-api-version>',
default=env('OS_IMAGE_API_VERSION', default='1.0'),
help='Image API version, default=1.0 '\
'(Env: OS_IMAGE_API_VERSION)')
parser.add_argument('--os-token', metavar='<token>',
default=env('OS_TOKEN'),
help='Defaults to env[OS_TOKEN]')
parser.add_argument('--os-url', metavar='<url>',
default=env('OS_URL'),
help='Defaults to env[OS_URL]')
return parser
def authenticate_user(self):
"""Make sure the user has provided all of the authentication
info we need.
"""
self.log.debug('validating authentication options')
if self.options.os_token or self.options.os_url:
# Token flow auth takes priority
if not self.options.os_token:
raise exc.CommandError(
"You must provide a token via"
" either --os-token or env[OS_TOKEN]")
if not self.options.os_url:
raise exc.CommandError(
"You must provide a service URL via"
" either --os-url or env[OS_URL]")
else:
# Validate password flow auth
if not self.options.os_username:
raise exc.CommandError(
"You must provide a username via"
" either --os-username or env[OS_USERNAME]")
if not self.options.os_password:
raise exc.CommandError(
"You must provide a password via"
" either --os-password or env[OS_PASSWORD]")
if not (self.options.os_tenant_id or self.options.os_tenant_name):
raise exc.CommandError(
"You must provide a tenant_id via"
" either --os-tenant-id or via env[OS_TENANT_ID]")
if not self.options.os_auth_url:
raise exc.CommandError(
"You must provide an auth url via"
" either --os-auth-url or via env[OS_AUTH_URL]")
self.client_manager = clientmanager.ClientManager(
token=self.options.os_token,
url=self.options.os_url,
auth_url=self.options.os_auth_url,
tenant_name=self.options.os_tenant_name,
tenant_id=self.options.os_tenant_id,
username=self.options.os_username,
password=self.options.os_password,
region_name=self.options.os_region_name,
api_version=self.api_version,
)
return
def initialize_app(self, argv):
"""Global app init bits:
* set up API versions
* validate authentication info
* authenticate against Identity if requested
"""
super(OpenStackShell, self).initialize_app(argv)
# stash selected API versions for later
# TODO(dtroyer): how do extenstions add their version requirements?
self.api_version = {
'compute': self.options.os_compute_api_version,
'identity': self.options.os_identity_api_version,
'image': self.options.os_image_api_version,
}
# If the user is not asking for help, make sure they
# have given us auth.
cmd_name = None
if argv:
cmd_info = self.command_manager.find_command(argv)
cmd_factory, cmd_name, sub_argv = cmd_info
if self.interactive_mode or cmd_name != 'help':
self.authenticate_user()
def prepare_to_run_command(self, cmd):
"""Set up auth and API versions"""
self.log.debug('prepare_to_run_command %s', cmd.__class__.__name__)
self.log.debug("api: %s" % cmd.api if hasattr(cmd, 'api') else None)
return
def clean_up(self, cmd, result, err):
self.log.debug('clean_up %s', cmd.__class__.__name__)
if err:
self.log.debug('got an error: %s', err)
def main(argv=sys.argv[1:]):
try:
return OpenStackShell().run(argv)
except:
return 1
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
| 34.872807 | 78 | 0.606213 |
d8fcd83cf759aa7d1e952d9ff25fb1935a951c45 | 9,356 | dart | Dart | lib/common/version.dart | jjjachyty/smh_app | 06fc197c4783153d6b0792ef7f87ee19e074c321 | [
"Apache-2.0"
] | null | null | null | lib/common/version.dart | jjjachyty/smh_app | 06fc197c4783153d6b0792ef7f87ee19e074c321 | [
"Apache-2.0"
] | null | null | null | lib/common/version.dart | jjjachyty/smh_app | 06fc197c4783153d6b0792ef7f87ee19e074c321 | [
"Apache-2.0"
] | null | null | null | import 'dart:io';
import 'dart:isolate';
import 'dart:ui';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:open_file/open_file.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:progress_dialog/progress_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import 'package:path_provider/path_provider.dart';
import 'package:smh/page/index.dart';
import 'package:url_launcher/url_launcher.dart';
import 'init.dart';
var _localPath;
var _name = "书名号.apk";
class VersionPage extends StatefulWidget {
@override
_VersionPageState createState() => _VersionPageState();
}
class _VersionPageState extends State<VersionPage> {
List<_TaskInfo> _tasks;
bool _isLoading = false;
bool _permissionReady;
ProgressDialog pr;
String _localPath;
ReceivePort _port = ReceivePort();
@override
void initState() {
super.initState();
if (Platform.isAndroid) {
WidgetsFlutterBinding.ensureInitialized();
FlutterDownloader.initialize().then((Null) {
_bindBackgroundIsolate();
FlutterDownloader.registerCallback(downloadCallback);
_permissionReady = false;
_prepare();
pr = new ProgressDialog(context,
type: ProgressDialogType.Download, isDismissible: false);
pr.style(message: "下载中,请稍后…");
});
}
}
@override
void dispose() {
if (Platform.isAndroid) {
_unbindBackgroundIsolate();
}
super.dispose();
}
void _bindBackgroundIsolate() {
print("_bindBackgroundIsolate");
bool isSuccess = IsolateNameServer.registerPortWithName(
_port.sendPort, 'downloader_send_port');
if (!isSuccess) {
_unbindBackgroundIsolate();
_bindBackgroundIsolate();
return;
}
_port.listen((dynamic data) {
setState(() {
pr.show();
});
print('UI Isolate Callback: $data');
String id = data[0];
DownloadTaskStatus status = data[1];
int progress = data[2];
print(
'Download task ($id) is in status ($status) and process ($progress)');
if (status == DownloadTaskStatus.running) {
pr.update(progress: progress.toDouble(), message: "下载中,请稍后…");
}
if (status == DownloadTaskStatus.failed) {
Fluttertoast.showToast(
msg: "下载异常,请稍后重试",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 2,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
if (pr.isShowing()) {
pr.hide();
}
}
if (status == DownloadTaskStatus.complete) {
print(pr.isShowing());
if (pr.isShowing()) {
pr.hide();
OpenFile.open(_localPath + "/" + _name);
//installApk(_localPath + "/MHC.apk", "com.example.apcc_wallet");
}
}
});
}
void _unbindBackgroundIsolate() {
IsolateNameServer.removePortNameMapping('downloader_send_port');
}
static void downloadCallback(
String id, DownloadTaskStatus status, int progress) {
print(
'Background Isolate Callback: task ($id) is in status ($status) and process ($progress)');
final SendPort send =
IsolateNameServer.lookupPortByName('downloader_send_port');
send.send([id, status, progress]);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
centerTitle: true,
title: new Text("新版本${newestVersion.VersionCode}发布"),
leading: IconButton(
icon: Icon(Icons.close),
onPressed: () {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) {
return IndexPage();
}));
},
),
actions: <Widget>[
FlatButton(
child: Text(
"去更新",
style: TextStyle(color: Colors.white),
),
onPressed: () async {
if (Platform.isAndroid) {
_requestDownload(_TaskInfo(
name: _name, link: "${newestVersion.DownloadURL}"));
} else {
if (await canLaunch(newestVersion.DownloadURL)) {
await launch(newestVersion.DownloadURL);
} else {
Fluttertoast.showToast(
msg: "无法打开浏览器",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIos: 2,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
}
},
)
],
),
body: Builder(
builder: (context) => _isLoading
? new Center(
child: new CircularProgressIndicator(),
)
: new Container(
child: Column(
children: <Widget>[
Container(
alignment: Alignment.centerRight,
child: Text(
"发布时间 ${newestVersion.ReleaseTime}",
style: TextStyle(fontSize: 12),
),
),
Container(
alignment: Alignment.center,
child: Text(
"本地版本 ${currentVersion}",
),
),
Expanded(
child: new MarkdownBody(
data:
"${newestVersion.ReleaseNote}"), //SingleChildScrollView(child: Text("${newestVersion.releaseNote}"),) ,
),
],
),
)));
}
void _requestDownload(_TaskInfo task) async {
task.taskId = await FlutterDownloader.enqueue(
url: task.link,
savedDir: _localPath,
showNotification: true,
fileName: _name,
openFileFromNotification: true);
}
void _cancelDownload(_TaskInfo task) async {
await FlutterDownloader.cancel(taskId: task.taskId);
}
void _pauseDownload(_TaskInfo task) async {
await FlutterDownloader.pause(taskId: task.taskId);
}
void _resumeDownload(_TaskInfo task) async {
String newTaskId = await FlutterDownloader.resume(taskId: task.taskId);
task.taskId = newTaskId;
}
void _retryDownload(_TaskInfo task) async {
String newTaskId = await FlutterDownloader.retry(taskId: task.taskId);
task.taskId = newTaskId;
}
Future<bool> _openDownloadedFile(_TaskInfo task) {
return FlutterDownloader.open(taskId: task.taskId);
}
void _delete(_TaskInfo task) async {
await FlutterDownloader.remove(
taskId: task.taskId, shouldDeleteContent: true);
await _prepare();
setState(() {});
}
Future<bool> _checkPermission() async {
if (Platform.isAndroid) {
PermissionStatus permission = await PermissionHandler()
.checkPermissionStatus(PermissionGroup.storage);
if (permission != PermissionStatus.granted) {
Map<PermissionGroup, PermissionStatus> permissions =
await PermissionHandler()
.requestPermissions([PermissionGroup.storage]);
if (permissions[PermissionGroup.storage] == PermissionStatus.granted) {
return true;
}
} else {
return true;
}
} else {
return true;
}
return false;
}
Future<Null> _prepare() async {
final tasks = await FlutterDownloader.loadTasks();
_tasks = [];
_tasks.add(_TaskInfo(name: _name, link: "${newestVersion.DownloadURL}"));
tasks?.forEach((task) {
for (_TaskInfo info in _tasks) {
if (info.link == task.url) {
info.taskId = task.taskId;
info.status = task.status;
info.progress = task.progress;
}
}
});
_permissionReady = await _checkPermission();
_localPath = (await _findLocalPath()) + '/Download';
final savedDir = Directory(_localPath);
bool hasExisted = await savedDir.exists();
if (!hasExisted) {
savedDir.create();
}
setState(() {
_isLoading = false;
});
}
Future<String> _findLocalPath() async {
final directory = Platform.isAndroid
? await getExternalStorageDirectory()
: await getApplicationDocumentsDirectory();
return directory.path;
}
}
class _TaskInfo {
final String name;
final String link;
String taskId;
int progress = 0;
DownloadTaskStatus status = DownloadTaskStatus.undefined;
_TaskInfo({this.name, this.link});
}
| 30.877888 | 139 | 0.553121 |
25d6afe2d865e88d073cb1512fb2750e4b994f6a | 13,158 | cs | C# | src/modules/launcher/Wox.Test/Plugins/ProgramPluginTest.cs | 0proto/PowerToys | 1533c9315f4719ccf803818997b1cf7d507fe00d | [
"MIT"
] | 1 | 2022-01-27T08:29:27.000Z | 2022-01-27T08:29:27.000Z | src/modules/launcher/Wox.Test/Plugins/ProgramPluginTest.cs | 0proto/PowerToys | 1533c9315f4719ccf803818997b1cf7d507fe00d | [
"MIT"
] | null | null | null | src/modules/launcher/Wox.Test/Plugins/ProgramPluginTest.cs | 0proto/PowerToys | 1533c9315f4719ccf803818997b1cf7d507fe00d | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
using Wox.Infrastructure;
using Wox.Plugin;
using Microsoft.Plugin.Program.Programs;
using Moq;
using System.IO;
namespace Wox.Test.Plugins
{
[TestFixture]
public class ProgramPluginTest
{
Win32 notepad_appdata = new Win32
{
Name = "Notepad",
ExecutableName = "notepad.exe",
FullPath = "c:\\windows\\system32\\notepad.exe",
LnkResolvedPath = "c:\\users\\powertoys\\appdata\\roaming\\microsoft\\windows\\start menu\\programs\\accessories\\notepad.lnk"
};
Win32 notepad_users = new Win32
{
Name = "Notepad",
ExecutableName = "notepad.exe",
FullPath = "c:\\windows\\system32\\notepad.exe",
LnkResolvedPath = "c:\\programdata\\microsoft\\windows\\start menu\\programs\\accessories\\notepad.lnk"
};
Win32 azure_command_prompt = new Win32
{
Name = "Microsoft Azure Command Prompt - v2.9",
ExecutableName = "cmd.exe",
FullPath = "c:\\windows\\system32\\cmd.exe",
LnkResolvedPath = "c:\\programdata\\microsoft\\windows\\start menu\\programs\\microsoft azure\\microsoft azure sdk for .net\\v2.9\\microsoft azure command prompt - v2.9.lnk"
};
Win32 visual_studio_command_prompt = new Win32
{
Name = "x64 Native Tools Command Prompt for VS 2019",
ExecutableName = "cmd.exe",
FullPath = "c:\\windows\\system32\\cmd.exe",
LnkResolvedPath = "c:\\programdata\\microsoft\\windows\\start menu\\programs\\visual studio 2019\\visual studio tools\\vc\\x64 native tools command prompt for vs 2019.lnk"
};
Win32 command_prompt = new Win32
{
Name = "Command Prompt",
ExecutableName = "cmd.exe",
FullPath = "c:\\windows\\system32\\cmd.exe",
LnkResolvedPath ="c:\\users\\powertoys\\appdata\\roaming\\microsoft\\windows\\start menu\\programs\\system tools\\command prompt.lnk"
};
Win32 file_explorer = new Win32
{
Name = "File Explorer",
ExecutableName = "File Explorer.lnk",
FullPath = "c:\\users\\powertoys\\appdata\\roaming\\microsoft\\windows\\start menu\\programs\\system tools\\file explorer.lnk",
LnkResolvedPath = null
};
Win32 wordpad = new Win32
{
Name = "Wordpad",
ExecutableName = "wordpad.exe",
FullPath = "c:\\program files\\windows nt\\accessories\\wordpad.exe",
LnkResolvedPath = "c:\\programdata\\microsoft\\windows\\start menu\\programs\\accessories\\wordpad.lnk"
};
Win32 wordpad_duplicate = new Win32
{
Name = "WORDPAD",
ExecutableName = "WORDPAD.EXE",
FullPath = "c:\\program files\\windows nt\\accessories\\wordpad.exe",
LnkResolvedPath = null
};
Win32 twitter_pwa = new Win32
{
Name = "Twitter",
FullPath = "c:\\program files (x86)\\google\\chrome\\application\\chrome_proxy.exe",
LnkResolvedPath = "c:\\users\\powertoys\\appdata\\roaming\\microsoft\\windows\\start menu\\programs\\chrome apps\\twitter.lnk",
Arguments = " --profile-directory=Default --app-id=jgeosdfsdsgmkedfgdfgdfgbkmhcgcflmi"
};
Win32 pinned_webpage = new Win32
{
Name = "Web page",
FullPath = "c:\\program files (x86)\\microsoft\\edge\\application\\msedge_proxy.exe",
LnkResolvedPath = "c:\\users\\powertoys\\appdata\\roaming\\microsoft\\windows\\start menu\\programs\\web page.lnk",
Arguments = "--profile-directory=Default --app-id=homljgmgpmcbpjbnjpfijnhipfkiclkd"
};
Win32 edge_named_pinned_webpage = new Win32
{
Name = "edge - Bing",
FullPath = "c:\\program files (x86)\\microsoft\\edge\\application\\msedge_proxy.exe",
LnkResolvedPath = "c:\\users\\powertoys\\appdata\\roaming\\microsoft\\windows\\start menu\\programs\\edge - bing.lnk",
Arguments = " --profile-directory=Default --app-id=aocfnapldcnfbofgmbbllojgocaelgdd"
};
Win32 msedge = new Win32
{
Name = "Microsoft Edge",
ExecutableName = "msedge.exe",
FullPath = "c:\\program files (x86)\\microsoft\\edge\\application\\msedge.exe",
LnkResolvedPath = "c:\\programdata\\microsoft\\windows\\start menu\\programs\\microsoft edge.lnk"
};
Win32 chrome = new Win32
{
Name = "Google Chrome",
ExecutableName = "chrome.exe",
FullPath = "c:\\program files (x86)\\google\\chrome\\application\\chrome.exe",
LnkResolvedPath = "c:\\programdata\\microsoft\\windows\\start menu\\programs\\google chrome.lnk"
};
Win32 dummy_proxy_app = new Win32
{
Name = "Proxy App",
ExecutableName = "test_proxy.exe",
FullPath = "c:\\program files (x86)\\microsoft\\edge\\application\\test_proxy.exe",
LnkResolvedPath = "c:\\programdata\\microsoft\\windows\\start menu\\programs\\test proxy.lnk"
};
Win32 cmd_run_command = new Win32
{
Name = "cmd",
ExecutableName = "cmd.exe",
FullPath = "c:\\windows\\system32\\cmd.exe",
LnkResolvedPath = null,
AppType = 3 // Run command
};
Win32 cmder_run_command = new Win32
{
Name = "Cmder",
ExecutableName = "Cmder.exe",
FullPath = "c:\\tools\\cmder\\cmder.exe",
LnkResolvedPath = null,
AppType = 3 // Run command
};
Win32 dummy_internetShortcut_app = new Win32
{
Name = "Shop Titans",
ExecutableName = "Shop Titans.url",
FullPath = "steam://rungameid/1258080",
ParentDirectory = "C:\\Users\\temp\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Steam",
LnkResolvedPath = null
};
Win32 dummy_internetShortcut_app_duplicate = new Win32
{
Name = "Shop Titans",
ExecutableName = "Shop Titans.url",
FullPath = "steam://rungameid/1258080",
ParentDirectory = "C:\\Users\\temp\\Desktop",
LnkResolvedPath = null
};
[Test]
public void DedupFunction_whenCalled_mustRemoveDuplicateNotepads()
{
// Arrange
List<Win32> prgms = new List<Win32>();
prgms.Add(notepad_appdata);
prgms.Add(notepad_users);
// Act
Win32[] apps = Win32.DeduplicatePrograms(prgms.AsParallel());
// Assert
Assert.AreEqual(apps.Length, 1);
}
[Test]
public void DedupFunction_whenCalled_MustRemoveInternetShortcuts()
{
// Arrange
List<Win32> prgms = new List<Win32>();
prgms.Add(dummy_internetShortcut_app);
prgms.Add(dummy_internetShortcut_app_duplicate);
// Act
Win32[] apps = Win32.DeduplicatePrograms(prgms.AsParallel());
// Assert
Assert.AreEqual(apps.Length, 1);
}
[Test]
public void DedupFunction_whenCalled_mustNotRemovelnkWhichdoesNotHaveExe()
{
// Arrange
List<Win32> prgms = new List<Win32>();
prgms.Add(file_explorer);
// Act
Win32[] apps = Win32.DeduplicatePrograms(prgms.AsParallel());
// Assert
Assert.AreEqual(apps.Length, 1);
}
[Test]
public void DedupFunction_mustRemoveDuplicates_forExeExtensionsWithoutLnkResolvedPath()
{
// Arrange
List<Win32> prgms = new List<Win32>();
prgms.Add(wordpad);
prgms.Add(wordpad_duplicate);
// Act
Win32[] apps = Win32.DeduplicatePrograms(prgms.AsParallel());
// Assert
Assert.AreEqual(apps.Length, 1);
Assert.IsTrue(!string.IsNullOrEmpty(apps[0].LnkResolvedPath));
}
[Test]
public void DedupFunction_mustNotRemovePrograms_withSameExeNameAndFullPath()
{
// Arrange
List<Win32> prgms = new List<Win32>();
prgms.Add(azure_command_prompt);
prgms.Add(visual_studio_command_prompt);
prgms.Add(command_prompt);
// Act
Win32[] apps = Win32.DeduplicatePrograms(prgms.AsParallel());
// Assert
Assert.AreEqual(apps.Length, 3);
}
[Test]
public void FunctionIsWebApplication_ShouldReturnTrue_ForWebApplications()
{
// The IsWebApplication(() function must return true for all PWAs and pinned web pages
Assert.IsTrue(twitter_pwa.IsWebApplication());
Assert.IsTrue(pinned_webpage.IsWebApplication());
Assert.IsTrue(edge_named_pinned_webpage.IsWebApplication());
// Should not filter apps whose executable name ends with proxy.exe
Assert.IsFalse(dummy_proxy_app.IsWebApplication());
}
[TestCase("ignore")]
public void FunctionFilterWebApplication_ShouldReturnFalse_WhenSearchingForTheMainApp(string query)
{
// Irrespective of the query, the FilterWebApplication() Function must not filter main apps such as edge and chrome
Assert.IsFalse(msedge.FilterWebApplication(query));
Assert.IsFalse(chrome.FilterWebApplication(query));
}
[TestCase("edge", ExpectedResult = true)]
[TestCase("EDGE", ExpectedResult = true)]
[TestCase("msedge", ExpectedResult = true)]
[TestCase("Microsoft", ExpectedResult = true)]
[TestCase("edg", ExpectedResult = true)]
[TestCase("Edge page", ExpectedResult = false)]
[TestCase("Edge Web page", ExpectedResult = false)]
public bool EdgeWebSites_ShouldBeFiltered_WhenSearchingForEdge(string query)
{
return pinned_webpage.FilterWebApplication(query);
}
[TestCase("chrome", ExpectedResult = true)]
[TestCase("CHROME", ExpectedResult = true)]
[TestCase("Google", ExpectedResult = true)]
[TestCase("Google Chrome", ExpectedResult = true)]
[TestCase("Google Chrome twitter", ExpectedResult = false)]
public bool ChromeWebSites_ShouldBeFiltered_WhenSearchingForChrome(string query)
{
return twitter_pwa.FilterWebApplication(query);
}
[TestCase("twitter", 0, ExpectedResult = false)]
[TestCase("Twit", 0, ExpectedResult = false)]
[TestCase("TWITTER", 0, ExpectedResult = false)]
[TestCase("web", 1, ExpectedResult = false)]
[TestCase("Page", 1, ExpectedResult = false)]
[TestCase("WEB PAGE", 1, ExpectedResult = false)]
[TestCase("edge", 2, ExpectedResult = false)]
[TestCase("EDGE", 2, ExpectedResult = false)]
public bool PinnedWebPages_ShouldNotBeFiltered_WhenSearchingForThem(string query, int Case)
{
const uint CASE_TWITTER = 0;
const uint CASE_WEB_PAGE = 1;
const uint CASE_EDGE_NAMED_WEBPAGE = 2;
// If the query is a part of the name of the web application, it should not be filtered,
// even if the name is the same as that of the main application, eg: case 2 - edge
if (Case == CASE_TWITTER)
{
return twitter_pwa.FilterWebApplication(query);
}
else if(Case == CASE_WEB_PAGE)
{
return pinned_webpage.FilterWebApplication(query);
}
else if(Case == CASE_EDGE_NAMED_WEBPAGE)
{
return edge_named_pinned_webpage.FilterWebApplication(query);
}
// unreachable code
return true;
}
[TestCase("Command Prompt")]
[TestCase("cmd")]
[TestCase("cmd.exe")]
[TestCase("ignoreQueryText")]
public void Win32Applications_ShouldNotBeFiltered_WhenFilteringRunCommands(string query)
{
// Even if there is an exact match in the name or exe name, applications should never be filtered
Assert.IsTrue(command_prompt.QueryEqualsNameForRunCommands(query));
}
[TestCase("cmd")]
[TestCase("Cmd")]
[TestCase("CMD")]
public void RunCommands_ShouldNotBeFiltered_OnExactMatch(string query)
{
// Partial matches should be filtered as cmd is not equal to cmder
Assert.IsFalse(cmder_run_command.QueryEqualsNameForRunCommands(query));
// the query matches the name (cmd) and is therefore not filtered (case-insensitive)
Assert.IsTrue(cmd_run_command.QueryEqualsNameForRunCommands(query));
}
}
}
| 38.928994 | 185 | 0.594771 |
c036ab70923574f87091e759d5d42530869fb81e | 204 | cs | C# | src/Scrapbook/GoogleSheet.cs | tomcrane/scrapbook | 8e7b0e6307ecdadede17b878061f78bc9d73bd9c | [
"MIT"
] | null | null | null | src/Scrapbook/GoogleSheet.cs | tomcrane/scrapbook | 8e7b0e6307ecdadede17b878061f78bc9d73bd9c | [
"MIT"
] | null | null | null | src/Scrapbook/GoogleSheet.cs | tomcrane/scrapbook | 8e7b0e6307ecdadede17b878061f78bc9d73bd9c | [
"MIT"
] | null | null | null | namespace Scrapbook
{
public class GoogleSheet
{
public string Range { get; set; }
public string MajorDimension { get; set; }
public string[][] Values { get; set; }
}
} | 22.666667 | 50 | 0.583333 |
79e9f0a5999f7304de9cba85a418b6339acf489c | 1,390 | php | PHP | vendor/twig/twig/src/Node/DeprecatedNode.php | Qtn49/project-php | 632ae69e6f3a69b8240017c8b96f615b475c876d | [
"MIT"
] | null | null | null | vendor/twig/twig/src/Node/DeprecatedNode.php | Qtn49/project-php | 632ae69e6f3a69b8240017c8b96f615b475c876d | [
"MIT"
] | null | null | null | vendor/twig/twig/src/Node/DeprecatedNode.php | Qtn49/project-php | 632ae69e6f3a69b8240017c8b96f615b475c876d | [
"MIT"
] | null | null | null | <?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please templates the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Expression\ConstantExpression;
/**
* Represents a deprecated node.
*
* @author Yonel Ceruto <[email protected]>
*/
class DeprecatedNode extends Node
{
public function __construct(AbstractExpression $expr, int $lineno, string $tag = null)
{
parent::__construct(['expr' => $expr], [], $lineno, $tag);
}
public function compile(Compiler $compiler): void
{
$compiler->addDebugInfo($this);
$expr = $this->getNode('expr');
if ($expr instanceof ConstantExpression) {
$compiler->write('@trigger_error(')
->subcompile($expr);
} else {
$varName = $compiler->getVarName();
$compiler->write(sprintf('$%s = ', $varName))
->subcompile($expr)
->raw(";\n")
->write(sprintf('@trigger_error($%s', $varName));
}
$compiler
->raw('.')
->string(sprintf(' ("%s" at line %d).', $this->getTemplateName(), $this->getTemplateLine()))
->raw(", E_USER_DEPRECATED);\n")
;
}
}
| 25.740741 | 104 | 0.579137 |
45d65891a06d722f73ec82d918dc0869a9d1d47f | 141 | py | Python | src/image_uploader/urls.py | Hazzari/backend-api-uploader | 38702abe72ccc85c2bf83951ff16c71ce510f46d | [
"MIT"
] | null | null | null | src/image_uploader/urls.py | Hazzari/backend-api-uploader | 38702abe72ccc85c2bf83951ff16c71ce510f46d | [
"MIT"
] | null | null | null | src/image_uploader/urls.py | Hazzari/backend-api-uploader | 38702abe72ccc85c2bf83951ff16c71ce510f46d | [
"MIT"
] | null | null | null | from django.urls import path
from . import views
app_name = 'authentication'
urlpatterns = [
path('', views.ImageViewSet.as_view()),
]
| 15.666667 | 43 | 0.70922 |
465466cc72f35f8189c1853ce159a1669c86b489 | 4,112 | php | PHP | application/views/template/back/js_back.php | premawaisnawa/here_sell_well | cd460579de9e901fb19fc126f3b5e2089b58d597 | [
"MIT"
] | null | null | null | application/views/template/back/js_back.php | premawaisnawa/here_sell_well | cd460579de9e901fb19fc126f3b5e2089b58d597 | [
"MIT"
] | null | null | null | application/views/template/back/js_back.php | premawaisnawa/here_sell_well | cd460579de9e901fb19fc126f3b5e2089b58d597 | [
"MIT"
] | null | null | null |
<!-- jQuery UI 1.11.2 -->
<script src="<?php echo base_url('assets/js/jquery-ui.min.js') ?>" type="text/javascript"></script>
<!-- Resolve conflict in jQuery UI tooltip with Bootstrap tooltip -->
<script>
$.widget.bridge('uibutton', $.ui.button);
</script>
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/plugins/knob/jquery.knob.js') ?>" type="text/javascript"></script>
<!-- Bootstrap WYSIHTML5 -->
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/plugins/bootstrap-wysihtml5/bootstrap3-wysihtml5.all.min.js') ?>" type="text/javascript"></script>
<!-- AdminLTE for demo purposes -->
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/dist/js/demo.js') ?>" type="text/javascript"></script>
<!-- jQuery 2.2.3 -->
<!-- jQuery 2.1.3 -->
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/plugins/jQuery/jquery-2.2.3.min.js') ?>"></script>
<!-- Bootstrap 3.3.6 -->
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/bootstrap/js/bootstrap.min.js') ?>" type="text/javascript"></script>
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/plugins/datatables/jquery.dataTables.min.js') ?>" type="text/javascript"></script>
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/plugins/datatables/dataTables.bootstrap.min.js') ?>" type="text/javascript"></script>
<!-- SlimScroll -->
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/plugins/slimScroll/jquery.slimscroll.min.js') ?>" type="text/javascript"></script>
<!-- FastClick -->
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/plugins/fastclick/fastclick.js') ?>" type="text/javascript"></script>
<!-- AdminLTE App -->
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/dist/js/app.min.js') ?>" type="text/javascript"></script>
<!-- AdminLTE for demo purposes -->
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/dist/js/demo.js') ?>" type="text/javascript"></script>
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/plugins/select2/select2.full.min.js') ?>" type="text/javascript"></script>
<!-- datepicker -->
<script src="<?php echo base_url('assets/AdminLTE-2.0.5/plugins/datepicker/bootstrap-datepicker.js') ?>" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.2.0/jquery-confirm.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.loadingoverlay/latest/loadingoverlay.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.loadingoverlay/latest/loadingoverlay_progress.min.js"></script>
<script type="text/javascript" src="<?php echo base_url('assets/js/pnoty/pnotify.js') ?>" src="src/pnotify.js"></script>
<script type="text/javascript" href="<?php echo base_url('assets/js/pnoty/pnotify.animate.js') ?>" ></script>
<script type="text/javascript" href="<?php echo base_url('assets/js/pnoty/pnotify.buttons.js') ?>" type="text/javascript" ></script>
<script src= "<?php echo base_url('assets/js/raphael-min.js') ?>" ></script>
<script src= "<?php echo base_url('assets/AdminLTE-2.0.5/plugins/morris/morris.min.js') ?>" ></script>
<script src= "<?php echo base_url('assets/AdminLTE-2.0.5/plugins/sparkline/jquery.sparkline.min.js') ?>" ></script>
<script src= "<?php echo base_url('assets/AdminLTE-2.0.5/plugins/jvectormap/jquery-jvectormap-1.2.2.min.js') ?>" ></script>
<script src= "<?php echo base_url('assets/AdminLTE-2.0.5/plugins/jvectormap/jquery-jvectormap-world-mill-en.js') ?>" ></script>
<script src= "<?php echo base_url('assets/AdminLTE-2.0.5/plugins/daterangepicker/moment.min.js') ?>" ></script>
<script src= "<?php echo base_url('assets/AdminLTE-2.0.5/plugins/daterangepicker/daterangepicker.js') ?>" ></script>
<script src= "<?php echo base_url('assets/AdminLTE-2.0.5/plugins/timepicker/bootstrap-timepicker.min.js') ?>" ></script>
<script type="text/javascript">
$.LoadingOverlaySetup({
color : "rgba(255, 255, 255, 0.8)" ,
image : "<?php echo base_url('assets/img-sistem/loadingsistem.gif') ?>",
maxSize : "200px",
minSize : "200px",
resizeInterval : 0,
size : "100%"
});
</script>
| 57.111111 | 154 | 0.686284 |
fa116ab2dba71367016ae32a0d280ef1ceac0c7a | 11,082 | cxx | C++ | src/escape.cxx | jktjkt/replxx | 12f2adee7f9123880db1f870c360a88c1f7ba182 | [
"Apache-2.0"
] | 1 | 2019-06-11T06:49:15.000Z | 2019-06-11T06:49:15.000Z | src/escape.cxx | jktjkt/replxx | 12f2adee7f9123880db1f870c360a88c1f7ba182 | [
"Apache-2.0"
] | null | null | null | src/escape.cxx | jktjkt/replxx | 12f2adee7f9123880db1f870c360a88c1f7ba182 | [
"Apache-2.0"
] | 1 | 2019-06-10T16:48:55.000Z | 2019-06-10T16:48:55.000Z | #include "escape.hxx"
#include "io.hxx"
#include "keycodes.hxx"
#ifndef _WIN32
namespace replxx {
namespace EscapeSequenceProcessing { // move these out of global namespace
// This chunk of code does parsing of the escape sequences sent by various Linux
// terminals.
//
// It handles arrow keys, Home, End and Delete keys by interpreting the
// sequences sent by
// gnome terminal, xterm, rxvt, konsole, aterm and yakuake including the Alt and
// Ctrl key
// combinations that are understood by replxx.
//
// The parsing uses tables, a bunch of intermediate dispatch routines and a
// doDispatch
// loop that reads the tables and sends control to "deeper" routines to continue
// the
// parsing. The starting call to doDispatch( c, initialDispatch ) will
// eventually return
// either a character (with optional CTRL and META bits set), or -1 if parsing
// fails, or
// zero if an attempt to read from the keyboard fails.
//
// This is rather sloppy escape sequence processing, since we're not paying
// attention to what the
// actual TERM is set to and are processing all key sequences for all terminals,
// but it works with
// the most common keystrokes on the most common terminals. It's intricate, but
// the nested 'if'
// statements required to do it directly would be worse. This way has the
// advantage of allowing
// changes and extensions without having to touch a lot of code.
static char32_t thisKeyMetaCtrl = 0; // holds pre-set Meta and/or Ctrl modifiers
// This dispatch routine is given a dispatch table and then farms work out to
// routines
// listed in the table based on the character it is called with. The dispatch
// routines can
// read more input characters to decide what should eventually be returned.
// Eventually,
// a called routine returns either a character or -1 to indicate parsing
// failure.
//
char32_t doDispatch(char32_t c, CharacterDispatch& dispatchTable) {
for (unsigned int i = 0; i < dispatchTable.len; ++i) {
if (static_cast<unsigned char>(dispatchTable.chars[i]) == c) {
return dispatchTable.dispatch[i](c);
}
}
return dispatchTable.dispatch[dispatchTable.len](c);
}
// Final dispatch routines -- return something
//
static char32_t normalKeyRoutine(char32_t c) { return thisKeyMetaCtrl | c; }
static char32_t upArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | UP_ARROW_KEY;
}
static char32_t downArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | DOWN_ARROW_KEY;
}
static char32_t rightArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | RIGHT_ARROW_KEY;
}
static char32_t leftArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | LEFT_ARROW_KEY;
}
static char32_t homeKeyRoutine(char32_t) { return thisKeyMetaCtrl | HOME_KEY; }
static char32_t endKeyRoutine(char32_t) { return thisKeyMetaCtrl | END_KEY; }
static char32_t pageUpKeyRoutine(char32_t) {
return thisKeyMetaCtrl | PAGE_UP_KEY;
}
static char32_t pageDownKeyRoutine(char32_t) {
return thisKeyMetaCtrl | PAGE_DOWN_KEY;
}
static char32_t deleteCharRoutine(char32_t) {
return thisKeyMetaCtrl | ctrlChar('H');
} // key labeled Backspace
static char32_t deleteKeyRoutine(char32_t) {
return thisKeyMetaCtrl | DELETE_KEY;
} // key labeled Delete
static char32_t ctrlUpArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | UP_ARROW_KEY;
}
static char32_t ctrlDownArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | DOWN_ARROW_KEY;
}
static char32_t ctrlRightArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | RIGHT_ARROW_KEY;
}
static char32_t ctrlLeftArrowKeyRoutine(char32_t) {
return thisKeyMetaCtrl | CTRL | LEFT_ARROW_KEY;
}
static char32_t escFailureRoutine(char32_t) {
beep();
return -1;
}
// Handle ESC [ 1 ; 3 (or 5) <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket1Semicolon3or5Routines[] = {
upArrowKeyRoutine, downArrowKeyRoutine, rightArrowKeyRoutine,
leftArrowKeyRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket1Semicolon3or5Dispatch = {
4, "ABCD", escLeftBracket1Semicolon3or5Routines};
// Handle ESC [ 1 ; <more stuff> escape sequences
//
static char32_t escLeftBracket1Semicolon3Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
thisKeyMetaCtrl |= META;
return doDispatch(c, escLeftBracket1Semicolon3or5Dispatch);
}
static char32_t escLeftBracket1Semicolon5Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
thisKeyMetaCtrl |= CTRL;
return doDispatch(c, escLeftBracket1Semicolon3or5Dispatch);
}
static CharacterDispatchRoutine escLeftBracket1SemicolonRoutines[] = {
escLeftBracket1Semicolon3Routine, escLeftBracket1Semicolon5Routine,
escFailureRoutine};
static CharacterDispatch escLeftBracket1SemicolonDispatch = {
2, "35", escLeftBracket1SemicolonRoutines};
// Handle ESC [ 1 <more stuff> escape sequences
//
static char32_t escLeftBracket1SemicolonRoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket1SemicolonDispatch);
}
static CharacterDispatchRoutine escLeftBracket1Routines[] = {
homeKeyRoutine, escLeftBracket1SemicolonRoutine, escFailureRoutine};
static CharacterDispatch escLeftBracket1Dispatch = {2, "~;",
escLeftBracket1Routines};
// Handle ESC [ 3 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket3Routines[] = {deleteKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket3Dispatch = {1, "~",
escLeftBracket3Routines};
// Handle ESC [ 4 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket4Routines[] = {endKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket4Dispatch = {1, "~",
escLeftBracket4Routines};
// Handle ESC [ 5 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket5Routines[] = {pageUpKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket5Dispatch = {1, "~",
escLeftBracket5Routines};
// Handle ESC [ 6 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket6Routines[] = {pageDownKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket6Dispatch = {1, "~",
escLeftBracket6Routines};
// Handle ESC [ 7 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket7Routines[] = {homeKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket7Dispatch = {1, "~",
escLeftBracket7Routines};
// Handle ESC [ 8 <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracket8Routines[] = {endKeyRoutine,
escFailureRoutine};
static CharacterDispatch escLeftBracket8Dispatch = {1, "~",
escLeftBracket8Routines};
// Handle ESC [ <digit> escape sequences
//
static char32_t escLeftBracket0Routine(char32_t c) {
return escFailureRoutine(c);
}
static char32_t escLeftBracket1Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket1Dispatch);
}
static char32_t escLeftBracket2Routine(char32_t c) {
return escFailureRoutine(c); // Insert key, unused
}
static char32_t escLeftBracket3Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket3Dispatch);
}
static char32_t escLeftBracket4Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket4Dispatch);
}
static char32_t escLeftBracket5Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket5Dispatch);
}
static char32_t escLeftBracket6Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket6Dispatch);
}
static char32_t escLeftBracket7Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket7Dispatch);
}
static char32_t escLeftBracket8Routine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracket8Dispatch);
}
static char32_t escLeftBracket9Routine(char32_t c) {
return escFailureRoutine(c);
}
// Handle ESC [ <more stuff> escape sequences
//
static CharacterDispatchRoutine escLeftBracketRoutines[] = {
upArrowKeyRoutine, downArrowKeyRoutine, rightArrowKeyRoutine,
leftArrowKeyRoutine, homeKeyRoutine, endKeyRoutine,
escLeftBracket0Routine, escLeftBracket1Routine, escLeftBracket2Routine,
escLeftBracket3Routine, escLeftBracket4Routine, escLeftBracket5Routine,
escLeftBracket6Routine, escLeftBracket7Routine, escLeftBracket8Routine,
escLeftBracket9Routine, escFailureRoutine};
static CharacterDispatch escLeftBracketDispatch = {16, "ABCDHF0123456789",
escLeftBracketRoutines};
// Handle ESC O <char> escape sequences
//
static CharacterDispatchRoutine escORoutines[] = {
upArrowKeyRoutine, downArrowKeyRoutine, rightArrowKeyRoutine,
leftArrowKeyRoutine, homeKeyRoutine, endKeyRoutine,
ctrlUpArrowKeyRoutine, ctrlDownArrowKeyRoutine, ctrlRightArrowKeyRoutine,
ctrlLeftArrowKeyRoutine, escFailureRoutine};
static CharacterDispatch escODispatch = {10, "ABCDHFabcd", escORoutines};
// Initial ESC dispatch -- could be a Meta prefix or the start of an escape
// sequence
//
static char32_t escLeftBracketRoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escLeftBracketDispatch);
}
static char32_t escORoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escODispatch);
}
static char32_t setMetaRoutine(char32_t c); // need forward reference
static CharacterDispatchRoutine escRoutines[] = {escLeftBracketRoutine,
escORoutine, setMetaRoutine};
static CharacterDispatch escDispatch = {2, "[O", escRoutines};
// Initial dispatch -- we are not in the middle of anything yet
//
static char32_t escRoutine(char32_t c) {
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escDispatch);
}
static CharacterDispatchRoutine initialRoutines[] = {
escRoutine, deleteCharRoutine, normalKeyRoutine};
static CharacterDispatch initialDispatch = {2, "\x1B\x7F", initialRoutines};
// Special handling for the ESC key because it does double duty
//
static char32_t setMetaRoutine(char32_t c) {
thisKeyMetaCtrl = META;
if (c == 0x1B) { // another ESC, stay in ESC processing mode
c = readUnicodeCharacter();
if (c == 0) return 0;
return doDispatch(c, escDispatch);
}
return doDispatch(c, initialDispatch);
}
char32_t doDispatch(char32_t c) {
EscapeSequenceProcessing::thisKeyMetaCtrl = 0; // no modifiers yet at initialDispatch
return doDispatch(c, initialDispatch);
}
} // namespace EscapeSequenceProcessing // move these out of global namespace
}
#endif /* #ifndef _WIN32 */
| 35.748387 | 86 | 0.750135 |
05a52c3611b9bdbeb84510d540d913fc35bd1bc1 | 5,395 | py | Python | Modules/nonExecAnalyzer.py | A1S0N/Qu1cksc0pe | 5298b49dec4f3529d6050b64c6a63bbd05d1b582 | [
"Apache-2.0"
] | 255 | 2019-10-19T13:43:33.000Z | 2022-03-27T16:45:36.000Z | Modules/nonExecAnalyzer.py | 0x731/Qu1cksc0pe | 931e8d32370cdc74a85e5ce6ee98537ee5a26675 | [
"Apache-2.0"
] | 7 | 2021-02-21T19:21:18.000Z | 2022-03-31T15:19:23.000Z | Modules/nonExecAnalyzer.py | 0x731/Qu1cksc0pe | 931e8d32370cdc74a85e5ce6ee98537ee5a26675 | [
"Apache-2.0"
] | 54 | 2020-01-23T18:37:06.000Z | 2022-03-07T21:01:31.000Z | #!/usr/bin/python3
import os
import sys
# Checking for puremagic
try:
import puremagic as pr
except:
print("Error: >puremagic< module not found.")
sys.exit(1)
# Checking for colorama
try:
from colorama import Fore, Style
except:
print("Error: >colorama< not found.")
sys.exit(1)
# Checking for prettytable
try:
from prettytable import PrettyTable
except:
print("Error: >prettytable< module not found.")
sys.exit(1)
# Checking for oletools
try:
from oletools.olevba import VBA_Parser
from oletools.crypto import is_encrypted
from oletools.oleid import OleID
from olefile import isOleFile
except:
print("Error: >oletools< module not found.")
print("Try 'sudo -H pip3 install -U oletools' command.")
sys.exit(1)
# Colors
red = Fore.LIGHTRED_EX
cyan = Fore.LIGHTCYAN_EX
white = Style.RESET_ALL
green = Fore.LIGHTGREEN_EX
yellow = Fore.LIGHTYELLOW_EX
magenta = Fore.LIGHTMAGENTA_EX
# Legends
infoS = f"{cyan}[{red}*{cyan}]{white}"
errorS = f"{cyan}[{red}!{cyan}]{white}"
# Target file
targetFile = str(sys.argv[1])
# A function that finds VBA Macros
def MacroHunter(targetFile):
answerTable = PrettyTable()
answerTable.field_names = [f"{green}Threat Levels{white}", f"{green}Macros{white}", f"{green}Descriptions{white}"]
print(f"\n{infoS} Looking for VBA Macros...")
try:
fileData = open(targetFile, "rb").read()
vbaparser = VBA_Parser(targetFile, fileData)
macroList = list(vbaparser.analyze_macros())
if vbaparser.contains_macros == True:
for fi in range(0, len(macroList)):
if macroList[fi][0] == 'Suspicious':
if "(use option --deobf to deobfuscate)" in macroList[fi][2]:
sanitized = f"{macroList[fi][2]}".replace("(use option --deobf to deobfuscate)", "")
answerTable.add_row([f"{yellow}{macroList[fi][0]}{white}", f"{macroList[fi][1]}", f"{sanitized}"])
elif "(option --decode to see all)" in macroList[fi][2]:
sanitized = f"{macroList[fi][2]}".replace("(option --decode to see all)", "")
answerTable.add_row([f"{yellow}{macroList[fi][0]}{white}", f"{macroList[fi][1]}", f"{sanitized}"])
else:
answerTable.add_row([f"{yellow}{macroList[fi][0]}{white}", f"{macroList[fi][1]}", f"{macroList[fi][2]}"])
elif macroList[fi][0] == 'IOC':
answerTable.add_row([f"{magenta}{macroList[fi][0]}{white}", f"{macroList[fi][1]}", f"{macroList[fi][2]}"])
elif macroList[fi][0] == 'AutoExec':
answerTable.add_row([f"{red}{macroList[fi][0]}{white}", f"{macroList[fi][1]}", f"{macroList[fi][2]}"])
else:
answerTable.add_row([f"{macroList[fi][0]}", f"{macroList[fi][1]}", f"{macroList[fi][2]}"])
print(f"{answerTable}\n")
else:
print(f"{errorS} Not any VBA macros found.")
except:
print(f"{errorS} An error occured while parsing that file for macro scan.")
# Gathering basic informations
def BasicInfoGa(targetFile):
# Check for ole structures
if isOleFile(targetFile) == True:
print(f"{infoS} Ole File: {green}True{white}")
else:
print(f"{infoS} Ole File: {red}False{white}")
# Check for encryption
if is_encrypted(targetFile) == True:
print(f"{infoS} Encrypted: {green}True{white}")
else:
print(f"{infoS} Encrypted: {red}False{white}")
# VBA_MACRO scanner
vbascan = OleID(targetFile)
vbascan.check()
# Sanitizing the array
vba_params = []
for vb in vbascan.indicators:
vba_params.append(vb.id)
if "vba_macros" in vba_params:
for vb in vbascan.indicators:
if vb.id == "vba_macros":
if vb.value == True:
print(f"{infoS} VBA Macros: {green}Found{white}")
MacroHunter(targetFile)
else:
print(f"{infoS} VBA Macros: {red}Not Found{white}")
else:
MacroHunter(targetFile)
# A function that handles file types, extensions etc.
def MagicParser(targetFile):
# Defining table
resTable = PrettyTable()
# Magic byte parsing
resCounter = 0
resTable.field_names = [f"File Extension", "Names", "Byte Matches", "Confidence"]
resourceList = list(pr.magic_file(targetFile))
for res in range(0, len(resourceList)):
extrExt = str(resourceList[res].extension)
extrNam = str(resourceList[res].name)
extrByt = str(resourceList[res].byte_match)
if resourceList[res].confidence >= 0.8:
resCounter += 1
if extrExt == '':
resTable.add_row([f"{red}No Extension{white}", f"{red}{extrNam}{white}", f"{red}{extrByt}{white}", f"{red}{resourceList[res].confidence}{white}"])
else:
resTable.add_row([f"{red}{extrExt}{white}", f"{red}{extrNam}{white}", f"{red}{extrByt}{white}", f"{red}{resourceList[res].confidence}{white}"])
if len(resourceList) != 0:
print(resTable)
# Execution area
try:
BasicInfoGa(targetFile)
print(f"\n{infoS} Performing magic number analysis...")
MagicParser(targetFile)
except:
print(f"{errorS} An error occured while analyzing that file.")
sys.exit(1)
| 36.208054 | 162 | 0.606487 |
23b725b0b5a8a59161b2aa7455ae9ee471fd7f0f | 1,765 | js | JavaScript | tests/unit/config/routing.spec.js | bjaanes/ExtremeResults-WebApp | d15e2690c9879366e1e8ebd472c63c5b64e71a16 | [
"MIT"
] | 20 | 2015-08-20T13:27:05.000Z | 2020-09-05T18:21:44.000Z | tests/unit/config/routing.spec.js | bjaanes/ExtremeResults-WebApp | d15e2690c9879366e1e8ebd472c63c5b64e71a16 | [
"MIT"
] | 85 | 2015-06-29T12:20:34.000Z | 2016-08-07T12:51:17.000Z | tests/unit/config/routing.spec.js | bjaanes/ExtremeResults-WebApp | d15e2690c9879366e1e8ebd472c63c5b64e71a16 | [
"MIT"
] | 12 | 2016-10-02T12:17:43.000Z | 2020-10-06T17:24:31.000Z | import { module, inject } from "angular-mocks";
import "../../../app/config/config.module";
(function () {
'use strict';
describe('Routing Config', function () {
var stateProvider,
stateProviderData,
urlRouterProvider,
urlRouterProviderOtherwiseMethod,
state,
CoreTypes;
beforeEach(function () {
module('ui.router', function ($stateProvider, $urlRouterProvider) {
stateProvider = $stateProvider;
urlRouterProvider = $urlRouterProvider;
stateProviderData = {};
spyOn($stateProvider, 'state').and.callFake(function (stateName, stateConfig) {
stateProviderData[stateName] = stateConfig;
return $stateProvider;
});
spyOn($urlRouterProvider, 'otherwise').and.callFake(function (func) {
urlRouterProviderOtherwiseMethod = func;
});
});
});
beforeEach(module('xr.config'));
// Kick off the above function
beforeEach(inject(function (_CoreTypes_) {
CoreTypes = _CoreTypes_;
}));
it('should got to overview state when state on otherwise', function () {
var stateNameCalled;
var stateMock = {
go: function (stateName) {
stateNameCalled = stateName;
}
};
var injectorMock = {
get: function () {
return stateMock;
}
};
urlRouterProviderOtherwiseMethod(injectorMock);
expect(stateNameCalled).toBe('app.overview');
});
});
})(); | 30.431034 | 95 | 0.514448 |
da112fd35643290bdbb0e3713d4448e245bf3a84 | 8,726 | php | PHP | resources/views/rrhh/empleados/empresa/edit.blade.php | carlosmiranda96/AdvancedEnergy | f673b18b201f0a05ece5d15e156f970b886bb25d | [
"MIT"
] | null | null | null | resources/views/rrhh/empleados/empresa/edit.blade.php | carlosmiranda96/AdvancedEnergy | f673b18b201f0a05ece5d15e156f970b886bb25d | [
"MIT"
] | null | null | null | resources/views/rrhh/empleados/empresa/edit.blade.php | carlosmiranda96/AdvancedEnergy | f673b18b201f0a05ece5d15e156f970b886bb25d | [
"MIT"
] | null | null | null | @extends('plantilla')
@section('pagina')
<div class='container-fluid'>
<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-primary">Empleados</h1>
</div>
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary"><a href="{{route('empleados.index')}}" style="color: #2E9A73"><i class="fas fa-arrow-left"></i></a>   Información de empleado</h6>
</div>
<div class="card-body">
<form id="frmempleado" method="POST" action="{{route('empleadoempresa.update',$empleadoempresa->id)}}" enctype="multipart/form-data">
@csrf
@method('PUT')
<div class="row">
<div class="col-xl-2">
<div class="row mb-3">
<div class="col-6 offset-3 col-lg-3 offset-lg-4 col-xl-12 offset-xl-0">
<img id="fotoperfil" width="100%" src="{{asset(Storage::url('app/'.$empleados->foto))}}" class="img-thumbnail">
</div>
</div>
</div>
<div class="col-xl-10">
<h4 id="nombre" class="font-weight-bold text-primary">{{$empleados->nombreCompleto}}</h4>
<hr>
@include('rrhh/empleados/menu')
<div class="row">
<div class="col-12">
@if ($errors->any())
<div class="alert alert-danger alert-dismissible fade show mt-2" role="alert">
<ul class="m-0">
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@endif
@if (session('mensaje'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{session('mensaje')}}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
@endif
</div>
</div>
<div class="row">
<div class="col-12 mt-2">
<h5 class="font-weight-bold text-primary">Editar ubicación de trabajo</h5>
<hr>
</div>
<input hidden type="text" class="form-control" name="idempleado" value="{{$empleados->id}}" required/>
<div class="col-lg-6">
<div class="form-group">
<label>Empresa <span class="text-danger">*</span></label>
<select class="form-control" id="idempresa" name="idempresa" autofocus required>
<option value="0">Seleccione</option>
@foreach($empresas as $item)
<option @if($empleadoempresa->idempresa==$item->id) {{'selected'}} @endif value="{{$item->id}}">{{$item->nombreEmpresa}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Horario <span class="text-danger">*</span></label>
<select class="form-control" name="idgrupohorario" required>
<option value="0">Seleccione</option>
@foreach($horario as $item)
<option @if($empleadoempresa->idgrupohorario==$item->id) {{'selected'}} @endif value="{{$item->id}}">{{$item->nombre}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Cargo <span class="text-danger">*</span></label>
<select class="form-control" id="idcargo" name="idcargo" required>
<option value="0">Seleccione</option>
@foreach($cargo as $item)
<option @if($empleadoempresa->idcargo==$item->id) {{'selected'}} @endif value="{{$item->id}}">{{$item->cargo}}</option>
@endforeach
</select>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label>Salario</label>
<input value="{{$empleadoempresa->salario}}" type="text" class="form-control" name="salario"/>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<div class="form-check form-check-inline">
<input @if($empleadoempresa->horasextras=="1") {{'checked'}} @endif class="form-check-input" type="checkbox" id="inlineCheckbox3" value="1" name="horasextras">
<label class="form-check-label" for="inlineCheckbox3">Aplica a horas extras</label>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-12 mt-3">
<div class="form-group">
<a href="{{route('empleadoempresa.show',$empleados->id)}}"><div class="btn btn-sm btn-secondary"><i class="fas fa-times"></i> Cancelar</div></a>
<button class="btn btn-sm btn-warning"><i class="fas fa-save"></i> Actualizar</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
@stop
@section('script')
<script>
$("#idempresa").on("change",function(){
if(this.value){
$.ajax({
type:"GET",
dataType:"json",
data:"idempresa="+$(this).val(),
url:"{{route('cargos.empresa')}}",
success:function(r){
$("#idcargo").empty();
$("#idcargo").append('<option value="0">Seleccione</option>');
$.each(r,function(value,key){
$("#idcargo").append('<option value="'+key.id+'">'+key.cargo+'</option>');
});
},
error:function(){
alert("Error");
},
beforeSend:function(){
$("#idcargo").empty();
$("#idcargo").append('<option value="">Cargando...</option>');
$("#idcargo").empty();
$("#idcargo").append('<option value="">Seleccione</option>');
}
})
}else{
$("#idcargo").empty();
$("#idcargo").append('<option value="">Seleccione</option>');
}
});
</script>
@stop | 57.03268 | 200 | 0.370273 |
68cf45cc762b648d562ee818a1e734db7f7d5848 | 1,158 | dart | Dart | test/get_field_configuration_entity_response_test.dart | wondenge/fineract.dart | 472f5d60d345365b6c362c20bc3f6fbcf4aad622 | [
"Apache-2.0"
] | 1 | 2022-03-19T12:23:23.000Z | 2022-03-19T12:23:23.000Z | test/get_field_configuration_entity_response_test.dart | wondenge/fineract.dart | 472f5d60d345365b6c362c20bc3f6fbcf4aad622 | [
"Apache-2.0"
] | null | null | null | test/get_field_configuration_entity_response_test.dart | wondenge/fineract.dart | 472f5d60d345365b6c362c20bc3f6fbcf4aad622 | [
"Apache-2.0"
] | null | null | null | import 'package:openapi/api.dart';
import 'package:test/test.dart';
// tests for GetFieldConfigurationEntityResponse
void main() {
var instance = new GetFieldConfigurationEntityResponse();
group('test GetFieldConfigurationEntityResponse', () {
// int fieldConfigurationId (default value: null)
test('to test the property `fieldConfigurationId`', () async {
// TODO
});
// String entity (default value: null)
test('to test the property `entity`', () async {
// TODO
});
// String subentity (default value: null)
test('to test the property `subentity`', () async {
// TODO
});
// String field (default value: null)
test('to test the property `field`', () async {
// TODO
});
// String isEnabled (default value: null)
test('to test the property `isEnabled`', () async {
// TODO
});
// String isMandatory (default value: null)
test('to test the property `isMandatory`', () async {
// TODO
});
// String validationRegex (default value: null)
test('to test the property `validationRegex`', () async {
// TODO
});
});
}
| 24.125 | 66 | 0.610535 |
8b26846d8851fc638fc5203e1a43b8455f1231cb | 447 | lua | Lua | resources/[gameplay]/gus/admin_c.lua | AfuSensi/MTA-Resources | e4a0f3981ddc92c8f15c3d93140196c6a8589fa8 | [
"MIT",
"0BSD"
] | 18 | 2018-09-13T14:50:40.000Z | 2022-02-02T21:44:50.000Z | resources/[gameplay]/gus/admin_c.lua | AfuSensi/MTA-Resources | e4a0f3981ddc92c8f15c3d93140196c6a8589fa8 | [
"MIT",
"0BSD"
] | 151 | 2018-03-08T11:01:42.000Z | 2021-10-05T17:25:05.000Z | resources/[gameplay]/gus/admin_c.lua | AfuSensi/MTA-Resources | e4a0f3981ddc92c8f15c3d93140196c6a8589fa8 | [
"MIT",
"0BSD"
] | 111 | 2018-03-08T10:53:00.000Z | 2022-03-12T18:54:54.000Z | addEvent("onGameMessageSend2", true)
addEventHandler("onGameMessageSend2", root,
function(text, lang)
local URL = "http://translate.google.com/translate_tts?ie=UTF-8&tl=" .. lang .. "&q=" .. text
-- Play the TTS. BASS returns the sound element even if it can not be played.
-- playSound(URL) -- disabled to wait out google ban
end
)
addEvent("flash", true)
addEventHandler("flash", resourceRoot, function()
setWindowFlashing(true,0)
end)
| 31.928571 | 94 | 0.724832 |
bec8e0144a780ad7d3d93dddaf745cdc86b5782c | 802 | ts | TypeScript | projects/demo-integrations/cypress/tests/kit/multi-select/multi-select.spec.ts | Mu-L/taiga-ui | 6dabb28797762575b4d3a52f79188fb7ce35ce09 | [
"Apache-2.0"
] | null | null | null | projects/demo-integrations/cypress/tests/kit/multi-select/multi-select.spec.ts | Mu-L/taiga-ui | 6dabb28797762575b4d3a52f79188fb7ce35ce09 | [
"Apache-2.0"
] | null | null | null | projects/demo-integrations/cypress/tests/kit/multi-select/multi-select.spec.ts | Mu-L/taiga-ui | 6dabb28797762575b4d3a52f79188fb7ce35ce09 | [
"Apache-2.0"
] | null | null | null | import {
DEFAULT_TIMEOUT_BEFORE_ACTION,
MULTI_SELECT_PAGE_URL,
} from '../../../support/shared.entities';
describe('MultiSelect', () => {
beforeEach(() => {
cy.viewport('macbook-13');
cy.goToDemoPage(MULTI_SELECT_PAGE_URL);
cy.hideHeader();
});
it('does not overflow arrow icon by many tags', () => {
cy.get('#object-array').findByAutomationId('tui-doc-example').as('wrapper');
cy.get('@wrapper').find('tui-multi-select').click();
[0, 1, 2, 3].forEach(() => cy.get('[tuioption]').first().click());
cy.get('@wrapper').findByAutomationId('tui-multi-select__arrow').click();
cy.get('@wrapper')
.wait(DEFAULT_TIMEOUT_BEFORE_ACTION)
.matchImageSnapshot(`01-not-overflow-by-tags`);
});
});
| 29.703704 | 84 | 0.593516 |
0c6762de0f26cab83622c39ed3c57ead7336428c | 1,897 | kt | Kotlin | uisdk/src/main/java/com/karhoo/uisdk/screen/rides/detail/rating/RatingView.kt | karhoo/karhoo-android-ui-sdk | a6bc8a43463236cc2e8be97f5587ae6b21960507 | [
"BSD-2-Clause"
] | 8 | 2020-09-29T14:06:40.000Z | 2022-02-07T14:56:34.000Z | uisdk/src/main/java/com/karhoo/uisdk/screen/rides/detail/rating/RatingView.kt | karhoo/karhoo-android-ui-sdk | a6bc8a43463236cc2e8be97f5587ae6b21960507 | [
"BSD-2-Clause"
] | 11 | 2020-11-16T11:51:41.000Z | 2022-01-14T09:17:40.000Z | uisdk/src/main/java/com/karhoo/uisdk/screen/rides/detail/rating/RatingView.kt | karhoo/karhoo-android-ui-sdk | a6bc8a43463236cc2e8be97f5587ae6b21960507 | [
"BSD-2-Clause"
] | null | null | null | package com.karhoo.uisdk.screen.rides.detail.rating
import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import android.widget.RatingBar
import com.karhoo.sdk.api.model.TripInfo
import com.karhoo.uisdk.KarhooUISDK
import com.karhoo.uisdk.R
import com.karhoo.uisdk.screen.rides.feedback.FeedbackActivity
import kotlinx.android.synthetic.main.uisdk_view_star_rating.view.additionalFeedbackButton
import kotlinx.android.synthetic.main.uisdk_view_star_rating.view.labelLayout
import kotlinx.android.synthetic.main.uisdk_view_star_rating.view.ratingBar
import kotlinx.android.synthetic.main.uisdk_view_star_rating.view.ratingLabel
class RatingView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0)
: LinearLayout(context, attrs, defStyleAttr) {
var trip: TripInfo? = null
init {
View.inflate(context, R.layout.uisdk_view_star_rating, this)
additionalFeedbackButton.setOnClickListener {
(context as Activity).startActivity(FeedbackActivity.Builder.newBuilder()
.trip(trip)
.build(context))
}
ratingBar.setOnRatingBarChangeListener { _: RatingBar, rating: Float, _: Boolean ->
ratingLabel.visibility = View.VISIBLE
ratingLabel.setText(R.string.kh_uisdk_rating_submitted)
KarhooUISDK.analytics?.submitRating(tripId = trip?.tripId.orEmpty(), rating = rating)
}
}
fun showFeedbackSubmitted() {
ratingBar.visibility = View.GONE
labelLayout.visibility = View.GONE
additionalFeedbackButton.visibility = View.GONE
ratingLabel.setText(R.string.kh_uisdk_feedback_submitted)
}
}
| 37.196078 | 97 | 0.711123 |
bd31118b678c1f32eecabca1099785a94ae24067 | 876 | ddl | SQL | tools/test/h5repack/testfiles/dataregion.tdatareg.h5.ddl | hyoklee/hdf5 | d128e98a69039be58deeca9b737bf4b465b9756f | [
"BSD-3-Clause-LBNL"
] | 215 | 2020-04-27T17:08:20.000Z | 2022-03-09T14:36:37.000Z | tools/test/h5repack/testfiles/dataregion.tdatareg.h5.ddl | hyoklee/hdf5 | d128e98a69039be58deeca9b737bf4b465b9756f | [
"BSD-3-Clause-LBNL"
] | 562 | 2020-06-21T15:38:20.000Z | 2022-03-31T15:33:59.000Z | tools/test/h5repack/testfiles/dataregion.tdatareg.h5.ddl | hyoklee/hdf5 | d128e98a69039be58deeca9b737bf4b465b9756f | [
"BSD-3-Clause-LBNL"
] | 180 | 2020-04-30T17:05:42.000Z | 2022-03-31T16:04:26.000Z | HDF5 "out-dataregion.tdatareg.h5" {
GROUP "/" {
DATASET "Dataset1" {
DATATYPE H5T_REFERENCE { H5T_STD_REF_DSETREG }
DATASPACE SIMPLE { ( 4 ) / ( 4 ) }
STORAGE_LAYOUT {
CONTIGUOUS
SIZE 48
OFFSET 6244
}
FILTERS {
NONE
}
FILLVALUE {
FILL_TIME H5D_FILL_TIME_IFSET
VALUE H5D_FILL_VALUE_UNDEFINED
}
ALLOCATION_TIME {
H5D_ALLOC_TIME_LATE
}
}
DATASET "Dataset2" {
DATATYPE H5T_STD_U8BE
DATASPACE SIMPLE { ( 10, 10 ) / ( 10, 10 ) }
STORAGE_LAYOUT {
CONTIGUOUS
SIZE 100
OFFSET 2048
}
FILTERS {
NONE
}
FILLVALUE {
FILL_TIME H5D_FILL_TIME_IFSET
VALUE H5D_FILL_VALUE_UNDEFINED
}
ALLOCATION_TIME {
H5D_ALLOC_TIME_LATE
}
}
}
}
| 20.372093 | 53 | 0.530822 |
7fc74b57a1ae1b434d61ca59ec38815eb898f0eb | 3,391 | php | PHP | server/admin/cli/fix_deleted_users.php | woon5118/totara_ub | a38f8e5433c93d295f6768fb24e5eecefa8294cd | [
"PostgreSQL"
] | null | null | null | server/admin/cli/fix_deleted_users.php | woon5118/totara_ub | a38f8e5433c93d295f6768fb24e5eecefa8294cd | [
"PostgreSQL"
] | null | null | null | server/admin/cli/fix_deleted_users.php | woon5118/totara_ub | a38f8e5433c93d295f6768fb24e5eecefa8294cd | [
"PostgreSQL"
] | null | null | null | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This script fixed incorrectly deleted users.
*
* @package core
* @subpackage cli
* @copyright 2013 Petr Skoda (http://skodak.org)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define('CLI_SCRIPT', true);
require(__DIR__.'/../../config.php');
require_once($CFG->libdir.'/clilib.php');
// Now get cli options.
list($options, $unrecognized) = cli_get_params(array('help'=>false, 'purge'=>false),
array('h'=>'help'));
if ($unrecognized) {
$unrecognized = implode("\n ", $unrecognized);
cli_error(get_string('cliunknowoption', 'admin', $unrecognized));
}
if (empty($options['purge'])) {
$help = "Fix incorrectly deleted users.
This scripts detects users that are marked as deleted instead
of calling delete_user().
Deleted users must not have idnumber, roles, enrolments, group memberships, etc.
Please note this script does not delete any public information
such as forum posts.
Options:
--purge Purge leftovers after incorrectly deleted users
-h, --help Print out this help
Example:
\$sudo -u www-data /usr/bin/php admin/cli/fix_deleted_users.php --purge
";
echo $help;
die;
}
cli_heading('Purge leftovers after incorrectly deleted users');
// We cannot use delete_user() here, so delete the same data in bulk without any events
// because user context does not exist any more.
$DB->set_field('user', 'idnumber', '', array('deleted'=>1));
$DB->delete_records_select('role_assignments', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
$DB->delete_records_select('cohort_members', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
$DB->delete_records_select('groups_members', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
$DB->delete_records_select('user_enrolments', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
$DB->delete_records_select('user_preferences', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
$DB->delete_records_select('user_info_data', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
$DB->delete_records_select('user_lastaccess', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
$DB->delete_records_select('external_tokens', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
$DB->delete_records_select('external_services_users', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
$DB->delete_records_select('user_private_key', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
$DB->delete_records_select('my_pages', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
$DB->delete_records_select('sessions', "userid IN (SELECT id FROM {user} WHERE deleted = 1)");
cli_writeln('...done');
exit(0);
| 38.977011 | 109 | 0.714244 |
84f963cc55cd78345df04594a2561040258aad44 | 3,051 | cs | C# | TestConsolePublish/Program.cs | heyehang/DotNetCore.RabbitMQ.Extensions | db6e9ac5a82c8b2d991a9fb69cb9c2bff774ca2c | [
"Apache-2.0"
] | 11 | 2019-12-19T08:51:19.000Z | 2021-11-07T20:27:20.000Z | TestConsolePublish/Program.cs | heyehang/DotNetCore.RabbitMQ.Extensions | db6e9ac5a82c8b2d991a9fb69cb9c2bff774ca2c | [
"Apache-2.0"
] | null | null | null | TestConsolePublish/Program.cs | heyehang/DotNetCore.RabbitMQ.Extensions | db6e9ac5a82c8b2d991a9fb69cb9c2bff774ca2c | [
"Apache-2.0"
] | 5 | 2020-07-28T02:52:04.000Z | 2022-03-12T13:17:35.000Z | using Microsoft.Extensions.DependencyInjection;
using System;
using DotNetCore.RabbitMQ.Extensions;
using TestCommon;
using System.Collections.Generic;
using System.Linq;
namespace TestConsolePublish
{
class Program
{
static void Main(string[] args)
{
IServiceCollection services = new ServiceCollection();
services.AddLogging();
//连接池
services.AddSingleton<IConnectionChannelPool, TestAConnection>();
services.AddSingleton<IConnectionChannelPool, TestBConnection>();
services.AddSingleton<IConnectionChannelPool, TestCConnection>();
services.AddSingleton<IConnectionChannelPool, TestDConnection>();
//生产者
services.AddSingleton<TestAPublish>();
services.AddSingleton<TestBPublish>();
services.AddSingleton<TestCPublish>();
services.AddSingleton<TestDPublish>();
services.AddSingleton<TestEPublish>();
IServiceProvider serviceProvider = services.BuildServiceProvider();
//var testAPublish = serviceProvider.GetService<TestAPublish>();
//var testBPublish = serviceProvider.GetService<TestBPublish>();
//var testCPublish = serviceProvider.GetService<TestCPublish>();
var testDPublish = serviceProvider.GetService<TestDPublish>();
var testEPublish = serviceProvider.GetService<TestEPublish>();
#region 普通测试
//while (true)
//{
// Console.WriteLine("请输入要发送的消息:");
// var msg = Console.ReadLine();
// testAPublish.Publish(msg);
// Console.WriteLine($"发送的消息{msg}成功");
// Console.ReadKey();
//}
#endregion 普通测试
//#region 压力测试
//Console.WriteLine("准备压力测试,按任意键继续");
//Console.ReadKey();
//for (int i = 1; i < 10000; i++)
//{
// testPublish.Publish(i);
// Console.WriteLine($"发送第{i}消息成功");
//}
//Console.WriteLine("压力测试完成");
//Console.ReadKey();
//#endregion 压力测试
#region 测试单个实例多消费者
//while (true)
//{
// Console.WriteLine("请输入要发送的消息:");
// var msg = Console.ReadLine();
// testCPublish.Publish("测试单个实例多消费者");
// Console.WriteLine($"发送的消息{msg}成功");
// Console.ReadKey();
//}
#endregion 测试单个实例多消费者
while (true)
{
Console.WriteLine("请输入要发送的消息:");
var msg = Console.ReadLine();
//testEPublish.Publish("测试单个实例多消费者");
//testDPublish.Publish("测试单个实例多消费者");
testEPublish.PublishAsync("测试单个实例多消费者").Wait();
testDPublish.PublishAsync("测试单个实例多消费者").Wait();
// Console.WriteLine($"发送的消息{msg}成功");
Console.ReadKey();
}
}
}
}
| 34.280899 | 79 | 0.548345 |
a4a36c6f858bb70b74a205f5e2f7c908214d78e8 | 172 | php | PHP | config/home.php | lhy197/TP5141 | 0ca3004bbbd2fbad1021a93b5f0dbc9eaed5200a | [
"Apache-2.0"
] | null | null | null | config/home.php | lhy197/TP5141 | 0ca3004bbbd2fbad1021a93b5f0dbc9eaed5200a | [
"Apache-2.0"
] | null | null | null | config/home.php | lhy197/TP5141 | 0ca3004bbbd2fbad1021a93b5f0dbc9eaed5200a | [
"Apache-2.0"
] | null | null | null | <?php
//新加的文件针对配置里边的 场景配置
return [
'app_address' => 'home',
'database' => [
'password' => '1111111111'
]
]; | 19.111111 | 39 | 0.383721 |
dd82c6d3ba304d572420507ab4fb0f5dd2a5a725 | 4,628 | java | Java | src/main/java/walkingkooka/emulator/c64/Ciaa.java | mP1/walkingkooka-emulator-c64 | 1dfb307afe99b6b41cb2a818b9e602193fba43c6 | [
"Apache-2.0"
] | null | null | null | src/main/java/walkingkooka/emulator/c64/Ciaa.java | mP1/walkingkooka-emulator-c64 | 1dfb307afe99b6b41cb2a818b9e602193fba43c6 | [
"Apache-2.0"
] | 14 | 2019-09-17T06:47:03.000Z | 2019-09-19T10:49:31.000Z | src/main/java/walkingkooka/emulator/c64/Ciaa.java | mP1/walkingkooka-emulator-c64 | 1dfb307afe99b6b41cb2a818b9e602193fba43c6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Miroslav Pokorny (github.com/mP1)
*
* 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 walkingkooka.emulator.c64;
import java.util.EnumSet;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
/**
* The first CIA.
*/
final class Ciaa extends Cia {
/**
* Creates a {@link Ciaa}.
* Note the two {@link Consumer} are used to register listeners both key press and key release events after the AWT
* key codes have been translated into {@link HardwareMatrixKey keys}.
*/
static Ciaa with(final Consumer<Consumer<HardwareMatrixKey>> keyPress,
final Consumer<Consumer<HardwareMatrixKey>> keyRelease,
final Runnable interrupt) {
Objects.requireNonNull(keyPress, "keyPress");
Objects.requireNonNull(keyRelease, "keyRelease");
Objects.requireNonNull(interrupt, "interrupt");
return new Ciaa(keyPress,
keyRelease,
interrupt);
}
private Ciaa(final Consumer<Consumer<HardwareMatrixKey>> keyPress,
final Consumer<Consumer<HardwareMatrixKey>> keyRelease,
final Runnable interrupt) {
super(interrupt);
keyPress.accept(this.keysDown::add);
keyRelease.accept(this.keysDown::remove);
}
/**
* Tracks keys that are currently down or pressed; When the keyboard matrix is scanned the selected column/row
* will be used to retrieve keys that are "down".
*/
private final EnumSet<HardwareMatrixKey> keysDown = EnumSet.noneOf(HardwareMatrixKey.class);
// PRA
@Override
byte readDataPortA() {
return this.readKeyboardRowKeys();
}
// PRB
@Override
byte readDataPortB() {
return this.readKeyboardColumnKeys();
}
private byte readKeyboardRowKeys() {
return readKeyboardMatrix(this.dataDirectionPortB,
this.dataDirectionPortA,
this.dataPortB,
KEYS_IN_ROW,
KEY_COLUMN);
}
private final static Function<Bit, Set<HardwareMatrixKey>> KEYS_IN_ROW = HardwareMatrixKey::keysInRow;
private final static Function<HardwareMatrixKey, Bit> KEY_COLUMN = HardwareMatrixKey::column;
private byte readKeyboardColumnKeys() {
return this.readKeyboardMatrix(this.dataDirectionPortA,
this.dataDirectionPortB,
this.dataPortA,
KEYS_IN_COLUMN,
KEY_ROW);
}
private final static Function<Bit, Set<HardwareMatrixKey>> KEYS_IN_COLUMN = HardwareMatrixKey::keysInColumn;
private final static Function<HardwareMatrixKey, Bit> KEY_ROW = HardwareMatrixKey::row;
private byte readKeyboardMatrix(final byte outputs,
final byte inputs,
final byte selected,
final Function<Bit, Set<HardwareMatrixKey>> keysForLine,
final Function<HardwareMatrixKey, Bit> keySelect) {
byte value = -1;
for (Bit bit : Bit.values()) {
// OUTPUT when true, INPUT when false, COL/ROW selected when false
if (bit.read(outputs) && false == bit.read(inputs) && false == bit.read(selected)) {
// read all keys for COL $bit
for (HardwareMatrixKey key : keysForLine.apply(bit)) {
if (this.keysDown.contains(key)) {
value &= keySelect.apply(key).not(); // clear bit if key down
}
}
}
}
return value;
}
@Override
void writeDataPortA(final byte value) {
this.dataPortA = value;
}
/**
* A true selects that bit for output, and false for input
*/
private byte dataPortA;
@Override
void writeDataPortB(final byte value) {
this.dataPortB = value;
}
/**
* A true selects that bit for output, and false for input
*/
private byte dataPortB;
}
| 33.294964 | 119 | 0.625756 |
e72cda6362af3e5147389158d625b0b91ae01ae5 | 2,105 | php | PHP | resources/views/account/index.blade.php | Joe-Ford/laravel | 1addd9d286fc23618cd31add8ff977de8cda7544 | [
"MIT"
] | null | null | null | resources/views/account/index.blade.php | Joe-Ford/laravel | 1addd9d286fc23618cd31add8ff977de8cda7544 | [
"MIT"
] | null | null | null | resources/views/account/index.blade.php | Joe-Ford/laravel | 1addd9d286fc23618cd31add8ff977de8cda7544 | [
"MIT"
] | null | null | null | @extends('template')
@section('content')
<main>
<div class="col-lg-8 mx-auto p-3 py-md-5">
<h1>Welcome, {{\Auth::user()->name}}</h1>
<p class="fs-5 col-md-8">Quickly and easily get started with Bootstrap's compiled, production-ready files with this barebones example featuring some basic HTML and helpful links. Download all our examples to get started.</p>
<div class="mb-5">
<a href="{!! route('createBlog') !!}" class="btn btn-secondary btn-lg px-4">Create blog</a>
</div>
<hr class="col-3 col-md-2 mb-5">
<div class="row g-5">
<div class="col-md-6">
<h2>Starter projects</h2>
<p>Ready to beyond the starter template? Check out these open source projects that you can quickly duplicate to a new GitHub repository.</p>
<ul class="icon-list">
<li><a href="https://github.com/twbs/bootstrap-npm-starter" rel="noopener" target="_blank">Bootstrap npm starter</a></li>
<li class="text-muted">Bootstrap Parcel starter (coming soon!)</li>
</ul>
</div>
<div class="col-md-6">
<h2>Guides</h2>
<p>Read more detailed instructions and documentation on using or contributing to Bootstrap.</p>
<ul class="icon-list">
<li><a href="/docs/5.0/getting-started/introduction/">Bootstrap quick start guide</a></li>
<li><a href="/docs/5.0/getting-started/webpack/">Bootstrap Webpack guide</a></li>
<li><a href="/docs/5.0/getting-started/parcel/">Bootstrap Parcel guide</a></li>
<li><a href="/docs/5.0/getting-started/build-tools/">Contributing to Bootstrap</a></li>
</ul>
</div>
</div>
</div>
</main>
<br>
@if(\Auth::user()->isAdmin == 1)
<a href="{{ route('admin') }}">Admin Panel</a><br>
@endif
@endsection
| 50.119048 | 236 | 0.527316 |
147220cc44f053d860d551b4195f487d1ef76473 | 3,196 | ts | TypeScript | src/index.ts | smart-table/smart-table-filter | ec2fbe9609910e2a555469dac5a3dd488521b1c4 | [
"MIT"
] | 2 | 2017-02-02T13:15:12.000Z | 2019-11-02T22:27:10.000Z | src/index.ts | smart-table/smart-table-filter | ec2fbe9609910e2a555469dac5a3dd488521b1c4 | [
"MIT"
] | 2 | 2018-07-20T21:20:29.000Z | 2019-06-17T16:55:18.000Z | src/index.ts | smart-table/smart-table-filter | ec2fbe9609910e2a555469dac5a3dd488521b1c4 | [
"MIT"
] | 1 | 2019-06-15T02:49:43.000Z | 2019-06-15T02:49:43.000Z | import {compose} from 'smart-table-operators';
import {pointer} from 'smart-table-json-pointer';
enum Type {
BOOLEAN = 'boolean',
NUMBER = 'number',
DATE = 'date',
STRING = 'string'
}
type TypeOrAny = Type | any;
const typeExpression = (type: TypeOrAny): Function => {
switch (type) {
case Type.BOOLEAN:
return Boolean;
case Type.NUMBER:
return Number;
case Type.DATE:
return val => new Date(val);
case Type.STRING:
return compose(String, val => val.toLowerCase());
default:
return val => val;
}
};
export const enum FilterOperator {
INCLUDES = 'includes',
IS = 'is',
IS_NOT = 'isNot',
LOWER_THAN = 'lt',
GREATER_THAN = 'gt',
GREATER_THAN_OR_EQUAL = 'gte',
LOWER_THAN_OR_EQUAL = 'lte',
EQUALS = 'equals',
NOT_EQUALS = 'notEquals',
ANY_OF = 'anyOf'
}
const not = fn => input => !fn(input);
const is = value => input => Object.is(value, input);
const lt = value => input => input < value;
const gt = value => input => input > value;
const equals = value => input => value === input;
const includes = value => input => input.includes(value);
const anyOf = value => input => value.includes(input);
const operators = {
[FilterOperator.INCLUDES]: includes,
[FilterOperator.IS]: is,
[FilterOperator.IS_NOT]: compose(is, not),
[FilterOperator.LOWER_THAN]: lt,
[FilterOperator.GREATER_THAN_OR_EQUAL]: compose(lt, not),
[FilterOperator.GREATER_THAN]: gt,
[FilterOperator.LOWER_THAN_OR_EQUAL]: compose(gt, not),
[FilterOperator.EQUALS]: equals,
[FilterOperator.NOT_EQUALS]: compose(equals, not),
[FilterOperator.ANY_OF]: anyOf
};
const every = fns => (...args) => fns.every(fn => fn(...args));
export interface PredicateDefinition {
type?: TypeOrAny
operator?: FilterOperator,
value?: any
}
export const predicate = ({value = '', operator = FilterOperator.INCLUDES, type}: PredicateDefinition) => {
const typeIt = typeExpression(type);
const operateOnTyped = compose(typeIt, operators[operator]);
const predicateFunc = operateOnTyped(value);
return compose(typeIt, predicateFunc);
};
export interface FilterConfiguration {
[s: string]: PredicateDefinition[]
}
// Avoid useless filter lookup (improve perf)
const normalizeClauses = (conf: FilterConfiguration) => {
const output = {};
const validPath = Object.keys(conf).filter(path => Array.isArray(conf[path]));
validPath.forEach(path => {
const validClauses = conf[path].filter(c => c.value !== '');
if (validClauses.length > 0) {
output[path] = validClauses;
}
});
return output;
};
export const filter = <T>(filter: FilterConfiguration): (array: T[]) => T[] => {
const normalizedClauses = normalizeClauses(filter);
const funcList = Object.keys(normalizedClauses).map(path => {
const getter = pointer<T>(path).get;
const clauses = normalizedClauses[path].map(predicate);
return compose(getter, every(clauses));
});
const filterPredicate = every(funcList);
return array => array.filter(filterPredicate);
};
| 30.438095 | 107 | 0.640488 |
45c40cbba7fbf4153cd88078872458c8be136c0d | 2,071 | py | Python | model.py | Shangwei-ZHOU/Fuel_Cell_Diagnosis | 65aee8803dc0ef7e9cae54f104c5b5cca823d2b9 | [
"MIT"
] | null | null | null | model.py | Shangwei-ZHOU/Fuel_Cell_Diagnosis | 65aee8803dc0ef7e9cae54f104c5b5cca823d2b9 | [
"MIT"
] | null | null | null | model.py | Shangwei-ZHOU/Fuel_Cell_Diagnosis | 65aee8803dc0ef7e9cae54f104c5b5cca823d2b9 | [
"MIT"
] | null | null | null | import torch.nn as nn
import torch.nn.functional as F
input_number=100
class Fuel_Cell_Net_16800(nn.Module):
def __init__(self):
super(Fuel_Cell_Net_16800,self).__init__()
self.conv1 = nn.Conv1d(1, 64, 100, 10)
self.pool1 = nn.MaxPool1d(3, 2)
self.conv2 = nn.Conv1d(64, 32, 5, 10)
self.pool2 = nn.MaxPool1d(2, 2)
self.fc1 = nn.Linear(32 * 42, 512)
self.fc2 = nn.Linear(512, 64)
self.fc3 = nn.Linear(64, 3)
def forward(self,x):
x = F.relu(self.conv1(x))
x = self.pool1(x)
x = F.relu(self.conv2(x))
x = self.pool2(x)
x = x.view(-1, 32 * 42)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
class Fuel_Cell_Net_40000(nn.Module):
def __init__(self):
super(Fuel_Cell_Net_40000,self).__init__()
self.conv1=nn.Conv1d(1,64,100,10)
self.pool1 = nn.MaxPool1d(3, 2)
self.conv2 = nn.Conv1d(64, 32, 5,10)
self.pool2=nn.MaxPool1d(2,2)
self.fc1=nn.Linear(32*100,512)
self.fc2=nn.Linear(512,64)
self.fc3 = nn.Linear(64, 3)
def forward(self,x):
x=F.relu(self.conv1(x))
x = self.pool1(x)
x = F.relu(self.conv2(x))
x=self.pool2(x)
x=x.view(-1,32*100)
x=F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x=self.fc3(x)
return x
class Fuel_Cell_Net_10001(nn.Module):
def __init__(self):
super(Fuel_Cell_Net_10001,self).__init__()
self.conv1=nn.Conv1d(1,32,101,10)
self.pool1 = nn.MaxPool1d(3, 2)
self.conv2 = nn.Conv1d(32, 16, 5,10)
self.pool2=nn.MaxPool1d(2,2)
self.fc1=nn.Linear(16*25,256)
self.fc2=nn.Linear(256,64)
self.fc3 = nn.Linear(64, 3)
def forward(self,x):
x=F.relu(self.conv1(x))
x = self.pool1(x)
x = F.relu(self.conv2(x))
x=self.pool2(x)
x=x.view(-1,16*25)
x=F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x=self.fc3(x)
return x
| 30.910448 | 50 | 0.550459 |
a77910f4ec729ad1a5a7e3e8a8ab7a2873bc6a01 | 1,382 | dart | Dart | lib/bitly_exception.dart | HadesPTIT/flutter_url_shortener | 9afac39b8ee9b18a20d0ac536827eb069b875e48 | [
"MIT"
] | 2 | 2021-11-11T14:14:59.000Z | 2021-12-27T10:47:12.000Z | lib/bitly_exception.dart | HadesPTIT/flutter_url_shortener | 9afac39b8ee9b18a20d0ac536827eb069b875e48 | [
"MIT"
] | null | null | null | lib/bitly_exception.dart | HadesPTIT/flutter_url_shortener | 9afac39b8ee9b18a20d0ac536827eb069b875e48 | [
"MIT"
] | null | null | null | ///
/// [BitlyException]
///
class BitlyException implements Exception {
String? message;
String? description;
String? resource;
List<Errors>? errors;
BitlyException({
this.message,
this.description,
this.resource,
this.errors,
});
BitlyException.fromJson(Map<String, dynamic> json) {
message = json['message'];
description = json['description'];
resource = json['resource'];
if (json['errors'] != null) {
errors = <Errors>[];
json['errors'].forEach((v) {
errors!.add(Errors.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final data = Map<String, dynamic>();
data['message'] = this.message;
data['description'] = this.description;
data['resource'] = this.resource;
if (this.errors != null) {
data['errors'] = this.errors!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Errors {
String? field;
String? errorCode;
String? message;
Errors({this.field, this.errorCode, this.message});
Errors.fromJson(Map<String, dynamic> json) {
field = json['field'];
errorCode = json['error_code'];
message = json['message'];
}
Map<String, dynamic> toJson() {
final data = Map<String, dynamic>();
data['field'] = this.field;
data['error_code'] = this.errorCode;
data['message'] = this.message;
return data;
}
}
| 22.290323 | 68 | 0.606368 |
2316e8956d7f27a06adb211242b167182336dbc5 | 362 | css | CSS | src/app/emp-dash/create/create.component.css | angadsinghsandhu/-PROJECT-VMS_MEAN_STACK_APP | 470dd33d5c2432a51f0d06e27394a881b84ffb06 | [
"MIT"
] | null | null | null | src/app/emp-dash/create/create.component.css | angadsinghsandhu/-PROJECT-VMS_MEAN_STACK_APP | 470dd33d5c2432a51f0d06e27394a881b84ffb06 | [
"MIT"
] | 2 | 2020-09-18T02:53:20.000Z | 2020-09-20T13:42:19.000Z | src/app/emp-dash/edit/edit.component.css | angadsinghsandhu/-PROJECT-VMS_MEAN_STACK_APP | 470dd33d5c2432a51f0d06e27394a881b84ffb06 | [
"MIT"
] | null | null | null | .heading {
display: grid;
place-items: center;
grid-template-rows: auto 1fr auto;
}
.form {
width: 80%;
}
#nameId.ng-valid {
border: 5px solid green;
}
#nameId.ng-invalid {
border: 5px solid red;
}
.box-border {
border-radius: 25px;
border: 2px solid #73AD21;
padding: 20px;
width: 220px;
float: left;
height: 140px;
margin: 10px
}
| 12.928571 | 36 | 0.640884 |
2245e98afaeb77d2fa489a1015de6486440ae0e0 | 90 | sql | SQL | src/test/resources/sql/select/cc9f72aa.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 66 | 2018-06-15T11:34:03.000Z | 2022-03-16T09:24:49.000Z | src/test/resources/sql/select/cc9f72aa.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 13 | 2019-03-19T11:56:28.000Z | 2020-08-05T04:20:50.000Z | src/test/resources/sql/select/cc9f72aa.sql | Shuttl-Tech/antlr_psql | fcf83192300abe723f3fd3709aff5b0c8118ad12 | [
"MIT"
] | 28 | 2019-01-05T19:59:02.000Z | 2022-03-24T11:55:50.000Z | -- file:aggregates.sql ln:44 expect:true
select sum(null::int8) from generate_series(1,3)
| 30 | 48 | 0.766667 |
1a918edc8706e0a5cfb7506c5d0a498cbde8db36 | 576 | py | Python | programming/python-curso_em_video/exercises/ex075.py | carlosevmoura/courses-notes | dc938625dd79267f9a262e7e6939205f63dda885 | [
"MIT"
] | null | null | null | programming/python-curso_em_video/exercises/ex075.py | carlosevmoura/courses-notes | dc938625dd79267f9a262e7e6939205f63dda885 | [
"MIT"
] | null | null | null | programming/python-curso_em_video/exercises/ex075.py | carlosevmoura/courses-notes | dc938625dd79267f9a262e7e6939205f63dda885 | [
"MIT"
] | null | null | null | tupla = (
int(input('Digite um número: ')),
int(input('Digite outro número: ')),
int(input('Digite mais número: ')),
int(input('Digite o último número: '))
)
print('Você digitou os valores: {}'.format(tupla))
print('O número 9 apareceu {} vezes.'.format(tupla.count(9)))
if 3 in tupla:
print('O número 3 foi digitado pela primeira vez na pergunta {}.'.format(tupla.index(3)+1))
else:
print('O número 3 não foi digitado.')
print('Os números pares digitados foram: ', end='')
for numero in tupla:
if numero % 2 == 0:
print(numero, end=' ')
| 30.315789 | 95 | 0.635417 |
cf276364b425f2f72b1fa57390bc3a66c113060c | 9,065 | kt | Kotlin | test/common/src/main/kotlin/com.github.jcornaz.collekt.test/PersistentListTest.kt | jcornaz/collekt | c947530780c2d60f3800e6095b999cef67bce79b | [
"MIT"
] | 4 | 2018-06-05T07:44:41.000Z | 2019-05-26T11:03:58.000Z | test/common/src/main/kotlin/com.github.jcornaz.collekt.test/PersistentListTest.kt | jcornaz/collekt | c947530780c2d60f3800e6095b999cef67bce79b | [
"MIT"
] | 38 | 2018-05-28T08:15:42.000Z | 2019-03-26T09:25:58.000Z | test/common/src/main/kotlin/com.github.jcornaz.collekt.test/PersistentListTest.kt | jcornaz/collekt | c947530780c2d60f3800e6095b999cef67bce79b | [
"MIT"
] | null | null | null | package com.github.jcornaz.collekt.test
import com.github.jcornaz.collekt.api.PersistentListFactory
import com.github.jcornaz.collekt.api.of
import kotlin.test.*
public abstract class PersistentListTest : PersistentCollectionTest() {
public abstract override val factory: PersistentListFactory
@Test
fun shouldSupportDuplicateElements() {
assertEquals(4, factory.of(1, 2, 2, 3).size)
}
@Test
fun shouldBeAccessibleByIndex() {
val list = factory.of(1, 2, 2, 3)
assertEquals(1, list[0])
assertEquals(2, list[1])
assertEquals(2, list[2])
assertEquals(3, list[3])
}
@Test
fun wrongIndexShouldThrowIndexOutOfBoundException() {
val list = factory.of(1, 2, 2, 3)
assertFailsWith<IndexOutOfBoundsException> { list[-1] }
assertFailsWith<IndexOutOfBoundsException> { list[4] }
}
@Test
fun indexOfFirstShouldReturnTheFirstIndex() {
val list = factory.of(1, 2, 2, 3)
assertEquals(0, list.indexOf(1))
assertEquals(1, list.indexOf(2))
assertEquals(3, list.indexOf(3))
assertEquals(-1, list.indexOf(4))
}
@Test
fun lastIndexOfShouldReturnTheLastIndex() {
val list = factory.of(1, 2, 2, 3)
assertEquals(0, list.lastIndexOf(1))
assertEquals(2, list.lastIndexOf(2))
assertEquals(3, list.lastIndexOf(3))
assertEquals(-1, list.lastIndexOf(4))
}
@Test
fun iterationShouldPreserveOrder() {
val iterator = factory.of(1, 2, 3, 4).iterator()
assertTrue(iterator.hasNext())
assertEquals(1, iterator.next())
assertTrue(iterator.hasNext())
assertEquals(2, iterator.next())
assertTrue(iterator.hasNext())
assertEquals(3, iterator.next())
assertTrue(iterator.hasNext())
assertEquals(4, iterator.next())
assertFalse(iterator.hasNext())
}
@Test
fun reverseIterationShouldReturnElementsFromTheLastToTheFirst() {
val iterator = factory.of(1, 2, 3, 4).listIterator(4)
assertTrue(iterator.hasPrevious())
assertEquals(4, iterator.previous())
assertTrue(iterator.hasPrevious())
assertEquals(3, iterator.previous())
assertTrue(iterator.hasPrevious())
assertEquals(2, iterator.previous())
assertTrue(iterator.hasPrevious())
assertEquals(1, iterator.previous())
assertFalse(iterator.hasPrevious())
}
@Test
fun elementsInDifferentOrderShouldNotBeEquals() {
assertNotEquals(factory.of(1, 2, 3, 4), factory.of(1, 4, 3, 2))
assertNotEquals(factory.of(1, 2, 3, 4), factory.of(4, 3, 2, 1))
}
@Test
fun differentOccurrenceCountOfElementShouldNotBeEquals() {
assertNotEquals(factory.of(1, 2, 3, 3), factory.of(1, 2, 3))
assertNotEquals(factory.of(1, 2, 3, 3), factory.of(1, 2, 2, 3))
}
@Test
fun equivalentListShouldBeEqualsStdList() {
assertEquals(factory.of(1, 2, 3, 4), listOf(1, 2, 3, 4))
assertEquals(factory.of(1), listOf(1))
assertEquals(factory.of(), listOf<Int>())
assertEquals(factory.empty(), emptyList<Int>())
}
@Test
fun differentListShouldNotEqualsStdList() {
assertNotEquals(factory.of(1, 2, 3, 4), listOf(4, 3, 2, 1))
assertNotEquals(factory.of(1, 2, 2, 3), listOf(1, 2, 3))
assertNotEquals(factory.of(1, 2, 3), listOf(1, 2, 3, 3))
assertNotEquals(factory.of(1, 2, 3, 4), listOf(1, 2, 4))
assertNotEquals(factory.of(1, 2, 3, 4), emptyList<Int>())
assertNotEquals(factory.empty(), listOf(1))
}
@Test
fun hashCodeShouldBeConsistentWithStdList() {
assertEquals(listOf(1, 2, 3, 4).hashCode(), factory.of(1, 2, 3, 4).hashCode())
assertEquals(emptyList<Int>().hashCode(), factory.empty<Int>().hashCode())
}
@Test
fun subListShouldReturnElementsBetweenTheGivenIndexes() {
val subList = factory.of(1, 2, 3, 4).subList(1, 3)
assertEquals(factory.of(2, 3), subList)
assertFalse(subList.isEmpty())
assertFailsWith<IndexOutOfBoundsException> { subList[-1] }
assertEquals(2, subList[0])
assertEquals(3, subList[1])
assertFailsWith<IndexOutOfBoundsException> { subList[2] }
}
@Test
fun subListShouldReturnEmptyListWhenToIndexAndFromIndexAreEquals() {
assertEquals(factory.empty(), factory.empty<Int>().subList(0, 0))
assertEquals(factory.empty(), factory.of(1, 2, 3).subList(1, 1))
}
@Test
fun subListShouldReturnEquivalentListForIndexBetween0AndSize() {
assertEquals(factory.of(1, 2, 3), factory.of(1, 2, 3).subList(0, 3))
}
@Test
fun subListShouldThrowIndexOutOfBoundExceptionForWrongIndexes() {
assertFailsWith<IndexOutOfBoundsException> { factory.empty<Int>().subList(-1, 0) }
assertFailsWith<IndexOutOfBoundsException> { factory.empty<Int>().subList(0, 1) }
assertFailsWith<IndexOutOfBoundsException> { factory.of(1, 2, 3).subList(-1, 2) }
assertFailsWith<IndexOutOfBoundsException> { factory.of(1, 2, 3).subList(2, 4) }
assertFailsWith<IndexOutOfBoundsException> { factory.of(1, 2, 3).subList(2, 1) }
}
@Test
fun splitShouldReturnTwoLists() {
val source = factory.of(1, 2, 3, 4)
assertEquals(factory.of(1, 2) to factory.of(3, 4), source.split(2))
assertEquals(factory.empty<Int>() to factory.of(1, 2, 3, 4), source.split(0))
assertEquals(factory.of(1, 2, 3, 4) to factory.empty(), source.split(4))
}
@Test
fun splitShouldReturnTwoEmptyListsIfTheSourceIsEmpty() {
assertEquals(factory.empty<Int>() to factory.empty(), factory.empty<Int>().split(0))
}
@Test
fun splitShouldThrowIndexOutOfBoundExceptionForWrongIndexes() {
assertFailsWith<IndexOutOfBoundsException> { factory.empty<Int>().split(-1) }
assertFailsWith<IndexOutOfBoundsException> { factory.of(1, 2, 3).split(-1) }
assertFailsWith<IndexOutOfBoundsException> { factory.of(1, 2, 3).split(4) }
}
@Test
fun emptySubListShouldReturnEmptyList() {
val subList = factory.of(1, 2, 3, 4).subList(1, 1)
assertTrue(subList.isEmpty())
assertEquals(subList, factory.empty())
}
@Test
fun withShouldReturnCollectionWithTheElementReplaced() {
val source = factory.of(1, 2, 3)
val result = source.with(1, 4)
assertEquals(4, result[1])
assertEquals(result, factory.of(1, 4, 3))
assertEquals(2, source[1])
assertEquals(source, factory.of(1, 2, 3))
}
@Test
fun withShouldThrowIndexOutOfBoundIfIndexIsOutOfBound() {
assertFailsWith<IndexOutOfBoundsException> {
factory.empty<Int>().with(0, 1)
}
assertFailsWith<IndexOutOfBoundsException> {
factory.of(1, 2, 3).with(-1, 0)
}
assertFailsWith<IndexOutOfBoundsException> {
factory.of(1, 2, 3).with(3, 0)
}
}
@Test
fun plusAtIndexShouldReturnCollectionWithTheElement() {
val list1 = factory.empty<Int>()
val list2 = list1.plus(index = 0, element = 0)
val list3 = list2.plus(index = 0, element = 1)
val list4 = list3.plus(index = 1, element = 2)
assertTrue(list1.isEmpty())
assertEquals(0, list2[0])
assertEquals(0, list3[1])
assertEquals(0, list4[2])
assertEquals(1, list3[0])
assertEquals(1, list4[0])
assertEquals(2, list4[1])
assertEquals(factory.empty(), list1)
assertEquals(factory.of(0), list2)
assertEquals(factory.of(1, 0), list3)
assertEquals(factory.of(1, 2, 0), list4)
}
@Test
fun plusCollectionAtIndexShouldReturnACollectionWithTheGivenCollectionInsertedAtIndex() {
val col1 = factory.of(1, 2, 3)
val col2 = factory.of(4, 5, 6)
val result = col1.plus(1, col2)
assertEquals(factory.of(1, 2, 3), col1)
assertEquals(factory.of(4, 5, 6), col2)
assertEquals(factory.of(1, 4, 5, 6, 2, 3), result)
}
@Test
fun plusEmptyCollectionAtIndexShouldReturnAnEqualCollection() {
val col = factory.of(1, 2, 3)
assertEquals(col, col.plus(1, factory.empty()))
}
@Test
fun minusIndexShouldReturnACollectionWithoutTheUnderlingElement() {
val col = factory.of(1, 2, 3)
val result = col.minusIndex(1)
assertEquals(-1, result.indexOf(2))
assertEquals(factory.of(1, 2, 3), col)
assertEquals(factory.of(1, 3), result)
}
@Test
fun minusIndexShouldThrowIndexOutOfBoundForWrongIndexes() {
assertFailsWith<IndexOutOfBoundsException> { factory.empty<Int>().minusIndex(0) }
assertFailsWith<IndexOutOfBoundsException> { factory.empty<Int>().minusIndex(-1) }
assertFailsWith<IndexOutOfBoundsException> { factory.of(1, 2, 3).minusIndex(-1) }
assertFailsWith<IndexOutOfBoundsException> { factory.of(1, 2, 3).minusIndex(3) }
}
}
| 33.327206 | 93 | 0.637397 |
17e03e26fda66c7e600d8c5717cce210474183a7 | 58 | rb | Ruby | test/mailers/previews/user_mailer_preview.rb | ShehanAT/Quiz-Game | c4c6c2c5f0eade0529fabfca6b5a8e8262e40f2c | [
"MIT"
] | 4 | 2019-11-01T19:57:35.000Z | 2021-11-16T11:47:44.000Z | test/mailers/previews/user_mailer_preview.rb | ShehanAT/Quiz-Game | c4c6c2c5f0eade0529fabfca6b5a8e8262e40f2c | [
"MIT"
] | 12 | 2020-02-29T04:38:52.000Z | 2021-10-10T20:57:11.000Z | test/mailers/previews/user_mailer_preview.rb | ShehanAT/Quiz-Game | c4c6c2c5f0eade0529fabfca6b5a8e8262e40f2c | [
"MIT"
] | null | null | null | class UserMailerPreview < ActionMailer::Preview
end | 11.6 | 48 | 0.758621 |
e578158b2f9051a0091989f550565791a7d7c667 | 5,391 | lua | Lua | SmileBASIC/animations.lua | TheV360/Love2DSmileBASICLibrary | a2004e4adb79b4aa09567be27048c748c3f503a3 | [
"Unlicense"
] | 2 | 2018-11-30T06:20:11.000Z | 2020-06-08T03:12:09.000Z | SmileBASIC/animations.lua | TheV360/Love2DSmileBASICLibrary | a2004e4adb79b4aa09567be27048c748c3f503a3 | [
"Unlicense"
] | 4 | 2018-11-28T15:47:50.000Z | 2021-04-02T16:08:51.000Z | SmileBASIC/animations.lua | TheV360/Love2DSmileBASICLibrary | a2004e4adb79b4aa09567be27048c748c3f503a3 | [
"Unlicense"
] | 1 | 2018-11-27T02:58:13.000Z | 2018-11-27T02:58:13.000Z | -- Animations: Vague class that makes an object that updates specific SmileBASIC-related values.
-- Maybe also allow a generic animation mode? You pass a table reference, it updates it over time.
-- if self.type == nil then
-- end
Animations = {
Types = {
Offset = 0, XY = 0,
Depth = 1, Z = 1,
SourceImage = 2, UV = 2,
Definition = 3, I = 3,
Rotation = 4, R = 4,
Scale = 5, S = 5,
Color = 6, C = 6,
Variable = 7, V = 7
},
Lerp = function(t, a, b) return a + t * (b - a) end,
LerpF = function(f, t, a, b) return a + f(t) * (b - a) end,
Timing = {
Instant = function(t) return 1 end,
Linear = function(t) return t end,
Sine = function(t) return math.pow(math.sin(math.pi * .5 * t), 2) end,
Quadratic = function(t) return t * t end
}
}
function Animations.animationPart(time, item, timingFunction)
local r = {
time = time and math.abs(time) or 0,
item = item or {0},
timingFunction = timingFunction
}
if not timingFunction then
if time < 0 then
r.timingFunction = Animations.Timing.Linear
else
r.timingFunction = Animations.Timing.Instant
end
end
return r
end
function Animations.new(table, type, relative, keyframes, loop)
if table.type ~= "sprite" and (type == Animations.Types.UV or type == Animations.Types.I) then return nil end
local animation = {
table = table,
type = type,
relative = relative or false,
current = {
index = 1,
frames = 0,
endFrame = nil
},
keyframes = keyframes or {Animations.animationPart(1, 0, Animations.Timing.Instant)},
loop = loop or 1
}
-- Core
function animation:setup()
self.current.endFrame = self.keyframes[self.current.index].time
-- 0th element is a fake keyframe containing the initial state of the animation.
self.keyframes[0] = {item = self:getData()}
end
function animation:update()
self.current.frames = self.current.frames + 1
if self.current.frames > self.current.endFrame then
self.current.index = self.current.index + 1
if self.current.index > #self.keyframes then
if self.loop > 0 then
if self.loop > 1 then
self.loop = self.loop - 1
self.current.index = 1
else
self = nil
return
end
else
self.current.index = 1
end
end
self.current.endFrame = self.keyframes[self.current.index].time
self.current.frames = 1
end
self:applyData()
end
function animation:getData()
if self.type then
if self.type == Animations.Types.Offset then
return {self.table.x, self.table.y}
elseif self.type == Animations.Types.Depth then
return {self.table.z}
elseif self.type == Animations.Types.SourceImage then
return {self.table.u, self.table.v}
elseif self.type == Animations.Types.Definition then
return {self.table.lastUsedDefinition}
elseif self.type == Animations.Types.Rotation then
return {self.table._rotation}
elseif self.type == Animations.Types.Scale then
return self.table._scale
elseif self.type == Animations.Types.Color then
return self.table._color
elseif self.type == Animations.Types.Variable or self.type < 0 then
if self.type < 0 then
return {self.sb.variables[-self.type]}
else
return {self.sb.variables[8]}
end
end
else
local i, t = 0, {}
for i = 1, #self.table.map do
t[i] = self.table.data[self.table.map[i]]
end
return t
end
end
function animation:applyData()
if self.type then
if self.type == Animations.Types.Offset then
self.table.x = self:animate(1)
self.table.y = self:animate(2)
elseif self.type == Animations.Types.Depth then
self.table.z = self:animate(1)
elseif self.type == Animations.Types.SourceImage then
self.table.u = self:animate(1)
self.table.v = self:animate(2)
elseif self.type == Animations.Types.Definition then
self.table:useDefinition(math.floor(self:animate(1)))
elseif self.type == Animations.Types.Rotation then
self.table._rotation = self:animate(1)
elseif self.type == Animations.Types.Scale then
self.table._scale[1] = self:animate(1)
self.table._scale[2] = self:animate(2)
elseif self.type == Animations.Types.Color then
self.table._color[1] = self:animate(1)
self.table._color[2] = self:animate(2)
self.table._color[3] = self:animate(3)
self.table._color[4] = self:animate(4)
elseif self.type == Animations.Types.Variable or self.type < 0 then
if self.type < 0 then
self.table.variables[-self.type] = self:animate(1)
else
self.table.variables[8] = self:animate(1)
end
end
else
local i
for i = 1, #self.table.map do
self.table.data[self.table.map[i]] = self:animate(i)
end
end
end
function animation:animate(index)
local f = self.keyframes[self.current.index].timingFunction
local t = self.current.frames / self.current.endFrame
local a = 0
local b = self.keyframes[self.current.index].item[index]
if self.relative then
if self.current.index > 1 then
a = self.keyframes[self.current.index - 1].item[index]
end
return self.keyframes[0].item[index] + Animations.LerpF(f, t, a, b)
else
a = self.keyframes[self.current.index - 1].item[index]
return Animations.LerpF(f, t, a, b)
end
end
animation:setup()
return animation
end
| 28.225131 | 110 | 0.656279 |
e1f7a4e5a0aa517bd01bdae9ef3862fb1f5fd7cc | 860 | cpp | C++ | dp/mnemonic_search/demo/acwing901.cpp | Fanjunmin/algorithm-template | db0d37a7c9c37ee9a167918fb74b03d1d09b6fad | [
"MIT"
] | 1 | 2021-04-26T11:03:04.000Z | 2021-04-26T11:03:04.000Z | dp/mnemonic_search/demo/acwing901.cpp | Fanjunmin/algrithm-template | db0d37a7c9c37ee9a167918fb74b03d1d09b6fad | [
"MIT"
] | null | null | null | dp/mnemonic_search/demo/acwing901.cpp | Fanjunmin/algrithm-template | db0d37a7c9c37ee9a167918fb74b03d1d09b6fad | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstring>
using namespace std;
const int N = 310;
int r, c;
int h[N][N], f[N][N];
int dx[4] = {0, 0, -1, 1};
int dy[4] = {1, -1, 0, 0};
void init()
{
memset(f, -1, sizeof(h));
}
int dp(int x, int y)
{
int &t = f[x][y];
if(t != -1) return t;
t = 1; //初始为1
for (int i = 0; i < 4; ++i) {
int a = x + dx[i], b = y + dy[i];
if (a > 0 && a <= r && b > 0 && b <= c && h[a][b] < h[x][y]) {
t = max(t, 1 + dp(a, b));
}
}
return t;
}
int main()
{
cin >> r >> c;
for (int i = 1; i <= r; ++i) {
for (int j = 1; j <= c; ++j) {
cin >> h[i][j];
}
}
init();
int res = 0;
for (int i = 1; i <= r; ++i) {
for (int j = 1; j <= c; ++j) {
res = max(res, dp(i, j));
}
}
cout << res;
return 0;
} | 18.695652 | 70 | 0.359302 |
20e27aa907c8b2bd3b1cb2da4f56c1e64ba3db6e | 957 | py | Python | pyasciinet/asciinet/test/test_ascii.py | cosminbasca/asciinet | cec4d1f18d4c568622f3b51b9798c4502abf1cdc | [
"Apache-2.0"
] | 16 | 2016-08-24T05:08:36.000Z | 2021-10-06T08:00:16.000Z | pyasciinet/asciinet/test/test_ascii.py | cosminbasca/asciinet | cec4d1f18d4c568622f3b51b9798c4502abf1cdc | [
"Apache-2.0"
] | 5 | 2017-11-26T18:10:44.000Z | 2021-04-21T21:41:02.000Z | pyasciinet/asciinet/test/test_ascii.py | cosminbasca/asciinet | cec4d1f18d4c568622f3b51b9798c4502abf1cdc | [
"Apache-2.0"
] | 4 | 2017-01-15T20:03:36.000Z | 2018-05-03T11:51:45.000Z | #!/usr/bin/env python
#
# author: Cosmin Basca
#
# Copyright 2010 University of Zurich
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from asciinet import graph_to_ascii
from asciinet.test.base import BaseTestCase
__author__ = 'basca'
class TestClient(BaseTestCase):
def test_to_ascii(self):
ascii = graph_to_ascii(self.graph)
self.assertEqual(ascii.replace("\n", "").replace("\t", "").replace(" ", "").strip(), self.graph_repr)
| 31.9 | 109 | 0.732497 |
ef09961840a16c0cf658c8fc7a4fe40db9fab31e | 754 | h | C | tests/nbody-java/java_io_Flushable.h | albertobarri/idk | a250884f79e2a484251fc750bb915ecbc962be58 | [
"MIT"
] | 58 | 2015-01-05T04:40:48.000Z | 2021-12-17T06:01:28.000Z | tests/nbody-java/java_io_Flushable.h | albertobarri/idk | a250884f79e2a484251fc750bb915ecbc962be58 | [
"MIT"
] | 4 | 2019-08-19T13:07:10.000Z | 2020-10-17T02:45:04.000Z | tests/nbody-java/java_io_Flushable.h | albertobarri/idk | a250884f79e2a484251fc750bb915ecbc962be58 | [
"MIT"
] | 46 | 2015-01-03T06:20:54.000Z | 2020-04-18T13:32:52.000Z | #ifndef __JAVA_IO_FLUSHABLE__
#define __JAVA_IO_FLUSHABLE__
#include "xmlvm.h"
// Preprocessor constants for interfaces:
#define XMLVM_ITABLE_IDX_java_io_Flushable_flush__ 1
// Implemented interfaces:
// Super Class:
#include "java_lang_Object.h"
// Circular references:
XMLVM_DEFINE_CLASS(java_io_Flushable, 0, 0)
extern JAVA_OBJECT __CLASS_java_io_Flushable;
extern JAVA_OBJECT __CLASS_java_io_Flushable_1ARRAY;
extern JAVA_OBJECT __CLASS_java_io_Flushable_2ARRAY;
extern JAVA_OBJECT __CLASS_java_io_Flushable_3ARRAY;
#ifndef XMLVM_FORWARD_DECL_java_io_Flushable
#define XMLVM_FORWARD_DECL_java_io_Flushable
typedef struct java_io_Flushable java_io_Flushable;
#endif
void __INIT_java_io_Flushable();
void __INIT_IMPL_java_io_Flushable();
#endif
| 26 | 52 | 0.863395 |
46ed5fd8164638992e021d1946c58dbcea74e74c | 1,272 | py | Python | saleor/checkout/migrations/0044_fulfill_checkout_line_new_fields.py | Vultik/saleor | dc8548f7ad49cc26950dbfa0fd81f02617350240 | [
"CC-BY-4.0"
] | null | null | null | saleor/checkout/migrations/0044_fulfill_checkout_line_new_fields.py | Vultik/saleor | dc8548f7ad49cc26950dbfa0fd81f02617350240 | [
"CC-BY-4.0"
] | null | null | null | saleor/checkout/migrations/0044_fulfill_checkout_line_new_fields.py | Vultik/saleor | dc8548f7ad49cc26950dbfa0fd81f02617350240 | [
"CC-BY-4.0"
] | null | null | null | # Generated by Django 3.2.13 on 2022-04-29 08:51
from django.db import migrations
from django.db.models import F, OuterRef, Subquery
from django.contrib.postgres.functions import RandomUUID
from django.contrib.postgres.operations import CryptoExtension
def set_checkout_line_token_and_created_at(apps, _schema_editor):
CheckoutLine = apps.get_model("checkout", "CheckoutLine")
Checkout = apps.get_model("checkout", "Checkout")
CheckoutLine.objects.filter(token__isnull=True).update(
token=RandomUUID(),
created_at=Subquery(
Checkout.objects.filter(lines=OuterRef("id")).values("created_at")[:1]
),
)
def set_checkout_line_old_id(apps, schema_editor):
CheckoutLine = apps.get_model("checkout", "CheckoutLine")
CheckoutLine.objects.all().update(old_id=F("id"))
class Migration(migrations.Migration):
dependencies = [
("checkout", "0043_add_token_old_id_created_at_to_checkout_line"),
]
operations = [
CryptoExtension(),
migrations.RunPython(
set_checkout_line_token_and_created_at,
migrations.RunPython.noop,
),
migrations.RunPython(
set_checkout_line_old_id, reverse_code=migrations.RunPython.noop
),
]
| 30.285714 | 82 | 0.704403 |
1a366c8789231305e0120f90b43bdefd0735d291 | 7,096 | py | Python | paper/figures/figure_2/gene_overlap/genes.py | OmnesRes/pan_cancer | 1014511ee6fded405ac882bbb65e8ba7b1882127 | [
"MIT"
] | 3 | 2016-01-11T19:19:49.000Z | 2017-04-17T14:43:57.000Z | paper/figures/figure_2/gene_overlap/genes.py | OmnesRes/pan_cancer | 1014511ee6fded405ac882bbb65e8ba7b1882127 | [
"MIT"
] | null | null | null | paper/figures/figure_2/gene_overlap/genes.py | OmnesRes/pan_cancer | 1014511ee6fded405ac882bbb65e8ba7b1882127 | [
"MIT"
] | 4 | 2016-04-13T13:12:09.000Z | 2018-12-19T00:19:16.000Z | ##script for finding the overlap in the top 100 most significant genes in each cancer and plotting results
##load necessary modules
import pylab as plt
import numpy as np
import math
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
##I did not write this function, from http://depts.washington.edu/clawpack/clawpack-4.6.3/python/pyclaw/plotters/colormaps.py
##-------------------------
def make_colormap(colors):
##-------------------------
"""
Define a new color map based on values specified in the dictionary
colors, where colors[z] is the color that value z should be mapped to,
with linear interpolation between the given values of z.
The z values (dictionary keys) are real numbers and the values
colors[z] can be either an RGB list, e.g. [1,0,0] for red, or an
html hex string, e.g. "#ff0000" for red.
"""
from matplotlib.colors import LinearSegmentedColormap, ColorConverter
from numpy import sort
z = sort(colors.keys())
n = len(z)
z1 = min(z)
zn = max(z)
x0 = (z - z1) / (zn - z1)
CC = ColorConverter()
R = []
G = []
B = []
for i in range(n):
#i'th color at level z[i]:
Ci = colors[z[i]]
if type(Ci) == str:
# a hex string of form '#ff0000' for example (for red)
RGB = CC.to_rgb(Ci)
else:
# assume it's an RGB triple already:
RGB = Ci
R.append(RGB[0])
G.append(RGB[1])
B.append(RGB[2])
cmap_dict = {}
cmap_dict['red'] = [(x0[i],R[i],R[i]) for i in range(len(R))]
cmap_dict['green'] = [(x0[i],G[i],G[i]) for i in range(len(G))]
cmap_dict['blue'] = [(x0[i],B[i],B[i]) for i in range(len(B))]
mymap = LinearSegmentedColormap('mymap',cmap_dict)
return mymap
def compare3(first,second):
if float(first[-1])>float(second[-1]):
return 1
elif float(first[-1])<float(second[-1]):
return -1
else:
return 0
##get the 100 most significant genes for each cancer
f=open(os.path.join(BASE_DIR,'cox_regression','BLCA','coeffs_pvalues.txt'))
BLCA=[i.strip().split() for i in f]
BLCA.sort(cmp=compare3)
BLCA_dict_100={}
for i in BLCA[:100]:
BLCA_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','LGG','coeffs_pvalues.txt'))
LGG=[i.strip().split() for i in f]
LGG.sort(cmp=compare3)
LGG_dict_100={}
for i in LGG[:100]:
LGG_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','BRCA','coeffs_pvalues.txt'))
BRCA=[i.strip().split() for i in f]
BRCA.sort(cmp=compare3)
BRCA_dict_100={}
for i in BRCA[:100]:
BRCA_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','CESC','coeffs_pvalues.txt'))
CESC=[i.strip().split() for i in f]
CESC.sort(cmp=compare3)
CESC_dict_100={}
for i in CESC[:100]:
CESC_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','COAD','coeffs_pvalues.txt'))
COAD=[i.strip().split() for i in f]
COAD.sort(cmp=compare3)
COAD_dict_100={}
for i in COAD[:100]:
COAD_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','GBM','coeffs_pvalues.txt'))
GBM=[i.strip().split() for i in f]
GBM.sort(cmp=compare3)
GBM_dict_100={}
for i in GBM[:100]:
GBM_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','HNSC','coeffs_pvalues.txt'))
HNSC=[i.strip().split() for i in f]
HNSC.sort(cmp=compare3)
HNSC_dict_100={}
for i in HNSC[:100]:
HNSC_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','KIRC','coeffs_pvalues.txt'))
KIRC=[i.strip().split() for i in f]
KIRC.sort(cmp=compare3)
KIRC_dict_100={}
for i in KIRC[:100]:
KIRC_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','KIRP','coeffs_pvalues.txt'))
KIRP=[i.strip().split() for i in f]
KIRP.sort(cmp=compare3)
KIRP_dict_100={}
for i in KIRP[:100]:
KIRP_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','LAML','coeffs_pvalues.txt'))
LAML=[i.strip().split() for i in f]
LAML.sort(cmp=compare3)
LAML_dict_100={}
for i in LAML[:100]:
LAML_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','LIHC','coeffs_pvalues.txt'))
LIHC=[i.strip().split() for i in f]
LIHC.sort(cmp=compare3)
LIHC_dict_100={}
for i in LIHC[:100]:
LIHC_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','LUAD','coeffs_pvalues.txt'))
LUAD=[i.strip().split() for i in f]
LUAD.sort(cmp=compare3)
LUAD_dict_100={}
for i in LUAD[:100]:
LUAD_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','LUSC','coeffs_pvalues.txt'))
LUSC=[i.strip().split() for i in f]
LUSC.sort(cmp=compare3)
LUSC_dict_100={}
for i in LUSC[:100]:
LUSC_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','SKCM','coeffs_pvalues.txt'))
SKCM=[i.strip().split() for i in f]
SKCM.sort(cmp=compare3)
SKCM_dict_100={}
for i in SKCM[:100]:
SKCM_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','OV','coeffs_pvalues.txt'))
OV=[i.strip().split() for i in f]
OV.sort(cmp=compare3)
OV_dict_100={}
for i in OV[:100]:
OV_dict_100[i[0]]=''
f=open(os.path.join(BASE_DIR,'cox_regression','STAD','coeffs_pvalues.txt'))
STAD=[i.strip().split() for i in f]
STAD.sort(cmp=compare3)
STAD_dict_100={}
for i in STAD[:100]:
STAD_dict_100[i[0]]=''
all_cancers=[BLCA_dict_100,BRCA_dict_100,CESC_dict_100,COAD_dict_100,\
GBM_dict_100,HNSC_dict_100,KIRC_dict_100,KIRP_dict_100,LAML_dict_100,\
LGG_dict_100,LIHC_dict_100,LUAD_dict_100,LUSC_dict_100,OV_dict_100,\
SKCM_dict_100,STAD_dict_100]
final_array=[]
for i in all_cancers[::-1]:
temp=[]
for j in all_cancers[::-1]:
##compute overlap
temp.append(len([k for k in j if k in i]))
final_array.append(temp)
##create a custom colormap
blue_yellow_red = make_colormap({0:'w',.05:'#85A3E0',.1:'#3366CC',.2:'#00FF00',.3:'#FFFF66',0.4:'#FF9966', 1:'#CC3300'})
##plot
Z=np.array(final_array)
mask=np.tri(Z.shape[0],k=-1)
Z= np.ma.array(Z, mask=mask)
fig = plt.figure()
fig.subplots_adjust(bottom=.15)
fig.subplots_adjust(left=.15)
ax = fig.add_subplot(111)
figure=ax.imshow(Z,cmap=blue_yellow_red,interpolation="nearest")
cbar=fig.colorbar(figure,pad=.02)
cbar.ax.tick_params(labelsize=40)
cbar.set_label('number of genes', rotation=270,fontsize=80,labelpad=25)
ax.set_yticks([i for i in range(0,16)])
ax.set_yticklabels(['BLCA','BRCA','CESC','COAD','GBM','HNSC','KIRC','KIRP','LAML','LGG','LIHC','LUAD','LUSC','OV','SKCM','STAD'][::-1])
ax.tick_params(axis='y',labelsize=40)
ax.set_xticks([i for i in range(0,16)])
ax.set_xticklabels(['BLCA','BRCA','CESC','COAD','GBM','HNSC','KIRC','KIRP','LAML','LGG','LIHC','LUAD','LUSC','OV','SKCM','STAD'][::-1],rotation=90)
ax.tick_params(axis='x',labelsize=40)
ax.tick_params(axis='x',length=0,width=0)
ax.tick_params(axis='y',length=0,width=0)
ax.invert_yaxis()
ax.invert_xaxis()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
plt.show()
| 30.067797 | 147 | 0.660654 |
9ad424582423e4b7a60556fd5407c63f03381ecb | 415 | swift | Swift | iOSPruebaCeibaTests/Launch/Router/LaunchRouterTests.swift | xkiRox/iOSPruebCeiba | f85320f8c81fe0e3531a01ae60b09adf42b171c3 | [
"MIT"
] | null | null | null | iOSPruebaCeibaTests/Launch/Router/LaunchRouterTests.swift | xkiRox/iOSPruebCeiba | f85320f8c81fe0e3531a01ae60b09adf42b171c3 | [
"MIT"
] | null | null | null | iOSPruebaCeibaTests/Launch/Router/LaunchRouterTests.swift | xkiRox/iOSPruebCeiba | f85320f8c81fe0e3531a01ae60b09adf42b171c3 | [
"MIT"
] | null | null | null | //
// LaunchRouterTests.swift
// iOSPruebaCeibaTests
//
// Created by Hector Satizabal on 28/08/21.
//
import XCTest
@testable import iOSPruebaCeiba
class LaunchRouterTests: XCTestCase {
var router: LaunchRouter?
override func setUpWithError() throws {
router = LaunchRouter()
}
func testLaunchRouter_ShouldInitAppResponseReturnNotNil() throws {
router?.initApp()
}
}
| 18.863636 | 70 | 0.696386 |
324faf8b2d0daa910a8546a83dfd588c541a0586 | 1,175 | kts | Kotlin | protoBindings/build.gradle.kts | Dufuqan/provenance | 9c9b597ff767869941dfc52383c91f94c5a404e5 | [
"Apache-2.0"
] | 64 | 2021-01-31T04:05:41.000Z | 2022-03-26T01:56:54.000Z | protoBindings/build.gradle.kts | Dufuqan/provenance | 9c9b597ff767869941dfc52383c91f94c5a404e5 | [
"Apache-2.0"
] | 532 | 2021-01-28T02:03:23.000Z | 2022-03-31T08:24:08.000Z | protoBindings/build.gradle.kts | Dufuqan/provenance | 9c9b597ff767869941dfc52383c91f94c5a404e5 | [
"Apache-2.0"
] | 13 | 2021-03-05T00:51:27.000Z | 2022-03-29T14:28:22.000Z |
plugins {
/*
* Nexus publishing plugin cannot exist in sub projects.
* See https://github.com/gradle-nexus/publish-plugin/issues/81
*/
id(PluginIds.NexusPublish) version PluginVersions.NexusPublish
}
// Publishing
nexusPublishing {
repositories {
sonatype {
nexusUrl.set(uri(project.property("nexus.url") as String))
snapshotRepositoryUrl.set(uri(project.property("nexus.snapshot.repository.url") as String))
username.set(findProject(project.property("nexus.username") as String)?.toString() ?: System.getenv("OSSRH_USERNAME"))
password.set(findProject(project.property("nexus.password") as String)?.toString() ?: System.getenv("OSSRH_PASSWORD"))
stagingProfileId.set(project.property("nexus.staging.profile.id") as String) // prevents querying for the staging profile id, performance optimization
}
}
}
tasks.register<io.provenance.DownloadProtosTask>("downloadProtos") {
cosmosVersion = project.property("cosmos.version") as String?
wasmdVersion = project.property("wasmd.version") as String?
ibcVersion = project.property("ibc.version") as String?
}
| 41.964286 | 162 | 0.70383 |
74d424e03fc38a2f41674183f03b4980a35f6f28 | 78 | css | CSS | dfd/static/index.css | legnaleurc/dfd | 50f580c4cf2d6528a6df8310093aef2b0b7f2c08 | [
"MIT"
] | null | null | null | dfd/static/index.css | legnaleurc/dfd | 50f580c4cf2d6528a6df8310093aef2b0b7f2c08 | [
"MIT"
] | null | null | null | dfd/static/index.css | legnaleurc/dfd | 50f580c4cf2d6528a6df8310093aef2b0b7f2c08 | [
"MIT"
] | null | null | null | input {
width: 50em;
font-family: monospace;
font-size: medium;
}
| 13 | 27 | 0.602564 |
dde2c7b9de2026e09e0da43a511004f06e00d744 | 3,137 | java | Java | src/it/cnr/isti/vir/util/ListingFiles.java | ffalchi/it.cnr.isti.vir | 01632d09fa6b31edb84774966b5e2c6fcdb02786 | [
"BSD-2-Clause"
] | 9 | 2015-09-01T10:51:47.000Z | 2021-08-22T01:56:35.000Z | src/it/cnr/isti/vir/util/ListingFiles.java | ffalchi/it.cnr.isti.vir | 01632d09fa6b31edb84774966b5e2c6fcdb02786 | [
"BSD-2-Clause"
] | null | null | null | src/it/cnr/isti/vir/util/ListingFiles.java | ffalchi/it.cnr.isti.vir | 01632d09fa6b31edb84774966b5e2c6fcdb02786 | [
"BSD-2-Clause"
] | 6 | 2015-03-27T10:32:03.000Z | 2019-05-02T08:04:01.000Z | /*******************************************************************************
* Copyright (c) 2013, Fabrizio Falchi (NeMIS Lab., ISTI-CNR, Italy)
* All rights reserved.
*
* 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package it.cnr.isti.vir.util;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Collection;
public class ListingFiles {
public static File[] listFilesAsArray(
File directory,
FilenameFilter filter,
boolean recurse)
{
Collection<File> files = listFiles(directory, filter, recurse);
File[] arr = new File[files.size()];
return files.toArray(arr);
}
public static ArrayList<File> listFiles(
String dir,
String ext,
boolean recurse)
{
return listFiles(
new File(dir),
getFilenameFilter(ext),
recurse);
}
public static ArrayList<File> listFiles(
File directory,
String ext,
boolean recurse)
{
return listFiles( directory, getFilenameFilter(ext), recurse);
}
public static ArrayList<File> listFiles(
File directory,
FilenameFilter filter,
boolean recurse)
{
ArrayList<File> files = new ArrayList<File>();
File[] entries = directory.listFiles();
if ( entries == null ) return files;
for (File entry : entries)
{
if (filter == null || filter.accept(directory, entry.getName()))
{
files.add(entry);
}
if (recurse && entry.isDirectory())
{
files.addAll(listFiles(entry, filter, recurse));
}
}
return files;
}
public static FilenameFilter getFilenameFilter(String ext ) {
final String end = "." + ext;
return new FilenameFilter() {
public boolean accept(File dir, String name) {
String lowercaseName = name.toLowerCase();
if (lowercaseName.endsWith(end)) {
return true;
} else {
return false;
}
}
};
}
}
| 32.010204 | 757 | 0.686962 |
67ab9b7a2877c7f820aaf2c0e38f1ff7f423b40b | 4,622 | swift | Swift | HotChat/General/NavigationMap.swift | ilumanxi/HotChat | ab8cfdf83a3cc40bbb57232f19fbe261c972f367 | [
"MIT"
] | 1 | 2021-01-11T03:44:02.000Z | 2021-01-11T03:44:02.000Z | HotChat/General/NavigationMap.swift | ilumanxi/HotChat | ab8cfdf83a3cc40bbb57232f19fbe261c972f367 | [
"MIT"
] | null | null | null | HotChat/General/NavigationMap.swift | ilumanxi/HotChat | ab8cfdf83a3cc40bbb57232f19fbe261c972f367 | [
"MIT"
] | null | null | null | //
// NavigationMap.swift
// HotChat
//
// Created by 风起兮 on 2021/1/20.
// Copyright © 2021 风起兮. All rights reserved.
//
import SafariServices
import URLNavigator
extension Navigator {
static let share = Navigator()
}
func HotChatURLString(path: String) -> String {
return "\(Constant.hotChatScheme)://\(path)"
}
enum NavigationMap {
static func initialize(navigator: NavigatorType) {
navigator.register(HotChatURLString(path: "jump/recharge")) { url, values, context in
return WalletViewController()
}
navigator.register(HotChatURLString(path: "jump/bindingPhone")) { url, values, context in
return PhoneBindingController()
}
navigator.register(HotChatURLString(path: "jump/chatDetail")) { url, values, context in
guard let userId = url.queryParameters["userId"]
else { return nil }
let vc = ChatViewController(userID: userId, title: url.queryParameters["nick"] ?? "")
return vc
}
navigator.register(HotChatURLString(path: "jump/editProfile")) { url, values, context in
return UserInfoEditingViewController.loadFromStoryboard()
}
navigator.register(HotChatURLString(path: "jump/editLabel")) { url, values, context in
let vc = UserInfoLikeObjectViewController.loadFromStoryboard()
vc.onUpdated.delegate(on: vc) { (controller, _) in
controller.navigationController?.popViewController(animated: true)
}
vc.sex = LoginManager.shared.user!.sex
return vc
}
navigator.register(HotChatURLString(path: "jump/chatmatch")) { url, values, context in
return PairsViewController()
}
navigator.register(HotChatURLString(path: "jump/rankList")) { url, values, context in
return TopController()
}
navigator.register(HotChatURLString(path: "jump/editIntroduction")) { url, values, context in
return UserInfoInputTextViewController.loadFromStoryboard()
}
navigator.register(HotChatURLString(path: "jump/nameAuthentication")) { url, values, context in
if LoginManager.shared.user?.sex == .female {
return AnchorAuthenticationViewController()
}
else {
return RealNameAuthenticationViewController.loadFromStoryboard()
}
}
navigator.register(HotChatURLString(path: "jump/youthModel")) { url, values, context in
return YouthModelViewController()
}
navigator.handle(HotChatURLString(path: "jump/home"), self.home(navigator: navigator))
navigator.register("http://<path:_>", self.webViewControllerFactory)
navigator.register("https://<path:_>", self.webViewControllerFactory)
navigator.handle("navigator://alert", self.alert(navigator: navigator))
navigator.handle("navigator://<path:_>") { (url, values, context) -> Bool in
// No navigator match, do analytics or fallback function here
print("[Navigator] NavigationMap.\(#function):\(#line) - global fallback function is called")
return true
}
}
private static func webViewControllerFactory(
url: URLConvertible,
values: [String: Any],
context: Any?
) -> UIViewController? {
guard let url = url.urlValue else { return nil }
return WebViewController(url: url)
}
// tanliao://jump/home?index=1
private static func home(navigator: NavigatorType) -> URLOpenHandlerFactory {
return { url, values, context in
guard let indexStringValue = url.queryParameters["index"], let index = Int(indexStringValue) else { return false }
guard let tabBarController = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController else { return false }
guard let navigationController = tabBarController.selectedViewController as? UINavigationController else { return false }
navigationController.popToRootViewController(animated: false)
tabBarController.selectedIndex = index
return true
}
}
private static func alert(navigator: NavigatorType) -> URLOpenHandlerFactory {
return { url, values, context in
guard let title = url.queryParameters["title"] else { return false }
let message = url.queryParameters["message"]
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
navigator.present(alertController)
return true
}
}
}
| 32.780142 | 132 | 0.673085 |
aa5197ab3c2a059fcf9ba09b12ee75bf92cf45d4 | 2,441 | sh | Shell | misc/dist.sh | mhamann/estrella | aca6a68104cdc35c9112d3a559840e38fdc1a12a | [
"0BSD"
] | 1,052 | 2020-05-21T23:31:13.000Z | 2022-03-24T11:14:49.000Z | misc/dist.sh | mhamann/estrella | aca6a68104cdc35c9112d3a559840e38fdc1a12a | [
"0BSD"
] | 49 | 2020-05-22T17:26:06.000Z | 2022-02-11T06:22:36.000Z | misc/dist.sh | mhamann/estrella | aca6a68104cdc35c9112d3a559840e38fdc1a12a | [
"0BSD"
] | 36 | 2020-05-22T11:08:05.000Z | 2022-03-03T00:14:19.000Z | #!/bin/bash -e
cd "$(dirname "$0")/.."
_step() {
echo "———————————————————————————————————————————————————————————————————————————"
echo ">>> $@"
}
# Check version
_step "Checking version in package.json vs NPM"
ESTRELLA_VERSION=$(node -e 'process.stdout.write(require("./package.json").version)')
ESTRELLA_NPM_VERSION=$(npm show estrella version)
if [ "$ESTRELLA_NPM_VERSION" == "$ESTRELLA_VERSION" ]; then
echo "version in package.json needs to be updated ($ESTRELLA_VERSION is already published on NPM)" >&2
exit 1
fi
# Check fsevents dependency which must match that in chokidar.
# Chokidar is embedded/bundled with estrella but fsevents must be loaded at runtime as it
# contains platform-native code.
_step "Checking fsevents version in package.json"
CHOKIDAR_FSEVENTS_VERSION=$(node -e \
'process.stdout.write(require("./node_modules/chokidar/package.json").optionalDependencies["fsevents"])')
ESTRELLA_FSEVENTS_VERSION=$(node -e \
'process.stdout.write(require("./package.json").optionalDependencies["fsevents"])')
if [ "$CHOKIDAR_FSEVENTS_VERSION" != "$ESTRELLA_FSEVENTS_VERSION" ]; then
echo "The version of fsevents needs to be updated in package.json" >&2
echo "to match that required by chokidar. Change it to this:" >&2
echo " \"fsevents\": \"$CHOKIDAR_FSEVENTS_VERSION\"" >&2
echo >&2
exit 1
fi
# checkout products so that npm version doesn't fail.
# These are regenerated later anyways.
# TODO: exception for changes to dist/npm-postinstall.js which is not generated
_step "Resetting ./dist/ and checking for uncommitted changes"
git checkout -- dist
if ! (git diff-index --quiet HEAD --); then
echo "There are uncommitted changes:" >&2
git status -s --untracked-files=no --ignored=no
exit 1
fi
GIT_TREE_HASH=$(git rev-parse HEAD)
CLEAN_EXIT=false
_onexit() {
if $CLEAN_EXIT; then
exit
fi
if [ "$(git rev-parse HEAD)" != "$GIT_TREE_HASH" ]; then
echo "Rolling back git (to $GIT_TREE_HASH)"
git reset --hard "$GIT_TREE_HASH"
fi
}
trap _onexit EXIT
# build
_step "./build.js"
./build.js
# test
_step "./test/test.sh"
./test/test.sh
# publish to npm (fails and stops this script if the version is already published)
_step "npm publish"
npm publish
# commit, tag and push git
_step "git commit"
git commit -m "release v${ESTRELLA_VERSION}" dist package.json package-lock.json
git tag "v${ESTRELLA_VERSION}"
git push origin master "v${ESTRELLA_VERSION}"
CLEAN_EXIT=true
| 31.294872 | 107 | 0.70422 |
a195d534abc773122f14b652b8fdc1e739e6d5b0 | 779 | ts | TypeScript | packages/core/src/picker/picker.context.ts | Brain777777/taroify | 80cd4a5be874e7566af849ccca9fb95b233f577a | [
"MIT"
] | 1 | 2021-12-31T04:29:01.000Z | 2021-12-31T04:29:01.000Z | packages/core/src/picker/picker.context.ts | Brain777777/taroify | 80cd4a5be874e7566af849ccca9fb95b233f577a | [
"MIT"
] | null | null | null | packages/core/src/picker/picker.context.ts | Brain777777/taroify | 80cd4a5be874e7566af849ccca9fb95b233f577a | [
"MIT"
] | 1 | 2022-02-06T12:56:44.000Z | 2022-02-06T12:56:44.000Z | import { createContext } from "react"
import { SetRefCallback } from "../utils/state"
import { DEFAULT_SIBLING_COUNT, PickerColumnInstance, PickerOptionObject } from "./picker.shared"
interface PickerContextValue {
values?: any[]
readonly?: boolean
siblingCount: number
isMultiValue?(): boolean
getValueOptions?(): PickerOptionObject[]
setValueOptions?(option: PickerOptionObject, column: PickerOptionObject): void
setColumnRefs?: SetRefCallback<PickerColumnInstance>
clearColumnRefs?(): void
onChange?(values: any, option: PickerOptionObject, column: PickerOptionObject): void
onConfirm?(): void
onCancel?(): void
}
const PickerContext = createContext<PickerContextValue>({
siblingCount: DEFAULT_SIBLING_COUNT,
})
export default PickerContext
| 24.34375 | 97 | 0.768935 |
6dde88fb71f2bc5c0528ff0f433abaaf042863e0 | 2,377 | ts | TypeScript | src/graphql/root/subscription/price.ts | leesalminen/galoy | 8024d5c82eb56c3385a2d48d8eeb21d1e2b83eb4 | [
"MIT"
] | null | null | null | src/graphql/root/subscription/price.ts | leesalminen/galoy | 8024d5c82eb56c3385a2d48d8eeb21d1e2b83eb4 | [
"MIT"
] | null | null | null | src/graphql/root/subscription/price.ts | leesalminen/galoy | 8024d5c82eb56c3385a2d48d8eeb21d1e2b83eb4 | [
"MIT"
] | null | null | null | import { GT } from "@graphql/index"
import ExchangeCurrencyUnit from "@graphql/types/scalar/exchange-currency-unit"
import PricePayload from "@graphql/types/payload/price"
import { SAT_PRICE_PRECISION_OFFSET, SAT_USDCENT_PRICE } from "@config"
import SatAmount from "@graphql/types/scalar/sat-amount"
import pubsub from "@services/pubsub"
import { Prices } from "@app"
const PriceInput = new GT.Input({
name: "PriceInput",
fields: () => ({
amount: { type: GT.NonNull(SatAmount) },
amountCurrencyUnit: { type: GT.NonNull(ExchangeCurrencyUnit) },
priceCurrencyUnit: { type: GT.NonNull(ExchangeCurrencyUnit) },
}),
})
const PriceSubscription = {
type: GT.NonNull(PricePayload),
args: {
input: { type: GT.NonNull(PriceInput) },
},
resolve: (source, args) => {
if (source.errors) {
return { errors: source.errors }
}
const amountPriceInCents = args.input.amount * source.satUsdCentPrice
return {
errors: [],
price: {
formattedAmount: amountPriceInCents.toString(),
base: Math.round(amountPriceInCents * 10 ** SAT_PRICE_PRECISION_OFFSET),
offset: SAT_PRICE_PRECISION_OFFSET,
currencyUnit: "USDCENT",
},
}
},
subscribe: async (_, args) => {
const { amount, amountCurrencyUnit, priceCurrencyUnit } = args.input
const eventName = SAT_USDCENT_PRICE
for (const input of [amountCurrencyUnit, priceCurrencyUnit]) {
if (input instanceof Error) {
pubsub.publishImmediate(eventName, {
errors: [{ message: input.message }],
})
return pubsub.asyncIterator(eventName)
}
}
if (amountCurrencyUnit !== "BTCSAT" || priceCurrencyUnit !== "USDCENT") {
// For now, keep the only supported exchange price as SAT -> USD
pubsub.publishImmediate(eventName, {
errors: [{ message: "Unsupported exchange unit" }],
})
} else if (amount >= 1000000) {
// SafeInt limit, reject for now
pubsub.publishImmediate(eventName, {
errors: [{ message: "Unsupported exchange amount" }],
})
} else {
const satUsdPrice = await Prices.getCurrentPrice()
if (!(satUsdPrice instanceof Error)) {
pubsub.publishImmediate(eventName, { satUsdCentPrice: 100 * satUsdPrice })
}
}
return pubsub.asyncIterator(eventName)
},
}
export default PriceSubscription
| 32.121622 | 82 | 0.659655 |
9815c6450da8f51cd416b55a153dcf02fcc83ef8 | 1,796 | sql | SQL | guns-vip-main/src/main/sqls/container_menus.sql | wangyue033/AI-PLATFORM | be3438b75be3fe84d8cd17d3e69dbb3603367d1c | [
"MIT"
] | null | null | null | guns-vip-main/src/main/sqls/container_menus.sql | wangyue033/AI-PLATFORM | be3438b75be3fe84d8cd17d3e69dbb3603367d1c | [
"MIT"
] | null | null | null | guns-vip-main/src/main/sqls/container_menus.sql | wangyue033/AI-PLATFORM | be3438b75be3fe84d8cd17d3e69dbb3603367d1c | [
"MIT"
] | null | null | null | INSERT INTO `sys_menu`(`MENU_ID`, `CODE`, `PCODE`, `PCODES`, `NAME`, `ICON`, `URL`, `SORT`, `LEVELS`, `MENU_FLAG`, `DESCRIPTION`, `STATUS`, `NEW_PAGE_FLAG`, `OPEN_FLAG`, `SYSTEM_TYPE`, `CREATE_TIME`, `UPDATE_TIME`, `CREATE_USER`, `UPDATE_USER`) VALUES (1285033032529858561, 'CONTAINER', '0', '[0],', '服务容器', 'fa-star', '/container', 999, 1, 'Y', '', 'ENABLE', '', '', 'BASE_SYSTEM', '2020-07-20 10:05:24', '2020-07-20 10:05:24', 1, 1);
INSERT INTO `sys_menu`(`MENU_ID`, `CODE`, `PCODE`, `PCODES`, `NAME`, `ICON`, `URL`, `SORT`, `LEVELS`, `MENU_FLAG`, `DESCRIPTION`, `STATUS`, `NEW_PAGE_FLAG`, `OPEN_FLAG`, `SYSTEM_TYPE`, `CREATE_TIME`, `UPDATE_TIME`, `CREATE_USER`, `UPDATE_USER`) VALUES (1285033032529858562, 'CONTAINER_ADD', 'CONTAINER', '[0],[CONTAINER],', '服务容器添加', 'fa-star', '', 999, 2, 'N', '', 'ENABLE', '', '', 'BASE_SYSTEM', '2020-07-20 10:05:24', '2020-07-20 10:05:24', 1, 1);
INSERT INTO `sys_menu`(`MENU_ID`, `CODE`, `PCODE`, `PCODES`, `NAME`, `ICON`, `URL`, `SORT`, `LEVELS`, `MENU_FLAG`, `DESCRIPTION`, `STATUS`, `NEW_PAGE_FLAG`, `OPEN_FLAG`, `SYSTEM_TYPE`, `CREATE_TIME`, `UPDATE_TIME`, `CREATE_USER`, `UPDATE_USER`) VALUES (1285033032529858563, 'CONTAINER_EDIT', 'CONTAINER', '[0],[CONTAINER],', '服务容器修改', 'fa-star', '', 999, 2, 'N', '', 'ENABLE', '', '', 'BASE_SYSTEM', '2020-07-20 10:05:24', '2020-07-20 10:05:24', 1, 1);
INSERT INTO `sys_menu`(`MENU_ID`, `CODE`, `PCODE`, `PCODES`, `NAME`, `ICON`, `URL`, `SORT`, `LEVELS`, `MENU_FLAG`, `DESCRIPTION`, `STATUS`, `NEW_PAGE_FLAG`, `OPEN_FLAG`, `SYSTEM_TYPE`, `CREATE_TIME`, `UPDATE_TIME`, `CREATE_USER`, `UPDATE_USER`) VALUES (1285033032529858564, 'CONTAINER_DELETE', 'CONTAINER', '[0],[CONTAINER],', '服务容器删除', 'fa-star', '', 999, 2, 'N', '', 'ENABLE', '', '', 'BASE_SYSTEM', '2020-07-20 10:05:24', '2020-07-20 10:05:24', 1, 1);
| 359.2 | 454 | 0.629176 |
58d1d53a2c4542ae9adeedabc57f63771bc7de82 | 1,738 | css | CSS | js/style.css | jagadeeshshetty/jagadeeshshetty.github.io | 892ba4d9ce024c269a52442559f961f1888f7f76 | [
"MIT"
] | 3 | 2018-02-22T11:04:49.000Z | 2018-02-22T11:04:55.000Z | js/style.css | jagadeeshshetty/jagadeeshshetty.github.io | 892ba4d9ce024c269a52442559f961f1888f7f76 | [
"MIT"
] | null | null | null | js/style.css | jagadeeshshetty/jagadeeshshetty.github.io | 892ba4d9ce024c269a52442559f961f1888f7f76 | [
"MIT"
] | null | null | null |
body {
margin: 0px;
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
h1 {
font-family: Monaco, Trebuchet MS;
font-size: 4em;
margin-top: 8px;
margin-left: 38px;
margin-bottom: 2px;
text-align: left;
/*border-radius: 4px;
border: 1px solid #8E8E93;
width: 400px;
text-align: center;
-moz-box-shadow: 4px 4px 5px #888888;
-ms-box-shadow: 4px 4px 5px #888888;
-webkit-box-shadow: 4px 4px 5px #888888;
-o-box-shadow: 4px 4px 5px #888888;
box-shadow: 1px 1px 2px #888888;
*/
}
h4 {
font-family: Monaco, Trebuchet MS;
font-style: italic;
border-radius: 4px;
border: 1px solid #8E8E93;
width: 100px;
text-align: center;
-moz-box-shadow: 4px 4px 5px #888888;
-ms-box-shadow: 4px 4px 5px #888888;
-webkit-box-shadow: 4px 4px 5px #888888;
-o-box-shadow: 4px 4px 5px #888888;
box-shadow: 1px 1px 2px #888888;
margin-top: 10px;
margin-left: 10px;
}
h6 {
font-family: Monaco, Trebuchet MS;
text-align: right;
color: #CECED2;
margin-right: 10px;
}
img {
max-width: 99%;
max-height: 99%;
margin: 22px;
transition: all 300ms;
border-radius: 4px;
border: 1px solid #8E8E93;
box-shadow: 1px 1px 2px #888888;
padding: 4px;
}
img:hover {
transform: scale(1);
}
.blue-line {
display: inline-block;
width: 25%;
height: 4px;
background-color: #176BEF;
white-space: nowrap;
}
.red-line {
display: inline-block;
width: 25%;
height: 4px;
background-color: #FF3E30;
white-space: nowrap;
}
.yellow-line {
display: inline-block;
width: 25%;
height: 4px;
background-color: #F7B529;
white-space: nowrap;
}
.green-line {
display: inline-block;
width: 25%;
height: 4px;
background-color: #179C52;
white-space: nowrap;
}
| 17.207921 | 41 | 0.658803 |
3cebbaef721ba0c6805e88ee2b1c6d86a327bb27 | 454 | lua | Lua | Projects/GenerateDatas/convert_lua/mail.TbGlobalMail/23.lua | fanlanweiy/luban_examples | 9ddca2a01e8db1573953be3f32c59104451cd96e | [
"MIT"
] | 44 | 2021-05-06T06:16:55.000Z | 2022-03-30T06:27:25.000Z | Projects/ConvertDatas/convert_lua/mail.TbGlobalMail/23.lua | HFX-93/luban_examples | 5b90e392d404950d12ff803a186b26bdea5e0292 | [
"MIT"
] | 1 | 2021-07-25T16:35:32.000Z | 2021-08-23T04:59:49.000Z | Projects/ConvertDatas/convert_lua/mail.TbGlobalMail/23.lua | HFX-93/luban_examples | 5b90e392d404950d12ff803a186b26bdea5e0292 | [
"MIT"
] | 14 | 2021-06-09T10:38:59.000Z | 2022-03-30T06:27:24.000Z | return {
id = 23,
title = "",
sender = "系统",
content = "测试内容3",
award = {
1,
},
all_server = false,
server_list = {
1,
},
platform = "1",
channel = "1",
min_max_level = {
min = 50,
max = 60,
},
register_time = {
date_time_range = {
end_time = 2020-5-17 00:00:00,
},
},
mail_time = {
date_time_range = {
},
},
} | 16.214286 | 42 | 0.398678 |
cc2de2124cd42be90fa613093dc80048d95c8847 | 473 | rb | Ruby | spec/core_ext/integer_spec.rb | ramonbrugman/nightly | 76653fa742b5e6101d132376f8fbd6fe7dc5ac53 | [
"MIT"
] | 196 | 2015-02-28T02:12:38.000Z | 2022-03-25T04:47:13.000Z | spec/core_ext/integer_spec.rb | ramonbrugman/nightly | 76653fa742b5e6101d132376f8fbd6fe7dc5ac53 | [
"MIT"
] | 29 | 2015-02-27T22:19:13.000Z | 2021-09-25T10:06:41.000Z | spec/core_ext/integer_spec.rb | ramonbrugman/nightly | 76653fa742b5e6101d132376f8fbd6fe7dc5ac53 | [
"MIT"
] | 22 | 2015-03-01T04:14:13.000Z | 2022-02-07T14:14:08.000Z | require_relative "../../lib/core_ext/integer"
RSpec.describe "String extensions" do
describe "#comma_separated" do
it "converts to comma separated string" do
expect(0.comma_separated).to eq "0"
expect(23.comma_separated).to eq "23"
expect(134.comma_separated).to eq "134"
expect(1234.comma_separated).to eq "1,234"
expect(48955.comma_separated).to eq "48,955"
expect(1_000_000.comma_separated).to eq "1,000,000"
end
end
end
| 31.533333 | 57 | 0.69556 |
a31262c729868bcef5ae74f4f79d7451fb5c532c | 1,254 | h | C | T9 Trie/trie.h | dray92/Programming-Questions | d04def011f9a1221e9438eafd754cec243397b18 | [
"MIT"
] | 8 | 2016-02-10T09:39:11.000Z | 2019-05-14T17:24:22.000Z | T9 Trie/trie.h | dray92/Programming-Questions | d04def011f9a1221e9438eafd754cec243397b18 | [
"MIT"
] | null | null | null | T9 Trie/trie.h | dray92/Programming-Questions | d04def011f9a1221e9438eafd754cec243397b18 | [
"MIT"
] | 5 | 2016-08-25T06:44:52.000Z | 2021-06-08T06:06:02.000Z | /*
Vishesh Sood [1239599]
CSE 374 Homework 4
02/12/2016
trie.h
This is my trie header file. It creates the required
structs and also prototypes my functions in the main file.
*/
#ifndef TRIE_H
#include <stdbool.h>
#define TRIE_H
#define NUM_SIZE 8 /* 2,3,4,5,6,7,8,9 */
#define LETTERS_SIZE 26
extern char MAP[]; // externed to prevent conflicts
// WordList struct
typedef struct Words WordList;
struct Words {
char *word;
WordList *next;
};
// Trie_Node struct
typedef struct Trie_Node Trie_Node_t;
struct Trie_Node {
Trie_Node_t *children[NUM_SIZE];
WordList *words;
};
// Trie struct
typedef struct Trie Trie_t;
struct Trie {
Trie_Node_t *root;
};
// Prototype functions in main file
Trie_t *initializeTrie(void);
Trie_Node_t *getNode(void);
WordList* getWordListNode(char word[]);
void freeWordsList(WordList *words);
// following prototypes are indirectly accessed by t9.c
// externed to prevent conflicts
extern void insertWord(Trie_t *root, char word[]);
extern void addWordToList(Trie_Node_t *node, char word[]);
extern WordList* searchWord(Trie_t *Trie, char digitSequence[]);
extern char charToDigit(char ch);
extern bool listContains(WordList *list, char *word);
extern void freeNode(Trie_Node_t *node);
#endif
| 22 | 64 | 0.747209 |
fa6517eb1dc938de28986b63d518964e926f9de0 | 9,312 | swift | Swift | Sources/GosenKit/MultiPatch.swift | coniferprod/GosenKit | 9823e8bc105859dc043c96ac1abc42a7c3bf8905 | [
"MIT"
] | null | null | null | Sources/GosenKit/MultiPatch.swift | coniferprod/GosenKit | 9823e8bc105859dc043c96ac1abc42a7c3bf8905 | [
"MIT"
] | null | null | null | Sources/GosenKit/MultiPatch.swift | coniferprod/GosenKit | 9823e8bc105859dc043c96ac1abc42a7c3bf8905 | [
"MIT"
] | null | null | null | import Foundation
/// A Kawai K5000 multi patch (combi on the K5000W).
public struct MultiPatch: Codable {
public static let sectionCount = 4
/// Common settings for multi patch.
public struct Common: Codable {
public static let dataLength = 54
static let geqBandCount = 7
static let nameLength = 8
public var effects: EffectSettings
public var geq: [Int]
public var name: String
public var volume: UInt
public var sectionMutes: [Bool]
public var effectControl1: EffectControl
public var effectControl2: EffectControl
/// Initializes the common part of a multi patch from MIDI System Exclusive data.
/// - Parameter d: A byte array with the System Exclusive data.
public init(data d: ByteArray) {
var offset: Int = 0
var b: Byte = 0
let effectData = d.slice(from: offset, length: EffectSettings.dataLength)
effects = EffectSettings(data: effectData)
offset += EffectSettings.dataLength
geq = [Int]()
for _ in 0..<SinglePatch.Common.geqBandCount {
b = d.next(&offset)
let v: Int = Int(b) - 64 // 58(-6) ~ 70(+6), so 64 is zero
//print("GEQ band \(i + 1): \(b) --> \(v)")
geq.append(Int(v))
}
offset += Common.geqBandCount
name = String(data: Data(d.slice(from: offset, length: Common.nameLength)), encoding: .ascii) ?? "--------"
offset += Common.nameLength
b = d.next(&offset)
volume = UInt(b)
b = d.next(&offset)
// Unpack the section mutes into a Bool array. Spec says "0:mute".
sectionMutes = [Bool]()
sectionMutes.append(b.isBitSet(0) ? false : true)
sectionMutes.append(b.isBitSet(1) ? false : true)
sectionMutes.append(b.isBitSet(2) ? false : true)
sectionMutes.append(b.isBitSet(3) ? false : true)
let effectControl1Data = d.slice(from: offset, length: EffectControl.dataLength)
effectControl1 = EffectControl(data: effectControl1Data)
offset += EffectControl.dataLength
let effectControl2Data = d.slice(from: offset, length: EffectControl.dataLength)
effectControl2 = EffectControl(data: effectControl2Data)
}
}
/// One section of a multi patch.
public struct Section: Codable {
public static let dataLength = 12
public var singlePatchNumber: UInt
public var volume: UInt
public var pan: Int
public var effectPath: UInt
public var transpose: Int
public var tune: Int
public var zone: Zone
public var velocitySwitch: VelocitySwitch
public var receiveChannel: UInt8
/// Initializes a multi section from MIDI System Exclusive data.
/// - Parameter d: A byte array with the System Exclusive data.
public init(data d: ByteArray) {
var offset: Int = 0
var b: Byte = 0
b = d.next(&offset)
let instrumentMSB = b
b = d.next(&offset)
let instrumentLSB = b
let instrumentMSBString = String(instrumentMSB, radix: 2).pad(with: "0", toLength: 2)
let instrumentLSBString = String(instrumentLSB, radix: 2).pad(with: "0", toLength: 7)
let bitString = instrumentMSBString + instrumentLSBString
// now we should have a 9-bit binary string, convert it to a decimal number
singlePatchNumber = UInt(bitString, radix: 2)!
b = d.next(&offset)
volume = UInt(b)
b = d.next(&offset)
pan = Int(b)
b = d.next(&offset)
effectPath = UInt(b)
b = d.next(&offset)
transpose = Int(b) - 64 // SysEx 40~88 to -24~+24
b = d.next(&offset)
tune = Int(b) - 64 // SysEx 1~127 to -63...+63
b = d.next(&offset)
let zoneLow = b
b = d.next(&offset)
let zoneHigh = b
zone = Zone(high: Key(note: Int(zoneHigh)), low: Key(note: Int(zoneLow)))
var velocitySwitchBytes = ByteArray()
b = d.next(&offset)
velocitySwitchBytes.append(b)
b = d.next(&offset)
velocitySwitchBytes.append(b)
velocitySwitch = VelocitySwitch(data: velocitySwitchBytes)
b = d.next(&offset)
receiveChannel = b
}
}
/// Multi patch common settings.
public var common: Common
/// Multi patch sections.
public var sections: [Section]
/// Initializes a multi patch from MIDI System Exclusive data.
/// - Parameter d: A byte array with the System Exclusive data.
public init(data d: ByteArray) {
var offset: Int = 0
common = Common(data: d)
offset += Common.dataLength
sections = [Section]()
for _ in 0..<MultiPatch.sectionCount {
let section = Section(data: d.slice(from: offset, length: Section.dataLength))
sections.append(section)
offset += Section.dataLength
}
}
/// Multi patch checksum.
public var checksum: Byte {
var totalSum: Int = 0
let commonData = common.asData()
var commonSum: Int = 0
for d in commonData {
commonSum += Int(d) & 0xFF
}
totalSum += commonSum
var sectionSum: Int = 0
for section in sections {
for b in section.asData() {
sectionSum += Int(b) & 0xFF
}
}
totalSum += sectionSum
totalSum += 0xA5
return Byte(totalSum & 0x7F)
}
/// Generates a MIDI System Exclusive message from this patch.
/// - Parameter channel: the MIDI channel to use
/// - Parameter instrument: 00...3F
public func asSystemExclusiveMessage(channel: Byte, instrument: Byte) -> ByteArray {
var data = ByteArray()
let header = SystemExclusive.Header(
channel: channel,
function: .oneBlockDump,
group: 0x00,
machineIdentifier: 0x0a,
substatus1: 0x20,
substatus2: instrument)
data.append(contentsOf: header.asData())
data.append(contentsOf: self.asData())
return data
}
}
// MARK: - SystemExclusiveData
extension MultiPatch: SystemExclusiveData {
/// Gets the multi patch as MIDI System Exclusive data.
/// Collects and arranges the data for the various components of the patch.
/// - Returns: A byte array with the patch data, without the System Exclusive header.
public func asData() -> ByteArray {
var data = ByteArray()
data.append(self.checksum)
data.append(contentsOf: common.asData())
for section in sections {
data.append(contentsOf: section.asData())
}
return data
}
}
extension MultiPatch.Common: SystemExclusiveData {
/// Gets the common part as MIDI System Exclusive data.
/// - Returns: A byte array with the common part data.
public func asData() -> ByteArray {
var data = ByteArray()
data.append(contentsOf: effects.asData())
geq.forEach { data.append(Byte($0 + 64)) } // 58(-6)~70(+6)
let nameBuffer: ByteArray = Array(name.utf8)
data.append(contentsOf: nameBuffer)
data.append(Byte(volume))
return data
}
}
extension MultiPatch.Section: SystemExclusiveData {
private func asBytes() -> (msb: Byte, lsb: Byte) {
// Convert wave kit number to binary string with 10 digits
// using a String extension (see Helpers.swift).
let waveBitString = String(self.singlePatchNumber, radix: 2).pad(with: "0", toLength: 9)
// Take the first two bits and convert them to a number
let msbBitString = waveBitString.prefix(2)
let msb = Byte(msbBitString, radix: 2)!
// Take the last seven bits and convert them to a number
let lsbBitString = waveBitString.suffix(7)
let lsb = Byte(lsbBitString, radix: 2)!
return (msb, lsb)
}
/// Gets a multi section as MIDI System Exclusive data.
/// - Returns: A byte array with the section SysEx data.
public func asData() -> ByteArray {
var data = ByteArray()
let (instrumentMSB, instrumentLSB) = self.asBytes()
data.append(instrumentMSB)
data.append(instrumentLSB)
data.append(Byte(volume))
data.append(Byte(pan))
data.append(Byte(effectPath))
data.append(Byte(transpose + 64))
data.append(Byte(tune + 64))
data.append(Byte(zone.low.note))
data.append(Byte(zone.high.note))
data.append(contentsOf: velocitySwitch.asData())
data.append(receiveChannel)
return data
}
}
| 34.10989 | 119 | 0.566366 |
a47d5cfc8cdd933b26b30c0d4d54c6f07040be72 | 2,510 | php | PHP | application/views/v_perusahaan_add.php | multimediary/point-of-sales-inventory-purchase | b58bfb57fb0ca7971e8d2fa35698e0e54a9d9d7f | [
"MIT"
] | null | null | null | application/views/v_perusahaan_add.php | multimediary/point-of-sales-inventory-purchase | b58bfb57fb0ca7971e8d2fa35698e0e54a9d9d7f | [
"MIT"
] | null | null | null | application/views/v_perusahaan_add.php | multimediary/point-of-sales-inventory-purchase | b58bfb57fb0ca7971e8d2fa35698e0e54a9d9d7f | [
"MIT"
] | 1 | 2021-06-13T14:08:07.000Z | 2021-06-13T14:08:07.000Z | <div class="content-wrapper" >
<section class="content-header">
<h3>
Tambah Perusahaan
</h3>
</section>
<!-- Main content -->
<section class="content" >
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">
<span>Silahkan melengkapi form berikut</span>
</h3>
<?php if(isset($_POST['nama_perusahaan'])){?>
<p style="color:red;"><i>Nama Perusahaan telah digunakan, coba yang lain.</i></p>
<?php
$nama_perusahaan = $_POST['nama_perusahaan'];
$npwp_perusahaan = $_POST['npwp_perusahaan'];
$alamat_perusahaan = $_POST['alamat_perusahaan'];
$no_telp_perusahaan = $_POST['no_telp_perusahaan'];
$email_perusahaan = $_POST['email_perusahaan'];
?>
<?php }else{
$nama_perusahaan = "";
$npwp_perusahaan = "";
$alamat_perusahaan = "";
$no_telp_perusahaan = "";
$email_perusahaan = "";
}
?>
</div>
<div class="box-body">
<div class="row">
<?php echo form_open_multipart("perusahaan/perusahaan_aksi_tambah"); ?>
<div class="col-md-4">
<div class="form-group">
<label>Nama Perusahaan</label>
<input type="text" class="form-control" name="nama_perusahaan" placeholder="Nama Perusahaan, Contoh : PT XYZ" value="<?php echo $nama_perusahaan;?>">
</div>
<div class="form-group">
<label>NPWP</label>
<input type="text" class="form-control" name="npwp_perusahaan" placeholder="NPWP" value="<?php echo $npwp_perusahaan;?>">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" name="email_perusahaan" placeholder="Email" value="<?php echo $email_perusahaan;?>">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>No. Telp</label>
<input type="text" class="form-control" name="no_telp_perusahaan" placeholder="No. Telp" value="<?php echo $no_telp_perusahaan;?>">
</div>
<div class="form-group">
<label>Alamat</label>
<textarea class="form-control" name="alamat_perusahaan" placeholder="Alamat"><?php echo $alamat_perusahaan;?></textarea>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-success">
</div>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
</div>
</div>
</section>
</div> | 35.352113 | 155 | 0.588048 |
f1a2ae10dc05a06906a5a93bf6f8c17862df973c | 5,580 | dart | Dart | floor_generator/lib/processor/query_processor.dart | ErliSoares/floor | f2e97955401ce65121331684bb9a263478a6f25c | [
"Apache-2.0"
] | null | null | null | floor_generator/lib/processor/query_processor.dart | ErliSoares/floor | f2e97955401ce65121331684bb9a263478a6f25c | [
"Apache-2.0"
] | null | null | null | floor_generator/lib/processor/query_processor.dart | ErliSoares/floor | f2e97955401ce65121331684bb9a263478a6f25c | [
"Apache-2.0"
] | null | null | null | import 'package:analyzer/dart/element/element.dart';
import 'package:floor_generator/misc/extension/dart_type_extension.dart';
import 'package:floor_generator/processor/error/query_processor_error.dart';
import 'package:floor_generator/processor/processor.dart';
import 'package:floor_generator/value_object/query.dart';
import 'package:floor_generator/misc/type_utils.dart';
class QueryProcessor extends Processor<Query> {
final QueryProcessorError _processorError;
final String _query;
final List<ParameterElement> _parameters;
QueryProcessor(MethodElement methodElement, this._query)
: _parameters = methodElement.parameters,
_processorError = QueryProcessorError(methodElement);
@override
Query process() {
_assertNoNullableParameters();
final indices = <String, int>{};
final fixedParameters = <String>{};
//map parameters to index (1-based) or 0 (if its a list)
int currentIndex = 1;
for (final parameter in _parameters) {
if (parameter.type.isDartCoreList) {
indices[':${parameter.name}'] = 0;
} else {
fixedParameters.add(parameter.name);
indices[':${parameter.name}'] = currentIndex++;
}
}
//get List of query variables
final variables = findVariables(_query);
_assertAllParametersAreUsed(variables);
_assertOneLoadOptions(variables);
// TODO Validar para nõo deixar colocar o loadoptions para querys que não seja select
final newQuery = StringBuffer();
final listParameters = <ListParameter>[];
// iterate over all found variables, replace them with their assigned
// numbered variable (?1,?2,...) or a placeholder if the variable is a list.
// the list variables have to be handled in the writer, so write down their
// positions and names.
int currentLast = 0;
for (final varToken in variables) {
newQuery.write(_query
.substring(currentLast, varToken.startPosition)
.replaceAll('\n', ' '));
final varIndexInMethod = indices[varToken.name];
if (varIndexInMethod == null) {
throw _processorError.unknownQueryVariable(varToken.name);
} else if (varIndexInMethod > 0) {
//normal variable/parameter
if (varToken.isListVar)
throw _processorError
.queryMethodParameterIsNormalButVariableIsList(varToken.name);
newQuery.write('?');
newQuery.write(varIndexInMethod);
} else {
//list variable/parameter
if (!varToken.isListVar)
throw _processorError
.queryMethodParameterIsListButVariableIsNot(varToken.name);
listParameters
.add(ListParameter(newQuery.length, varToken.name.substring(1)));
newQuery.write(varlistPlaceholder);
}
currentLast = varToken.endPosition;
}
newQuery.write(_query.substring(currentLast).replaceAll('\n', ' '));
return Query(
newQuery.toString(),
listParameters,
);
}
void _assertNoNullableParameters() {
for (final parameter in _parameters) {
if (parameter.type.isNullable) {
throw _processorError.queryMethodParameterIsNullable(parameter);
}
}
}
void _assertAllParametersAreUsed(List<VariableToken> variables) {
final queryVariables = variables.map((e) => e.name.substring(1)).toSet();
for (final param in _parameters) {
if (!queryVariables.contains(param.displayName) && !param.type.isLoadOptions && !param.type.isLoadOptionsEntry) {
throw _processorError.unusedQueryMethodParameter(param);
}
}
}
void _assertOneLoadOptions(List<VariableToken> variables) {
final parameters = _parameters.where((e) => e.type.isLoadOptions || e.type.isLoadOptionsEntry).toList();
if (parameters.length > 1) {
throw _processorError.moreOneLoadOptionsQueryMethodParameter(parameters[1]);
}
}
}
/// Treats the incoming String as an Sqlite query and tries to find all used
/// sqlite variables. Also try do identify List variables by looking at their
/// context.
List<VariableToken> findVariables(final String query) {
final output = <VariableToken>[];
for (final match
in RegExp(r':[\w]+| [iI][nN]\s*\((:[\w]+)\)').allMatches(query)) {
final content = match.group(0)!;
final expectsList = content.toLowerCase().startsWith(' in');
if (expectsList) {
final varname = match.group(1)!;
output.add(
VariableToken(varname, query.indexOf(varname, match.start), true));
} else {
output.add(VariableToken(content, match.start, false));
}
}
return output;
}
/// Represents a variable within an sqlite query.
class VariableToken {
/// the variable name including `:` (e.g. `:foo`)
final String name;
/// the offset within the query, where the variable name starts. Useful for
/// splitting the query here.
final int startPosition;
/// the offset within the query, where the variable name ends. Useful for
/// splitting the query here.
int get endPosition => startPosition + name.length;
/// denotes if the variable was determined to contain a list
final bool isListVar;
VariableToken(this.name, this.startPosition, this.isListVar);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is VariableToken &&
runtimeType == other.runtimeType &&
name == other.name &&
startPosition == other.startPosition &&
isListVar == other.isListVar;
@override
int get hashCode =>
name.hashCode ^ startPosition.hashCode ^ isListVar.hashCode;
}
| 35.316456 | 119 | 0.68638 |
900146c7a08986ce59bb40f7f97624d62412a816 | 11,226 | h | C | include/barrelfish_kpi/vmx_encodings.h | Liblor/advanced_operating_systems_2020 | 1e9137db8a47d922e22c0a2d78b24a7364b7629a | [
"MIT"
] | 5 | 2020-06-12T11:47:21.000Z | 2022-02-27T14:39:05.000Z | include/barrelfish_kpi/vmx_encodings.h | Liblor/advanced_operating_systems_2020 | 1e9137db8a47d922e22c0a2d78b24a7364b7629a | [
"MIT"
] | 3 | 2020-06-04T20:11:26.000Z | 2020-07-26T23:16:33.000Z | include/barrelfish_kpi/vmx_encodings.h | Liblor/advanced_operating_systems_2020 | 1e9137db8a47d922e22c0a2d78b24a7364b7629a | [
"MIT"
] | 3 | 2020-06-12T18:06:29.000Z | 2022-03-13T17:19:02.000Z | /*
* Copyright (c) 2014, University of Washington.
* All rights reserved.
*
* This file is distributed under the terms in the attached LICENSE file.
* If you do not find this file, copies can be found by writing to:
* ETH Zurich D-INFK, CAB F.78, Universitaetstrasse 6, CH-8092 Zurich.
* Attn: Systems Group.
*/
#ifndef VMX_ENCODINGS_H
#define VMX_ENCODINGS_H
// 16-bit field encodings
// read-only data fields
#define VMX_VPID 0x0 // Virtual-processor identifier (VPID)
#define VMX_PINV 0x2 // Posted-interrupt notification vector
#define VMX_EPTP 0x4 // EPTP index
// guest-state fields
#define VMX_GUEST_ES_SEL 0x800 // Guest ES selector
#define VMX_GUEST_CS_SEL 0x802 // Guest CS selector
#define VMX_GUEST_SS_SEL 0x804 // Guest SS selector
#define VMX_GUEST_DS_SEL 0x806 // Guest DS selector
#define VMX_GUEST_FS_SEL 0x808 // Guest FS selector
#define VMX_GUEST_GS_SEL 0x80A // Guest GS selector
#define VMX_GUEST_LDTR_SEL 0x80C // Guest LDTR selector
#define VMX_GUEST_TR_SEL 0x80E // Guest TR selector
#define VMX_GUEST_IS 0x810 // Guest interrupt status
// host-state fields
#define VMX_HOST_ES_SEL 0xC00 // Guest ES selector
#define VMX_HOST_CS_SEL 0xC02 // Guest CS selector
#define VMX_HOST_SS_SEL 0xC04 // Guest SS selector
#define VMX_HOST_DS_SEL 0xC06 // Guest DS selector
#define VMX_HOST_FS_SEL 0xC08 // Guest FS selector
#define VMX_HOST_GS_SEL 0xC0A // Guest GS selector
#define VMX_HOST_TR_SEL 0xC0C // Guest TR selector
// 32-bit field encodings
// control fields
#define VMX_EXEC_PIN_BASED 0x4000 // Pin-based controls
#define VMX_EXEC_PRIM_PROC 0x4002 // Primary processor-based controls
#define VMX_EXCP_BMP 0x4004 // Exception bitmap
#define VMX_PF_ERR_MASK 0x4006 // Page-fault error-code mask
#define VMX_PF_ERR_MATCH 0x4008 // Page-fault error-code match
#define VMX_CR3_TARGET_CNT 0x400A // CR3-target count
#define VMX_EXIT_CONTROLS 0x400C // VM-exit controls
#define VMX_EXIT_MSR_STORE_CNT 0x400E // VM-exit MSR-store count
#define VMX_EXIT_MSR_LOAD_CNT 0x4010 // VM-exit MSR-load count
#define VMX_ENTRY_CONTROLS 0x4012 // VM-entry controls
#define VMX_ENTRY_MSR_LOAD_CNT 0x4014 // VM-entry MSR-load count
#define VMX_ENTRY_INTR_INFO 0x4016 // VM-entry interruption-information field
#define VMX_ENTRY_EXCP_ERR 0x4018 // VM-entry exception error code
#define VMX_ENTRY_INSTR_LEN 0x401A // VM-entry instruction length
#define VMX_TPR_THRESHOLD 0x401C // TPR threshold
#define VMX_EXEC_SEC_PROC 0x401E // Secondary processor-based controls
#define VMX_PLE_GAP 0x4020 // PLE_Gap
#define VMX_PLE_WINDOW 0x4022 // PLE_Window
// read-only data fields
#define VMX_INSTR_ERROR 0x4400 // VM-instruction error
#define VMX_EXIT_REASON 0x4402 // Exit reason
#define VMX_EXIT_INTR_INFO 0x4404 // VM-exit interruption information
#define VMX_EXIT_INTR_ERR 0x4406 // VM-exit interruption error code
#define VMX_IDT_VEC_INFO 0x4408 // IDT-vectoring information field
#define VMX_IDT_VEC_ERR 0x440A // IDT-vectoring error code
#define VMX_EXIT_INSTR_LEN 0x440C // VM-exit instruction length
#define VMX_EXIT_INSTR_INFO 0x440E // VM-exit instruction information
// guest-state fields
#define VMX_GUEST_ES_LIM 0x4800 // Guest ES limit
#define VMX_GUEST_CS_LIM 0x4802 // Guest CS limit
#define VMX_GUEST_SS_LIM 0x4804 // Guest SS limit
#define VMX_GUEST_DS_LIM 0x4806 // Guest DS limit
#define VMX_GUEST_FS_LIM 0x4808 // Guest FS limit
#define VMX_GUEST_GS_LIM 0x480A // Guest GS limit
#define VMX_GUEST_LDTR_LIM 0x480C // Guest LDTR limit
#define VMX_GUEST_TR_LIM 0x480E // Guest TR limit
#define VMX_GUEST_GDTR_LIM 0x4810 // Guest GDTR limit
#define VMX_GUEST_IDTR_LIM 0x4812 // Guest IDTR limit
#define VMX_GUEST_ES_ACCESS 0x4814 // Guest ES access rights
#define VMX_GUEST_CS_ACCESS 0x4816 // Guest CS access rights
#define VMX_GUEST_SS_ACCESS 0x4818 // Guest SS access rights
#define VMX_GUEST_DS_ACCESS 0x481A // Guest DS access rights
#define VMX_GUEST_FS_ACCESS 0x481C // Guest FS access rights
#define VMX_GUEST_GS_ACCESS 0x481E // Guest GS access rights
#define VMX_GUEST_LDTR_ACCESS 0x4820 // Guest LDTR access rights
#define VMX_GUEST_TR_ACCESS 0x4822 // Guest TR access rights
#define VMX_GUEST_INTR_STATE 0x4824 // Guest activity state
#define VMX_GUEST_ACTIV_STATE 0x4826 // Guest activity state
#define VMX_GUEST_SMBASE 0x4828 // Guest SMBASE
#define VMX_GUEST_SYSENTER_CS 0x482A // Guest IA32_SYSENTER_CS
#define VMX_GUEST_PREEMPT_TIMER 0x482E // VMX-preemption timer value
// host-state fields
#define VMX_HOST_SYSENTER_CS 0x4C00 // Host IA32_SYSENTER_CS
// 64-bit field encodings
// control fields
#define VMX_IOBMP_A_F 0x2000 // Address of I/O bitmap A (full)
#define VMX_IOBMP_A_H 0x2001 // Address of I/O bitmap A (high)
#define VMX_IOBMP_B_F 0x2002 // Address of I/O bitmap B (full)
#define VMX_IOBMP_B_H 0x2003 // Address of I/O bitmap B (high)
#define VMX_MSRBMP_F 0x2004 // Address of MSR bitmaps (full)
#define VMX_MSRBMP_H 0x2005 // Address of MSR bitmaps (high)
#define VMX_EXIT_MSR_STORE_F 0x2006 // VM-exit MSR-store address (full)
#define VMX_EXIT_MSR_STORE_H 0x2007 // VM-exit MSR-store address (high)
#define VMX_EXIT_MSR_LOAD_F 0x2008 // VM-exit MSR-load address (full)
#define VMX_EXIT_MSR_LOAD_H 0x2009 // VM-exit MSR-load address (high)
#define VMX_ENTRY_MSR_LOAD_F 0x200A // VM-entry MSR-load address (full)
#define VMX_ENTRY_MSR_LOAD_H 0x200B // VM-entry MSR-load address (high)
#define VMX_EVMCS_PTR_F 0x200C // Executive-VMCS pointer (full)
#define VMX_EVMCS_PTR_H 0x200D // Executive-VMCS pointer (high)
#define VMX_TSC_OFF_F 0x2010 // TSC offset (full)
#define VMX_TSC_OFF_H 0x2011 // TSC offset (high)
#define VMX_VAPIC_F 0x2012 // Virtual-APIC address (full)
#define VMX_VAPIC_H 0x2013 // Virtual-APIC address (high)
#define VMX_APIC_ACC_F 0x2014 // APIC-access address (full)
#define VMX_APIC_ACC_H 0x2015 // APIC-access address (high)
#define VMX_PID_F 0x2016 // Posted-interrupt descriptor address (full)
#define VMX_PID_H 0x2017 // Posted-interrupt descriptor address (high)
#define VMX_VMFUNC_F 0x2018 // VM-function controls (full)
#define VMX_VMFUNC_H 0x2019 // VM-function controls (high)
#define VMX_EPTP_F 0x201A // EPT pointer (full)
#define VMX_EPTP_H 0x201B // EPT pointer (high)
#define VMX_EOI_EXIT_BMP0_F 0x201C // EOI-exit bitmap 0 (full)
#define VMX_EOI_EXIT_BMP0_H 0x201D // EOI-exit bitmap 0 (high)
#define VMX_EOI_EXIT_BMP1_F 0x201E // EOI-exit bitmap 1 (full)
#define VMX_EOI_EXIT_BMP1_H 0x201F // EOI-exit bitmap 1 (high)
#define VMX_EOI_EXIT_BMP2_F 0x2020 // EOI-exit bitmap 2 (full)
#define VMX_EOI_EXIT_BMP2_H 0x2021 // EOI-exit bitmap 2 (high)
#define VMX_EOI_EXIT_BMP3_F 0x2022 // EOI-exit bitmap 3 (full)
#define VMX_EOI_EXIT_BMP3_H 0x2023 // EOI-exit bitmap 3 (high)
#define VMX_EPTP_LIST_F 0x2024 // EPTP-list address (full)
#define VMX_EPTP_LIST_H 0x2025 // EPTP-list address (high)
#define VMX_VMREAD_BMP_F 0x2026 // VMREAD-bitmap address (full)
#define VMX_VMREAD_BMP_H 0x2027 // VMREAD-bitmap address (high)
#define VMX_VMWRITE_BMP_F 0x2028 // VMWRITE-bitmap address (full)
#define VMX_VMWRITE_BMP_H 0x2029 // VMWRITE-bitmap address (high)
#define VMX_VEXCP_INFO_F 0x202A // Virtualization-exception info. address (full)
#define VMX_VEXCP_INFO_H 0x202B // Virtualization-exception info. address (high)
// read-only data fields
#define VMX_GPADDR_F 0x2400 // Guest-physical address (full)
#define VMX_GPADDR_H 0x2401 // Guest-physical address (high)
// guest-state fields
#define VMX_GUEST_VMCS_LPTR_F 0x2800 // VMCS link pointer (full)
#define VMX_GUEST_VMCS_LPTR_H 0x2801 // VMCS link pointer (high)
#define VMX_GUEST_DCTL_F 0x2802 // Guest IA32_DEBUGCTL (full)
#define VMX_GUEST_DCTL_H 0x2803 // Guest IA32_DEBUGCTL (high)
#define VMX_GUEST_PAT_F 0x2804 // Guest IA32_PAT (full)
#define VMX_GUEST_PAT_H 0x2805 // Guest IA32_PAT (high)
#define VMX_GUEST_EFER_F 0x2806 // Guest IA32_EFER (full)
#define VMX_GUEST_EFER_H 0x2807 // Guest IA32_EFER (high)
#define VMX_GUEST_PGC_F 0x2808 // Guest IA32_PERF_GLOBAL_CTRL (full)
#define VMX_GUEST_PGC_H 0x2809 // Guest IA32_PERF_GLOBAL_CTRL (high)
#define VMX_GUEST_PDPTE0_F 0x280A // Guest PDPTE0 (full)
#define VMX_GUEST_PDPTE0_H 0x280B // Guest PDPTE0 (high)
#define VMX_GUEST_PDPTE1_F 0x280C // Guest PDPTE1 (full)
#define VMX_GUEST_PDPTE1_H 0x280D // Guest PDPTE1 (high)
#define VMX_GUEST_PDPTE2_F 0x280E // Guest PDPTE2 (full)
#define VMX_GUEST_PDPTE2_H 0x280F // Guest PDPTE2 (high)
#define VMX_GUEST_PDPTE3_F 0x2810 // Guest PDPTE3 (full)
#define VMX_GUEST_PDPTE3_H 0x2811 // Guest PDPTE3 (high)
// host-state fields
#define VMX_HOST_PAT_F 0x2C00 // Host IA32_PAT (full)
#define VMX_HOST_PAT_H 0x2C01 // Host IA32_PAT (high)
#define VMX_HOST_EFER_F 0x2C02 // Host IA32_EFER (full)
#define VMX_HOST_EFER_H 0x2C03 // Host IA32_EFER (high)
#define VMX_HOST_PGC_F 0x2C04 // Host IA32_PERF_GLOBAL_CTRL (full)
#define VMX_HOST_PGC_H 0x2C05 // Host IA32_PERF_GLOBAL_CTRL (high)
// Natural-width field encodings
// control fields
#define VMX_CR0_GH_MASK 0x6000 // CR0 guest/host mask
#define VMX_CR4_GH_MASK 0x6002 // CR4 guest/host mask
#define VMX_CR0_RD_SHADOW 0x6004 // CR0 read shadow
#define VMX_CR4_RD_SHADOW 0x6006 // CR4 read shadow
#define VMX_CR3_T0 0x6008 // CR3-target value 0
#define VMX_CR3_T1 0x600A // CR3-target value 1
#define VMX_CR3_T2 0x600C // CR3-target value 2
#define VMX_CR3_T3 0x600E // CR3-target value 3
// read-only data fields
#define VMX_EXIT_QUAL 0x6400 // Exit qualification
#define VMX_IO_RCX 0x6402 // I/O RCX
#define VMX_IO_RSI 0x6404 // I/O RSI
#define VMX_IO_RDI 0x6406 // I/O RDI
#define VMX_IO_RIP 0x6408 // I/O RIP
#define VMX_GL_ADDR 0x640A // Guest-linear address
// guest-state fields
#define VMX_GUEST_CR0 0x6800 // Guest CR0
#define VMX_GUEST_CR3 0x6802 // Guest CR3
#define VMX_GUEST_CR4 0x6804 // Guest CR4
#define VMX_GUEST_ES_BASE 0x6806 // Guest ES base
#define VMX_GUEST_CS_BASE 0x6808 // Guest CS base
#define VMX_GUEST_SS_BASE 0x680A // Guest SS base
#define VMX_GUEST_DS_BASE 0x680C // Guest DS base
#define VMX_GUEST_FS_BASE 0x680E // Guest FS base
#define VMX_GUEST_GS_BASE 0x6810 // Guest GS base
#define VMX_GUEST_LDTR_BASE 0x6812 // Guest LDTR base
#define VMX_GUEST_TR_BASE 0x6814 // Guest TR base
#define VMX_GUEST_GDTR_BASE 0x6816 // Guest GDTR base
#define VMX_GUEST_IDTR_BASE 0x6818 // Guest IDTR base
#define VMX_GUEST_DR7 0x681A // Guest DR7
#define VMX_GUEST_RSP 0x681C // Guest RSP
#define VMX_GUEST_RIP 0x681E // Guest RIP
#define VMX_GUEST_RFLAGS 0x6820 // Guest RFLAGS
#define VMX_GUEST_PDEXCP 0x6822 // Guest pending debug exceptions
#define VMX_GUEST_SYSENTER_ESP 0x6824 // Guest IA32_SYSENTER_ESP
#define VMX_GUEST_SYSENTER_EIP 0x6826 // Guest IA32_SYSENTER_EIP
// host-state fields
#define VMX_HOST_CR0 0x6C00 // Host CR0
#define VMX_HOST_CR3 0x6C02 // Host CR3
#define VMX_HOST_CR4 0x6C04 // Host CR4
#define VMX_HOST_FS_BASE 0x6C06 // Host FS base
#define VMX_HOST_GS_BASE 0x6C08 // Host GS base
#define VMX_HOST_TR_BASE 0x6C0A // Host TR base
#define VMX_HOST_GDTR_BASE 0x6C0C // Host GDTR base
#define VMX_HOST_IDTR_BASE 0x6C0E // Host IDTR base
#define VMX_HOST_SYSENTER_ESP 0x6C10 // Host IA32_SYSENTER_ESP
#define VMX_HOST_SYSENTER_EIP 0x6C12 // Host IA32_SYSENTER_EIP
#define VMX_HOST_RSP 0x6C14 // Host RSP
#define VMX_HOST_RIP 0x6C16 // Host RIP
#endif // VMX_ENCODINGS_H
| 47.567797 | 80 | 0.794228 |
da1dd7ef781d74fe035f1dfc5c186a5f4655fe8f | 3,427 | php | PHP | resources/views/noc/generate_noc_app.blade.php | kumar2411sanjaygithub/master | bc18da5bafa690bc06a01bf3f51293709bc59339 | [
"MIT"
] | null | null | null | resources/views/noc/generate_noc_app.blade.php | kumar2411sanjaygithub/master | bc18da5bafa690bc06a01bf3f51293709bc59339 | [
"MIT"
] | null | null | null | resources/views/noc/generate_noc_app.blade.php | kumar2411sanjaygithub/master | bc18da5bafa690bc06a01bf3f51293709bc59339 | [
"MIT"
] | null | null | null | <html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="target">
<div style="background:#f0f0f0;width:100vw;display:flex;justify-content:center;padding:20px;">
<div style="width:100%;height:60%;background:#fff;padding:30px 40px;">
<div style="text-align: center;" ><img src="<?php echo public_path();?>/img/Tata_logo.svg" style="width:90px!important;height:90px!important;"></div>
<span style="margin-left:40px;">{{$date}}</span><span style="float:right;">{{$application_no}}</span>
<div style="margin-top:30px;">
<div id="emp1">To</div>
<div id="emp2">{{isset($sldc_name)?$sldc_name:''}}</div>
<div id="emp3">{!!isset($sldc_address)?$sldc_address:''!!}</div>
</div>
<div class="row"> </div>
<div class="row"> </div>
<div style="font-size:14px;font-weight:600;">
<u>Sub: Standing Clearance for {{$short_id}} {{$company_name}} in Power Exchanges({{$exchange}})</u>
</div>
<div class="row"> </div>
<div>Dear Sir,</div>
<div class="row"> </div>
<div style="font-size:13px;">
Tata Power Trading is a member of both the power exchange(IEX/PXIL),presently in operation.We have power purchase aggreement with
{{$short_id}} {{$company_name}} for Buying Power for their plant in {{$conn_state}}. We request you to kindly issue the Standing Clearance
for Buying {{$quantum}} MW for {{$short_id}} {{$company_name}} in Power Exchange ({{$exchange}}) from {{$from_date}} to {{$end_date}}, as per Exchange PX-I format. Processing Fees of Rs.{{$amount}} with UTR no.
{{$challan_no}} is paid on {{$transcation_date}}.
</div>
<div class="row"> </div>
<div style="font-size:14px;font-weight:600;">Note: Payment is made on {{$transcation_date}}.</div>
<div class="row"> </div>
<div class="row"> </div>
<div>Thank You ,</div>
<div class="row"> </div>
<div>Your Faithfully,</div>
<div>For Tata Power Trading Company Limited,</div>
<div class="row"> </div>
<div class="row"> </div>
<div>(Anujesh Shahi)</div>
<div>Head-Operations</div>
<div style="margin-top:5%;text-align:center;">
<div style="font-size:10px;font-weight:600;">Tata Power Trading Company Limited</div>
<div style="font-size:10px;font-weight:600;">2nd Floor,Shatabdi Bhawan</div>
<div style="font-size:10px;font-weight:600;">B-12-13 Sector-4 Noida,Uttar Pardesh-201301</div>
<div style="font-size:10px;font-weight:600;">Tel 91 120-6102210,6102213,Fax: 91-120-2540050,91-120-2540085</div>
<div style="font-size:10px;font-weight:600;">www.tatapowertrading.com CIN: U40100MH20003PLC143770</div>
</div>
</div>
</div>
</div>
</body>
</html>
| 59.086207 | 228 | 0.55267 |
eb7ffc4142bd6018e6a8a2f951811b6bd171c42e | 1,425 | css | CSS | app/src/main/assets/callsms_files/main.css | YuMENGQI/WebView | 6d3517b9b52f2c5ad10c3f15029a573811efdbe7 | [
"Apache-2.0"
] | 1,597 | 2017-10-10T11:18:48.000Z | 2022-03-30T03:22:16.000Z | app/src/main/assets/callsms_files/main.css | YuMENGQI/WebView | 6d3517b9b52f2c5ad10c3f15029a573811efdbe7 | [
"Apache-2.0"
] | 117 | 2019-09-25T00:28:54.000Z | 2022-03-22T07:38:24.000Z | app/src/main/assets/callsms_files/main.css | YuMENGQI/WebView | 6d3517b9b52f2c5ad10c3f15029a573811efdbe7 | [
"Apache-2.0"
] | 257 | 2019-09-23T06:47:08.000Z | 2022-03-29T10:15:02.000Z |
/* http://v4-stage-api.kangaiweishi.com/v3/main.css */
*{
margin: 0;
padding: 0;
}
body {
background-color: white;
color: #666666;
word-break: break-all;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid #e9eaeb;
height: 44px;
}
.howto_upgrade_table {
font-size: 12px;
}
.header {
height: 25px;
background-color: #e9eaeb;
font-size: 14px;
width: 320px;
}
p {
margin: 2px 5px 2px 5px;
}
#level_table {
font-size: 12px;
text-align: center;
}
.lv {
text-align: center;
display: inline;
color: white;
padding: 5px 5px 4px 5px;
border-radius:3px;
}
.lv1-5 {
background: #35e181;
}
.lv6-10 {
background: #2bb8ed;
}
.lv11-15 {
background: #ff7578;
}
.lv16-20 {
background: #f7822c;
}
.number {
color: orange;
text-align: center;
padding: 3px 3px 3px 3px;
}
.article_body {
line-height: 1.8em;
}
.article_title {
margin: 20px 15px 5px 15px;
color: #333;
font-weight: bold;
font-size: 22px;
border-style: hidden;
/*border-left-style: solid;*/
/*padding-left: 5px;*/
}
.article_title_pic {
margin: 5px 5px 5px 5px;
}
.article_created_at {
margin: 0 15px 0 15px;
color: #999999;
font-size: 15px;
}
.article_content {
margin: 5px 15px 30px 15px;
font-size: 17px;
color: #4c4c4c;
text-align: justify;
}
.article_content img{
margin-bottom: 10px;
margin-top: 10px;
}
.article_content p img {
margin: 0;
}
| 13.194444 | 54 | 0.640702 |
33b8c486e5a95404c5ece9e85f13b3df014a982e | 1,489 | swift | Swift | Sources/ValidationLibrary/String+Validatins.swift | RaviiOS/ValidationsLibrary | ed4a7fd770b8cb0f3279a44fef9230f35075ad31 | [
"MIT"
] | null | null | null | Sources/ValidationLibrary/String+Validatins.swift | RaviiOS/ValidationsLibrary | ed4a7fd770b8cb0f3279a44fef9230f35075ad31 | [
"MIT"
] | null | null | null | Sources/ValidationLibrary/String+Validatins.swift | RaviiOS/ValidationsLibrary | ed4a7fd770b8cb0f3279a44fef9230f35075ad31 | [
"MIT"
] | null | null | null | //
// File.swift
//
//
// Created by Ravi Kumar Yaganti on 15/04/21.
//
import Foundation
public extension String {
//To check text field or String is blank or not
var isBlank: Bool {
get {
let trimmed = trimmingCharacters(in: CharacterSet.whitespaces)
return trimmed.isEmpty
}
}
//Validate Email
var isEmail: Bool {
do {
let regex = try NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}", options: .caseInsensitive)
return regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count)) != nil
} catch {
return false
}
}
var isAlphanumeric: Bool {
return !isEmpty && range(of: "[^a-zA-Z0-9]", options: .regularExpression) == nil
}
//validate Password
var isValidPassword: Bool {
do {
let regex = try NSRegularExpression(pattern: "^[a-zA-Z_0-9\\-_,;.:#+*?=!§$%&/()@]+$", options: .caseInsensitive)
if(regex.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count)) != nil){
if(self.count>=6 && self.count<=20){
return true
}else{
return false
}
}else{
return false
}
} catch {
return false
}
}
}
| 28.09434 | 146 | 0.533915 |
20bf4875b1506306c60535b18e1211874a3cd698 | 1,793 | py | Python | _pycharm_skeletons/renderdoc/BlendOperation.py | Lex-DRL/renderdoc-py-stubs | 75d280e4f500ded506f3315a49fc432b37ab4fa6 | [
"MIT"
] | null | null | null | _pycharm_skeletons/renderdoc/BlendOperation.py | Lex-DRL/renderdoc-py-stubs | 75d280e4f500ded506f3315a49fc432b37ab4fa6 | [
"MIT"
] | null | null | null | _pycharm_skeletons/renderdoc/BlendOperation.py | Lex-DRL/renderdoc-py-stubs | 75d280e4f500ded506f3315a49fc432b37ab4fa6 | [
"MIT"
] | null | null | null | # encoding: utf-8
# module renderdoc
# from P:\1-Scripts\_Python\Py-Autocomplete\renderdoc.pyd
# by generator 1.146
# no doc
# imports
import enum as __enum
class BlendOperation(__enum.IntEnum):
"""
A blending operation to apply in color blending.
.. note:: The "source" value is the value written out by the shader.
The "destination" value is the value in the target being blended to.
These values are multiplied by a given blend factor, see :class:`BlendMultiplier`.
.. data:: Add
Add the two values being processed together.
.. data:: Subtract
Subtract the destination value from the source value.
.. data:: ReversedSubtract
Subtract the source value from the destination value.
.. data:: Minimum
The minimum of the source and destination value.
.. data:: Maximum
The maximum of the source and destination value.
"""
def _generate_next_value_(name, start, count, last_values): # reliably restored by inspect
# no doc
pass
def __init__(self, *args, **kwargs): # real signature unknown
pass
@staticmethod # known case of __new__
def __new__(cls, value): # reliably restored by inspect
# no doc
pass
Add = 0
Maximum = 4
Minimum = 3
ReversedSubtract = 2
Subtract = 1
_member_map_ = {
'Add': 0,
'Maximum': 4,
'Minimum': 3,
'ReversedSubtract': 2,
'Subtract': 1,
}
_member_names_ = [
'Add',
'Subtract',
'ReversedSubtract',
'Minimum',
'Maximum',
]
_member_type_ = int
_value2member_map_ = {
0: 0,
1: 1,
2: 2,
3: 3,
4: 4,
}
| 21.865854 | 94 | 0.582264 |
db111e0972b58fb7ef5be3f5cc6c8e0fc57aa301 | 3,368 | lua | Lua | game/hud.lua | MarcoLizza/fugue | 4edaba17aa0320e3536668037f871177bd462a00 | [
"Zlib"
] | null | null | null | game/hud.lua | MarcoLizza/fugue | 4edaba17aa0320e3536668037f871177bd462a00 | [
"Zlib"
] | null | null | null | game/hud.lua | MarcoLizza/fugue | 4edaba17aa0320e3536668037f871177bd462a00 | [
"Zlib"
] | null | null | null | --[[
Copyright (c) 2016 by Marco Lizza ([email protected])
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgement in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
]]--
-- MODULE INCLUSIONS -----------------------------------------------------------
local constants = require('game.constants')
local collections = require('lib.collections')
local graphics = require('lib.graphics')
local utils = require('lib.utils')
-- MODULE DECLARATION ----------------------------------------------------------
local Hud = {
}
-- MODULE OBJECT CONSTRUCTOR ---------------------------------------------------
Hud.__index = Hud
function Hud.new()
local self = setmetatable({}, Hud)
return self
end
-- LOCAL CONSTANTS -------------------------------------------------------------
local DIRECTIONS = {
'e', 'se', 's', 'sw', 'w', 'nw', 'n', 'ne'
}
-- LOCAL FUNCTIONS -------------------------------------------------------------
-- http://stackoverflow.com/questions/1437790/how-to-snap-a-directional-2d-vector-to-a-compass-n-ne-e-se-s-sw-w-nw
local function compass(x, y)
if x == 0 and y == 0 then
return '-'
end
local angle = math.atan2(y, x)
local scaled = math.floor(angle / (2 * math.pi / 8))
local value = (scaled + 8) % 8
return DIRECTIONS[value + 1]
end
-- MODULE FUNCTIONS ------------------------------------------------------------
function Hud:initialize(world)
self.world = world
end
function Hud:update(dt)
end
function Hud:draw()
local world = self.world
local entities = world.entities
local avatar = entities.avatar
-- The target is the first visible key (the player could have collected them
-- in any order), or the door.
local key = collections.select(entities.keys, function(_, value)
return value.visible
end)
local target = key or entities.door
-- Compute the angle/distance from the current target (key, door, etc)
-- and display a compass.
local dx, dy = utils.delta(target.position, avatar.position)
local compass = compass(dx, dy)
graphics.text(string.format('NIGHT #%d', world.level),
constants.SCREEN_RECT, 'silkscreen', { 255, 255, 255 }, 'left', 'top')
graphics.text(compass,
constants.SCREEN_RECT, 'silkscreen', { 255, 255, 255 }, 'right', 'top', 2)
graphics.text(string.format('duration %d | health %d | flares %d',
avatar.duration, avatar.health, avatar.flares),
constants.SCREEN_RECT, 'silkscreen', { 255, 255, 255 }, 'center', 'bottom')
end
-- END OF MODULE ---------------------------------------------------------------
return Hud
-- END OF FILE -----------------------------------------------------------------
| 32.07619 | 114 | 0.605998 |
523c27f6bc3c8850e595799a36cced6b7d5a7541 | 5,917 | ps1 | PowerShell | PowerShell_Scripts/Get-DatabaseConfigurationInfo.ps1 | CodeNameSQL/ITAM | ebdd2cdce98cb27022e399668323fc654a1d1171 | [
"MIT"
] | 1 | 2022-03-22T17:59:26.000Z | 2022-03-22T17:59:26.000Z | PowerShell_Scripts/Get-DatabaseConfigurationInfo.ps1 | Jhiggin/ITAM | ebdd2cdce98cb27022e399668323fc654a1d1171 | [
"MIT"
] | 4 | 2019-05-09T20:35:35.000Z | 2019-09-14T12:51:55.000Z | PowerShell_Scripts/Get-DatabaseConfigurationInfo.ps1 | Jhiggin/ITAM | ebdd2cdce98cb27022e399668323fc654a1d1171 | [
"MIT"
] | 10 | 2019-10-05T13:41:35.000Z | 2021-03-04T01:01:24.000Z | #ValidationTags#Messaging,FlowControl,Pipeline,CodeStyle#
function Get-DatabaseConfigurationInfo {
<#
.SYNOPSIS
Returns database configuration info for the system.
.DESCRIPTION
This script is part of the ITAM process and is called by the Start-ServerAssetScan.ps1 script
.PARAMETER WhatIf
Shows what would happen if the command were to run. No actions are actually performed.
.EXAMPLE
PS C:\> Get-DatabaseConfigurationInfo -AssetID 1000 -AssetName LocalHost -AssetType 1
#>
[CmdletBinding()]
param (
[object[]]$AssetID,
[object[]]$AssetName,
[object[]]$AssetType
)
begin {
$sql = @"
SELECT
$AssetID as 'Asset_ID',
SERVERPROPERTY('MachineName') AS MachineName,
CASE
WHEN SERVERPROPERTY('InstanceName') IS NULL THEN ''
ELSE SERVERPROPERTY('InstanceName')
END AS InstanceName,
'' as Port, --need to update to strip from Servername. Note: Assumes Registered Server is named with Port
SUBSTRING ( (SELECT @@VERSION),1, CHARINDEX('-',(SELECT @@VERSION))-1 ) as ProductName,
SERVERPROPERTY('ProductVersion') AS ProductVersion,
SERVERPROPERTY('ProductLevel') AS ProductLevel,
SERVERPROPERTY('ProductMajorVersion') AS ProductMajorVersion,
SERVERPROPERTY('ProductMinorVersion') AS ProductMinorVersion,
SERVERPROPERTY('ProductBuild') AS ProductBuild,
SERVERPROPERTY('Edition') AS Edition,
CASE SERVERPROPERTY('EngineEdition')
WHEN 1 THEN 'PERSONAL'
WHEN 2 THEN 'STANDARD'
WHEN 3 THEN 'ENTERPRISE'
WHEN 4 THEN 'EXPRESS'
WHEN 5 THEN 'SQL DATABASE'
WHEN 6 THEN 'SQL DATAWAREHOUSE'
END AS EngineEdition,
CASE SERVERPROPERTY('IsHadrEnabled')
WHEN 0 THEN 'The Always On Availability Groups feature is disabled'
WHEN 1 THEN 'The Always On Availability Groups feature is enabled'
ELSE 'Not applicable'
END AS HadrEnabled,
CASE SERVERPROPERTY('HadrManagerStatus')
WHEN 0 THEN 'Not started, pending communication'
WHEN 1 THEN 'Started and running'
WHEN 2 THEN 'Not started and failed'
ELSE 'Not applicable'
END AS HadrManagerStatus,
CASE SERVERPROPERTY('IsSingleUser') WHEN 0 THEN 'No' ELSE 'Yes' END AS InSingleUserMode,
CASE SERVERPROPERTY('IsClustered')
WHEN 1 THEN 'Clustered'
WHEN 0 THEN 'Not Clustered'
ELSE 'Not applicable'
END AS IsClustered,
'' as ServerEnvironment,
'' as ServerStatus,
'' as Comments
"@
$sql2 = @"
SELECT $AssetID as 'Asset_ID',database_id,
CONVERT(VARCHAR(25), DB.name) AS dbName,
CONVERT(VARCHAR(10), DATABASEPROPERTYEX(name, 'status')) AS [Status],
state_desc,
(SELECT COUNT(1) FROM sys.master_files WHERE DB_NAME(database_id) = DB.name AND type_desc = 'rows') AS DataFiles,
(SELECT SUM((size*8)/1024) FROM sys.master_files WHERE DB_NAME(database_id) = DB.name AND type_desc = 'rows') AS [Data MB],
(SELECT COUNT(1) FROM sys.master_files WHERE DB_NAME(database_id) = DB.name AND type_desc = 'log') AS LogFiles,
(SELECT SUM((size*8)/1024) FROM sys.master_files WHERE DB_NAME(database_id) = DB.name AND type_desc = 'log') AS [Log MB],
user_access_desc AS [User access],
recovery_model_desc AS [Recovery model],
CASE compatibility_level
WHEN 60 THEN '60 (SQL Server 6.0)'
WHEN 65 THEN '65 (SQL Server 6.5)'
WHEN 70 THEN '70 (SQL Server 7.0)'
WHEN 80 THEN '80 (SQL Server 2000)'
WHEN 90 THEN '90 (SQL Server 2005)'
WHEN 100 THEN '100 (SQL Server 2008)'
WHEN 110 THEN '110 (SQL Server 2012)'
WHEN 120 THEN '120 (SQL Server 2014)'
WHEN 130 THEN '130 (SQL Server 2016)'
WHEN 140 THEN '140 (SQL Server 2017)'
END AS [compatibility level],
CONVERT(VARCHAR(20), create_date, 103) + ' ' + CONVERT(VARCHAR(20), create_date, 108) AS [Creation date],
-- last backup
ISNULL((SELECT TOP 1
CASE TYPE WHEN 'D' THEN 'Full' WHEN 'I' THEN 'Differential' WHEN 'L' THEN 'Transaction log' END + ' – ' +
LTRIM(ISNULL(STR(ABS(DATEDIFF(DAY, GETDATE(),Backup_finish_date))) + ' days ago', 'NEVER')) + ' – ' +
CONVERT(VARCHAR(20), backup_start_date, 103) + ' ' + CONVERT(VARCHAR(20), backup_start_date, 108) + ' – ' +
CONVERT(VARCHAR(20), backup_finish_date, 103) + ' ' + CONVERT(VARCHAR(20), backup_finish_date, 108) +
' (' + CAST(DATEDIFF(second, BK.backup_start_date,
BK.backup_finish_date) AS VARCHAR(4)) + ' '
+ 'seconds)'
FROM msdb..backupset BK WHERE BK.database_name = DB.name ORDER BY backup_set_id DESC),'-') AS [Last backup],
CASE WHEN is_fulltext_enabled = 1 THEN 'Fulltext enabled' ELSE '' END AS [fulltext],
CASE WHEN is_auto_close_on = 1 THEN 'autoclose' ELSE '' END AS [autoclose],
page_verify_option_desc AS [page verify option],
CASE WHEN is_read_only = 1 THEN 'read only' ELSE '' END AS [read only],
CASE WHEN is_auto_shrink_on = 1 THEN 'autoshrink' ELSE '' END AS [autoshrink],
CASE WHEN is_in_standby = 1 THEN 'standby' ELSE '' END AS [standby],
CASE WHEN is_cleanly_shutdown = 1 THEN 'cleanly shutdown' ELSE '' END AS [cleanly shutdown] FROM sys.databases DB
WHERE CONVERT(VARCHAR(25), DB.name) NOT IN ('DBAMaintain','Master','Model','MSDB','TempDB')
ORDER BY dbName, [Last backup] DESC, NAME
"@
}
process {
$MyResults = Invoke-DbaQuery -ServerInstance $AssetName -Database Master -Query $sql | ConvertTo-DbaDataTable
Write-DbaDataTable -InputObject $MyResults -SqlInstance localhost -Database ITAM -Table Stage.SQL_Instance_Info -AutoCreateTable -Verbose
$MyResults = Invoke-DbaQuery -ServerInstance $AssetName -Database Master -Query $sql2 | ConvertTo-DbaDataTable
Write-DbaDataTable -InputObject $MyResults -SqlInstance localhost -Database ITAM -Table Stage.SQL_Database_Info -AutoCreateTable -Verbose
}
} | 48.105691 | 145 | 0.680919 |
9ab9512ccfa0963e50d982c8148ed3fb5d057ea6 | 2,916 | py | Python | energy_demand/scripts/cluster_execution.py | nismod/energy_demand | 247fcea074a846026710ed9b039b22f8b9835643 | [
"MIT"
] | 14 | 2018-02-23T10:03:45.000Z | 2022-03-03T13:59:30.000Z | energy_demand/scripts/cluster_execution.py | nismod/energy_demand | 247fcea074a846026710ed9b039b22f8b9835643 | [
"MIT"
] | 59 | 2017-02-22T15:03:30.000Z | 2020-12-16T12:26:17.000Z | energy_demand/scripts/cluster_execution.py | nismod/energy_demand | 247fcea074a846026710ed9b039b22f8b9835643 | [
"MIT"
] | 5 | 2017-08-22T11:31:42.000Z | 2020-06-24T18:30:12.000Z | import os
import subprocess
from multiprocessing import Pool, cpu_count
import numpy as np
from energy_demand.read_write import read_weather_data
def my_function(simulation_number):
print('simulation_number ' + str(simulation_number))
run_name = '_low'
all_weather_stations = False
same_weather_yr = True
defined_weather_yr = 2015
run_smif = False
# --------------------------
# Get all weather yrs with data (maybe read existing years from data folder)
# and select weather yr
# --------------------------
path_to_weather_data = "/soge-home/staff/cenv0553/data/_raw_data/A-temperature_data/cleaned_weather_stations_data"
weather_yrs_stations = read_weather_data.get_all_station_per_weather_yr(path_to_weather_data, min_nr_of_stations=30)
weather_yrs = list(weather_yrs_stations.keys())
print("all weather yrs: " + str(weather_yrs))
print("Total nr of stations: " + str(len(weather_yrs)))
if same_weather_yr:
weather_yr = defined_weather_yr
else:
weather_yr = weather_yrs[simulation_number]
# --------------------------
# Select weather station
# --------------------------
if all_weather_stations:
weather_station_cnt = [] #All stationssimulation_number
else:
weather_station_cnt = simulation_number
# Make run name_specifiv
run_name = "{}_{}".format(run_name, simulation_number)
# Run energy demand main.py
if run_smif:
# Run smif
#bash_command = "smif -v run ed_constrained_pop-baseline16_econ-c16_fuel-c16"
#os.system(bash_command)
pass
else:
bash_command = "python energy_demand/energy_demand/main.py {} {} {}".format(run_name, weather_yr, weather_station_cnt)
os.system(bash_command)
return
# WEather years
simulation_number = range(10)
if __name__ == "__main__":
with Pool(int(cpu_count()/2)) as pool:
pool.map(
my_function,
simulation_number,
chunksize=1)
'''
for i in range(2):
print("run " + str(i))
# Activate virtual environement
bashCommand = "activate ed"
os.system(bashCommand)
# Run smif
bashCommand = "smif -v run ed_constrained_pop-baseline16_econ-c16_fuel-c16"
os.system(bashCommand)
#process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
#output, error = process.communicate()
'''
'''
#import this
from multiprocessing import Pool, cpu_count
#import any other packages
import numpy as np
def my_function(simulation_number):
print('simulation_number')
return
simulation_list = [1,2,3,4,5,6,7,8,9,10]
if __name__ == "__main__":
with Pool(int(cpu_count()/2)) as pool:
pool.map(my_function,simulation_list,chunksize=1)
#import sh
#sh.cd('C:/Users/cenv0553/ed')
#print(sh.pwd())
#stream = os.popen("cd C:/Users/cenv0553/ed")
''' | 27.771429 | 126 | 0.662209 |
7f531cc2031817b6dcfa08de33b3c2732505a1ba | 3,366 | php | PHP | application/controllers/Pindahprodi_user.php | alexistdev/ebaak | 66274defb236514badf20dc2b28aa5ecd776cc74 | [
"MIT"
] | null | null | null | application/controllers/Pindahprodi_user.php | alexistdev/ebaak | 66274defb236514badf20dc2b28aa5ecd776cc74 | [
"MIT"
] | null | null | null | application/controllers/Pindahprodi_user.php | alexistdev/ebaak | 66274defb236514badf20dc2b28aa5ecd776cc74 | [
"MIT"
] | 2 | 2021-11-11T07:56:36.000Z | 2021-12-22T03:15:20.000Z | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Pindahprodi_user extends CI_Controller
{
public $form_validation;
public $session;
public $input;
public $admin;
public $idUser;
public $upload;
/** Constructor dari Class Pindahprodi_user */
public function __construct()
{
parent::__construct();
$this->load->model('m_admin', 'admin');
$this->idUser = $this->session->userdata('idUser');
if ($this->session->userdata('is_user_login') !== TRUE) {
redirect('Login');
}
}
/** Template untuk memanggil view */
private function _template($data, $view)
{
$this->load->view('mahasiswa/views/' . $view, $data);
}
/** Menampilkan halaman index Pindahprodi_user */
public function index()
{
$this->form_validation->set_rules(
'proditujuan',
'Prodi Tujuan',
'trim|required',
[
'required' => 'Prodi Tujuan harus diisi!'
]
);
$this->form_validation->set_rules(
'alasan',
'Alasan',
'trim|required',
[
'required' => 'Alasan harus diisi!'
]
);
$this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
if ($this->form_validation->run() === false) {
$this->session->set_flashdata('notif1', validation_errors());
$data['title'] = "Dashboard | Ebaak - Layanan BAAK Darmajaya";
$view = 'v_pindahprodi';
$this->_template($data, $view);
}else{
$getDataprodi = $this->admin->get_pindahprodi_iduser($this->idUser);
if ($getDataprodi->num_rows() != 0){
$this->session->set_flashdata('notif2', '<div class="alert alert-danger" role="alert">Anda sudah mengajukan Surat Pindah Program Studi sebelumnya!</div>');
redirect("mahasiswa/riwayat");
} else {
$proditujuan= $this->input->post("proditujuan", TRUE);
$alasan= $this->input->post("alasan", TRUE);
$namaFile = angkaUnik();
/** upload file rar */
$config['upload_path'] = './file/';
$config['allowed_types'] = 'rar';
$config['max_size'] = 8024;
$config['file_name'] = $namaFile;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('lampiran')){
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('notif2', '<div class="alert alert-danger" role="alert">'.$error['error'].'</div>');
redirect('mahasiswa/keterangan');
}else{
/** Menyimpan ke dalam tabel surat_pindahprodi */
$kodeSurat = angkaUnik();
$dataProdi = [
'id_user' => $this->idUser,
'nama_prodi' => $proditujuan,
'alasan_pindah' => $alasan,
'kode_surat' => $kodeSurat,
'lampiran' => base_url()."file/".$namaFile.".rar"
];
$this->admin->simpan_prodi($dataProdi);
/** Menyimpan ke dalam tabel riwayat_surat */
$tglNow = date("Y-m-d");
$dataRiwayat =[
'id_user' => $this->idUser,
'nama_surat' => "Surat Permohonan Pindah Program Studi",
'tanggal_surat' => $tglNow,
'kode_surat' => $kodeSurat,
'status_riwayat' => 3,
'type' => 8
];
$this->admin->simpan_riwayat($dataRiwayat);
$this->session->set_flashdata('notif2', '<div class="alert alert-success" role="alert">Surat Permohonan Pindah Program Studi berhasil didaftarkan, silahkan ditunggu proses selanjutnya!</div>');
redirect("mahasiswa/riwayat");
}
}
}
}
}
| 32.057143 | 198 | 0.626263 |
ed267fb23964cced6129dc8e573692f3dd7e32c1 | 906 | h | C | QClient/connectthread.h | KailinLi/QChat | ea5e762b31cc4769611516d4f6ca1a79ad0f93c1 | [
"MIT"
] | 4 | 2017-10-19T15:44:06.000Z | 2021-08-24T12:32:29.000Z | QClient/connectthread.h | KailinLi/QChat | ea5e762b31cc4769611516d4f6ca1a79ad0f93c1 | [
"MIT"
] | null | null | null | QClient/connectthread.h | KailinLi/QChat | ea5e762b31cc4769611516d4f6ca1a79ad0f93c1 | [
"MIT"
] | 1 | 2020-04-30T08:21:50.000Z | 2020-04-30T08:21:50.000Z | #ifndef CONNECTTHREAD_H
#define CONNECTTHREAD_H
#include <QObject>
#include "tcpsocketmsg.h"
class ConnectThread : public QThread
{
Q_OBJECT
public:
ConnectThread(int socketDescriptor, QObject* parent);
ConnectThread(const QString &address, quint16 port, quint32 userID, QObject *parent);
private:
int socketDescriptor;
volatile bool runThread;
quint32 userID;
public:
void run() Q_DECL_OVERRIDE;
void stop();
void setUserID(quint32 id);
quint32 getUserID();
TcpSocketMsg *tcpMsg;
signals:
void newMsg(ConnectThread*, Message*);
void error(TcpSocketMsg::SocketError socketError);
void loseConnect(ConnectThread*);
void setUpCommunication(ConnectThread*);
private slots:
void threadReadyRead();
void disconnect();
void connectSuccess();
public slots:
void sendMsg(ConnectThread*thread, Message*);
};
#endif // CONNECTTHREAD_H
| 23.230769 | 89 | 0.729581 |
07975857127b64fdf69f60e5a70ef1c608d73841 | 1,369 | rb | Ruby | lib/divergence/cache_manager.rb | layervault/divergence | 1ff4021d204afdf9fa1c672f405f6d1d0c435c1d | [
"Apache-2.0"
] | 22 | 2015-02-03T02:52:03.000Z | 2021-11-23T05:55:06.000Z | lib/divergence/cache_manager.rb | daenoor/divergence | cf11b697867887a7d8d00e14f00e6ff6cea25980 | [
"Apache-2.0"
] | 1 | 2015-10-26T15:59:46.000Z | 2015-10-28T19:45:52.000Z | lib/divergence/cache_manager.rb | daenoor/divergence | cf11b697867887a7d8d00e14f00e6ff6cea25980 | [
"Apache-2.0"
] | 6 | 2015-03-11T21:09:57.000Z | 2019-12-02T13:31:08.000Z | module Divergence
class CacheManager
def initialize(cache_path, cache_num)
@cache_path = cache_path
@cache_num = cache_num
Dir.chdir @cache_path do
@cached_branches = Dir['*/'].map {|dir| dir.gsub('/', '')}
end
end
def is_cached?(branch)
@cached_branches.include?(branch)
end
def add(branch, src_path)
Application.log.info "Caching: #{branch} from #{src_path}"
prune_cache!
Application.config.callback :before_cache, src_path, :branch => branch
FileUtils.mkdir_p path(branch)
sync branch, src_path
@cached_branches.push branch
Application.config.callback :after_cache, path(branch), :branch => branch
end
def sync(branch, src_path)
`rsync -a --delete --exclude .git --exclude .gitignore #{src_path}/ #{path(branch)}`
end
def path(branch)
"#{@cache_path}/#{branch}"
end
private
# Delete the oldest cached branches to make room for new
def prune_cache!
Dir.chdir @cache_path do
branches = Dir.glob('*/')
return if branches.nil? or branches.length <= @cache_num
branches \
.sort_by {|f| File.mtime(f)}[@cache_num..-1] \
.each do|dir|
FileUtils.rm_rf(dir)
@cached_branches.delete(dir.gsub('/', ''))
end
end
end
end
end
| 24.446429 | 90 | 0.607743 |
cd48d665fc75a3816547f33f03821647fade719a | 1,025 | cs | C# | src/EventSourced.Net.ReadModel/ReadModel/Users/UserIdByContactChallengeCorrelationId.cs | danludwig/eventsourced.net | 30f089a52d0bdb98e396459765c42c2231a01a80 | [
"MIT"
] | 8 | 2015-12-21T12:39:11.000Z | 2019-09-06T12:13:39.000Z | src/EventSourced.Net.ReadModel/ReadModel/Users/UserIdByContactChallengeCorrelationId.cs | danludwig/eventsourced.net | 30f089a52d0bdb98e396459765c42c2231a01a80 | [
"MIT"
] | null | null | null | src/EventSourced.Net.ReadModel/ReadModel/Users/UserIdByContactChallengeCorrelationId.cs | danludwig/eventsourced.net | 30f089a52d0bdb98e396459765c42c2231a01a80 | [
"MIT"
] | 4 | 2016-01-04T07:48:45.000Z | 2022-02-03T10:57:05.000Z | using System;
using System.Threading.Tasks;
using EventSourced.Net.ReadModel.Users.Internal.Documents;
using EventSourced.Net.ReadModel.Users.Internal.Queries;
namespace EventSourced.Net.ReadModel.Users
{
public class UserIdByContactChallengeCorrelationId : IQuery<Task<Guid?>>
{
public Guid CorrelationId { get; }
public UserIdByContactChallengeCorrelationId(Guid correlationId) {
CorrelationId = correlationId;
}
}
public class HandleUserIdByContactChallengeCorrelationId : IHandleQuery<UserIdByContactChallengeCorrelationId, Task<Guid?>>
{
private IExecuteQuery Query { get; }
public HandleUserIdByContactChallengeCorrelationId(IExecuteQuery query) {
Query = query;
}
public async Task<Guid?> Handle(UserIdByContactChallengeCorrelationId query) {
Guid? userId = null;
UserDocument user = await Query.Execute(new UserDocumentByContactChallengeCorrelationId(query.CorrelationId));
if (user != null) userId = user.Id;
return userId;
}
}
}
| 31.060606 | 125 | 0.757073 |
7df7cdbcfaa37efe32cb1e41b9deed153e129630 | 469 | rb | Ruby | spec/spec_helper.rb | thomasf1234/puppet-unit | 3c808b5120b4a252153b12b54bb762f21c3abd05 | [
"MIT"
] | null | null | null | spec/spec_helper.rb | thomasf1234/puppet-unit | 3c808b5120b4a252153b12b54bb762f21c3abd05 | [
"MIT"
] | null | null | null | spec/spec_helper.rb | thomasf1234/puppet-unit | 3c808b5120b4a252153b12b54bb762f21c3abd05 | [
"MIT"
] | null | null | null | ENV['ENV'] ||= 'test'
Bundler.require(:default, ENV['ENV'])
require "puppet-unit"
require "support/helpers/unit_helpers"
RSpec.configure do |config|
config.color= true
config.order= :rand
config.default_formatter = 'doc'
config.profile_examples = 10
config.warnings = true
config.raise_errors_for_deprecations!
config.disable_monkey_patching!
config.include SpecHelper::UnitHelpers
config.before(:each) do
PuppetUnit::Util.refresh_tmp
end
end | 23.45 | 40 | 0.754797 |
a127a7d5fe6650f77cc68123fff258f31a70a007 | 972 | ts | TypeScript | dist/Form/ValidatedForm.d.ts | tkdaj/react-validated-form | 8674a1f9f73203fbe08904bab2d42bdc076e0bc0 | [
"MIT"
] | 3 | 2020-10-17T12:03:31.000Z | 2020-10-22T13:02:17.000Z | dist/Form/ValidatedForm.d.ts | tkdaj/react-validated-form | 8674a1f9f73203fbe08904bab2d42bdc076e0bc0 | [
"MIT"
] | null | null | null | dist/Form/ValidatedForm.d.ts | tkdaj/react-validated-form | 8674a1f9f73203fbe08904bab2d42bdc076e0bc0 | [
"MIT"
] | null | null | null | import React from 'react';
import { IValidatedFormState, IValidatedFormProps } from './models';
export default class ValidatedForm extends React.Component<IValidatedFormProps, {
validationData: IValidatedFormState;
}> {
static defaultProps: {
customValidators: {};
hideNameWarnings: boolean;
formErrorClass: string;
};
state: {
validationData: {
submissionAttempted: boolean;
formIsValid: boolean;
formValues: {};
};
};
componentDidMount(): void;
componentDidUpdate(): void;
formRef: React.RefObject<HTMLFormElement>;
onFormSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
getFormData: () => {
validationData: {
submissionAttempted: boolean;
formIsValid: boolean;
formValues: {};
};
};
resetFormSubmitted: () => void;
render(): JSX.Element;
}
//# sourceMappingURL=ValidatedForm.d.ts.map | 30.375 | 81 | 0.622428 |
53c2506523aa65d60575e0c35727ea81f1aeac40 | 1,037 | lua | Lua | scripts/vscripts/lua_abilities/disruptor_thunder_strike_lua/disruptor_thunder_strike_lua.lua | GIANTCRAB/dota-2-lua-abilities | fb1c2a78444e50f879b1cbedf4e0060408478278 | [
"MIT"
] | 125 | 2018-03-26T21:35:49.000Z | 2022-03-31T21:01:38.000Z | scripts/vscripts/lua_abilities/disruptor_thunder_strike_lua/disruptor_thunder_strike_lua.lua | hanzhengit/dota-2-lua-abilities | c6d7b7cff8be6bc32f3580411f31c24b8c0b0eca | [
"MIT"
] | 2 | 2020-07-05T16:02:19.000Z | 2020-11-18T02:24:48.000Z | scripts/vscripts/lua_abilities/disruptor_thunder_strike_lua/disruptor_thunder_strike_lua.lua | hanzhengit/dota-2-lua-abilities | c6d7b7cff8be6bc32f3580411f31c24b8c0b0eca | [
"MIT"
] | 40 | 2019-03-02T11:17:10.000Z | 2022-03-31T05:45:26.000Z | -- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
disruptor_thunder_strike_lua = class({})
LinkLuaModifier( "modifier_disruptor_thunder_strike_lua", "lua_abilities/disruptor_thunder_strike_lua/modifier_disruptor_thunder_strike_lua", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
-- Ability Start
function disruptor_thunder_strike_lua:OnSpellStart()
-- unit identifier
local caster = self:GetCaster()
local target = self:GetCursorTarget()
-- add modifier
target:AddNewModifier(
caster, -- player source
self, -- ability source
"modifier_disruptor_thunder_strike_lua", -- modifier name
{} -- kv
)
-- play effects
local sound_cast = "Hero_Disruptor.ThunderStrike.Cast"
EmitSoundOn( sound_cast, caster )
end | 31.424242 | 168 | 0.664417 |
a356cbaa26762e749012aac9590b59d3b5008a7a | 5,282 | java | Java | Source/Plugins/Core/com.equella.core/src/com/tle/web/search/filter/ResetFiltersSection.java | infiniticg/equella | 75ddd69bca3a94e213705dcfe90cf7077cc89872 | [
"Apache-2.0"
] | 1 | 2018-07-25T02:34:16.000Z | 2018-07-25T02:34:16.000Z | Source/Plugins/Core/com.equella.core/src/com/tle/web/search/filter/ResetFiltersSection.java | infiniticg/equella | 75ddd69bca3a94e213705dcfe90cf7077cc89872 | [
"Apache-2.0"
] | null | null | null | Source/Plugins/Core/com.equella.core/src/com/tle/web/search/filter/ResetFiltersSection.java | infiniticg/equella | 75ddd69bca3a94e213705dcfe90cf7077cc89872 | [
"Apache-2.0"
] | 1 | 2018-04-11T20:31:51.000Z | 2018-04-11T20:31:51.000Z | /*
* Copyright 2017 Apereo
*
* 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.tle.web.search.filter;
import java.util.List;
import com.tle.core.guice.Bind;
import com.tle.core.guice.Type;
import com.tle.web.freemarker.FreemarkerFactory;
import com.tle.web.freemarker.annotations.ViewFactory;
import com.tle.web.search.base.AbstractSearchResultsSection;
import com.tle.web.sections.SectionInfo;
import com.tle.web.sections.SectionResult;
import com.tle.web.sections.SectionTree;
import com.tle.web.sections.annotations.EventFactory;
import com.tle.web.sections.annotations.EventHandlerMethod;
import com.tle.web.sections.annotations.TreeLookup;
import com.tle.web.sections.equella.annotation.PlugKey;
import com.tle.web.sections.equella.search.SearchResultsActionsSection;
import com.tle.web.sections.equella.search.event.AbstractSearchResultsEvent;
import com.tle.web.sections.equella.search.event.SearchResultsListener;
import com.tle.web.sections.events.RenderEventContext;
import com.tle.web.sections.events.js.EventGenerator;
import com.tle.web.sections.generic.AbstractPrototypeSection;
import com.tle.web.sections.render.HtmlRenderer;
import com.tle.web.sections.render.Label;
import com.tle.web.sections.result.util.KeyLabel;
import com.tle.web.sections.standard.Button;
import com.tle.web.sections.standard.annotations.Component;
@Bind(value = ResetFiltersSection.class, types = @Type(unknown = true, value = Object.class))
public class ResetFiltersSection<RE extends AbstractSearchResultsEvent<RE>>
extends
AbstractPrototypeSection<ResetFiltersSection.Model> implements SearchResultsListener<RE>, HtmlRenderer
{
private static final String DIV_ID = "searchform-filteredout"; //$NON-NLS-1$
@ViewFactory
private FreemarkerFactory viewFactory;
@EventFactory
private EventGenerator events;
@PlugKey("search.generic.filteredout")
private static String KEY_FILTEREDOUT;
@PlugKey("search.generic.filteredout1")
private static String KEY_FILTEREDOUT1;
@PlugKey("search.generic.filtersinplace")
private static String KEY_FILTERS_IN_PLACE;
@Component
@PlugKey("search.generic.clearfilters")
private Button resetButton;
@TreeLookup
private AbstractSearchResultsSection<?, ?, ?, ?> searchResultsSection;
@TreeLookup
private SearchResultsActionsSection searchResultsActionsSection;
@SuppressWarnings("nls")
@Override
public void treeFinished(String id, SectionTree tree)
{
resetButton.setClickHandler(searchResultsSection.getResultsUpdater(tree,
events.getEventHandler("resetFilters"), searchResultsActionsSection.getResetFilterAjaxIds()));
}
public void addAjaxDiv(List<String> ajaxDivs)
{
ajaxDivs.add(DIV_ID);
}
@SuppressWarnings("nls")
@Override
public SectionResult renderHtml(RenderEventContext context)
{
return viewFactory.createResult("filter/resetfilters.ftl", this);
}
@EventHandlerMethod
public void resetFilters(SectionInfo info)
{
info.processEvent(new ResetFiltersEvent());
}
/**
* In the typical case, this class applies to an internal search where the
* search can determine how many elements would be returned for an
* unfiltered search, and thus the filteredOut value, where non-zero, can be
* used to inform the user of the actual number excluded by the filters.
* Where an external search service (such a the Flickr service) is being
* queried, we content ourselves with setting the filteredOut value as
* Integer.MIN_VALUE, where a filter has been applied to the search (ie in
* addition to keyword search), to serve as a simple pseudo-boolean alerting
* the user to the fact that a filter is in place and therefore the result
* set ~may~ have been reduced by some unspecified number. Some SearchResult
* structures may return small negatives with an identical intent to
* returning zero (eg Hierarchy search), so -1 is an unsatisfactory choice
* for 'non-zero but unspecified', which is the intent of passing
* Integer.MIN_VALUE.
*/
@Override
public void processResults(SectionInfo info, RE results)
{
int filteredOut = results.getFilteredOut();
if( filteredOut > 0 )
{
getModel(info).setFilteredOutLabel(
new KeyLabel(filteredOut == 1 ? KEY_FILTEREDOUT1 : KEY_FILTEREDOUT, filteredOut));
}
else if( filteredOut == Integer.MIN_VALUE )
{
getModel(info).setFilteredOutLabel(new KeyLabel(KEY_FILTERS_IN_PLACE));
}
}
public Button getResetButton()
{
return resetButton;
}
@Override
public Object instantiateModel(SectionInfo info)
{
return new Model();
}
public static class Model
{
private Label filteredOutLabel;
public Label getFilteredOutLabel()
{
return filteredOutLabel;
}
public void setFilteredOutLabel(Label filteredOutLabel)
{
this.filteredOutLabel = filteredOutLabel;
}
}
}
| 34.298701 | 104 | 0.783226 |
b0a06ee8b28b672a39d134faee0dc99485892ccb | 3,554 | py | Python | aliyun-python-sdk-mse/aliyunsdkmse/request/v20190531/AddMockRuleRequest.py | yndu13/aliyun-openapi-python-sdk | 12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5 | [
"Apache-2.0"
] | null | null | null | aliyun-python-sdk-mse/aliyunsdkmse/request/v20190531/AddMockRuleRequest.py | yndu13/aliyun-openapi-python-sdk | 12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5 | [
"Apache-2.0"
] | null | null | null | aliyun-python-sdk-mse/aliyunsdkmse/request/v20190531/AddMockRuleRequest.py | yndu13/aliyun-openapi-python-sdk | 12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5 | [
"Apache-2.0"
] | null | null | null | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
from aliyunsdkmse.endpoint import endpoint_data
class AddMockRuleRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'mse', '2019-05-31', 'AddMockRule','mse')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_ExtraJson(self): # String
return self.get_query_params().get('ExtraJson')
def set_ExtraJson(self, ExtraJson): # String
self.add_query_param('ExtraJson', ExtraJson)
def get_ProviderAppId(self): # String
return self.get_query_params().get('ProviderAppId')
def set_ProviderAppId(self, ProviderAppId): # String
self.add_query_param('ProviderAppId', ProviderAppId)
def get_Source(self): # String
return self.get_query_params().get('Source')
def set_Source(self, Source): # String
self.add_query_param('Source', Source)
def get_Enable(self): # Boolean
return self.get_query_params().get('Enable')
def set_Enable(self, Enable): # Boolean
self.add_query_param('Enable', Enable)
def get_ScMockItems(self): # String
return self.get_query_params().get('ScMockItems')
def set_ScMockItems(self, ScMockItems): # String
self.add_query_param('ScMockItems', ScMockItems)
def get_ProviderAppName(self): # String
return self.get_query_params().get('ProviderAppName')
def set_ProviderAppName(self, ProviderAppName): # String
self.add_query_param('ProviderAppName', ProviderAppName)
def get_ConsumerAppIds(self): # String
return self.get_query_params().get('ConsumerAppIds')
def set_ConsumerAppIds(self, ConsumerAppIds): # String
self.add_query_param('ConsumerAppIds', ConsumerAppIds)
def get_DubboMockItems(self): # String
return self.get_query_params().get('DubboMockItems')
def set_DubboMockItems(self, DubboMockItems): # String
self.add_query_param('DubboMockItems', DubboMockItems)
def get_Name(self): # String
return self.get_query_params().get('Name')
def set_Name(self, Name): # String
self.add_query_param('Name', Name)
def get_AcceptLanguage(self): # String
return self.get_query_params().get('AcceptLanguage')
def set_AcceptLanguage(self, AcceptLanguage): # String
self.add_query_param('AcceptLanguage', AcceptLanguage)
def get_MockType(self): # Long
return self.get_query_params().get('MockType')
def set_MockType(self, MockType): # Long
self.add_query_param('MockType', MockType)
def get_Region(self): # String
return self.get_query_params().get('Region')
def set_Region(self, Region): # String
self.add_query_param('Region', Region)
| 37.808511 | 74 | 0.751266 |
39c33324115574d039aff7f0486449099a75bbe2 | 1,809 | rs | Rust | src/crd.rs | locmai/secret-generator-rs | e057ca93e55139637a6b664acd307fca0c25eaf1 | [
"MIT"
] | 8 | 2022-01-23T17:40:02.000Z | 2022-03-15T14:17:35.000Z | src/crd.rs | locmai/secret-generator-rs | e057ca93e55139637a6b664acd307fca0c25eaf1 | [
"MIT"
] | 5 | 2022-01-26T17:05:57.000Z | 2022-01-29T11:04:12.000Z | src/crd.rs | locmai/secret-generator-rs | e057ca93e55139637a6b664acd307fca0c25eaf1 | [
"MIT"
] | null | null | null | use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
// use chrono::{DateTime, Utc};
#[allow(unused_imports)]
use apiexts::CustomResourceDefinition;
#[allow(unused_imports)]
use
k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1 as apiexts;
#[allow(unused_imports)]
use kube::{
api::{Api, Patch, PatchParams, ResourceExt},
runtime::wait::{await_condition, conditions},
Client, CustomResource, CustomResourceExt,
};
fn default_backend_value() -> String {
"Kubernetes".into()
}
fn default_status_value() -> String {
"Not ready".into()
}
#[derive(Deserialize, Serialize, Clone, Debug, JsonSchema)]
pub struct DeclaredSecretSpec {
pub name: String,
pub length: i32,
}
// SecretGenerator resource specification
#[derive(CustomResource, Deserialize, Serialize, Clone, Debug, JsonSchema)]
#[kube(
group = "locmai.dev",
version = "v1alpha1",
kind = "SecretGenerator",
plural = "secretgenerators",
namespaced,
status = "SecretGeneratorStatus",
category = "secretgenerator",
shortname = "sg",
printcolumn = r#"{"name":"Condition", "type":"string", "description":"condition of the secret-generator", "jsonPath":".status.condition"}, {"name":"Last updated", "type":"date", "description":"last updated timestamp of the secret-generator", "jsonPath":".status.last_updated"}"#
)]
pub struct SecretGeneratorSpec {
pub name: String,
pub secrets: Vec<DeclaredSecretSpec>,
#[serde(default = "default_backend_value")]
pub backend: String,
}
#[derive(Deserialize, Serialize, Clone, Debug, JsonSchema)]
pub struct SecretGeneratorStatus {
#[serde(default = "default_status_value")]
pub condition: String,
// #[schemars(schema_with = "set_datetime_schema")]
// pub last_updated: Option<DateTime<Utc>>
}
| 30.661017 | 282 | 0.706468 |
d485b66501eef9ce2945b9b9f5e1dd4eb4a08986 | 6,927 | sql | SQL | src/main/resources/docs/DB/wine-2017-08-06.sql | guhanjie/wine | a0ef1464b1524743c01e6d585ae7f0198a703680 | [
"Apache-2.0"
] | null | null | null | src/main/resources/docs/DB/wine-2017-08-06.sql | guhanjie/wine | a0ef1464b1524743c01e6d585ae7f0198a703680 | [
"Apache-2.0"
] | 3 | 2021-04-23T02:34:14.000Z | 2021-04-23T02:34:15.000Z | src/main/resources/docs/DB/wine-2017-08-06.sql | guhanjie/wine | a0ef1464b1524743c01e6d585ae7f0198a703680 | [
"Apache-2.0"
] | null | null | null | USE wine;
-- Table: bannar
ALTER TABLE `bannar`
ADD COLUMN `img` varchar(200) NULL COMMENT 'banner图片' AFTER `id`,
ADD COLUMN `title` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '图片居中标题' AFTER `img`,
ADD COLUMN `description` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL COMMENT '图片居中详述' AFTER `title`,
CHANGE COLUMN `index` `idx` smallint(6) UNSIGNED NULL DEFAULT NULL COMMENT 'bannar位置' AFTER `description`,
MODIFY COLUMN `idx` int(6) UNSIGNED NULL DEFAULT NULL COMMENT 'bannar位置' AFTER `description`,
ADD UNIQUE INDEX `IDX_idx` (`idx`) USING BTREE ;
-- Table: category
ALTER TABLE `category`
MODIFY COLUMN `level` int(6) NULL DEFAULT 1 COMMENT '目录层级' AFTER `name`,
ADD COLUMN `idx` int NULL COMMENT '本层级内的排列位置' AFTEsR `level`,
ADD UNIQUE INDEX `IDX_parent_id_idx` (`parent_id`, `idx`) USING BTREE ;
-- Table: item
ALTER TABLE `item`
MODIFY COLUMN `status` int(6) NULL DEFAULT 2 COMMENT '商品状态(1:上架、2:下架、3:删除)' AFTER `sales`,
DROP COLUMN `img2`,
DROP COLUMN `img3`,
DROP COLUMN `img4`,
DROP COLUMN `img5`,
DROP COLUMN `img6`,
DROP COLUMN `img7`,
DROP COLUMN `img8`,
DROP COLUMN `img9`,
DROP COLUMN `img10`,
CHANGE COLUMN `img1` `images` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '商品图片(以,分隔)' AFTER `status`,
CHANGE COLUMN `images` `detail_imgs` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '商品详情图片(以,分隔)' AFTER `status`,
ADD COLUMN `title_imgs` varchar(1000) NULL COMMENT '商品预览图片(以,分隔)' AFTER `status`;
-- Table: rush_item
ALTER TABLE `rush_item`
DROP COLUMN `img2`,
DROP COLUMN `img3`,
DROP COLUMN `img4`,
DROP COLUMN `img5`,
DROP COLUMN `img6`,
DROP COLUMN `img7`,
DROP COLUMN `img8`,
DROP COLUMN `img9`,
DROP COLUMN `img10`,
CHANGE COLUMN `img1` `images` varchar(1000) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '商品图片(以,分隔)' AFTER `end_time`;
-- Table: order
ALTER TABLE `order`
MODIFY COLUMN `status` int(6) NULL DEFAULT 1 COMMENT '订单状态(位表示法,第1位:是否下单,第2位:是否取消订单,第3位:是否开始送货,第4位:是否送货完成,第5位:是否支付完成)' AFTER `address`,
MODIFY COLUMN `pay_type` int(6) NULL DEFAULT 0 COMMENT '支付类型(0:微信支付,1:现金)' AFTER `pay_id`,
MODIFY COLUMN `pay_status` int(6) NULL DEFAULT 0 COMMENT '支付状态(0:未支付,1:支付成功,2:支付失败,3:转入退款,4:已关闭,5:已撤销(刷卡支付),6: 用户支付中)' AFTER `pay_type`,
CHANGE COLUMN `source` `spm` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '推广源跟踪(a.b.c.d)' AFTER `remark`,
ADD COLUMN `source_id` int(10) NULL COMMENT '订单来源商品id' AFTER `remark`,
ADD COLUMN `source_type` varchar(50) NULL COMMENT '订单来源类型(normal:普通商品,rush:1元购活动)' AFTER `item_id`;
--------------------------
-- initialize data
--------------------------
-- Table: bannar
INSERT INTO `bannar` (`id`, `img`, `title`, `description`, `idx`, `item_id`) VALUES ('1', 'images/banner-1.jpg', '经典洋河好酒', '酒体饱满丰润,珍藏版佳酿!', '1', '1');
INSERT INTO `bannar` (`id`, `img`, `title`, `description`, `idx`, `item_id`) VALUES ('2', 'images/banner-2.jpg', '长城 干红葡萄酒', '细选葡萄原料,用心酿制而成!', '2', '2');
INSERT INTO `bannar` (`id`, `img`, `title`, `description`, `idx`, `item_id`) VALUES ('3', 'images/banner-3.jpg', '茅台 15年贵州茅台酒', '天贵人和,厚德致远!', '3', '3');
INSERT INTO `bannar` (`id`, `img`, `title`, `description`, `idx`, `item_id`) VALUES ('4', 'images/banner-4.jpg', '郎酒 红花郎酒', '自然美景,良好水源,天宝洞藏!', '4', '4');
INSERT INTO `bannar` (`id`, `img`, `title`, `description`, `idx`, `item_id`) VALUES ('5', 'images/banner-5.jpg', '小糊涂仙 浓香型', '选用高粱,秉承传统工艺酿造而成!', '5', '5');
-- Table: category
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('1', '酒水', '1', '0');
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('2', '茶叶', '1', '0');
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('3', '礼品', '1', '0');
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('4', '集市', '1', '0');
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('5', '白酒', '2', '1');
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('6', '红酒', '2', '1');
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('7', '啤酒', '2', '1');
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('8', '碧螺春', '2', '2');
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('9', '龙井', '2', '2');
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('10', '海鲜', '2', '3');
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('11', '肉', '2', '3');
INSERT INTO `category` (`id`, `name`, `level`, `parent_id`) VALUES ('12', '鱼', '2', '3');
-- Table: item
INSERT INTO `item` (`id`, `name`, `icon`, `detail`, `category_id`, `normal_price`, `vip_price`, `back_points`, `sales`, `status`)
VALUES ('1', '泸州老窖 国窖 1573', 'images/product-1.jpg', '', '5', '1200', '800', '1000', '18', '1');
INSERT INTO `item` (`id`, `name`, `icon`, `detail`, `category_id`, `normal_price`, `vip_price`, `back_points`, `sales`, `status`)
VALUES ('2', '小糊涂仙 浓香型', 'images/product-2.jpg', '', '5', '1200', '800', '1000', '18', '1');
INSERT INTO `item` (`id`, `name`, `icon`, `detail`, `category_id`, `normal_price`, `vip_price`, `back_points`, `sales`, `status`)
VALUES ('3', '郎酒 红花郎酒', 'images/product-3.jpg', '', '5', '1200', '800', '1000', '18', '1');
INSERT INTO `item` (`id`, `name`, `icon`, `detail`, `category_id`, `normal_price`, `vip_price`, `back_points`, `sales`, `status`)
VALUES ('4', '茅台 15年贵州茅台酒', 'images/product-4.jpg', '', '5', '1200', '800', '1000', '18', '1');
INSERT INTO `item` (`id`, `name`, `icon`, `detail`, `category_id`, `normal_price`, `vip_price`, `back_points`, `sales`, `status`)
VALUES ('5', '巴黎之花 PerrierJouet特级干型香槟', 'images/product-5.jpg', '', '6', '1200', '800', '1000', '18', '1');
INSERT INTO `item` (`id`, `name`, `icon`, `detail`, `category_id`, `normal_price`, `vip_price`, `back_points`, `sales`, `status`)
VALUES ('6', '长城 干红葡萄酒', 'images/product-6.jpg', '', '6', '1200', '800', '1000', '18', '1');
INSERT INTO `item` (`id`, `name`, `icon`, `detail`, `category_id`, `normal_price`, `vip_price`, `back_points`, `sales`, `status`)
VALUES ('7', '1664白啤酒', 'images/product-7.jpg', '', '7', '1200', '800', '1000', '18', '1');
INSERT INTO `item` (`id`, `name`, `icon`, `detail`, `category_id`, `normal_price`, `vip_price`, `back_points`, `sales`, `status`)
VALUES ('8', 'Baileys/百利甜酒 爱尔兰甜酒', 'images/product-8.jpg', '', '7', '1200', '800', '1000', '18', '1');
-- Table: rush_item
INSERT INTO `rush_item` (`id`, `name`, `icon`, `detail`, `category_id`, `normal_price`, `vip_price`, `back_points`, `buyers`, `counts`, `status`)
VALUES ('1', '经典海之蓝', 'images/offer-1 (2).jpg', '', '5', '1200', '800', '1000', 198, 98, 1);
INSERT INTO `rush_item` (`id`, `name`, `icon`, `detail`, `category_id`, `normal_price`, `vip_price`, `back_points`, `buyers`, `counts`, `status`)
VALUES ('2', '法国精品葡萄酒', 'images/offer-8.jpg', '', '5', '1200', '800', '1000', 198, 98, 1); | 67.252427 | 155 | 0.636495 |
e3ea4e2c28a58d3724c5437090868cd65a9bfecc | 178 | rb | Ruby | app/jobs/shipit/clear_git_cache_job.rb | goodtouch/shipit-engine | 770d52701a0d4f7d7295fef99a1fa145fc2fd0ff | [
"MIT"
] | 1,299 | 2015-05-21T23:01:51.000Z | 2022-03-24T23:58:31.000Z | app/jobs/shipit/clear_git_cache_job.rb | goodtouch/shipit-engine | 770d52701a0d4f7d7295fef99a1fa145fc2fd0ff | [
"MIT"
] | 630 | 2015-05-21T21:57:16.000Z | 2022-03-14T16:15:40.000Z | app/jobs/shipit/clear_git_cache_job.rb | powerhome/shipit-engine | 76cca4764d815660b85210eed41d5b9d3c8a97a4 | [
"MIT"
] | 161 | 2015-05-27T02:02:40.000Z | 2022-03-25T05:14:53.000Z | # frozen_string_literal: true
module Shipit
class ClearGitCacheJob < BackgroundJob
queue_as :deploys
def perform(stack)
stack.clear_git_cache!
end
end
end
| 16.181818 | 40 | 0.730337 |
d16a5acce64375a9284f21d9bf6a23e9fb925f31 | 18,930 | sql | SQL | sql/archived/crapi_JULY22_2019.sql | renzsanchez69/Crapi_admin | 9646a1205379a7619a8bc756257a67f55544fd20 | [
"MIT"
] | null | null | null | sql/archived/crapi_JULY22_2019.sql | renzsanchez69/Crapi_admin | 9646a1205379a7619a8bc756257a67f55544fd20 | [
"MIT"
] | null | null | null | sql/archived/crapi_JULY22_2019.sql | renzsanchez69/Crapi_admin | 9646a1205379a7619a8bc756257a67f55544fd20 | [
"MIT"
] | null | null | null | -- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Jul 21, 2019 at 07:11 PM
-- Server version: 10.1.28-MariaDB
-- PHP Version: 5.6.32
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!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 utf8mb4 */;
--
-- Database: `crapi`
--
-- --------------------------------------------------------
--
-- Table structure for table `admins`
--
CREATE TABLE `admins` (
`id` int(10) UNSIGNED NOT NULL,
`status` int(11) NOT NULL DEFAULT '1' COMMENT '1:active; 2:stop',
`firstname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`lastname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`address` text COLLATE utf8mb4_unicode_ci,
`contact_number` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`gender` enum('male','female','others') COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`username` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`display_photo` text COLLATE utf8mb4_unicode_ci,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `admins`
--
INSERT INTO `admins` (`id`, `status`, `firstname`, `lastname`, `address`, `contact_number`, `gender`, `username`, `email`, `display_photo`, `password`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 1, 'Admin', 'Istrator', NULL, NULL, 'male', 'admin', '[email protected]', NULL, '$2y$10$OMSeK8Pe70nIHjkiTFLm8uX72fErkZKP6B4H6z7nZcakdPlMsayxe', NULL, NULL, NULL);
-- --------------------------------------------------------
--
-- Table structure for table `customers`
--
CREATE TABLE `customers` (
`id` int(10) UNSIGNED NOT NULL,
`login_token` varchar(300) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`status` int(11) NOT NULL DEFAULT '1' COMMENT '1:active; 2:stop',
`firstname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`lastname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`address` text COLLATE utf8mb4_unicode_ci,
`contact_number` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`gender` enum('male','female') COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`longitude` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`latitude` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `customers`
--
INSERT INTO `customers` (`id`, `login_token`, `password`, `status`, `firstname`, `lastname`, `address`, `contact_number`, `gender`, `email`, `longitude`, `latitude`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'e04dfb0249d0733aff5cf2dbd6e18053780ebfc693dd', '$2y$10$6FxP4VobegfLnXCFBQPrcezAU3HhECpKWPSs4ladWM0TmGpWGMujW', 1, 'Customer ', 'One', '887 MJ Cuenco Ave., Cebu City', '09876542310', 'female', '[email protected]', NULL, NULL, '2019-07-10 15:27:12', '2019-07-20 23:30:50', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `employees`
--
CREATE TABLE `employees` (
`id` int(10) UNSIGNED NOT NULL,
`login_token` varchar(300) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`owner_id` int(10) UNSIGNED NOT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`status` int(11) NOT NULL DEFAULT '1' COMMENT '1:active; 2:stop',
`firstname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`lastname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`address` text COLLATE utf8mb4_unicode_ci,
`contact_number` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`gender` enum('male','female') COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `employees`
--
INSERT INTO `employees` (`id`, `login_token`, `owner_id`, `password`, `status`, `firstname`, `lastname`, `address`, `contact_number`, `gender`, `email`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, NULL, 1, '$2y$10$OMSeK8Pe70nIHjkiTFLm8uX72fErkZKP6B4H6z7nZcakdPlMsayxe', 1, 'Employee', 'One', 'test address emp 1', '09876542310', 'male', '[email protected]', NULL, '2019-06-27 16:12:37', NULL),
(2, NULL, 2, '$2y$10$OMSeK8Pe70nIHjkiTFLm8uX72fErkZKP6B4H6z7nZcakdPlMsayxe', 1, 'Employee', 'Two', '887 MJ Cuenco Ave., Cebu City', '9994092682', 'female', '[email protected]', '2019-06-27 14:25:13', '2019-06-27 14:25:13', NULL),
(4, NULL, 1, '$2y$10$8O1cvyW/rcqKJDdxW5eaFechHALxEupsjP1Qg/7tS4KvaECTFON9i', 1, 'Employee', 'Three', '887 MJ Cuenco Ave., Cebu City', '09876542310', 'male', '[email protected]', '2019-07-03 17:01:47', '2019-07-03 17:01:56', NULL),
(5, NULL, 1, '$2y$10$gY9/6MUdfBBni9PpcVLxMuU.IDIrMn7Y8TJ5i69ILfbSjAzC/uksq', 1, 'Karl', 'Lim', '887 MJ Cuenco Ave., Cebu City', '879678867856', 'male', 'user1', '2019-07-10 14:09:48', '2019-07-10 14:09:48', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `orders`
--
CREATE TABLE `orders` (
`id` int(10) UNSIGNED NOT NULL,
`order_hash` varchar(100) NOT NULL,
`customer_id` int(10) UNSIGNED NOT NULL,
`resto_id` int(11) NOT NULL,
`employee_id` int(11) DEFAULT NULL,
`order_status` enum('pending','success','failed') NOT NULL DEFAULT 'pending',
`is_approved` tinyint(2) NOT NULL DEFAULT '0' COMMENT '0:default; 1:customer request approval; 2:employee approved order',
`is_paid` tinyint(2) NOT NULL DEFAULT '0',
`is_preparing` tinyint(2) NOT NULL DEFAULT '0',
`is_delivered` tinyint(2) NOT NULL DEFAULT '0',
`is_received` tinyint(2) NOT NULL DEFAULT '0',
`payment_type` enum('paymaya','coa') DEFAULT NULL,
`cod_cash` int(11) DEFAULT NULL,
`delivery_address` text NOT NULL,
`longitude` varchar(200) DEFAULT NULL,
`latitude` varchar(200) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`order_number` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `orders`
--
INSERT INTO `orders` (`id`, `order_hash`, `customer_id`, `resto_id`, `employee_id`, `order_status`, `is_approved`, `is_paid`, `is_preparing`, `is_delivered`, `is_received`, `payment_type`, `cod_cash`, `delivery_address`, `longitude`, `latitude`, `created_at`, `updated_at`, `order_number`) VALUES
(1, 'CRP_11562857715', 1, 1, NULL, 'success', 1, 1, 1, 1, 1, 'coa', 250, '', '123.88655871429444', '10.319753253345784', '2019-07-11 15:08:35', '2019-07-20 15:26:54', '11562857715'),
(2, 'CRP_11562858786', 1, 1, NULL, 'success', 1, 1, 1, 1, 1, 'coa', 120, '', '123.89080733337403', '10.312997802106642', '2019-07-11 15:26:26', '2019-07-20 15:26:59', '11562858786'),
(3, 'CRP_11562865912', 1, 1, NULL, 'pending', 1, 1, 1, 1, 0, 'paymaya', NULL, '', '123.8861724761963', '10.314940009186753', '2019-07-11 17:25:12', '2019-07-20 15:27:39', '11562865912'),
(4, 'CRP_11562866445', 1, 1, NULL, 'pending', 1, 1, 1, 0, 0, 'coa', 50, '193 Don Mariano Cui St, Cebu City, Cebu, Philippines', '123.89059275665284', '10.313842241439719', '2019-07-11 17:34:05', '2019-07-20 17:22:42', '11562866445'),
(5, 'CRP_11563461501', 1, 1, NULL, 'pending', 2, 1, 1, 0, 0, 'coa', 300, '', '123.89174938201904', '10.309514853436628', '2019-07-18 14:51:41', '2019-07-20 15:27:24', '11563461501'),
(6, 'CRP_11563464578', 1, 2, 1, 'pending', 2, 1, 1, 0, 0, 'coa', 100, '', '123.88788908996582', '10.322962041884372', '2019-07-18 15:42:58', '2019-07-20 15:27:24', '11563464578'),
(7, 'CRP_11563545030', 1, 1, 1, 'success', 2, 0, 1, 1, 1, 'coa', 200, '', '123.89171547358524', '10.321035765081083', '2019-07-19 14:03:50', '2019-07-20 15:27:24', '11563545030'),
(8, 'CRP_11563611169', 1, 1, 1, 'pending', 2, 0, 1, 1, 0, 'coa', 220, '', '123.89503798763303', '10.311409351991191', '2019-07-20 08:26:09', '2019-07-20 15:48:26', '11563611169');
-- --------------------------------------------------------
--
-- Table structure for table `order_details`
--
CREATE TABLE `order_details` (
`id` int(10) UNSIGNED NOT NULL,
`order_id` int(10) UNSIGNED NOT NULL,
`product_id` int(10) UNSIGNED NOT NULL,
`qty` int(10) UNSIGNED NOT NULL,
`price` int(10) UNSIGNED NOT NULL,
`sub_total` int(10) UNSIGNED NOT NULL,
`description_request` text,
`status` enum('pending','success','falied') NOT NULL DEFAULT 'pending',
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`order_status` enum('pending','success','falied') NOT NULL,
`resto_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `order_details`
--
INSERT INTO `order_details` (`id`, `order_id`, `product_id`, `qty`, `price`, `sub_total`, `description_request`, `status`, `created_at`, `updated_at`, `order_status`, `resto_id`) VALUES
(1, 1, 8, 2, 49, 98, '', 'pending', '2019-07-11 15:08:35', '2019-07-11 15:08:35', 'pending', 1),
(2, 1, 7, 2, 49, 98, '', 'pending', '2019-07-11 15:08:38', '2019-07-11 15:08:38', 'pending', 0),
(3, 2, 8, 1, 49, 49, '', 'pending', '2019-07-11 15:26:26', '2019-07-11 15:26:26', 'pending', 1),
(4, 2, 7, 1, 49, 49, '', 'pending', '2019-07-11 15:26:28', '2019-07-11 15:26:28', 'pending', 0),
(5, 3, 8, 2, 49, 98, '', 'pending', '2019-07-11 17:25:12', '2019-07-11 17:25:12', 'pending', 1),
(6, 3, 6, 2, 50, 100, '', 'pending', '2019-07-11 17:25:15', '2019-07-11 17:25:15', 'pending', 0),
(7, 4, 8, 1, 49, 49, '', 'pending', '2019-07-11 17:34:05', '2019-07-11 17:34:05', 'pending', 1),
(8, 5, 3, 2, 69, 138, '', 'pending', '2019-07-18 14:51:41', '2019-07-18 14:51:41', 'pending', 1),
(9, 5, 8, 2, 49, 98, '', 'pending', '2019-07-18 14:51:44', '2019-07-18 14:51:44', 'pending', 0),
(10, 6, 9, 2, 50, 100, '', 'pending', '2019-07-18 15:42:58', '2019-07-18 15:42:58', 'pending', 2),
(11, 7, 8, 3, 49, 147, '', 'pending', '2019-07-19 14:03:50', '2019-07-19 16:09:09', 'pending', 1),
(12, 7, 7, 1, 49, 49, '', 'pending', '2019-07-19 16:09:12', '2019-07-19 16:09:12', 'pending', 0),
(13, 8, 3, 1, 69, 69, '', 'pending', '2019-07-20 08:26:09', '2019-07-20 08:26:09', 'pending', 1),
(14, 8, 6, 1, 50, 50, '', 'pending', '2019-07-20 08:26:11', '2019-07-20 08:26:11', 'pending', 0),
(15, 8, 7, 2, 49, 98, '', 'pending', '2019-07-20 08:26:13', '2019-07-20 08:26:17', 'pending', 0);
-- --------------------------------------------------------
--
-- Table structure for table `owners`
--
CREATE TABLE `owners` (
`id` int(10) UNSIGNED NOT NULL,
`login_token` varchar(300) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`status` int(11) NOT NULL DEFAULT '1' COMMENT '1:active; 2:stop',
`firstname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`lastname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`address` text COLLATE utf8mb4_unicode_ci,
`contact_number` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`gender` enum('male','female') COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`subscription_end` datetime DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `owners`
--
INSERT INTO `owners` (`id`, `login_token`, `password`, `status`, `firstname`, `lastname`, `address`, `contact_number`, `gender`, `email`, `subscription_end`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'abc123', '$2y$10$OMSeK8Pe70nIHjkiTFLm8uX72fErkZKP6B4H6z7nZcakdPlMsayxe', 1, 'Owner', 'One', 'addresss11 1 1 ', '09876543219', 'male', '[email protected]', '2019-07-31 00:00:00', NULL, '2019-07-11 22:55:49', NULL),
(2, 'abc123', '$2y$10$OMSeK8Pe70nIHjkiTFLm8uX72fErkZKP6B4H6z7nZcakdPlMsayxe', 1, 'Owner', 'Two', 'addresss11 1 1 ', '09876543219', 'male', '[email protected]', '2019-07-31 00:00:00', NULL, NULL, NULL),
(3, NULL, '$2y$10$yF1alWea24fgXecI8z.aBOAkvP84ZRVybga6FLghEOmU6yHl8ANZW', 1, 'Own', 'One', 'rwerwe', '9994092682', 'male', '[email protected]', '2019-08-12 07:52:17', '2019-07-11 23:40:59', '2019-07-11 23:52:17', NULL);
-- --------------------------------------------------------
--
-- Table structure for table `products`
--
CREATE TABLE `products` (
`id` int(10) UNSIGNED NOT NULL,
`resto_id` int(10) UNSIGNED NOT NULL,
`name` varchar(50) NOT NULL,
`details` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
`type` enum('appetizer','main','dessert','beverage') CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`price` int(10) UNSIGNED NOT NULL,
`image_url` varchar(500) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `products`
--
INSERT INTO `products` (`id`, `resto_id`, `name`, `details`, `type`, `price`, `image_url`, `created_at`, `updated_at`) VALUES
(4, 2, 'Beer na Beer', 'beer', 'main', 40, NULL, NULL, '2019-06-26 15:14:34'),
(5, 2, 'RH Beer', 'beer', 'main', 30, NULL, NULL, '2019-06-27 14:26:48'),
(6, 1, 'Tosilog', 'longganisa itlog rice', 'main', 50, NULL, NULL, '2019-07-01 15:58:40'),
(7, 1, 'Kingsilog', 'longganisa itlog rice', 'main', 49, NULL, NULL, '2019-06-27 14:26:57'),
(8, 1, 'Logsilog', 'longganisa itlog rice', 'main', 49, NULL, NULL, '2019-06-27 14:26:57'),
(9, 2, 'Longsilog', 'longganisa itlog rice', 'main', 50, 'product_image/product_image_15620722405d1b54b055600.png', '2019-07-02 12:57:20', '2019-07-06 16:23:34'),
(10, 1, 'TestFood', 'longganisa itlog rice', 'main', 50, 'product_image/product_image_15637288965d349c0055e62.jpg', '2019-07-21 17:08:16', '2019-07-21 17:08:16');
-- --------------------------------------------------------
--
-- Table structure for table `restaurants`
--
CREATE TABLE `restaurants` (
`id` int(10) UNSIGNED NOT NULL,
`owner_id` int(10) UNSIGNED NOT NULL,
`employee_id` int(11) DEFAULT NULL,
`resto_name` varchar(50) NOT NULL,
`address` text,
`longitude` varchar(100) DEFAULT NULL,
`latitude` varchar(100) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `restaurants`
--
INSERT INTO `restaurants` (`id`, `owner_id`, `employee_id`, `resto_name`, `address`, `longitude`, `latitude`, `created_at`, `updated_at`) VALUES
(1, 1, NULL, 'ACT Restaurant', '123 ABC ', '123.64505005', '10.27353477', '2019-06-22 10:49:05', '2019-07-21 17:09:46'),
(2, 2, 2, 'Two Restaurant', '123 ABC ', '123.88694495239258', '10.3163755458492', '2019-06-22 10:49:05', '2019-07-21 17:08:49');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admins`
--
ALTER TABLE `admins`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `customers`
--
ALTER TABLE `customers`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `employees`
--
ALTER TABLE `employees`
ADD PRIMARY KEY (`id`),
ADD KEY `employees_owner_id_foreign` (`owner_id`);
--
-- Indexes for table `orders`
--
ALTER TABLE `orders`
ADD PRIMARY KEY (`id`),
ADD KEY `orders_customer_id_foreign` (`customer_id`);
--
-- Indexes for table `order_details`
--
ALTER TABLE `order_details`
ADD PRIMARY KEY (`id`),
ADD KEY `order_details_order_id_foreign` (`order_id`),
ADD KEY `order_details_product_id_foreign` (`product_id`);
--
-- Indexes for table `owners`
--
ALTER TABLE `owners`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `products`
--
ALTER TABLE `products`
ADD PRIMARY KEY (`id`),
ADD KEY `products_resto_id_foreign` (`resto_id`) USING BTREE;
--
-- Indexes for table `restaurants`
--
ALTER TABLE `restaurants`
ADD PRIMARY KEY (`id`),
ADD KEY `restaurants_owner_id_foreign` (`owner_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `admins`
--
ALTER TABLE `admins`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `customers`
--
ALTER TABLE `customers`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `employees`
--
ALTER TABLE `employees`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `orders`
--
ALTER TABLE `orders`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `order_details`
--
ALTER TABLE `order_details`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16;
--
-- AUTO_INCREMENT for table `owners`
--
ALTER TABLE `owners`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- AUTO_INCREMENT for table `products`
--
ALTER TABLE `products`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11;
--
-- AUTO_INCREMENT for table `restaurants`
--
ALTER TABLE `restaurants`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `employees`
--
ALTER TABLE `employees`
ADD CONSTRAINT `employees_owner_id_foreign` FOREIGN KEY (`owner_id`) REFERENCES `owners` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `orders`
--
ALTER TABLE `orders`
ADD CONSTRAINT `orders_customer_id_foreign` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `products`
--
ALTER TABLE `products`
ADD CONSTRAINT `products_resto_id_foreign` FOREIGN KEY (`resto_id`) REFERENCES `restaurants` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
--
-- Constraints for table `restaurants`
--
ALTER TABLE `restaurants`
ADD CONSTRAINT `restaurants_owner_id_foreign` FOREIGN KEY (`owner_id`) REFERENCES `owners` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
COMMIT;
/*!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 */;
| 43.617512 | 296 | 0.680085 |
8b469cd640936ccf5e1cbc081b331606ac0c628b | 5,963 | ps1 | PowerShell | src/poshBAR/SiteAdministration.ps1 | FutureStateMobile/fsm-posh | 23c631320a6b6b2c63ffee6d9d6be1234e073322 | [
"MS-PL"
] | 2 | 2017-01-25T15:00:03.000Z | 2017-04-26T13:38:38.000Z | src/poshBAR/SiteAdministration.ps1 | FutureStateMobile/fsm-posh | 23c631320a6b6b2c63ffee6d9d6be1234e073322 | [
"MS-PL"
] | null | null | null | src/poshBAR/SiteAdministration.ps1 | FutureStateMobile/fsm-posh | 23c631320a6b6b2c63ffee6d9d6be1234e073322 | [
"MS-PL"
] | null | null | null | $appcmd = "$env:windir\system32\inetsrv\appcmd.exe"
<#
.DESCRIPTION
Will create a Website with the specified settings if one doesn't exist.
.EXAMPLE
New-Site "myWebsite.com" "c:\inetpub\wwwroot" @(@{"protocol" = "http"; "port" = 80; "hostName"="mysite.com"}) "myAppPool" -updateIfFound
.PARAMETER siteName
The name of the Website that we are creating.
.PARAMETER sitePath
The physical path where this Website is located on disk.
.PARAMETER bindings
An Object Array of bindings. Must include "protocol", "port", and "hostName"
.PARAMETER appPoolName
The name of the app pool to use
.PARAMETER updateIfFound
Should we update an existing website if it already exists?
.SYNOPSIS
Will setup a website under the specified site name and AppPool.
#>
function New-Site{
[CmdletBinding()]
param(
[parameter(Mandatory=$true,position=0)] [string] $siteName,
[parameter(Mandatory=$true,position=1)] [string] $sitePath,
[parameter(Mandatory=$true,position=3)] [object[]] $bindings,
[parameter(Mandatory=$true,position=5)] [string] $appPoolName,
[parameter(Mandatory=$false,position=6)] [switch] $updateIfFound
)
Write-Host "Creating Site: $siteName" -NoNewLine
$exists = Confirm-SiteExists $siteName
if (!$exists) {
if($poshBAR.DisableCreateIISWebsite) {
throw $msgs.error_website_creation_disabled
}
$bindingString = @()
$bindings | % { $bindingString += "$($_.protocol)/*:$($_.port):$($_.hostName)" }
Exec { Invoke-Expression "$appcmd add site /name:$siteName /physicalPath:$sitePath /bindings:$($bindingString -join ",")"} -retry 10 | Out-Null
Exec { Invoke-Expression "$appcmd set app $siteName/ /applicationPool:$appPoolName"} -retry 10 | Out-Null
Write-Host "`tDone" -f Green
}else{
Write-Host "`tExists" -f Cyan
if ($updateIfFound.isPresent) {
Update-Site $siteName $sitePath $bindings $appPoolName
} else {
# Message
Write-Host ($msgs.msg_not_updating -f "Site")
}
}
}
<#
.DESCRIPTION
Will update a Website with the specified settings if one doesn't exist.
.EXAMPLE
Update-Site "myWebsite.com" "c:\inetpub\wwwroot" @(@{"protocol" = "http"; "port" = 80; "hostName"="mysite.com"}) "myAppPool"
.PARAMETER siteName
The name of the Website that we are updating.
.PARAMETER sitePath
The physical path where this Website is located on disk.
.PARAMETER bindings
An Object Array of bindings. Must include "protocol", "port", and "hostName"
.PARAMETER appPoolName
The name of the app pool to use
.SYNOPSIS
Will update a website under the specified site name and AppPool.
#>
function Update-Site{
param(
[parameter(Mandatory=$true,position=0)] [string] $siteName,
[parameter(Mandatory=$true,position=1)] [string] $sitePath,
[parameter(Mandatory=$true,position=3)] [object[]] $bindings,
[parameter(Mandatory=$true,position=5)] [string] $appPoolName
)
Write-Host "Updating Site: $siteName" -NoNewLine
$exists = Confirm-SiteExists $siteName
if ($exists){
$bindingString = @()
$bindings | % { $bindingString += "$($_.protocol)/*:$($_.port):$($_.hostName)" }
Exec { Invoke-Expression "$appcmd set Site $siteName/ /bindings:$($bindingString -join ",")"} -retry 10 | Out-Null
Exec { Invoke-Expression "$appcmd set App $siteName/ /applicationPool:$appPoolName"} -retry 10 | Out-Null
Exec { Invoke-Expression "$appcmd set App $siteName/ `"/[path='/'].physicalPath:$sitePath`""} -retry 10 | Out-Null
Write-Host "`tDone" -f Green
}else{
Write-Host "" #forces a new line
Write-Warning ($msgs.cant_find -f "Site",$siteName)
}
}
<#
.SYNOPSIS
Checks to see if a website already exists
.EXAMPLE
Confirm-SiteExists "myWebsite.com"
.PARAMETER siteName
Name of the website as it appears in IIS
#>
function Confirm-SiteExists{
[CmdletBinding()]
param([string] $siteName)
$getSite = Get-Site($siteName)
return ($getSite -ne $null)
}
<#
.SYNOPSIS
Removes an existing website
.EXAMPLE
Remove-Site "myWebsite.com"
.PARAMETER siteName
Name of the website as it appears in IIS
#>
function Remove-Site{
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string] $siteName)
$getSite = "$appcmd delete App $siteName/"
return Invoke-Expression $getSite
}
<#
.SYNOPSIS
Starts a website
.EXAMPLE
Start-Site "myWebsite.com"
.PARAMETER siteName
Name of the website as it appears in IIS
#>
function Start-Site{
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string] $siteName)
$getSite = "$appcmd start App $siteName/"
return Invoke-Expression $getSite
}
<#
.SYNOPSIS
Stops a website
.EXAMPLE
Stop-Site "myWebsite.com"
.PARAMETER siteName
Name of the website as it appears in IIS
#>
function Stop-Site{
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string] $siteName)
$getSite = "$appcmd stop App $siteName/"
return Invoke-Expression $getSite
}
<#
.SYNOPSIS
Gets a website's details
.EXAMPLE
Get-Site "myWebsite.com"
.PARAMETER siteName
Name of the website as it appears in IIS
#>
function Get-Site{
[CmdletBinding()]
param([Parameter(Mandatory=$true)][string] $siteName)
$getSite = "$appcmd list App $siteName/"
return Invoke-Expression $getSite
}
<#
.SYNOPSIS
Gets all websites from IIS
.EXAMPLE
Get-Sites
#>
function Get-Sites{
$getSite = "$appcmd list Apps"
Invoke-Expression $getSite
}
| 28.395238 | 152 | 0.629381 |
feb8e94e1b002aacfb9a162fd4561021d7960b42 | 15,318 | kt | Kotlin | ex/src/main/java/com/fox/one/ex/core/stream/StreamDataManager.kt | fox-one/foxone-opensdk-android | ebfb2e21a5c204b02c44a02625cf2a40eaca69fd | [
"Apache-2.0"
] | 2 | 2019-03-28T12:16:40.000Z | 2019-11-20T03:16:41.000Z | ex/src/main/java/com/fox/one/ex/core/stream/StreamDataManager.kt | fox-one/foxone-opensdk-android | ebfb2e21a5c204b02c44a02625cf2a40eaca69fd | [
"Apache-2.0"
] | null | null | null | ex/src/main/java/com/fox/one/ex/core/stream/StreamDataManager.kt | fox-one/foxone-opensdk-android | ebfb2e21a5c204b02c44a02625cf2a40eaca69fd | [
"Apache-2.0"
] | null | null | null | package com.fox.one.ex.core.stream
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import com.fox.one.ex.core.stream.model.*
import com.fox.one.support.common.concurrent.TaskScheduler
import com.fox.one.support.common.utils.JsonUtils
import com.fox.one.support.common.utils.LogUtils
import com.fox.one.support.framework.network.APILoader
import com.fox.one.support.framework.network.HttpEngine
import com.fox.one.support.framework.network.WebSocketEngine
import com.fox.one.support.framework.network.unGzip
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import java.net.URL
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CopyOnWriteArrayList
/**
* class description here
* @author [email protected]
* @version 1.0.0
* @since 2018-12-17
*/
object StreamDataManager {
private const val TAG = "StreamDataManager"
private const val ALPHA_URL = "https://dev-gateway.fox.one"
private const val BETA_URL = "https://openapi.fox.one"
private const val RELEASE_URL = "https://openapi.fox.one"
private const val PATH_WS = "/ws"
private const val ALIGNMENT_DELAY = 3000
private var alignmentTime: Long = 0
private val handler = StreamHandler()
private val observers: MutableMap<String, StreamObserver<*, *>> = ConcurrentHashMap()
private val apiLoader = APILoader()
private var webSocketEngine: WebSocketEngine?= null
@Volatile
private var state: WebSocketEngine.State = WebSocketEngine.State.IDLE
private val alignmentCache:ConcurrentHashMap<String?, StreamResponse> = ConcurrentHashMap()
private val reqCache: MutableList<String> = CopyOnWriteArrayList<String>()
var webSocketListener = object: WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
LogUtils.i(TAG, "${response.toString()}")
state = WebSocketEngine.State.OPENED
}
override fun onMessage(webSocket: WebSocket, text: String) {
LogUtils.i(TAG, "String:: $text")
state = WebSocketEngine.State.OPENED
dispatchMessage(text)
}
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
state = WebSocketEngine.State.OPENED
bytes?.let {
TaskScheduler.execute {
val byteArray = it.toByteArray().unGzip()
val jsonString = byteArray.toString(Charsets.UTF_8)
LogUtils.i(TAG, "String:: $jsonString")
dispatchMessage(jsonString)
}
}
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
state = WebSocketEngine.State.CLOSING
LogUtils.i(TAG, "$code, $reason")
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
state = WebSocketEngine.State.CLOSED
LogUtils.i(TAG, "$code, $reason")
}
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
state = WebSocketEngine.State.CLOSED
LogUtils.i(TAG, "${response?.toString()}, ${t.toString()}")
}
}
private fun getRealUrl(): String {
val url = URL(apiLoader.getBaseUrl())
val host = url.host
return "wss://$host$PATH_WS"
}
init {
apiLoader.setBaseUri(APILoader.BaseUrl(ALPHA_URL, BETA_URL, RELEASE_URL))
webSocketEngine = WebSocketEngine(getRealUrl(), apiLoader.getHttpClient(), webSocketListener)
LogUtils.i("foxone", "websocket: ${getRealUrl()}")
}
fun dispatchMessage(message: String) {
val streamResponse = JsonUtils.optFromJson(message, StreamResponse::class.java)
streamResponse?.let {
if (TextUtils.isEmpty(it.event)) {
return
}
alignmentCache[it.event] = it
if (System.currentTimeMillis() - alignmentTime > ALIGNMENT_DELAY) {
handler.post {
alignmentCache.forEach { cacheItem ->
when(cacheItem.key) {
StreamEvent.ORDER_OPEN -> {
observers.forEach {entry ->
if (entry.value.getEvent() == StreamEvent.USER_DATA) {
val data = JsonUtils.optFrom(cacheItem.value.data, OrderOpenStreamInfo::class.java)
data?.let {
(entry.value as StreamObserver<OrderStreamReqBody, BaseOrderStreamInfo>).onUpdate(data)
}
}
}
}
StreamEvent.ORDER_CANCEL -> {
observers.forEach {entry ->
if (entry.value.getEvent() == StreamEvent.USER_DATA) {
val data = JsonUtils.optFrom(cacheItem.value.data, OrderCancelStreamInfo::class.java)
data?.let {
(entry.value as StreamObserver<OrderStreamReqBody, BaseOrderStreamInfo>).onUpdate(data)
}
}
}
}
StreamEvent.ORDER_MATCH -> {
observers.forEach {entry ->
if (entry.value.getEvent() == StreamEvent.USER_DATA) {
val data = JsonUtils.optFrom(cacheItem.value.data, OrderMatchStreamInfo::class.java)
data?.let {
(entry.value as StreamObserver<OrderStreamReqBody, BaseOrderStreamInfo>).onUpdate(data)
}
}
}
}
StreamEvent.KLINE -> {
observers.forEach {entry ->
if (entry.value.getEvent() == StreamEvent.KLINE) {
val data = JsonUtils.optFrom(cacheItem.value.data, KLineStreamInfo::class.java)
data?.let {
(entry.value as StreamObserver<KLineStreamReqBody, KLineStreamInfo>).onUpdate(data)
}
}
}
}
StreamEvent.TICKER_24HR -> {
observers.forEach {entry ->
if (entry.value.getEvent() == StreamEvent.TICKER_24HR) {
val data = JsonUtils.optFrom(cacheItem.value.data, TickerStreamInfo::class.java)
data?.let {
(entry.value as StreamObserver<TickerStreamReqBody, TickerStreamInfo>).onUpdate(data)
}
}
}
}
StreamEvent.ALL_TICKER_24HR -> {
observers.forEach {entry ->
if (entry.value.getEvent() == StreamEvent.ALL_TICKER_24HR) {
val data = JsonUtils.optFrom(cacheItem.value.data, AllTickerStreamInfo::class.java)
data?.let {
(entry.value as StreamObserver<AllTickerStreamReqBody, AllTickerStreamInfo>).onUpdate(data)
}
}
}
}
StreamEvent.DEPTH_UPDATE -> {
observers.forEach {entry ->
if (entry.value.getEvent() == StreamEvent.DEPTH_UPDATE) {
val data = JsonUtils.optFrom(cacheItem.value.data, DepthStreamInfo::class.java)
data?.let {
(entry.value as StreamObserver<DepthStreamReqBody, DepthStreamInfo>).onUpdate(data)
}
}
}
}
StreamEvent.DEPTH_WITH_LEVEL -> {
observers.forEach {entry ->
if (entry.value.getEvent() == StreamEvent.DEPTH_WITH_LEVEL) {
val data = JsonUtils.optFrom(cacheItem.value.data, DepthLevelStreamInfo::class.java)
data?.let {
(entry.value as StreamObserver<DepthLevelStreamReqBody, DepthLevelStreamInfo>).onUpdate(data)
}
}
}
}
StreamEvent.TRADE -> {
observers.forEach {entry ->
if (entry.value.getEvent() == StreamEvent.TRADE) {
val data = JsonUtils.optFrom(cacheItem.value.data, TradeStreamInfo::class.java)
data?.let {
(entry.value as StreamObserver<TradeStreamReqBody, TradeStreamInfo>).onUpdate(data)
}
}
}
}
}
}
}
alignmentTime = System.currentTimeMillis()
}
}
}
fun reset() {
close()
webSocketEngine = WebSocketEngine(getRealUrl(), apiLoader.getHttpClient(), webSocketListener)
}
private fun close() {
webSocketEngine?.close()
observers.clear()
reqCache.clear()
handler.removeMessages(WHAT_CHECK_CONNECTION)
handler.removeMessages(WHAT_SEND_MSG)
handler.removeMessages(WHAT_CLOSE)
LogUtils.i(TAG, "websocket close>>>>>>>>>>>>>>")
}
private fun tryConnect() {
if (state != WebSocketEngine.State.OPENING
&& state != WebSocketEngine.State.OPENED) {
webSocketEngine?.connect()
LogUtils.i(TAG, "websocket connect-----------")
state = WebSocketEngine.State.OPENING
}
}
private fun doSubscribe(observer: StreamObserver<*, *>) {
tryConnect()
val reqStr = JsonUtils.optToJson(observer.reqBody)
observers[observer.reqBody.subId] = observer
LogUtils.i(TAG, "state:$state;; subMessage::$reqStr")
if (state == WebSocketEngine.State.OPENED) {
webSocketEngine?.send(reqStr)
} else {
reqCache.add(reqStr)
handler.sendEmptyMessage(WHAT_CHECK_CONNECTION)
}
handler.removeMessages(WHAT_CLOSE)
}
private fun doUnSubscribe(subId: String, unSubReq: String) {
LogUtils.i(TAG, "$unSubReq")
webSocketEngine?.send(unSubReq)
observers.remove(subId)
if (observers.isEmpty()) {
handler.sendEmptyMessageDelayed(WHAT_CLOSE, DELAY_CLOSE)
}
}
/**
* 订阅K线数据流
*/
fun subscribe(observer: KLineStreamObserver) {
doSubscribe(observer)
}
/**
* 取消K线数据流订阅
*/
fun unsubscribe(klineRequest: KLineStreamReqBody) {
doUnSubscribe(klineRequest.subId, JsonUtils.optToJson(klineRequest))
}
/**
* 订阅Ticker数据流
*/
fun subscribe(observer: TickerStreamObserver) {
doSubscribe(observer)
}
/**
* 取消Ticker数据流订阅
*/
fun unsubscribe(tickerRequest: TickerStreamReqBody) {
doUnSubscribe(tickerRequest.subId, JsonUtils.optToJson(tickerRequest))
}
/**
* 订阅所有币对的Ticker数据流
*/
fun subscribe(observer: AllTickerStreamObserver) {
doSubscribe(observer)
}
/**
* 取消所有币对Ticker数据流的订阅
*/
fun unsubscribe(allTickerRequest: AllTickerStreamReqBody) {
doUnSubscribe(allTickerRequest.subId, JsonUtils.optToJson(allTickerRequest))
}
/**
* 订阅深度数据流
*/
fun subscribe(observer: DepthStreamObserver) {
doSubscribe(observer)
}
/**
* 取消深度数据流订阅
*/
fun unsubscribe(depthRequest: DepthStreamReqBody) {
doUnSubscribe(depthRequest.subId, JsonUtils.optToJson(depthRequest))
}
/**
* 订阅深度数据流,level: 5, 10, 20
*/
fun subscribe(observer: DepthLevelStreamObserver) {
doSubscribe(observer)
}
/**
* 取消深度数据流订阅
*/
fun unsubscribe(depthLevelRequest: DepthLevelStreamReqBody) {
doUnSubscribe(depthLevelRequest.subId, JsonUtils.optToJson(depthLevelRequest))
}
/**
* 订阅交易数据流
*/
fun subscribe(observer: TradeStreamObserver) {
doSubscribe(observer)
}
/**
* 取消交易数据流订阅
*/
fun unsubscribe(tradeRequest: TradeStreamReqBody) {
doUnSubscribe(tradeRequest.subId, JsonUtils.optToJson(tradeRequest))
}
/**
* 订阅订单数据流
*/
fun subscribe(observer: OrderStreamObserver) {
doSubscribe(observer)
}
/**
* 取消订单数据流订阅
*/
fun unsubscribe(orderRequest: OrderStreamReqBody) {
doUnSubscribe(orderRequest.subId, JsonUtils.optToJson(orderRequest))
}
private const val WHAT_SEND_MSG = 1
private const val WHAT_CHECK_CONNECTION = 2
private const val WHAT_CLOSE = 3
private const val DELAY_CHECK = 500L
private const val DELAY_CLOSE = 20 * 1000L
class StreamHandler: Handler(Looper.getMainLooper()) {
override fun handleMessage(msg: Message?) {
val what = msg?.what ?: 0
when(what) {
WHAT_CHECK_CONNECTION -> {
if (state == WebSocketEngine.State.OPENED) {
reqCache.forEach {
LogUtils.i(TAG, "handler send message:$it")
webSocketEngine?.send(it)
}
reqCache.clear()
} else {
if (handler.hasMessages(WHAT_CHECK_CONNECTION)) {
handler.removeMessages(WHAT_CHECK_CONNECTION)
}
LogUtils.i(TAG, "handler check connection")
handler.sendEmptyMessageDelayed(WHAT_CHECK_CONNECTION, DELAY_CHECK)
}
}
WHAT_CLOSE -> {
close()
}
}
}
}
} | 38.009926 | 137 | 0.511947 |
43c69bea943d7b4ac34fdd517eb91fe96f797019 | 101 | ts | TypeScript | web/src/models/item.ts | ethanturk/SDi | c7374343146cedf882e1dbf8bda1ad8f66d3405c | [
"MIT"
] | null | null | null | web/src/models/item.ts | ethanturk/SDi | c7374343146cedf882e1dbf8bda1ad8f66d3405c | [
"MIT"
] | null | null | null | web/src/models/item.ts | ethanturk/SDi | c7374343146cedf882e1dbf8bda1ad8f66d3405c | [
"MIT"
] | null | null | null | class Item {
firstName: string;
lastName: string;
dateOfBirth: string;
gpa: string;
} | 16.833333 | 24 | 0.633663 |
b01fd3864ba4da0d399c2f52444858e8bb1e3a6f | 1,613 | py | Python | coffeecups/management/commands/grant_no_takes_points.py | J1bz/ecoloscore | 68e3e7975c59dcf2db5f050ccea5f65d6f2d8645 | [
"BSD-3-Clause"
] | null | null | null | coffeecups/management/commands/grant_no_takes_points.py | J1bz/ecoloscore | 68e3e7975c59dcf2db5f050ccea5f65d6f2d8645 | [
"BSD-3-Clause"
] | null | null | null | coffeecups/management/commands/grant_no_takes_points.py | J1bz/ecoloscore | 68e3e7975c59dcf2db5f050ccea5f65d6f2d8645 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from django.core.exceptions import ObjectDoesNotExist
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from coffeecups.models import Take, CupPolicy
from score.models import Score
class Command(BaseCommand):
help = """Command that should be triggered each working day to grant
points to users who did not take any cup during the last day"""
def handle(self, *args, **options):
for user in User.objects.all():
# Users can be management entities. To be sure that a user should
# be considered as a player, we try to access his profile data
# (where his/her rfid tag is saved) and if it does not exist we
# just skip this user
try:
user.profile
except ObjectDoesNotExist:
break
now = datetime.now()
more_than_day = timedelta(hours=16)
period = now - more_than_day
user_takes = Take.objects.filter(user=user, date__gte=period)
if not user_takes.exists():
try:
policy = CupPolicy.objects.get(users=user)
except ObjectDoesNotExist:
# If a user does not have a policy... well... he should
# not be very active in ecoloscore games so we just ignore
# him
break
points = policy.no_takes
Score.objects.create(user=user, game='c', value=points).save()
| 34.319149 | 78 | 0.600744 |
d837ab1a3c83c7a1798a72667816dc7257cde4ec | 68 | sql | SQL | db-migrations/20190521114441.sql | inventid/iaas | c31a03b3d3b6c7ec8ac674f6e8459ef53ac32a15 | [
"MIT"
] | 17 | 2016-07-05T10:16:52.000Z | 2022-02-22T07:33:41.000Z | db-migrations/20190521114441.sql | inventid/live-image-resize | c31a03b3d3b6c7ec8ac674f6e8459ef53ac32a15 | [
"MIT"
] | 48 | 2015-02-23T07:02:18.000Z | 2016-06-30T10:18:12.000Z | db-migrations/20190521114441.sql | inventid/iaas | c31a03b3d3b6c7ec8ac674f6e8459ef53ac32a15 | [
"MIT"
] | 3 | 2016-07-07T05:45:45.000Z | 2017-01-12T08:43:48.000Z | ALTER TABLE tokens ADD COLUMN uploaded_at timestamp with time zone;
| 34 | 67 | 0.838235 |
fd7d253b145b5fb1b7eead8f7a98b63c0000903a | 5,245 | css | CSS | data/usercss/20470.user.css | 33kk/uso-archive | 2c4962d1d507ff0eaec6dcca555efc531b37a9b4 | [
"MIT"
] | 118 | 2020-08-28T19:59:28.000Z | 2022-03-26T16:28:40.000Z | data/usercss/20470.user.css | 33kk/uso-archive | 2c4962d1d507ff0eaec6dcca555efc531b37a9b4 | [
"MIT"
] | 38 | 2020-09-02T01:08:45.000Z | 2022-01-23T02:47:24.000Z | data/usercss/20470.user.css | 33kk/uso-archive | 2c4962d1d507ff0eaec6dcca555efc531b37a9b4 | [
"MIT"
] | 21 | 2020-08-19T01:12:43.000Z | 2022-03-15T21:55:17.000Z | /* ==UserStyle==
@name Round, black and blue CSM skin
@namespace USO Archive
@author raapulis
@description `New CSM skin by me.It has round logo and based on black, blue, white and a bit of grey. Enjoy! :]Screen link: http://bildites.lv/images/6hj670ci1tzvlsddm1i.png`
@version 20090826.20.48
@license NO-REDISTRIBUTION
@preprocessor uso
==/UserStyle== */
/** cs-manager.com only: **/
@-moz-document domain(cs-manager.com) {
body{
background: url(http://bildites.lv/images/5dejhrl090pvk5xsyt2r.png) !important;
}
#header {
margin: 0 auto !important;
border:0!important;
border-left:0px solid #000000 !important;
border-right:0px solid #000000 !important;
width: 902px !important;
height: 166px !important;
border-bottom: 0px solid #000000 !important;
background: url(http://bildites.lv/images/e94wvo15vjoj7qofw7y6.png) !important;
}
#header a[href="/"]{
visibility: hidden !important;
}
#upcoming {
color: #444444 !important;
position: absolute !important;
top: 140px !important;
margin-left: 20px !important;
border: none !important;
background-color:transparent !important;
}
#upcoming a{
border-bottom: 1px #000000 dotted !important;
font-weight: bold !important;
}
ul#menu li a {
border: none !important;
background: #e2e2e2 !important;
}
li a {
background-color: #2e2e2e !important;
border-bottom: 1px solid #444444 !important;
color: #ffffff !important;
}
li a:hover {
background: #e1e1e1 !important;
color: #000000 !important;
font-style: normal !important;
}
/** Adding borders and bg-colour to headers **/
td.head, h3 , h2 {
color: #ffffff !important;
background-color: #004dad !important;
border-top: 0px solid #000000 !important;
border-right: 0px solid #000000 !important;
border-bottom: 1px solid #444444 !important;
}
td.head a, h3 a, h2 a {
color: #ffffff !important;
border-bottom: 0px dotted #ffffff !important;
}
#help_tab{
background: #004dad !important;
color: #ffffff !important;
}
#search {
background-color: #2e2e2e !important;
border-bottom: 1px solid #444444 !important;
}
.ok{
background-color: #004dad !important;
}
.lan .info{
background-color: #e5e5e5 !important;
background-image:url("http://users.telenet.be/tim.daminet/csm/lancamp.png") !important;
background-repeat: no-repeat !important;
background-position: center right !important;
}
.lan .value{
background-color: #f2f2f2 !important;
}
.new{
background-color: #CCFFFF !important;
}
.button{
border: 1px solid #000000 !important;
background-color: #004dad !important;
}
.button:hover{
background-color: #3366FF !important;
}
.buttonsmall{
border: 1px solid #000000 !important;
background-color: #004dad !important;
}
.buttonsmall:hover{
background-color: #3366FF !important;
}
.lineup:hover{
background-color: #004dad !important;
color: #ffffff !important;
}
ul#friend a[title^="Idle:"] span{
background-color: transparent !important;
color: #FFCC00 !important;
font-weight: bold !important;
background-repeat: no-repeat !important;
background-position: top right !important;
padding-right: 8px !important;
padding-top: 0px !important;
}
ul#friend a[title="Active"] span{
background-color: transparent !important;
color: #90ee90 !important;
font-weight: bold !important;
background-repeat: no-repeat !important;
background-position: top right !important;
padding-right: 8px !important;
padding-top: 0px !important;
}
#container, #footer_container,.post,#content {
margin: 0 auto !important;
}
#container {
border-left: solid #004dad 1px !important;
border-right: solid #004dad 1px !important;
}
#footer_container {
border-left: solid #004dad 1px !important;
border-bottom: solid #004dad 1px !important;
}
#footer_right {
width: 140px !important;
margin-left: 0px !important;
border-right: solid #004dad 1px !important;
}
div#tab_container [href="?p=search"] {
background-color: transparent !important;
background-repeat: no-repeat !important;
color: #747474 !important;
font-weight: bold !important;
}
div#tab_container [href="?p=search"]:hover {
background-color: transparent !important;
background-repeat: no-repeat !important;
color: #747474 !important;
font-weight: bold !important;
}
/**csm, forum and logout bottons **/
ul#tabtop li a[title="CSM"]{
position: relative !important;
background-color: #3f3f3f !important;
top: 75px !important;
border-bottom: 0px !important;
}
ul#tabtop li a[title="CSM"]:hover{
position: relative !important;
background-color: #e2e2e2 !important;
top: 75px !important;
border-bottom: 0px !important;
}
ul#tabtop li a[title="Log out"]{
position: relative !important;
top: 75px !important;
border-bottom: 0px !important;
}
ul#tabtop li a[title="Forum"]{
position: relative !important;
background-color: #3f3f3f !important;
top: 75px !important;
border-bottom: 0px !important;
}
ul#tabtop li a[title="Forum"]:hover{
position: relative !important;
background-color: #e2e2e2 !important;
top: 75px !important;
border-bottom: 0px !important;
}
} | 27.751323 | 177 | 0.694757 |
20eb9f6077d9180c08c9035ad937ffa28a698e5d | 6,141 | py | Python | petl/test/transform/test_headers.py | a-musing-moose/petl | 719cea43117543eaccadb53d255cbbe1177b3cc5 | [
"MIT"
] | null | null | null | petl/test/transform/test_headers.py | a-musing-moose/petl | 719cea43117543eaccadb53d255cbbe1177b3cc5 | [
"MIT"
] | null | null | null | petl/test/transform/test_headers.py | a-musing-moose/petl | 719cea43117543eaccadb53d255cbbe1177b3cc5 | [
"MIT"
] | null | null | null | from __future__ import absolute_import, print_function, division
from petl.test.helpers import ieq
from petl.errors import FieldSelectionError
from petl.util import fieldnames
from petl.transform.headers import setheader, extendheader, pushheader, skip,\
rename, prefixheader, suffixheader
def test_setheader():
table1 = (('foo', 'bar'),
('a', 1),
('b', 2))
table2 = setheader(table1, ['foofoo', 'barbar'])
expect2 = (('foofoo', 'barbar'),
('a', 1),
('b', 2))
ieq(expect2, table2)
ieq(expect2, table2) # can iterate twice?
def test_setheader_empty():
table1 = (('foo', 'bar'),)
table2 = setheader(table1, ['foofoo', 'barbar'])
expect2 = (('foofoo', 'barbar'),)
ieq(expect2, table2)
def test_extendheader():
table1 = (('foo',),
('a', 1, True),
('b', 2, False))
table2 = extendheader(table1, ['bar', 'baz'])
expect2 = (('foo', 'bar', 'baz'),
('a', 1, True),
('b', 2, False))
ieq(expect2, table2)
ieq(expect2, table2) # can iterate twice?
def test_extendheader_empty():
table1 = (('foo',),)
table2 = extendheader(table1, ['bar', 'baz'])
expect2 = (('foo', 'bar', 'baz'),)
ieq(expect2, table2)
def test_pushheader():
table1 = (('a', 1),
('b', 2))
table2 = pushheader(table1, ['foo', 'bar'])
expect2 = (('foo', 'bar'),
('a', 1),
('b', 2))
ieq(expect2, table2)
ieq(expect2, table2) # can iterate twice?
def test_pushheader_empty():
table1 = (('a', 1),)
table2 = pushheader(table1, ['foo', 'bar'])
expect2 = (('foo', 'bar'),
('a', 1))
ieq(expect2, table2)
table1 = tuple()
table2 = pushheader(table1, ['foo', 'bar'])
expect2 = (('foo', 'bar'),)
ieq(expect2, table2)
table1 = tuple()
table2 = pushheader(table1, 'foo', 'bar')
expect2 = (('foo', 'bar'),)
ieq(expect2, table2)
def test_pushheader_positional():
table1 = (('a', 1),
('b', 2))
# positional arguments instead of list
table2 = pushheader(table1, 'foo', 'bar')
expect2 = (('foo', 'bar'),
('a', 1),
('b', 2))
ieq(expect2, table2)
ieq(expect2, table2) # can iterate twice?
# test with many fields
table1 = (('a', 1, 11, 111, 1111),
('b', 2, 22, 222, 2222))
# positional arguments instead of list
table2 = pushheader(table1, 'foo', 'bar', 'foo1', 'foo2', 'foo3')
expect2 = (('foo', 'bar', 'foo1', 'foo2', 'foo3'),
('a', 1, 11, 111, 1111),
('b', 2, 22, 222, 2222))
ieq(expect2, table2)
ieq(expect2, table2) # can iterate twice?
# test with too few fields in header
table1 = (('a', 1, 11, 111, 1111),
('b', 2, 22, 222, 2222))
# positional arguments instead of list
table2 = pushheader(table1, 'foo', 'bar', 'foo1', 'foo2')
expect2 = (('foo', 'bar', 'foo1', 'foo2'),
('a', 1, 11, 111, 1111),
('b', 2, 22, 222, 2222))
ieq(expect2, table2)
ieq(expect2, table2) # can iterate twice?
# test with too many fields in header
table1 = (('a', 1, 11, 111, 1111),
('b', 2, 22, 222, 2222))
# positional arguments instead of list
table2 = pushheader(table1, 'foo', 'bar', 'foo1', 'foo2', 'foo3', 'foo4')
expect2 = (('foo', 'bar', 'foo1', 'foo2', 'foo3', 'foo4'),
('a', 1, 11, 111, 1111),
('b', 2, 22, 222, 2222))
ieq(expect2, table2)
ieq(expect2, table2) # can iterate twice?
def test_skip():
table1 = (('#aaa', 'bbb', 'ccc'),
('#mmm',),
('foo', 'bar'),
('a', 1),
('b', 2))
table2 = skip(table1, 2)
expect2 = (('foo', 'bar'),
('a', 1),
('b', 2))
ieq(expect2, table2)
ieq(expect2, table2) # can iterate twice?
def test_skip_empty():
table1 = (('#aaa', 'bbb', 'ccc'),
('#mmm',),
('foo', 'bar'))
table2 = skip(table1, 2)
expect2 = (('foo', 'bar'),)
ieq(expect2, table2)
def test_rename():
table = (('foo', 'bar'),
('M', 12),
('F', 34),
('-', 56))
result = rename(table, 'foo', 'foofoo')
assert fieldnames(result) == ('foofoo', 'bar')
result = rename(table, 0, 'foofoo')
assert fieldnames(result) == ('foofoo', 'bar')
result = rename(table, {'foo': 'foofoo', 'bar': 'barbar'})
assert fieldnames(result) == ('foofoo', 'barbar')
result = rename(table)
result['foo'] = 'spong'
assert fieldnames(result) == ('spong', 'bar')
def test_rename_strict():
table = (('foo', 'bar'),
('M', 12),
('F', 34),
('-', 56))
result = rename(table, 'baz', 'quux')
try:
fieldnames(result)
except FieldSelectionError:
pass
else:
assert False, 'exception expected'
result = rename(table, 2, 'quux')
try:
fieldnames(result)
except FieldSelectionError:
pass
else:
assert False, 'exception expected'
result = rename(table, 'baz', 'quux', strict=False)
assert fieldnames(result) == ('foo', 'bar')
result = rename(table, 2, 'quux', strict=False)
assert fieldnames(result) == ('foo', 'bar')
def test_rename_empty():
table = (('foo', 'bar'),)
expect = (('foofoo', 'bar'),)
actual = rename(table, 'foo', 'foofoo')
ieq(expect, actual)
def test_prefixheader():
table1 = (('foo', 'bar'),
(1, 'A'),
(2, 'B'))
expect = (('pre_foo', 'pre_bar'),
(1, 'A'),
(2, 'B'))
actual = prefixheader(table1, 'pre_')
ieq(expect, actual)
ieq(expect, actual)
def test_suffixheader():
table1 = (('foo', 'bar'),
(1, 'A'),
(2, 'B'))
expect = (('foo_suf', 'bar_suf'),
(1, 'A'),
(2, 'B'))
actual = suffixheader(table1, '_suf')
ieq(expect, actual)
ieq(expect, actual)
| 25.5875 | 78 | 0.500733 |
405ab21123487e7d44930a50872f9e595ba9d287 | 3,274 | sql | SQL | docs/deployment/db_deployment_request/db_scripts/cleanup_dupe_series.sql | TCIA/national-biomedical-image-archive | ac26ef878a3d8818a0037e2b74ace6b8068f4ce1 | [
"BSD-3-Clause"
] | 1 | 2019-04-22T17:38:54.000Z | 2019-04-22T17:38:54.000Z | docs/deployment/db_deployment_request/db_scripts/cleanup_dupe_series.sql | TCIA/national-biomedical-image-archive | ac26ef878a3d8818a0037e2b74ace6b8068f4ce1 | [
"BSD-3-Clause"
] | null | null | null | docs/deployment/db_deployment_request/db_scripts/cleanup_dupe_series.sql | TCIA/national-biomedical-image-archive | ac26ef878a3d8818a0037e2b74ace6b8068f4ce1 | [
"BSD-3-Clause"
] | null | null | null | /*L
Copyright SAIC, Ellumen and RSNA (CTP)
Distributed under the OSI-approved BSD 3-Clause License.
See http://ncip.github.com/national-biomedical-image-archive/LICENSE.txt for details.
L*/
update general_image
set general_series_pk_id = 343638016
where general_series_pk_id = 343670784;
delete from general_series
where general_series_pk_id = 343670784;
update general_image
set general_series_pk_id = 359104517
where general_series_pk_id = 359137283;
delete from general_series
where general_series_pk_id = 359137283;
delete from general_series
where general_series_pk_id = 371982338;
delete from general_series
where general_series_pk_id = 380567552;
delete from general_series
where general_series_pk_id = 372637696;
update general_image
set general_series_pk_id = 373751811
where general_series_pk_id = 373686275;
delete from general_series
where general_series_pk_id = 373686275;
delete from general_series
where general_series_pk_id = 404848642;
delete from general_series
where general_series_pk_id = 404848644;
update general_image
set general_series_pk_id = 407371779
where general_series_pk_id = 407339009;
delete from general_series
where general_series_pk_id = 407339009;
create table image_temp as select image_pk_id from general_image where general_series_pk_id = 742096896;
delete from ct_image
where image_pk_id in (select image_pk_id from image_temp);
delete from qa_status_history
where general_image_pk_id in (select image_pk_id from image_temp);
delete from group9_dicom_tags
where image_pk_id in (select image_pk_id from image_temp);
delete from general_image
where general_series_pk_id = 742096896;
delete from general_series
where general_series_pk_id = 742096896;
drop table image_temp;
create table image_temp as select image_pk_id from general_image where general_series_pk_id = 881786880;
delete from ct_image
where image_pk_id in (select image_pk_id from image_temp);
delete from qa_status_history
where general_image_pk_id in (select image_pk_id from image_temp);
delete from group9_dicom_tags
where image_pk_id in (select image_pk_id from image_temp);
delete from general_image
where general_series_pk_id = 881786880;
delete from general_series
where general_series_pk_id = 881786880;
drop table image_temp;
delete from general_series
where general_series_pk_id = 353140740;
update general_image
set general_series_pk_id = 372047875
where general_series_pk_id = 371982337;
delete from general_series
where general_series_pk_id = 371982337;
delete from general_series
where general_series_pk_id = 372637697;
update general_image
set general_series_pk_id = 387448835
where general_series_pk_id = 387416070;
delete from general_series
where general_series_pk_id = 387416070;
delete from general_series
where general_series_pk_id = 404815875;
update general_image
set general_series_pk_id = 407339014
where general_series_pk_id = 407371780;
delete from general_series
where general_series_pk_id = 407371780;
delete from general_series
where general_series_pk_id = 1252753412;
| 18.924855 | 105 | 0.787111 |
433bdc7032c16a435489f12edd40e595be3b0515 | 1,042 | ts | TypeScript | features/classes.ts | SandraCoburn/typrescript-practice | 4cae5262479305f2888006a9bb5ec29f2805d777 | [
"MIT"
] | null | null | null | features/classes.ts | SandraCoburn/typrescript-practice | 4cae5262479305f2888006a9bb5ec29f2805d777 | [
"MIT"
] | null | null | null | features/classes.ts | SandraCoburn/typrescript-practice | 4cae5262479305f2888006a9bb5ec29f2805d777 | [
"MIT"
] | null | null | null | // by default all methods are public
class Vehicle {
// color: string; //we can initialize the color here or delete it and add it in constructors
//constructor(color: string) {
constructor(public color: string) {
// this.color = color; // ^ if we add public, we don't need to do this part
}
public drive(): void {
console.log('this is a class');
}
protected honk(): void {
console.log('beep');
}
}
const vehicle2 = new Vehicle('organge');
vehicle2.honk(); // we get an error because honk is protected in class, it cannot be used outside class or child class
class Car extends Vehicle {
constructor(public wheels: number, color: string) {
super(color);
}
private drive(): void {
console.log(' this is a car class');
}
startDrivingProcess(): void {
this.drive();
this.honk(); // we can use a protected method in child class
}
}
//an instance of a class:
const vehicle = new Vehicle('green');
vehicle.drive();
vehicle.honk();
const car = new Car(4, 'blue');
car.startDrivingProcess();
| 26.717949 | 118 | 0.667946 |
e459afb71f09ece8be744e667a586b294c3d602b | 1,219 | sql | SQL | src/setup/install.sql | shopgate/interface-prestashop | bf7df3bf68c710d79dcef1e77b60de8206d8eed7 | [
"Apache-2.0"
] | 1 | 2017-11-03T14:09:57.000Z | 2017-11-03T14:09:57.000Z | setup/install.sql | PrestaShopCorp/shopgate | 7ede2b16c0251865fcddda3c6f7d4242381b3bbc | [
"AFL-3.0"
] | 8 | 2015-02-26T10:04:14.000Z | 2016-01-19T09:18:51.000Z | src/setup/install.sql | shopgate/cart-integration-prestashop | bf7df3bf68c710d79dcef1e77b60de8206d8eed7 | [
"Apache-2.0"
] | 4 | 2015-02-23T13:00:42.000Z | 2019-06-02T19:44:53.000Z | CREATE TABLE IF NOT EXISTS `PREFIX_shopgate_order`
(
`id_shopgate_order` int(11) NOT NULL AUTO_INCREMENT,
`id_cart` int(11) NOT NULL DEFAULT '0',
`id_order` int(11) DEFAULT NULL,
`order_number` int(16) NOT NULL,
`shop_number` int(16) NULL DEFAULT NULL,
`tracking_number` varchar(32) NOT NULL DEFAULT '',
`shipping_service` varchar(16) NOT NULL DEFAULT 'OTHER',
`shipping_cost` decimal(17,2) NOT NULL DEFAULT '0.00',
`comments` text NULL DEFAULT NULL,
`status` int(1) NOT NULL DEFAULT '0',
`shopgate_order` text NULL DEFAULT NULL,
PRIMARY KEY (`id_shopgate_order`),
UNIQUE KEY `order_number` (`order_number`)
)
ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `PREFIX_shopgate_customer`
(
`id_shopgate_customer` int(11) NOT NULL AUTO_INCREMENT,
`id_customer` int(11) NOT NULL DEFAULT '0',
`customer_token` varchar(255) NOT NULL DEFAULT '0',
`date_add` datetime NOT NULL,
PRIMARY KEY (`id_shopgate_customer`),
UNIQUE KEY `id_customer_token` (`customer_token`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
| 43.535714 | 68 | 0.634947 |
da954915a66b9011e0122952c5f2a057842e0d71 | 2,039 | php | PHP | src/applications/base/base.php | awilfox/dagd | d5cea72cfa0ff2468daab74d151e02d5f99c82e8 | [
"Apache-2.0"
] | null | null | null | src/applications/base/base.php | awilfox/dagd | d5cea72cfa0ff2468daab74d151e02d5f99c82e8 | [
"Apache-2.0"
] | null | null | null | src/applications/base/base.php | awilfox/dagd | d5cea72cfa0ff2468daab74d151e02d5f99c82e8 | [
"Apache-2.0"
] | null | null | null | <?php
abstract class DaGdBaseClass {
// Automatically escape stuff to prevent against xss.
protected $escape = true;
// Wrap the response in <pre>...</pre> in non-cli browsers.
protected $wrap_pre = true;
// Enable text-UA specific html stripping?
protected $text_html_strip = true;
// This is "global" for now, and probably needs to be refactored.
protected $db_connection;
// This contains matches that the router finds in the accessed URL.
protected $route_matches = null;
// Set text/plain by default for all text-useragent responses.
protected $text_content_type = true;
// Acceptable request types to listen for in this controller.
protected $request_methods = array('GET', 'HEAD');
// This is used for DaGdHelpController to generate its list of commands.
public static $__help__ = null;
public function __construct() {
global $__db_handler;
$this->db_connection = $__db_handler;
}
public function setRouteMatches($matches=null) {
$this->route_matches = $matches;
}
public function render() {
return 'Override this method to make stuff happen!';
}
/*
* A function that, when overridden, returns a certain version of a response
* to a CLI browser. By default handle things normally.
*/
public function renderCLI() {
return strip_tags($this->render());
}
public function finalize() {
if (!in_array($_SERVER['REQUEST_METHOD'], $this->request_methods)) {
error405();
return;
}
$response = null;
if ($this->text_html_strip && !is_html_useragent()) {
if ($this->text_content_type) {
header('Content-type: text/plain; charset=utf-8');
header('X-Content-Type-Options: nosniff');
}
$response = $this->renderCLI();
} else {
$response = $this->render();
if ($this->escape) {
$response = htmlspecialchars($response);
}
}
if (is_html_useragent() && $this->wrap_pre) {
$response = '<pre>'.$response.'</pre>';
}
return $response;
}
}
| 26.480519 | 78 | 0.655714 |
e035c257508ddd49625bb07014fd3d2e9fd6adb5 | 199 | h | C | common/headers/report_utils.h | PanPapag/Game-Of-Life | 690a95b201e5d1f3a6452182f07f408d3bf61d72 | [
"MIT"
] | 13 | 2020-11-08T20:51:05.000Z | 2022-03-27T00:27:26.000Z | common/headers/report_utils.h | nikosgalanis/Game-Of-Life | 0ebcb67ad231126486f2ab9d70e7eea2c7bc54de | [
"MIT"
] | null | null | null | common/headers/report_utils.h | nikosgalanis/Game-Of-Life | 0ebcb67ad231126486f2ab9d70e7eea2c7bc54de | [
"MIT"
] | 2 | 2020-11-08T20:51:58.000Z | 2021-04-15T15:51:05.000Z | #ifndef __COMMON_REPORT_UTILS__
#define __COMMON_REPORT_UTILS__
void die(const char *fmt, ...);
void report_error(const char *fmt, ...);
void report_warning(const char *fmt, ...);
#endif
| 18.090909 | 44 | 0.703518 |
9097019ee5e1cab1c5870d56ecb0d06a0a263239 | 407 | c | C | C03/C03Test/ex03/ft_strncat.c | buiterma/Codam-Piscine | 8f3886ced7ba519326617e9ccc542abeda1e146c | [
"Apache-2.0"
] | null | null | null | C03/C03Test/ex03/ft_strncat.c | buiterma/Codam-Piscine | 8f3886ced7ba519326617e9ccc542abeda1e146c | [
"Apache-2.0"
] | null | null | null | C03/C03Test/ex03/ft_strncat.c | buiterma/Codam-Piscine | 8f3886ced7ba519326617e9ccc542abeda1e146c | [
"Apache-2.0"
] | null | null | null | char *ft_strncat(char *dest, char *src, unsigned int nb)
{
unsigned int i;
char *temp;
i = 0;
temp = dest;
while (*dest)
dest++;
while (src[i] != '\0' && i < nb)
{
*dest = src[i];
dest++;
i++;
}
*dest = '\0';
return (temp);
}
/*#include <stdio.h>
int main(void)
{
char string1[] = "Hello";
char string2[] = " world!";
ft_strncat(string1, string2, 2);
printf("%s\n", string1);
}*/ | 14.034483 | 56 | 0.545455 |
9ab4d29aa6845d370b8d7d60096f720129be0e66 | 227 | py | Python | Lesson07/random_normal.py | TrainingByPackt/Beginning-Python-AI | b1e68d892e65b1f7b347330ef2a90a1b546bdd25 | [
"MIT"
] | 14 | 2018-12-26T23:07:28.000Z | 2021-06-30T19:51:57.000Z | Lesson07/random_normal.py | TrainingByPackt/Beginning-Python-AI | b1e68d892e65b1f7b347330ef2a90a1b546bdd25 | [
"MIT"
] | 16 | 2018-10-20T13:37:51.000Z | 2018-10-22T22:21:52.000Z | Lesson07/random_normal.py | TrainingByPackt/Beginning-AI-Machine-Learning-and-Python | b1e68d892e65b1f7b347330ef2a90a1b546bdd25 | [
"MIT"
] | 13 | 2018-12-21T07:07:31.000Z | 2022-02-05T12:34:27.000Z | import tensorflow as tf
randomMatrix = tf.Variable(tf.random_normal([3, 4]))
with tf.Session() as session:
initializer = tf.global_variables_initializer()
session.run(initializer)
print(session.run(randomMatrix))
| 25.222222 | 52 | 0.748899 |
67ef8a74c96cf7e44ecf6a259914c331eab81077 | 854 | rs | Rust | Solutions/Rust/src/bin/problem_009.rs | IsmaelU/Project-Euler-Solutions | 00df75dea2be6a3f0341496ce5fb509a64c6029d | [
"CC0-1.0"
] | null | null | null | Solutions/Rust/src/bin/problem_009.rs | IsmaelU/Project-Euler-Solutions | 00df75dea2be6a3f0341496ce5fb509a64c6029d | [
"CC0-1.0"
] | null | null | null | Solutions/Rust/src/bin/problem_009.rs | IsmaelU/Project-Euler-Solutions | 00df75dea2be6a3f0341496ce5fb509a64c6029d | [
"CC0-1.0"
] | null | null | null | // Problem 1 -
// https://projecteuler.net/problem=9
// Answer =
fn question(){
println!("{}", {"
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"});
}
fn generate(m: i32, n: i32) -> (i32,i32,i32) {
let a:i32 = 2 * m * n;
let b:i32 = (m ^ 2) - (n ^ 2);
let c:i32 = (m ^ 2) + (n ^ 2);
return(a,b,c)
}
fn solve(num:i32) -> i32 {
let mut m = 2;
let mut n = 1;
let (a,b,c) = generate(m,n);
while a + b + c != num{
if m == n{
m += 1;
n = 1;
}
n += 1;
let (a,b,c)= generate(m,n);
}
a * b * c
}
fn main() {
question();
println!("The answer is {}", solve(1000));
}
| 19.409091 | 78 | 0.481265 |
c33a47543af6f816525ab09b4abc83ea597cf599 | 585 | swift | Swift | Package.swift | elian3/swift-nio-mqtt | 6a61857b94af858a27f2f910cd73343a237e27f5 | [
"MIT"
] | null | null | null | Package.swift | elian3/swift-nio-mqtt | 6a61857b94af858a27f2f910cd73343a237e27f5 | [
"MIT"
] | null | null | null | Package.swift | elian3/swift-nio-mqtt | 6a61857b94af858a27f2f910cd73343a237e27f5 | [
"MIT"
] | null | null | null | // swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "NIOMQTT",
dependencies: [
.package(url: "https://github.com/danger/swift.git", from: "1.0.0")
],
targets: [
// This is just an arbitrary Swift file in our app, that has
// no dependencies outside of Foundation, the dependencies section
// ensures that the library for Danger gets build also.
.target(
name: "NIOMQTT",
dependencies: ["Danger"],
path: "Danger",
sources: ["Foundation.swift"])
]
)
| 29.25 | 74 | 0.589744 |
cd1ef44eb10d6d0f993690cacd497fec5592a610 | 7,840 | cs | C# | contrib/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs | sercand/assimp | d8bb6e446a95df905bfe47e5558f22daf01248c8 | [
"BSD-3-Clause"
] | 13,885 | 2018-08-03T17:46:24.000Z | 2022-03-31T14:26:19.000Z | contrib/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs | sercand/assimp | d8bb6e446a95df905bfe47e5558f22daf01248c8 | [
"BSD-3-Clause"
] | 3,677 | 2015-01-02T08:06:57.000Z | 2022-03-31T19:24:26.000Z | contrib/zlib/contrib/dotzlib/DotZLib/ChecksumImpl.cs | sercand/assimp | d8bb6e446a95df905bfe47e5558f22daf01248c8 | [
"BSD-3-Clause"
] | 2,728 | 2015-01-01T19:28:19.000Z | 2022-03-31T16:07:18.000Z | //
// © Copyright Henrik Ravn 2004
//
// Use, modification and distribution are subject to the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace DotZLib
{
#region ChecksumGeneratorBase
/// <summary>
/// Implements the common functionality needed for all <see cref="ChecksumGenerator"/>s
/// </summary>
/// <example></example>
public abstract class ChecksumGeneratorBase : ChecksumGenerator
{
/// <summary>
/// The value of the current checksum
/// </summary>
protected uint _current;
/// <summary>
/// Initializes a new instance of the checksum generator base - the current checksum is
/// set to zero
/// </summary>
public ChecksumGeneratorBase()
{
_current = 0;
}
/// <summary>
/// Initializes a new instance of the checksum generator basewith a specified value
/// </summary>
/// <param name="initialValue">The value to set the current checksum to</param>
public ChecksumGeneratorBase(uint initialValue)
{
_current = initialValue;
}
/// <summary>
/// Resets the current checksum to zero
/// </summary>
public void Reset() { _current = 0; }
/// <summary>
/// Gets the current checksum value
/// </summary>
public uint Value { get { return _current; } }
/// <summary>
/// Updates the current checksum with part of an array of bytes
/// </summary>
/// <param name="data">The data to update the checksum with</param>
/// <param name="offset">Where in <c>data</c> to start updating</param>
/// <param name="count">The number of bytes from <c>data</c> to use</param>
/// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>
/// <exception cref="NullReferenceException"><c>data</c> is a null reference</exception>
/// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>
/// <remarks>All the other <c>Update</c> methods are implmeneted in terms of this one.
/// This is therefore the only method a derived class has to implement</remarks>
public abstract void Update(byte[] data, int offset, int count);
/// <summary>
/// Updates the current checksum with an array of bytes.
/// </summary>
/// <param name="data">The data to update the checksum with</param>
public void Update(byte[] data)
{
Update(data, 0, data.Length);
}
/// <summary>
/// Updates the current checksum with the data from a string
/// </summary>
/// <param name="data">The string to update the checksum with</param>
/// <remarks>The characters in the string are converted by the UTF-8 encoding</remarks>
public void Update(string data)
{
Update(Encoding.UTF8.GetBytes(data));
}
/// <summary>
/// Updates the current checksum with the data from a string, using a specific encoding
/// </summary>
/// <param name="data">The string to update the checksum with</param>
/// <param name="encoding">The encoding to use</param>
public void Update(string data, Encoding encoding)
{
Update(encoding.GetBytes(data));
}
}
#endregion
#region CRC32
/// <summary>
/// Implements a CRC32 checksum generator
/// </summary>
public sealed class CRC32Checksum : ChecksumGeneratorBase
{
#region DLL imports
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern uint crc32(uint crc, int data, uint length);
#endregion
/// <summary>
/// Initializes a new instance of the CRC32 checksum generator
/// </summary>
public CRC32Checksum() : base() {}
/// <summary>
/// Initializes a new instance of the CRC32 checksum generator with a specified value
/// </summary>
/// <param name="initialValue">The value to set the current checksum to</param>
public CRC32Checksum(uint initialValue) : base(initialValue) {}
/// <summary>
/// Updates the current checksum with part of an array of bytes
/// </summary>
/// <param name="data">The data to update the checksum with</param>
/// <param name="offset">Where in <c>data</c> to start updating</param>
/// <param name="count">The number of bytes from <c>data</c> to use</param>
/// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>
/// <exception cref="NullReferenceException"><c>data</c> is a null reference</exception>
/// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>
public override void Update(byte[] data, int offset, int count)
{
if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
if ((offset+count) > data.Length) throw new ArgumentException();
GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
_current = crc32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count);
}
finally
{
hData.Free();
}
}
}
#endregion
#region Adler
/// <summary>
/// Implements a checksum generator that computes the Adler checksum on data
/// </summary>
public sealed class AdlerChecksum : ChecksumGeneratorBase
{
#region DLL imports
[DllImport("ZLIB1.dll", CallingConvention=CallingConvention.Cdecl)]
private static extern uint adler32(uint adler, int data, uint length);
#endregion
/// <summary>
/// Initializes a new instance of the Adler checksum generator
/// </summary>
public AdlerChecksum() : base() {}
/// <summary>
/// Initializes a new instance of the Adler checksum generator with a specified value
/// </summary>
/// <param name="initialValue">The value to set the current checksum to</param>
public AdlerChecksum(uint initialValue) : base(initialValue) {}
/// <summary>
/// Updates the current checksum with part of an array of bytes
/// </summary>
/// <param name="data">The data to update the checksum with</param>
/// <param name="offset">Where in <c>data</c> to start updating</param>
/// <param name="count">The number of bytes from <c>data</c> to use</param>
/// <exception cref="ArgumentException">The sum of offset and count is larger than the length of <c>data</c></exception>
/// <exception cref="NullReferenceException"><c>data</c> is a null reference</exception>
/// <exception cref="ArgumentOutOfRangeException">Offset or count is negative.</exception>
public override void Update(byte[] data, int offset, int count)
{
if (offset < 0 || count < 0) throw new ArgumentOutOfRangeException();
if ((offset+count) > data.Length) throw new ArgumentException();
GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
_current = adler32(_current, hData.AddrOfPinnedObject().ToInt32()+offset, (uint)count);
}
finally
{
hData.Free();
}
}
}
#endregion
}
| 38.62069 | 128 | 0.603699 |
ae6929e3678d973c096926b823090e10763de50e | 4,959 | cs | C# | Hiku.Services/Service/BlobStorage/BlobStorage.cs | didaskein/HikuBackend | 870699d4c4a511dd72d9ad69f2efc531e4ed1cde | [
"MIT"
] | null | null | null | Hiku.Services/Service/BlobStorage/BlobStorage.cs | didaskein/HikuBackend | 870699d4c4a511dd72d9ad69f2efc531e4ed1cde | [
"MIT"
] | null | null | null | Hiku.Services/Service/BlobStorage/BlobStorage.cs | didaskein/HikuBackend | 870699d4c4a511dd72d9ad69f2efc531e4ed1cde | [
"MIT"
] | null | null | null | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Compression;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Specialized;
using Azure;
using Azure.Storage.Sas;
using System.Runtime.CompilerServices;
using Azure.Storage;
namespace Hiku.Services.Service.BlobStorage
{
public class BlobStorage : IBlobStorage, IAudioBlobStorage
{
private readonly BlobServiceClient _blobServiceClient;
private readonly BlobContainerClient _blobContainerClient;
private readonly string _blobContainerName;
public BlobStorage(string connectionString, string blobContainerName)
{
_blobServiceClient = new BlobServiceClient(connectionString);
_blobContainerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName);
_blobContainerClient.CreateIfNotExists();
_blobContainerName = blobContainerName;
}
public async Task<Uri> CreateBlockBlobAsync(string blobId, Stream stream, string contentType)
{
BlobClient blobClient = _blobContainerClient.GetBlobClient(blobId);
await blobClient.UploadAsync(stream, new BlobHttpHeaders { ContentType = contentType }).ConfigureAwait(false);
return blobClient.Uri;
}
public async Task<Uri> CreateBlockBlobAsync(string blobId, string filePath)
{
BlobClient blobClient = _blobContainerClient.GetBlobClient(blobId);
await blobClient.UploadAsync(filePath).ConfigureAwait(false);
return blobClient.Uri;
}
public async Task<Response<BlobProperties>> GetBlobPropertiesAsync(string blobId)
{
BlobClient blobClient = _blobContainerClient.GetBlobClient(blobId);
return await blobClient.GetPropertiesAsync().ConfigureAwait(false);
}
public async Task<string> GetBlockBlobDataAsStringAsync(string blobId)
{
string text = string.Empty;
BlobClient blobClient = _blobContainerClient.GetBlobClient(blobId);
BlobDownloadInfo download = await blobClient.DownloadAsync().ConfigureAwait(false);
using (StreamReader reader = new StreamReader(download.Content))
{
text = reader.ReadToEnd();
}
return text;
}
public async Task<Stream> GetBlockBlobDataAsStreamAsync(string blobId)
{
BlobClient blobClient = _blobContainerClient.GetBlobClient(blobId);
BlobDownloadInfo download = await blobClient.DownloadAsync().ConfigureAwait(false);
return download.Content;
}
public Pageable<BlobItem> ListBlobsInContainer()
{
return _blobContainerClient.GetBlobs();
}
public async Task DeleteBlobAsync(string blobId)
{
BlobClient blobClient = _blobContainerClient.GetBlobClient(blobId);
await blobClient.DeleteIfExistsAsync().ConfigureAwait(false);
}
public async Task DeleteBlobContainerAsync()
{
await _blobContainerClient.DeleteIfExistsAsync().ConfigureAwait(false);
}
//public string GetBlobSasUri(string blobName, DateTimeOffset accessExpiryTime)
//{
// BlobClient blobClient = _blobContainerClient.GetBlobClient(blobName);
// //SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
// //{
// // SharedAccessExpiryTime = accessExpiryTime,
// // Permissions = permissions
// //};
// //blobClient.get
// //string sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
// //return blob.Uri + sasBlobToken;
// TimeSpan clockSkew = TimeSpan.FromMinutes(15d);
// TimeSpan accessDuration = TimeSpan.FromMinutes(15d);
// // Defines the resource being accessed and for how long the access is allowed.
// var blobSasBuilder = new BlobSasBuilder
// {
// StartsOn = DateTime.UtcNow.Subtract(clockSkew),
// ExpiresOn = DateTime.UtcNow.Add(accessDuration) + clockSkew,
// BlobContainerName = _blobContainerName,
// BlobName = blobName,
// };
// // Defines the type of permission.
// blobSasBuilder.SetPermissions(BlobSasPermissions.Write);
// // Builds an instance of StorageSharedKeyCredential
// var storageSharedKeyCredential = new StorageSharedKeyCredential(< AccountName >, < AccountKey >);
// // Builds the Sas URI.
// BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential);
// return sasQueryParameters.ToString();
//}
}
}
| 36.733333 | 122 | 0.658802 |
23d23282beeb639a1e8da45f24047cd992c13f93 | 490 | js | JavaScript | src/App.js | alanlucascruz/react-native-to-do-list | 466f57127dc8b2e1b59961d81e65eee02f478825 | [
"MIT"
] | null | null | null | src/App.js | alanlucascruz/react-native-to-do-list | 466f57127dc8b2e1b59961d81e65eee02f478825 | [
"MIT"
] | null | null | null | src/App.js | alanlucascruz/react-native-to-do-list | 466f57127dc8b2e1b59961d81e65eee02f478825 | [
"MIT"
] | null | null | null | /**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React from 'react';
import {StatusBar} from 'react-native';
import {Provider} from 'react-redux';
import store from './store';
import List from './screens/List';
StatusBar.setBackgroundColor('#003491');
StatusBar.setBarStyle('light-content');
const App = () => {
return (
<Provider store={store}>
<List />
</Provider>
);
};
export default App;
| 16.896552 | 43 | 0.657143 |
96dff9f7a1d22173e57f9d546ebc09b3cb7f7922 | 11,323 | dart | Dart | lib/src/template/properties.dart | acanvas/acanvas-generator | 05dbf5a7639e946680dfc5572d32a0fa19d66745 | [
"BSD-3-Clause"
] | 9 | 2018-09-18T08:19:49.000Z | 2020-09-10T03:33:36.000Z | lib/src/template/properties.dart | block-forest/rockdot-generator | 05dbf5a7639e946680dfc5572d32a0fa19d66745 | [
"BSD-3-Clause"
] | null | null | null | lib/src/template/properties.dart | block-forest/rockdot-generator | 05dbf5a7639e946680dfc5572d32a0fa19d66745 | [
"BSD-3-Clause"
] | 1 | 2020-07-27T01:02:05.000Z | 2020-07-27T01:02:05.000Z | part of acanvas_generator;
/**
* The <code>Properties</code> class represents a collection of properties
* in the form of key-value pairs. All keys and values are of type
* <code>String</code>
*
* @author Christophe Herreman
* @author Roland Zwaga
*/
class Properties {
/**
* Creates a new <code>Properties</code> object.
*/
Properties() {
_content = {};
_propertyNames = new List<String>();
}
Map _content;
List<String> _propertyNames;
/**
* The content of the Properties instance as an object.
* @return an object containing the content of the properties
*/
Map get content {
return _content;
}
int get length {
return _propertyNames.length;
}
/**
* Returns an array with the keys of all properties. If no properties
* were found, an empty array is returned.
*
* @return an array with all keys
*/
List<String> get propertyNames {
return _propertyNames;
}
/**
* Gets the value of property that corresponds to the given <code>key</code>.
* If no property was found, <code>null</code> is returned.
*
* @param key the name of the property to get
* @returns the value of the property with the given key, or null if none was found
*/
dynamic getProperty(String key) {
return _content[key];
}
bool hasProperty(String key) {
return _content.containsKey(key);
}
/**
* Adds all conIPropertiese given properties object to this Properties.
*/
void merge(Properties properties, [bool overrideProperty = false]) {
if ((properties == null) || (properties == this)) {
return;
}
for (String key in properties.content.keys) {
if (_content[key] == null ||
(_content[key] != null && overrideProperty)) {
setProperty(key, properties.content[key]);
/*addPropertyName(key);
_content[key] = properties.content[key];*/
}
}
}
/**
* Sets a property. If the property with the given key already exists,
* it will be replaced by the new value.
*
* @param key the key of the property to set
* @param value the value of the property to set
*/
void setProperty(String key, String value) {
addPropertyName(key);
_content[key] = value;
//logger.finer("Added property: $key = $value");
}
void addPropertyName(String key) {
if (_propertyNames.indexOf(key) < 0) {
_propertyNames.add(key);
}
}
}
/**
* <p><code>KeyValuePropertiesParser</code> parses a properties source string into a <code>IPropertiesProvider</code>
* instance.</p>
*
* <p>The source string contains simple key-value pairs. Multiple pairs are
* separated by line terminators (\n or \r or \r\n). Keys are separated from
* values with the characters '=', ':' or a white space character.</p>
*
* <p>Comments are also supported. Just add a '#' or '!' character at the
* beginning of your comment-line.</p>
*
* <p>If you want to use any of the special characters in your key or value you
* must escape it with a back-slash character '\'.</p>
*
* <p>The key contains all of the characters in a line starting from the first
* non-white space character up to, but not including, the first unescaped
* key-value-separator.</p>
*
* <p>The value contains all of the characters in a line starting from the first
* non-white space character after the key-value-separator up to the end of the
* line. You may of course also escape the line terminator and create a value
* across multiple lines.</p>
*
* @see org.springextensions.actionscript.collections.Properties Properties
*
* @author Martin Heidegger
* @author Simon Wacker
* @author Christophe Herreman
* @version 1.0
*/
class KeyValuePropertiesParser {
static const int HASH_CHARCODE = 35;
//= "#";
static const int EXCLAMATION_MARK_CHARCODE = 33;
//= "!";
static const String DOUBLE_BACKWARD_SLASH = '\\';
static const String NEWLINE_CHAR = "\n";
static final RegExp NEWLINE_REGEX = new RegExp(r'\\n');
// /\\n/gm;
/**
* Constructs a new <code>PropertiesParser</code> instance.
*/
KeyValuePropertiesParser() : super() {}
/**
* Parses the given <code>source</code> and creates a <code>Properties</code> instance from it.
*
* @param source the source to parse
* @return the properties defined by the given <code>source</code>
*/
void parseProperties(dynamic source, Properties provider) {
MultilineString lines = new MultilineString((source.toString()));
num numLines = lines.numLines;
String key = "";
String value = "";
String formerKey = "";
String formerValue = "";
bool useNextLine = false;
for (int i = 0; i < numLines; i++) {
String line = lines.getLine(i);
//logger.finer("Parsing line: {0}", [line]);
// Trim the line
line = trim(line);
// Ignore Comments and empty lines
if (isPropertyLine(line)) {
// Line break processing
if (useNextLine) {
key = formerKey;
value = formerValue + line;
useNextLine = false;
} else {
int sep = line.indexOf("=");
key = rightTrim(line.substring(0, sep));
value = line.substring(sep + 1);
formerKey = key;
formerValue = value;
}
// Trim the content
value = leftTrim(value);
// Allow normal lines
String end = value == "" ? "" : value.substring(value.length - 1);
if (end == DOUBLE_BACKWARD_SLASH) {
formerValue = value = value.substring(0, value.length - 1);
useNextLine = true;
} else {
// restore newlines since these were escaped when loaded
value = value.replaceAll(NEWLINE_REGEX, NEWLINE_CHAR);
provider.setProperty(key, value);
}
} else {
//logger.finer("Ignoring commented line.");
}
}
}
static String trim(String str) {
if (str == null) {
return null;
}
return str
.replaceAll(new RegExp(r'^\s*'), '')
.replaceAll(new RegExp(r'\s*$'), '');
}
/**
* Removes all empty characters at the beginning of a string.
*
* <p>Characters that are removed: spaces <code>" "</code>, line forwards <code>\n</code>
* and extended line forwarding <code>\t\n</code>.</p>
*
* @param string the string to trim
* @return the trimmed string
*/
static String leftTrim(String string) {
return leftTrimForChars(string, "\n\t\n ");
}
/**
* Removes all empty characters at the end of a string.
*
* <p>Characters that are removed: spaces <code>" "</code>, line forwards <code>\n</code>
* and extended line forwarding <code>\t\n</code>.</p>
*
* @param string the string to trim
* @return the trimmed string
*/
static String rightTrim(String string) {
return rightTrimForChars(string, "\n\t\n ");
}
/**
* Removes all characters at the beginning of the <code>String</code> that match to the
* set of <code>chars</code>.
*
* <p>This method splits all <code>chars</code> and removes occurencies at the beginning.</p>
*
* <p>Example: dynamic <code>
* print(StringUtil.rightTrimForChars("ymoynkeym", "ym")); // oynkeym
* print(StringUtil.rightTrimForChars("monkey", "mo")); // nkey
* print(StringUtil.rightTrimForChars("monkey", "om")); // nkey
* </code></p>
*
* @param string the string to trim
* @param chars the characters to remove from the beginning of the <code>String</code>
* @return the trimmed string
*/
static String leftTrimForChars(String string, String chars) {
num from = 0;
num to = string.length;
while (from < to && chars.indexOf(string[from]) >= 0) {
from++;
}
return (from > 0 ? string.substring(from, to) : string);
}
/**
* Removes all characters at the end of the <code>String</code> that match to the set of
* <code>chars</code>.
*
* <p>This method splits all <code>chars</code> and removes occurencies at the end.</p>
*
* <p>Example: dynamic <code>
* print(StringUtil.rightTrimForChars("ymoynkeym", "ym")); // ymoynke
* print(StringUtil.rightTrimForChars("monkey***", "*y")); // monke
* print(StringUtil.rightTrimForChars("monke*y**", "*y")); // monke
* </code></p>
*
* @param string the string to trim
* @param chars the characters to remove from the end of the <code>String</code>
* @return the trimmed string
*/
static String rightTrimForChars(String string, String chars) {
num from = 0;
num to = string.length - 1;
while (from < to && chars.indexOf(string[to]) >= 0) {
to--;
}
return (to >= 0 ? string.substring(from, to + 1) : string);
}
bool isPropertyLine(String line) {
return (line != null &&
line.length > 0 &&
line.codeUnitAt(0) != HASH_CHARCODE &&
line.codeUnitAt(0) != EXCLAMATION_MARK_CHARCODE &&
line.length != 0);
}
}
/**
* <code>MultilineString</code> allows to access all lines of a string separately.
*
* <p>To not have to deal with different forms of line breaks (Windows/Apple/Unix)
* <code>MultilineString</code> automatically standardizes them to the <code>\n</code> character.
* So the passed-in <code>String</code> will always get standardized.</p>
*
* <p>If you need to access the original <code>String</code> you can use
* <code>getOriginalString</code>.</p>
*
* @author Martin Heidegger, Christophe Herreman
* @version 1.0
*/
class MultilineString {
/** Character code for the WINDOWS line break. */
static final String WIN_BREAK =
new String.fromCharCodes([13]) + new String.fromCharCodes([10]);
/** Character code for the APPLE line break. */
static final String MAC_BREAK = new String.fromCharCodes([13]);
/** Character used internally for line breaks. */
static const String NEWLINE_CHAR = "\n";
/** Original content without standardized line breaks. */
String _original;
/** Separation of all lines for the string. */
List _lines;
/**
* Constructs a new MultilineString.
*/
MultilineString(String string) : super() {
initMultiString(string);
}
void initMultiString(String string) {
_original = string;
_lines = string
.split(WIN_BREAK)
.join(NEWLINE_CHAR)
.split(MAC_BREAK)
.join(NEWLINE_CHAR)
.split(NEWLINE_CHAR);
}
/**
* Returns the original used string (without line break standarisation).
*
* @return the original used string
*/
String get originalString {
return _original;
}
/**
* Returns a specific line within the <code>MultilineString</code>.
*
* <p>It will return <code>undefined</code> if the line does not exist.</p>
*
* <p>The line does not contain the line break.</p>
*
* <p>The counting of lines startes with <code>0</code>.</p>
*
* @param line number of the line to get the content of
* @return content of the line
*/
String getLine(int line) {
return _lines[line];
}
/**
* Returns the content as array that contains each line.
*
* @return content split into lines
*/
List get lines {
return new List.from(_lines);
}
/**
* Returns the amount of lines in the content.
*
* @return amount of lines within the content
*/
int get numLines {
return _lines.length;
}
}
| 29.41039 | 117 | 0.636934 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.