hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
af156d0a06838c6e2ca2275f5a6750e2270ca288
| 39
|
py
|
Python
|
mypackage/subpackage_A/A.py
|
mheikenfeld/package_testing
|
af87e50524659c7e9929e59278bb52a272a4e934
|
[
"MIT"
] | null | null | null |
mypackage/subpackage_A/A.py
|
mheikenfeld/package_testing
|
af87e50524659c7e9929e59278bb52a272a4e934
|
[
"MIT"
] | null | null | null |
mypackage/subpackage_A/A.py
|
mheikenfeld/package_testing
|
af87e50524659c7e9929e59278bb52a272a4e934
|
[
"MIT"
] | null | null | null |
def do_A():
out="A"
return out
| 9.75
| 14
| 0.512821
|
7dd44858040045b4b0632a23107fbdf0fd7e2c98
| 579
|
css
|
CSS
|
TeamsSampleHub/SampleHubReactVersion/ClientApp/src/components/MeetingVideo/MeetingVideo.css
|
jasonwbaxter/tools
|
1d15060c0ea31c22c87d4d04f741d6db199abab5
|
[
"MIT"
] | null | null | null |
TeamsSampleHub/SampleHubReactVersion/ClientApp/src/components/MeetingVideo/MeetingVideo.css
|
jasonwbaxter/tools
|
1d15060c0ea31c22c87d4d04f741d6db199abab5
|
[
"MIT"
] | null | null | null |
TeamsSampleHub/SampleHubReactVersion/ClientApp/src/components/MeetingVideo/MeetingVideo.css
|
jasonwbaxter/tools
|
1d15060c0ea31c22c87d4d04f741d6db199abab5
|
[
"MIT"
] | null | null | null |
.video-head {
margin: 0 1.5rem;
padding-top: 1rem;
font-weight: bold;
font-size: 1.063rem;
line-height: 1.25rem;
color: #ffffff;
}
.video {
height: 25rem;
margin: 1rem 1.5rem;
background: linear-gradient(
180deg,
rgba(0, 0, 0, 0) 0%,
rgba(0, 0, 0, 0.15) 100%
),
#72a1c8;
border-radius: 0.5rem;
}
.vd-stream {
height: 100%;
width: 100%;
border-radius: 0.5rem;
}
@media screen and (max-width: 26.563rem) {
.team-img {
height: 12.5rem;
}
.section4 {
height: 16.625rem;
}
.video {
height: 11.5rem;
}
}
| 14.121951
| 42
| 0.564767
|
125b85d923b84c41f021257fab8ebe9a0cb7637d
| 756
|
cs
|
C#
|
source/BackEnd/DrugCheckingCrawler/Parsers/StringHelperExtensions.cs
|
YanicHoegger/PillWarningImageRecognition
|
a006da9e719e70cb70f2787e1e396926b09b599c
|
[
"MIT"
] | null | null | null |
source/BackEnd/DrugCheckingCrawler/Parsers/StringHelperExtensions.cs
|
YanicHoegger/PillWarningImageRecognition
|
a006da9e719e70cb70f2787e1e396926b09b599c
|
[
"MIT"
] | null | null | null |
source/BackEnd/DrugCheckingCrawler/Parsers/StringHelperExtensions.cs
|
YanicHoegger/PillWarningImageRecognition
|
a006da9e719e70cb70f2787e1e396926b09b599c
|
[
"MIT"
] | null | null | null |
using System;
namespace DrugCheckingCrawler.Parsers
{
public static class StringHelperExtensions
{
public static string Replace(this string text, string oldValue, string newValue, int position)
{
var removed = text.Remove(position, oldValue.Length);
return removed.Insert(position, newValue);
}
public static string RemoveAllBefore(this string text, char toRemove, int position)
{
int i;
for(i = position - 1; i >= 0; i--)
{
if(text[i] != toRemove)
{
break;
}
}
return text.Remove(i + 1, position - i - 1);
}
}
}
| 27
| 103
| 0.5
|
1a99bd3bc5b6b54e943c5ae4f21b519800f08a65
| 1,670
|
py
|
Python
|
ProjectApplication/variable_templates/models.py
|
code-review-doctor/project-application
|
d85b40b69572efbcda24ce9c40803f76d8ffd192
|
[
"MIT"
] | 5
|
2020-07-29T10:00:11.000Z
|
2022-02-19T11:00:34.000Z
|
ProjectApplication/variable_templates/models.py
|
code-review-doctor/project-application
|
d85b40b69572efbcda24ce9c40803f76d8ffd192
|
[
"MIT"
] | 471
|
2019-09-20T14:37:28.000Z
|
2022-03-25T14:16:34.000Z
|
ProjectApplication/variable_templates/models.py
|
code-review-doctor/project-application
|
d85b40b69572efbcda24ce9c40803f76d8ffd192
|
[
"MIT"
] | 5
|
2020-03-15T12:42:47.000Z
|
2022-02-15T18:06:52.000Z
|
from django.db import models
from project_core.models import CreateModifyOn, FundingInstrument, Call
class TemplateVariableName(CreateModifyOn):
name = models.CharField(help_text='{{ name }} in the text where this gets replaced', max_length=200)
default = models.CharField(help_text="Default value if a Call doesn't override it", max_length=200)
description = models.CharField(help_text='Definition of a variable', max_length=200)
def __str__(self):
return f'{self.name}-{self.default}'
class AbstractVariableTemplate(CreateModifyOn):
name = models.ForeignKey(TemplateVariableName, on_delete=models.PROTECT)
value = models.CharField(help_text='Value for the variable in this funding instrument', max_length=200)
class Meta:
abstract = True
def __str__(self):
return f'{self.name}-{self.value}'
class FundingInstrumentVariableTemplate(AbstractVariableTemplate):
funding_instrument = models.ForeignKey(FundingInstrument, help_text='Funding instrument that this text belongs to',
on_delete=models.PROTECT)
class Meta:
unique_together = (('funding_instrument', 'name'),)
def __str__(self):
return f'Funding Instrument: {self.funding_instrument} - {{{self.name}}}-{self.value}'
class CallVariableTemplate(AbstractVariableTemplate):
call = models.ForeignKey(Call, help_text='Call that this text belongs to',
on_delete=models.PROTECT)
class Meta:
unique_together = (('call', 'name'),)
def __str__(self):
return f'Funding Instrument: {self.call} - {{{self.name}}}-{self.value}'
| 36.304348
| 119
| 0.698204
|
ab7b10de78158f46790b8f39354802c08f07ad84
| 261
|
rb
|
Ruby
|
models/rx_confirmations.rb
|
nondejus/satellite-api
|
c167a6628b8e642d69cbb015e4e362d39d2b0295
|
[
"MIT"
] | 1
|
2019-06-09T14:43:43.000Z
|
2019-06-09T14:43:43.000Z
|
models/rx_confirmations.rb
|
nondejus/satellite-api
|
c167a6628b8e642d69cbb015e4e362d39d2b0295
|
[
"MIT"
] | null | null | null |
models/rx_confirmations.rb
|
nondejus/satellite-api
|
c167a6628b8e642d69cbb015e4e362d39d2b0295
|
[
"MIT"
] | 1
|
2019-10-06T12:16:55.000Z
|
2019-10-06T12:16:55.000Z
|
require "sinatra/activerecord"
require_relative '../constants'
require_relative './orders'
class RxConfirmation < ActiveRecord::Base
validates :order_id, presence: true
validates :region_id, presence: true
belongs_to :order
belongs_to :region
end
| 21.75
| 41
| 0.770115
|
f4b5975172c10ecfefc3fa21a7980c00cd376c71
| 1,963
|
php
|
PHP
|
wp-content/plugins/wp-simple-firewall/src/lib/vendor/fernleafsystems/wordpress-services/src/Utilities/WpOrg/Plugin/Repo.php
|
biocuration/website
|
ec99ee1f9e161ff7a9247ad041d44739f9212dfb
|
[
"BSD-3-Clause"
] | 2
|
2017-07-24T09:25:07.000Z
|
2018-04-09T14:51:38.000Z
|
wp-content/plugins/wp-simple-firewall/src/lib/vendor/fernleafsystems/wordpress-services/src/Utilities/WpOrg/Plugin/Repo.php
|
biocuration/isb-website
|
ec99ee1f9e161ff7a9247ad041d44739f9212dfb
|
[
"BSD-3-Clause"
] | 66
|
2016-11-30T10:46:15.000Z
|
2022-02-19T03:57:11.000Z
|
wp-content/plugins/wp-simple-firewall/src/lib/vendor/fernleafsystems/wordpress-services/src/Utilities/WpOrg/Plugin/Repo.php
|
biocuration/website
|
ec99ee1f9e161ff7a9247ad041d44739f9212dfb
|
[
"BSD-3-Clause"
] | 1
|
2020-11-04T07:39:15.000Z
|
2020-11-04T07:39:15.000Z
|
<?php
namespace FernleafSystems\Wordpress\Services\Utilities\WpOrg\Plugin;
use FernleafSystems\Wordpress\Services;
/**
* Class Repo
* @package FernleafSystems\Wordpress\Services\Utilities\WpOrg\Plugin
*/
class Repo extends Services\Utilities\WpOrg\Base\RepoBase {
use Base;
const URL_VCS_ROOT = 'https://plugins.svn.wordpress.org';
const URL_VCS_DOWNLOAD_VERSIONS = 'https://plugins.svn.wordpress.org/%s/tags/';
const URL_DOWNLOAD_SVN_FILE = 'https://plugins.svn.wordpress.org/%s/tags/%s/%s';
/**
* @param string $sSlug
* @return string
*/
public static function GetUrlForPlugin( $sSlug ) {
return sprintf( '%s/%s', static::URL_VCS_ROOT, $sSlug );
}
/**
* @param string $sSlug
* @param string $sVersion
* @return string
*/
public static function GetUrlForPluginVersion( $sSlug, $sVersion ) {
if ( $sVersion != 'trunk' ) {
$sVersion = sprintf( 'tags/%s', $sVersion );
}
return sprintf( '%s/%s', static::GetUrlForPlugin( $sSlug ), $sVersion );
}
/**
* @param string $sSlug
* @return string
*/
public static function GetUrlForPluginVersions( $sSlug ) {
return static::GetUrlForPluginVersion( $sSlug, '' );
}
/**
* @param string $sFileFragment - relative to the working plugin directory
* @param string $sVersion
* @param bool $bUseSiteLocale - unused
* @return string
* @throws \Exception
*/
protected function getVcsUrlForFileAndVersion( $sFileFragment, $sVersion = null, $bUseSiteLocale = true ) {
if ( empty( $sFileFragment ) ) {
throw new \InvalidArgumentException( 'Plugin file fragment path provided is empty' );
}
if ( empty( $sVersion ) ) {
$sVersion = $this->getWorkingVersion();
}
if ( empty( $sVersion ) ) {
$sVersion = ( new Versions() )
->setWorkingSlug( $this->getWorkingSlug() )
->latest();
}
return sprintf( '%s/%s',
rtrim( static::GetUrlForPluginVersion( $this->getWorkingSlug(), $sVersion ), '/' ),
ltrim( $sFileFragment, '/' )
);
}
}
| 28.042857
| 108
| 0.673459
|
e29205b17333ab189596e2dde72eb7cc60a40b8e
| 1,056
|
js
|
JavaScript
|
examples/nodejs/index-account.js
|
jchavarri/flywheeljs
|
7616dc481e58c9094d37162a74a424addf8d8da6
|
[
"MIT"
] | 5
|
2016-04-03T19:58:09.000Z
|
2018-11-11T16:46:57.000Z
|
examples/nodejs/index-account.js
|
jchavarri/flywheeljs
|
7616dc481e58c9094d37162a74a424addf8d8da6
|
[
"MIT"
] | null | null | null |
examples/nodejs/index-account.js
|
jchavarri/flywheeljs
|
7616dc481e58c9094d37162a74a424addf8d8da6
|
[
"MIT"
] | null | null | null |
const program = require('commander');
const chalk = require('chalk');
const flywheel = require('flywheeljs');
program
.description('get information about your Flywheel account')
.option('-e, --email <email>', '[required] The email of the user to authenticate as')
.option('-p, --password <password>', '[required] The user\'s password')
.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp();
}
else {
if (program.email && program.password) {
flywheel.login({
email: program.email,
password: program.password
})
.then(function(response) {
console.log(chalk.green('Success! 😀\nAuth token:\n', response.auth_token, '\nYour user information is:\n', JSON.stringify(response.passenger, null, ' ')));
})
.catch(function(error) {
console.log(chalk.red('There was an error: ⚠️\n', JSON.stringify(error, null, ' ')));
});
}
else {
console.log(chalk.yellow('Some of these params are missing: <email>, <password>. Use -h or --help to get some usage information'));
}
}
| 34.064516
| 162
| 0.655303
|
207937bb149e2927bbf7894e84b2ffaaf752d1ea
| 2,672
|
lua
|
Lua
|
lua/engine/camera.lua
|
ousttrue/limgui
|
98c95bd283b92a23495f42a7dd9c8b1c48681945
|
[
"MIT"
] | null | null | null |
lua/engine/camera.lua
|
ousttrue/limgui
|
98c95bd283b92a23495f42a7dd9c8b1c48681945
|
[
"MIT"
] | null | null | null |
lua/engine/camera.lua
|
ousttrue/limgui
|
98c95bd283b92a23495f42a7dd9c8b1c48681945
|
[
"MIT"
] | null | null | null |
local maf = require "mafex"
local utils = require "limgui.utils"
local M = {}
---@class Camera
---@field shift vec3
---@field yaw_degree number
---@field pietch_degree number
---@field view mat4
---@field projection mat4
M.OrbitCamera = {
matrix = function(self)
return self.view * self.projection
end,
--projection
update_projection = function(self)
self.projection = maf.mat4.perspective(self.fovy_degree, self.width / self.height, self.near, self.far)
end,
resize = function(self, w, h)
self.width = w
self.height = h
self:update_projection()
end,
--view
update_view = function(self)
self.view = maf.mat4.rotation_y(self.yaw_degree)
* maf.mat4.rotation_x(self.pitch_degree)
* maf.mat4.translation(self.shift)
end,
mouse_move = function(self, x, y)
if self.x then
local dx = x - self.x
local dy = y - self.y
if self.mouse_right then
self.yaw_degree = self.yaw_degree + dx
self.pitch_degree = self.pitch_degree - dy
self:update_view()
end
if self.mouse_middle then
local t = math.tan(self.fovy_degree * 0.5 * math.pi / 180)
self.shift.x = self.shift.x - (dx / self.height) * t * self.shift.z * 2
self.shift.y = self.shift.y + (dy / self.height) * t * self.shift.z * 2
self:update_view()
end
end
self.x = x
self.y = y
end,
mouse_button = function(self, button, is_down)
if button == 0 then
self.mouse_left = is_down
elseif button == 1 then
self.mouse_right = is_down
elseif button == 2 then
self.mouse_middle = is_down
end
end,
mouse_wheel = function(self, d)
if d > 0 then
self.shift.z = self.shift.z * 0.9
self:update_view()
elseif d < 0 then
self.shift.z = self.shift.z * 1.1
self:update_view()
end
end,
}
M.OrbitCamera.new = function(width, height)
local camera = utils.new(M.OrbitCamera, {
projection = maf.mat4.identity(),
near = 0.01,
far = 100,
fovy_degree = 50,
width = width or 1,
height = height or 1,
view = maf.mat4.identity(),
shift = maf.vec3(0, 0, -5),
yaw_degree = 0,
pitch_degree = 0,
mouse_left = false,
mouse_middle = false,
mouse_right = false,
})
camera:update_projection()
camera:update_view()
return camera
end
return M
| 26.72
| 111
| 0.552021
|
4ac814d23b50a014c10ffbf8a2d5bc57c4eec233
| 856
|
swift
|
Swift
|
Example/SimpleMenuKit/AppDelegate.swift
|
DistributionSouceCode/SimpleMenuKit
|
1053f63581223bf150d6a8c2461422d1a3428ad8
|
[
"MIT"
] | 2
|
2018-10-01T06:16:25.000Z
|
2019-06-20T13:54:39.000Z
|
Example/SimpleMenuKit/AppDelegate.swift
|
DistributionSouceCode/SimpleMenuKit
|
1053f63581223bf150d6a8c2461422d1a3428ad8
|
[
"MIT"
] | null | null | null |
Example/SimpleMenuKit/AppDelegate.swift
|
DistributionSouceCode/SimpleMenuKit
|
1053f63581223bf150d6a8c2461422d1a3428ad8
|
[
"MIT"
] | null | null | null |
//
// AppDelegate.swift
// SimpleMenuKit
//
// Created by seyhagithub on 03/14/2018.
// Copyright (c) 2018 seyhagithub. All rights reserved.
//
import UIKit
import SimpleMenuKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let menuSide = LeftViewController()
let home = ViewController()
let mainViewController = MKWrapperViewController({
return menuSide
}, mkHomeViewController: home)
window?.rootViewController = mainViewController
return true
}
}
| 20.878049
| 143
| 0.671729
|
fcc088ef6df90308b04db8a0799ac1a2b53174ba
| 335
|
dart
|
Dart
|
lib/loading_widget.dart
|
danilopeixoto/mural
|
fdc8410f8a02960cdd55a7be45ed738e55c315c2
|
[
"BSD-3-Clause"
] | null | null | null |
lib/loading_widget.dart
|
danilopeixoto/mural
|
fdc8410f8a02960cdd55a7be45ed738e55c315c2
|
[
"BSD-3-Clause"
] | null | null | null |
lib/loading_widget.dart
|
danilopeixoto/mural
|
fdc8410f8a02960cdd55a7be45ed738e55c315c2
|
[
"BSD-3-Clause"
] | null | null | null |
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class LoadingWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SpinKitFadingCircle(
color: Theme.of(context).primaryColor,
size: 50.0,
)
);
}
}
| 22.333333
| 54
| 0.692537
|
15837ee150045d5e0318cbc7f8be8bec0862e4e7
| 646
|
rb
|
Ruby
|
lib/at_coder_friends/scraping/session.rb
|
suzukiapple/at_coder_friends
|
764cf41449b71a0e2e32ed1be008c43641438133
|
[
"MIT"
] | 14
|
2018-11-21T12:56:22.000Z
|
2021-11-30T23:34:10.000Z
|
lib/at_coder_friends/scraping/session.rb
|
suzukiapple/at_coder_friends
|
764cf41449b71a0e2e32ed1be008c43641438133
|
[
"MIT"
] | 3
|
2019-09-01T09:19:43.000Z
|
2020-12-14T04:56:12.000Z
|
lib/at_coder_friends/scraping/session.rb
|
suzukiapple/at_coder_friends
|
764cf41449b71a0e2e32ed1be008c43641438133
|
[
"MIT"
] | 2
|
2019-08-30T15:51:56.000Z
|
2020-12-14T02:14:58.000Z
|
# frozen_string_literal: true
module AtCoderFriends
module Scraping
# session management for scraping
module Session
SESSION_STORE_FMT = File.join(
Dir.home, '.at_coder_friends', '%<user>s_session.yml'
)
def load_session
agent.cookie_jar.load(session_store) if File.exist?(session_store)
end
def save_session
dir = File.dirname(session_store)
Dir.mkdir(dir) unless Dir.exist?(dir)
agent.cookie_jar.save_as(session_store)
end
def session_store
@session_store ||= format(SESSION_STORE_FMT, user: ctx.config['user'])
end
end
end
end
| 23.925926
| 78
| 0.660991
|
da5507fffa6781fb1889d15069dfbadfbaece948
| 2,953
|
php
|
PHP
|
resources/views/hairdresser/menu.blade.php
|
GeorgeLxL/publicmedia
|
91b5fef8d523c267b195c9b70ebe43f6b3962580
|
[
"MIT"
] | 1
|
2021-03-20T02:00:19.000Z
|
2021-03-20T02:00:19.000Z
|
resources/views/hairdresser/menu.blade.php
|
GeorgeLxL/publicmedia
|
91b5fef8d523c267b195c9b70ebe43f6b3962580
|
[
"MIT"
] | null | null | null |
resources/views/hairdresser/menu.blade.php
|
GeorgeLxL/publicmedia
|
91b5fef8d523c267b195c9b70ebe43f6b3962580
|
[
"MIT"
] | null | null | null |
@extends('layouts.header1')
@section('title','menu')
@section('page-title')
<img src="{{asset('img/menu.png')}}">
<span class="title">メニュー</span>
@endsection
@section('content')
<div class="container" style="padding-bottom:30px">
<div class="row justify-content-center">
<div class="col-lg-11" style="padding-top: 70px;">
<div class="card card-default" >
<div class="card-header">メニュー</div>
<div class="card-body">
<h6>メニューグループ</h6>
<center>
<a href="menu_groups/edit" class="menu_button">メニューグループを編集する</a>
</center>
@foreach($returnval['menu_groups'] as $row)
<div>{{$row->name}}</div>
@endforeach
<hr>
<h6>メニ1ュー</h6>
@php
$i=0;
@endphp
@foreach($returnval['menu_groups'] as $row)
<div class="menu-group-title"> {{$row->name}} のメニュー </div>
<div class="row" style="margin-top:20px">
<div class="col-md-12">
<table class="table">
<thead>
<tr><th>名前</th>
<th>金額</th>
<th>説明</th>
<th> 所要時間</th>
</tr></thead>
<tbody>
@foreach($returnval['menus'][$i] as $menu)
<tr>
@foreach($menu as $key=>$val)
@if($key=='name' || $key=='amount' || $key=='explanation' || $key=='requiretime')
<td>{{$val}}</td>
@endif
@endforeach
</tr>
@endforeach
</tbody>
</table>
<center>
<a href="menu/edit/{{$row->name}}" class="menu_button">{{$row->name}}のメニューを編集する</a>
</center>
</div>
</div>
@php
$i++;
@endphp
@endforeach
</div>
</div>
</div>
</div>
</div>
@endsection
| 44.074627
| 129
| 0.293938
|
454f6845dd1744d0736b6966d1cbbdf4594ec3c7
| 1,601
|
py
|
Python
|
Main/Files/inference.py
|
123freezebrennan/OpenVINO-Car-Pedestrian-Tracker-and-Counter
|
cc582965ad001e5978ebe31bae649dd360c24dca
|
[
"Intel"
] | null | null | null |
Main/Files/inference.py
|
123freezebrennan/OpenVINO-Car-Pedestrian-Tracker-and-Counter
|
cc582965ad001e5978ebe31bae649dd360c24dca
|
[
"Intel"
] | null | null | null |
Main/Files/inference.py
|
123freezebrennan/OpenVINO-Car-Pedestrian-Tracker-and-Counter
|
cc582965ad001e5978ebe31bae649dd360c24dca
|
[
"Intel"
] | null | null | null |
from openvino.inference_engine import IECore, IENetwork
class Network:
#Constructor class to declare variables, any of these still as 'None' in console, an error occured when initializing it
def __init__(self):
#NEED TO: put ntoes done indicating what each does
self.plugin = None
self.network = None
self.input_blob = None
self.output_blob = None
self.exec_network = None
self.infer_request = None
def load_model(self, model, bin, device = "CPU"):
#Brings in IR file to be read as an .xml, morphs string to be seen as a .bin in the same folder, as it should be
model_xml = model
model_bin = bin
self.plugin = IECore()
self.network = IENetwork(model_xml, weights = model_bin)
self.exec_network = self.plugin.load_network(self.network, device)
self.input_blob = next(iter(self.network.inputs))
self.output_blob = next(iter(self.network.outputs))
return
def get_input_shape(self):
return self.network.inputs[self.input_blob].shape
def async_inference(self, image):
self.exec_network.start_async(request_id = 0, inputs = {self.input_blob: image})
return
def synchronous_inference(self,image):
self.exec_network.infer({self.input_blob: image})
return
def wait(self):
status = self.exec_network.requests[0].wait(-1)
return status
def extract_output(self):
return self.exec_network.requests[0].outputs[self.output_blob]
| 34.06383
| 124
| 0.646471
|
6db8b2ba33ba80c4c63aa4c5bd7347a9a48006cb
| 4,155
|
ts
|
TypeScript
|
client/src/store/chat/reducers/chatReducer.ts
|
AzamatKomaev/social_site
|
4db54c593e6315aa9a767b4db75f43a0cd7f2683
|
[
"MIT"
] | 2
|
2021-11-16T04:46:47.000Z
|
2022-02-15T12:06:08.000Z
|
client/src/store/chat/reducers/chatReducer.ts
|
AzamatKomaev/social_site
|
4db54c593e6315aa9a767b4db75f43a0cd7f2683
|
[
"MIT"
] | null | null | null |
client/src/store/chat/reducers/chatReducer.ts
|
AzamatKomaev/social_site
|
4db54c593e6315aa9a767b4db75f43a0cd7f2683
|
[
"MIT"
] | null | null | null |
import {
SET_FETCHING,
GET_CHAT_LIST, SORT_CHATS_BY_NAME, SORT_CHATS_BY_LAST_MESSAGE, FILTER_CHATS_BY_STRING, GET_CHAT_DETAIL
} from "../actionTypes";
import {GroupChatI, PersonalChatI} from "../../../interfaces";
interface ChatListStateI {
detail: any,
type: string,
list: any,
filteredChatList: Array<GroupChatI | PersonalChatI>
}
const defaultChatListState: ChatListStateI = {
type: null,
detail: {
value: null,
statusCode: null
},
list: {
values: null,
lastStatusCode: null,
page: 1,
fetching: true,
},
filteredChatList: []
}
export const chatListReducer = (state: ChatListStateI = defaultChatListState, action: any) => {
let newChatList;
switch (action.type) {
case GET_CHAT_LIST:
if (state.list.fetching && state.list.lastStatusCode !== 201) {
let page = state.list.page;
if (action.payload.statusCode === 204 || action.payload.statusCode === 404) page = -1;
else page++;
return {
...state,
...action.payload,
list: {
values: [...state.list.values || [], ...action.payload.list],
lastStatusCode: action.payload.statusCode === 404 ? 201 : action.payload.statusCode,
page: page,
fetching: false,
type: action.payload.type
}
}
}
return state
case GET_CHAT_DETAIL:
return {
...state,
detail: {
value: action.payload.detail,
statusCode: action.payload.statusCode
}
}
case SET_FETCHING:
return {
...state,
list: {
...state.list,
fetching: action.payload.fetching
}
}
case SORT_CHATS_BY_NAME:
if (state.type === "group") {
newChatList = state.list.values.sort(
(a: GroupChatI, b: GroupChatI) => a.name.localeCompare(b.name)
)
} else if (state.type === "personal") {
newChatList = state.list.values.sort(
(a: PersonalChatI, b: PersonalChatI) => a.interlocutor.username.localeCompare(b.interlocutor.username)
)
}
return {
...state,
list: {
...state.list,
values: newChatList
}
}
case SORT_CHATS_BY_LAST_MESSAGE:
newChatList = state.list.values.sort((a: GroupChatI | PersonalChatI, b: GroupChatI | PersonalChatI): number => {
if (!a.last_message.created_at) {
return 1
}
if (!b.last_message.created_at) {
return -1
}
if (a.last_message.created_at > b.last_message.created_at) {
return -1
} else {
return 1
}
}
)
return {
...state,
list: {
...state.list,
values: newChatList
}
}
case FILTER_CHATS_BY_STRING:
let filteredChatList;
if (state.type === "group") {
filteredChatList = state.list.values.filter(chat => chat.name.indexOf(action.payload.string) !== -1)
} else if (state.type === "personal") {
filteredChatList = state.list.values.filter(
chat => chat.interlocutor.username.indexOf(action.payload.string) !== -1
)
}
return {
...state,
filteredChatList: filteredChatList
}
default:
return state
}
}
| 31.007463
| 124
| 0.455355
|
dbf8bc164e5d0c5e5002788b2fecae8c3165d616
| 2,010
|
php
|
PHP
|
views/dokter/_form.php
|
yogizafitrah/mini-rs
|
38d21cc8071f7453771954f8397d9021d4b60b2d
|
[
"BSD-3-Clause"
] | null | null | null |
views/dokter/_form.php
|
yogizafitrah/mini-rs
|
38d21cc8071f7453771954f8397d9021d4b60b2d
|
[
"BSD-3-Clause"
] | null | null | null |
views/dokter/_form.php
|
yogizafitrah/mini-rs
|
38d21cc8071f7453771954f8397d9021d4b60b2d
|
[
"BSD-3-Clause"
] | null | null | null |
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\widgets\DateRangePicker;
/* @var $this yii\web\View */
/* @var $model app\models\Dokter */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="dokter-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'no_dokter')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'nama_dokter')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'jk_dokter')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'tanggal_lahir')->widget(\yii\widgets\MaskedInput::class, [
'mask' => '99/99/9999',]); ?>
<?= $form->field($model, 'tempat_lahir')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'status_dokter')->dropDownList([ 'Belum Menikah' => 'Belum Menikah', 'Menikah' => 'Menikah', 'Duda' => 'Duda', 'Janda' => 'Janda', ], ['prompt' => '']) ?>
<?= $form->field($model, 'agama_dokter')->dropDownList([ 'Islam' => 'Islam', 'Katolik' => 'Katolik', 'Protestan' => 'Protestan', 'Buddha' => 'Buddha', 'Hindu' => 'Hindu', 'Kong Hu cu' => 'Kong Hu cu', ], ['prompt' => '']) ?>
<?= $form->field($model, 'pendidikan_dokter')->dropDownList([ 'TK' => 'TK', 'SD' => 'SD', 'SMP' => 'SMP', 'SMA/SMK' => 'SMA/SMK', 'D3' => 'D3', 'D4' => 'D4', 'S1' => 'S1', ], ['prompt' => '']) ?>
<?= $form->field($model, 'alamat_dokter')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'nohp_dokter')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'jenis_dokter')->dropDownList([ 'Umum' => 'Umum', 'Gigi' => 'Gigi', 'Spesialis' => 'Spesialis', '' => '', ], ['prompt' => '']) ?>
<?= $form->field($model, 'jenis_spesialis')->dropDownList([ 'Penyakit Dalam' => 'Penyakit Dalam', 'Syaraf' => 'Syaraf', 'Jantung' => 'Jantung', 'Obgyn' => 'Obgyn', ], ['prompt' => '']) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| 41.875
| 228
| 0.550249
|
b887e64f1d8fb50a8f48b4983236035edf763151
| 1,715
|
h
|
C
|
PrivateFrameworks/PhotoLibraryServices/PLAssetsdServer.h
|
phatblat/macOSPrivateFrameworks
|
9047371eb80f925642c8a7c4f1e00095aec66044
|
[
"MIT"
] | 17
|
2018-11-13T04:02:58.000Z
|
2022-01-20T09:27:13.000Z
|
PrivateFrameworks/PhotoLibraryServices/PLAssetsdServer.h
|
phatblat/macOSPrivateFrameworks
|
9047371eb80f925642c8a7c4f1e00095aec66044
|
[
"MIT"
] | 3
|
2018-04-06T02:02:27.000Z
|
2018-10-02T01:12:10.000Z
|
PrivateFrameworks/PhotoLibraryServices/PLAssetsdServer.h
|
phatblat/macOSPrivateFrameworks
|
9047371eb80f925642c8a7c4f1e00095aec66044
|
[
"MIT"
] | 1
|
2018-09-28T13:54:23.000Z
|
2018-09-28T13:54:23.000Z
|
//
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
#import "NSXPCListenerDelegate.h"
@class NSArray, NSMutableSet, NSString, NSXPCListener, PLBackgroundJobService, PLDistributedNotificationHandler, PLPhotoLibraryBundleController, PLXPCMessageLogger;
@interface PLAssetsdServer : NSObject <NSXPCListenerDelegate>
{
NSXPCListener *_listener;
PLXPCMessageLogger *_connectionLogger;
struct os_unfair_lock_s _servicesLock;
NSMutableSet *_services;
PLPhotoLibraryBundleController *_libraryBundleController;
PLBackgroundJobService *_backgroundJobService;
PLDistributedNotificationHandler *_distributedNotificationHandler;
NSArray *_previewRenderedContentURLs;
NSArray *_previewAssetLocalIdentifiers;
}
+ (id)sharedServer;
@property(retain, nonatomic) NSArray *previewAssetLocalIdentifiers; // @synthesize previewAssetLocalIdentifiers=_previewAssetLocalIdentifiers;
- (void).cxx_destruct;
- (id)previewRenderedContentURLAtIndex:(unsigned long long)arg1;
@property(readonly, nonatomic) unsigned long long previewRenderedContentURLCount;
- (void)setPreviewRenderedContentURLs:(id)arg1;
- (BOOL)listener:(id)arg1 shouldAcceptNewConnection:(id)arg2;
- (void)handleInvalidation:(id)arg1;
- (void)handleInterruption:(id)arg1;
- (void)removeService:(id)arg1;
- (void)addService:(id)arg1;
- (void)logStatus;
- (void)_checkInWithLaunchd;
- (void)start;
- (id)init;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 34.3
| 164
| 0.793586
|
05bd376dd5628d7b549caf34657630bda2a92602
| 1,255
|
py
|
Python
|
nobody/design_pattern.py
|
Nobody2019/nobody
|
6e3acbd02c2ea758e4e85f69d08406f26d6965de
|
[
"MIT"
] | null | null | null |
nobody/design_pattern.py
|
Nobody2019/nobody
|
6e3acbd02c2ea758e4e85f69d08406f26d6965de
|
[
"MIT"
] | null | null | null |
nobody/design_pattern.py
|
Nobody2019/nobody
|
6e3acbd02c2ea758e4e85f69d08406f26d6965de
|
[
"MIT"
] | null | null | null |
# coding=utf-8
"""
@Author: Liang Chao
@Email: nobody_team@outlook.com
@File: design_pattern.py
@Created: 2020/10/23 19:25
@Desc:
"""
from nobody.decorators import synchronized
def singleton(cls):
instances = {}
@synchronized
def get_instance(*args, **kw):
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return get_instance
# class SingletonType(type):
# _instance_lock = threading.Lock()
#
# def __call__(cls, *args, **kwargs):
# if not hasattr(cls, "_instance"):
# with SingletonType._instance_lock:
# if not hasattr(cls, "_instance"):
# cls._instance = super(SingletonType, cls).__call__(*args, **kwargs)
# return cls._instance
class SingletonType(type):
# _instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
cls._instance = super(SingletonType, cls).__call__(*args, **kwargs)
return cls._instance
class Singleton:
__instance = None
def __new__(cls, *args, **kwargs):
""""""
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
| 23.679245
| 89
| 0.612749
|
4cf9c9265a295886c8d95b8fc3125bf4c6565fba
| 290
|
py
|
Python
|
fitsbits/__init__.py
|
waqasbhatti/fitsbits
|
849fcb76d923ee7b91ca3000ff7fd0e2cd5708e7
|
[
"MIT"
] | null | null | null |
fitsbits/__init__.py
|
waqasbhatti/fitsbits
|
849fcb76d923ee7b91ca3000ff7fd0e2cd5708e7
|
[
"MIT"
] | null | null | null |
fitsbits/__init__.py
|
waqasbhatti/fitsbits
|
849fcb76d923ee7b91ca3000ff7fd0e2cd5708e7
|
[
"MIT"
] | null | null | null |
from ._version import get_versions
__version__ = get_versions()['version']
__gitrev__ = get_versions()['full-revisionid'][:7]
del get_versions
# the basic logging styles common to all modules
log_sub = '{'
log_fmt = '[{levelname} {asctime}] {message}'
log_date_fmt = '%Y-%m-%d %H:%M:%S%z'
| 29
| 50
| 0.713793
|
cc96f3b7dcd4e0f53b3c7b9cddfb0006f0f95bd9
| 17,004
|
rb
|
Ruby
|
spanner/spanner_samples.rb
|
simonz130/ruby-docs-samples
|
5713de7eff7b5705f992dcdd3a72895ddb666d39
|
[
"Apache-2.0"
] | null | null | null |
spanner/spanner_samples.rb
|
simonz130/ruby-docs-samples
|
5713de7eff7b5705f992dcdd3a72895ddb666d39
|
[
"Apache-2.0"
] | null | null | null |
spanner/spanner_samples.rb
|
simonz130/ruby-docs-samples
|
5713de7eff7b5705f992dcdd3a72895ddb666d39
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2017 Google, Inc
#
# 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.
def create_database project_id:, instance_id:, database_id:
# [START spanner_create_database]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
instance = spanner.instance instance_id
job = instance.create_database database_id, statements: [
"CREATE TABLE Singers (
SingerId INT64 NOT NULL,
FirstName STRING(1024),
LastName STRING(1024),
SingerInfo BYTES(MAX)
) PRIMARY KEY (SingerId)",
"CREATE TABLE Albums (
SingerId INT64 NOT NULL,
AlbumId INT64 NOT NULL,
AlbumTitle STRING(MAX)
) PRIMARY KEY (SingerId, AlbumId),
INTERLEAVE IN PARENT Singers ON DELETE CASCADE"
]
puts "Waiting for create database operation to complete"
job.wait_until_done!
puts "Created database #{database_id} on instance #{instance_id}"
# [END spanner_create_database]
end
def insert_data project_id:, instance_id:, database_id:
# [START spanner_insert_data]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
client.commit do |c|
c.insert "Singers", [
{ SingerId: 1, FirstName: "Marc", LastName: "Richards" },
{ SingerId: 2, FirstName: "Catalina", LastName: "Smith" },
{ SingerId: 3, FirstName: "Alice", LastName: "Trentor" },
{ SingerId: 4, FirstName: "Lea", LastName: "Martin" },
{ SingerId: 5, FirstName: "David", LastName: "Lomond" }
]
c.insert "Albums", [
{ SingerId: 1, AlbumId: 1, AlbumTitle: "Total Junk" },
{ SingerId: 1, AlbumId: 2, AlbumTitle: "Go, Go, Go" },
{ SingerId: 2, AlbumId: 1, AlbumTitle: "Green" },
{ SingerId: 2, AlbumId: 2, AlbumTitle: "Forever Hold Your Peace" },
{ SingerId: 2, AlbumId: 3, AlbumTitle: "Terrified" }
]
end
puts "Inserted data"
# [END spanner_insert_data]
end
def query_data project_id:, instance_id:, database_id:
# [START spanner_query_data]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
client.execute("SELECT SingerId, AlbumId, AlbumTitle FROM Albums").rows.each do |row|
puts "#{row[:SingerId]} #{row[:AlbumId]} #{row[:AlbumTitle]}"
end
# [END spanner_query_data]
end
def read_data project_id:, instance_id:, database_id:
# [START spanner_read_data]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
client.read("Albums", [:SingerId, :AlbumId, :AlbumTitle]).rows.each do |row|
puts "#{row[:SingerId]} #{row[:AlbumId]} #{row[:AlbumTitle]}"
end
# [END spanner_read_data]
end
def read_stale_data project_id:, instance_id:, database_id:
# [START spanner_read_stale_data]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
# Perform a read with a data staleness of 15 seconds
client.snapshot staleness: 15 do |snapshot|
snapshot.read("Albums", [:SingerId, :AlbumId, :AlbumTitle]).rows.each do |row|
puts "#{row[:SingerId]} #{row[:AlbumId]} #{row[:AlbumTitle]}"
end
end
# [END spanner_read_stale_data]
end
def create_index project_id:, instance_id:, database_id:
# [START spanner_create_index]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
instance = spanner.instance instance_id
database = instance.database database_id
job = database.update statements: [
"CREATE INDEX AlbumsByAlbumTitle ON Albums(AlbumTitle)"
]
puts "Waiting for database update to complete"
job.wait_until_done!
puts "Added the AlbumsByAlbumTitle index"
# [END spanner_create_index]
end
def create_storing_index project_id:, instance_id:, database_id:
# [START spanner_create_storing_index]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
instance = spanner.instance instance_id
database = instance.database database_id
job = database.update statements: [
"CREATE INDEX AlbumsByAlbumTitle2 ON Albums(AlbumTitle)
STORING (MarketingBudget)"
]
puts "Waiting for database update to complete"
job.wait_until_done!
puts "Added the AlbumsByAlbumTitle2 storing index"
# [END spanner_create_storing_index]
end
def add_column project_id:, instance_id:, database_id:
# [START spanner_add_column]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
instance = spanner.instance instance_id
database = instance.database database_id
job = database.update statements: [
"ALTER TABLE Albums ADD COLUMN MarketingBudget INT64"
]
puts "Waiting for database update to complete"
job.wait_until_done!
puts "Added the MarketingBudget column"
# [END spanner_add_column]
end
def update_data project_id:, instance_id:, database_id:
# [START spanner_update_data]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
client.commit do |c|
c.update "Albums", [
{ SingerId: 1, AlbumId: 1, MarketingBudget: 100_000 },
{ SingerId: 2, AlbumId: 2, MarketingBudget: 500_000 }
]
end
puts "Updated data"
# [END spanner_update_data]
end
def query_data_with_new_column project_id:, instance_id:, database_id:
# [START spanner_query_data_with_new_column]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
client.execute("SELECT SingerId, AlbumId, MarketingBudget FROM Albums").rows.each do |row|
puts "#{row[:SingerId]} #{row[:AlbumId]} #{row[:MarketingBudget]}"
end
# [END spanner_query_data_with_new_column]
end
def read_write_transaction project_id:, instance_id:, database_id:
# [START spanner_read_write_transaction]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
client.transaction do |transaction|
first_album = transaction.read("Albums", [:MarketingBudget], keys: [[1,1]]).rows.first
second_album = transaction.read("Albums", [:MarketingBudget], keys: [[2,2]]).rows.first
if second_album[:MarketingBudget] < 300_000
raise "The second album does not have enough funds to transfer"
end
new_first_album_budget = first_album[:MarketingBudget] + 200_000
new_second_album_budget = second_album[:MarketingBudget] - 200_000
transaction.update "Albums", [
{ SingerId: 1, AlbumId: 1, MarketingBudget: new_first_album_budget },
{ SingerId: 2, AlbumId: 2, MarketingBudget: new_second_album_budget }
]
end
puts "Transaction complete"
# [END spanner_read_write_transaction]
end
def query_data_with_index project_id:, instance_id:, database_id:, start_title: "Ardvark", end_title: "Goo"
# [START spanner_query_data_with_index]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
# start_title = "An album title to start with such as 'Ardvark'"
# end_title = "An album title to end with such as 'Goo'"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
sql_query = "SELECT AlbumId, AlbumTitle, MarketingBudget
FROM Albums@{FORCE_INDEX=AlbumsByAlbumTitle}
WHERE AlbumTitle >= @start_title AND AlbumTitle < @end_title"
params = { start_title: start_title, end_title: end_title }
param_types = { start_title: :STRING, end_title: :STRING }
client.execute(sql_query, params: params, types: param_types).rows.each do |row|
puts "#{row[:AlbumId]} #{row[:AlbumTitle]} #{row[:MarketingBudget]}"
end
# [END spanner_query_data_with_index]
end
def read_data_with_index project_id:, instance_id:, database_id:
# [START spanner_read_data_with_index]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
result = client.read "Albums", [:AlbumId, :AlbumTitle],
index: "AlbumsByAlbumTitle"
result.rows.each do |row|
puts "#{row[:AlbumId]} #{row[:AlbumTitle]}"
end
# [END spanner_read_data_with_index]
end
def read_data_with_storing_index project_id:, instance_id:, database_id:
# [START spanner_read_data_with_storing_index]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
result = client.read "Albums", [:AlbumId, :AlbumTitle, :MarketingBudget],
index: "AlbumsByAlbumTitle2"
result.rows.each do |row|
puts "#{row[:AlbumId]} #{row[:AlbumTitle]} #{row[:MarketingBudget]}"
end
# [END spanner_read_data_with_storing_index]
end
def read_only_transaction project_id:, instance_id:, database_id:
# [START spanner_read_only_transaction]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
spanner = Google::Cloud::Spanner.new project: project_id
client = spanner.client instance_id, database_id
client.snapshot do |snapshot|
snapshot.execute("SELECT SingerId, AlbumId, AlbumTitle FROM Albums").rows.each do |row|
puts "#{row[:AlbumId]} #{row[:AlbumTitle]} #{row[:SingerId]}"
end
# Even if changes occur in-between the reads, the transaction ensures that
# both return the same data.
snapshot.read("Albums", [:AlbumId, :AlbumTitle, :SingerId]).rows.each do |row|
puts "#{row[:AlbumId]} #{row[:AlbumTitle]} #{row[:SingerId]}"
end
end
# [END spanner_read_only_transaction]
end
def spanner_batch_client project_id:, instance_id:, database_id:
# [START spanner_batch_client]
# project_id = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"
# database_id = "Your Spanner database ID"
require "google/cloud/spanner"
# Prepare a thread pool with number of processors
processor_count = Concurrent.processor_count
thread_pool = Concurrent::FixedThreadPool.new processor_count
# Prepare AtomicFixnum to count total records using multiple threads
total_records = Concurrent::AtomicFixnum.new
# Create a new Spanner batch client
spanner = Google::Cloud::Spanner.new project: project_id
batch_client = spanner.batch_client instance_id, database_id
# Get a strong timestamp bound batch_snapshot
batch_snapshot = batch_client.batch_snapshot strong: true
# Get partitions for specified query
partitions = batch_snapshot.partition_query "SELECT SingerId, FirstName, LastName FROM Singers"
total_partitions = partitions.size
# Enqueue a new thread pool job
partitions.each_with_index do |partition, partition_index|
thread_pool.post do
# Increment total_records per new row
batch_snapshot.execute_partition(partition).rows.each do |row|
total_records.increment
end
end
end
# Wait for queued jobs to complete
thread_pool.shutdown
thread_pool.wait_for_termination
# Close the client connection and release resources.
batch_snapshot.close
# Collect statistics for batch query
average_records_per_partition = 0.0
if total_partitions != 0
average_records_per_partition = total_records.value.to_f / total_partitions.to_f
end
puts "Total Partitions: #{total_partitions}"
puts "Total Records: #{total_records.value}"
puts "Average records per Partition: #{average_records_per_partition}"
# [END spanner_batch_client]
end
def usage
puts <<-usage
Usage: bundle exec ruby spanner_samples.rb [command] [arguments]
Commands:
create_database <instance_id> <database_id> Create Database
insert_data <instance_id> <database_id> Insert Data
query_data <instance_id> <database_id> Query Data
read_data <instance_id> <database_id> Read Data
read_stale_data <instance_id> <database_id> Read Stale Data
create_index <instance_id> <database_id> Create Index
create_storing_index <instance_id> <database_id> Create Storing Index
add_column <instance_id> <database_id> Add Column
update_data <instance_id> <database_id> Update Data
query_data_with_new_column <instance_id> <database_id> Query Data with New Column
query_data_with_index <instance_id> <database_id> <start_title> <end_title> Query Data with Index
read_write_transaction <instance_id> <database_id> Read-Write Transaction
read_data_with_index <instance_id> <database_id> Read Data with Index
read_data_with_storing_index <instance_id> <database_id> Read Data with Storing Index
read_only_transaction <instance_id> <database_id> Read-Only Transaction
spanner_batch_client <instance_id> <database_id> Use Spanner batch query with a thread pool
Environment variables:
GOOGLE_CLOUD_PROJECT must be set to your Google Cloud project ID
usage
end
def run_sample arguments
command = arguments.shift
instance_id = arguments.shift
database_id = arguments.shift
project_id = ENV["GOOGLE_CLOUD_PROJECT"]
commands = [
"create_database", "insert_data", "query_data", "read_data", "read_stale_data",
"create_index", "create_storing_index", "add_column", "update_data",
"query_data_with_new_column", "read_write_transaction", "query_data_with_index",
"read_data_with_index", "read_data_with_storing_index", "read_only_transaction",
"spanner_batch_client"
]
if command.eql?("query_data_with_index") && instance_id && database_id && arguments.size >= 2
query_data_with_index project_id: project_id,
instance_id: instance_id,
database_id: database_id,
start_title: arguments.shift,
end_title: arguments.shift
elsif commands.include?(command) && instance_id && database_id
send command, project_id: project_id,
instance_id: instance_id,
database_id: database_id
else
usage
end
end
if __FILE__ == $PROGRAM_NAME
run_sample ARGV
end
| 35.132231
| 107
| 0.714244
|
dd8643daca953739d4e708cb228b9df1d5b26f6b
| 15,483
|
java
|
Java
|
gremlin-test/src/main/java/com/tinkerpop/gremlin/structure/SerializationTest.java
|
davidcrouch/tinkerpop3
|
4a2f05516f9fdfb3fa7d9079f0cc79e365a8282b
|
[
"Apache-2.0"
] | null | null | null |
gremlin-test/src/main/java/com/tinkerpop/gremlin/structure/SerializationTest.java
|
davidcrouch/tinkerpop3
|
4a2f05516f9fdfb3fa7d9079f0cc79e365a8282b
|
[
"Apache-2.0"
] | null | null | null |
gremlin-test/src/main/java/com/tinkerpop/gremlin/structure/SerializationTest.java
|
davidcrouch/tinkerpop3
|
4a2f05516f9fdfb3fa7d9079f0cc79e365a8282b
|
[
"Apache-2.0"
] | null | null | null |
package com.tinkerpop.gremlin.structure;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tinkerpop.gremlin.AbstractGremlinTest;
import com.tinkerpop.gremlin.LoadGraphWith;
import com.tinkerpop.gremlin.process.Path;
import com.tinkerpop.gremlin.structure.io.graphson.GraphSONTokens;
import com.tinkerpop.gremlin.structure.io.kryo.KryoMapper;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import java.io.ByteArrayOutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.*;
/**
* Serialization tests that occur at a lower level than IO. Note that there is no need to test GraphML here as
* it is not a format that can be used for generalized serialization (i.e. it only serializes an entire graph).
*
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
@RunWith(Enclosed.class)
public class SerializationTest {
public static class KryoTest extends AbstractGremlinTest {
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializeVertexAsDetached() throws Exception {
final KryoMapper kryoMapper = g.io().kryoMapper().create();
final Kryo kryo = kryoMapper.createMapper();
final Vertex v = g.V(convertToVertexId("marko")).next();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
final Output output = new Output(stream);
kryo.writeObject(output, v);
output.close();
final Input input = new Input(stream.toByteArray());
final Vertex detached = kryo.readObject(input, Vertex.class);
input.close();
assertNotNull(detached);
assertEquals(v.label(), detached.label());
assertEquals(v.id(), detached.id());
assertEquals(v.value("name").toString(), detached.value("name"));
assertEquals((Integer) v.value("age"), detached.value("age"));
}
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializeEdgeAsDetached() throws Exception {
final KryoMapper kryoMapper = g.io().kryoMapper().create();
final Kryo kryo = kryoMapper.createMapper();
final Edge e = g.E(convertToEdgeId("marko", "knows", "vadas")).next();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
final Output output = new Output(stream);
kryo.writeObject(output, e);
output.close();
final Input input = new Input(stream.toByteArray());
final Edge detached = kryo.readObject(input, Edge.class);
assertNotNull(detached);
assertEquals(e.label(), detached.label());
assertEquals(e.id(), detached.id());
assertEquals((Double) e.value("weight"), detached.value("weight"));
}
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializePropertyAsDetached() throws Exception {
final KryoMapper kryoMapper = g.io().kryoMapper().create();
final Kryo kryo = kryoMapper.createMapper();
final Property p = g.E(convertToEdgeId("marko", "knows", "vadas")).next().property("weight");
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
final Output output = new Output(stream);
kryo.writeObject(output, p);
output.close();
final Input input = new Input(stream.toByteArray());
final Property detached = kryo.readObject(input, Property.class);
assertNotNull(detached);
assertEquals(p.key(), detached.key());
assertEquals(p.value(), detached.value());
}
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializeVertexPropertyAsDetached() throws Exception {
final KryoMapper kryoMapper = g.io().kryoMapper().create();
final Kryo kryo = kryoMapper.createMapper();
final VertexProperty vp = g.V(convertToVertexId("marko")).next().property("name");
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
final Output output = new Output(stream);
kryo.writeObject(output, vp);
output.close();
final Input input = new Input(stream.toByteArray());
final VertexProperty detached = kryo.readObject(input, VertexProperty.class);
input.close();
assertNotNull(detached);
assertEquals(vp.label(), detached.label());
assertEquals(vp.id(), detached.id());
assertEquals(vp.value(), detached.value());
}
@Test
@LoadGraphWith(LoadGraphWith.GraphData.CREW)
public void shouldSerializeVertexPropertyWithPropertiesAsDetached() throws Exception {
final KryoMapper kryoMapper = g.io().kryoMapper().create();
final Kryo kryo = kryoMapper.createMapper();
final VertexProperty vp = g.V(convertToVertexId("marko")).next().iterators().propertyIterator("location").next();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
final Output output = new Output(stream);
kryo.writeObject(output, vp);
output.close();
final Input input = new Input(stream.toByteArray());
final VertexProperty detached = kryo.readObject(input, VertexProperty.class);
input.close();
assertNotNull(detached);
assertEquals(vp.label(), detached.label());
assertEquals(vp.id(), detached.id());
assertEquals(vp.value(), detached.value());
assertEquals(vp.iterators().propertyIterator("startTime").next().value(), detached.iterators().propertyIterator("startTime").next().value());
assertEquals(vp.iterators().propertyIterator("startTime").next().key(), detached.iterators().propertyIterator("startTime").next().key());
assertEquals(vp.iterators().propertyIterator("endTime").next().value(), detached.iterators().propertyIterator("endTime").next().value());
assertEquals(vp.iterators().propertyIterator("endTime").next().key(), detached.iterators().propertyIterator("endTime").next().key());
}
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializePathAsDetached() throws Exception {
final KryoMapper kryoMapper = g.io().kryoMapper().create();
final Kryo kryo = kryoMapper.createMapper();
final Path p = g.V(convertToVertexId("marko")).as("a").outE().as("b").inV().as("c").path().next();
final ByteArrayOutputStream stream = new ByteArrayOutputStream();
final Output output = new Output(stream);
kryo.writeObject(output, p);
output.close();
final Input input = new Input(stream.toByteArray());
final Path detached = kryo.readObject(input, Path.class);
input.close();
assertNotNull(detached);
assertEquals(p.labels().size(), detached.labels().size());
assertEquals(p.labels().get(0).size(), detached.labels().get(0).size());
assertEquals(p.labels().get(1).size(), detached.labels().get(1).size());
assertEquals(p.labels().get(2).size(), detached.labels().get(2).size());
assertTrue(p.labels().stream().flatMap(Collection::stream).allMatch(detached::hasLabel));
final Vertex vOut = p.get("a");
final Vertex detachedVOut = detached.get("a");
assertEquals(vOut.label(), detachedVOut.label());
assertEquals(vOut.id(), detachedVOut.id());
// this is a SimpleTraverser so no properties are present in detachment
assertFalse(detachedVOut.iterators().propertyIterator().hasNext());
final Edge e = p.get("b");
final Edge detachedE = detached.get("b");
assertEquals(e.label(), detachedE.label());
assertEquals(e.id(), detachedE.id());
// this is a SimpleTraverser so no properties are present in detachment
assertFalse(detachedE.iterators().propertyIterator().hasNext());
final Vertex vIn = p.get("c");
final Vertex detachedVIn = detached.get("c");
assertEquals(vIn.label(), detachedVIn.label());
assertEquals(vIn.id(), detachedVIn.id());
// this is a SimpleTraverser so no properties are present in detachment
assertFalse(detachedVIn.iterators().propertyIterator().hasNext());
}
}
public static class GraphSONTest extends AbstractGremlinTest {
private final TypeReference<HashMap<String, Object>> mapTypeReference = new TypeReference<HashMap<String, Object>>() {
};
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializeVertex() throws Exception {
final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper();
final Vertex v = g.V(convertToVertexId("marko")).next();
final String json = mapper.writeValueAsString(v);
final Map<String, Object> m = mapper.readValue(json, mapTypeReference);
assertEquals(GraphSONTokens.VERTEX, m.get(GraphSONTokens.TYPE));
assertEquals(v.label(), m.get(GraphSONTokens.LABEL));
assertNotNull(m.get(GraphSONTokens.ID));
assertEquals(v.value("name").toString(), ((Map) ((List) ((Map) m.get(GraphSONTokens.PROPERTIES)).get("name")).get(0)).get(GraphSONTokens.VALUE));
assertEquals((Integer) v.value("age"), ((Map) ((List) ((Map) m.get(GraphSONTokens.PROPERTIES)).get("age")).get(0)).get(GraphSONTokens.VALUE));
}
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializeEdge() throws Exception {
final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper();
final Edge e = g.E(convertToEdgeId("marko", "knows", "vadas")).next();
final String json = mapper.writeValueAsString(e);
final Map<String, Object> m = mapper.readValue(json, mapTypeReference);
assertEquals(GraphSONTokens.EDGE, m.get(GraphSONTokens.TYPE));
assertEquals(e.label(), m.get(GraphSONTokens.LABEL));
assertNotNull(m.get(GraphSONTokens.ID));
assertEquals((Double) e.value("weight"), ((Map) m.get(GraphSONTokens.PROPERTIES)).get("weight"));
}
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializeProperty() throws Exception {
final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper();
final Property p = g.E(convertToEdgeId("marko", "knows", "vadas")).next().property("weight");
final String json = mapper.writeValueAsString(p);
final Map<String, Object> m = mapper.readValue(json, mapTypeReference);
// todo: decide if this should really include "key" and "type" since Property is a first class citizen
assertEquals(p.value(), m.get(GraphSONTokens.VALUE));
}
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializeVertexProperty() throws Exception {
final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper();
final VertexProperty vp = g.V(convertToVertexId("marko")).next().property("name");
final String json = mapper.writeValueAsString(vp);
final Map<String, Object> m = mapper.readValue(json, mapTypeReference);
// todo: should we have "type" here too?
assertEquals(vp.label(), m.get(GraphSONTokens.LABEL));
assertNotNull(m.get(GraphSONTokens.ID));
assertEquals(vp.value(), m.get(GraphSONTokens.VALUE));
}
@Test
@LoadGraphWith(LoadGraphWith.GraphData.CREW)
public void shouldSerializeVertexPropertyWithProperties() throws Exception {
final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper();
final VertexProperty vp = g.V(convertToVertexId("marko")).next().iterators().propertyIterator("location").next();
final String json = mapper.writeValueAsString(vp);
final Map<String, Object> m = mapper.readValue(json, mapTypeReference);
// todo: should we have "type" here too?
assertEquals(vp.label(), m.get(GraphSONTokens.LABEL));
assertNotNull(m.get(GraphSONTokens.ID));
assertEquals(vp.value(), m.get(GraphSONTokens.VALUE));
assertEquals(vp.iterators().propertyIterator("startTime").next().value(), ((Map) m.get(GraphSONTokens.PROPERTIES)).get("startTime"));
assertEquals(vp.iterators().propertyIterator("endTime").next().value(), ((Map) m.get(GraphSONTokens.PROPERTIES)).get("endTime"));
}
@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldSerializePath() throws Exception {
final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper();
final Path p = g.V(convertToVertexId("marko")).as("a").outE().as("b").inV().as("c").path().next();
final String json = mapper.writeValueAsString(p);
final Map<String, Object> m = mapper.readValue(json, mapTypeReference);
// todo: path is not asserted yet...
/*
assertEquals(p.labels().size(), detached.labels().size());
assertEquals(p.labels().get(0).size(), detached.labels().get(0).size());
assertEquals(p.labels().get(1).size(), detached.labels().get(1).size());
assertEquals(p.labels().get(2).size(), detached.labels().get(2).size());
assertTrue(p.labels().stream().flatMap(Collection::stream).allMatch(detached::hasLabel));
final Vertex vOut = p.get("a");
final Vertex detachedVOut = detached.get("a");
assertEquals(vOut.label(), detachedVOut.label());
assertEquals(vOut.id(), detachedVOut.id());
// this is a SimpleTraverser so no properties are present in detachment
assertFalse(detachedVOut.iterators().propertyIterator().hasNext());
final Edge e = p.get("b");
final Edge detachedE = detached.get("b");
assertEquals(e.label(), detachedE.label());
assertEquals(e.id(), detachedE.id());
// this is a SimpleTraverser so no properties are present in detachment
assertFalse(detachedE.iterators().propertyIterator().hasNext());
final Vertex vIn = p.get("c");
final Vertex detachedVIn = detached.get("c");
assertEquals(vIn.label(), detachedVIn.label());
assertEquals(vIn.id(), detachedVIn.id());
// this is a SimpleTraverser so no properties are present in detachment
assertFalse(detachedVIn.iterators().propertyIterator().hasNext());
*/
}
}
}
| 51.268212
| 157
| 0.636375
|
6d9e2b93fad5bd5057bb00e4f50c97c8e3a0afb3
| 1,100
|
c
|
C
|
baseboard/brya/cbi.c
|
coreboot/chrome-ec
|
61044db105bc854167efe83815acb3fcb55deb85
|
[
"BSD-3-Clause"
] | 46
|
2017-02-12T20:48:45.000Z
|
2022-03-01T15:53:39.000Z
|
baseboard/brya/cbi.c
|
coreboot/chrome-ec
|
61044db105bc854167efe83815acb3fcb55deb85
|
[
"BSD-3-Clause"
] | null | null | null |
baseboard/brya/cbi.c
|
coreboot/chrome-ec
|
61044db105bc854167efe83815acb3fcb55deb85
|
[
"BSD-3-Clause"
] | 46
|
2016-02-07T18:43:27.000Z
|
2022-01-03T02:30:51.000Z
|
/* Copyright 2021 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <stdint.h>
#include "console.h"
#include "common.h"
#include "cros_board_info.h"
#include "hooks.h"
#define CPRINTS(format, args...) cprints(CC_CHIPSET, format, ## args)
#define CPRINTF(format, args...) cprintf(CC_CHIPSET, format, ## args)
static uint8_t board_id;
uint8_t get_board_id(void)
{
return board_id;
}
__overridable void board_cbi_init(void)
{
}
__overridable void board_init_fw_config(void)
{
}
/*
* Read CBI from I2C EEPROM and initialize variables for board variants.
*/
static void cbi_init(void)
{
uint32_t cbi_val;
/* Board ID */
if (cbi_get_board_version(&cbi_val) != EC_SUCCESS ||
cbi_val > UINT8_MAX)
CPRINTS("CBI: Read Board ID failed");
else
board_id = cbi_val;
CPRINTS("Board ID: %d", board_id);
board_init_fw_config();
/* Allow the board project to make runtime changes based on CBI data */
board_cbi_init();
}
DECLARE_HOOK(HOOK_INIT, cbi_init, HOOK_PRIO_FIRST);
| 20.754717
| 73
| 0.726364
|
0d397997e9ddd41a768b8eaf17fd8c80565d436a
| 773
|
rb
|
Ruby
|
railstube/app/controllers/comments_controller.rb
|
S-H-GAMELINKS/MyFirstRails
|
c53b68a43d4d1d2a6825f4c2c2f64b523a40562a
|
[
"MIT"
] | 18
|
2019-02-04T16:44:05.000Z
|
2022-03-13T12:01:37.000Z
|
railstube/app/controllers/comments_controller.rb
|
S-H-GAMELINKS/MyFirstRails
|
c53b68a43d4d1d2a6825f4c2c2f64b523a40562a
|
[
"MIT"
] | 78
|
2019-02-04T01:14:39.000Z
|
2019-04-12T04:54:49.000Z
|
railstube/app/controllers/comments_controller.rb
|
S-H-GAMELINKS/MyFirstRails
|
c53b68a43d4d1d2a6825f4c2c2f64b523a40562a
|
[
"MIT"
] | 4
|
2019-03-08T08:03:02.000Z
|
2020-12-21T00:11:00.000Z
|
class CommentsController < ApplicationController
before_action :set_movie
before_action :check_login, only: [:destroy]
def create
@comment = @movie.comments.create! comments_params
@comment.update(:user_id => current_user.id, :score => params[:score])
redirect_to @movie
end
def destroy
@movie.comments.destroy params[:id]
redirect_to @movie
end
private
def set_movie
@movie = Movie.find(params[:movie_id])
end
def check_login
redirect_to :root if current_user == nil || @movie.comments.find(params[:id]).user_id != current_user.id
end
def comments_params
params.required(:comment).permit(:content, :auther)
end
end
| 27.607143
| 117
| 0.628719
|
b06cd80d0661a4fad14051b55b76c6e62676ec9b
| 134
|
py
|
Python
|
utilities/ray.py
|
fietensen/raytracer
|
856e9dfa39d1c7fd77fd2409ce19a244af6e479c
|
[
"MIT"
] | null | null | null |
utilities/ray.py
|
fietensen/raytracer
|
856e9dfa39d1c7fd77fd2409ce19a244af6e479c
|
[
"MIT"
] | null | null | null |
utilities/ray.py
|
fietensen/raytracer
|
856e9dfa39d1c7fd77fd2409ce19a244af6e479c
|
[
"MIT"
] | null | null | null |
class Ray:
def __init__(self, origin, direction):
self.origin = origin
self.direction = direction.normalize()
| 26.8
| 47
| 0.634328
|
f5fc86c26d74840965001077017abf68fcb67144
| 64
|
css
|
CSS
|
packages/map-creator/src/App.module.css
|
yongcycchen/prisel
|
d7f1aec270f63b684f12639f726d383a4e408a3d
|
[
"MIT"
] | 5
|
2019-01-01T03:41:36.000Z
|
2019-07-08T17:55:15.000Z
|
packages/map-creator/src/App.module.css
|
yongcycchen/prisel
|
d7f1aec270f63b684f12639f726d383a4e408a3d
|
[
"MIT"
] | 41
|
2018-05-14T00:49:38.000Z
|
2018-12-25T19:46:22.000Z
|
packages/map-creator/src/App.module.css
|
yongcycchen/prisel
|
d7f1aec270f63b684f12639f726d383a4e408a3d
|
[
"MIT"
] | 1
|
2021-03-22T05:36:46.000Z
|
2021-03-22T05:36:46.000Z
|
.propertyPanel {
width: 400px;
background: lightgrey;
}
| 12.8
| 26
| 0.65625
|
ca345d655c3b480af6405500ddfe2e6628ac8e5e
| 526
|
dart
|
Dart
|
lib/interfaces/general_screens/splash_screen/controllers/splash_ui_controller.dart
|
ChrisChV/Flutter-Project-Template
|
2f597160fdd87b1367f0c2bc4bc6a590ecc5da36
|
[
"MIT"
] | null | null | null |
lib/interfaces/general_screens/splash_screen/controllers/splash_ui_controller.dart
|
ChrisChV/Flutter-Project-Template
|
2f597160fdd87b1367f0c2bc4bc6a590ecc5da36
|
[
"MIT"
] | 8
|
2020-04-29T20:52:29.000Z
|
2021-02-18T17:35:48.000Z
|
lib/interfaces/general_screens/splash_screen/controllers/splash_ui_controller.dart
|
ChrisChV/Flutter-Project-Template
|
2f597160fdd87b1367f0c2bc4bc6a590ecc5da36
|
[
"MIT"
] | null | null | null |
import 'package:flutter_project_template/routes/routingConstants.dart';
import 'package:flutter_project_template/view_models/controllers/AppUserController.dart';
import 'package:get/get.dart';
class SplashScreenController extends GetxController {
@override
void onReady() {
loadControllers();
super.onReady();
}
Future<void> loadControllers() async{
await Get.find<AppUserController>().initialVerification();
navigate();
}
void navigate(){
Get.offAllNamed(RouteNames.PrincipalRoute);
}
}
| 23.909091
| 89
| 0.752852
|
74262674e732d3a265926f025551da3a64786f7b
| 694
|
css
|
CSS
|
book-list.css
|
mizuki0127/proN-4Q
|
1957f6d65921893edb95e01a9c8e451b391ec803
|
[
"MIT"
] | null | null | null |
book-list.css
|
mizuki0127/proN-4Q
|
1957f6d65921893edb95e01a9c8e451b391ec803
|
[
"MIT"
] | null | null | null |
book-list.css
|
mizuki0127/proN-4Q
|
1957f6d65921893edb95e01a9c8e451b391ec803
|
[
"MIT"
] | null | null | null |
h1 {
font-size: 100px;
margin-top: 100px;
margin-left: 120px;
font-family: 'Shippori Mincho B1', serif;
color: #696969;
}
/* 検索エリア */
.search p {
margin-left: 140px;
font-size: 20px;
font-family: 'Shippori Mincho B1', serif;
color: #696969;
}
.search input {
margin-top: 20px;
margin-left: 160px;
}
/* 一覧エリア */
.booklist p {
margin-left: 140px;
margin-top: 80px;
font-size: 20px;
font-family: 'Shippori Mincho B1', serif;
color: #696969;
}
.booklist img {
width: 350px;
height: auto;
}
.booklist img.b1 {
margin-top: 50px;
margin-left: 140px;
margin-right: 10px;
}
.booklist img.b3{
margin-left: 10px;
}
| 16.926829
| 45
| 0.599424
|
da4b4e38b405aea2b106934a53c3eb78f521c33d
| 475
|
php
|
PHP
|
src/FiltrableServiceProvider.php
|
hmshafeeq/query-filter
|
5f7f3284de4a264e2f5b820651fb37ea5bc2bb07
|
[
"MIT"
] | 21
|
2018-09-26T16:13:51.000Z
|
2019-04-09T04:55:51.000Z
|
src/FiltrableServiceProvider.php
|
hmshafeeq/eloquent-filter
|
5f7f3284de4a264e2f5b820651fb37ea5bc2bb07
|
[
"MIT"
] | 2
|
2018-10-01T12:58:56.000Z
|
2018-10-05T07:09:06.000Z
|
src/FiltrableServiceProvider.php
|
hmshafeeq/query-filter
|
5f7f3284de4a264e2f5b820651fb37ea5bc2bb07
|
[
"MIT"
] | 2
|
2018-10-03T05:38:29.000Z
|
2019-04-16T02:44:17.000Z
|
<?php
namespace VelitSol\EloquentFilter;
use Illuminate\Support\ServiceProvider;
class FiltrableServiceProvider extends ServiceProvider
{
public function boot()
{
$this->publishes([
__DIR__.'/../config/filterable.php' => config_path('filterable.php'),
], 'config');
}
public function register()
{
$this->mergeConfigFrom(
__DIR__.'/../config/filterable.php',
'filterable'
);
}
}
| 19.791667
| 81
| 0.597895
|
464f482af5f326f654544090f215484e97c56b04
| 2,133
|
php
|
PHP
|
resources/views/admin/default/_shared/topMenubar.blade.php
|
tumao/myoa2.0
|
322b0787716859745469751f1513aa9fc599f633
|
[
"MIT"
] | null | null | null |
resources/views/admin/default/_shared/topMenubar.blade.php
|
tumao/myoa2.0
|
322b0787716859745469751f1513aa9fc599f633
|
[
"MIT"
] | null | null | null |
resources/views/admin/default/_shared/topMenubar.blade.php
|
tumao/myoa2.0
|
322b0787716859745469751f1513aa9fc599f633
|
[
"MIT"
] | null | null | null |
<!-- topbar starts -->
<div class="navbar navbar-default" role="navigation">
<div class="navbar-inner">
<button type="button" class="navbar-toggle pull-left animated flip">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"> <img alt="Charisma Logo" src="/default/framework/img/logo20.png" class="hidden-xs"/>
<span>后台管理</span></a>
<!-- user dropdown starts -->
<div class="btn-group pull-right">
<button class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<i class="glyphicon glyphicon-user"></i><span class="hidden-sm hidden-xs"> 管理员</span>
<span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="/admin/user/self">个人详情</a></li>
<li class="divider"></li>
<li><a href="/admin/logout">退出</a></li>
</ul>
</div>
<!-- user dropdown ends -->
<ul class="collapse navbar-collapse nav navbar-nav top-menu">
@foreach( $menu['main_menu'] as $item)
<li @if($item['active']) class="active" @endif> <a href="{{$item['path']}}"><i class="{{$item['icon']}}"></i>{{$item['name']}}</a></li>
<!-- <li class="active"><a href="#"><i class="glyphicon glyphicon-sound-5-1"></i> 仪表盘</a></li>
<li><a href="#"><i class="glyphicon glyphicon-user"></i> 用户</a></li>
<li><a href="#"><i class="glyphicon glyphicon-tint"></i> 资源</a></li>
<li><a href="#"><i class="glyphicon glyphicon-cog"></i> 配置</a></li> -->
@endforeach
</ul>
<!-- <form class="navbar-form navbar-right" role="search">
<div class="form-group">
<input type="text" class="form-control" placeholder="请输入关键字" />
</div>
<button type="subbmit" class="btn btn-default" >搜索</button>
</form> -->
</div>
</div>
<!-- topbar ends -->
| 48.477273
| 147
| 0.526489
|
8bd449e4c39190fe35c5d2736f2dcc3f213816c1
| 2,138
|
swift
|
Swift
|
Desktop Cleaner/ShortcutField.swift
|
Kyome22/Desktop-Cleaner
|
c4d101f5f8e65f47a3ce3e93a92c7194af649368
|
[
"MIT"
] | 3
|
2019-02-06T08:03:09.000Z
|
2019-06-16T13:38:44.000Z
|
Desktop Cleaner/ShortcutField.swift
|
Kyome22/Desktop-Cleaner
|
c4d101f5f8e65f47a3ce3e93a92c7194af649368
|
[
"MIT"
] | null | null | null |
Desktop Cleaner/ShortcutField.swift
|
Kyome22/Desktop-Cleaner
|
c4d101f5f8e65f47a3ce3e93a92c7194af649368
|
[
"MIT"
] | null | null | null |
//
// ShortcutField.swift
// Desktop Cleaner
//
// Created by Takuto Nakamura on 2019/02/02.
// Copyright © 2019 Takuto Nakamura. All rights reserved.
//
import Cocoa
protocol ShortcutFieldDelegate: NSTextFieldDelegate {
func didPressKey(event: NSEvent)
func didChangeFlag(event: NSEvent)
}
class ShortcutField: NSTextField {
var delegate_: ShortcutFieldDelegate?
var monitors = [Any?]()
required init?(coder: NSCoder) {
super.init(coder: coder)
self.placeholderString = "Type Shortcut"
self.isBordered = true
self.isSelectable = false
self.wantsLayer = true
self.layer?.borderColor = NSColor(hex: "B0BEC5").cgColor
self.layer?.borderWidth = 1.0
self.layer?.cornerRadius = 4.0
}
override func becomeFirstResponder() -> Bool {
if monitors.count == 0 {
monitors.append(NSEvent.addLocalMonitorForEvents(matching: NSEvent.EventTypeMask.keyDown) { (event) -> NSEvent? in
self.delegate_?.didPressKey(event: event)
return event
})
monitors.append(NSEvent.addLocalMonitorForEvents(matching: NSEvent.EventTypeMask.flagsChanged) { (event) -> NSEvent? in
self.delegate_?.didChangeFlag(event: event)
return event
})
}
return true
}
override func performKeyEquivalent(with event: NSEvent) -> Bool {
return true
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
public func removeMonitor() {
for monitor in monitors {
NSEvent.removeMonitor(monitor!)
}
monitors.removeAll()
}
override func resetCursorRects() {
let rectL = NSRect(x: 0, y: 0, width: bounds.width - 25, height: 25)
let cursorL: NSCursor = NSCursor.iBeam
addCursorRect(rectL, cursor: cursorL)
let rectR = NSRect(x: bounds.width - 25, y: 0, width: 25, height: 25)
let cursorR: NSCursor = NSCursor.pointingHand
addCursorRect(rectR, cursor: cursorR)
}
}
| 29.694444
| 131
| 0.615061
|
4b9572f3d61de9388831bfdd40a78ae7f07c14db
| 3,409
|
hpp
|
C++
|
external/boost_1_60_0/qsboost/smart_ptr/detail/sp_counted_base.hpp
|
wouterboomsma/quickstep
|
a33447562eca1350c626883f21c68125bd9f776c
|
[
"MIT"
] | 1
|
2019-06-27T17:54:13.000Z
|
2019-06-27T17:54:13.000Z
|
external/boost_1_60_0/qsboost/smart_ptr/detail/sp_counted_base.hpp
|
wouterboomsma/quickstep
|
a33447562eca1350c626883f21c68125bd9f776c
|
[
"MIT"
] | null | null | null |
external/boost_1_60_0/qsboost/smart_ptr/detail/sp_counted_base.hpp
|
wouterboomsma/quickstep
|
a33447562eca1350c626883f21c68125bd9f776c
|
[
"MIT"
] | null | null | null |
#ifndef QSBOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_HPP_INCLUDED
#define QSBOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_HPP_INCLUDED
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif
//
// detail/sp_counted_base.hpp
//
// Copyright 2005-2013 Peter Dimov
//
// Distributed under 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)
//
#include <qsboost/config.hpp>
#include <qsboost/smart_ptr/detail/sp_has_sync.hpp>
#if defined( __clang__ ) && defined( __has_extension )
# if __has_extension( __c_atomic__ )
# define QSBOOST_SP_HAS_CLANG_C11_ATOMICS
# endif
#endif
#if defined( QSBOOST_SP_DISABLE_THREADS )
# include <qsboost/smart_ptr/detail/sp_counted_base_nt.hpp>
#elif defined( QSBOOST_SP_USE_STD_ATOMIC )
# include <qsboost/smart_ptr/detail/sp_counted_base_std_atomic.hpp>
#elif defined( QSBOOST_SP_USE_SPINLOCK )
# include <qsboost/smart_ptr/detail/sp_counted_base_spin.hpp>
#elif defined( QSBOOST_SP_USE_PTHREADS )
# include <qsboost/smart_ptr/detail/sp_counted_base_pt.hpp>
#elif defined( QSBOOST_DISABLE_THREADS ) && !defined( QSBOOST_SP_ENABLE_THREADS ) && !defined( QSBOOST_DISABLE_WIN32 )
# include <qsboost/smart_ptr/detail/sp_counted_base_nt.hpp>
#elif defined( QSBOOST_SP_HAS_CLANG_C11_ATOMICS )
# include <qsboost/smart_ptr/detail/sp_counted_base_clang.hpp>
#elif defined( __SNC__ )
# include <qsboost/smart_ptr/detail/sp_counted_base_snc_ps3.hpp>
#elif defined( __GNUC__ ) && ( defined( __i386__ ) || defined( __x86_64__ ) ) && !defined(__PATHSCALE__)
# include <qsboost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp>
#elif defined(__HP_aCC) && defined(__ia64)
# include <qsboost/smart_ptr/detail/sp_counted_base_acc_ia64.hpp>
#elif defined( __GNUC__ ) && defined( __ia64__ ) && !defined( __INTEL_COMPILER ) && !defined(__PATHSCALE__)
# include <qsboost/smart_ptr/detail/sp_counted_base_gcc_ia64.hpp>
#elif defined( __IBMCPP__ ) && defined( __powerpc )
# include <qsboost/smart_ptr/detail/sp_counted_base_vacpp_ppc.hpp>
#elif defined( __MWERKS__ ) && defined( __POWERPC__ )
# include <qsboost/smart_ptr/detail/sp_counted_base_cw_ppc.hpp>
#elif defined( __GNUC__ ) && ( defined( __powerpc__ ) || defined( __ppc__ ) || defined( __ppc ) ) && !defined(__PATHSCALE__) && !defined( _AIX )
# include <qsboost/smart_ptr/detail/sp_counted_base_gcc_ppc.hpp>
#elif defined( __GNUC__ ) && ( defined( __mips__ ) || defined( _mips ) ) && !defined(__PATHSCALE__)
# include <qsboost/smart_ptr/detail/sp_counted_base_gcc_mips.hpp>
#elif defined( QSBOOST_SP_HAS_SYNC )
# include <qsboost/smart_ptr/detail/sp_counted_base_sync.hpp>
#elif defined(__GNUC__) && ( defined( __sparcv9 ) || ( defined( __sparcv8 ) && ( __GNUC__ * 100 + __GNUC_MINOR__ >= 402 ) ) )
# include <qsboost/smart_ptr/detail/sp_counted_base_gcc_sparc.hpp>
#elif defined( WIN32 ) || defined( _WIN32 ) || defined( __WIN32__ ) || defined(__CYGWIN__)
# include <qsboost/smart_ptr/detail/sp_counted_base_w32.hpp>
#elif defined( _AIX )
# include <qsboost/smart_ptr/detail/sp_counted_base_aix.hpp>
#elif !defined( QSBOOST_HAS_THREADS )
# include <qsboost/smart_ptr/detail/sp_counted_base_nt.hpp>
#else
# include <qsboost/smart_ptr/detail/sp_counted_base_spin.hpp>
#endif
#undef QSBOOST_SP_HAS_CLANG_C11_ATOMICS
#endif // #ifndef BOOST_SMART_PTR_DETAIL_SP_COUNTED_BASE_HPP_INCLUDED
| 36.265957
| 144
| 0.779114
|
006be26685bdcbd1e9f558733d8a10a56dc1ef65
| 60
|
sql
|
SQL
|
src/OrdersCollector/db/updates/20160806-2251.sql
|
jmansar/orders-collector
|
1ede930c442b252112c22bba0686f865a6331ff5
|
[
"MIT"
] | null | null | null |
src/OrdersCollector/db/updates/20160806-2251.sql
|
jmansar/orders-collector
|
1ede930c442b252112c22bba0686f865a6331ff5
|
[
"MIT"
] | 4
|
2018-08-04T13:58:11.000Z
|
2018-08-04T17:53:30.000Z
|
src/OrdersCollector/db/updates/20160806-2251.sql
|
jmansar/orders-collector
|
1ede930c442b252112c22bba0686f865a6331ff5
|
[
"MIT"
] | null | null | null |
alter table OrderItems
add AuditInfo_InvokedByName text null
| 30
| 37
| 0.9
|
df7b0345e9662267c85a1454cdb911162dd6c5e4
| 1,344
|
cs
|
C#
|
SpaceSimulator/Rendering/Plot/PlotHelpers.cs
|
svenslaggare/SpaceSimulator.NET
|
20088244277b2983915da400f346083a5f940d58
|
[
"MIT"
] | 4
|
2017-04-23T17:22:06.000Z
|
2020-08-26T08:11:05.000Z
|
SpaceSimulator/Rendering/Plot/PlotHelpers.cs
|
svenslaggare/SpaceSimulator.NET
|
20088244277b2983915da400f346083a5f940d58
|
[
"MIT"
] | null | null | null |
SpaceSimulator/Rendering/Plot/PlotHelpers.cs
|
svenslaggare/SpaceSimulator.NET
|
20088244277b2983915da400f346083a5f940d58
|
[
"MIT"
] | 1
|
2022-01-29T12:45:47.000Z
|
2022-01-29T12:45:47.000Z
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharpDX;
using SpaceSimulator.Helpers;
namespace SpaceSimulator.Rendering.Plot
{
/// <summary>
/// Contains helper methods for plots
/// </summary>
public static class PlotHelpers
{
/// <summary>
/// Splits the given values into parts
/// </summary>
/// <param name="values">The values</param>
/// <param name="splitPart">Determines when parts should be split</param>
public static IEnumerable<IList<Vector2>> SplitIntoParts(IList<Vector2> values, Func<Vector2, Vector2, bool> splitPart)
{
var i = 0;
while (i < values.Count)
{
var prev = values[i];
var end = values.Count;
for (int j = i + 1; j < values.Count; j++)
{
var value = values[j];
if (splitPart(prev, value))
{
end = j;
break;
}
prev = value;
}
//Console.WriteLine($"{i}-{end}");
yield return values.GetRange(i, end - i);
i += end - i;
}
}
}
}
| 28
| 127
| 0.482143
|
e28245600cb0a03c026e4a7a345a44501a75bac2
| 8,107
|
py
|
Python
|
pegasus_base/scripts/stocktake_script.py
|
protogarden/pegasus-mini
|
9918a2bb3ab94e374f54926de5c686d1d9a0d50e
|
[
"MIT"
] | null | null | null |
pegasus_base/scripts/stocktake_script.py
|
protogarden/pegasus-mini
|
9918a2bb3ab94e374f54926de5c686d1d9a0d50e
|
[
"MIT"
] | null | null | null |
pegasus_base/scripts/stocktake_script.py
|
protogarden/pegasus-mini
|
9918a2bb3ab94e374f54926de5c686d1d9a0d50e
|
[
"MIT"
] | null | null | null |
#!/bin/env python
import rospy
from geometry_msgs.msg import PoseStamped, PoseWithCovarianceStamped
from actionlib_msgs.msg import GoalStatusArray
from move_base_msgs.msg import MoveBaseActionGoal, MoveBaseActionResult, MoveBaseAction, MoveBaseGoal
import time
import actionlib
import tf
import tf2_ros
from tf.transformations import quaternion_from_euler
from std_msgs.msg import Int32
class StocktakeInterface():
def __init__(self):
self.status = 0
self.initial_position = [0,0,0]
self.undock_position = [0,-1.1, 3.14159]
self.dock_pos = [0.769, 0.232, 3.140] #done
self.pos_1 = [2.53,-3.5 ,0] #Start aisle 2
self.pos_2 = [27.865 ,-2.899,3.14] #End aisle 2
self.pos_3 = [2.131,-3.489, 1.741] #Back to start ailes 2
self.pos_4 = [2.131, 2.909, 0] #Start aisles 1
self.pos_5 = [24.810, 3.337, 3.14] #End aisles 1
self.pos_6 = [2.454, 2.89, -2.282] #Back to start ailes
self.no_action_cmd = 0
self.dock_cmd = 1
self.undock_cmd = 2
self.docking_result = 0 #1- Docking, #2 -Undocking,#3 - Docked, #4 - Undocked
self.driving_led = 1
self.charging_led = 2
self.docking_led = 3
self.finnish_charging = 4
self.startup_led = 5
self.off_led = 6
def undock(self):
print("Send udocking cmd")
self.dock_cmd_pub.publish(self.undock_cmd) #publish cmd
while self.docking_result != 2: #wait for result
self.rate.sleep()
self.dock_cmd_pub.publish(self.undock_cmd) #publish cmd
self.dock_cmd_pub.publish(self.no_action_cmd)
print("received feedback of undocking")
while self.docking_result != 4: #wait for result
self.rate.sleep()
print("received feedback of undocked")
def dock(self):
print("Send docking cmd")
self.dock_cmd_pub.publish(self.dock_cmd) #publish cmd
while self.docking_result != 1: #wait for result
self.rate.sleep()
self.dock_cmd_pub.publish(self.dock_cmd) #publish cmd
self.dock_cmd_pub.publish(self.no_action_cmd)
print("received feedback of docking")
while self.docking_result != 3: #wait for result
self.rate.sleep()
print("received feedback of docked")
def docking_callback(self, data):
self.docking_result = data.data
def goal_pose(self, goal_x, goal_y, goal_thetha):
goal = MoveBaseGoal()
goal.target_pose.header.frame_id = "map"
goal.target_pose.header.stamp = rospy.Time.now()
goal.target_pose.pose.position.x = goal_x
goal.target_pose.pose.position.y = goal_y
goal.target_pose.pose.position.z = 0
q = quaternion_from_euler(0.0, 0.0, goal_thetha)
goal.target_pose.pose.orientation.x = 0
goal.target_pose.pose.orientation.y = 0
goal.target_pose.pose.orientation.z = q[2]
goal.target_pose.pose.orientation.w = q[3]
self.client.send_goal(goal)
def estimate_pose(self, est_x, est_y, est_thetha):
pose_estimate_data = PoseWithCovarianceStamped()
pose_estimate_data.header.frame_id = 'map'
pose_estimate_data.header.stamp = rospy.Time.now()
pose_estimate_data.pose.pose.position.x = est_x
pose_estimate_data.pose.pose.position.y = est_y
pose_estimate_data.pose.pose.position.z = 0.0
q = quaternion_from_euler(0.0, 0.0, est_thetha)
pose_estimate_data.pose.pose.orientation.x = 0.0
pose_estimate_data.pose.pose.orientation.y = 0.0
pose_estimate_data.pose.pose.orientation.z = q[2]
pose_estimate_data.pose.pose.orientation.w = q[3]
pose_estimate_data.pose.covariance = [0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.06853892326654787]
self.pose_estimate_pub.publish(pose_estimate_data)
def run(self):
rospy.init_node('stocktake_cmd_node', anonymous=True)
self.pose_estimate_pub = rospy.Publisher('/initialpose', PoseWithCovarianceStamped, queue_size=5)
self.dock_cmd_pub = rospy.Publisher('/docking_cmd', Int32, queue_size=1)
self.led_cmd_pub = rospy.Publisher("led_cmd", Int32, queue_size=1)
rospy.Subscriber('/docking_result', Int32 , self.docking_callback)
self.rate = rospy.Rate(20)
self.client = actionlib.SimpleActionClient('move_base', MoveBaseAction)
self.client.wait_for_server()
self.estimate_pose(self.initial_position[0], self.initial_position[1], self.initial_position[2]) #Send initial Pose
while not rospy.is_shutdown():
self.led_cmd_pub.publish(self.driving_led)
time.sleep(2)
self.goal_pose(self.pos_1[0], self.pos_1[1], self.pos_1[2])
goal_state = self.client.get_state()
print("current_state", goal_state)
wait = self.client.wait_for_result()
goal_state = self.client.get_state()
result = self.client.get_result()
print("result",goal_state )
'''
self.goal_pose(self.pos_2[0], self.pos_2[1], self.pos_2[2])
goal_state = self.client.get_state()
print("current_state", goal_state)
wait = self.client.wait_for_result()
goal_state = self.client.get_state()
result = self.client.get_result()
print("result",goal_state )
self.goal_pose(self.pos_3[0], self.pos_3[1], self.pos_3[2])
goal_state = self.client.get_state()
print("current_state", goal_state)
wait = self.client.wait_for_result()
goal_state = self.client.get_state()
result = self.client.get_result()
print("result",goal_state )
'''
self.goal_pose(self.pos_4[0], self.pos_4[1], self.pos_4[2])
goal_state = self.client.get_state()
print("current_state", goal_state)
wait = self.client.wait_for_result()
goal_state = self.client.get_state()
result = self.client.get_result()
print("result",goal_state )
'''
self.goal_pose(self.pos_5[0], self.pos_5[1], self.pos_5[2])
goal_state = self.client.get_state()
print("current_state", goal_state)
wait = self.client.wait_for_result()
goal_state = self.client.get_state()
result = self.client.get_result()
print("result",goal_state )
self.goal_pose(self.pos_6[0], self.pos_6[1], self.pos_6[2])
goal_state = self.client.get_state()
print("current_state", goal_state)
wait = self.client.wait_for_result()
goal_state = self.client.get_state()
result = self.client.get_result()
print("result",goal_state )
'''
self.goal_pose(self.dock_pos[0], self.dock_pos[1], self.dock_pos[2])
goal_state = self.client.get_state()
print("current_state", goal_state)
wait = self.client.wait_for_result()
goal_state = self.client.get_state()
result = self.client.get_result()
print("result",goal_state )
time.sleep(1)
self.dock()
time.sleep(7)
self.undock()
self.rate.sleep()
break
if __name__ == '__main__':
st_interface = StocktakeInterface()
try:
st_interface.run()
except rospy.ROSInterruptException:
pass
| 32.955285
| 243
| 0.589614
|
54bf9b4c333c8923fc97af7381466124e81028ac
| 6,420
|
rb
|
Ruby
|
actionview/test/template/capture_helper_test.rb
|
Alwahsh/rails
|
0e7dfbe9a2ffd3ee885b0783b20ebe5fdd4f9eec
|
[
"MIT"
] | null | null | null |
actionview/test/template/capture_helper_test.rb
|
Alwahsh/rails
|
0e7dfbe9a2ffd3ee885b0783b20ebe5fdd4f9eec
|
[
"MIT"
] | 21
|
2020-03-20T21:46:02.000Z
|
2021-09-08T20:09:49.000Z
|
actionview/test/template/capture_helper_test.rb
|
Alwahsh/rails
|
0e7dfbe9a2ffd3ee885b0783b20ebe5fdd4f9eec
|
[
"MIT"
] | 1
|
2020-02-14T12:06:08.000Z
|
2020-02-14T12:06:08.000Z
|
require "abstract_unit"
class CaptureHelperTest < ActionView::TestCase
def setup
super
@av = ActionView::Base.new
@view_flow = ActionView::OutputFlow.new
end
def test_capture_captures_the_temporary_output_buffer_in_its_block
assert_nil @av.output_buffer
string = @av.capture do
@av.output_buffer << "foo"
@av.output_buffer << "bar"
end
assert_nil @av.output_buffer
assert_equal "foobar", string
end
def test_capture_captures_the_value_returned_by_the_block_if_the_temporary_buffer_is_blank
string = @av.capture("foo", "bar") do |a, b|
a + b
end
assert_equal "foobar", string
end
def test_capture_returns_nil_if_the_returned_value_is_not_a_string
assert_nil @av.capture { 1 }
end
def test_capture_escapes_html
string = @av.capture { "<em>bar</em>" }
assert_equal "<em>bar</em>", string
end
def test_capture_doesnt_escape_twice
string = @av.capture { raw("<em>bar</em>") }
assert_equal "<em>bar</em>", string
end
def test_capture_used_for_read
content_for :foo, "foo"
assert_equal "foo", content_for(:foo)
content_for(:bar) { "bar" }
assert_equal "bar", content_for(:bar)
end
def test_content_for_with_multiple_calls
assert ! content_for?(:title)
content_for :title, "foo"
content_for :title, "bar"
assert_equal "foobar", content_for(:title)
end
def test_content_for_with_multiple_calls_and_flush
assert ! content_for?(:title)
content_for :title, "foo"
content_for :title, "bar", flush: true
assert_equal "bar", content_for(:title)
end
def test_content_for_with_block
assert ! content_for?(:title)
content_for :title do
output_buffer << "foo"
output_buffer << "bar"
nil
end
assert_equal "foobar", content_for(:title)
end
def test_content_for_with_block_and_multiple_calls_with_flush
assert ! content_for?(:title)
content_for :title do
"foo"
end
content_for :title, flush: true do
"bar"
end
assert_equal "bar", content_for(:title)
end
def test_content_for_with_block_and_multiple_calls_with_flush_nil_content
assert ! content_for?(:title)
content_for :title do
"foo"
end
content_for :title, nil, flush: true do
"bar"
end
assert_equal "bar", content_for(:title)
end
def test_content_for_with_block_and_multiple_calls_without_flush
assert ! content_for?(:title)
content_for :title do
"foo"
end
content_for :title, flush: false do
"bar"
end
assert_equal "foobar", content_for(:title)
end
def test_content_for_with_whitespace_block
assert ! content_for?(:title)
content_for :title, "foo"
content_for :title do
output_buffer << " \n "
nil
end
content_for :title, "bar"
assert_equal "foobar", content_for(:title)
end
def test_content_for_with_whitespace_block_and_flush
assert ! content_for?(:title)
content_for :title, "foo"
content_for :title, flush: true do
output_buffer << " \n "
nil
end
content_for :title, "bar", flush: true
assert_equal "bar", content_for(:title)
end
def test_content_for_returns_nil_when_writing
assert ! content_for?(:title)
assert_equal nil, content_for(:title, "foo")
assert_equal nil, content_for(:title) { output_buffer << "bar"; nil }
assert_equal nil, content_for(:title) { output_buffer << " \n "; nil }
assert_equal "foobar", content_for(:title)
assert_equal nil, content_for(:title, "foo", flush: true)
assert_equal nil, content_for(:title, flush: true) { output_buffer << "bar"; nil }
assert_equal nil, content_for(:title, flush: true) { output_buffer << " \n "; nil }
assert_equal "bar", content_for(:title)
end
def test_content_for_returns_nil_when_content_missing
assert_equal nil, content_for(:some_missing_key)
end
def test_content_for_question_mark
assert ! content_for?(:title)
content_for :title, "title"
assert content_for?(:title)
assert ! content_for?(:something_else)
end
def test_content_for_should_be_html_safe_after_flush_empty
assert ! content_for?(:title)
content_for :title do
content_tag(:p, "title")
end
assert content_for(:title).html_safe?
content_for :title, "", flush: true
content_for(:title) do
content_tag(:p, "title")
end
assert content_for(:title).html_safe?
end
def test_provide
assert !content_for?(:title)
provide :title, "hi"
assert content_for?(:title)
assert_equal "hi", content_for(:title)
provide :title, "<p>title</p>"
assert_equal "hi<p>title</p>", content_for(:title)
@view_flow = ActionView::OutputFlow.new
provide :title, "hi"
provide :title, raw("<p>title</p>")
assert_equal "hi<p>title</p>", content_for(:title)
end
def test_with_output_buffer_swaps_the_output_buffer_given_no_argument
assert_nil @av.output_buffer
buffer = @av.with_output_buffer do
@av.output_buffer << "."
end
assert_equal ".", buffer
assert_nil @av.output_buffer
end
def test_with_output_buffer_swaps_the_output_buffer_with_an_argument
assert_nil @av.output_buffer
buffer = ActionView::OutputBuffer.new(".")
@av.with_output_buffer(buffer) do
@av.output_buffer << "."
end
assert_equal "..", buffer
assert_nil @av.output_buffer
end
def test_with_output_buffer_restores_the_output_buffer
buffer = ActionView::OutputBuffer.new
@av.output_buffer = buffer
@av.with_output_buffer do
@av.output_buffer << "."
end
assert buffer.equal?(@av.output_buffer)
end
def test_with_output_buffer_sets_proper_encoding
@av.output_buffer = ActionView::OutputBuffer.new
# Ensure we set the output buffer to an encoding different than the default one.
alt_encoding = alt_encoding(@av.output_buffer)
@av.output_buffer.force_encoding(alt_encoding)
@av.with_output_buffer do
assert_equal alt_encoding, @av.output_buffer.encoding
end
end
def test_with_output_buffer_does_not_assume_there_is_an_output_buffer
assert_nil @av.output_buffer
assert_equal "", @av.with_output_buffer {}
end
def alt_encoding(output_buffer)
output_buffer.encoding == Encoding::US_ASCII ? Encoding::UTF_8 : Encoding::US_ASCII
end
end
| 28.281938
| 92
| 0.702804
|
43f700beb7c9c140d76c7a0bd424635d5eb75155
| 38
|
ts
|
TypeScript
|
src/app/pages/campaign/index.ts
|
alokKumarSingh89/angular-firebase-sail
|
72f43c162d9f971fa811950b351c361fb34a0157
|
[
"MIT"
] | null | null | null |
src/app/pages/campaign/index.ts
|
alokKumarSingh89/angular-firebase-sail
|
72f43c162d9f971fa811950b351c361fb34a0157
|
[
"MIT"
] | null | null | null |
src/app/pages/campaign/index.ts
|
alokKumarSingh89/angular-firebase-sail
|
72f43c162d9f971fa811950b351c361fb34a0157
|
[
"MIT"
] | null | null | null |
export * from './campaign.component';
| 19
| 37
| 0.710526
|
b0c074773ab99866ac587534be9b11db15239fcb
| 440
|
py
|
Python
|
evento/migrations/0004_palestrante_social_midia.py
|
kelwys/open_event
|
5fb4b8e88839745b5be50acde563f8ec0b1cab24
|
[
"MIT"
] | null | null | null |
evento/migrations/0004_palestrante_social_midia.py
|
kelwys/open_event
|
5fb4b8e88839745b5be50acde563f8ec0b1cab24
|
[
"MIT"
] | 4
|
2020-02-12T01:22:34.000Z
|
2021-04-08T19:49:45.000Z
|
evento/migrations/0004_palestrante_social_midia.py
|
kelwys/open_event
|
5fb4b8e88839745b5be50acde563f8ec0b1cab24
|
[
"MIT"
] | null | null | null |
# Generated by Django 2.2.4 on 2019-08-14 14:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('evento', '0003_remove_palestrante_slug'),
]
operations = [
migrations.AddField(
model_name='palestrante',
name='social_midia',
field=models.CharField(blank=True, max_length=20, verbose_name='social midia'),
),
]
| 23.157895
| 91
| 0.627273
|
d674f52831d4a7b98e4a69e3089d96a1e8a88753
| 1,260
|
cs
|
C#
|
src/Nirvana/Util/Extensions/AssignableExtensions.cs
|
jasoncavaliere/Nirvana
|
b96d73543c5f653009630a8f6ba2e4a680e3ce63
|
[
"Apache-2.0"
] | 1
|
2017-05-03T10:29:20.000Z
|
2017-05-03T10:29:20.000Z
|
src/Nirvana/Util/Extensions/AssignableExtensions.cs
|
jasoncavaliere/Nirvana
|
b96d73543c5f653009630a8f6ba2e4a680e3ce63
|
[
"Apache-2.0"
] | null | null | null |
src/Nirvana/Util/Extensions/AssignableExtensions.cs
|
jasoncavaliere/Nirvana
|
b96d73543c5f653009630a8f6ba2e4a680e3ce63
|
[
"Apache-2.0"
] | null | null | null |
using System;
using System.Linq;
namespace Nirvana.Util.Extensions
{
public static class AssignableExtensions
{
public static bool IsAssignableToGenericType(this Type givenType, Type genericType)
{
if (givenType == null || genericType == null)
{
return false;
}
return givenType == genericType
|| givenType.MapsToGenericTypeDefinition(genericType)
|| givenType.HasInterfaceThatMapsToGenericTypeDefinition(genericType)
|| givenType.BaseType.IsAssignableToGenericType(genericType);
}
private static bool HasInterfaceThatMapsToGenericTypeDefinition(this Type givenType, Type genericType)
{
return givenType
.GetInterfaces()
.Where(it => it.IsGenericType)
.Any(it => it.GetGenericTypeDefinition() == genericType);
}
private static bool MapsToGenericTypeDefinition(this Type givenType, Type genericType)
{
return genericType.IsGenericTypeDefinition
&& givenType.IsGenericType
&& givenType.GetGenericTypeDefinition() == genericType;
}
}
}
| 33.157895
| 110
| 0.604762
|
dd6f4c46cbe8fdb64316353a3318045a56299cdf
| 785
|
java
|
Java
|
app/src/main/java/com/example/selfgrowth/enums/LabelEnum.java
|
lw1243925457/self_growth_android
|
9476a5224c85e09d348f55d42a9b91acfbd6d906
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/example/selfgrowth/enums/LabelEnum.java
|
lw1243925457/self_growth_android
|
9476a5224c85e09d348f55d42a9b91acfbd6d906
|
[
"Apache-2.0"
] | null | null | null |
app/src/main/java/com/example/selfgrowth/enums/LabelEnum.java
|
lw1243925457/self_growth_android
|
9476a5224c85e09d348f55d42a9b91acfbd6d906
|
[
"Apache-2.0"
] | null | null | null |
package com.example.selfgrowth.enums;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum LabelEnum {
DEFAULT("其他"),
LEARN("学习"),
RUNNING("运动"),
SLEEP("睡觉")
;
private String name;
public static LabelEnum fromString(final String name) {
for (LabelEnum label: LabelEnum.values()) {
if (label.name.equalsIgnoreCase(name)) {
return label;
}
}
return DEFAULT;
}
public static List<String> names() {
return Arrays.stream(LabelEnum.values()).map(e -> e.name).collect(Collectors.toList());
}
}
| 21.216216
| 95
| 0.650955
|
e2bc818e01945d9c0408c4cbbc441b836d509f64
| 374
|
py
|
Python
|
polls/api/views.py
|
s-wirth/thesis
|
a093dfb39a644b95509e2f5b25fbf3b2efa72545
|
[
"MIT"
] | null | null | null |
polls/api/views.py
|
s-wirth/thesis
|
a093dfb39a644b95509e2f5b25fbf3b2efa72545
|
[
"MIT"
] | null | null | null |
polls/api/views.py
|
s-wirth/thesis
|
a093dfb39a644b95509e2f5b25fbf3b2efa72545
|
[
"MIT"
] | null | null | null |
from rest_framework.generics import ListAPIView, RetrieveAPIView
from polls.models import Question
from .serializers import PollSerializer
class PollListAPIView(ListAPIView):
queryset = Question.objects.all()
serializer_class = PollSerializer
class PollDetailAPIView(RetrieveAPIView):
queryset = Question.objects.all()
serializer_class = PollSerializer
| 24.933333
| 64
| 0.807487
|
b37227f009c0f016d58c574d0e93c9187bb4ad92
| 3,510
|
py
|
Python
|
videoReid.py
|
Akimoto-Cris/Pytorch_AMOC
|
d2587ff3cfdd555c537c021dd616844da63210b9
|
[
"Apache-2.0"
] | 2
|
2020-10-23T03:16:52.000Z
|
2021-03-06T02:03:04.000Z
|
videoReid.py
|
Akimoto-Cris/Pytorch_AMOC
|
d2587ff3cfdd555c537c021dd616844da63210b9
|
[
"Apache-2.0"
] | 1
|
2021-03-08T01:53:06.000Z
|
2021-03-28T13:34:25.000Z
|
videoReid.py
|
Akimoto-Cris/Pytorch_AMOC
|
d2587ff3cfdd555c537c021dd616844da63210b9
|
[
"Apache-2.0"
] | 1
|
2020-03-21T01:48:08.000Z
|
2020-03-21T01:48:08.000Z
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Author: Xu Kaixin
@License: Apache Licence
@Time: 2019.10.25 : 下午 8:24
@File Name: videoReid.py
@Software: PyCharm
-----------------
"""
import os
from options import parser_args
from torch.utils.data.sampler import SubsetRandomSampler
from prepareDataset import ReIDDataset
import logging as log
from buildModel import *
from train import train_sequence, load_weight
from test import compute_cmc
from torchnet.logger import VisdomLogger, VisdomPlotLogger
import pickle
def isnan(z):
return z != z
if __name__ == "__main__":
torch.multiprocessing.freeze_support()
opt = parser_args()
torch.manual_seed(opt.seed)
torch.cuda.manual_seed_all(opt.seed)
# change these paths to point to the place where you store i-lids or prid datasets
dataset_root = "D:\\datasets"
if opt.dataset == 0:
seqRootRGB = os.path.join(dataset_root, 'i-LIDS-VID', 'sequences')
seqRootOF = os.path.join(dataset_root, 'i-LIDS-VID-OF-HVP', 'sequences')
else:
seqRootRGB = os.path.join(dataset_root, 'PRID2011', 'multi_shot')
seqRootOF = os.path.join(dataset_root, 'PRID2011-OF-HVP', 'multi_shot')
log.info('loading Dataset - ', seqRootRGB, seqRootOF)
reid_set = ReIDDataset(opt.dataset, seqRootRGB, seqRootOF, 'png', opt.sampleSeqLength, split_ratio=opt.data_split)
log.info('Dataset loaded', len(reid_set))
train_loader = torch.utils.data.DataLoader(reid_set, 1, num_workers=1,
sampler=SubsetRandomSampler(list(range(len(reid_set)))))
train_loader.dataset.inds_set = reid_set.train_inds
test_loader = torch.utils.data.DataLoader(reid_set, 1, num_workers=1,
sampler=SubsetRandomSampler(list(range(len(reid_set.test_inds)))))
test_loader.dataset.inds_set = reid_set.test_inds
# build the model
fullModel = AMOCNet(len(reid_set.train_inds), opt)
contrastive_criterion = ContrastiveLoss(opt.hingeMargin)
class_criterion_A = nn.CrossEntropyLoss()
class_criterion_B = nn.CrossEntropyLoss()
if torch.cuda.is_available():
fullModel = fullModel.cuda()
contrastive_criterion = contrastive_criterion.cuda()
class_criterion_A = class_criterion_A.cuda()
class_criterion_B = class_criterion_B.cuda()
# -- Training
if opt.train:
trained_model, trainer_log, val_history = train_sequence(fullModel, contrastive_criterion, class_criterion_A,
class_criterion_B, train_loader, test_loader, opt)
if opt.pretrained:
trained_model = load_weight(fullModel, opt.pretrained, verbose=True)
# -- Evaluation
nTestImages = reid_set.test_inds # [2 ** (n+1) for n in range(5)]
cmc, simMat, _, avgSame, avgDiff = compute_cmc(reid_set, nTestImages, trained_model, 128)
print(cmc)
print(simMat)
print(avgSame, avgDiff)
sim_logger = VisdomLogger('heatmap', port=8097, opts={
'title': 'simMat',
'columnnames': list(range(len(simMat[0]))),
'rownames': list(range(len(simMat)))
})
cmc_logger = VisdomPlotLogger("line", win="cmc_curve")
for i, v in enumerate(cmc):
cmc_logger.log(i, v, name="cmc_curve")
sim_logger.log(simMat)
log.info("Saving results...")
with open("cmc.pkl", 'w') as f:
pickle.dump(cmc, f)
with open("simMat.pkl", 'w') as f:
pickle.dump(simMat, f)
| 35.816327
| 118
| 0.667806
|
6d81855c3347ed57a65249843ffe0819591f83c4
| 3,841
|
ts
|
TypeScript
|
src/modules/helper.ts
|
TryphonX/react-native-build-manager
|
db92c106f7eedf53213faa08f43a884f731e6b80
|
[
"MIT"
] | null | null | null |
src/modules/helper.ts
|
TryphonX/react-native-build-manager
|
db92c106f7eedf53213faa08f43a884f731e6b80
|
[
"MIT"
] | null | null | null |
src/modules/helper.ts
|
TryphonX/react-native-build-manager
|
db92c106f7eedf53213faa08f43a884f731e6b80
|
[
"MIT"
] | null | null | null |
import chalk from 'chalk';
import { exec } from 'child_process';
import { BuildTask, giveChoice, logReply, makeYesNoQuestion, START_PHRASES } from './common.js';
import { error, warn } from './consolePlus.js';
const { greenBright, red } = chalk;
/**
* The options for the new version name question.
*/
enum versionIncrement {
Major = 'Major',
Minor = 'Minor',
Patch = 'Patch',
None = 'None',
}
/**
* Gets the random phrase
* @returns a random phrase with a random emoji.
*/
export const getRandomPhrase = (): string => `🤯 ${START_PHRASES[Math.floor(Math.random()*START_PHRASES.length)]} \n`;
/**
* Checks for uncommited changes.
* @param callback The function to be called after checking for commit changes
*/
export const checkForUncommited = (callback: () => Promise<void>): void => {
try {
exec('git diff-index --quiet HEAD --').on('exit', (code) => {
if (code === 1) warn('Your repository is not clean! It is recommended you commit all uncommited changes before proceeding.');
callback();
});
} catch (err) {
warn(`Failed to get git difference: ${err.message}`);
warn('It is recommended you commit all uncommited changes before proceeding.');
callback();
}
};
/**
* Asks the user questions about what the new version should be and determines the new versionName.
* @param version The current version name.
* @returns The new version name.
*/
export const getNewVersionName = async(version: string): Promise<string> => {
// splitting the version by '.', we retrieve a tuple with the three numbers of the version name.
const [majorStr, minorStr, patchStr] = version.split('.');
// getting a new tuple by shifting the previous string tuple to numbers
let [major, minor, patch] = [~~majorStr, ~~minorStr, ~~patchStr];
const choice = await giveChoice('The new APK version should increment:', versionIncrement);
switch (choice) {
case versionIncrement.Major:
major++;
minor = patch = 0;
break;
case versionIncrement.Minor:
minor++;
patch = 0;
break;
case versionIncrement.Patch:
patch++;
break;
// none
default:
break;
}
logReply(choice);
return `${major}.${minor}.${patch}`;
};
export const getNewVersionCode = (_versionCode: string): string => {
const inc = makeYesNoQuestion('Increment versionCode?');
if (inc) {
return (~~_versionCode + 1).toString();
}
else {
return _versionCode;
}
};
export const askToConfirm = (): boolean => makeYesNoQuestion('Confirm?');
export const getBuildTask = async(): Promise<BuildTask> => await giveChoice('Build:', BuildTask) as BuildTask;
export const buildApk = (task: BuildTask): void => {
const bundleCmd = 'react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle';
let buildCmd: string;
switch (task) {
case BuildTask.Debug:
buildCmd = 'cd ./android/ && gradlew assembleDebug';
break;
case BuildTask.ReleaseApk:
buildCmd = 'cd ./android/ && gradlew assembleRelease';
break;
case BuildTask.ReleaseBundle:
buildCmd = 'cd ./android/ && gradlew bundleRelease';
break;
case BuildTask.ReleaseFull:
buildCmd = 'cd ./android/ && gradlew assembleRelease && gradlew bundleRelease';
break;
default:
warn('Unexpected error @ helper');
break;
}
const buildProcess = exec(`${bundleCmd} && ${buildCmd}`);
let success = false;
buildProcess.stdout.on('data', (data) => {
console.log(data);
if (data.toString().match(/build successful/i)) {
success = true;
}
});
buildProcess.stderr.on('data', (data) => {
console.log(data);
});
buildProcess.stderr.on('error', (data) => error(data.message));
buildProcess.stdout.on('end', () => {
if (success) {
console.log(greenBright.bold('Build Successful\n'));
}
else {
console.log(red.bold('Build Failed\n'));
}
});
};
| 25.437086
| 159
| 0.67899
|
b8a3476363fc91e1aec1f5251e764e137f6c7268
| 2,474
|
h
|
C
|
engine/Engine.UI/src/ui/widget/VerticalScrollBar.h
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | null | null | null |
engine/Engine.UI/src/ui/widget/VerticalScrollBar.h
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | null | null | null |
engine/Engine.UI/src/ui/widget/VerticalScrollBar.h
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | null | null | null |
#pragma once
#include "DragHelper.h"
#include "Widget.h"
#include "ui/widget/button/Button.h"
#include "ui/control/ClickableControl.h"
#include "ui/layout/ManualLayout.h"
#include <algorithm>
namespace Ghurund::UI {
class VerticalScrollBar:public Widget {
private:
Button* topButton;
Button* barButton;
ClickableControl* clickableTrack;
ManualLayout* track;
Button* bottomButton;
uint32_t pressMousePos = 0;
float pressBarPos = 0;
DragHelper* dragHelper = nullptr;
float scroll = 0;
float maxScroll = 100;
Event<Control> onScrolled = Event<Control>(*this);
void updateBar();
void updateScroll();
protected:
virtual void bind() override;
static const Ghurund::Core::Type& GET_TYPE() {
static const auto CONSTRUCTOR = Constructor<VerticalScrollBar>();
static const Ghurund::Core::Type TYPE = TypeBuilder<VerticalScrollBar>(NAMESPACE_NAME, GH_STRINGIFY(VerticalScrollBar))
.withConstructor(CONSTRUCTOR)
.withSupertype(__super::GET_TYPE());
return TYPE;
}
public:
VerticalScrollBar() {
setPreferredSize(PreferredSize::Width::WRAP, PreferredSize::Height::FILL);
};
~VerticalScrollBar() {
delete dragHelper;
}
inline float getScroll() const {
return scroll;
}
inline void setScroll(float scroll) {
this->scroll = std::max(0.0f, std::min(scroll, maxScroll));
updateBar();
}
__declspec(property(get = getScroll, put = setScroll)) float Scroll;
inline float getMaxScroll() const {
return maxScroll;
}
inline void setMaxScroll(float maxScroll) {
this->maxScroll = std::max(0.0f, maxScroll);
Scroll = std::max(0.0f, std::min(scroll, maxScroll));
}
__declspec(property(get = getMaxScroll, put = setMaxScroll)) float MaxScroll;
inline Event<Control>& getOnScrolled() {
return onScrolled;
}
__declspec(property(get = getOnScrolled)) Event<Control>& OnScrolled;
inline static const Ghurund::Core::Type& TYPE = GET_TYPE();
virtual const Ghurund::Core::Type& getType() const override {
return TYPE;
}
};
typedef SharedPointer<VerticalScrollBar> VerticalScrollBarPtr;
}
| 27.797753
| 131
| 0.607518
|
79628dc8f2810da09ab8783411d5db38180018a5
| 4,664
|
php
|
PHP
|
vendor/bitwasp/bitcoin/src/Crypto/EcAdapter/Impl/Secp256k1/Key/PublicKey.php
|
halesyy/mix
|
f2953726f02e3c11400904d23b581e140cd791df
|
[
"MIT"
] | 17
|
2019-07-23T00:35:32.000Z
|
2022-02-27T22:12:41.000Z
|
vendor/bitwasp/bitcoin/src/Crypto/EcAdapter/Impl/Secp256k1/Key/PublicKey.php
|
halesyy/mix
|
f2953726f02e3c11400904d23b581e140cd791df
|
[
"MIT"
] | 4
|
2021-03-11T19:03:35.000Z
|
2021-05-06T06:37:52.000Z
|
vendor/bitwasp/bitcoin/src/Crypto/EcAdapter/Impl/Secp256k1/Key/PublicKey.php
|
halesyy/mix
|
f2953726f02e3c11400904d23b581e140cd791df
|
[
"MIT"
] | 13
|
2020-02-22T18:27:01.000Z
|
2022-03-16T18:50:59.000Z
|
<?php
namespace BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Key;
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Adapter\EcAdapter;
use BitWasp\Bitcoin\Crypto\EcAdapter\Impl\Secp256k1\Serializer\Key\PublicKeySerializer;
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\Key;
use BitWasp\Bitcoin\Crypto\EcAdapter\Key\PublicKeyInterface;
use BitWasp\Bitcoin\Crypto\EcAdapter\Signature\SignatureInterface;
use BitWasp\Buffertools\Buffer;
use BitWasp\Buffertools\BufferInterface;
class PublicKey extends Key implements PublicKeyInterface
{
/**
* @var EcAdapter
*/
private $ecAdapter;
/**
* @var bool|false
*/
private $compressed;
/**
* @var resource
*/
private $pubkey_t;
/**
* @param EcAdapter $ecAdapter
* @param resource $secp256k1_pubkey_t
* @param bool|false $compressed
*/
public function __construct(EcAdapter $ecAdapter, $secp256k1_pubkey_t, $compressed = false)
{
if (!is_resource($secp256k1_pubkey_t) ||
!get_resource_type($secp256k1_pubkey_t) === SECP256K1_TYPE_PUBKEY) {
throw new \InvalidArgumentException('Secp256k1\Key\PublicKey expects ' . SECP256K1_TYPE_PUBKEY . ' resource');
}
if (false === is_bool($compressed)) {
throw new \InvalidArgumentException('PublicKey: Compressed must be a boolean');
}
$this->ecAdapter = $ecAdapter;
$this->pubkey_t = $secp256k1_pubkey_t;
$this->compressed = $compressed;
}
/**
* @param BufferInterface $msg32
* @param SignatureInterface $signature
* @return bool
*/
public function verify(BufferInterface $msg32, SignatureInterface $signature)
{
return $this->ecAdapter->verify($msg32, $this, $signature);
}
/**
* @param PublicKey $other
* @return bool
*/
private function doEquals(PublicKey $other)
{
$context = $this->ecAdapter->getContext();
$pubA = '';
$pubB = '';
if (!(secp256k1_ec_pubkey_serialize($context, $pubA, $this->pubkey_t, $this->compressed) && secp256k1_ec_pubkey_serialize($context, $pubB, $other->pubkey_t, $this->compressed))) {
throw new \RuntimeException('Unable to serialize public key during equals');
}
return hash_equals($pubA, $pubB);
}
/**
* @param PublicKeyInterface $other
* @return bool
*/
public function equals(PublicKeyInterface $other)
{
/** @var PublicKey $other */
return $this->doEquals($other);
}
/**
* @return bool|false
*/
public function isCompressed()
{
return $this->compressed;
}
/**
* @return resource
*/
public function getResource()
{
return $this->pubkey_t;
}
/**
* @return resource
* @throws \Exception
*/
private function clonePubkey()
{
$context = $this->ecAdapter->getContext();
$serialized = '';
if (1 !== secp256k1_ec_pubkey_serialize($context, $serialized, $this->pubkey_t, $this->compressed)) {
throw new \Exception('Secp256k1: pubkey serialize');
}
/** @var resource $clone */
$clone = '';
if (1 !== secp256k1_ec_pubkey_parse($context, $clone, $serialized)) {
throw new \Exception('Secp256k1 pubkey parse');
}
return $clone;
}
/**
* @param \GMP $tweak
* @return PublicKey
* @throws \Exception
*/
public function tweakAdd(\GMP $tweak)
{
$context = $this->ecAdapter->getContext();
$bin = Buffer::int(gmp_strval($tweak, 10), 32)->getBinary();
$clone = $this->clonePubkey();
if (1 !== secp256k1_ec_pubkey_tweak_add($context, $clone, $bin)) {
throw new \RuntimeException('Secp256k1: tweak add failed.');
}
return new PublicKey($this->ecAdapter, $clone, $this->compressed);
}
/**
* @param \GMP $tweak
* @return PublicKey
* @throws \Exception
*/
public function tweakMul(\GMP $tweak)
{
$context = $this->ecAdapter->getContext();
$bin = Buffer::int(gmp_strval($tweak, 10), 32)->getBinary();
$clone = $this->clonePubkey();
if (1 !== secp256k1_ec_pubkey_tweak_mul($context, $clone, $bin)) {
throw new \RuntimeException('Secp256k1: tweak mul failed.');
}
return new PublicKey($this->ecAdapter, $clone, $this->compressed);
}
/**
* @return BufferInterface
*/
public function getBuffer()
{
return (new PublicKeySerializer($this->ecAdapter))->serialize($this);
}
}
| 27.761905
| 187
| 0.60506
|
af8ae78f2e45dfec1e8b2a45b9839f93f62ea8dd
| 7,151
|
py
|
Python
|
tests/test_one_pod_pipeline_generator.py
|
0shimax/kedro-kubeflow
|
72551f3a66f21719f8af7afe883df79f70c67c51
|
[
"Apache-2.0"
] | null | null | null |
tests/test_one_pod_pipeline_generator.py
|
0shimax/kedro-kubeflow
|
72551f3a66f21719f8af7afe883df79f70c67c51
|
[
"Apache-2.0"
] | null | null | null |
tests/test_one_pod_pipeline_generator.py
|
0shimax/kedro-kubeflow
|
72551f3a66f21719f8af7afe883df79f70c67c51
|
[
"Apache-2.0"
] | null | null | null |
"""Test generator"""
import os
import unittest
from inspect import signature
from unittest.mock import MagicMock
import kfp
from kedro.pipeline import Pipeline, node
from kedro_kubeflow.config import PluginConfig
from kedro_kubeflow.generators.one_pod_pipeline_generator import (
OnePodPipelineGenerator,
)
def identity(input1: str):
return input1 # pragma: no cover
class TestGenerator(unittest.TestCase):
def test_support_modification_of_pull_policy(self):
# given
self.create_generator()
# when
with kfp.dsl.Pipeline(None) as dsl_pipeline:
self.generator_under_test.generate_pipeline(
"pipeline", "unittest-image", "Never"
)()
# then
assert len(dsl_pipeline.ops) == 1
assert dsl_pipeline.ops["pipeline"].container.image == "unittest-image"
assert (
dsl_pipeline.ops["pipeline"].container.image_pull_policy == "Never"
)
def test_should_support_params_and_inject_them_to_the_node(self):
# given
self.create_generator(params={"param1": 0.3, "param2": 42})
# when
with kfp.dsl.Pipeline(None) as dsl_pipeline:
pipeline = self.generator_under_test.generate_pipeline(
"pipeline", "unittest-image", "Always"
)
default_params = signature(pipeline).parameters
pipeline()
# then
assert len(default_params) == 2
assert default_params["param1"].default == 0.3
assert default_params["param2"].default == 42
assert dsl_pipeline.ops["pipeline"].container.args[1:] == [
"param1",
"{{pipelineparam:op=;name=param1}}",
"param2",
"{{pipelineparam:op=;name=param2}}",
]
def test_should_not_add_resources_spec_if_not_requested(self):
# given
self.create_generator(config={})
# when
with kfp.dsl.Pipeline(None) as dsl_pipeline:
self.generator_under_test.generate_pipeline(
"pipeline", "unittest-image", "Always"
)()
# then
assert dsl_pipeline.ops["pipeline"].container.resources is None
def test_should_add_resources_spec(self):
# given
self.create_generator(
config={
"resources": {
"__default__": {"cpu": "100m", "memory": "8Gi"},
"node1": {"cpu": "400m", "memory": "64Gi"},
}
}
)
# when
with kfp.dsl.Pipeline(None) as dsl_pipeline:
self.generator_under_test.generate_pipeline(
"pipeline", "unittest-image", "Always"
)()
# then
resources = dsl_pipeline.ops["pipeline"].container.resources
assert resources.limits == {"cpu": "100m", "memory": "8Gi"}
assert resources.requests == {"cpu": "100m", "memory": "8Gi"}
def test_should_set_description(self):
# given
self.create_generator(config={"description": "DESC"})
# when
pipeline = self.generator_under_test.generate_pipeline(
"pipeline", "unittest-image", "Never"
)
# then
assert pipeline._component_description == "DESC"
def test_artifact_registration(self):
# given
self.create_generator(
catalog={
"B": {
"type": "pandas.CSVDataSet",
"filepath": "data/02_intermediate/b.csv",
}
}
)
# when
with kfp.dsl.Pipeline(None) as dsl_pipeline:
self.generator_under_test.generate_pipeline(
"pipeline", "unittest-image", "Always"
)()
# then
assert dsl_pipeline.ops["pipeline"].file_outputs == {
"B": "/home/kedro/data/02_intermediate/b.csv"
}
def test_should_skip_artifact_registration_if_requested(self):
# given
self.create_generator(
catalog={
"B": {
"type": "pandas.CSVDataSet",
"filepath": "data/02_intermediate/b.csv",
}
},
config={"store_kedro_outputs_as_kfp_artifacts": False},
)
# when
with kfp.dsl.Pipeline(None) as dsl_pipeline:
self.generator_under_test.generate_pipeline(
"pipeline", "unittest-image", "Always"
)()
# then
assert dsl_pipeline.ops["pipeline"].file_outputs == {}
def test_should_pass_kedro_config_env_to_nodes(self):
# given
self.create_generator(params={"param1": 0.3, "param2": 42})
os.environ["KEDRO_CONFIG_MY_KEY"] = "42"
os.environ["SOME_VALUE"] = "100"
try:
# when
with kfp.dsl.Pipeline(None) as dsl_pipeline:
self.generator_under_test.generate_pipeline(
"pipeline", "unittest-image", "Always"
)()
# then
env_values = {
e.name: e.value
for e in dsl_pipeline.ops["pipeline"].container.env
}
assert "KEDRO_CONFIG_MY_KEY" in env_values
assert env_values["KEDRO_CONFIG_MY_KEY"] == "42"
assert "SOME_VALUE" not in env_values
finally:
del os.environ["KEDRO_CONFIG_MY_KEY"]
del os.environ["SOME_VALUE"]
def test_should_pass_kubeflow_run_id_to_nodes(self):
# given
self.create_generator(params={"param1": 0.3, "param2": 42})
# when
with kfp.dsl.Pipeline(None) as dsl_pipeline:
self.generator_under_test.generate_pipeline(
"pipeline", "unittest-image", "Always"
)()
# then
env_values = {
e.name: e.value for e in dsl_pipeline.ops["pipeline"].container.env
}
assert "KUBEFLOW_RUN_ID" in env_values
assert env_values["KUBEFLOW_RUN_ID"] == "{{workflow.uid}}"
def create_generator(self, config=None, params=None, catalog=None):
if config is None:
config = {}
if params is None:
params = {}
if catalog is None:
catalog = {}
config_loader = MagicMock()
config_loader.get.return_value = catalog
context = type(
"obj",
(object,),
{
"env": "unittests",
"params": params,
"config_loader": config_loader,
"pipelines": {
"pipeline": Pipeline(
[
node(identity, "A", "B", name="node1"),
node(identity, "B", "C", name="node2"),
]
)
},
},
)
self.generator_under_test = OnePodPipelineGenerator(
config=PluginConfig(
{"host": "http://unittest", "run_config": config}
),
project_name="my-awesome-project",
context=context,
)
| 31.502203
| 79
| 0.544399
|
854de5203ceb93dbd19c03e6208f54099b6f63ca
| 111
|
cs
|
C#
|
src/Classes/Something.cs
|
JKerens/build-powershell-modules
|
390a206ac2a8d049eca7490cf1cdb9fa3d3e1c94
|
[
"MIT"
] | 2
|
2022-01-25T19:57:39.000Z
|
2022-03-22T07:03:36.000Z
|
src/Classes/Something.cs
|
JKerens/build-powershell-modules
|
390a206ac2a8d049eca7490cf1cdb9fa3d3e1c94
|
[
"MIT"
] | null | null | null |
src/Classes/Something.cs
|
JKerens/build-powershell-modules
|
390a206ac2a8d049eca7490cf1cdb9fa3d3e1c94
|
[
"MIT"
] | 1
|
2022-03-22T07:03:51.000Z
|
2022-03-22T07:03:51.000Z
|
namespace Build.PowerShell
{
public class Something
{
public string Name { get; set; }
}
}
| 15.857143
| 40
| 0.594595
|
cca237ccf6de368be1f2769545a84b79e2520ef0
| 2,900
|
rb
|
Ruby
|
app/models/place_scrobble/match_options.rb
|
quantitare/quantitare
|
c2c35e74e94f7bb3779b20bd23abdd08b8d938ab
|
[
"MIT"
] | 7
|
2018-05-18T00:42:13.000Z
|
2021-12-01T05:38:52.000Z
|
app/models/place_scrobble/match_options.rb
|
quantitare/quantitare
|
c2c35e74e94f7bb3779b20bd23abdd08b8d938ab
|
[
"MIT"
] | 721
|
2018-09-12T06:33:18.000Z
|
2022-03-30T22:01:35.000Z
|
app/models/place_scrobble/match_options.rb
|
quantitare/quantitare
|
c2c35e74e94f7bb3779b20bd23abdd08b8d938ab
|
[
"MIT"
] | null | null | null |
# frozen_string_literal: true
class PlaceScrobble
# Wrapper for accomodating nested attributes for {PlaceMatch}es on a given {PlaceScrobble}. Delegates most
# "persistence" logic to the associated {PlaceMatch}, and decides whether it ought to create or update one when given
# the +enabled+ flag. Takes care of copying all the fields from the associated scrobble to the {PlaceMatch}.
#
# my_location_scrobble.assign_attributes(match_options_attributes: { enabled: true, match_name: true })
# my_location_scrobble.match_options.save
#
# Since this is not an ActiveRecord association, it must be saved separately. The service object
# {ProcessPlaceMatchOptions} takes care of the business logic of handling form input.
#
class MatchOptions
DEFAULT_RADIUS = 250
attr_reader :place_scrobble, :to_delete, :enabled
alias enabled? enabled
alias to_delete? to_delete
delegate :coordinates, to: :place_scrobble
delegate :id, :source_field_radius, :source_field_radius=, :place, :place=, :save, :destroy, :valid?, :new_record?,
:persisted?, :destroyed?,
to: :place_match
def initialize(place_scrobble)
@place_scrobble = place_scrobble
end
def place_match
@place_match ||= FindPlaceMatchForLocationScrobble.(place_scrobble) || new_place_match
end
def enabled=(value)
@enabled = value.to_bool
end
def to_delete=(value)
@to_delete = value.to_bool
end
def attributes=(attributes)
attributes ||= {}
self.enabled = attributes[:enabled]
self.to_delete = attributes[:to_delete]
self.match_name = attributes[:match_name]
self.match_coordinates = attributes[:match_coordinates]
self.source_field_radius = attributes[:source_field_radius]
end
def match_name
place_match.source_field_name.present?
end
def match_name=(value)
place_match.source_field_name = value.to_bool ? source_field_name : nil
end
def match_coordinates
place_match.source_field_radius.present?
end
def match_coordinates=(value)
if value.to_bool
place_match.source_field_radius = DEFAULT_RADIUS
place_match.source_field_latitude = source_field_latitude
place_match.source_field_longitude = source_field_longitude
else
place_match.source_field_radius = nil
place_match.source_field_latitude = nil
place_match.source_field_longitude = nil
end
end
def source_field_name
place_scrobble.read_attribute(:name)
end
def source_field_latitude
place_scrobble.latitude
end
def source_field_longitude
place_scrobble.longitude
end
private
def new_place_match
PlaceMatch.new(
user: place_scrobble.user,
source: place_scrobble.source,
place: place_scrobble.place
)
end
end
end
| 28.431373
| 119
| 0.714483
|
df13f88b187629144f9832e4cfa65c919d01df42
| 1,513
|
cs
|
C#
|
src/MultiPlug.Ext.RasPi.GPIO/Components/RaspberryPi/GpioPin.cs
|
Industry4/MultiPlug.Ext.RasPi.GPIO
|
445aae7436cfc23bdd56ac7dfc0603c8b2d07602
|
[
"MIT"
] | null | null | null |
src/MultiPlug.Ext.RasPi.GPIO/Components/RaspberryPi/GpioPin.cs
|
Industry4/MultiPlug.Ext.RasPi.GPIO
|
445aae7436cfc23bdd56ac7dfc0603c8b2d07602
|
[
"MIT"
] | null | null | null |
src/MultiPlug.Ext.RasPi.GPIO/Components/RaspberryPi/GpioPin.cs
|
Industry4/MultiPlug.Ext.RasPi.GPIO
|
445aae7436cfc23bdd56ac7dfc0603c8b2d07602
|
[
"MIT"
] | null | null | null |
using System;
using Unosquare.RaspberryIO.Abstractions;
namespace MultiPlug.Ext.RasPi.GPIO.Components.RaspberryPi
{
internal class GpioPin
{
readonly IGpioPin m_GpioPin;
internal Action StateChange;
public GpioPin(IGpioPin theGpioPin)
{
m_GpioPin = theGpioPin;
}
internal int BcmPinNumber { get { return m_GpioPin.BcmPinNumber; } }
internal GpioPinResistorPullMode InputPullMode
{
get
{
return m_GpioPin.InputPullMode;
}
set
{
m_GpioPin.InputPullMode = value;
}
}
internal GpioPinDriveMode PinMode
{
get
{
return m_GpioPin.PinMode;
}
set
{
m_GpioPin.PinMode = value;
}
}
internal bool LastValue { get; private set; }
internal bool Read()
{
LastValue = m_GpioPin.Read();
return LastValue;
}
internal void RegisterInterruptCallback(EdgeDetection edgeDetection, Action callback)
{
m_GpioPin.RegisterInterruptCallback(edgeDetection, callback);
}
internal void Write(bool value)
{
m_GpioPin.Write(value);
if(LastValue != value )
{
LastValue = value;
StateChange?.Invoke();
}
}
}
}
| 21.927536
| 93
| 0.507601
|
798aaba8d2ad4dafde098553c38174a2f614d8b9
| 3,349
|
php
|
PHP
|
app/tools/html/HtmlFormatter.php
|
dewframework/dew
|
c929e6bf140565c7b21c3ccd62112ba17e50502f
|
[
"MIT"
] | 1
|
2016-02-14T18:29:42.000Z
|
2016-02-14T18:29:42.000Z
|
app/tools/html/HtmlFormatter.php
|
dewframework/dew
|
c929e6bf140565c7b21c3ccd62112ba17e50502f
|
[
"MIT"
] | null | null | null |
app/tools/html/HtmlFormatter.php
|
dewframework/dew
|
c929e6bf140565c7b21c3ccd62112ba17e50502f
|
[
"MIT"
] | null | null | null |
<?php
namespace Mihaeu;
/**
* HTML Formatter
*
* @author Michael Haeuslmann <haeuslmann@gmail.com>
*/
class HtmlFormatter
{
/**
* Formats HTML by re-indenting the tags and removing unnecessary whitespace.
*
* @param string $html HTML string.
* @param string $indentWith Characters that are being used for indentation (default = 4 spaces).
* @param string $tagsWithoutIndentation Comma-separated list of HTML tags that should not be indented (default = html,link,img,meta)
* @return string Re-indented HTML.
*/
public static function format($html, $indentWith = ' ', $tagsWithoutIndentation = 'html,link,img,meta')
{
// remove all line feeds and replace tabs with spaces
$html = str_replace(["\n", "\r", "\t"], ['', '', ' '], $html);
$elements = preg_split('/(<.+>)/U', $html, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
$dom = self::parseDom($elements);
$indent = 0;
$output = array();
foreach ($dom as $index => $element)
{
if ($element['opening'])
{
$output[] = "\n".str_repeat($indentWith, $indent).trim($element['content']);
// make sure that only the elements who have not been blacklisted are being indented
if ( ! in_array($element['type'], explode(',', $tagsWithoutIndentation)))
{
++$indent;
}
}
else if ($element['standalone'])
{
$output[] = "\n".str_repeat($indentWith, $indent).trim($element['content']);
}
else if ($element['closing'])
{
--$indent;
$lf = "\n".str_repeat($indentWith, $indent);
if (isset($dom[$index - 1]) && $dom[$index - 1]['opening'])
{
$lf = '';
}
$output[] = $lf.trim($element['content']);
}
else if ($element['text'])
{
// $output[] = "\n".str_repeat($indentWith, $indent).trim($element['content']);
$output[] = "\n".str_repeat($indentWith, $indent).preg_replace('/ [ \t]*/', ' ', $element['content']);
}
else if ($element['comment'])
{
$output[] = "\n".str_repeat($indentWith, $indent).trim($element['content']);
}
}
return trim(implode('', $output));
}
/**
* Parses an array of HTML tokens and adds basic information about about the type of
* tag the token represents.
*
* @param Array $elements Array of HTML tokens (tags and text tokens).
* @return Array HTML elements with extra information.
*/
public static function parseDom(Array $elements)
{
$dom = array();
foreach ($elements as $element)
{
$isText = false;
$isComment = false;
$isClosing = false;
$isOpening = false;
$isStandalone = false;
$currentElement = trim($element);
// comment
if (strpos($currentElement, '<!') === 0)
{
$isComment = true;
}
// closing tag
else if (strpos($currentElement, '</') === 0)
{
$isClosing = true;
}
// stand-alone tag
else if (preg_match('/\/>$/', $currentElement))
{
$isStandalone = true;
}
// normal opening tag
else if (strpos($currentElement, '<') === 0)
{
$isOpening = true;
}
// text
else
{
$isText = true;
}
$dom[] = array(
'text' => $isText,
'comment' => $isComment,
'closing' => $isClosing,
'opening' => $isOpening,
'standalone' => $isStandalone,
'content' => $element,
'type' => preg_replace('/^<\/?(\w+)[ >].*$/U', '$1', $element)
);
}
return $dom;
}
}
| 26.370079
| 134
| 0.58943
|
c6d5258571d945740ebf95e6113191419ba4ea3e
| 8,185
|
py
|
Python
|
TestTimeAugmentation/generate_xml_cvat.py
|
onepanelio/ensembleObjectDetection
|
ddc742b553ba7e18d5dcdcf30f61f5858f369d3a
|
[
"MIT"
] | null | null | null |
TestTimeAugmentation/generate_xml_cvat.py
|
onepanelio/ensembleObjectDetection
|
ddc742b553ba7e18d5dcdcf30f61f5858f369d3a
|
[
"MIT"
] | null | null | null |
TestTimeAugmentation/generate_xml_cvat.py
|
onepanelio/ensembleObjectDetection
|
ddc742b553ba7e18d5dcdcf30f61f5858f369d3a
|
[
"MIT"
] | null | null | null |
from xml.sax.saxutils import XMLGenerator
from collections import OrderedDict
import json
import glob
import xml.etree.ElementTree as ET
import os
class XmlAnnotationWriter:
def __init__(self, file):
self.version = "1.1"
self.file = file
self.xmlgen = XMLGenerator(self.file, 'utf-8')
self._level = 0
def _indent(self, newline = True):
if newline:
self.xmlgen.ignorableWhitespace("\n")
self.xmlgen.ignorableWhitespace(" " * self._level)
def _add_version(self):
self._indent()
self.xmlgen.startElement("version", {})
self.xmlgen.characters(self.version)
self.xmlgen.endElement("version")
def open_root(self):
self.xmlgen.startDocument()
self.xmlgen.startElement("annotations", {})
self._level += 1
self._add_version()
def _add_meta(self, meta):
self._level += 1
for k, v in meta.items():
if isinstance(v, OrderedDict):
self._indent()
self.xmlgen.startElement(k, {})
self._add_meta(v)
self._indent()
self.xmlgen.endElement(k)
elif isinstance(v, list):
self._indent()
self.xmlgen.startElement(k, {})
for tup in v:
self._add_meta(OrderedDict([tup]))
self._indent()
self.xmlgen.endElement(k)
else:
self._indent()
self.xmlgen.startElement(k, {})
self.xmlgen.characters(v)
self.xmlgen.endElement(k)
self._level -= 1
def add_meta(self, meta):
self._indent()
self.xmlgen.startElement("meta", {})
self._add_meta(meta)
self._indent()
self.xmlgen.endElement("meta")
def open_track(self, track):
self._indent()
self.xmlgen.startElement("track", track)
self._level += 1
def open_image(self, image):
self._indent()
self.xmlgen.startElement("image", image)
self._level += 1
def open_box(self, box):
self._indent()
self.xmlgen.startElement("box", box)
self._level += 1
def open_polygon(self, polygon):
self._indent()
self.xmlgen.startElement("polygon", polygon)
self._level += 1
def open_polyline(self, polyline):
self._indent()
self.xmlgen.startElement("polyline", polyline)
self._level += 1
def open_points(self, points):
self._indent()
self.xmlgen.startElement("points", points)
self._level += 1
def open_cuboid(self, cuboid):
self._indent()
self.xmlgen.startElement("cuboid", cuboid)
self._level += 1
def open_tag(self, tag):
self._indent()
self.xmlgen.startElement("tag", tag)
self._level += 1
def add_attribute(self, attribute):
self._indent()
self.xmlgen.startElement("attribute", {"name": attribute["name"]})
self.xmlgen.characters(attribute["value"])
self.xmlgen.endElement("attribute")
def close_box(self):
self._level -= 1
self._indent()
self.xmlgen.endElement("box")
def close_polygon(self):
self._level -= 1
self._indent()
self.xmlgen.endElement("polygon")
def close_polyline(self):
self._level -= 1
self._indent()
self.xmlgen.endElement("polyline")
def close_points(self):
self._level -= 1
self._indent()
self.xmlgen.endElement("points")
def close_cuboid(self):
self._level -= 1
self._indent()
self.xmlgen.endElement("cuboid")
def close_tag(self):
self._level -= 1
self._indent()
self.xmlgen.endElement("tag")
def close_image(self):
self._level -= 1
self._indent()
self.xmlgen.endElement("image")
def close_track(self):
self._level -= 1
self._indent()
self.xmlgen.endElement("track")
def close_root(self):
self._level -= 1
self._indent()
self.xmlgen.endElement("annotations")
self.xmlgen.endDocument()
def pairwise(iterable):
a = iter(iterable)
return zip(a, a)
def dump_as_cvat_annotation(file_object, annotations):
from collections import OrderedDict
dumper = XmlAnnotationWriter(file_object)
dumper.open_root()
dumper.add_meta(annotations['meta'])
for frame_annotation in annotations['frames']:
frame_id = frame_annotation['frame']
dumper.open_image(OrderedDict([
("id", str(frame_id)),
("name", 'frame_'+str(frame_id).zfill(6)),
("width", str(frame_annotation['width'])),
("height", str(frame_annotation['height']))
]))
for shape in frame_annotation['shapes']:
dump_data = OrderedDict([
("label", shape['label']),
("occluded", str(int(shape['occluded']))),
])
if shape['type'] == "rectangle":
dump_data.update(OrderedDict([
("xtl", "{:.2f}".format(shape['points'][0])),
("ytl", "{:.2f}".format(shape['points'][1])),
("xbr", "{:.2f}".format(shape['points'][2])),
("ybr", "{:.2f}".format(shape['points'][3]))
]))
else:
dump_data.update(OrderedDict([
("points", ';'.join((
','.join((
"{:.2f}".format(x),
"{:.2f}".format(y)
)) for x, y in pairwise(shape['points']))
)),
]))
if shape['type'] == "rectangle":
dumper.open_box(dump_data)
elif shape['type'] == "polygon":
dumper.open_polygon(dump_data)
if shape['type'] == "rectangle":
dumper.close_box()
elif shape['type'] == "polygon":
dumper.close_polygon()
dumper.close_image()
dumper.close_root()
def get_labels_from_json(json_path):
with open(json_path, 'r') as json_file:
data = json.load(json_file)
labels = []
for label in data['categories']:
labels.append(('label', [('name', label['name'])]))
return labels,data
def generate_xml(pathImg):
labels,data = get_labels_from_json("/mnt/data/dataorig/annotations/instances_default.json")
_images = glob.glob("/mnt/data/dataorig/images/*.jpg")
_images.extend(glob.glob("/mnt/data/dataorig/images/*.png"))
len_images = len(_images)
final_result = {'meta':{'task': OrderedDict([('id','0'),('name',"onepanel_workflow_default_name"),('size',str(len_images)),('mode','interpolation'),('start_frame', '0'),('stop_frame', str(len_images-1)),('z_order',"False"),('labels', labels)])}, 'frames':[]}
for image in data['images']:
tree = ET.parse(os.path.join(pathImg+"output", os.path.basename(image['file_name']))[:-4]+'.xml')
root = tree.getroot()
shapes = []
for obj in root.findall('object'):
shapes.append({'type':'rectangle','label':obj.find('name').text,'occluded':0,'points':[float(list(obj.iter('xmin'))[0].text),float(list(obj.iter('ymin'))[0].text),float(list(obj.iter('xmax'))[0].text),float(list(obj.iter('ymax'))[0].text)]})
final_result['frames'].append({'frame':int(image['id']), 'width':int(image['width']), 'height':int(image['height']), 'shapes':shapes})
dump_as_cvat_annotation(open(pathImg+"output/cvat_xml_output.xml", "w"), final_result)
if __name__ =="__main__":
#annotations = {'meta':{'task': OrderedDict([('id','48'),('name','test'),('size','44'),('mode','interpolation'),('z_order',False),('labels', [('label',[('name','cut')]),('label', [('name','zero')])])])},'frames':[{'frame':0,'width':2280,'height':1920, 'shapes':[{'type':'polygon','label':'cut','occluded':0,'points':[10,5,11,6]}]}]}
#dump_as_cvat_annotation(open("cvat_anno_test.xml","w"), annotations)
generate_xml()
| 33.683128
| 336
| 0.559805
|
8e4f5e22e444e3a1a37b058dc97409bc1120d130
| 1,641
|
swift
|
Swift
|
Example/VandMarvelUIKit/Features/CharacterDisplayCompact/CharacterDisplayCompactView.swift
|
Vandcarlos/VandMarvelUIKit
|
e065912b1107f02ff8665b715b82e17866d6528b
|
[
"MIT"
] | null | null | null |
Example/VandMarvelUIKit/Features/CharacterDisplayCompact/CharacterDisplayCompactView.swift
|
Vandcarlos/VandMarvelUIKit
|
e065912b1107f02ff8665b715b82e17866d6528b
|
[
"MIT"
] | null | null | null |
Example/VandMarvelUIKit/Features/CharacterDisplayCompact/CharacterDisplayCompactView.swift
|
Vandcarlos/VandMarvelUIKit
|
e065912b1107f02ff8665b715b82e17866d6528b
|
[
"MIT"
] | null | null | null |
// Created on 20/01/21. Copyright © 2021 Vand. All rights reserved.
import VandMarvelUIKit
class CharacterDisplayCompactView: UIView, VMViewCode {
init() {
super.init(frame: .zero)
setupView()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private let contentStackView: UIStackView = {
let stackVew = UIStackView()
stackVew.axis = .vertical
stackVew.alignment = .center
stackVew.spacing = 20
return stackVew
}()
private let characterDisplay = VMCharacterDisplayCompactView()
private let characterDisplayLoading = VMCharacterDisplayCompactView()
func buildHierarchy() {
contentStackView.addArrangedSubview(characterDisplay)
contentStackView.addArrangedSubview(characterDisplayLoading)
contentStackView.addSpace()
addSubview(contentStackView)
}
func setupConstraints() {
contentStackView.snp.makeConstraints { maker in
maker.edges.equalTo(self.safeAreaLayoutGuide)
}
characterDisplay.snp.makeConstraints { maker in
maker.height.equalTo(150)
}
characterDisplayLoading.snp.makeConstraints { maker in
maker.height.equalTo(150)
}
}
func configViews() {
backgroundColor = .white
characterDisplay.thumbnail = UIImage(named: "iron_man")
characterDisplay.name = "Character display"
characterDisplay.favoriteHandler = {
debugPrint("Character display")
}
characterDisplayLoading.isLoading = true
}
}
| 26.467742
| 73
| 0.657526
|
65187e773e47dcccf92a75e8f5823adebf4bbc86
| 2,046
|
css
|
CSS
|
assets/css/chart.css
|
zhanglina0902/Group-project
|
dd4a4fcb1b1c6621b6a150e3304f50da34e03859
|
[
"MIT"
] | null | null | null |
assets/css/chart.css
|
zhanglina0902/Group-project
|
dd4a4fcb1b1c6621b6a150e3304f50da34e03859
|
[
"MIT"
] | null | null | null |
assets/css/chart.css
|
zhanglina0902/Group-project
|
dd4a4fcb1b1c6621b6a150e3304f50da34e03859
|
[
"MIT"
] | null | null | null |
.tpl-portlet-components {
border: 1px solid #e7ecf1;
padding: 12px 20px 15px;
background-color: #fff;
margin-top: 0;
margin-bottom: 25px;
overflow: hidden;
}
.tpl-portlet-components .portlet-title {
border-bottom: 1px solid #eef1f5;
padding: 0;
min-height: 48px;
margin-bottom: 10px;
}
.tpl-portlet-components .portlet-title .caption {
float: left;
display: inline-block;
font-size: 18px;
line-height: 18px;
color: #666;
padding: 10px 0;
}
.tpl-portlet-input {
float: right;
display: inline-block;
padding: 4px 0;
}
.input-icon.right {
left: auto;
right: 0;
}
.input-inline {
display: inline-block;
width: auto;
vertical-align: middle;
}
.input-small {
width: 145px!important;
}
.input-icon {
position: relative;
left: 0;
}
.input-icon i {
font-size: 14px;
margin-top: 9px;
}
.input-icon>i {
color: #ccc;
position: absolute;
margin-top: 2px;
z-index: 3;
width: 16px;
font-size: 16px;
text-align: center;
left: 0;
left: auto;
right: 8px;
float: right;
}
.form-control {
display: block;
width: 100%;
height: 34px;
padding: 6px 12px;
font-size: 14px;
line-height: 1.42857;
color: #4d6b8a;
background-color: #fff;
background-image: none;
border: 1px solid #c2cad8;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
-o-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s;
outline: none;
}
.form-control {
height: 30px;
padding: 2px 26px 3px 10px;
font-size: 13px;
}
.tpl-chart-mb {
margin-top: 20px;
margin-bottom: 40px;
}
.tpl-echarts {
width: 100%;
min-height: 400px;
}
.tpl-scrollable {
width: 100%;
min-height: 400px;
}
| 19.485714
| 85
| 0.614858
|
ee2950e0bdd4cb4f7d520bb8b9b3a06f422f232f
| 4,235
|
rb
|
Ruby
|
app/models/cell_metadatum.rb
|
ssabrii/single_cell_portal_core
|
76de2d18e0283c5e4f6b311c87bf718398826a41
|
[
"BSD-3-Clause"
] | null | null | null |
app/models/cell_metadatum.rb
|
ssabrii/single_cell_portal_core
|
76de2d18e0283c5e4f6b311c87bf718398826a41
|
[
"BSD-3-Clause"
] | null | null | null |
app/models/cell_metadatum.rb
|
ssabrii/single_cell_portal_core
|
76de2d18e0283c5e4f6b311c87bf718398826a41
|
[
"BSD-3-Clause"
] | null | null | null |
class CellMetadatum
include Mongoid::Document
# Constants for scoping values for AnalysisParameter inputs/outputs
ASSOCIATED_MODEL_METHOD = %w(name annotation_type)
ASSOCIATED_MODEL_DISPLAY_METHOD = %w(name annotation_type)
OUTPUT_ASSOCIATION_ATTRIBUTE = %w(study_file_id)
ANALYSIS_PARAMETER_FILTERS = {
'annotation_type' => %w(group numeric)
}
belongs_to :study
belongs_to :study_file
has_many :data_arrays, as: :linear_data
field :name, type: String
field :annotation_type, type: String
field :values, type: Array
index({ name: 1, annotation_type: 1, study_id: 1 }, { unique: true, background: true })
index({ study_id: 1 }, { unique: false, background: true })
index({ study_id: 1, study_file_id: 1 }, { unique: false, background: true })
validates_uniqueness_of :name, scope: [:study_id, :annotation_type]
validates_presence_of :name, :annotation_type
##
# INSTANCE METHODS
##
# concatenate all the necessary data_array objects and construct a hash of cell names => expression values
def cell_annotations
cells = self.study.all_cells_array
annot_values = self.concatenate_data_arrays(self.name, 'annotations')
Hash[cells.zip(annot_values)]
end
# concatenate data arrays of a given name/type in order
def concatenate_data_arrays(array_name, array_type)
data_arrays = DataArray.where(name: array_name, array_type: array_type, linear_data_type: 'CellMetadatum',
linear_data_id: self.id).order(:array_index => 'asc')
all_values = []
data_arrays.each do |array|
all_values += array.values
end
all_values
end
# generate a select box option for use in dropdowns that corresponds to this cell_metadatum
def annotation_select_option
[self.name, "#{self.name}--#{self.annotation_type}--study"]
end
##
#
# CLASS INSTANCE METHODS
#
##
# generate new entries based on existing StudyMetadata objects
def self.generate_new_entries
start_time = Time.zone.now
arrays_created = 0
# we only want to generate the list of 'All Cells' once per study, so do that first
Study.all.each do |study|
all_cells = study.all_cells
all_cells.each_slice(DataArray::MAX_ENTRIES).with_index do |slice, index|
cell_array = study.data_arrays.build(study_file_id: study.metadata_file.id, name: 'All Cells',
cluster_name: study.metadata_file.name, array_type: 'cells',
array_index: index + 1, values: slice, study_id: study.id)
cell_array.save
end
end
records = []
StudyMetadatum.all.each do |study_metadatum|
cell_metadatum = CellMetadatum.create(study_id: study_metadatum.study_id, study_file_id: study_metadatum.study_file_id,
name: study_metadatum.name, annotation_type: study_metadatum.annotation_type,
values: study_metadatum.values)
annot_values = study_metadatum.cell_annotations.values
annot_values.each_slice(DataArray::MAX_ENTRIES).with_index do |slice, index|
records << {name: study_metadatum.name, cluster_name: cell_metadatum.study_file.name, array_type: 'annotations',
array_index: index + 1, values: slice, study_id: cell_metadatum.study_id,
study_file_id: cell_metadatum.study_file_id, linear_data_id: cell_metadatum.id,
linear_data_type: 'CellMetadatum'
}
end
if records.size >= 1000
DataArray.create(records)
arrays_created += records.size
records = []
end
end
DataArray.create(records)
arrays_created += records.size
end_time = Time.zone.now
seconds_diff = (start_time - end_time).to_i.abs
hours = seconds_diff / 3600
seconds_diff -= hours * 3600
minutes = seconds_diff / 60
seconds_diff -= minutes * 60
seconds = seconds_diff
msg = "Cell Metadata migration complete: generated #{self.count} new entries with #{arrays_created} child data_arrays; elapsed time: #{hours} hours, #{minutes} minutes, #{seconds} seconds"
Rails.logger.info msg
msg
end
end
| 38.853211
| 192
| 0.681936
|
60cec9d146df3abbcc803e8e909e46dc13363755
| 149
|
sql
|
SQL
|
src/corpwatch_cleanup.sql
|
ANCIR/mozambique
|
6a1f07a9c3911e3f5bdeea995ad0e10cad1046bf
|
[
"MIT"
] | 16
|
2015-03-12T14:44:59.000Z
|
2021-10-09T00:30:31.000Z
|
src/corpwatch_cleanup.sql
|
4bic/scraper_Mozmbq
|
0043c84aa497ada532b82e2ac74ad5543cb3205d
|
[
"MIT"
] | null | null | null |
src/corpwatch_cleanup.sql
|
4bic/scraper_Mozmbq
|
0043c84aa497ada532b82e2ac74ad5543cb3205d
|
[
"MIT"
] | 2
|
2015-07-09T17:26:32.000Z
|
2018-07-16T16:50:36.000Z
|
SELECT f_add_col('corpwatch_companies', 'company_name_norm', 'text');
UPDATE corpwatch_companies SET company_name_norm = f_mz_person(company_name);
| 37.25
| 77
| 0.825503
|
75b081edb83168392d37903a01e8407365272399
| 2,899
|
css
|
CSS
|
js/addOns/adyen.cardtype.css
|
rvanlaak/CSE-JS
|
256b8495aa5d87508852a78db78e359e4ba755bc
|
[
"MIT"
] | null | null | null |
js/addOns/adyen.cardtype.css
|
rvanlaak/CSE-JS
|
256b8495aa5d87508852a78db78e359e4ba755bc
|
[
"MIT"
] | null | null | null |
js/addOns/adyen.cardtype.css
|
rvanlaak/CSE-JS
|
256b8495aa5d87508852a78db78e359e4ba755bc
|
[
"MIT"
] | 2
|
2016-09-12T20:06:02.000Z
|
2018-12-20T07:56:25.000Z
|
/* In case you want to show the icon and the friendly name */
#cardType {
min-height: 14px;
padding-left: 27px;
background-repeat: no-repeat;
}
/* In case you only want to show the icon */
#cardType {
height: 14px;
width: 25px;
background-repeat: no-repeat;
}
#cardType .cse-cardtype-label {
display: none;
}
/* The icons of various card types */
#cardType.cse-cardtype-mc {
background-image: url(https://live.adyen.com/hpp/img/pm/mc_tiny.png);
}
#cardType.cse-cardtype-visadankort {
background-image: url(https://live.adyen.com/hpp/img/pm/visadankort_tiny.png);
}
#cardType.cse-cardtype-visa {
background-image: url(https://live.adyen.com/hpp/img/pm/visa_tiny.png);
}
#cardType.cse-cardtype-amex {
background-image: url(https://live.adyen.com/hpp/img/pm/amex_tiny.png);
}
#cardType.cse-cardtype-vias {
background-image: url(https://live.adyen.com/hpp/img/pm/vias_tiny.png);
}
#cardType.cse-cardtype-diners {
background-image: url(https://live.adyen.com/hpp/img/pm/diners_tiny.png);
}
#cardType.cse-cardtype-maestrouk {
background-image: url(https://live.adyen.com/hpp/img/pm/maestrouk_tiny.png);
}
#cardType.cse-cardtype-solo {
background-image: url(https://live.adyen.com/hpp/img/pm/solo_tiny.png);
}
#cardType.cse-cardtype-laser {
background-image: url(https://live.adyen.com/hpp/img/pm/laser_tiny.png);
}
#cardType.cse-cardtype-discover {
background-image: url(https://live.adyen.com/hpp/img/pm/discover_tiny.png);
}
#cardType.cse-cardtype-jcb {
background-image: url(https://live.adyen.com/hpp/img/pm/jcb_tiny.png);
}
#cardType.cse-cardtype-bcmc {
background-image: url(https://live.adyen.com/hpp/img/pm/bcmc_tiny.png);
}
#cardType.cse-cardtype-bijcard {
background-image: url(https://live.adyen.com/hpp/img/pm/bijcard_tiny.png);
}
#cardType.cse-cardtype-dankort {
background-image: url(https://live.adyen.com/hpp/img/pm/dankort_tiny.png);
}
#cardType.cse-cardtype-hipercard {
background-image: url(https://live.adyen.com/hpp/img/pm/hipercard_tiny.png);
}
#cardType.cse-cardtype-maestro {
background-image: url(https://live.adyen.com/hpp/img/pm/maestro_tiny.png);
}
#cardType.cse-cardtype-elo {
background-image: url(https://live.adyen.com/hpp/img/pm/elo_tiny.png);
}
#cardType.cse-cardtype-uatp {
background-image: url(https://live.adyen.com/hpp/img/pm/uatp_tiny.png);
}
#cardType.cse-cardtype-cup {
background-image: url(https://live.adyen.com/hpp/img/pm/cup_tiny.png);
}
#cardType.cse-cardtype-cartebancaire {
background-image: url(https://live.adyen.com/hpp/img/pm/cartebancaire_tiny.png);
}
#cardType.cse-cardtype-visaalphabankbonus {
background-image: url(https://live.adyen.com/hpp/img/pm/visaalphabankbonus_tiny.png);
}
#cardType.cse-cardtype-mcalphabankbonus {
background-image: url(https://live.adyen.com/hpp/img/pm/mcalphabankbonus_tiny.png);
}
| 27.875
| 89
| 0.720248
|
2ca71f97088aba9ec01a7b75f91a42c6d88e697a
| 596
|
py
|
Python
|
transforms.py
|
dscarmo/IA376J_final_project
|
33422bc6da29dd8a664f61e98d34c0c0057e7598
|
[
"MIT"
] | 1
|
2020-12-13T05:05:24.000Z
|
2020-12-13T05:05:24.000Z
|
transforms.py
|
dscarmo/IA376J_final_project
|
33422bc6da29dd8a664f61e98d34c0c0057e7598
|
[
"MIT"
] | null | null | null |
transforms.py
|
dscarmo/IA376J_final_project
|
33422bc6da29dd8a664f61e98d34c0c0057e7598
|
[
"MIT"
] | null | null | null |
from torchvision import transforms
def get_transform(transform_str):
transform = None
if transform_str == "baseline":
transform = transforms.Compose([transforms.ToPILImage(),
transforms.Resize((512, 256)),
transforms.ToTensor()])
elif transform_str == "base":
transform = transforms.Compose([transforms.ToPILImage(),
transforms.Resize((1024, 512)),
transforms.ToTensor()])
return transform, transform
| 37.25
| 71
| 0.526846
|
e47ebea76935b542b01141001b2120f7e5d5a0b8
| 2,095
|
h
|
C
|
tests/CompileTests/PythonExample_tests/pythonDir/methodobject.h
|
maurizioabba/rose
|
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
|
[
"BSD-3-Clause"
] | 488
|
2015-01-09T08:54:48.000Z
|
2022-03-30T07:15:46.000Z
|
tests/CompileTests/PythonExample_tests/pythonDir/methodobject.h
|
sujankh/rose-matlab
|
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
|
[
"BSD-3-Clause"
] | 174
|
2015-01-28T18:41:32.000Z
|
2022-03-31T16:51:05.000Z
|
tests/CompileTests/PythonExample_tests/pythonDir/methodobject.h
|
sujankh/rose-matlab
|
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
|
[
"BSD-3-Clause"
] | 146
|
2015-04-27T02:48:34.000Z
|
2022-03-04T07:32:53.000Z
|
/* Method object interface */
#ifndef Py_METHODOBJECT_H
#define Py_METHODOBJECT_H
#ifdef __cplusplus
extern "C" {
#endif
extern DL_IMPORT(PyTypeObject) PyCFunction_Type;
#define PyCFunction_Check(op) ((op)->ob_type == &PyCFunction_Type)
typedef PyObject *(*PyCFunction)(PyObject *, PyObject *);
typedef PyObject *(*PyCFunctionWithKeywords)(PyObject *, PyObject *,
PyObject *);
typedef PyObject *(*PyNoArgsFunction)(PyObject *);
extern DL_IMPORT(PyCFunction) PyCFunction_GetFunction(PyObject *);
extern DL_IMPORT(PyObject *) PyCFunction_GetSelf(PyObject *);
extern DL_IMPORT(int) PyCFunction_GetFlags(PyObject *);
/* Macros for direct access to these values. Type checks are *not*
done, so use with care. */
#define PyCFunction_GET_FUNCTION(func) \
(((PyCFunctionObject *)func) -> m_ml -> ml_meth)
#define PyCFunction_GET_SELF(func) \
(((PyCFunctionObject *)func) -> m_self)
#define PyCFunction_GET_FLAGS(func) \
(((PyCFunctionObject *)func) -> m_ml -> ml_flags)
extern DL_IMPORT(PyObject *) PyCFunction_Call(PyObject *, PyObject *, PyObject *);
struct PyMethodDef {
char *ml_name;
PyCFunction ml_meth;
int ml_flags;
char *ml_doc;
};
typedef struct PyMethodDef PyMethodDef;
extern DL_IMPORT(PyObject *) Py_FindMethod(PyMethodDef[], PyObject *, char *);
extern DL_IMPORT(PyObject *) PyCFunction_New(PyMethodDef *, PyObject *);
/* Flag passed to newmethodobject */
#define METH_OLDARGS 0x0000
#define METH_VARARGS 0x0001
#define METH_KEYWORDS 0x0002
/* METH_NOARGS and METH_O must not be combined with any other flag. */
#define METH_NOARGS 0x0004
#define METH_O 0x0008
typedef struct PyMethodChain {
PyMethodDef *methods; /* Methods of this type */
struct PyMethodChain *link; /* NULL or base type */
} PyMethodChain;
extern DL_IMPORT(PyObject *) Py_FindMethodInChain(PyMethodChain *, PyObject *,
char *);
typedef struct {
PyObject_HEAD
PyMethodDef *m_ml;
PyObject *m_self;
} PyCFunctionObject;
#ifdef __cplusplus
}
#endif
#endif /* !Py_METHODOBJECT_H */
| 29.507042
| 82
| 0.719332
|
8db4293136c1a35bfd355f13a9c0142c62f309e6
| 8,886
|
js
|
JavaScript
|
controllers/ScheduleController.js
|
workarounds/instilive
|
28d93c9e339dbc6700d1f7a412e1eba2eee1636e
|
[
"Apache-2.0"
] | 1
|
2017-02-06T17:43:02.000Z
|
2017-02-06T17:43:02.000Z
|
controllers/ScheduleController.js
|
workarounds/instilive
|
28d93c9e339dbc6700d1f7a412e1eba2eee1636e
|
[
"Apache-2.0"
] | null | null | null |
controllers/ScheduleController.js
|
workarounds/instilive
|
28d93c9e339dbc6700d1f7a412e1eba2eee1636e
|
[
"Apache-2.0"
] | null | null | null |
/**
* Created by manidesto on 05/12/14.
*/
(function () {
var app = angular.module('Vnb');
function getDateObj(s) {
var a = s.split(/[^0-9]/);
var d = new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
return d;
}
function isNextDay(d){
var now = new Date();
return (toDateId(now) <= toDateId(d));
}
function toDateId(d){
var date = d.getDate();
var month = d.getMonth();
var year = d.getYear();
return year*366 + month*31 + date;
}
app.controller('ScheduleController', [
'StateService',
'VnbModal',
'$scope',
'$rootScope',
function (StateService, VnbModal, $scope, $rootScope) {
var scheduleCtrl = this;
scheduleCtrl.notices = [];
scheduleCtrl.displayNotices = [];
scheduleCtrl.eventDays = {};
scheduleCtrl.nextDaySet = false;
scheduleCtrl.showPrevious = false;
scheduleCtrl.dataLoaded = false;
scheduleCtrl.loadingMore = false;
$scope.scheduleLimit = 1;
function generateEvents() {
scheduleCtrl.eventDays = {};
var notices = scheduleCtrl.notices;
var eventDays = scheduleCtrl.eventDays;
for (var i = 0; i < notices.length; i++) {
var start = getDateObj(notices[i].start_time);
if (eventDays[toDateId(start)] === undefined) {
eventDays[toDateId(start)] = {
date: start,
anchor:'',
next:false,
events: []
};
}
notices[i].start = start;
if(typeof notices[i].data === "string") {
notices[i].data = JSON.parse(notices[i].data);
}
if(typeof notices[i].data === "string") {
notices[i].corners = JSON.parse(notices[i].corners);
}
eventDays[toDateId(start)].events.push(notices[i]);
notices[i].next = isNextDay(start);
eventDays[toDateId(start)].next = notices[i].next;
if(!scheduleCtrl.nextDaySet){
if(isNextDay(start)){
eventDays[toDateId(start)].anchor = 'vnb-schedule-next-day';
scheduleCtrl.nextDaySet = true;
}
}
if(notices[i].next){
scheduleCtrl.displayNotices.push(notices[i]);
}
}
}
scheduleCtrl.getPrevious = function(){
if(scheduleCtrl.notices.length>0) {
var to = getDateObj(scheduleCtrl.notices[0].start_time);
var from = angular.copy(to);
to.setMinutes(to.getMinutes() -1);
from.setDate(from.getDate() -3);
var limit = 1000;
var options = {
from: from.getTime()/1000,
to: to.getTime()/1000,
limit: limit
};
}
else{
var from = '2014-12-11 23:59:59';
var limit = 1000;
var options = {
from: from,
limit: limit
};
}
scheduleCtrl.showPrevious = true;
scheduleCtrl.dataLoaded = false;
StateService.getSchedule(false, options, true).then(
function(data){
fillPrevious(data);
},
function(err){
console.log(err);
scheduleCtrl.dataLoaded = true;
scheduleCtrl.showPrevious = false;
StateService.showToast('Some error occurred. Please try again');
}
)
};
scheduleCtrl.loadMore = function(){
var last = scheduleCtrl.notices.length - 1;
var from;
if(last>=0) {
from = getDateObj(scheduleCtrl.notices[last].start_time);
}
else{
from = new Date();
}
from.setMinutes(from.getMinutes() + 1);
var options = {
from: from.getTime()/1000
};
scheduleCtrl.loadingMore = true;
StateService.getSchedule(false, options, true).then(
function(data){
fillMore(data);
},
function(err){
console.log(err);
scheduleCtrl.loadingMore = false;
StateService.showToast('Some error occurred. Please try again');
}
)
};
function fillMore(data){
var current = angular.copy(scheduleCtrl.notices);
var more = data.Notice;
if(more.length == 0){
scheduleCtrl.loadingMore = false;
StateService.showToast('Nothing more actually :P');
return;
}
scheduleCtrl.notices = [];
scheduleCtrl.notices = current.concat(more);
generateEvents();
scheduleCtrl.loadingMore = false;
setTimeout(increaseLimit, 200);
StateService.setSchedule({Notice: scheduleCtrl.notices});
}
function fillPrevious(data){
var previous = data.Notice;
if(previous.length == 0){
scheduleCtrl.dataLoaded = true;
scheduleCtrl.showPrevious = true;
StateService.showToast('We don\'t remember anything before that :P');
return;
}
var current = angular.copy(scheduleCtrl.notices);
scheduleCtrl.notices = [];
scheduleCtrl.notices = previous.concat(current);
generateEvents();
scheduleCtrl.showPrevious = false;
scheduleCtrl.scheduleLimit = 1;
scheduleCtrl.dataLoaded = true;
setTimeout(increaseLimit, 400);
StateService.setSchedule({Notice: scheduleCtrl.notices});
}
function increaseLimit(){
if($scope.scheduleLimit < scheduleCtrl.notices.length){
$scope.$apply(function(){
$scope.scheduleLimit = $scope.scheduleLimit + 1;
});
setTimeout(increaseLimit, 400);
}
}
function fillData(data){
scheduleCtrl.notices = data.Notice;
generateEvents();
scheduleCtrl.dataLoaded = true;
setTimeout(increaseLimit, 250);
}
function loadingFailed(){
console.log('error loading schedule');
scheduleCtrl.dataLoaded = true;
StateService.showToast('Could not load schedule');
}
StateService.getSchedule().then(
function (data) {
fillData(data);
},
function () {
loadingFailed();
}
);
$rootScope.$on('VnbReloadData', function(){
scheduleCtrl.dataLoaded = false;
StateService.getSchedule(false, false, true).then(
function(data){
scheduleCtrl.showPrevious = false;
fillData(data);
},
function(){
loadingFailed();
}
);
});
scheduleCtrl.showEvent = function(event) {
var modalParams = {
templateUrl: 'components/notice/updates.html',
controller: 'UpdatesController as updatesCtrl',
size: 'lg',
resolve: {
notice: function () {
return event;
}
},
state: '^.notice',
params: {notice: event.id}
};
VnbModal.openModal(modalParams);
};
}
]);
})();
| 36.871369
| 89
| 0.430452
|
e4eb977c0e25b2fd25b13f0cc1b27b334cf182b8
| 16,312
|
sql
|
SQL
|
nedimmed_tarim.sql
|
yaseminsekmen/tarim
|
4de0959f70706de583a9e21271dda0cfe60f04f9
|
[
"MIT"
] | null | null | null |
nedimmed_tarim.sql
|
yaseminsekmen/tarim
|
4de0959f70706de583a9e21271dda0cfe60f04f9
|
[
"MIT"
] | null | null | null |
nedimmed_tarim.sql
|
yaseminsekmen/tarim
|
4de0959f70706de583a9e21271dda0cfe60f04f9
|
[
"MIT"
] | null | null | null |
-- phpMyAdmin SQL Dump
-- version 4.0.4.2
-- http://www.phpmyadmin.net
--
-- Anamakine: localhost
-- Üretim Zamanı: 23 Eyl 2019, 21:43:36
-- Sunucu sürümü: 5.6.13
-- PHP Sürümü: 5.4.17
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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 utf8 */;
--
-- Veritabanı: `nedimmed_tarim`
--
CREATE DATABASE IF NOT EXISTS `nedimmed_tarim` DEFAULT CHARACTER SET utf8 COLLATE utf8_turkish_ci;
USE `nedimmed_tarim`;
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `admin`
--
CREATE TABLE IF NOT EXISTS `admin` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`admin_adi` varchar(50) COLLATE utf8_turkish_ci DEFAULT NULL,
`admin_sifre` varchar(50) COLLATE utf8_turkish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci ROW_FORMAT=COMPACT AUTO_INCREMENT=2 ;
--
-- Tablo döküm verisi `admin`
--
INSERT INTO `admin` (`id`, `admin_adi`, `admin_sifre`) VALUES
(1, 'admin', '1234');
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `anasayfa_ayarlari`
--
CREATE TABLE IF NOT EXISTS `anasayfa_ayarlari` (
`id` int(11) NOT NULL,
`title` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
`title_aciklama` varchar(1000) COLLATE utf8_turkish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci ROW_FORMAT=COMPACT;
--
-- Tablo döküm verisi `anasayfa_ayarlari`
--
INSERT INTO `anasayfa_ayarlari` (`id`, `title`, `title_aciklama`) VALUES
(0, 'Sitemize Hoş Geldiniz', '<p>Lorem ipsum dolor sit amet consectetur adipiscing elit sagittis urna a senectus pulvinar integer commodo, vivamus vel dui ante quisque felis fringilla viverra mollis venenatis porta libero mattis. In nullam vehicula facilisis vestibulum dignissim eget aptent nulla mattis donec risus, natoque auctor vulputate vivamus himenaeos sodales nisi gravida lacus metus, semper cras feugiat fermentum augue ligula condimentum montes convallis aenean. Sed hendrerit purus porta vehicula volutpat augue, diam commodo lacinia eget viverra euismod dapibus, penatibus pharetra iaculis condimentum est.</p>\r\n\r\n<p>Aenean praesent purus quam hac auctor gravida a nisi rutrum vel, hendrerit semper ridiculus convallis aptent volutpat conubia dictumst mus lacus, pretium placerat potenti ligula mollis sodales orci parturient ac. Venenatis imperdiet laoreet semper quisque vitae massa ligula, turpis nascetur porttitor ac purus posuere pulvinar, tincidunt urna senectus cursus blandit hendrerit. Pellentesque tincidu');
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `ayarlar`
--
CREATE TABLE IF NOT EXISTS `ayarlar` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`meta` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`keywords` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
`description` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`logo` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`telefon` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`fax` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`email` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`adres` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`maps` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`face` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`twitter` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`google` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`instagram` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`youtube` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`Calisma_saati1` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
`Calisma_saati2` varchar(255) COLLATE utf8_turkish_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci ROW_FORMAT=COMPACT AUTO_INCREMENT=2 ;
--
-- Tablo döküm verisi `ayarlar`
--
INSERT INTO `ayarlar` (`id`, `title`, `meta`, `keywords`, `description`, `logo`, `telefon`, `fax`, `email`, `adres`, `maps`, `face`, `twitter`, `google`, `instagram`, `youtube`, `Calisma_saati1`, `Calisma_saati2`) VALUES
(1, 'Tarım Sitesi', '', '', 'description ', 'logo.jpg', '02165558888', '', 'demo@outlook.com', 'Adana', 'https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d6376.036078226401!2d35.3367318908838!3d36.961626006837!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x152885f106bba293%3A0x17fa4bf6042577a8!2sDNC%20TARIM!5e0!3m2!1str!2str!4v156923240', 'https://www.facebook.com/', 'https://twitter.com/login?lang=tr', 'google', 'https://www.instagram.com/', '', 'Çalışma saatini giriniz', 'Çalışma saatini giriniz');
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `bayi`
--
CREATE TABLE IF NOT EXISTS `bayi` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bayi_adi` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
`bayi_aciklama` varchar(1000) COLLATE utf8_turkish_ci DEFAULT NULL,
`bayi_resim` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
`bayi_link` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
`bayilik_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=7 ;
--
-- Tablo döküm verisi `bayi`
--
INSERT INTO `bayi` (`id`, `bayi_adi`, `bayi_aciklama`, `bayi_resim`, `bayi_link`, `bayilik_id`) VALUES
(2, 'bayi.png', '<p><strong>Klasik Gübreler</strong><br />\r\nAzotlu Gübreler - Fosforlu ve Potasyumlu Gübreler - Kompoze Gübreler</p>\r\n\r\n<p><strong>Özel Gübreler</strong><br />\r\nSaf Gübreler - Damlama Sulama Gübreleri - Yaprak Gübreleri - Sıvı Gübreler - Organik Gübreler</p>\r\n', 'gubre2.jpg', '', 2),
(3, 'bayi1.png', '<h2><span style="font-size:13px">Mısır Tohumuları.</span></h2>\r\n\r\n<p>Ayçiçeği Tohumları</p>\r\n\r\n<p>Kanola Tohumları</p>\r\n\r\n<p>İnokulantlar Pamuk Tohumları</p>\r\n', 'product1.jpg', 'https://www.pioneer.com/web/site/turkey', 1),
(4, 'bayi2.png', '<p>sacd</p>\r\n', 'sunlight.jpg', 'sd', 1),
(5, 'icl.PNG', '<p>ICL, dünyanın en büyük mineral, tarım, mühendislik ve ziraat firmasıdır. 80 yılı aşkın deneyimi olan ICL, 180 ülkede faaliyet göstermekte ve yaklaşık 13000 kişiye istihdam sağlamaktadır</p>\r\n', 'b83f8b6c76e0ef3aebbf5b9ac09ae4dd3.jpg', 'http://www.icl-group.com/', 2),
(6, 'bon.png', '<p>En yüksek kalite standartlarında üretilen Bontera ürünleri,% 100 organik olarak elde edilmektedir. Sentetik kimyasallardan ve genetiği değiştirilmiş organizmalardan aridirler ve tüm sürdürülebilir ve organik yetiştirme yöntemleriyle tamamen uyumludurlar. Geleneksel tarım içinde kullanıldığında, Bontera üreticilerin kimyasal gübre kullanımlarını azaltmalarına izin verir. Bontera insanlar, hayvanlar ve çevre için güvenlidir.</p>\r\n', 'do.jpg', 'https://bontera.com/', 4);
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `bayilik`
--
CREATE TABLE IF NOT EXISTS `bayilik` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`bayilik_adi` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
`header_resim` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=5 ;
--
-- Tablo döküm verisi `bayilik`
--
INSERT INTO `bayilik` (`id`, `bayilik_adi`, `header_resim`) VALUES
(1, 'Tohum Bayilikleri', 'tohum.png'),
(2, 'Gübre Bayilikleri', 'gubre.jpg'),
(4, 'Zirai İlaç Bayilikleri', 'gubre21.jpg');
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `hakkimizda`
--
CREATE TABLE IF NOT EXISTS `hakkimizda` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`hakkimizda_aciklama` varchar(6000) COLLATE utf8_turkish_ci DEFAULT NULL,
`resim` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci;
--
-- Tablo döküm verisi `hakkimizda`
--
INSERT INTO `hakkimizda` (`id`, `hakkimizda_aciklama`, `resim`) VALUES
(1, '<p>Lorem ipsum dolor sit amet consectetur adipiscing elit sagittis urna a senectus pulvinar integer commodo, vivamus vel dui ante quisque felis fringilla viverra mollis venenatis porta libero mattis. In nullam vehicula facilisis vestibulum dignissim eget aptent nulla mattis donec risus, natoque auctor vulputate vivamus himenaeos sodales nisi gravida lacus metus, semper cras feugiat fermentum augue ligula condimentum montes convallis aenean. Sed hendrerit purus porta vehicula volutpat augue, diam commodo lacinia eget viverra euismod dapibus, penatibus pharetra iaculis condimentum est.</p>\r\n\r\n<p>Aenean praesent purus quam hac auctor gravida a nisi rutrum vel, hendrerit semper ridiculus convallis aptent volutpat conubia dictumst mus lacus, pretium placerat potenti ligula mollis sodales orci parturient ac. Venenatis imperdiet laoreet semper quisque vitae massa ligula, turpis nascetur porttitor ac purus posuere pulvinar, tincidunt urna senectus cursus blandit hendrerit. Pellentesque tincidunt sodales erat arcu eu porttitor laoreet, dis auctor fringilla faucibus tristique convallis aliquet nam, iaculis mattis ligula at ac habitasse.</p>\r\n', 'ban1.png');
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `hizmetlerimiz`
--
CREATE TABLE IF NOT EXISTS `hizmetlerimiz` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`hizmet_adi` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
`hizmet_aciklama` varchar(6000) COLLATE utf8_turkish_ci DEFAULT NULL,
`hizmet_resim` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=3 ;
--
-- Tablo döküm verisi `hizmetlerimiz`
--
INSERT INTO `hizmetlerimiz` (`id`, `hizmet_adi`, `hizmet_aciklama`, `hizmet_resim`) VALUES
(1, 'Tarla ve Bahçe Ürünleri Danışmanlığı', '<p>Lorem ipsum dolor sit amet consectetur adipiscing elit sagittis urna a senectus pulvinar integer commodo, vivamus vel dui ante quisque felis fringilla viverra mollis venenatis porta libero mattis. In nullam vehicula facilisis vestibulum dignissim eget aptent nulla mattis donec risus, natoque auctor vulputate vivamus himenaeos sodales nisi gravida lacus metus, semper cras feugiat fermentum augue ligula condimentum montes convallis aenean. Sed hendrerit purus porta vehicula volutpat augue, diam commodo lacinia eget viverra euismod dapibus, penatibus pharetra iaculis condimentum est.</p>\r\n\r\n<p>Aenean praesent purus quam hac auctor gravida a nisi rutrum vel, hendrerit semper ridiculus convallis aptent volutpat conubia dictumst mus lacus, pretium placerat potenti ligula mollis sodales orci parturient ac. Venenatis imperdiet laoreet semper quisque vitae massa ligula, turpis nascetur porttitor ac purus posuere pulvinar, tincidunt urna senectus cursus blandit hendrerit. Pellentesque tincidunt sodales erat arcu eu porttitor laoreet, dis auctor fringilla faucibus tristique convallis aliquet nam, iaculis mattis ligula at ac habitasse.</p>\r\n', 'product11.jpg'),
(2, 'Tohum, Gübre ve Zirai İlaç Satışı', '<p>Lorem ipsum dolor sit amet consectetur adipiscing elit sagittis urna a senectus pulvinar integer commodo, vivamus vel dui ante quisque felis fringilla viverra mollis venenatis porta libero mattis. In nullam vehicula facilisis vestibulum dignissim eget aptent nulla mattis donec risus, natoque auctor vulputate vivamus himenaeos sodales nisi gravida lacus metus, semper cras feugiat fermentum augue ligula condimentum montes convallis aenean. Sed hendrerit purus porta vehicula volutpat augue, diam commodo lacinia eget viverra euismod dapibus, penatibus pharetra iaculis condimentum est.</p>\r\n\r\n<p>Aenean praesent purus quam hac auctor gravida a nisi rutrum vel, hendrerit semper ridiculus convallis aptent volutpat conubia dictumst mus lacus, pretium placerat potenti ligula mollis sodales orci parturient ac. Venenatis imperdiet laoreet semper quisque vitae massa ligula, turpis nascetur porttitor ac purus posuere pulvinar, tincidunt urna senectus cursus blandit hendrerit. Pellentesque tincidunt sodales erat arcu eu porttitor laoreet, dis auctor fringilla faucibus tristique convallis aliquet nam, iaculis mattis ligula at ac habitasse.</p>\r\n', 'gubre22.jpg');
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `hizmet_resim`
--
CREATE TABLE IF NOT EXISTS `hizmet_resim` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`header_resim` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
`hizmet_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=15 ;
--
-- Tablo döküm verisi `hizmet_resim`
--
INSERT INTO `hizmet_resim` (`id`, `header_resim`, `hizmet_id`) VALUES
(13, 'bugday5.jpg', 1),
(14, 'b83f8b6c76e0ef3aebbf5b9ac09ae4dd2.jpg', 2);
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `menu`
--
CREATE TABLE IF NOT EXISTS `menu` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`menu_adi` varchar(50) COLLATE utf8_turkish_ci DEFAULT NULL,
`menu_durum` varchar(50) COLLATE utf8_turkish_ci DEFAULT NULL,
`resim` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci ROW_FORMAT=COMPACT AUTO_INCREMENT=5 ;
--
-- Tablo döküm verisi `menu`
--
INSERT INTO `menu` (`id`, `menu_adi`, `menu_durum`, `resim`) VALUES
(1, 'Hakkımızda', 'Aktif', 'sa.jpg'),
(2, 'Hizmetlerimiz', 'Aktif', 'mi2.jpg'),
(3, 'Bayilikler', 'Aktif', 'mi3.jpg'),
(4, 'İletişim', 'Aktif', 'bu5.jpg');
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `mini`
--
CREATE TABLE IF NOT EXISTS `mini` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tohum` varchar(1000) COLLATE utf8_turkish_ci DEFAULT NULL,
`gubre` varchar(1000) COLLATE utf8_turkish_ci DEFAULT NULL,
`ilac` varchar(1000) COLLATE utf8_turkish_ci DEFAULT NULL,
`sera` varchar(1000) COLLATE utf8_turkish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci;
--
-- Tablo döküm verisi `mini`
--
INSERT INTO `mini` (`id`, `tohum`, `gubre`, `ilac`, `sera`) VALUES
(1, '<p>Mısır Tohumları, Ayçiçeği Tohumları, Kanola Tohumları, Pamuk Tohumları, Soya Tohumu, Tohumluk Arpa</p>\r\n', '<p>Katı Gübreler, Sıvı Gübreler,Toz Gübreler, Organik Gübreler, Özel Gübreler</p>\r\n', '<p>Feromonlar, İnsektisitler, Fungisitler, Herbisitler, Tohum İlaçları, Çevre Sağlığı</p>\r\n', '<p>Sera örtüleri, Malç Sera Filmleri, Solarizasyon Örtüleri, Isı Perde Örtüleri, Sulama Hortumları, Fide ve Gübre Torbaları</p>\r\n');
-- --------------------------------------------------------
--
-- Tablo için tablo yapısı `slider`
--
CREATE TABLE IF NOT EXISTS `slider` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`slogan` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
`slogan2` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
`resim` varchar(255) COLLATE utf8_turkish_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=4 ;
--
-- Tablo döküm verisi `slider`
--
INSERT INTO `slider` (`id`, `slogan`, `slogan2`, `resim`) VALUES
(1, 'Siz Yetiştirin,BİZ KORUYALIM!', 'Zirai İlaçlamada Türkiye''nin Lider Markaların Bayilikleri ve Ürün Destek Satışları Siz Yetiştirin,BİZ KORUYALIM!', 'pa.jpg'),
(2, 'Toğrağın KALBİNDE ÇALIŞIYORUZ', ''''' Önce Tohum '''' Sloganı İle, En kaliteli tohumları en uyguna fiyatlara size sunmaktadır.', 'bu.jpg'),
(3, 'Bin bir emek, bin bir zahmet; düzgün tohum, bol bereket.', 'Emek olmadan yemek olmaz.', 'ka3.jpg');
/*!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 */;
| 57.43662
| 1,221
| 0.730996
|
bf7101e96a0b389ca5226c79f86818ee159372fe
| 11,991
|
go
|
Go
|
pkg/security/v1beta1/authorizationpolicy_types.go
|
shanchunyang0919/istio-client-go
|
15d1d53f2857eb232484070b3b6106de70677f27
|
[
"Apache-2.0"
] | 12
|
2019-10-30T15:23:39.000Z
|
2022-02-09T11:08:29.000Z
|
pkg/security/v1beta1/authorizationpolicy_types.go
|
shanchunyang0919/istio-client-go
|
15d1d53f2857eb232484070b3b6106de70677f27
|
[
"Apache-2.0"
] | 3
|
2021-12-15T08:36:30.000Z
|
2022-02-15T15:54:18.000Z
|
pkg/security/v1beta1/authorizationpolicy_types.go
|
shanchunyang0919/istio-client-go
|
15d1d53f2857eb232484070b3b6106de70677f27
|
[
"Apache-2.0"
] | 3
|
2021-01-02T14:27:28.000Z
|
2021-12-14T15:25:25.000Z
|
// Copyright © 2020 Banzai Cloud
//
// 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 v1beta1
import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
selector "github.com/banzaicloud/istio-client-go/pkg/type/v1beta1"
)
// Istio Authorization Policy enables access control on workloads in the mesh.
//
// Authorization policy supports both allow and deny policies. When allow and
// deny policies are used for a workload at the same time, the deny policies are
// evaluated first. The evaluation is determined by the following rules:
//
// 1. If there are any DENY policies that match the request, deny the request.
// 2. If there are no ALLOW policies for the workload, allow the request.
// 3. If any of the ALLOW policies match the request, allow the request.
// 4. Deny the request.
//
// For example, the following authorization policy sets the `action` to "ALLOW"
// to create an allow policy. The default action is "ALLOW" but it is useful
// to be explicit in the policy.
//
// It allows requests from:
//
// - service account "cluster.local/ns/default/sa/sleep" or
// - namespace "test"
//
// to access the workload with:
//
// - "GET" method at paths of prefix "/info" or,
// - "POST" method at path "/data".
//
// when the request has a valid JWT token issued by "https://accounts.google.com".
//
// Any other requests will be denied.
//
// ```yaml
// apiVersion: security.istio.io/v1beta1
// kind: AuthorizationPolicy
// metadata:
// name: httpbin
// namespace: foo
// spec:
// action: ALLOW
// rules:
// - from:
// - source:
// principals: ["cluster.local/ns/default/sa/sleep"]
// - source:
// namespaces: ["test"]
// to:
// - operation:
// methods: ["GET"]
// paths: ["/info*"]
// - operation:
// methods: ["POST"]
// paths: ["/data"]
// when:
// - key: request.auth.claims[iss]
// values: ["https://accounts.google.com"]
// ```
//
// The following is another example that sets `action` to "DENY" to create a deny policy.
// It denies requests from the "dev" namespace to the "POST" method on all workloads
// in the "foo" namespace.
//
// ```yaml
// apiVersion: security.istio.io/v1beta1
// kind: AuthorizationPolicy
// metadata:
// name: httpbin
// namespace: foo
// spec:
// action: DENY
// rules:
// - from:
// - source:
// namespaces: ["dev"]
// to:
// - operation:
// methods: ["POST"]
// ```
//
// Authorization Policy scope (target) is determined by "metadata/namespace" and
// an optional "selector".
//
// - "metadata/namespace" tells which namespace the policy applies. If set to root
// namespace, the policy applies to all namespaces in a mesh.
// - workload "selector" can be used to further restrict where a policy applies.
//
// For example,
//
// The following authorization policy applies to workloads containing label
// "app: httpbin" in namespace bar.
//
// ```yaml
// apiVersion: security.istio.io/v1beta1
// kind: AuthorizationPolicy
// metadata:
// name: policy
// namespace: bar
// spec:
// selector:
// matchLabels:
// app: httpbin
// ```
//
// The following authorization policy applies to all workloads in namespace foo.
//
// ```yaml
// apiVersion: security.istio.io/v1beta1
// kind: AuthorizationPolicy
// metadata:
// name: policy
// namespace: foo
// spec:
// {}
// ```
//
// The following authorization policy applies to workloads containing label
// "version: v1" in all namespaces in the mesh. (Assuming the root namespace is
// configured to "istio-config").
//
// ```yaml
// apiVersion: security.istio.io/v1beta1
// kind: AuthorizationPolicy
// metadata:
// name: policy
// namespace: istio-config
// spec:
// selector:
// matchLabels:
// version: v1
// ```
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// AuthorizationPolicy
type AuthorizationPolicy struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec AuthorizationPolicySpec `json:"spec"`
}
// AuthorizationPolicy enables access control on workloads.
//
// For example, the following authorization policy denies all requests to workloads
// in namespace foo.
//
// ```yaml
// apiVersion: security.istio.io/v1beta1
// kind: AuthorizationPolicy
// metadata:
// name: deny-all
// namespace: foo
// spec:
// {}
// ```
//
// The following authorization policy allows all requests to workloads in namespace
// foo.
//
// ```yaml
// apiVersion: security.istio.io/v1beta1
// kind: AuthorizationPolicy
// metadata:
// name: allow-all
// namespace: foo
// spec:
// rules:
// - {}
// ```
type AuthorizationPolicySpec struct {
// Optional. Workload selector decides where to apply the authorization policy.
// If not set, the authorization policy will be applied to all workloads in the
// same namespace as the authorization policy.
Selector *selector.WorkloadSelector `json:"selector,omitempty"`
// Optional. A list of rules to match the request. A match occurs when at least
// one rule matches the request.
//
// If not set, the match will never occur. This is equivalent to setting a
// default of deny for the target workloads.
Rules []*Rule `json:"rules,omitempty"`
// Optional. The action to take if the request is matched with the rules.
Action AuthorizationPolicyAction `json:"action,omitempty"`
}
// Action specifies the operation to take.
type AuthorizationPolicyAction string
const (
// Allow a request only if it matches the rules. This is the default type.
AuthorizationPolicyActionAllow AuthorizationPolicyAction = "ALLOW"
// Deny a request if it matches any of the rules.
AuthorizationPolicyActionDeny AuthorizationPolicyAction = "DENY"
)
// Rule matches requests from a list of sources that perform a list of operations subject to a
// list of conditions. A match occurs when at least one source, operation and condition
// matches the request. An empty rule is always matched.
//
// Any string field in the rule supports Exact, Prefix, Suffix and Presence match:
//
// - Exact match: "abc" will match on value "abc".
// - Prefix match: "abc*" will match on value "abc" and "abcd".
// - Suffix match: "*abc" will match on value "abc" and "xabc".
// - Presence match: "*" will match when value is not empty.
type Rule struct {
// Optional. from specifies the source of a request.
//
// If not set, any source is allowed.
From []*RuleFrom `json:"from,omitempty"`
// Optional. to specifies the operation of a request.
//
// If not set, any operation is allowed.
To []*RuleTo `json:"to,omitempty"`
// Optional. when specifies a list of additional conditions of a request.
//
// If not set, any condition is allowed.
When []*Condition `json:"when,omitempty"`
}
// From includes a list or sources.
type RuleFrom struct {
// Source specifies the source of a request.
Source *Source `json:"source,omitempty"`
}
// To includes a list or operations.
type RuleTo struct {
// Operation specifies the operation of a request.
Operation *Operation `json:"operation,omitempty"`
}
// Source specifies the source identities of a request. Fields in the source are
// ANDed together.
//
// For example, the following source matches if the principal is "admin" or "dev"
// and the namespace is "prod" or "test" and the ip is not "1.2.3.4".
//
// ```yaml
// principals: ["admin", "dev"]
// namespaces: ["prod", "test"]
// not_ipblocks: ["1.2.3.4"]
// ```
type Source struct {
// Optional. A list of source peer identities (i.e. service account), which
// matches to the "source.principal" attribute. This field requires mTLS enabled.
//
// If not set, any principal is allowed.
Principals []string `json:"principals,omitempty"`
// Optional. A list of negative match of source peer identities.
NotPrincipals []string `json:"notPrincipals,omitempty"`
// Optional. A list of request identities (i.e. "iss/sub" claims), which
// matches to the "request.auth.principal" attribute.
//
// If not set, any request principal is allowed.
RequestPrincipals []string `json:"requestPrincipals,omitempty"`
// Optional. A list of negative match of request identities.
NotRequestPrincipals []string `json:"notRequestPrincipals,omitempty"`
// Optional. A list of namespaces, which matches to the "source.namespace"
// attribute. This field requires mTLS enabled.
//
// If not set, any namespace is allowed.
Namespaces []string `json:"namespaces,omitempty"`
// Optional. A list of negative match of namespaces.
NotNamespaces []string `json:"notNamespaces,omitempty"`
// Optional. A list of IP blocks, which matches to the "source.ip" attribute.
// Single IP (e.g. "1.2.3.4") and CIDR (e.g. "1.2.3.0/24") are supported.
//
// If not set, any IP is allowed.
IPBlocks []string `json:"ipBlocks,omitempty"`
// Optional. A list of negative match of IP blocks.
NotIPBlocks []string `json:"notIpBlocks,omitempty"`
}
// Operation specifies the operations of a request. Fields in the operation are
// ANDed together.
//
// For example, the following operation matches if the host has suffix ".example.com"
// and the method is "GET" or "HEAD" and the path doesn't have prefix "/admin".
//
// ```yaml
// hosts: ["*.example.com"]
// methods: ["GET", "HEAD"]
// not_paths: ["/admin*"]
// ```
type Operation struct {
// Optional. A list of hosts, which matches to the "request.host" attribute.
//
// If not set, any host is allowed. Must be used only with HTTP.
Hosts []string `json:"hosts,omitempty"`
// Optional. A list of negative match of hosts.
NotHosts []string `json:"notHosts,omitempty"`
// Optional. A list of ports, which matches to the "destination.port" attribute.
//
// If not set, any port is allowed.
Ports []string `json:"ports,omitempty"`
// Optional. A list of negative match of ports.
NotPorts []string `json:"notPorts,omitempty"`
// Optional. A list of methods, which matches to the "request.method" attribute.
// For gRPC service, this will always be "POST".
//
// If not set, any method is allowed. Must be used only with HTTP.
Methods []string `json:"methods,omitempty"`
// Optional. A list of negative match of methods.
NotMethods []string `json:"notMethods,omitempty"`
// Optional. A list of paths, which matches to the "request.url_path" attribute.
// For gRPC service, this will be the fully-qualified name in the form of
// "/package.service/method".
//
// If not set, any path is allowed. Must be used only with HTTP.
Paths []string `json:"paths,omitempty"`
// Optional. A list of negative match of paths.
NotPaths []string `json:"notPaths,omitempty"`
}
// Condition specifies additional required attributes.
type Condition struct {
// The name of an Istio attribute.
// See the [full list of supported attributes](https://istio.io/docs/reference/config/security/conditions/).
Key string `json:"key,omitempty"`
// Optional. A list of allowed values for the attribute.
// Note: at least one of values or not_values must be set.
Values []string `json:"values,omitempty"`
// Optional. A list of negative match of values for the attribute.
// Note: at least one of values or not_values must be set.
NotValues []string `json:"notValues,omitempty"`
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// AuthorizationPolicyList is a list of AuthorizationPolicy resources
type AuthorizationPolicyList struct {
metav1.TypeMeta `json:",inline"`
metav1.ListMeta `json:"metadata"`
Items []AuthorizationPolicy `json:"items"`
}
| 33.968839
| 109
| 0.703444
|
6177d00670098cb52087ae5e65bd5d1a550a3792
| 692
|
swift
|
Swift
|
FearlessUtils/Classes/Extrinsic/CryptoType+Extrinsic.swift
|
ERussel/fearless-utils-iOS
|
eee0e18b497227e149c8412d1fd5d0372b23fc40
|
[
"Apache-2.0"
] | 5
|
2020-09-24T10:24:20.000Z
|
2021-07-15T01:11:57.000Z
|
FearlessUtils/Classes/Extrinsic/CryptoType+Extrinsic.swift
|
ERussel/fearless-utils-iOS
|
eee0e18b497227e149c8412d1fd5d0372b23fc40
|
[
"Apache-2.0"
] | 5
|
2021-02-02T07:54:34.000Z
|
2021-09-28T20:02:12.000Z
|
FearlessUtils/Classes/Extrinsic/CryptoType+Extrinsic.swift
|
ERussel/fearless-utils-iOS
|
eee0e18b497227e149c8412d1fd5d0372b23fc40
|
[
"Apache-2.0"
] | 7
|
2021-01-18T03:39:49.000Z
|
2021-10-14T10:02:13.000Z
|
import Foundation
extension CryptoType {
init?(onChainType: UInt8) {
switch onChainType {
case 0:
self = .ed25519
case 1:
self = .sr25519
case 2:
self = .ecdsa
default:
return nil
}
}
var onChainType: UInt8 {
switch self {
case .sr25519:
return 1
case .ed25519:
return 0
case .ecdsa:
return 2
}
}
var signatureLength: Int {
switch self {
case .sr25519:
return 64
case .ed25519:
return 64
case .ecdsa:
return 65
}
}
}
| 17.74359
| 31
| 0.434971
|
b066d1ac766c0ae3624e333e173729750cc42a2a
| 10,420
|
py
|
Python
|
emi_measure.py
|
HongquanSu/find-roots-of-equations-in-Su-et-al-2018-479-4041
|
333ceb0ef2c63ea25d3a5cbe2b8e52e237f9939e
|
[
"MIT"
] | null | null | null |
emi_measure.py
|
HongquanSu/find-roots-of-equations-in-Su-et-al-2018-479-4041
|
333ceb0ef2c63ea25d3a5cbe2b8e52e237f9939e
|
[
"MIT"
] | null | null | null |
emi_measure.py
|
HongquanSu/find-roots-of-equations-in-Su-et-al-2018-479-4041
|
333ceb0ef2c63ea25d3a5cbe2b8e52e237f9939e
|
[
"MIT"
] | null | null | null |
from sympy import exp
from astropy import units as u
import numpy as np
from scipy.optimize import fsolve, root
import math as m
def convert_jyperbeam_k(v,bmaj=0.,bmin=0.,fits_img=None):
"""
calculate the conversion factor from Jy/beam to K
ref: http://docs.astropy.org/en/stable/api/astropy.units.brightness_temperature.html#astropy.units.brightness_temperature
this code give the same results as miriad imstat
:param v: MHz, the freqency of observation
:param bmaj: deg, the beam major angle
:param bmin: deg, the beam minor angle
:param fits_img: optional, the fits image to provide the bmaj and bmin
:return: the conversion factor from Jy/beam to K
"""
if fits_img != None:
fits_open = fits.open(fits_img)
head = fits_open[0].header
bmaj = head['BMAJ']
bmin = head['BMIN']
bmaj = bmaj*u.deg
bmin = bmin*u.deg
fwhm_to_sigma = 1./(8.*np.log(2.))**0.5
beam_area = 2.*np.pi*(bmaj*bmin*fwhm_to_sigma**2.)
freq = v*u.MHz
equiv = u.brightness_temperature(beam_area, freq)
return u.Jy.to(u.K, equivalencies=equiv)
def cal_tau_tb_write_3freq_no_cal_error_no_template(freq1, freq2, freq3, bmaj1, bmaj2, bmaj3, bmin1, bmin2, bmin3, hii1, hii2, hii3, bkg1, bkg2, bkg3, te, disf, disb, tt1_has, tt2_has, tt3_has):
"""
calculate the emissivity and optical depths of the target source
:param freq1: MHz, the central frequency of the first fits image
:param freq2: MHz, the central frequency of the second fits image
:param freq3: MHz, the central frequency of the third fits image
:param bmaj1: degree, the beam major axis length of the first fits image
:param bmaj2: degree, the beam major axis length of the second fits image
:param bmaj3: degree, the beam major axis length of the third fits image
:param bmin1: degree, the beam minor axis length of the first fits image
:param bmin2: degree, the beam minor axis length of the second fits image
:param bmin3: degree, the beam minor axis length of the third fits image
:param hii1: Jy, the flux density of the source region in the first image
:param hii2: Jy, the flux density of the source region in the second image
:param hii3: Jy, the flux density of the source region in the third image
:param bkg1: Jy, the flux density of the background region in the first image
:param bkg2: Jy, the flux density of the background region in the second image
:param bkg3: Jy, the flux density of the background region in the third image
:param te: K, the electron temperature of the target source
:param disf: kpc, the distance from the target source to the Sun
:param disb: kpc, the distance from the target source to the Galactic edge
:param tt1_has: K, the brightness temperature of the source region in the 408 MHz Haslam map scaled to freq1
:param tt2_has: K, the brightness temperature of the source region in the 408 MHz Haslam map scaled to freq2
:param tt3_has: K, the brightness temperature of the source region in the 408 MHz Haslam map scaled to freq3
:return: the optical depth (tau1, tau2, tau3),
the emissivity from the target source to the Galactic edge (emib1, emib2, emib3),
the emissivity from the target source to the Sun (emif1, emif2, emif3),
the missed surface brightness from the target source to the Galactic edge (xb1, xb2, xb3),
the missed surface brightness from the target source to the Sun (xf1, xf2, xf3).
"""
tau1_ini = np.arange(0.5, 3.0, 1.0)
tb1_ini = np.arange(5000., 50000., 20000.)
tf1_ini = np.arange(5000., 50000., 20000.)
xb1_ini = np.arange(5000., 50000., 20000.)
xf1_ini = np.arange(5000., 30000., 10000.)
print('Start calculating ...')
roots, z_sum_min = find_roots_3freq_no_template(hii1, hii2, hii3, te, bkg1, bkg2, bkg3, freq1, freq2, freq3, tt1_has, tt2_has, tt3_has, tau1_ini, tb1_ini, tf1_ini, xb1_ini, xf1_ini, si_syn=si_syn)
print('Calculation finished.')
# tau1, tau2, tau3, tb1, tb2, tb3, tf1, tf2, tf3, xb1, xb2, xb3, xf1, xf2, xf3
if roots is np.nan:
print('I could not find roots. Roots may not exist. I set all roots to be zeros.')
tau1, tau2, tau3, tb1, tb2, tb3, tf1, tf2, tf3, xb1, xb2, xb3, xf1, xf2, xf3 = np.zeros(15)
else:
tau1, tau2, tau3, tb1, tb2, tb3, tf1, tf2, tf3, xb1, xb2, xb3, xf1, xf2, xf3 = roots
emib1 = tb1 / disb / 1000.
emib2 = tb2 / disb / 1000.
emib3 = tb3 / disb / 1000.
emif1 = tf1 / disf / 1000.
emif2 = tf2 / disf / 1000.
emif3 = tf3 / disf / 1000.
return tau1, tau2, tau3, emib1, emib2, emib3, emif1, emif2, emif3, xb1, xb2, xb3, xf1, xf2, xf3
def find_roots_3freq_no_template(thii1, thii2, thii3, te, tm1, tm2, tm3, f1, f2, f3, tt1, tt2, tt3,
tau1_ini, tb1_ini, tf1_ini, xb1_ini, xf1_ini, si_syn):
def func(z):
"""
define the functions of emissivity calculation
:param z: the optical depths, brightness temperature
:param template: a vot file containing the best roots from previous calculation, use these roots as the best guess
if template == None, means no best guess provided, I will use several group of guesses to solve the equations
:return: the equation set
"""
tau1, tau2, tau3, tb1, tb2, tb3, tf1, tf2, tf3, xb1, xb2, xb3, xf1, xf2, xf3 = z
f = np.zeros(15) # len(f) = 15
f[0] = te * (1 - exp(-tau1)) + (tb1-xb1) * exp(-tau1) + tf1 - xf1 - thii1
f[1] = te * (1 - exp(-tau2)) + (tb2-xb2) * exp(-tau2) + tf2 - xf2 - thii2
f[2] = te * (1 - exp(-tau3)) + (tb3-xb3) * exp(-tau3) + tf3 - xf3 - thii3
f[3] = tt1 - xf1 - xb1 - tm1
f[4] = tt2 - xf2 - xb2 - tm2
f[5] = tt3 - xf3 - xb3 - tm3
f[6] = tf1 + tb1 - tt1
f[7] = tf2 + tb2 - tt2
f[8] = tf3 + tb3 - tt3
f[8] = tau2 / tau1 - (f2 / f1) ** si_tau
f[10] = tau3 / tau1 - (f3 / f1) ** si_tau
f[11] = tb2 / tb1 - (f2 / f1) ** si_syn
f[12] = tb3 / tb1 - (f3 / f1) ** si_syn
f[13] = tf2 / tf1 - (f2 / f1) ** si_syn
f[14] = tf3 / tf1 - (f3 / f1) ** si_syn
return f
# define the constants
b = (f2 / f1) ** si_tau
c = (f3 / f1) ** si_tau
d = (f2 / f1) ** si_syn
e = (f3 / f1) ** si_syn
# try different initial values of variables
z_sum_min = 1.e10
best_roots = np.zeros(15)
for i in tau1_ini:
for j in tb1_ini:
for k in tf1_ini:
for l in xb1_ini:
for m in xf1_ini:
init = np.array([i, j, k, l, m]) # tau1, tb1, tf1, x1
# initial guess of roots
x0 = np.array([init[0], b * init[0], c * init[0],
init[1], d * init[1], e * init[1],
init[2], d * init[2], e * init[2],
init[3], d * init[3], e * init[3],
init[4], d * init[4], e * init[4]])
# use fsolve to solve equations
# fslove: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.fsolve.html
roots, infodict, ier, mesg = fsolve(func, x0, xtol=1.49012e-30, full_output=True)
z_sum = np.sum(abs(func(roots)))
positive = roots > 0.001 # return an array of bool
if (z_sum_min > z_sum) and positive.all():
z_sum_min = z_sum
best_roots = roots
# check again if roots are real
if z_sum_min < 1.0:
return best_roots, z_sum_min
else:
print('I can not find roots.')
return np.nan, z_sum_min
if __name__ == '__main__':
###### inputs start ######
si_syn = -2.7
gr = 20. # kpc, the radius of the Galactic disk
si_tau = -2.1 # the spectral index of the HII region optical depth from Williams & Bridle, 1967, 87, 280
d_sun = 8.5 # the distance between the Sun and the Galactic center
freq1 = 76.155 # the central frequency of the first image in MHz
freq2 = 83.835 # the central frequency of the second image in MHz
freq3 = 91.515 # the central frequency of the third image in MHz
# the lengths of the beam major axis in degree for the three images
bmaj1 = 0.0901480006511
bmaj2 = 0.0796129599472
bmaj3 = 0.0724691295069
# the lengths of the beam minor axis in degree for the three images
bmin1 = 0.07376939297640001
bmin2 = 0.06484773213019999
bmin3 = 0.0589988644441
#######################################################
# Parameters below are for HII region G010.769-00.487 #
#######################################################
# the average surface brightness in the source region in unit of Jy/beam
hii1 = 3.530228640345904
hii2 = 2.678627432563366
hii3 = 2.1066876082322685
bkg1 = 6.99128526865497
bkg2 = 5.134549801612369
bkg3 = 3.7295525340899363
te = 5300 # electron temperature of the target source in unit of K
disf = 5.0 # distance from the target source to the Sun in unit of kpc
disb = 23.3 # distance from the target source to the Galactic edge along the line of sight in unit of kpc
tt1_has = 41591.707
tt2_has = 32088.1
tt3_has = 25325.809
###### inputs end ######
# find the roots
roots = cal_tau_tb_write_3freq_no_cal_error_no_template(freq1, freq2, freq3, bmaj1, bmaj2, bmaj3, bmin1, bmin2, bmin3, hii1, hii2, hii3, bkg1, bkg2, bkg3, te, disf, disb, tt1_has, tt2_has, tt3_has)
tau1, tau2, tau3, emib1, emib2, emib3, emif1, emif2, emif3, xb1, xb2, xb3, xf1, xf2, xf3 = roots
# compare the roots to confirm that your calculation is correct
print('The emissivities at three frequencies from the target source to the Galactic edge are:')
print('Expected emib1 = 1.14, you get', emib1)
print('Expected emib2 = 0.88, you get', emib2)
print('Expected emib3 = 0.69, you get', emib3)
print('The emissivities at three frequencies from the target source to the Sun are:')
print('Expected emif1 = 3.02, you get', emif1)
print('Expected emif2 = 2.33, you get', emif2)
print('Expected emif3 = 1.84, you get', emif3)
| 46.517857
| 201
| 0.614971
|
69fef1a670d6c389cc2d521bc4d2ae9624d10585
| 494
|
asm
|
Assembly
|
libsrc/adt/queue/adt_QueueCreate.asm
|
jpoikela/z88dk
|
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
|
[
"ClArtistic"
] | 640
|
2017-01-14T23:33:45.000Z
|
2022-03-30T11:28:42.000Z
|
libsrc/adt/queue/adt_QueueCreate.asm
|
jpoikela/z88dk
|
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
|
[
"ClArtistic"
] | 1,600
|
2017-01-15T16:12:02.000Z
|
2022-03-31T12:11:12.000Z
|
libsrc/adt/queue/adt_QueueCreate.asm
|
jpoikela/z88dk
|
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
|
[
"ClArtistic"
] | 215
|
2017-01-17T10:43:03.000Z
|
2022-03-23T17:25:02.000Z
|
; struct adt_Queue *adt_QueueCreate(void)
; 09.2005 aralbrec
SECTION code_clib
PUBLIC adt_QueueCreate
PUBLIC _adt_QueueCreate
EXTERN l_setmem
EXTERN _u_malloc
; exit : HL = struct adt_Queue * and carry set
; = 0 and nc if fail
.adt_QueueCreate
._adt_QueueCreate
ld hl,6 ; sizeof(struct adt_Queue)
push hl
call _u_malloc
pop de
ret nc ; ret with hl = 0 and nc if fail
ld e,l
ld d,h
xor a
call l_setmem-11
ex de,hl
scf
ret
| 16.466667
| 53
| 0.657895
|
5103a48749f101ebc1a64cfb6bc8d14ad39f531c
| 1,246
|
css
|
CSS
|
data/usercss/86845.user.css
|
33kk/uso-archive
|
2c4962d1d507ff0eaec6dcca555efc531b37a9b4
|
[
"MIT"
] | 118
|
2020-08-28T19:59:28.000Z
|
2022-03-26T16:28:40.000Z
|
data/usercss/86845.user.css
|
33kk/uso-archive
|
2c4962d1d507ff0eaec6dcca555efc531b37a9b4
|
[
"MIT"
] | 38
|
2020-09-02T01:08:45.000Z
|
2022-01-23T02:47:24.000Z
|
data/usercss/86845.user.css
|
33kk/uso-archive
|
2c4962d1d507ff0eaec6dcca555efc531b37a9b4
|
[
"MIT"
] | 21
|
2020-08-19T01:12:43.000Z
|
2022-03-15T21:55:17.000Z
|
/* ==UserStyle==
@name mp-weixin
@namespace USO Archive
@author alexzhan
@description `change styles of essays in mp.weixin.qq.com`
@version 20130505.8.4
@license NO-REDISTRIBUTION
@preprocessor uso
==/UserStyle== */
@-moz-document url-prefix("http://mp.weixin.qq.com/mp/appmsg"){
body{
background-color: #e7f4fe !important;
}
.text,.page-url{
background-color: #e7f4fe !important;
font-family:"Monaco","Courier New",Courier,monospace,宋体 !important;
font-size:20px !important;
word-spacing:.1em;
line-height:1.8 !important;
margin: 0 auto ;
width:60% !important;
color:black !important
}
p,p span,.text div,.text div div,.text p div,.text p p,.text div p,.text div span,.text p span{
background-color: #e7f4fe !important;
font-family:"Monaco","Courier New",Courier,monospace,宋体 !important;
font-size:20px !important;
word-spacing:.1em;
line-height:1.8 !important;
margin: 0;
width: 100% !important;
color:black !important
}
.header{
text-align:center
}
#activity-detail .page-content .media img{
max-width: 500px;
max-height: 500px;
margin: 0 auto ;
}
.ad{
display:none !important;
}
img{
display: block;
margin-left: auto;
margin-right: auto;
}
}
| 24.92
| 96
| 0.677368
|
e175afc3bf1af953e0225c0b357c337525f4e435
| 716
|
go
|
Go
|
utils/utils.go
|
rancher/network-policy-manager
|
4c4a004fe98a868d4e6966ca73d75f067dc815bb
|
[
"Apache-2.0"
] | 4
|
2017-04-27T07:26:28.000Z
|
2018-01-31T07:21:56.000Z
|
utils/utils.go
|
rancher/network-policy-manager
|
4c4a004fe98a868d4e6966ca73d75f067dc815bb
|
[
"Apache-2.0"
] | 5
|
2017-02-13T22:03:05.000Z
|
2020-07-31T16:37:24.000Z
|
utils/utils.go
|
rancher/network-policy-manager
|
4c4a004fe98a868d4e6966ca73d75f067dc815bb
|
[
"Apache-2.0"
] | 8
|
2017-02-08T22:48:20.000Z
|
2021-01-21T19:36:26.000Z
|
package utils
import (
"strings"
)
// ConvertToLocalLink checks if the given link is local and then converts
// to local format
// Valid local links:
// localRegionName/envName/stackName/serviceName
// envName/stackName/serviceName
func ConvertToLocalLink(link, regionName, envName string) (bool, string) {
words := strings.Split(link, "/")
if len(words) == 4 {
splits := strings.SplitAfter(link, regionName+"/"+envName+"/")
//log.Debugf("splits: %v", splits)
if len(splits) == 2 {
return true, splits[1]
}
} else if len(words) == 3 {
splits := strings.SplitAfter(link, envName+"/")
//log.Debugf("splits: %v", splits)
if len(splits) == 2 {
return true, splits[1]
}
}
return false, ""
}
| 24.689655
| 74
| 0.668994
|
ddd446b7f53d0920baa2da99cbc2cf1499270a6e
| 8,252
|
java
|
Java
|
cql/src/test/java/com/huawei/streaming/cql/executor/userdefined/WebFilterLogSpout.java
|
QiangCai/StreamCQL
|
f5a809c97cb6599ab0e18beb88fb98264c588b39
|
[
"Apache-2.0"
] | 1
|
2018-06-18T22:45:24.000Z
|
2018-06-18T22:45:24.000Z
|
cql/src/test/java/com/huawei/streaming/cql/executor/userdefined/WebFilterLogSpout.java
|
QiangCai/StreamCQL
|
f5a809c97cb6599ab0e18beb88fb98264c588b39
|
[
"Apache-2.0"
] | null | null | null |
cql/src/test/java/com/huawei/streaming/cql/executor/userdefined/WebFilterLogSpout.java
|
QiangCai/StreamCQL
|
f5a809c97cb6599ab0e18beb88fb98264c588b39
|
[
"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.
*/
package com.huawei.streaming.cql.executor.userdefined;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.BigEndianHeapChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.frame.FixedLengthFrameDecoder;
import org.jboss.netty.handler.codec.socks.SocksMessageEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.huawei.streaming.config.StreamingConfig;
import com.huawei.streaming.cql.CQLConst;
import com.huawei.streaming.exception.StreamingException;
import com.huawei.streaming.operator.IEmitter;
import com.huawei.streaming.operator.IInputStreamOperator;
import com.huawei.streaming.serde.StreamSerDe;
/**
* 起一个TCP的Server端,监听指定端口,接收数据
* 接收指定长度的数据
* 收到数据之后过滤并打印
*
*/
public class WebFilterLogSpout implements IInputStreamOperator
{
private static final long serialVersionUID = 6887440225527541244L;
private static final Logger LOG = LoggerFactory.getLogger(WebFilterLogSpout.class);
private static final int DEFAULT_LISTENER_PORT = 9999;
private static final int DEFAULT_FIXED_LENGTH = 883;
private int listenerPort = DEFAULT_LISTENER_PORT;
private int fixedLength = DEFAULT_FIXED_LENGTH;
private boolean isAlreadyStart = false;
private ServerBootstrap bootstrap = null;
private StreamingConfig config;
/**
* 设置配置属性
* 编译时接口
* 各种配置属性的缺失,可以在该阶段快速发现
*
*/
@Override
public void setConfig(StreamingConfig conf) throws StreamingException
{
listenerPort = conf.getIntValue("port");
fixedLength =conf.getIntValue("fixlength");
config = conf;
}
/**
* {@inheritDoc}
*/
@Override
public StreamingConfig getConfig()
{
return config;
}
/**
* {@inheritDoc}
*/
@Override
public void initialize()
throws StreamingException
{
}
/**
* {@inheritDoc}
*/
@Override
public void destroy()
throws StreamingException
{
if (bootstrap != null)
{
bootstrap.releaseExternalResources();
}
}
/**
* {@inheritDoc}
*/
@Override
public void execute()
throws StreamingException
{
if (isAlreadyStart)
{
return;
}
LOG.info("start to call execute.");
startNettyServer();
isAlreadyStart = true;
LOG.info("finished to call execute.");
}
/**
* 设置数据发送对象
* 运行时调用
*
*/
@Override
public void setEmitter(IEmitter emitter)
{
}
/**
* 设置序列化和反序列化类
*
*/
@Override
public void setSerDe(StreamSerDe serde)
{
}
/**
* 获取序列化和反序列化类
*
*/
@Override
public StreamSerDe getSerDe()
{
return null;
}
private void startNettyServer()
{
//storm要求spout要在同一个线程内执行emit和execute,以及acker,所以这里只能使用单线程
bootstrap =
new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),
Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(new ServerChannelPipelineFactory());
LOG.info("tcp server will start on {}", listenerPort);
bootstrap.bind(new InetSocketAddress(listenerPort));
}
/**
* netty channel factory
*
*/
private class ServerChannelPipelineFactory implements ChannelPipelineFactory
{
/**
* {@inheritDoc}
*/
@Override
public ChannelPipeline getPipeline()
throws Exception
{
ChannelPipeline pipleline = Channels.pipeline();
pipleline.addLast("encode", new SocksMessageEncoder());
pipleline.addLast("decode", new FixedLengthFrameDecoder(fixedLength));
pipleline.addLast("handler", new NettyServerHandler());
return pipleline;
}
}
/**
* server处理句柄
*
*/
private class NettyServerHandler extends SimpleChannelUpstreamHandler
{
/**
* {@inheritDoc}
*/
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception
{
BigEndianHeapChannelBuffer buffer = (BigEndianHeapChannelBuffer)e.getMessage();
byte[] bytes = buffer.array();
Object[] values = parseEDR(bytes);
if ("http://www.huawei.com".equals(values[1].toString()))
{
String sid = values[CQLConst.I_0].toString();
String host = values[CQLConst.I_1].toString();
String uri = values[CQLConst.I_2].toString();
LOG.info(sid + "," + host + "," + uri);
}
}
private Object[] parseEDR(byte[] bt)
{
Object[] starr = new Object[CQLConst.I_3];
int WEB_MESSAGE_MSISDN_OFFSET = 41;
int WEB_MESSAGE_MSISDN_LENGTH = 16;
int WEB_MESSAGE_HOST_OFFSET = 357;
int WEB_MESSAGE_HOST_LENGTH = 64;
int WEB_MESSAGE_FST_URI_OFFSET = 421;
int WEB_MESSAGE_FST_URI_LENGTH = 128;
char[] chs = new char[WEB_MESSAGE_MSISDN_LENGTH];
for (int i = WEB_MESSAGE_MSISDN_OFFSET; i < WEB_MESSAGE_MSISDN_OFFSET + WEB_MESSAGE_MSISDN_LENGTH; ++i)
{
if (bt[i] == 0x0)
{
break;
}
//sb1.append((char)bt[i]);
chs[i - WEB_MESSAGE_MSISDN_OFFSET] = (char)bt[i];
}
starr[0] = String.valueOf(chs).trim();
char[] chs2 = new char[WEB_MESSAGE_HOST_LENGTH];
for (int i = WEB_MESSAGE_HOST_OFFSET; i < WEB_MESSAGE_HOST_OFFSET + WEB_MESSAGE_HOST_LENGTH; ++i)
{
if (bt[i] == 0x0)
{
break;
}
chs2[i - WEB_MESSAGE_HOST_OFFSET] = (char)bt[i];
}
starr[1] = String.valueOf(chs2).trim();
char[] chs3 = new char[WEB_MESSAGE_FST_URI_LENGTH];
for (int i = WEB_MESSAGE_FST_URI_OFFSET; i < WEB_MESSAGE_FST_URI_OFFSET + WEB_MESSAGE_FST_URI_LENGTH; ++i)
{
if (bt[i] == 0x0)
{
break;
}
chs3[i - WEB_MESSAGE_FST_URI_OFFSET] = (char)bt[i];
}
starr[CQLConst.I_2] = String.valueOf(chs3).trim();
return starr;
}
/**
* {@inheritDoc}
*/
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e)
throws Exception
{
LOG.error("Client has an error,Error cause:" + e.getCause());
e.getChannel().close();
}
}
}
| 28.954386
| 118
| 0.606156
|
7f04ecfed0650731a4ca1d0e969ded205ec4c7f6
| 1,188
|
cs
|
C#
|
C# review/Interfaces/Interfaces/Interfaces/MasterCradCreditCard.cs
|
PabloGaspar/TecWeb-1-2021
|
7085c55e18d6ce916b1b82f1e512560ff010c9d8
|
[
"MIT"
] | null | null | null |
C# review/Interfaces/Interfaces/Interfaces/MasterCradCreditCard.cs
|
PabloGaspar/TecWeb-1-2021
|
7085c55e18d6ce916b1b82f1e512560ff010c9d8
|
[
"MIT"
] | null | null | null |
C# review/Interfaces/Interfaces/Interfaces/MasterCradCreditCard.cs
|
PabloGaspar/TecWeb-1-2021
|
7085c55e18d6ce916b1b82f1e512560ff010c9d8
|
[
"MIT"
] | 1
|
2021-02-18T23:25:23.000Z
|
2021-02-18T23:25:23.000Z
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Interfaces
{
public class MasterCradCreditCard : ICreditCard
{
private string owner;
private decimal maxAmount;
private const string brand = "Master Card";
public string Owner {
get { return owner; }
set { owner = value; }
}
public decimal MaxAmount
{
get { return maxAmount; }
set { maxAmount = value; }
}
public decimal CalculateInterest(decimal amount)
{
decimal interestFactor;
if (maxAmount > 1000)
{
interestFactor = 0.10m;
}
else
{
interestFactor = 0.05m;
}
return amount * interestFactor;
}
public string GetBrand()
{
return $"The brand is: {brand}";
}
public CardHolderInfo GetHolderInformation()
{
return new CardHolderInfo()
{
Name = $"Owner: {owner}",
Address = "no Adress"
};
}
}
}
| 20.482759
| 56
| 0.478956
|
d637ce9a786b990529b35168f1de23339ae09f46
| 127
|
cs
|
C#
|
SqlSchema.Library/Interfaces/IDefinition.cs
|
adamosoftware/SqlSchema
|
5e43d11c92d5c6d85352bc91862c9e62b84584d3
|
[
"MIT"
] | null | null | null |
SqlSchema.Library/Interfaces/IDefinition.cs
|
adamosoftware/SqlSchema
|
5e43d11c92d5c6d85352bc91862c9e62b84584d3
|
[
"MIT"
] | 1
|
2020-11-22T17:31:04.000Z
|
2020-11-22T17:31:04.000Z
|
SqlSchema.Library/Interfaces/IDefinition.cs
|
adamosoftware/SqlSchema
|
5e43d11c92d5c6d85352bc91862c9e62b84584d3
|
[
"MIT"
] | null | null | null |
namespace SqlSchema.Library.Interfaces
{
public interface IDefinition
{
string SqlDefinition { get; }
}
}
| 15.875
| 39
| 0.653543
|
a7959b05d2ef5827efa364c5c5b45923a2e6d14d
| 911
|
sql
|
SQL
|
Universidad_Paso-3_FIX.sql
|
dev-lang/UTN
|
51fc169add379956f3560d79bee5bc90c86f6edd
|
[
"CC0-1.0"
] | null | null | null |
Universidad_Paso-3_FIX.sql
|
dev-lang/UTN
|
51fc169add379956f3560d79bee5bc90c86f6edd
|
[
"CC0-1.0"
] | null | null | null |
Universidad_Paso-3_FIX.sql
|
dev-lang/UTN
|
51fc169add379956f3560d79bee5bc90c86f6edd
|
[
"CC0-1.0"
] | null | null | null |
-- fix db
-- PASO 1
-- Se agregan columnas faltantes en Profesores
ALTER TABLE Profesores ADD Pro_Apellido char(50);
ALTER TABLE Profesores ADD Pro_FecNac datetime;
--
-- SELECT * FROM Profesores;
-- PASO 2 (MS SQL)
-- cambiar nombre de CarrerasMaterias, CursosAlumnos y MateriasProfesores para que incluya un _ como separador
-- DEBERÁ DESCONECTAR Y VOLVER A CONECTARSE AL SERVIDOR PARA QUE LOS CAMBIOS SE VEAN EN EL EXPLORADOR DE OBJETOS
-- IGNORAR LOG DE PRECAUCIÓN
EXEC sp_rename 'CarrerasMaterias', 'Carreras_Materias'
EXEC sp_rename 'CursosAlumnos', 'Cursos_Alumnos'
EXEC sp_rename 'MateriasProfesores', 'Materias_Profesores'
-- PASO 3 (MS SQL)
-- Se cambia el nombre de Alumno.Alu_FechaIngreso a Alu_FecIngreso
-- DEBERÁ ACTUALIZAR LA DB PARA QUE LOS CAMBIOS SE VEAN EN EL EXPLORADOR DE OBJETOS
-- IGNORAR LOG DE PRECAUCIÓN
EXEC sp_rename 'Alumnos.Alu_FechaIngreso', 'Alu_FecIngreso', 'COLUMN';
| 33.740741
| 112
| 0.780461
|
f6927ed8296f8564da2d51f92c64865481e75e53
| 1,197
|
swift
|
Swift
|
Example/SmartToast/ViewController.swift
|
Aamirali86/iToast
|
d8b9662ff8931892984adf83bb74bb5e08966da5
|
[
"MIT"
] | 6
|
2018-08-31T07:49:33.000Z
|
2018-10-13T15:37:48.000Z
|
Example/SmartToast/ViewController.swift
|
Aamirali86/iToast
|
d8b9662ff8931892984adf83bb74bb5e08966da5
|
[
"MIT"
] | null | null | null |
Example/SmartToast/ViewController.swift
|
Aamirali86/iToast
|
d8b9662ff8931892984adf83bb74bb5e08966da5
|
[
"MIT"
] | null | null | null |
//
// ViewController.swift
// Toast
//
// Created by Amir on 12/04/2018.
// Copyright © 2018 Muhammad Aamir. All rights reserved.
//
import UIKit
import SmartToast
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func shortLenghtBottomToast(_ sender: UIButton) {
ToastManager.showToast((sender.titleLabel?.text)!)
}
@IBAction func shortLenghtCenterToast(_ sender: UIButton) {
ToastManager.showToast((sender.titleLabel?.text)!, position: .center)
}
@IBAction func longLenghtTopToast(_ sender: UIButton) {
ToastManager.showToast("Hello world", duration: ToastManager.LENGHT_LONG, position: .top)
}
@IBAction func customStyleToast(_ sender: UIButton) {
ToastManager.showToast((sender.titleLabel?.text)!, style:customizeAppearance())
}
private func customizeAppearance() -> ToastStyle {
var style = ToastStyle()
style.backgroundColor = UIColor.red.withAlphaComponent(0.8)
return style
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 23.94
| 93
| 0.715957
|
533fbd26df26c9d58ed81aec67e16de9a3a0b061
| 3,360
|
rb
|
Ruby
|
engines/adva_cms/app/helpers/content_helper.rb
|
priit/adva_cms
|
776e024c6c1e07d816c0572ca6fa92912da96697
|
[
"MIT"
] | 3
|
2015-12-22T09:34:36.000Z
|
2016-05-08T15:37:54.000Z
|
engines/adva_cms/app/helpers/content_helper.rb
|
priit/adva_cms
|
776e024c6c1e07d816c0572ca6fa92912da96697
|
[
"MIT"
] | null | null | null |
engines/adva_cms/app/helpers/content_helper.rb
|
priit/adva_cms
|
776e024c6c1e07d816c0572ca6fa92912da96697
|
[
"MIT"
] | null | null | null |
module ContentHelper
def published_at_formatted(article)
return t(:'adva.contents.not_published') unless article && article.published?
l(article.published_at, :format => (article.published_at.year == Time.now.year ? :short : :long))
end
def section_path(section, options = {})
send :"#{section.type.downcase}_path", section, options
end
def article_url(section, article, options = {})
article.section.is_a?(Page) ?
page_article_url(*[section, article.permalink, options].compact) :
blog_article_url(section, article.full_permalink.merge(options))
end
def article_path(section, article, options = {})
article.section.is_a?(Page) ?
page_article_path(*[section, article.permalink, options].compact) :
blog_article_path(section, article.full_permalink.merge(options))
end
def admin_section_contents_path(section)
content_type = section.class.content_type.pluralize.gsub('::', '_').underscore.downcase
send(:"admin_#{content_type}_path", section.site, section)
end
def link_to_preview(*args)
options = args.extract_options!
content, text = *args.reverse
text ||= :"adva.#{content.class.name.tableize}.links.preview"
url = show_path(content, :cl => content.class.locale, :namespace => nil)
options.reverse_merge!(:url => url, :class => "preview #{content.class.name.underscore}")
link_to_show text, content, options
end
def link_to_content(*args)
options = args.extract_options!
object, text = *args.reverse
link_to_show(text || (object.is_a?(Site) ? object.name : object.title), object, options) if object
end
def link_to_admin(*args)
options = args.extract_options!
options.update :namespace => :admin
object, text = *args.reverse
case object
when Content
link_to_edit(object.title, object, options)
when Section
link_to_show(object.title, object, options.merge(:url => admin_section_contents_path(object)))
when Site
link_to_show(object.name, object, options.merge(:url => admin_site_path(object)))
end
end
def link_to_category(*args)
text = args.shift if args.first.is_a? String
category = args.pop
section = args.pop || category.section
route_name = "#{section.class.name.downcase}_category_path"
link_to text || category.title, send(route_name, :section_id => section.id, :category_id => category.id)
end
def links_to_content_categories(content, key = nil)
return if content.categories.empty?
links = content.categories.map{|category| link_to_category content.section, category }
key ? t( key, :links => links.join(', ') ) : links
end
def link_to_tag(*args)
tag = args.pop
section = args.pop
route_name = "#{section.class.name.downcase}_tag_path"
link_to args.pop || tag.name, send(route_name, :section_id => section.id, :tags => tag)
end
def links_to_content_tags(content, key = nil)
return if content.tags.empty?
links = content.tags.map{|tag| link_to_tag content.section, tag }
key ? t( key, :links => links.join(', ') ) : links
end
def content_category_checkbox(content, category)
type = content.type.downcase
checked = content.categories.include?(category)
name = "#{type}[category_ids][]"
id = "#{type}_category_#{category.id}"
check_box_tag name, category.id, checked, :id => id
end
end
| 35.744681
| 108
| 0.702976
|
d6525609cb9f4984a422f5cd5bebc70c3ad87f61
| 805
|
cs
|
C#
|
Assets/Projects/Telexistence/UI/UINEDOWifi.cs
|
mrayy/TxKit
|
3ea416166c32a78a18a4a3cdaa388b4ef44746b1
|
[
"MIT"
] | null | null | null |
Assets/Projects/Telexistence/UI/UINEDOWifi.cs
|
mrayy/TxKit
|
3ea416166c32a78a18a4a3cdaa388b4ef44746b1
|
[
"MIT"
] | null | null | null |
Assets/Projects/Telexistence/UI/UINEDOWifi.cs
|
mrayy/TxKit
|
3ea416166c32a78a18a4a3cdaa388b4ef44746b1
|
[
"MIT"
] | null | null | null |
using UnityEngine;
using System.Collections;
using System;
using UnityEngine.UI;
public class UINEDOWifi : MonoBehaviour {
[Serializable]
public class SignalLevel
{
public Sprite img;
public int level;
}
public SignalLevel[] levels;
public Image image;
public Text label;
public int level;
int m_level=-1;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
SetLevel (level);
}
public void SetLevel(int level)
{
if (m_level == level)
return;
label.text = level.ToString () + "db";
bool found = false;
for(int i=0;i<levels.Length;++i)
{
if(level<levels[i].level)
{
image.sprite=levels[i].img;
found=true;
break;
}
}
if (!found)
image.sprite = levels [levels.Length - 1].img;
}
}
| 15.188679
| 49
| 0.652174
|
88f9d9809e2eae70fe3e5a68f71206ae2c17c20d
| 5,965
|
rs
|
Rust
|
src/dim/matmul.rs
|
jerry73204/tch-typed-tensor
|
ca541b640957253485e282d65316933da67a79f8
|
[
"Apache-2.0"
] | 4
|
2019-09-20T20:04:54.000Z
|
2020-04-10T16:48:11.000Z
|
src/dim/matmul.rs
|
jerry73204/tch-typed-tensor
|
ca541b640957253485e282d65316933da67a79f8
|
[
"Apache-2.0"
] | 1
|
2019-10-01T12:31:35.000Z
|
2019-10-01T13:12:55.000Z
|
src/dim/matmul.rs
|
jerry73204/tch-typed-tensor
|
ca541b640957253485e282d65316933da67a79f8
|
[
"Apache-2.0"
] | null | null | null |
use super::{
BcastAbscent, BroadcastMatcher, DBroadcastBothReversely, DBroadcastBothReverselyOutput,
DReverse, DReverseOutput, Dim, DimList, MatrixDim,
};
use crate::{DimListType, DimListTypeWithTail};
use typenum::Unsigned;
// two-dimensional matrix multiplication
pub trait DMatMul<Rhs>
where
Self: MatrixDim,
Rhs: MatrixDim,
Self::Output: MatrixDim,
{
type Output;
}
pub type DMatMulOutput<Lhs, Rhs> = <Lhs as DMatMul<Rhs>>::Output;
// (m x n) . (n x p) -> (m x p)
impl<MDim, MSize, NDim, NSize, PDim, PSize> DMatMul<DimListType! {(NDim, NSize), (PDim, PSize)}> for DimListType! {(MDim, MSize), (NDim, NSize)}
where
MDim: Dim,
MSize: Unsigned,
NDim: Dim,
NSize: Unsigned,
PDim: Dim,
PSize: Unsigned,
{
type Output = DimListType! {(MDim, MSize), (PDim, PSize)};
}
// broadcasted matmul
pub trait DMatMulBroadcasted<Rhs, Matcher>
where
Rhs: DimList,
Matcher: BroadcastMatcher,
Self: DimList,
Self::Output: DimList,
{
type Output;
}
pub type DMatMulBroadcastedOutput<Lhs, Rhs, Matcher> =
<Lhs as DMatMulBroadcasted<Rhs, Matcher>>::Output;
impl<Lhs, Rhs, Matcher> DMatMulBroadcasted<Rhs, Matcher> for Lhs
where
Lhs: DimList + DReverse,
Rhs: DimList + DReverse,
Matcher: BroadcastMatcher,
DReverseOutput<Lhs>: DMatMulAuxiliary<DReverseOutput<Rhs>, Matcher>,
DMatMulAuxiliaryOutput<DReverseOutput<Lhs>, DReverseOutput<Rhs>, Matcher>: DReverse,
{
type Output =
DReverseOutput<DMatMulAuxiliaryOutput<DReverseOutput<Lhs>, DReverseOutput<Rhs>, Matcher>>;
}
// auxiliary trait for DMatMulBroadcastable broadcastable matrix multiplication
pub trait DMatMulAuxiliary<Rhs, Matcher>
where
Rhs: DimList,
Matcher: BroadcastMatcher,
Self: DimList,
Self::Output: DimList,
{
type Output;
}
pub type DMatMulAuxiliaryOutput<Lhs, Rhs, Matcher> =
<Lhs as DMatMulAuxiliary<Rhs, Matcher>>::Output;
// vector x vector
impl<LDim, RDim, Size> DMatMulAuxiliary<DimListType! {(RDim, Size)}, BcastAbscent> for DimListType! {(LDim, Size)}
where
LDim: Dim,
RDim: Dim,
Size: Unsigned,
{
type Output = DimListType! {};
}
// broadcasted matrix x matrix
impl<MDim, MSize, NDim, NSize, PDim, PSize, LTail, RTail, Matcher>
DMatMulAuxiliary<DimListTypeWithTail! {(PDim, PSize), (NDim, NSize), RTail}, Matcher> for DimListTypeWithTail! {(NDim, NSize), (MDim, MSize), LTail}
where
MDim: Dim,
MSize: Unsigned,
NDim: Dim,
NSize: Unsigned,
PDim: Dim,
PSize: Unsigned,
LTail: DimList + DBroadcastBothReversely<RTail, Matcher>,
RTail: DimList,
Matcher: BroadcastMatcher,
{
type Output = DimListTypeWithTail! {(PDim, PSize), (MDim, MSize), DBroadcastBothReverselyOutput<LTail, RTail, Matcher>};
}
// broadcasted vector x matrix
impl<NDim, NSize, PDim, PSize, Tail>
DMatMulAuxiliary<DimListTypeWithTail! {(PDim, PSize), (NDim, NSize), Tail}, BcastAbscent> for DimListType! {(NDim, NSize)}
where
NDim: Dim,
NSize: Unsigned,
PDim: Dim,
PSize: Unsigned,
Tail: DimList,
{
type Output = DimListTypeWithTail! {(PDim, PSize), Tail};
}
// broadcasted matrix x vector
impl<MDim, MSize, NDim, NSize, Tail> DMatMulAuxiliary<DimListType! {(NDim, NSize)}, BcastAbscent> for DimListTypeWithTail! {(NDim, NSize), (MDim, MSize), Tail}
where
MDim: Dim,
MSize: Unsigned,
NDim: Dim,
NSize: Unsigned,
Tail: DimList,
{
type Output = DimListTypeWithTail! {(MDim, MSize), Tail};
}
// tests
#[cfg(test)]
mod tests {
use super::*;
use crate::{make_dims, DimListType};
use type_freak::control::IfSameOutput;
use typenum::consts::*;
make_dims! {M, N, P, X, Y}
type VecDims1 = DimListType! {(N, U2)};
type VecDims2 = DimListType! {(M, U2)};
type MatDims1 = DimListType! {(M, U3), (N, U2)};
type MatDims2 = DimListType! {(N, U2), (P, U5)};
type BatchMatDims1 = DimListType! {(X, U7), (Y, U1), (M, U3), (N, U2)};
type BatchMatDims2 = DimListType! {(Y, U11), (N, U2), (P, U5)};
type AssertSame<Lhs, Rhs> = IfSameOutput<(), Lhs, Rhs>;
// non-broadcasted matmul
type Assert1 = AssertSame<DMatMulOutput<MatDims1, MatDims2>, DimListType! {(M, U3), (P, U5)}>;
// vector x vector
type Assert2<Matcher> =
AssertSame<DMatMulBroadcastedOutput<VecDims1, VecDims2, Matcher>, DimListType! {}>;
// matrix x vector
type Assert3<Matcher> =
AssertSame<DMatMulBroadcastedOutput<MatDims1, VecDims1, Matcher>, DimListType! {(M, U3)}>;
// vector x matrix
type Assert4<Matcher> =
AssertSame<DMatMulBroadcastedOutput<VecDims1, MatDims2, Matcher>, DimListType! {(P, U5)}>;
// matrix x matrix
type Assert5<Matcher> = AssertSame<
DMatMulBroadcastedOutput<MatDims1, MatDims2, Matcher>,
DimListType! {(M, U3), (P, U5)},
>;
// batched matrix x vector
type Assert6<Matcher> = AssertSame<
DMatMulBroadcastedOutput<BatchMatDims1, VecDims1, Matcher>,
DimListType! {(X, U7), (Y, U1), (M, U3)},
>;
// vector x batched matrix
type Assert7<Matcher> = AssertSame<
DMatMulBroadcastedOutput<VecDims1, BatchMatDims2, Matcher>,
DimListType! {(Y, U11), (P, U5)},
>;
// batched matrix x matrix
type Assert8<Matcher> = AssertSame<
DMatMulBroadcastedOutput<BatchMatDims1, MatDims2, Matcher>,
DimListType! {(X, U7), (Y, U1), (M, U3), (P, U5)},
>;
// batched matrix x batched matrix
type Assert9<Matcher> = AssertSame<
DMatMulBroadcastedOutput<BatchMatDims1, BatchMatDims2, Matcher>,
DimListType! {(X, U7), (Y, U11), (M, U3), (P, U5)},
>;
#[test]
fn dim_matmul_test() {
let _: Assert1 = ();
let _: Assert2<_> = ();
let _: Assert3<_> = ();
let _: Assert4<_> = ();
let _: Assert5<_> = ();
let _: Assert6<_> = ();
let _: Assert7<_> = ();
let _: Assert8<_> = ();
let _: Assert9<_> = ();
}
}
| 28.816425
| 159
| 0.64912
|
07167b7780f6d0f95eaeee6d5714faaf68615e61
| 6,047
|
css
|
CSS
|
mobile/assets/themes/escrow/css/escrow.css
|
technifist/technifist
|
9a0150e7b47bf6e60a75774e601106dd47d0a4c8
|
[
"MIT"
] | null | null | null |
mobile/assets/themes/escrow/css/escrow.css
|
technifist/technifist
|
9a0150e7b47bf6e60a75774e601106dd47d0a4c8
|
[
"MIT"
] | null | null | null |
mobile/assets/themes/escrow/css/escrow.css
|
technifist/technifist
|
9a0150e7b47bf6e60a75774e601106dd47d0a4c8
|
[
"MIT"
] | null | null | null |
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
/* Чтобы занимал оставшееся пространство */
flex-grow: 1;
}
footer {
/* Чтобы footer не уменьшался */
flex-shrink: 0;
}
.header-st {
height: 180px;
background: #7867a7 url(../img/just3-bg.png);
padding-top: 100px;
padding-bottom: 40px;
color: #fff;
}
.header-st h3{
text-align:center;
}
.header-st2 {
height: 180px;
background: #7867a7 url(../img/just3-bg.png);
padding-top: 100px;
padding-bottom: 40px;
}
@media (min-width: 768px) {
.navbar-expand-md {
background-color: #343a4066;
}
}
@media (max-width: 768px) {
.navbar-expand-md {
background-color: #00403c;
}
}
.nav-user a{
color: rgba(255, 255, 255, 0.81);
}
.nav-user a:hover{
color: #fff;
text-decoration: none;
}
.footer {
color: #828282;
background-color: #333333;
}
.footer .list-inline-item a {
color: #828282;
}
.footer .list-inline-item a:hover{
color: #fff;
text-decoration: none;
}
.footer .list-inline {
margin-top: 20px;
margin-bottom: 20px;
display: inline-block;
list-style: none;
}
.footer .list-inline-item {
background-color: #333333;
border: none;
display: inline-block;
}
.footer .btn {
margin-top: 13px;
}
.footer .col-md-10{
max-width: 60% !important;
}
.footer .col-md-2{
flex: 0 0 83.333333%;
max-width: 40% !important;
}
.footer a img{
margin-top:12px;
}
.landing {
height: 480px;
background: url(../img/main7.jpg);
background-repeat: no-repeat;
background-position: 100% 40%;
background-size: cover;
padding-top: 70px;
padding-bottom: 40px;
color: #fff;
}
.landing-2{
height: 480px;
background: url(../img/shop.jpg);
background-repeat: no-repeat;
background-position: 100% 40%;
background-size: cover;
padding-top: 70px;
padding-bottom: 40px;
color: #fff;
}
.landing-3{
height: 480px;
background: url(../img/shop2.jpg);
background-repeat: no-repeat;
background-position: 100% 40%;
background-size: cover;
padding-top: 70px;
padding-bottom: 40px;
color: #fff;
}
.top-merchant {
background-color: #f7f9fa;
}
.top-protect {
background-image: radial-gradient(circle farthest-side at center bottom,#868e96,#3d3e40 125%);
}
.foot-merchant {
background-image: radial-gradient(circle farthest-side at center bottom,#7867a7,#553e94 125%);
}
.mt-6 {
margin-top: 5rem !important;
}
.step-badge {
background: #ffffff;
padding: 5px 13px 5px 12px;
color: #28a745;
font-weight: 600;
font-size: 16px;
border-radius: 216px;
border: 1px solid #28a745;
}
.step-badge-2 {
background: #ffffff;
padding: 5px 11px 5px 12px;
color: #28a745;
font-weight: 600;
font-size: 16px;
border-radius: 216px;
border: 1px solid #28a745;
}
.top-badge {
background: #ffffff00;
padding: 10px 18px 9px 19px;
color: #ffffff;
font-weight: 600;
font-size: 20px;
border-radius: 216px;
border: 1px solid #ffffff;
}
.top-badge-2 {
background: #ffffff00;
padding: 10px 17px 9px 18px;
color: #ffffff;
font-weight: 600;
font-size: 20px;
border-radius: 216px;
border: 1px solid #ffffff;
}
.code-editor {
background-color: #313440;
border-radius: 5px;
border: 1px solid #1B1C22;
font-family: Inconsolata, Monaco, Consolas, 'Courier New', Courier;
}
.code-editor > .tabs {
background-color: transparent;
}
.code-editor > .tabs > .title {
width: 100%;
position: relative;
padding: 5px 0 7px 5px;
text-align: center;
font-size: 1.2rem;
word-wrap: break-word;
}
.code-editor > .tabs > .title.-ruby {
color: #D16262;
}
.code-editor > .tabs > .title.-javascript {
color: #DBB984;
}
.code-editor > .tabs > .title.-html {
color: #E27B60;
}
.code-editor > .tabs > .title.-react {
color: #75E0FD;
}
.code-editor > .tabs > .title > .icon {
position: relative;
top: 2px;
margin-right: 5px;
color: inherit;
font-size: 1rem;
}
.code-editor > .content {
padding: 20px 0 20px 10px;
font-size: 0.7rem;
}
.code-editor > .content > .lines {
list-style: none;
padding: 0;
margin: 0;
}
.code-editor .lines > .line ::selection {
background-color: rgba(62, 68, 81, 0.8);
}
.code-editor .lines > .line {
white-space: nowrap;
}
.code-editor .lines > .line > span {
white-space: normal;
word-wrap: break-word;
}
.code-editor .lines .linenumber {
color: #414556;
padding: 0 15px 0 0;
font-weight: normal;
}
.code-editor .red {
color: #e06c75;
}
.code-editor .purple {
color: #c678dd;
}
.code-editor .yellow {
color: #FECF5F;
}
.code-editor .orange {
color: #FB8578;
}
.code-editor .blue {
color: #7EBAFF;
}
.code-editor .green {
color: #98c379;
}
.code-editor .light-blue {
color: #75E0FD;
}
.navbar-expand-md {
background-color: rgba(52, 58, 64, 0.5);
}
.code-editor .comment {
color: #5c6370;
font-style: italic;
}
.mb-head {
margin-bottom: 9rem;
}
.win-img {
border-radius: 50%;
box-shadow: 0 15px 35px rgba(50,50,93,.1), 0 5px 15px rgba(0,0,0,.07);
}
.w-10 {
width: 10%;
}
.mt-10 {
margin-top: 35rem;
}
.notify-popup {
width: 100%;
z-index: 5000;
position: fixed;
left: 0;
bottom: 0px;
border-radius: 4px;
box-shadow: 1px 1px 2px 1px #bbb;
}
/* Mobile CSS*/
@media only screen and (max-width: 768px) {
#header-st{
display:none;
}
.footer .btn {
display:none;
}
.footer .list-inline {
margin-top: 5px;
margin-bottom: 5px;
display: inline-block;
list-style: none;
}
.footer .list-inline-item a {
font-size: 10px;
}
.footer{
position:absolute;
bottom:0;
width:100%;
}
#rightTxt{
text-align:right;
}
.g-recaptcha{
float:right;
}
#card{
margin-top:60px;
margin-bottom:70px;
background-color:rgba(255, 255, 255,0.8) !important;
}
#navbar-toggler {
display: none;
}
.navbar-dark .navbar-brand {
margin-left: 16%;
}
.navbar-expand-md {
background-color: rgba(3, 19, 109, 0.4);
}
body{
background:url(../img/bckmob.png);
background-repeat: no-repeat;
background-size:500px;
position:relative;
}
.footer a img{
display:none;
}
.footer .col-md-10{
max-width: 99% !important;
text-align:center;
}
}
| 17.997024
| 96
| 0.649578
|
1aa5241b4124179e3e67718a04ada2b25bfab754
| 1,443
|
py
|
Python
|
Python/Camscanner/camscanner.py
|
tanishq-arya/Rotten-Scripts
|
93f62eb1213f739c13103610d3f502e1dc2d3790
|
[
"MIT"
] | 4
|
2021-04-27T19:54:06.000Z
|
2021-09-28T15:34:12.000Z
|
Python/Camscanner/camscanner.py
|
tanishq-arya/Rotten-Scripts
|
93f62eb1213f739c13103610d3f502e1dc2d3790
|
[
"MIT"
] | null | null | null |
Python/Camscanner/camscanner.py
|
tanishq-arya/Rotten-Scripts
|
93f62eb1213f739c13103610d3f502e1dc2d3790
|
[
"MIT"
] | null | null | null |
import sys,cv2
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
# the image that needs to be scanned
filename= sys.argv[1]
img= cv2.imread(filename)
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
thresh1 = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
cv2.imwrite('try1.jpg',thresh1)
thresh2 = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 31, 3)
cv2.imwrite('try2.jpg',thresh2)
thresh3 = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 13, 5)
cv2.imwrite('try3.jpg',thresh3)
thresh4 = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 4)
cv2.imwrite('try4.jpg',thresh4)
thresh5 = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 11, 2)
cv2.imwrite('try5.jpg',thresh5)
thresh6 = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 31, 5)
cv2.imwrite('try6.jpg',thresh6)
thresh7 = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 21,5 )
cv2.imwrite('try7.jpg',thresh7)
thresh8 = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 5)
cv2.imwrite('try8.jpg',thresh8)
cv2.waitKey(0)
cv2.destroyAllWindows()
| 37
| 108
| 0.741511
|
cd8fc745782890eb144dbbaa31d92c67ac79d216
| 17,356
|
cs
|
C#
|
src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultRazorDocumentMappingService.cs
|
ladipro/aspnetcore-tooling
|
48d22f9def38bfd9eedc8077f683796bfae94132
|
[
"Apache-2.0"
] | null | null | null |
src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultRazorDocumentMappingService.cs
|
ladipro/aspnetcore-tooling
|
48d22f9def38bfd9eedc8077f683796bfae94132
|
[
"Apache-2.0"
] | null | null | null |
src/Razor/src/Microsoft.AspNetCore.Razor.LanguageServer/DefaultRazorDocumentMappingService.cs
|
ladipro/aspnetcore-tooling
|
48d22f9def38bfd9eedc8077f683796bfae94132
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.Language.Legacy;
using Microsoft.CodeAnalysis.Razor.Workspaces;
using Microsoft.CodeAnalysis.Text;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range;
namespace Microsoft.AspNetCore.Razor.LanguageServer
{
internal class DefaultRazorDocumentMappingService : RazorDocumentMappingService
{
public override bool TryMapFromProjectedDocumentRange(RazorCodeDocument codeDocument, Range projectedRange, out Range originalRange) => TryMapFromProjectedDocumentRange(codeDocument, projectedRange, MappingBehavior.Strict, out originalRange);
public override bool TryMapFromProjectedDocumentRange(RazorCodeDocument codeDocument, Range projectedRange, MappingBehavior mappingBehavior, out Range originalRange)
{
if (codeDocument is null)
{
throw new ArgumentNullException(nameof(codeDocument));
}
if (projectedRange is null)
{
throw new ArgumentNullException(nameof(projectedRange));
}
if (mappingBehavior == MappingBehavior.Strict)
{
return TryMapFromProjectedDocumentRangeStrict(codeDocument, projectedRange, out originalRange);
}
else if (mappingBehavior == MappingBehavior.Inclusive)
{
return TryMapFromProjectedDocumentRangeInclusive(codeDocument, projectedRange, out originalRange);
}
else
{
throw new InvalidOperationException(RazorLS.Resources.Unknown_mapping_behavior);
}
}
public override bool TryMapToProjectedDocumentRange(RazorCodeDocument codeDocument, Range originalRange, out Range projectedRange)
{
if (codeDocument is null)
{
throw new ArgumentNullException(nameof(codeDocument));
}
if (originalRange is null)
{
throw new ArgumentNullException(nameof(originalRange));
}
projectedRange = default;
if ((originalRange.End.Line < originalRange.Start.Line) ||
(originalRange.End.Line == originalRange.Start.Line &&
originalRange.End.Character < originalRange.Start.Character))
{
Debug.Fail($"DefaultRazorDocumentMappingService:TryMapToProjectedDocumentRange original range end < start '{originalRange}'");
return false;
}
var sourceText = codeDocument.GetSourceText();
var range = originalRange;
if (!IsRangeWithinDocument(range, sourceText))
{
return false;
}
var startIndex = range.Start.GetAbsoluteIndex(sourceText);
if (!TryMapToProjectedDocumentPosition(codeDocument, startIndex, out var projectedStart, out var _))
{
return false;
}
var endIndex = range.End.GetAbsoluteIndex(sourceText);
if (!TryMapToProjectedDocumentPosition(codeDocument, endIndex, out var projectedEnd, out var _))
{
return false;
}
// Ensures a valid range is returned.
// As we're doing two seperate TryMapToProjectedDocumentPosition calls,
// it's possible the projectedStart and projectedEnd positions are in completely
// different places in the document, including the possibility that the
// projectedEnd position occurs before the projectedStart position.
// We explicitly disallow such ranges where the end < start.
if ((projectedEnd.Line < projectedStart.Line) ||
(projectedEnd.Line == projectedStart.Line &&
projectedEnd.Character < projectedStart.Character))
{
return false;
}
projectedRange = new Range(
projectedStart,
projectedEnd);
return true;
}
public override bool TryMapFromProjectedDocumentPosition(RazorCodeDocument codeDocument, int csharpAbsoluteIndex, out Position originalPosition, out int originalIndex)
{
if (codeDocument is null)
{
throw new ArgumentNullException(nameof(codeDocument));
}
var csharpDoc = codeDocument.GetCSharpDocument();
foreach (var mapping in csharpDoc.SourceMappings)
{
var generatedSpan = mapping.GeneratedSpan;
var generatedAbsoluteIndex = generatedSpan.AbsoluteIndex;
if (generatedAbsoluteIndex <= csharpAbsoluteIndex)
{
// Treat the mapping as owning the edge at its end (hence <= originalSpan.Length),
// otherwise we wouldn't handle the cursor being right after the final C# char
var distanceIntoGeneratedSpan = csharpAbsoluteIndex - generatedAbsoluteIndex;
if (distanceIntoGeneratedSpan <= generatedSpan.Length)
{
// Found the generated span that contains the csharp absolute index
originalIndex = mapping.OriginalSpan.AbsoluteIndex + distanceIntoGeneratedSpan;
var originalLocation = codeDocument.Source.Lines.GetLocation(originalIndex);
originalPosition = new Position(originalLocation.LineIndex, originalLocation.CharacterIndex);
return true;
}
}
}
originalPosition = default;
originalIndex = default;
return false;
}
public override bool TryMapToProjectedDocumentPosition(RazorCodeDocument codeDocument, int absoluteIndex, out Position projectedPosition, out int projectedIndex)
{
if (codeDocument is null)
{
throw new ArgumentNullException(nameof(codeDocument));
}
var csharpDoc = codeDocument.GetCSharpDocument();
foreach (var mapping in csharpDoc.SourceMappings)
{
var originalSpan = mapping.OriginalSpan;
var originalAbsoluteIndex = originalSpan.AbsoluteIndex;
if (originalAbsoluteIndex <= absoluteIndex)
{
// Treat the mapping as owning the edge at its end (hence <= originalSpan.Length),
// otherwise we wouldn't handle the cursor being right after the final C# char
var distanceIntoOriginalSpan = absoluteIndex - originalAbsoluteIndex;
if (distanceIntoOriginalSpan <= originalSpan.Length)
{
var generatedSource = codeDocument.GetCSharpSourceText();
projectedIndex = mapping.GeneratedSpan.AbsoluteIndex + distanceIntoOriginalSpan;
var generatedLinePosition = generatedSource.Lines.GetLinePosition(projectedIndex);
projectedPosition = new Position(generatedLinePosition.Line, generatedLinePosition.Character);
return true;
}
}
}
projectedPosition = default;
projectedIndex = default;
return false;
}
public override RazorLanguageKind GetLanguageKind(RazorCodeDocument codeDocument, int originalIndex)
{
if (codeDocument is null)
{
throw new ArgumentNullException(nameof(codeDocument));
}
var syntaxTree = codeDocument.GetSyntaxTree();
var classifiedSpans = syntaxTree.GetClassifiedSpans();
var tagHelperSpans = syntaxTree.GetTagHelperSpans();
var documentLength = codeDocument.GetSourceText().Length;
var languageKind = GetLanguageKindCore(classifiedSpans, tagHelperSpans, originalIndex, documentLength);
return languageKind;
}
// Internal for testing
internal static RazorLanguageKind GetLanguageKindCore(
IReadOnlyList<ClassifiedSpanInternal> classifiedSpans,
IReadOnlyList<TagHelperSpanInternal> tagHelperSpans,
int absoluteIndex,
int documentLength)
{
for (var i = 0; i < classifiedSpans.Count; i++)
{
var classifiedSpan = classifiedSpans[i];
var span = classifiedSpan.Span;
if (span.AbsoluteIndex <= absoluteIndex)
{
var end = span.AbsoluteIndex + span.Length;
if (end >= absoluteIndex)
{
if (end == absoluteIndex)
{
// We're at an edge.
if (span.Length > 0 &&
classifiedSpan.AcceptedCharacters == AcceptedCharactersInternal.None)
{
// Non-marker spans do not own the edges after it
continue;
}
}
return GetLanguageFromClassifiedSpan(classifiedSpan);
}
}
}
for (var i = 0; i < tagHelperSpans.Count; i++)
{
var tagHelperSpan = tagHelperSpans[i];
var span = tagHelperSpan.Span;
if (span.AbsoluteIndex <= absoluteIndex)
{
var end = span.AbsoluteIndex + span.Length;
if (end >= absoluteIndex)
{
if (end == absoluteIndex)
{
// We're at an edge. TagHelper spans never own their edge and aren't represented by marker spans
continue;
}
// Found intersection
return RazorLanguageKind.Html;
}
}
}
// Use the language of the last classified span if we're at the end
// of the document.
if (classifiedSpans.Count != 0 && absoluteIndex == documentLength)
{
var lastClassifiedSpan = classifiedSpans.Last();
return GetLanguageFromClassifiedSpan(lastClassifiedSpan);
}
// Default to Razor
return RazorLanguageKind.Razor;
static RazorLanguageKind GetLanguageFromClassifiedSpan(ClassifiedSpanInternal classifiedSpan)
{
// Overlaps with request
return classifiedSpan.SpanKind switch
{
SpanKindInternal.Markup => RazorLanguageKind.Html,
SpanKindInternal.Code => RazorLanguageKind.CSharp,
// Content type was non-C# or Html or we couldn't find a classified span overlapping the request position.
// All other classified span kinds default back to Razor
_ => RazorLanguageKind.Razor,
};
}
}
private bool TryMapFromProjectedDocumentRangeStrict(RazorCodeDocument codeDocument, Range projectedRange, out Range originalRange)
{
originalRange = default;
var csharpSourceText = codeDocument.GetCSharpSourceText();
var range = projectedRange;
if (!IsRangeWithinDocument(range, csharpSourceText))
{
return false;
}
var startIndex = range.Start.GetAbsoluteIndex(csharpSourceText);
if (!TryMapFromProjectedDocumentPosition(codeDocument, startIndex, out var hostDocumentStart, out _))
{
return false;
}
var endIndex = range.End.GetAbsoluteIndex(csharpSourceText);
if (!TryMapFromProjectedDocumentPosition(codeDocument, endIndex, out var hostDocumentEnd, out _))
{
return false;
}
originalRange = new Range(
hostDocumentStart,
hostDocumentEnd);
return true;
}
private bool TryMapFromProjectedDocumentRangeInclusive(RazorCodeDocument codeDocument, Range projectedRange, out Range originalRange)
{
originalRange = default;
var csharpDoc = codeDocument.GetCSharpDocument();
var csharpSourceText = codeDocument.GetCSharpSourceText();
var projectedRangeAsSpan = projectedRange.AsTextSpan(csharpSourceText);
var range = projectedRange;
var startIndex = projectedRangeAsSpan.Start;
var startMappedDirectly = TryMapFromProjectedDocumentPosition(codeDocument, startIndex, out var hostDocumentStart, out _);
var endIndex = projectedRangeAsSpan.End;
var endMappedDirectly = TryMapFromProjectedDocumentPosition(codeDocument, endIndex, out var hostDocumentEnd, out _);
if (startMappedDirectly && endMappedDirectly)
{
// We strictly mapped the start/end of the projected range.
originalRange = new Range(hostDocumentStart, hostDocumentEnd);
return true;
}
List<SourceMapping> candidateMappings;
if (startMappedDirectly)
{
// Start of projected range intersects with a mapping
candidateMappings = csharpDoc.SourceMappings.Where(mapping => IntersectsWith(startIndex, mapping.GeneratedSpan)).ToList();
}
else if (endMappedDirectly)
{
// End of projected range intersects with a mapping
candidateMappings = csharpDoc.SourceMappings.Where(mapping => IntersectsWith(endIndex, mapping.GeneratedSpan)).ToList();
}
else
{
// Our range does not intersect with any mapping; we should see if it overlaps generated locations
candidateMappings = csharpDoc.SourceMappings.Where(mapping => Overlaps(projectedRangeAsSpan, mapping.GeneratedSpan)).ToList();
}
if (candidateMappings.Count == 1)
{
// We're intersecting or overlapping a single mapping, lets choose that.
var mapping = candidateMappings[0];
originalRange = ConvertMapping(codeDocument.Source, mapping);
return true;
}
else
{
// More then 1 or exactly 0 intersecting/overlapping mappings
return false;
}
bool Overlaps(TextSpan projectedRangeAsSpan, SourceSpan span)
{
var overlapStart = Math.Max(projectedRangeAsSpan.Start, span.AbsoluteIndex);
var overlapEnd = Math.Min(projectedRangeAsSpan.End, span.AbsoluteIndex + span.Length);
return overlapStart < overlapEnd;
}
bool IntersectsWith(int position, SourceSpan span)
{
return unchecked((uint)(position - span.AbsoluteIndex) <= (uint)span.Length);
}
static Range ConvertMapping(RazorSourceDocument sourceDocument, SourceMapping mapping)
{
var startLocation = sourceDocument.Lines.GetLocation(mapping.OriginalSpan.AbsoluteIndex);
var endLocation = sourceDocument.Lines.GetLocation(mapping.OriginalSpan.AbsoluteIndex + mapping.OriginalSpan.Length);
var convertedRange = new Range(
new Position(startLocation.LineIndex, startLocation.CharacterIndex),
new Position(endLocation.LineIndex, endLocation.CharacterIndex));
return convertedRange;
}
}
private static bool _haveAsserted = false;
private static bool IsRangeWithinDocument(Range range, SourceText sourceText)
{
// This might happen when the document that ranges were created against was not the same as the document we're consulting.
var result = IsPositionWithinDocument(range.Start, sourceText) && IsPositionWithinDocument(range.End, sourceText);
if(!_haveAsserted && !result)
{
_haveAsserted = true;
Debug.Fail($"Attempted to map a range {range} outside of the Source (line count {sourceText.Lines.Count}.) This could happen if the Roslyn and Razor LSP servers are not in sync.");
}
return result;
static bool IsPositionWithinDocument(Position position, SourceText sourceText)
{
return position.Line < sourceText.Lines.Count;
}
}
}
}
| 43.281796
| 250
| 0.591265
|
180736e03ffeb6e2dc9d270a078543f0e1e69296
| 19,461
|
rs
|
Rust
|
pac/src/pmu/ffe_mem_ctrl_0.rs
|
coolbreeze413/eos-s3-rs
|
ab26eb6c93f1b9d7e0710e48efb87beadac615a0
|
[
"Apache-2.0",
"MIT"
] | 5
|
2022-01-04T22:09:47.000Z
|
2022-01-07T20:00:04.000Z
|
pac/src/pmu/ffe_mem_ctrl_0.rs
|
coolbreeze413/eos-s3-rs
|
ab26eb6c93f1b9d7e0710e48efb87beadac615a0
|
[
"Apache-2.0",
"MIT"
] | 4
|
2022-01-02T22:59:09.000Z
|
2022-01-08T05:21:16.000Z
|
pac/src/pmu/ffe_mem_ctrl_0.rs
|
coolbreeze413/eos-s3-rs
|
ab26eb6c93f1b9d7e0710e48efb87beadac615a0
|
[
"Apache-2.0",
"MIT"
] | 1
|
2022-01-07T20:05:05.000Z
|
2022-01-07T20:05:05.000Z
|
#[doc = "Register `FFE_MEM_CTRL_0` reader"]
pub struct R(crate::R<FFE_MEM_CTRL_0_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<FFE_MEM_CTRL_0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<FFE_MEM_CTRL_0_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<FFE_MEM_CTRL_0_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `FFE_MEM_CTRL_0` writer"]
pub struct W(crate::W<FFE_MEM_CTRL_0_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<FFE_MEM_CTRL_0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<FFE_MEM_CTRL_0_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<FFE_MEM_CTRL_0_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Control DS pin of CM0 8Kx40\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CTRL_FFE_SRAM_DS_CM0_A {
#[doc = "0: Disable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
DISABLE_DEEP_SLEEP = 0,
#[doc = "1: Enable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
ENABLE_DEEP_SLEEP = 1,
}
impl From<CTRL_FFE_SRAM_DS_CM0_A> for bool {
#[inline(always)]
fn from(variant: CTRL_FFE_SRAM_DS_CM0_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Field `CTRL_FFE_SRAM_DS_CM0` reader - Control DS pin of CM0 8Kx40"]
pub struct CTRL_FFE_SRAM_DS_CM0_R(
crate::FieldReader<bool, CTRL_FFE_SRAM_DS_CM0_A>,
);
impl CTRL_FFE_SRAM_DS_CM0_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CTRL_FFE_SRAM_DS_CM0_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CTRL_FFE_SRAM_DS_CM0_A {
match self.bits {
false => CTRL_FFE_SRAM_DS_CM0_A::DISABLE_DEEP_SLEEP,
true => CTRL_FFE_SRAM_DS_CM0_A::ENABLE_DEEP_SLEEP,
}
}
#[doc = "Checks if the value of the field is `DISABLE_DEEP_SLEEP`"]
#[inline(always)]
pub fn is_disable_deep_sleep(&self) -> bool {
**self == CTRL_FFE_SRAM_DS_CM0_A::DISABLE_DEEP_SLEEP
}
#[doc = "Checks if the value of the field is `ENABLE_DEEP_SLEEP`"]
#[inline(always)]
pub fn is_enable_deep_sleep(&self) -> bool {
**self == CTRL_FFE_SRAM_DS_CM0_A::ENABLE_DEEP_SLEEP
}
}
impl core::ops::Deref for CTRL_FFE_SRAM_DS_CM0_R {
type Target = crate::FieldReader<bool, CTRL_FFE_SRAM_DS_CM0_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CTRL_FFE_SRAM_DS_CM0` writer - Control DS pin of CM0 8Kx40"]
pub struct CTRL_FFE_SRAM_DS_CM0_W<'a> {
w: &'a mut W,
}
impl<'a> CTRL_FFE_SRAM_DS_CM0_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CTRL_FFE_SRAM_DS_CM0_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Disable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn disable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_CM0_A::DISABLE_DEEP_SLEEP)
}
#[doc = "Enable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn enable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_CM0_A::ENABLE_DEEP_SLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
}
}
#[doc = "Control DS pin of DM0 1Kx32"]
pub type CTRL_FFE_SRAM_DS_DM0_A = CTRL_FFE_SRAM_DS_CM0_A;
#[doc = "Field `CTRL_FFE_SRAM_DS_DM0` reader - Control DS pin of DM0 1Kx32"]
pub type CTRL_FFE_SRAM_DS_DM0_R = CTRL_FFE_SRAM_DS_CM0_R;
#[doc = "Field `CTRL_FFE_SRAM_DS_DM0` writer - Control DS pin of DM0 1Kx32"]
pub struct CTRL_FFE_SRAM_DS_DM0_W<'a> {
w: &'a mut W,
}
impl<'a> CTRL_FFE_SRAM_DS_DM0_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CTRL_FFE_SRAM_DS_DM0_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Disable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn disable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_DM0_A::DISABLE_DEEP_SLEEP)
}
#[doc = "Enable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn enable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_DM0_A::ENABLE_DEEP_SLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits =
(self.w.bits & !(0x01 << 1)) | ((value as u32 & 0x01) << 1);
self.w
}
}
#[doc = "Control DS pin of DM1 1Kx32"]
pub type CTRL_FFE_SRAM_DS_DM1_A = CTRL_FFE_SRAM_DS_CM0_A;
#[doc = "Field `CTRL_FFE_SRAM_DS_DM1` reader - Control DS pin of DM1 1Kx32"]
pub type CTRL_FFE_SRAM_DS_DM1_R = CTRL_FFE_SRAM_DS_CM0_R;
#[doc = "Field `CTRL_FFE_SRAM_DS_DM1` writer - Control DS pin of DM1 1Kx32"]
pub struct CTRL_FFE_SRAM_DS_DM1_W<'a> {
w: &'a mut W,
}
impl<'a> CTRL_FFE_SRAM_DS_DM1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CTRL_FFE_SRAM_DS_DM1_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Disable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn disable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_DM1_A::DISABLE_DEEP_SLEEP)
}
#[doc = "Enable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn enable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_DM1_A::ENABLE_DEEP_SLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits =
(self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2);
self.w
}
}
#[doc = "Control DS pin of SM0 1Kx18"]
pub type CTRL_FFE_SRAM_DS_SM0_A = CTRL_FFE_SRAM_DS_CM0_A;
#[doc = "Field `CTRL_FFE_SRAM_DS_SM0` reader - Control DS pin of SM0 1Kx18"]
pub type CTRL_FFE_SRAM_DS_SM0_R = CTRL_FFE_SRAM_DS_CM0_R;
#[doc = "Field `CTRL_FFE_SRAM_DS_SM0` writer - Control DS pin of SM0 1Kx18"]
pub struct CTRL_FFE_SRAM_DS_SM0_W<'a> {
w: &'a mut W,
}
impl<'a> CTRL_FFE_SRAM_DS_SM0_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CTRL_FFE_SRAM_DS_SM0_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Disable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn disable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_SM0_A::DISABLE_DEEP_SLEEP)
}
#[doc = "Enable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn enable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_SM0_A::ENABLE_DEEP_SLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits =
(self.w.bits & !(0x01 << 3)) | ((value as u32 & 0x01) << 3);
self.w
}
}
#[doc = "Control DS pin of SM1 0.5Kx18"]
pub type CTRL_FFE_SRAM_DS_SM1_A = CTRL_FFE_SRAM_DS_CM0_A;
#[doc = "Field `CTRL_FFE_SRAM_DS_SM1` reader - Control DS pin of SM1 0.5Kx18"]
pub type CTRL_FFE_SRAM_DS_SM1_R = CTRL_FFE_SRAM_DS_CM0_R;
#[doc = "Field `CTRL_FFE_SRAM_DS_SM1` writer - Control DS pin of SM1 0.5Kx18"]
pub struct CTRL_FFE_SRAM_DS_SM1_W<'a> {
w: &'a mut W,
}
impl<'a> CTRL_FFE_SRAM_DS_SM1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CTRL_FFE_SRAM_DS_SM1_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Disable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn disable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_SM1_A::DISABLE_DEEP_SLEEP)
}
#[doc = "Enable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn enable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_SM1_A::ENABLE_DEEP_SLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits =
(self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4);
self.w
}
}
#[doc = "Control DS pin of CM1 2Kx40"]
pub type CTRL_FFE_SRAM_DS_CM1_A = CTRL_FFE_SRAM_DS_CM0_A;
#[doc = "Field `CTRL_FFE_SRAM_DS_CM1` reader - Control DS pin of CM1 2Kx40"]
pub type CTRL_FFE_SRAM_DS_CM1_R = CTRL_FFE_SRAM_DS_CM0_R;
#[doc = "Field `CTRL_FFE_SRAM_DS_CM1` writer - Control DS pin of CM1 2Kx40"]
pub struct CTRL_FFE_SRAM_DS_CM1_W<'a> {
w: &'a mut W,
}
impl<'a> CTRL_FFE_SRAM_DS_CM1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CTRL_FFE_SRAM_DS_CM1_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Disable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn disable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_CM1_A::DISABLE_DEEP_SLEEP)
}
#[doc = "Enable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn enable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_CM1_A::ENABLE_DEEP_SLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits =
(self.w.bits & !(0x01 << 5)) | ((value as u32 & 0x01) << 5);
self.w
}
}
#[doc = "Control DS pin of CM0 1Kx32"]
pub type CTRL_FFE_SRAM_DS_DM2_A = CTRL_FFE_SRAM_DS_CM0_A;
#[doc = "Field `CTRL_FFE_SRAM_DS_DM2` reader - Control DS pin of CM0 1Kx32"]
pub type CTRL_FFE_SRAM_DS_DM2_R = CTRL_FFE_SRAM_DS_CM0_R;
#[doc = "Field `CTRL_FFE_SRAM_DS_DM2` writer - Control DS pin of CM0 1Kx32"]
pub struct CTRL_FFE_SRAM_DS_DM2_W<'a> {
w: &'a mut W,
}
impl<'a> CTRL_FFE_SRAM_DS_DM2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CTRL_FFE_SRAM_DS_DM2_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Disable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn disable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_DM2_A::DISABLE_DEEP_SLEEP)
}
#[doc = "Enable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn enable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_DM2_A::ENABLE_DEEP_SLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits =
(self.w.bits & !(0x01 << 6)) | ((value as u32 & 0x01) << 6);
self.w
}
}
#[doc = "Control DS pin of CM0 1Kx32"]
pub type CTRL_FFE_SRAM_DS_DM3_A = CTRL_FFE_SRAM_DS_CM0_A;
#[doc = "Field `CTRL_FFE_SRAM_DS_DM3` reader - Control DS pin of CM0 1Kx32"]
pub type CTRL_FFE_SRAM_DS_DM3_R = CTRL_FFE_SRAM_DS_CM0_R;
#[doc = "Field `CTRL_FFE_SRAM_DS_DM3` writer - Control DS pin of CM0 1Kx32"]
pub struct CTRL_FFE_SRAM_DS_DM3_W<'a> {
w: &'a mut W,
}
impl<'a> CTRL_FFE_SRAM_DS_DM3_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CTRL_FFE_SRAM_DS_DM3_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "Disable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn disable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_DM3_A::DISABLE_DEEP_SLEEP)
}
#[doc = "Enable the Deep Sleep function of SRAM Macro, Memory content will be kept."]
#[inline(always)]
pub fn enable_deep_sleep(self) -> &'a mut W {
self.variant(CTRL_FFE_SRAM_DS_DM3_A::ENABLE_DEEP_SLEEP)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits =
(self.w.bits & !(0x01 << 7)) | ((value as u32 & 0x01) << 7);
self.w
}
}
impl R {
#[doc = "Bit 0 - Control DS pin of CM0 8Kx40"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_cm0(&self) -> CTRL_FFE_SRAM_DS_CM0_R {
CTRL_FFE_SRAM_DS_CM0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Control DS pin of DM0 1Kx32"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_dm0(&self) -> CTRL_FFE_SRAM_DS_DM0_R {
CTRL_FFE_SRAM_DS_DM0_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Control DS pin of DM1 1Kx32"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_dm1(&self) -> CTRL_FFE_SRAM_DS_DM1_R {
CTRL_FFE_SRAM_DS_DM1_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Control DS pin of SM0 1Kx18"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_sm0(&self) -> CTRL_FFE_SRAM_DS_SM0_R {
CTRL_FFE_SRAM_DS_SM0_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Control DS pin of SM1 0.5Kx18"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_sm1(&self) -> CTRL_FFE_SRAM_DS_SM1_R {
CTRL_FFE_SRAM_DS_SM1_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Control DS pin of CM1 2Kx40"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_cm1(&self) -> CTRL_FFE_SRAM_DS_CM1_R {
CTRL_FFE_SRAM_DS_CM1_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Control DS pin of CM0 1Kx32"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_dm2(&self) -> CTRL_FFE_SRAM_DS_DM2_R {
CTRL_FFE_SRAM_DS_DM2_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Control DS pin of CM0 1Kx32"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_dm3(&self) -> CTRL_FFE_SRAM_DS_DM3_R {
CTRL_FFE_SRAM_DS_DM3_R::new(((self.bits >> 7) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Control DS pin of CM0 8Kx40"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_cm0(&mut self) -> CTRL_FFE_SRAM_DS_CM0_W {
CTRL_FFE_SRAM_DS_CM0_W { w: self }
}
#[doc = "Bit 1 - Control DS pin of DM0 1Kx32"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_dm0(&mut self) -> CTRL_FFE_SRAM_DS_DM0_W {
CTRL_FFE_SRAM_DS_DM0_W { w: self }
}
#[doc = "Bit 2 - Control DS pin of DM1 1Kx32"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_dm1(&mut self) -> CTRL_FFE_SRAM_DS_DM1_W {
CTRL_FFE_SRAM_DS_DM1_W { w: self }
}
#[doc = "Bit 3 - Control DS pin of SM0 1Kx18"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_sm0(&mut self) -> CTRL_FFE_SRAM_DS_SM0_W {
CTRL_FFE_SRAM_DS_SM0_W { w: self }
}
#[doc = "Bit 4 - Control DS pin of SM1 0.5Kx18"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_sm1(&mut self) -> CTRL_FFE_SRAM_DS_SM1_W {
CTRL_FFE_SRAM_DS_SM1_W { w: self }
}
#[doc = "Bit 5 - Control DS pin of CM1 2Kx40"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_cm1(&mut self) -> CTRL_FFE_SRAM_DS_CM1_W {
CTRL_FFE_SRAM_DS_CM1_W { w: self }
}
#[doc = "Bit 6 - Control DS pin of CM0 1Kx32"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_dm2(&mut self) -> CTRL_FFE_SRAM_DS_DM2_W {
CTRL_FFE_SRAM_DS_DM2_W { w: self }
}
#[doc = "Bit 7 - Control DS pin of CM0 1Kx32"]
#[inline(always)]
pub fn ctrl_ffe_sram_ds_dm3(&mut self) -> CTRL_FFE_SRAM_DS_DM3_W {
CTRL_FFE_SRAM_DS_DM3_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "Control the Deep Sleep pin of various elements in the Flexible Fusion Engine power domain. For each: 1'b1 : Enable the Deep Sleep function of SRAM Macro, Memory content will be kept.\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ffe_mem_ctrl_0](index.html) module"]
pub struct FFE_MEM_CTRL_0_SPEC;
impl crate::RegisterSpec for FFE_MEM_CTRL_0_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [ffe_mem_ctrl_0::R](R) reader structure"]
impl crate::Readable for FFE_MEM_CTRL_0_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [ffe_mem_ctrl_0::W](W) writer structure"]
impl crate::Writable for FFE_MEM_CTRL_0_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets FFE_MEM_CTRL_0 to value 0"]
impl crate::Resettable for FFE_MEM_CTRL_0_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| 36.927894
| 577
| 0.630389
|
a58fd1646b8a6fa5d98dfeee5502ac7276496eef
| 2,229
|
swift
|
Swift
|
SygicUIKit/Classes/Views/ProgressView/CirclePathCountdownView.swift
|
Sygic/sygic-ui-kit-ios
|
1cc765c80857f52204a42da3e65e57fe70df3ad9
|
[
"MIT"
] | 4
|
2018-11-28T10:02:38.000Z
|
2022-01-10T00:26:48.000Z
|
SygicUIKit/Classes/Views/ProgressView/CirclePathCountdownView.swift
|
Sygic/sygic-ui-kit-ios
|
1cc765c80857f52204a42da3e65e57fe70df3ad9
|
[
"MIT"
] | 4
|
2018-11-26T11:31:26.000Z
|
2020-03-14T08:47:03.000Z
|
SygicUIKit/Classes/Views/ProgressView/CirclePathCountdownView.swift
|
Sygic/sygic-ui-kit-ios
|
1cc765c80857f52204a42da3e65e57fe70df3ad9
|
[
"MIT"
] | 2
|
2019-10-03T07:36:59.000Z
|
2019-10-11T14:35:46.000Z
|
//// CirclePathCountdownView.swift
//
// Copyright (c) 2019 Sygic a.s.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/**
Circle path view with countdown.
To set countdown and stroke color call
```
public func setup(with countdownDuration: TimeInterval, strokeColor: UIColor = .action)
```
*/
public class CirclePathCountdownView: PathProgressView {
override public var path: UIBezierPath {
return UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - PathProgressView.lineWidth)/2, startAngle: CGFloat(.pi * -0.5), endAngle: CGFloat(.pi * 1.5), clockwise: true)
}
}
/**
Circle path view with progress.
To set progress and stroke color call
```
public func setup(progress: CGFloat, strokeColor: UIColor = .action)
```
*/
public class CirclePathProgressView: PathProgressView {
override public var path: UIBezierPath {
return UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - PathProgressView.lineWidth)/2, startAngle: CGFloat(.pi * -0.5), endAngle: CGFloat(.pi * -2.5), clockwise: false)
}
}
| 39.105263
| 243
| 0.73127
|
43600a1bf0694311f6ad35e13d9691f9da3758b3
| 766
|
ts
|
TypeScript
|
src/app/pages/users/users.module.ts
|
yellowcipher/sinprfba-admin
|
bc173dec704e1284f38cd7c8ad3b808870776b07
|
[
"MIT"
] | null | null | null |
src/app/pages/users/users.module.ts
|
yellowcipher/sinprfba-admin
|
bc173dec704e1284f38cd7c8ad3b808870776b07
|
[
"MIT"
] | 10
|
2020-05-11T20:26:30.000Z
|
2022-03-02T05:33:16.000Z
|
src/app/pages/users/users.module.ts
|
yellowcipher/sinprfba-admin
|
bc173dec704e1284f38cd7c8ad3b808870776b07
|
[
"MIT"
] | null | null | null |
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { routedComponents, UsersRoutingModule } from './users-routing.module';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import { NbCardModule, NbSelectModule } from '@nebular/theme';
import { NewUserComponent } from './new-user/new-user.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { TextMaskModule } from 'angular2-text-mask';
const MODULES = [
CommonModule,
UsersRoutingModule,
Ng2SmartTableModule,
NbCardModule,
FormsModule,
ReactiveFormsModule,
TextMaskModule,
NbSelectModule,
];
@NgModule({
declarations: [ ...routedComponents, NewUserComponent ],
imports: [ ...MODULES ],
})
export class UsersModule {}
| 29.461538
| 78
| 0.751958
|
cdd9e7dbcb9ceb560de883c8dc8a0ccffe251772
| 6,113
|
cs
|
C#
|
src/Technosoftware/DaAeHdaClient/Hda/BrowseFilterCollection.cs
|
technosoftware-gmbh/opc-daaehda-client-net
|
a53138d2cdd3d66e1eb5939b028798cadf19ad78
|
[
"MIT"
] | 11
|
2019-09-02T06:52:07.000Z
|
2019-12-17T22:03:42.000Z
|
src/Technosoftware/DaAeHdaClient/Hda/BrowseFilterCollection.cs
|
technosoftware-gmbh/opc-daaehda-client-net
|
a53138d2cdd3d66e1eb5939b028798cadf19ad78
|
[
"MIT"
] | null | null | null |
src/Technosoftware/DaAeHdaClient/Hda/BrowseFilterCollection.cs
|
technosoftware-gmbh/opc-daaehda-client-net
|
a53138d2cdd3d66e1eb5939b028798cadf19ad78
|
[
"MIT"
] | 8
|
2019-08-10T10:50:13.000Z
|
2019-12-22T12:55:32.000Z
|
#region Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved
//-----------------------------------------------------------------------------
// Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved
// Web: https://www.technosoftware.com
//
// The source code in this file is covered under a dual-license scenario:
// - Owner of a purchased license: SCLA 1.0
// - GPL V3: everybody else
//
// SCLA license terms accompanied with this source code.
// See SCLA 1.0://technosoftware.com/license/Source_Code_License_Agreement.pdf
//
// GNU General Public License as published by the Free Software Foundation;
// version 3 of the License are accompanied with this source code.
// See https://technosoftware.com/license/GPLv3License.txt
//
// This source code 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.
//-----------------------------------------------------------------------------
#endregion Copyright (c) 2011-2022 Technosoftware GmbH. All rights reserved
#region Using Directives
using System;
using System.Collections;
#endregion
namespace Technosoftware.DaAeHdaClient.Hda
{
/// <summary>
/// A collection of attribute filters used when browsing the server address space.
/// </summary>
[Serializable]
public class TsCHdaBrowseFilterCollection : OpcItem, ICollection
{
#region Fields
private TsCHdaBrowseFilter[] browseFilters_ = new TsCHdaBrowseFilter[0];
#endregion
#region Constructors, Destructor, Initialization
/// <summary>
/// Creates an empty collection.
/// </summary>
public TsCHdaBrowseFilterCollection()
{
// do nothing.
}
/// <summary>
/// Initializes the object with any BrowseFilter contained in the collection.
/// </summary>
/// <param name="collection">A collection containing browse filters.</param>
public TsCHdaBrowseFilterCollection(ICollection collection)
{
Init(collection);
}
#endregion
#region Properties
/// <summary>
/// Returns the browse filter at the specified index.
/// </summary>
public TsCHdaBrowseFilter this[int index]
{
get => browseFilters_[index];
set => browseFilters_[index] = value;
}
#endregion
#region Public Methods
/// <summary>
/// Returns the browse filter for the specified attribute id.
/// </summary>
public TsCHdaBrowseFilter Find(int id)
{
foreach (TsCHdaBrowseFilter filter in browseFilters_)
{
if (filter.AttributeID == id)
{
return filter;
}
}
return null;
}
/// <summary>
/// Initializes the object with any attribute values contained in the collection.
/// </summary>
/// <param name="collection">A collection containing attribute values.</param>
public void Init(ICollection collection)
{
Clear();
if (collection != null)
{
ArrayList values = new ArrayList(collection.Count);
foreach (object value in collection)
{
if (value.GetType() == typeof(TsCHdaBrowseFilter))
{
values.Add(OpcConvert.Clone(value));
}
}
browseFilters_ = (TsCHdaBrowseFilter[])values.ToArray(typeof(TsCHdaBrowseFilter));
}
}
/// <summary>
/// Removes all attribute values in the collection.
/// </summary>
public void Clear()
{
browseFilters_ = new TsCHdaBrowseFilter[0];
}
#endregion
#region ICloneable Members
/// <summary>
/// Creates a deep copy of the object.
/// </summary>
public override object Clone()
{
return new TsCHdaBrowseFilterCollection(this);
}
#endregion
#region ICollection Members
/// <summary>
/// Indicates whether access to the ICollection is synchronized (thread-safe).
/// </summary>
public bool IsSynchronized => false;
/// <summary>
/// Gets the number of objects in the collection.
/// </summary>
public int Count => browseFilters_?.Length ?? 0;
/// <summary>
/// Copies the objects in to an Array, starting at a the specified index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination for the objects.</param>
/// <param name="index">The zero-based index in the Array at which copying begins.</param>
public void CopyTo(Array array, int index)
{
browseFilters_?.CopyTo(array, index);
}
/// <summary>
/// Copies the objects to an Array, starting at a the specified index.
/// </summary>
/// <param name="array">The one-dimensional Array that is the destination for the objects.</param>
/// <param name="index">The zero-based index in the Array at which copying begins.</param>
public void CopyTo(TsCHdaBrowseFilter[] array, int index)
{
CopyTo((Array)array, index);
}
/// <summary>
/// Indicates whether access to the ICollection is synchronized (thread-safe).
/// </summary>
public object SyncRoot => this;
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that can iterate through a collection.
/// </summary>
/// <returns>An IEnumerator that can be used to iterate through the collection.</returns>
public IEnumerator GetEnumerator()
{
return browseFilters_.GetEnumerator();
}
#endregion
}
}
| 34.150838
| 106
| 0.57664
|
b05322c0201b2ace1dc01fe18aad442a9f023906
| 1,170
|
py
|
Python
|
esteganography/arguments.py
|
giovaninppc/MC920
|
7d46238f4079dabc4769c72cbed44d024fcf5c97
|
[
"MIT"
] | 1
|
2019-08-23T19:23:18.000Z
|
2019-08-23T19:23:18.000Z
|
esteganography/arguments.py
|
giovaninppc/MC920
|
7d46238f4079dabc4769c72cbed44d024fcf5c97
|
[
"MIT"
] | null | null | null |
esteganography/arguments.py
|
giovaninppc/MC920
|
7d46238f4079dabc4769c72cbed44d024fcf5c97
|
[
"MIT"
] | 1
|
2020-11-05T23:56:49.000Z
|
2020-11-05T23:56:49.000Z
|
import argparse
def setupCodificationArguments():
argParser = argparse.ArgumentParser(description = 'Arguments for the Image processing')
argParser.add_argument('input_image_path', help = 'The path to image file to be processed')
argParser.add_argument('input_text', help = 'The path to the text to be codificated')
argParser.add_argument('bits', help = 'The bit plan to be used')
argParser.add_argument('output_image_path', help = 'The path to image file to be stored')
argParser.add_argument('-d', '--debug', help='Show debug info', action='store_true')
args = argParser.parse_args()
return args
def setupDecodificationArguments():
argParser = argparse.ArgumentParser(description = 'Arguments for the Image processing')
argParser.add_argument('input_image_path', help = 'The path to image file to be processed')
argParser.add_argument('bits', help = 'The bit plan to be used')
argParser.add_argument('output_text_path', help = 'The path to decripted text file to be stored')
argParser.add_argument('-d', '--debug', help='Show debug info', action='store_true')
args = argParser.parse_args()
return args
| 46.8
| 101
| 0.730769
|
a0742ab8dec1ff72315b52d98483cc93492b4879
| 815
|
dart
|
Dart
|
WebPlatformTest/custom-elements/instantiating/createElement_A01_t01.dart
|
tvolkert/co19
|
435727789062a45da3d20da09024651fdeb8cafe
|
[
"BSD-3-Clause"
] | null | null | null |
WebPlatformTest/custom-elements/instantiating/createElement_A01_t01.dart
|
tvolkert/co19
|
435727789062a45da3d20da09024651fdeb8cafe
|
[
"BSD-3-Clause"
] | null | null | null |
WebPlatformTest/custom-elements/instantiating/createElement_A01_t01.dart
|
tvolkert/co19
|
435727789062a45da3d20da09024651fdeb8cafe
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
/*
* Portions of this test are derived from code under the following license:
*
* Web-platform-tests are covered by the dual-licensing approach described in:
* http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html
*/
/**
* @assertion If typeExtension is not present then type is a local name.
*/
import 'dart:html';
import "../../../Utils/expect.dart";
class Foo extends HtmlElement {
static const tag = 'x-foo';
Foo.created() : super.created();
}
main() {
document.register(Foo.tag, Foo);
var x = document.createElement(Foo.tag);
Expect.isTrue(x is Foo);
}
| 28.103448
| 78
| 0.705521
|
d320297ff4d5a0100fd5457f67acc175a1131271
| 4,597
|
css
|
CSS
|
public/angular/registration-locum/registration_locum.css
|
darkokostic/locum-project
|
7fea13aba7f288cb17d1258b60be9eb9476271ac
|
[
"MIT"
] | null | null | null |
public/angular/registration-locum/registration_locum.css
|
darkokostic/locum-project
|
7fea13aba7f288cb17d1258b60be9eb9476271ac
|
[
"MIT"
] | null | null | null |
public/angular/registration-locum/registration_locum.css
|
darkokostic/locum-project
|
7fea13aba7f288cb17d1258b60be9eb9476271ac
|
[
"MIT"
] | null | null | null |
.hover-query select {
max-width: 264px;
height: 40px;
border: none;
}
.hover-query select:focus {
outline: none !important;
}
.container-locum {
margin-top: 80px;
}
.registration-locum {
border-radius: 4px;
background-color: rgb(255, 255, 255);
box-shadow: 0px 1px 13px 0px rgba(0, 0, 0, 0.12);
z-index: 31;
}
.registration-locum h1 {
font-size: 25px;
color: rgb(33, 33, 33);
line-height: 1.2;
text-align: center;
z-index: 122;
}
.registration-locum h2 {
font-size: 16px;
color: rgb(144, 164, 174);
line-height: 1.438;
text-align: center;
-moz-transform: matrix( 0.99988637508828, 0, 0, 1, 0, 0);
-webkit-transform: matrix( 0.99988637508828, 0, 0, 1, 0, 0);
-ms-transform: matrix( 0.99988637508828, 0, 0, 1, 0, 0);
z-index: 120;
margin: 0;
margin-top: 10px;
}
.line-registration-locum {
text-align: center;
}
.input-registration-locum i {
color: rgb(207, 216, 220);
/*margin-left: 20px;*/
font-size: 11px;
line-height: 42px;
}
.input-registration-locum {
border-style: solid;
border-width: 1px;
border-color: rgb(207, 216, 220);
border-radius: 2px;
background-color: rgba(233, 132, 4, 0);
z-index: 78;
min-height: 42px;
margin-top: 25px;
margin-left: 22%;
margin-right: 22%;
}
.registration-form input {
border: none;
font-size: 14px;
margin-top: 9px;
width: 100%;
}
.registration-form input:hover {
border: none;
}
.registration-form input:focus {
border: none;
outline: none;
}
.registration-form input:active {
border: none;
}
.registration-locum-button button {
background-color: #fff;
border: 1px solid #ff8f00;
width: 100%;
min-height: 42px;
color: #ff8f00;
margin-top: 20px;
border-radius: 2px;
}
.registration-locum-button button:hover {
background-color: #ff8f00;
color: #fff;
border-color: #ff8f00;
}
.registration-locum-button button:active {
background-color: #fff;
color: #ff8f00;
border-color: #ff8f00;
}
.registration-locum-button button:active:focus {
background-color: #ff8f00;
color: #fff;
border-color: #ff8f00;
outline: none;
}
.registration-locum-button button:focus {
background-color: #fff;
color: #ff8f00;
border-color: #ff8f00;
outline: none;
}
.registration-locum-button {
margin-bottom: 20px;
margin-left: 22%;
margin-right: 22%;
}
.sign-up-button-locum {
padding-left: 66px;
padding-right: 66px;
}
.input-register i span {
font-family: 'Asap', sans-serif;
font-weight: 700;
color: #000;
margin-left: 10px;
}
.input-register i {
font-weight: 700;
color: #000;
margin-left: 0px;
}
.input-registration-locum i span {
font-family: 'Asap', sans-serif;
font-weight: 700;
color: #000;
margin-left: 7px;
}
.input-registration-locum i {
font-weight: 700;
color: #000;
}
.input-about {
max-width: 145px;
}
.terms-conditions-hover {
color: rgb(144, 164, 174);
}
.terms-conditions-hover:hover {
color: #ff8f00;
text-decoration: none;
}
.terms-conditions-hover:focus {
color: rgb(144, 164, 174);
text-decoration: none;
}
.left-checkbox-locum {
margin-left: 13%;
}
@media (max-width: 1000px) {
.input-registration-locum {
margin-left: 0%;
margin-right: 0%;
}
.input-register {
margin-left: 0%;
margin-right: 0%;
}
.input-first-last-name {
max-width: 230px;
}
.input-register i {
margin-left: 0px;
}
}
@media (max-width: 750px) {
.input-registration-locum {
margin-left: 12%;
margin-right: 12%;
}
.input-register {
margin-left: 12%;
margin-right: 12%;
}
.input-register i {
margin-left: 0px;
}
}
@media (max-width: 500px) {
.input-registration-locum {
margin-left: 0;
margin-right: 0;
}
.input-register {
margin-left: 0%;
margin-right: 0%;
}
.input-registration-locum i {
margin-left: 0px;
}
.input-register i {
margin-left: 0px;
}
.input-registration-locum i span {
margin-left: 0px;
}
.input-register i span {
margin-left: 0px;
}
}
/*responsive*/
@media only screen and (max-width: 768px) {
.container-locum {
margin-top: 0px;
}
.hover-query select {
width: 190px;
}
.input-registration-locum i {
margin-left:0px;
}
}
@media (max-width: 768px) {
.left-checkbox-locum {
margin-left: 0;
}
}
| 20.800905
| 64
| 0.594518
|
a54eac147e0fbfdf7ea960136238cf0cf9511181
| 262
|
sql
|
SQL
|
components/schema-migrator/migrations/director/202001271010_change_unique_on_business_tenants.down.sql
|
piotrmsc/compass
|
17d624e0c925a1f93fe1cb277314645262105457
|
[
"Apache-2.0"
] | 47
|
2019-05-15T07:47:27.000Z
|
2022-02-22T19:48:21.000Z
|
components/schema-migrator/migrations/director/202001271010_change_unique_on_business_tenants.down.sql
|
piotrmsc/compass
|
17d624e0c925a1f93fe1cb277314645262105457
|
[
"Apache-2.0"
] | 1,774
|
2019-05-14T09:53:10.000Z
|
2022-03-31T20:46:33.000Z
|
components/schema-migrator/migrations/director/202001271010_change_unique_on_business_tenants.down.sql
|
piotrmsc/compass
|
17d624e0c925a1f93fe1cb277314645262105457
|
[
"Apache-2.0"
] | 101
|
2019-05-14T09:36:08.000Z
|
2022-01-06T09:43:44.000Z
|
alter table business_tenant_mappings
drop constraint business_tenant_mappings_external_tenant_unique;
alter table business_tenant_mappings
add constraint business_tenant_mappings_external_tenant_provider_name_key unique (external_tenant, provider_name);
| 52.4
| 118
| 0.89313
|
cdab2b812fa5fbc05bae25506b64ad1147d6f5f6
| 1,800
|
cs
|
C#
|
Desafios em C#/1786 - CPF 2.cs
|
lucasmarcuzo/URI
|
86c470965831c9bbe9c01ba7ff32fdc0492a4995
|
[
"MIT"
] | null | null | null |
Desafios em C#/1786 - CPF 2.cs
|
lucasmarcuzo/URI
|
86c470965831c9bbe9c01ba7ff32fdc0492a4995
|
[
"MIT"
] | null | null | null |
Desafios em C#/1786 - CPF 2.cs
|
lucasmarcuzo/URI
|
86c470965831c9bbe9c01ba7ff32fdc0492a4995
|
[
"MIT"
] | null | null | null |
using System;
//Developed by: @LucasMarcuzo
class URI
{
static void Main(string[] args)
{
while(true)
{
string cpf = " ";
int verificar=0, verificar2=0, teste1=1, teste2=9;
int[] cpf_ver=new int[9];
int[] cpf_ver2=new int[9];
cpf=Console.ReadLine();
if (string.IsNullOrEmpty(cpf))
{
break;
}
else
{
for (int i = 0; i < cpf_ver.Length; i++)
{
cpf_ver[i]=Convert.ToInt32(cpf.Substring(i, 1));
verificar+=cpf_ver[i]*teste1;
teste1++;
}
verificar%=11;
if(verificar == 10)
{
verificar=0;
}
for (int j = 0; j < cpf_ver2.Length; j++)
{
cpf_ver2[j]=Convert.ToInt32(cpf.Substring(j, 1));
verificar2+=cpf_ver2[j]*teste2;
teste2--;
}
verificar2%=11;
if(verificar2 == 10)
{
verificar2=0;
}
int[] cpf_completo = new int[11];
Array.Copy(cpf_ver, cpf_completo, 9);
cpf_completo[9]=verificar;
cpf_completo[10]=verificar2;
Console.WriteLine("{0}{1}{2}.{3}{4}{5}.{6}{7}{8}-{9}{10}", cpf_completo[0], cpf_completo[1], cpf_completo[2],
cpf_completo[3], cpf_completo[4], cpf_completo[5], cpf_completo[6], cpf_completo[7], cpf_completo[8], cpf_completo[9], cpf_completo[10]);
}
}
}
}
| 26.470588
| 153
| 0.405
|
b8fdfb617992f9a863ef31d11eae48c59da0772b
| 8,612
|
py
|
Python
|
bin/bundle_tools/staging.py
|
HumanCellAtlas/data-bundle-examples
|
58e13576dac4e2429d58a2a7d2ba0b982d7cf8b4
|
[
"Apache-2.0"
] | 13
|
2017-06-01T12:40:54.000Z
|
2022-01-09T07:31:55.000Z
|
bin/bundle_tools/staging.py
|
HumanCellAtlas/data-bundle-examples
|
58e13576dac4e2429d58a2a7d2ba0b982d7cf8b4
|
[
"Apache-2.0"
] | 13
|
2017-06-14T05:24:42.000Z
|
2018-08-01T02:10:22.000Z
|
bin/bundle_tools/staging.py
|
HumanCellAtlas/data-bundle-examples
|
58e13576dac4e2429d58a2a7d2ba0b982d7cf8b4
|
[
"Apache-2.0"
] | 4
|
2017-08-04T14:40:18.000Z
|
2021-12-03T21:38:20.000Z
|
import os
from shutil import copyfileobj
import urllib3
from urllib3.util import parse_url
from checksumming_io.checksumming_io import ChecksummingSink
from .parallel_logger import logger
from .utils import sizeof_fmt, measure_duration_and_rate
from .s3 import S3Location, S3Agent, S3ObjectTagger
from bundle_tools import LocalBundle, File, DataFile, MetadataFile, SubmissionInfo
class BundleMissingDataFile(Exception):
pass
def report_duration_and_rate(func, *args, size):
retval, duration, rate = measure_duration_and_rate(func, *args, size=size)
logger.output(" (%.1f sec, %.1f MiB/sec) " % (duration, rate))
return retval
s3 = S3Agent()
http = urllib3.PoolManager()
class BundleStager:
def __init__(self, bundle: LocalBundle, target_bucket: str):
self.bundle = bundle
self.target_bucket = target_bucket
def stage(self, comment=""):
logger.output(f"\nBundle: {self.bundle.path} {comment}", "B")
try:
self.bundle.submission_info = SubmissionInfo(self.target_bucket, self.bundle)
self.bundle.submission_info.load()
self.bundle.enumerate_local_metadata_files()
self.bundle.enumerate_data_files_using_manifest()
self._stage_files_of_type(DataFile)
self._stage_files_of_type(MetadataFile)
if self.bundle.submission_info.save():
logger.output("\n Writing submission.json", progress_char='*')
except BundleMissingDataFile as e:
logger.output(f" -> {str(e)}\n", "!")
logger.flush()
def _stage_files_of_type(self, file_class):
files = [file for file in self.bundle.files.values() if type(file) == file_class]
logger.output(f"\n {file_class.__name__}s ({len(files)}):")
for file in files:
logger.output(f"\n {file.name} ({sizeof_fmt(file.size)}) ")
if type(file) == DataFile:
DataFileStager(file).stage_file(self.target_bucket)
else:
MetadataFileStager(file).stage(self.target_bucket)
class DataFileStager:
def __init__(self, file):
self.file = file
self.bundle = file.bundle
self.target_url = None
def stage_file(self, target_bucket):
self.target_url = f"s3://{target_bucket}/{self.file.path()}"
if self._obj_is_at_target_location():
logger.output("=present ", progress_char="✔︎")
else:
src_location = self.source_data_file()
self.copy_file_to_target_location(src_location)
self._delete_downloaded_file(src_location)
self.file.staged_url = self.target_url
self._ensure_checksum_tags()
def _obj_is_at_target_location(self):
obj = s3.get_object(self.target_url)
if obj:
if obj.content_length == self.file.size:
return self.etag_matches_or_not_present(obj)
else:
logger.output("\n exists at target but has different size: %d / %d" %
(self.file.size, obj.content_length))
return False
def etag_matches_or_not_present(self, obj):
s3_etag = obj.e_tag.strip('"')
tags = s3.get_tagging(self.target_url)
if tags.get('hca-dss-s3_etag'):
if s3_etag == tags['hca-dss-s3_etag']:
return True
else:
logger.output("\n exists at target but has wrong etag: %s / %s" %
(s3_etag, tags['hca-dss-s3_etag']))
logger.output("\n copy to itself to correct etag... ", progress_char='↻︎')
report_duration_and_rate(s3.copy_between_buckets,
self.target_url, self.target_url, self.file.size,
size=self.file.size)
return True
else:
# File size matches but file has no checksum tag.
# Assume file is good and proceed so we compute new checksums.
return True
def source_data_file(self):
location = self._find_locally() or self._download_from_origin()
if location:
logger.output(f"\n found at {location}")
return location
raise BundleMissingDataFile(f"Cannot find source for {self.file.name}")
def copy_file_to_target_location(self, source_location):
if parse_url(source_location).scheme == 's3':
self.copy_s3_file_to_target_location(source_location)
elif parse_url(source_location).scheme == 'file':
self.copy_local_file_to_target_location(source_location)
else:
raise RuntimeError(f"Unrecognized scheme: {source_location}")
def copy_s3_file_to_target_location(self, source_location):
logger.output(f"\n copy to {self.target_url} ", "C")
report_duration_and_rate(s3.copy_between_buckets,
source_location,
self.target_url,
self.file.size,
size=self.file.size)
S3ObjectTagger(self.target_url).complete_tags()
def copy_local_file_to_target_location(self, source_location):
local_path = parse_url(source_location).path.lstrip('/')
logger.output(f"\n upload to {self.target_url} ", "⬆︎")
self.file.checksums = report_duration_and_rate(s3.upload_and_checksum,
local_path,
self.target_url,
self.file.size,
size=self.file.size)
S3ObjectTagger(self.target_url).tag_using_these_checksums(self.file.checksums)
logger.output("+tagging ")
def _find_locally(self):
local_path = self.file.path()
if os.path.isfile(local_path) and os.stat(local_path).st_size == self.file.size:
return f"file:///{local_path}"
return None
def _download_from_origin(self):
logger.output(f"\n downloading {self.file.origin_url}", "↓")
dest_path = self.file.path()
try:
report_duration_and_rate(self._download, self.file.origin_url, dest_path, size=self.file.size)
return f"file:///{dest_path}"
# except urllib.error.HTTPError:
except Exception as e:
logger.output(f" error downloading ({str(e)})", "!")
os.remove(dest_path)
return None
def _ensure_checksum_tags(self):
if S3ObjectTagger(self.target_url).complete_tags():
logger.progress("+")
@staticmethod
def _delete_downloaded_file(location):
urlbits = parse_url(location)
if urlbits.scheme == 'file':
logger.output(f"\n Deleting {location}")
os.remove(urlbits.path.lstrip('/'))
@staticmethod
def _download(src_url: str, dest_path: str):
with open(dest_path, 'wb') as out_file:
# TODO now that we switched from urlopen(), this will fail with FTP files
with http.request('GET', src_url, preload_content=False) as in_stream:
copyfileobj(in_stream, out_file)
class MetadataFileStager:
def __init__(self, file: File):
self.file = file
self.bundle = file.bundle
def stage(self, bucket):
self.target = f"s3://{bucket}/{self.file.path()}"
if self._obj_is_at_target_location():
logger.output("=present ", progress_char="✓")
S3ObjectTagger(self.target).complete_tags()
else:
logger.output("+uploading ", progress_char="↑")
checksums = s3.upload_and_checksum(self.file.path(), self.target, self.file.size)
S3ObjectTagger(self.target).tag_using_these_checksums(checksums)
logger.output("+tagging ")
self.file.staged_url = self.target
def _obj_is_at_target_location(self):
obj = s3.get_object(self.target)
if obj:
local_checksums = self._checksum_local_file()
if local_checksums['s3_etag'] == obj.e_tag.strip('"'):
return True
else:
logger.output(f"\n exists at target but has a different ETAG ")
return False
def _checksum_local_file(self):
with ChecksummingSink() as sink:
with open(self.file.path(), 'rb') as fh:
copyfileobj(fh, sink)
return sink.get_checksums()
| 40.242991
| 106
| 0.603925
|
25e8f7366d615487eade8f65e88277d7eef0b17e
| 2,218
|
cs
|
C#
|
DataAccess/Concrete/EntityFramework/EfCarDal.cs
|
OzerBey/ReCapProject
|
702d76e274649dc04075fed52eea829abed3f79a
|
[
"MIT"
] | 15
|
2021-02-08T22:49:15.000Z
|
2021-09-17T09:01:41.000Z
|
DataAccess/Concrete/EntityFramework/EfCarDal.cs
|
OzerBey/ReCapProject
|
702d76e274649dc04075fed52eea829abed3f79a
|
[
"MIT"
] | null | null | null |
DataAccess/Concrete/EntityFramework/EfCarDal.cs
|
OzerBey/ReCapProject
|
702d76e274649dc04075fed52eea829abed3f79a
|
[
"MIT"
] | null | null | null |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using Core.DataAccess;
using Core.DataAccess.EntityFramework;
using DataAccess.Abstract;
using Entities.Concrete;
using Entities.DTOs;
using Microsoft.EntityFrameworkCore;
namespace DataAccess.Concrete.EntityFramework
{
//NuGet: DataAccess icinde entityframework kodu yazabilecegimiz anlamına gelir
public class EfCarDal : EfEntityRepositoryBase<Car, ReCapDatabaseContext>, ICarDal
{
public List<CarDetailDto> GetCarDetails(Expression<Func<Car, bool>> filter = null)
{
using (ReCapDatabaseContext context = new ReCapDatabaseContext())
{
var result = from cr in filter == null ? context.Cars : context.Cars.Where(filter)
join br in context.Brands
on cr.BrandId equals br.BrandId
join co in context.Colors
on cr.ColorId equals co.ColorId
join image in context.CarImages on cr.CarId equals image.CarId
select new CarDetailDto //sonucu buradaki kolonlara (verilere) uydurarak verilmesi söyleniliyor
{
CarId = cr.CarId,
BrandId = br.BrandId,
ColorId = co.ColorId,
ModelYear = cr.ModelYear,
Description = cr.Descriptions, // döndürülecek olan (istenilen) veri tabanımda carName diye kolon yapmadıgım icin Description verdim
BrandName = br.BrandName, // istenilen degerleri belirlenen bölümlerden cekerek geri döndürür
ColorName = co.ColorName,
DailyPrice = cr.DailyPrice,
ImageId = image.Id,
ImagePath = image.ImagePath,
CarImageDate = image.CarImageDate
};
return result.ToList();
}
}
}
}
| 44.36
| 165
| 0.545987
|
b74e4af4cd191956e70ee4f07f014b9d5fca2832
| 284
|
cs
|
C#
|
Domain/Context/EntityBase.cs
|
lucasvieiravicente/ApiResume
|
5d34f24baee3d151e3226ff6543c3b7aaf7b4c3d
|
[
"MIT"
] | null | null | null |
Domain/Context/EntityBase.cs
|
lucasvieiravicente/ApiResume
|
5d34f24baee3d151e3226ff6543c3b7aaf7b4c3d
|
[
"MIT"
] | null | null | null |
Domain/Context/EntityBase.cs
|
lucasvieiravicente/ApiResume
|
5d34f24baee3d151e3226ff6543c3b7aaf7b4c3d
|
[
"MIT"
] | null | null | null |
using System;
namespace ApiResume.Domain.Context
{
public class EntityBase
{
public Guid Id { get; set; }
public DateTime DateAdded { get; set; }
public DateTime DateModified { get; set; }
public bool FlagActive { get; set; } = true;
}
}
| 21.846154
| 52
| 0.605634
|
ae35d18cd082ddac14575ef0440aac3e0aea80c2
| 691
|
swift
|
Swift
|
hw6/SwiftGenerics_01.playground/Contents.swift
|
webunreal/sber
|
9b420c17f2210a77eb9ba81d580b14721f5f8e64
|
[
"MIT"
] | null | null | null |
hw6/SwiftGenerics_01.playground/Contents.swift
|
webunreal/sber
|
9b420c17f2210a77eb9ba81d580b14721f5f8e64
|
[
"MIT"
] | null | null | null |
hw6/SwiftGenerics_01.playground/Contents.swift
|
webunreal/sber
|
9b420c17f2210a77eb9ba81d580b14721f5f8e64
|
[
"MIT"
] | null | null | null |
import UIKit
// MARK: - Задача 1 "Сделать так, чтобы закомментированный код работал"
func sumTwoValues<T: AdditiveArithmetic>(_ a: T, _ b: T) -> T {
let result = a + b
return result
}
let a = 25.0
let b = 34.0
let resultDouble = sumTwoValues(a, b)
print(resultDouble)
let c = "ABC"
let d = "DEF"
let resultString = sumTwoValues(c, d)
print(resultString)
extension String: AdditiveArithmetic {
public static var zero: String {
""
}
public static func - (lhs: String, rhs: String) -> String {
var lhsArray = Array(lhs)
let rhsArray = Array(rhs)
lhsArray.removeAll { rhsArray.contains($0) }
return String(lhsArray)
}
}
| 19.742857
| 71
| 0.636758
|
f4630a4732ee9561ab027cfe9d1de47bde094e86
| 3,788
|
tsx
|
TypeScript
|
src/Molecules/CoachMarks/BubbleArrow/BubbleArrow.tsx
|
nordnet/ui
|
668f64d8b4b0f94c35277930247f5ae162564893
|
[
"MIT"
] | 29
|
2019-03-15T12:56:14.000Z
|
2022-03-29T10:20:12.000Z
|
src/Molecules/CoachMarks/BubbleArrow/BubbleArrow.tsx
|
nordnet/ui
|
668f64d8b4b0f94c35277930247f5ae162564893
|
[
"MIT"
] | 1,052
|
2019-03-22T09:58:11.000Z
|
2022-03-29T15:07:20.000Z
|
src/Molecules/CoachMarks/BubbleArrow/BubbleArrow.tsx
|
nordnet/ui
|
668f64d8b4b0f94c35277930247f5ae162564893
|
[
"MIT"
] | 6
|
2019-06-17T08:58:06.000Z
|
2021-07-07T14:11:02.000Z
|
import React from 'react';
import styled, { css } from 'styled-components';
import { Component, InternalProps, Props } from './BubbleArrow.types';
import { TRIANGLE_INDENTATION, TRIANGLE_SIZE } from './consts';
import { BORDER_SIZE } from '../Bubble/consts';
const arrowUp = css`
&::before {
border-left: ${TRIANGLE_SIZE}px solid transparent;
border-right: ${TRIANGLE_SIZE}px solid transparent;
border-bottom: ${TRIANGLE_SIZE}px solid ${(p) => p.theme.color.bubbleBorder};
}
&::after {
left: ${BORDER_SIZE * 2}px;
top: ${BORDER_SIZE * 2}px;
border-left: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid transparent;
border-right: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid transparent;
border-bottom: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid
${(p) => p.theme.color.bubbleBackground};
}
`;
const arrowRight = css`
&::before {
border-top: ${TRIANGLE_SIZE}px solid transparent;
border-bottom: ${TRIANGLE_SIZE}px solid transparent;
border-left: ${TRIANGLE_SIZE}px solid ${(p) => p.theme.color.bubbleBorder};
}
&::after {
left: 0;
top: ${BORDER_SIZE * 2}px;
border-top: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid transparent;
border-bottom: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid transparent;
border-left: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid ${(p) => p.theme.color.bubbleBackground};
}
`;
const arrowDown = css`
&::before {
border-left: ${TRIANGLE_SIZE}px solid transparent;
border-right: ${TRIANGLE_SIZE}px solid transparent;
border-top: ${TRIANGLE_SIZE}px solid ${(p) => p.theme.color.bubbleBorder};
}
&::after {
left: ${BORDER_SIZE * 2}px;
top: 0;
border-left: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid transparent;
border-right: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid transparent;
border-top: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid ${(p) => p.theme.color.bubbleBackground};
}
`;
const arrowLeft = css`
&::before {
border-top: ${TRIANGLE_SIZE}px solid transparent;
border-bottom: ${TRIANGLE_SIZE}px solid transparent;
border-right: ${TRIANGLE_SIZE}px solid ${(p) => p.theme.color.bubbleBorder};
}
&::after {
left: ${BORDER_SIZE * 2}px;
top: ${BORDER_SIZE * 2}px;
border-top: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid transparent;
border-bottom: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid transparent;
border-right: ${TRIANGLE_SIZE - BORDER_SIZE * 2}px solid
${(p) => p.theme.color.bubbleBackground};
}
`;
const Arrow = styled.div<InternalProps>`
position: absolute;
&::before,
&::after {
content: '';
display: block;
width: 0;
height: 0;
position: absolute;
top: 0;
left: 0;
}
${(p) => (p.$bubblePlacement === 'left' ? arrowRight : '')}
${(p) => (p.$bubblePlacement === 'top' ? arrowDown : '')}
${(p) => (p.$bubblePlacement === 'right' ? arrowLeft : '')}
${(p) => (p.$bubblePlacement === 'bottom' ? arrowUp : '')}
`;
const getArrowPositionStyles = (bubblePlacement: Props['bubblePlacement']) => {
if (bubblePlacement === 'top') {
return {
left: TRIANGLE_INDENTATION,
top: '100%',
};
}
if (bubblePlacement === 'right') {
return {
left: 0 - TRIANGLE_SIZE,
top: TRIANGLE_INDENTATION,
};
}
if (bubblePlacement === 'left') {
return {
left: '100%',
top: TRIANGLE_INDENTATION,
};
}
// position === bottom
return {
left: TRIANGLE_INDENTATION,
top: 0 - TRIANGLE_SIZE,
};
};
export const BubbleArrow: Component = React.forwardRef<HTMLDivElement, Props>(
({ bubblePlacement }, ref) => {
const arrowPositionStyles = getArrowPositionStyles(bubblePlacement);
return <Arrow $bubblePlacement={bubblePlacement} style={arrowPositionStyles} ref={ref} />;
},
);
| 29.364341
| 101
| 0.642027
|
7f95c94c9a35d7db9bdc46bea5efaf20c27c3117
| 718
|
php
|
PHP
|
src/Paginator/Paginator.php
|
zetta-code/dotrine-util
|
351fcaf231df152f483ff20b564c0230779f5ebc
|
[
"MIT"
] | null | null | null |
src/Paginator/Paginator.php
|
zetta-code/dotrine-util
|
351fcaf231df152f483ff20b564c0230779f5ebc
|
[
"MIT"
] | null | null | null |
src/Paginator/Paginator.php
|
zetta-code/dotrine-util
|
351fcaf231df152f483ff20b564c0230779f5ebc
|
[
"MIT"
] | null | null | null |
<?php
/**
* @link https://github.com/zetta-code/doctrine-util for the canonical source repository
* @copyright Copyright (c) 2018 Zetta Code
*/
declare(strict_types=1);
namespace Zetta\DoctrineUtil\Paginator;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrineORMPaginator;
use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator;
use Laminas\Paginator\Paginator as LaminasPaginator;
class Paginator extends LaminasPaginator
{
/**
* Paginator constructor.
* @param QueryBuilder $queryBuilder
*/
public function __construct($queryBuilder)
{
parent::__construct(new DoctrinePaginator(new DoctrineORMPaginator($queryBuilder)));
}
}
| 25.642857
| 93
| 0.752089
|
e282fbfec2136c009e47f26d07e8f7ae349cfc0a
| 932
|
js
|
JavaScript
|
test/lexer.js
|
rameshvarun/galaxy-parser
|
8d8bafce2460cd79b33664456e5d06b7e3af74b4
|
[
"MIT"
] | null | null | null |
test/lexer.js
|
rameshvarun/galaxy-parser
|
8d8bafce2460cd79b33664456e5d06b7e3af74b4
|
[
"MIT"
] | null | null | null |
test/lexer.js
|
rameshvarun/galaxy-parser
|
8d8bafce2460cd79b33664456e5d06b7e3af74b4
|
[
"MIT"
] | null | null | null |
require('chai').should();
var lexer = require('../lib/lexer.js');
var fs = require('fs');
var path = require('path');
var assert = require('chai').assert;
var walk = require('fs-walk');
var sources_dir = path.join(__dirname, 'galaxy/');
var tokens_dir = path.join(__dirname, 'tokens/');
describe('Galaxy Lexer', function() {
walk.walkSync(sources_dir, function (basedir, filename, stat) {
var rel_dir = path.relative(sources_dir, basedir);
if (filename.endsWith('.galaxy')) {
it(path.join(rel_dir, filename), function() {
var code = fs.readFileSync(path.join(basedir, filename), 'utf-8');
var tokens = lexer(code);
var expectedFile = path.join(tokens_dir, rel_dir, filename) + '.json';
if (fs.existsSync(expectedFile)) {
var expected = JSON.parse(fs.readFileSync(expectedFile, 'utf-8'));
tokens.should.deep.equal(expected);
}
});
}
});
});
| 32.137931
| 78
| 0.633047
|
c61b2e867d3670821900516d4cb110c3fd42f1bd
| 2,029
|
kt
|
Kotlin
|
IpaShare/src/main/kotlin/com/nail/servlet/LoadBuildListServlet.kt
|
NailxSharipov/IpaShare
|
051f15cf58800502cb52fcea968fab2d4fbfef78
|
[
"MIT"
] | null | null | null |
IpaShare/src/main/kotlin/com/nail/servlet/LoadBuildListServlet.kt
|
NailxSharipov/IpaShare
|
051f15cf58800502cb52fcea968fab2d4fbfef78
|
[
"MIT"
] | null | null | null |
IpaShare/src/main/kotlin/com/nail/servlet/LoadBuildListServlet.kt
|
NailxSharipov/IpaShare
|
051f15cf58800502cb52fcea968fab2d4fbfef78
|
[
"MIT"
] | null | null | null |
package com.nail.servlet
import com.nail.ipa.Bundle
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.lang.StringBuilder
import java.util.*
import javax.servlet.ServletException
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class LoadBuildListServlet(private val artefactsFolder: File): HttpServlet() {
@Throws(ServletException::class, IOException::class)
override fun doGet(request: HttpServletRequest, response: HttpServletResponse) {
val identifier = request.getParameter("identifier")
response.contentType = "application/json; charset=utf-8"
response.status = HttpServletResponse.SC_OK
val out = response.writer
out.print(this.getBuildList(identifier))
out.close()
}
private fun getBuildList(identifier: String): String? {
val appFolder = File(artefactsFolder, identifier)
val buildsFolder = File(appFolder, "builds")
if (!buildsFolder.exists()) {
return null
}
val folders = buildsFolder.listFiles().toMutableList()
Collections.sort(folders, Comparator<File> { a, b -> (a.lastModified() - b.lastModified()).toInt() })
val stringBuilder = StringBuilder()
stringBuilder.append("[")
var isFirst = true
var i = 0;
for (folder in folders) {
if (i > 50) break
if (folder.isDirectory) {
if (!isFirst) {
stringBuilder.append(",")
}
isFirst = false
val buildFile = File(folder, "build.properties")
val properties = Properties()
properties.load(FileInputStream(buildFile))
val bundle = Bundle(properties)
stringBuilder.append(bundle.toJSON())
}
i += 1
}
stringBuilder.append("]")
return stringBuilder.toString()
}
}
| 33.816667
| 109
| 0.63036
|
1cffe766a42dba8bc1e950d65457d6e9ad00b806
| 1,405
|
swift
|
Swift
|
Sources/NStack/Configs/ApplicationConfig.swift
|
niknovak/nstack-custom
|
d128c21aa11826dd768e5fb98e9e228152f6208a
|
[
"MIT"
] | null | null | null |
Sources/NStack/Configs/ApplicationConfig.swift
|
niknovak/nstack-custom
|
d128c21aa11826dd768e5fb98e9e228152f6208a
|
[
"MIT"
] | null | null | null |
Sources/NStack/Configs/ApplicationConfig.swift
|
niknovak/nstack-custom
|
d128c21aa11826dd768e5fb98e9e228152f6208a
|
[
"MIT"
] | null | null | null |
import Vapor
struct ApplicationConfig {
enum ConfigError: String {
case name = "name"
case applicationId = "applicationId"
case restKey = "restKey"
case masterKey = "masterKey"
var error: Abort {
return Abort(
.internalServerError,
metadata: nil,
reason: "NStack error - nstack.applications[].\(rawValue) config is missing."
)
}
}
let name: String
let applicationId: String
let restKey: String
let masterKey: String
init(config: Config) throws {
// Set name
guard let name: String = config["name"]?.string else {
throw ConfigError.name.error
}
self.name = name;
// Set applicationId
guard let applicationId: String = config["applicationId"]?.string else {
throw ConfigError.applicationId.error
}
self.applicationId = applicationId;
// Set restKey
guard let restKey: String = config["restKey"]?.string else {
throw ConfigError.restKey.error
}
self.restKey = restKey;
// Set masterKey
guard let masterKey: String = config["masterKey"]?.string else {
throw ConfigError.masterKey.error
}
self.masterKey = masterKey;
}
}
| 27.019231
| 93
| 0.548043
|
495eaadcb200e23a3b7645ad77270894bed51010
| 6,178
|
lua
|
Lua
|
util/metronomectl.lua
|
maranda/metronome
|
b95eba5f29e4c0402928153c75a6bcfccfc2d99b
|
[
"0BSD"
] | 132
|
2015-01-03T12:27:34.000Z
|
2022-02-13T09:38:29.000Z
|
util/metronomectl.lua
|
maranda/metronome
|
b95eba5f29e4c0402928153c75a6bcfccfc2d99b
|
[
"0BSD"
] | 334
|
2015-01-02T00:39:54.000Z
|
2022-02-19T13:59:03.000Z
|
util/metronomectl.lua
|
maranda/metronome
|
b95eba5f29e4c0402928153c75a6bcfccfc2d99b
|
[
"0BSD"
] | 23
|
2015-01-01T23:37:58.000Z
|
2022-01-07T01:33:09.000Z
|
-- * Metronome IM *
--
-- This file is part of the Metronome XMPP server and is released under the
-- ISC License, please see the LICENSE file in this source package for more
-- information about copyright and licensing.
--
-- As per the sublicensing clause, this file is also MIT/X11 Licensed.
-- ** Copyright (c) 2009-2012, Brian Cully, Kim Alvefur, Matthew Wild, Tobias Tom, Vladimir Protasov, Waqas Hussain
local config = require "core.configmanager";
local encodings = require "util.encodings";
local stringprep = encodings.stringprep;
local storagemanager = require "core.storagemanager";
local usermanager = require "core.usermanager";
local signal = require "util.signal";
local set = require "util.set";
local lfs = require "lfs";
local pcall = pcall;
local type = type;
local nodeprep, nameprep = stringprep.nodeprep, stringprep.nameprep;
local io, os = io, os;
local print = print;
local tostring, tonumber = tostring, tonumber;
local CFG_SOURCEDIR = _G.CFG_SOURCEDIR;
local _G = _G;
local metronome = _G.metronome;
local _ctl = {};
-- UI helpers
local function show_message(msg, ...)
if ... then
print(msg:format(...));
else
print(msg);
end
end
function _ctl.show_warning(msg, ...)
if ... then
print(msg:format(...));
else
print(msg);
end
end
function _ctl.show_usage(usage, desc)
print("Usage: ".._G.arg[0].." "..usage);
if desc then
print(" "..desc);
end
end
local function getchar(n)
local stty_ret = os.execute("stty raw -echo 2>/dev/null");
local ok, char;
if stty_ret == true or stty_ret == 0 then
ok, char = pcall(io.read, n or 1);
os.execute("stty sane");
else
ok, char = pcall(io.read, "*l");
if ok then
char = char:sub(1, n or 1);
end
end
if ok then
return char;
end
end
local function getline()
local ok, line = pcall(io.read, "*l");
if ok then
return line;
end
end
local function getpass()
local stty_ret = os.execute("stty -echo 2>/dev/null");
if stty_ret ~= 0 then
io.write("\027[08m"); -- ANSI 'hidden' text attribute
end
local ok, pass = pcall(io.read, "*l");
if stty_ret == 0 then
os.execute("stty sane");
else
io.write("\027[00m");
end
io.write("\n");
if ok then
return pass;
end
end
local function show_yesno(prompt)
io.write(prompt, " ");
local choice = getchar():lower();
io.write("\n");
if not choice:match("%a") then
choice = prompt:match("%[.-(%U).-%]$");
if not choice then return nil; end
end
return (choice == "y");
end
function _ctl.read_password()
local password;
while true do
io.write("Enter new password: ");
password = getpass();
if not password then
show_message("No password - cancelled");
return;
end
io.write("Retype new password: ");
if getpass() ~= password then
if not show_yesno [=[Passwords did not match, try again? [Y/n]]=] then
return;
end
else
break;
end
end
return password;
end
function _ctl.show_prompt(prompt)
io.write(prompt, " ");
local line = getline();
line = line and line:gsub("\n$","");
return (line and #line > 0) and line or nil;
end
-- Server control
function _ctl.controluser(params, action)
local user, host, password = nodeprep(params.user), nameprep(params.host), params.password;
if not user then
return false, "invalid-username";
elseif not host then
return false, "invalid-hostname";
end
local host_session = metronome.hosts[host];
if not host_session then
return false, "no-such-host";
end
if not host_session.storage_initialized then storagemanager.initialize_host(host); end
local provider = host_session.users;
if not(provider) or provider.name == "null" then
usermanager.initialize_host(host);
end
if provider.name == "anonymous" then
return false, "You can't manage users on an anonymous host";
end
local ok, errmsg;
if action == "check" then
ok, errmsg = usermanager.user_exists(user, host);
elseif action == "create" then
ok, errmsg = usermanager.create_user(user, password, host);
elseif action == "delete" then
ok, errmsg = usermanager.delete_user(user, host, "metronomectl");
elseif action == "passwd" then
ok, errmsg = usermanager.set_password(user, password, host);
end
if not ok then
return false, errmsg;
end
return true;
end
function _ctl.getpid()
local pidfile = config.get("*", "pidfile");
if not pidfile then
return false, "no-pidfile";
end
local modules_enabled = set.new(config.get("*", "modules_enabled"));
if not modules_enabled:contains("posix") then
return false, "no-posix";
end
local file, err = io.open(pidfile, "r+");
if not file then
return false, "pidfile-read-failed", err;
end
local locked, err = lfs.lock(file, "w");
if locked then
file:close();
return false, "pidfile-not-locked";
end
local pid = tonumber(file:read("*a"));
file:close();
if not pid then
return false, "invalid-pid";
end
return true, pid;
end
function _ctl.isrunning()
local ok, pid, err = _ctl.getpid();
if not ok then
if pid == "pidfile-read-failed" or pid == "pidfile-not-locked" then
-- Report as not running, since we can't open the pidfile
-- (it probably doesn't exist)
return true, false;
end
return ok, pid;
end
return true, signal.kill(pid, 0) == 0;
end
function _ctl.start()
local ok, ret = _ctl.isrunning();
if not ok then
return ok, ret;
end
if ret then
return false, "already-running";
end
if not CFG_SOURCEDIR then
os.execute("./metronome");
else
os.execute(CFG_SOURCEDIR.."/../../bin/metronome");
end
return true;
end
function _ctl.stop()
local ok, ret = _ctl.isrunning();
if not ok then
return ok, ret;
end
if not ret then
return false, "not-running";
end
local ok, pid = _ctl.getpid()
if not ok then return false, pid; end
signal.kill(pid, signal.SIGTERM);
return true;
end
function _ctl.reload()
local ok, ret = _ctl.isrunning();
if not ok then
return ok, ret;
end
if not ret then
return false, "not-running";
end
local ok, pid = _ctl.getpid()
if not ok then return false, pid; end
signal.kill(pid, signal.SIGHUP);
return true;
end
_ctl.show_message = show_message;
_ctl.getchar = getchar;
_ctl.getline = getline;
_ctl.getpass = getpass;
_ctl.show_yesno = show_yesno;
return _ctl;
| 22.223022
| 115
| 0.688249
|
4bc95a73a5da883da83c79612d4b0bcf48433be7
| 10,367
|
go
|
Go
|
internal/api/store.go
|
honeyscience/honeydipper
|
ada31de969a39a6501d458cafe8ab460d0ea245c
|
[
"MIT"
] | null | null | null |
internal/api/store.go
|
honeyscience/honeydipper
|
ada31de969a39a6501d458cafe8ab460d0ea245c
|
[
"MIT"
] | null | null | null |
internal/api/store.go
|
honeyscience/honeydipper
|
ada31de969a39a6501d458cafe8ab460d0ea245c
|
[
"MIT"
] | null | null | null |
// Copyright 2022 PayPal Inc.
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT License was not distributed with this file,
// you can obtain one at https://mit-license.org/.
package api
import (
"errors"
"fmt"
"net/http"
"strings"
"sync"
"time"
"github.com/casbin/casbin/v2"
"github.com/casbin/casbin/v2/model"
"github.com/gin-gonic/gin"
"github.com/honeydipper/honeydipper/pkg/dipper"
scas "github.com/qiangmzsx/string-adapter/v2"
)
const (
// DefaultAPIAckTimeout is the number of milliseconds to wait for acks.
DefaultAPIAckTimeout time.Duration = 10
// DefaultAPIWriteTimeout is the default timeout in seconds for responding to the request.
DefaultAPIWriteTimeout time.Duration = 10
// ACLAllow reprensts allowing the subject to access the API.
ACLAllow = "allow"
// ACLDeny reprensts denying the subject to access the API.
ACLDeny = "deny"
)
var (
// ErrAPIError is the base for all API related error.
ErrAPIError = errors.New("API error")
// ErrAPINoACK means not able to receive ACK for the API call.
ErrAPINoACK = fmt.Errorf("%w: no ACK", ErrAPIError)
)
// Store stores the live API calls in memory.
type Store struct {
requests *sync.Map
requestsByInput *sync.Map
caller dipper.RPCCaller
engine *gin.Engine
config interface{}
apiDef map[string]map[string]Def
newUUID dipper.UUIDSource
enforcer *casbin.Enforcer
writeTimeout time.Duration
}
// HandleAPIACK handles the call ACK from the eventbus.
func (l *Store) HandleAPIACK(m *dipper.Message) {
defer dipper.SafeExitOnError("error handling api ack %+v", m.Labels)
uuid, ok := m.Labels["uuid"]
if !ok {
panic(fmt.Errorf("%w: uuid missing ACK", ErrAPIError))
}
dipper.Logger.Debugf("handling api ACK for %s", uuid)
a, ok := l.requests.Load(uuid)
if !ok {
panic(fmt.Errorf("%w: request not found", ErrAPIError))
}
api := a.(*Request)
responder, ok := m.Labels["from"]
if !ok {
panic(fmt.Errorf("%w: missing from label in ACK", ErrAPIError))
}
switch api.reqType {
case TypeAll:
api.acks = append(api.acks, responder)
case TypeMatch:
api.acks = append(api.acks, responder)
api.firstACK <- 1
case TypeFirst:
panic(fmt.Errorf("%w: TypeFirst APIs do not expect ACKs", ErrAPIError))
}
}
// HandleAPIReturn handles the call return value from the eventbus.
func (l *Store) HandleAPIReturn(m *dipper.Message) {
defer dipper.SafeExitOnError("error handling api return %+v", m.Labels)
m = dipper.DeserializePayload(m)
uuid, ok := m.Labels["uuid"]
if !ok {
panic(fmt.Errorf("%w: uuid missing return", ErrAPIError))
}
a, ok := l.requests.Load(uuid)
if !ok {
panic(fmt.Errorf("%w: request not found", ErrAPIError))
}
api := a.(*Request)
responder, ok := m.Labels["from"]
if !ok {
panic(fmt.Errorf("%w: missing from label in return", ErrAPIError))
}
if errmsg, ok := m.Labels["error"]; ok {
api.err = fmt.Errorf("%w: from [%s]: %s", ErrAPIError, responder, errmsg)
api.received <- 1
return
}
if api.reqType == TypeFirst {
api.results[responder] = m.Payload
api.received <- 1
return
}
api.results[responder] = m.Payload
if api.received != nil && len(api.results) == len(api.acks) {
api.received <- 1
}
}
// NewStore creates a new Store.
func NewStore(c dipper.RPCCaller) *Store {
store := &Store{
caller: c,
requests: &sync.Map{},
requestsByInput: &sync.Map{},
}
store.apiDef = GetDefs()
store.newUUID = dipper.NewUUID
return store
}
// GetAPIHandler prepares and returns the gin Engine for API.
func (l *Store) GetAPIHandler(prefix string, cfg interface{}) http.Handler {
gin.DefaultWriter = dipper.LoggingWriter
l.config = cfg
l.engine = gin.New()
l.engine.Use(gin.Logger())
l.engine.Use(gin.Recovery())
l.engine.Use(l.AuthMiddleware())
l.writeTimeout = DefaultAPIWriteTimeout * time.Second
if writeTimeoutStr, ok := dipper.GetMapDataStr(l.config, "writeTimeout"); ok {
l.writeTimeout = dipper.Must(time.ParseDuration(writeTimeoutStr)).(time.Duration)
}
l.setupRoutes(prefix)
l.setupAuthorization()
return l.engine
}
// setupAuthorization sets up authorization enforcer.
func (l *Store) setupAuthorization() {
modelList := dipper.MustGetMapData(l.config, "auth.casbin.models").([]interface{})
modelText := make([]string, len(modelList))
for i, line := range modelList {
modelText[i] = line.(string)
}
policyList := dipper.MustGetMapData(l.config, "auth.casbin.policies").([]interface{})
policyText := make([]string, len(policyList))
for i, line := range dipper.MustGetMapData(l.config, "auth.casbin.policies").([]interface{}) {
policyText[i] = line.(string)
}
models := model.NewModel()
dipper.Must(models.LoadModelFromText(strings.Join(modelText, "\n")))
policies := scas.NewAdapter(strings.Join(policyText, "\n"))
l.enforcer = dipper.Must(casbin.NewEnforcer(models, policies)).(*casbin.Enforcer)
}
// Enforce checks if the action is allowed based on rules.
func (l *Store) Enforce(args ...interface{}) (bool, error) {
ef, e := l.enforcer.Enforce(args...)
if e != nil {
return ef, fmt.Errorf("auth middleware error: %w", e)
}
return ef, nil
}
// AuthMiddleware is a middleware handles auth.
func (l *Store) AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
providers, ok := dipper.GetMapData(l.config, "auth-providers")
if !ok || providers == nil || len(providers.([]interface{})) == 0 {
c.Next()
return
}
allErrors := map[string]string{}
for _, p := range providers.([]interface{}) {
parts := strings.Split(p.(string), ".")
provider := parts[0]
fn := "auth_web_request"
if len(parts) > 1 {
fn = parts[1]
}
subject, err := l.caller.Call("driver:"+provider, fn, dipper.ExtractWebRequestExceptBody(c.Request))
if err != nil || subject == nil {
allErrors[p.(string)] = err.Error()
} else {
c.Set("subject", dipper.DeserializeContent(subject))
c.Next()
return
}
}
c.AbortWithStatusJSON(http.StatusUnauthorized, map[string]interface{}{"errors": allErrors})
}
}
// Authorize determines if a subject is allowed to call a API.
func (l *Store) Authorize(c RequestContext, def Def) bool {
subject, ok := c.Get("subject")
if !ok {
return false
}
dipper.Logger.Warningf("'%s' , '%s', '%s'", subject, def.Object, def.Method)
if res, err := l.enforcer.Enforce(subject.(string), def.Object, def.Method); res && err == nil {
return true
} else if err != nil {
dipper.Logger.Warningf("[api] denied access with enforcer error: %+v", err)
}
return false
}
// HandleHTTPRequest handles http requests.
func (l *Store) HandleHTTPRequest(c RequestContext, def Def) {
if !l.Authorize(c, def) {
c.AbortWithStatusJSON(http.StatusForbidden, map[string]interface{}{"errors": "not allowed"})
return
}
// create or find the original request
r := l.GetRequest(def, c)
r.Dispatch()
// wait for the results
select {
case <-r.ready:
if r.err != nil {
if errors.Is(r.err, ErrAPINoACK) {
c.AbortWithStatusJSON(http.StatusNotFound, map[string]interface{}{"error": "object not found"})
} else {
c.AbortWithStatusJSON(http.StatusInternalServerError, map[string]interface{}{"error": r.err.Error()})
}
} else {
c.IndentedJSON(http.StatusOK, r.getResults())
}
case <-time.After(l.writeTimeout - time.Millisecond):
if r.method == http.MethodGet && (r.timeout == InfiniteDuration || r.timeout > l.writeTimeout) {
c.IndentedJSON(http.StatusAccepted, map[string]interface{}{"uuid": r.uuid, "results": r.getResults()})
} else {
c.AbortWithStatusJSON(http.StatusInternalServerError, map[string]interface{}{"error": dipper.ErrTimeout.Error()})
}
}
}
// CreateHTTPHandlerFunc return a handler function for GET method.
func (l *Store) CreateHTTPHandlerFunc(def Def) gin.HandlerFunc {
// create and return the function
return func(c *gin.Context) {
l.HandleHTTPRequest(&GinRequestContext{gin: c}, def)
}
}
// setupRoutes sets up the routes.
func (l *Store) setupRoutes(prefix string) {
group := &l.engine.RouterGroup
if prefix != "" {
group = group.Group(prefix)
}
for path, defs := range l.apiDef {
for method, def := range defs {
def.Method = method
def.Path = path
switch method {
case http.MethodGet:
group.GET(path, l.CreateHTTPHandlerFunc(def))
case http.MethodPost:
group.POST(path, l.CreateHTTPHandlerFunc(def))
}
}
}
}
// ClearRequest removes the API requests from memory.
func (l *Store) ClearRequest(r *Request) {
l.requests.Delete(r.uuid)
if r.method == http.MethodGet && (r.timeout == InfiniteDuration || r.timeout > l.writeTimeout) {
l.requestsByInput.Delete(r.urlPath)
}
}
// SaveRequest saves the request into maps for future references.
func (l *Store) SaveRequest(r *Request) {
l.requests.Store(r.uuid, r)
if r.method == http.MethodGet && (r.timeout == InfiniteDuration || r.timeout > l.writeTimeout) {
l.requestsByInput.Store(r.urlPath, r)
}
}
// GetRequest creates a new Request with the given definition and parameters or return an existing one based on uuid.
func (l *Store) GetRequest(def Def, c RequestContext) *Request {
path := c.GetPath()
if def.Method == http.MethodGet {
if req, ok := l.requestsByInput.Load(path); ok && req != nil {
return req.(*Request)
}
}
// prepare the parameters
payload := c.GetPayload(def.Method)
return &Request{
store: l,
uuid: l.newUUID(),
urlPath: path,
method: def.Method,
fn: def.Name,
params: payload,
reqType: def.ReqType,
service: def.Service,
ackTimeout: l.getAckTimeout(def),
timeout: l.getTimeout(def),
contentType: c.ContentType(),
}
}
// get the ackTimeout with default value.
func (l *Store) getAckTimeout(d Def) time.Duration {
if d.AckTimeout != 0 {
return d.AckTimeout
}
timeoutStr, ok := dipper.GetMapDataStr(l.config, "ack_timeout")
if ok {
return dipper.Must(time.ParseDuration(timeoutStr)).(time.Duration)
}
return DefaultAPIAckTimeout * time.Millisecond
}
// get the timeout with default value.
func (l *Store) getTimeout(d Def) time.Duration {
if d.Timeout != 0 {
return d.Timeout
}
timeoutStr, ok := dipper.GetMapDataStr(l.config, "timeout")
if ok {
return dipper.Must(time.ParseDuration(timeoutStr)).(time.Duration)
}
return DefaultAPIWriteTimeout * time.Second
}
| 27.943396
| 117
| 0.68747
|
11215553bbe7727700dcca1f856db5c23ecaa943
| 2,396
|
swift
|
Swift
|
WHUIComponentsDemo/Coordinators/CarManufacturerCoordinator.swift
|
chronicqazxc/WHUIComponents
|
bb9ce37adac67ff83b6135f4442ecd50867f2450
|
[
"MIT"
] | null | null | null |
WHUIComponentsDemo/Coordinators/CarManufacturerCoordinator.swift
|
chronicqazxc/WHUIComponents
|
bb9ce37adac67ff83b6135f4442ecd50867f2450
|
[
"MIT"
] | 3
|
2021-03-30T01:42:33.000Z
|
2022-02-26T05:40:55.000Z
|
WHUIComponentsDemo/Coordinators/CarManufacturerCoordinator.swift
|
chronicqazxc/WHUIComponent
|
bb9ce37adac67ff83b6135f4442ecd50867f2450
|
[
"MIT"
] | null | null | null |
//
// ManufacturerCoordinator.swift
// WHUIComponentsDemo
//
// Created by Hsiao, Wayne on 2019/9/21.
// Copyright © 2019 Wayne Hsiao. All rights reserved.
//
import Foundation
import WHUIComponents
class CarManufacturerCoordinator: Debug, Coordinator {
var parameters: [AnyHashable : Any]?
var delegate: CoordinatorDelegate?
var coordinators = [AnyHashable: Coordinator]()
private(set) var viewController: UIViewController?
weak var navigationController: UINavigationController?
required override init() {
super.init()
}
required convenience init(navigationController: UINavigationController) {
self.init()
self.navigationController = navigationController
}
func start() {
let carManufactureViewController = CarManufacturerTableViewController.instanceFromStoryboard()
let viewModel = CarManufacturerViewModel()
viewModel.coordinator = self
carManufactureViewController.viewModel = viewModel
navigationController?.pushViewController(carManufactureViewController, animated: true)
viewController = carManufactureViewController
}
}
extension CarManufacturerCoordinator {
func navigateForwardToNextPage() {
guard let navigationController = navigationController,
let manufacturerViewController = viewController as? CarManufacturerTableViewController else {
return
}
let viewModel = manufacturerViewController.viewModel
let manufacture = viewModel!.selectedData().first as! CarManufacturer
let modelCoordinator = CarModelCoordinator(navigationController: navigationController)
modelCoordinator.delegate = self
modelCoordinator.parameters = [CarManufacturerTableViewController.Constant.parameterKey: manufacture]
modelCoordinator.start()
coordinators["CarModelCoordinator"] = modelCoordinator
}
func naviageBackToPreviousPage() {
guard let toViewController = delegate?.viewController else {
return
}
navigationController?.popToViewController(toViewController, animated: true)
delegate?.presentingFinished()
}
}
extension CarManufacturerCoordinator: CoordinatorDelegate {
func presentingFinished() {
coordinators.removeValue(forKey: "CarModelCoordinator")
}
}
| 33.746479
| 109
| 0.719115
|
ae451829606ec215e1115038f41861d0eb0181f2
| 4,527
|
cs
|
C#
|
osu.Game.Rulesets.Catch/Objects/CatchHitObject.cs
|
ItayLast/osu
|
a8be7499e964444ea5041fb6c743e68f09bb7976
|
[
"MIT"
] | 27
|
2019-09-06T07:58:01.000Z
|
2021-08-28T00:42:28.000Z
|
osu.Game.Rulesets.Catch/Objects/CatchHitObject.cs
|
redyellow4/osu
|
5a23c4b10612056ba74762ee4c03bd0ce1009633
|
[
"MIT"
] | 79
|
2021-06-01T20:36:33.000Z
|
2022-03-01T17:02:52.000Z
|
osu.Game.Rulesets.Catch/Objects/CatchHitObject.cs
|
ThereGoesMySanity/osu
|
bf9ae2d656e3af1eab6b02cfa8ef7fe0f3c3c4dc
|
[
"MIT"
] | 14
|
2021-05-21T05:57:08.000Z
|
2021-10-03T22:54:21.000Z
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Catch.Objects
{
public abstract class CatchHitObject : HitObject, IHasXPosition, IHasComboInformation
{
public const float OBJECT_RADIUS = 64;
public readonly Bindable<float> OriginalXBindable = new Bindable<float>();
/// <summary>
/// The horizontal position of the hit object between 0 and <see cref="CatchPlayfield.WIDTH"/>.
/// </summary>
public float X
{
set => OriginalXBindable.Value = value;
}
float IHasXPosition.X => OriginalXBindable.Value;
public readonly Bindable<float> XOffsetBindable = new Bindable<float>();
/// <summary>
/// A random offset applied to the horizontal position, set by the beatmap processing.
/// </summary>
public float XOffset
{
set => XOffsetBindable.Value = value;
}
/// <summary>
/// The horizontal position of the hit object between 0 and <see cref="CatchPlayfield.WIDTH"/>.
/// </summary>
/// <remarks>
/// This value is the original <see cref="X"/> value specified in the beatmap, not affected by the beatmap processing.
/// Use <see cref="EffectiveX"/> for a gameplay.
/// </remarks>
public float OriginalX => OriginalXBindable.Value;
/// <summary>
/// The effective horizontal position of the hit object between 0 and <see cref="CatchPlayfield.WIDTH"/>.
/// </summary>
/// <remarks>
/// This value is the original <see cref="X"/> value plus the offset applied by the beatmap processing.
/// Use <see cref="OriginalX"/> if a value not affected by the offset is desired.
/// </remarks>
public float EffectiveX => OriginalXBindable.Value + XOffsetBindable.Value;
public double TimePreempt = 1000;
public readonly Bindable<int> IndexInBeatmapBindable = new Bindable<int>();
public int IndexInBeatmap
{
get => IndexInBeatmapBindable.Value;
set => IndexInBeatmapBindable.Value = value;
}
public virtual bool NewCombo { get; set; }
public int ComboOffset { get; set; }
public Bindable<int> IndexInCurrentComboBindable { get; } = new Bindable<int>();
public int IndexInCurrentCombo
{
get => IndexInCurrentComboBindable.Value;
set => IndexInCurrentComboBindable.Value = value;
}
public Bindable<int> ComboIndexBindable { get; } = new Bindable<int>();
public int ComboIndex
{
get => ComboIndexBindable.Value;
set => ComboIndexBindable.Value = value;
}
public Bindable<bool> LastInComboBindable { get; } = new Bindable<bool>();
/// <summary>
/// The next fruit starts a new combo. Used for explodey.
/// </summary>
public virtual bool LastInCombo
{
get => LastInComboBindable.Value;
set => LastInComboBindable.Value = value;
}
public readonly Bindable<float> ScaleBindable = new Bindable<float>(1);
public float Scale
{
get => ScaleBindable.Value;
set => ScaleBindable.Value = value;
}
/// <summary>
/// The seed value used for visual randomness such as fruit rotation.
/// The value is <see cref="HitObject.StartTime"/> truncated to an integer.
/// </summary>
public int RandomSeed => (int)StartTime;
protected override void ApplyDefaultsToSelf(ControlPointInfo controlPointInfo, BeatmapDifficulty difficulty)
{
base.ApplyDefaultsToSelf(controlPointInfo, difficulty);
TimePreempt = (float)BeatmapDifficulty.DifficultyRange(difficulty.ApproachRate, 1800, 1200, 450);
Scale = (1.0f - 0.7f * (difficulty.CircleSize - 5) / 5) / 2;
}
protected override HitWindows CreateHitWindows() => HitWindows.Empty;
}
}
| 36.216
| 127
| 0.607025
|
38b5bb8500ea696566e3607392c728d32e9a8399
| 3,673
|
php
|
PHP
|
app/helpers.php
|
zhimingdou/SSRPanel-1
|
c70ab8d0e8f83223b57e9c39e5712e0297aa18d5
|
[
"MIT"
] | 2
|
2021-10-13T16:00:02.000Z
|
2021-11-24T21:51:28.000Z
|
app/helpers.php
|
1309822767/ssrpanel_resource
|
b72dee81c9b4efe6bac8c7696328b9683891c6c5
|
[
"MIT"
] | null | null | null |
app/helpers.php
|
1309822767/ssrpanel_resource
|
b72dee81c9b4efe6bac8c7696328b9683891c6c5
|
[
"MIT"
] | 1
|
2021-03-21T09:34:29.000Z
|
2021-03-21T09:34:29.000Z
|
<?php
// 生成SS密码
if (!function_exists('makeRandStr')) {
function makeRandStr($length = 6, $isNumbers = false)
{
// 密码字符集,可任意添加你需要的字符
if (!$isNumbers) {
$chars = 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789';
} else {
$chars = '0123456789';
}
$char = '';
for ($i = 0; $i < $length; $i++) {
$char .= $chars[mt_rand(0, strlen($chars) - 1)];
}
return $char;
}
}
// base64加密(处理URL)
if (!function_exists('base64url_encode')) {
function base64url_encode($data)
{
return strtr(base64_encode($data), ['+' => '-', '/' => '_', '=' => '']);
}
}
// base64解密(处理URL)
if (!function_exists('base64url_decode')) {
function base64url_decode($data)
{
return base64_decode(strtr($data, '-_', '+/'));
}
}
// 根据流量值自动转换单位输出
if (!function_exists('flowAutoShow')) {
function flowAutoShow($value = 0)
{
$kb = 1024;
$mb = 1048576;
$gb = 1073741824;
$tb = $gb * 1024;
$pb = $tb * 1024;
if (abs($value) >= $pb) {
return round($value / $pb, 2) . "PB";
} elseif (abs($value) >= $tb) {
return round($value / $tb, 2) . "TB";
} elseif (abs($value) >= $gb) {
return round($value / $gb, 2) . "GB";
} elseif (abs($value) >= $mb) {
return round($value / $mb, 2) . "MB";
} elseif (abs($value) >= $kb) {
return round($value / $kb, 2) . "KB";
} else {
return round($value, 2) . "B";
}
}
}
if (!function_exists('toMB')) {
function toMB($traffic)
{
$mb = 1048576;
return $traffic * $mb;
}
}
if (!function_exists('toGB')) {
function toGB($traffic)
{
$gb = 1048576 * 1024;
return $traffic * $gb;
}
}
if (!function_exists('flowToGB')) {
function flowToGB($traffic)
{
$gb = 1048576 * 1024;
return $traffic / $gb;
}
}
// 文件大小转换
if (!function_exists('formatBytes')) {
function formatBytes($bytes, $precision = 2)
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= pow(1024, $pow);
return round($bytes, $precision) . ' ' . $units[$pow];
}
}
// 获取访客真实IP
if (!function_exists('getClientIP')) {
function getClientIP()
{
/*
* 访问时用localhost访问的,读出来的是“::1”是正常情况
* ::1说明开启了IPv6支持,这是IPv6下的本地回环地址的表示
* 使用IPv4地址访问或者关闭IPv6支持都可以不显示这个
*/
if (isset($_SERVER)) {
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
$ip = $_SERVER['REMOTE_ADDR'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_CLIENT_ip'])) {
$ip = $_SERVER['HTTP_CLIENT_ip'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
} else {
$ip = 'unknown';
}
} else {
if (getenv('HTTP_X_FORWARDED_FOR')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('HTTP_CLIENT_ip')) {
$ip = getenv('HTTP_CLIENT_ip');
} else {
$ip = getenv('REMOTE_ADDR');
}
}
if (trim($ip) == '::1') {
$ip = '127.0.0.1';
}
return $ip;
}
}
| 25.685315
| 80
| 0.477539
|
1a6cf85328761f30a331fccc6c872d136db30c2b
| 1,642
|
cshtml
|
C#
|
Pages/App/Reports.cshtml
|
tcplomp/budoco
|
d519d1f61e504d1f6b05f901a3e43011793c3d7d
|
[
"MIT"
] | 32
|
2020-12-09T01:45:45.000Z
|
2022-03-23T11:53:13.000Z
|
Pages/App/Reports.cshtml
|
tcplomp/budoco
|
d519d1f61e504d1f6b05f901a3e43011793c3d7d
|
[
"MIT"
] | 49
|
2020-11-22T23:13:05.000Z
|
2022-02-25T16:32:43.000Z
|
Pages/App/Reports.cshtml
|
tcplomp/budoco
|
d519d1f61e504d1f6b05f901a3e43011793c3d7d
|
[
"MIT"
] | 14
|
2020-12-05T17:50:49.000Z
|
2021-11-04T06:41:38.000Z
|
@page
@model ReportsModel
@{
ViewData["Title"] = "Reports";
}
<h1>@ViewData["Title"]</h1>
<partial name="_FlashPartial" />
<div class="data_table_div crud_table">
<table class="dt">
@{
<tr>
@{
for (int i = 0; i < Model.dt.Columns.Count; i++)
{
<th>@Model.dt.Columns[i].ColumnName</th>
}
<th>Data</th>
}
</tr>
if (Model.dt.Rows.Count > 0)
{
foreach (DataRow dr in Model.dt.Rows)
{
<tr>
<td>@dr[0]</td>
<td>@dr[1]</td>
<td>
@{
var chartType = (string)dr["Chart Type"];
if (chartType == "pie" || chartType == "line" || chartType == "bar")
{
<a asp-page="ViewReport" asp-route-id="@dr[0]" asp-route-view="chart">@chartType</a>
}
}
</td>
<td>
<a asp-page="ViewReport" asp-route-id="@dr[0]" asp-route-view="data">data</a>
</td>
</tr>
}
}
else
{
<tr>
<td colspan="5">No reports in the database.</td>
</tr>
}
}
</table>
</div>
@section Scripts {
}
| 26.063492
| 120
| 0.311815
|
43fbc9ec1d16e19e410e9176057740fe5baa12d5
| 11,694
|
cpp
|
C++
|
src/engine.cpp
|
adamjedlicka/yarpg
|
6c8a3fde76ec340b76b046c05822e09aabb6e830
|
[
"MIT"
] | 1
|
2016-06-04T12:11:53.000Z
|
2016-06-04T12:11:53.000Z
|
src/engine.cpp
|
adamjedlicka/yarpg
|
6c8a3fde76ec340b76b046c05822e09aabb6e830
|
[
"MIT"
] | null | null | null |
src/engine.cpp
|
adamjedlicka/yarpg
|
6c8a3fde76ec340b76b046c05822e09aabb6e830
|
[
"MIT"
] | null | null | null |
#include "engine.h"
Engine::Engine() {
window = initscr();
nodelay(window, true);
keypad(window, true);
noecho();
// cbreak();
// timeout(1);
// wtimeout(window, 1);
curs_set(0);
// raw();
// clear();
_COLOR = has_colors();
if (_COLOR) {
start_color();
init_pair(1, COLOR_WHITE, COLOR_BLACK); // fixes a bug with blinking text
}
splash = new Splash();
maxHeight = getmaxy(window);
maxWidth = getmaxx(window);
for (int i = 0; i < MAX_BUFFERS; ++i)
buffers[i] = new Buffer(maxWidth, maxHeight);
active = false;
debug = false;
tickCount = 0;
}
Engine::~Engine() {
active = false;
for (int i = 0; i < MAX_BUFFERS; ++i)
delete buffers[i];
delete splash;
endwin();
}
void Engine::Start(std::function< void(std::map< std::string, std::string >, Engine &) > fn) {
loader = fn;
active = true;
loop();
}
void Engine::LoadContent(std::map< std::string, std::string > flags) { loader(flags, *this); }
void Engine::Stop() {
delete level;
active = false;
}
bool Engine::LoadLevel(Level *lvl) {
level = lvl;
return true;
}
std::pair< int, int > Engine::Direction(int up, int left, int down, int right) {
std::pair< int, int > p = std::make_pair(0, 0);
if (GetKey(right))
p.first++;
if (GetKey(left))
p.first--;
if (GetKey(down))
p.second++;
if (GetKey(up))
p.second--;
return p;
}
Buffer *Engine::GetCurBuffer() { return buffers[0]; }
Buffer::Buffer() {}
Buffer::Buffer(int w, int h) {
width = w;
height = h;
frameCount = 0;
canvas = new Cell *[height];
for (int i = 0; i < height; ++i)
canvas[i] = new Cell[width];
}
Buffer::~Buffer() {
for (int i = 0; i < height; ++i)
delete[] canvas[i];
delete[] canvas;
}
void Buffer::DrawChar(int x, int y, char c) { DrawChar(x, y, c, COLOR_WHITE, COLOR_BLACK); }
void Buffer::DrawChar(int x, int y, char c, short fg) { DrawChar(x, y, c, fg, COLOR_BLACK); }
void Buffer::DrawChar(int x, int y, char c, short fg, short bg) {
if (x < 0 || y < 0)
return;
if (x >= width || y >= height)
return;
switch (c) {
case '\0':
case '\t':
break;
default:
canvas[y][x].ch = c;
canvas[y][x].fg = fg;
canvas[y][x].bg = bg;
break;
}
}
void Buffer::DrawString(int width, int height, const std::string &str) {
int w = 0;
int h = 0;
for (unsigned int i = 0; i < str.length(); ++i) {
if (str[i] == '\n') {
++h;
w = 0;
continue;
}
DrawChar(width + w++, height + h, str[i]);
}
}
void Buffer::ClearCanvas() {
frameCount++;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; j++) {
canvas[i][j].ch = ' ';
canvas[i][j].fg = COLOR_WHITE;
canvas[i][j].bg = COLOR_BLACK;
}
}
}
void Engine::loop() {
clock_t drawTime = clock();
while (active) {
// Store all key presses in keyboard for future querries
int c = 0;
for (int i = 0; i < MAX_KEYS; ++i)
keys[i] = false;
while (c = getch(), c != ERR)
keys[c] = true;
if (GetKey(KEY_EXIT)) { // quit the game
Stop();
return;
}
GetCurBuffer()->ClearCanvas();
if (splash->Active()) {
splash->Tick(this);
splash->Render(GetCurBuffer());
} else {
// Game logic and rendering
tick();
tickCount++;
render();
}
drawBuffer();
// Calculate sleep time for the rest of the frame, to save CPU load
clock_t now = clock();
double tm = double(now - drawTime) / CLOCKS_PER_SEC;
double sleep = (1.0 / MAX_FPS - tm) * 1000000;
if (sleep > 0)
usleep(sleep);
drawTime = clock();
}
}
void Engine::tick() {
if (GetKey(KEY_F(2)))
debug = !debug;
log << "tickCount: " << tickCount << std::endl; // DEBUG
if (level && (level->GameState() == OK_STATE || level->GameState() == UNLOAD_STATE))
level->Tick(this);
else if (level && (level->GameState() == LOOSE_STATE || level->GameState() == WIN_STATE)) {
if (GetKey('\n')) {
delete level;
level = NULL;
splash->Activate();
}
}
}
void Engine::render() {
Buffer *buf = GetCurBuffer();
if (level)
level->Render(buf);
if (debug)
buf->DrawString(0, 0, log.str());
log.str("");
}
void Engine::drawBuffer() {
clear();
erase();
Buffer *buf = GetCurBuffer();
attron(COLOR_PAIR(1));
int usedColorPairs = 1; // 1 because we already initialized
for (int i = 0; i < buf->GetHeight(); ++i) {
const Cell *line = buf->GetLine(i);
for (int j = 0; j < buf->GetWidth(); ++j) {
int index = 1;
if (_COLOR) {
short fg, bg;
for (int i = 1; i <= usedColorPairs; ++i) {
pair_content(i, &fg, &bg);
if (fg == line[j].fg && bg == line[j].bg) {
index = i;
break;
}
if (i == usedColorPairs) {
index = ++usedColorPairs;
init_pair(index, line[j].fg, line[j].bg);
break;
}
}
}
attron(COLOR_PAIR(index));
mvaddch(i, j, line[j].ch);
attroff(COLOR_PAIR(index));
}
}
attron(COLOR_PAIR(1));
if (_COLOR) {
log << "max color_pairs: " << COLOR_PAIRS - 1 << std::endl;
log << "used color_pairs: " << usedColorPairs << std::endl;
}
refresh();
}
Entity::~Entity() {
for (unsigned int i = 0; i < inventory.size(); ++i)
delete inventory[i];
}
SML::SML() {}
SML::~SML() {}
void SML::ReadFile(const std::string &file) {
std::ifstream ifs;
ifs.open(file.c_str());
if (ifs.fail()) {
std::cout << file << " error..." << std::endl;
ifs.close();
return;
}
std::cout << file << " succesfully opened..." << std::endl;
char tmp[1024];
int tmp_len = 0;
std::stringstream ss;
std::string key = "global";
while (ifs.good()) {
ss.str("");
ifs.getline(tmp, 1024);
tmp_len = strlen(tmp);
while (tmp[tmp_len - 1] == '\\' && ifs.good()) {
tmp[tmp_len - 1] = '\0';
ss << tmp;
ifs.getline(tmp, 1024);
tmp_len = strlen(tmp);
}
ss << tmp;
std::string line = ss.str();
if (line[0] == '[' && line[line.size() - 1] == ']')
key = line.substr(1, line.size() - 2);
if (data.find(key) == data.end())
data[key] = SML_Fragment();
data[key].AddValue(line);
}
ifs.close();
}
void SML::ForEach(std::function< void(const std::string &, const SML_Fragment &) > f) const {
for (const auto &v : data)
if (v.first != "global")
f(v.first, v.second);
}
const SML_Fragment &SML::GetFragment(const std::string &key) const { return data.find(key)->second; }
SML_Fragment::SML_Fragment() {}
SML_Fragment::~SML_Fragment() {}
void SML_Fragment::AddValue(const std::string &raw) {
size_t index = raw.find(' ');
data[raw.substr(0, index)] = raw.substr(index + 3);
}
std::string SML_Fragment::GetValue(const std::string &key) const {
return (data.find(key) != data.end()) ? data.find(key)->second : "";
}
int SML_Fragment::GetValueAsInt(const std::string &key) const {
return (data.find(key) != data.end()) ? std::stoi(data.find(key)->second) : 0;
}
char SML_Fragment::GetValueAsChar(const std::string &key) const {
return (data.find(key) != data.end()) ? data.find(key)->second[0] : ' ';
}
short SML_Fragment::GetColor(const std::string &key) const {
if (data.find(key) == data.end())
return COLOR_BLACK;
std::string val = data.find(key)->second;
if (val == "WHITE")
return COLOR_WHITE;
else if (val == "GREEN")
return COLOR_GREEN;
else if (val == "MAGENTA")
return COLOR_MAGENTA;
else if (val == "BLUE")
return COLOR_BLUE;
else if (val == "BLACK")
return COLOR_BLACK;
else if (val == "YELLOW")
return COLOR_YELLOW;
else if (val == "CYAN")
return COLOR_CYAN;
else if (val == "RED")
return COLOR_RED;
else
return COLOR_BLACK;
}
Splash::Splash() {
logo = " \n"
" ,-.----. \n"
" ,---, ,-.----. \\ / \\ ,----.. \n"
" ,---, ' .' \\ \\ / \\ | : \\ / / \\ \n"
" /_ ./| / ; '. ; : \\ | | .\\ :| : : \n"
" ,---, | ' :: : \\ | | .\\ : . : |: |. | ;. / \n"
"/___/ \\. : |: | /\\ \\ . : |: | | | \\ :. ; /--` \n"
" . \\ \\ ,' '| : ' ;. : | | \\ : | : . /; | ; __ \n"
" \\ ; ` ,'| | ;/ \\ \\| : . / ; | |`-' | : |.' .' \n"
" \\ \\ ' ' : | \\ \\ ,'; | | \\ | | ; . | '_.' : \n"
" ' \\ | | | ' '--' | | ;\\ \\: ' | ' ; : \\ | \n"
" \\ ; ; | : : : ' | \\.': : : ' | '/ .' \n"
" : \\ \\| | ,' : : :-' | | : | : / \n"
" \\ ' ;`--'' | |.' `---'.| \\ \\ .' \n"
" `--` `---' `---` `---` \n"
" by Adam Jedlicka ";
menu.push_back("New game");
menu.push_back("Quit");
menuSelection = 0;
menuStage = 0;
active = true;
flags["playerType"] = "";
flags["playerName"] = "";
}
Splash::~Splash() {}
void Splash::Tick(Engine *engine) {
if (menuStage == 0) {
if (engine->GetKey(KEY_DOWN))
menuSelection++;
if (engine->GetKey(KEY_UP))
menuSelection--;
menuSelection = MIN(menuSelection, menu.size() - 1);
if (engine->GetKey('\n')) {
if (menuSelection == 0) {
menuStage++;
} else if (menuSelection == 1) {
engine->Stop();
}
}
} else if (menuStage == 1) {
if (engine->GetKey('\n'))
menuStage++;
if (engine->GetKey(KEY_BACKSPACE) && flags["playerName"].size() > 0)
flags["playerName"] = flags["playerName"].substr(0, flags["playerName"].size() - 1);
for (int i = 65; i <= 90; ++i) {
if (engine->GetKey(i))
flags["playerName"] += (char)i;
}
for (int i = 97; i <= 122; ++i) {
if (engine->GetKey(i))
flags["playerName"] += (char)i;
}
} else if (menuStage == 2) {
if (engine->GetKey('m') || engine->GetKey('M')) {
flags["playerType"] = "melee";
menuStage++;
} else if (engine->GetKey('r') || engine->GetKey('R')) {
flags["playerType"] = "ranged";
menuStage++;
}
} else if (menuStage == 3) {
menuStage = 0;
active = false;
flags["levelName"] = "level_1";
engine->LoadContent(flags);
}
}
void Splash::Render(Buffer *buffer) const {
int logoWidth = 64;
int logoHeight = 16;
int startX = buffer->GetWidth() / 2 - logoWidth / 2;
int startY = MAX(buffer->GetHeight() / 2 - (logoHeight / 2 + 5), 0);
buffer->DrawString(startX, startY, logo);
if (menuStage == 0) {
for (unsigned int i = 0; i < menu.size(); ++i) {
int len = menu[i].size();
if (menuSelection == i)
buffer->DrawString(buffer->GetWidth() / 2 - len / 2 - 2, startY + logoHeight + i + 2, "> " + menu[i]);
else
buffer->DrawString(buffer->GetWidth() / 2 - len / 2, startY + logoHeight + i + 2, menu[i]);
}
} else if (menuStage == 1) {
int frameCnt = buffer->GetFrameCnt();
frameCnt = frameCnt % 60;
std::string text = "Choose your name: " + flags.find("playerName")->second;
std::string text2 = "(confirm with [ENTER])";
if (frameCnt > 30)
buffer->DrawString(buffer->GetWidth() / 2 - text.size() / 2, startY + logoHeight + 2, text + '_');
else
buffer->DrawString(buffer->GetWidth() / 2 - text.size() / 2, startY + logoHeight + 2, text);
buffer->DrawString(buffer->GetWidth() / 2 - text.size() / 2, startY + logoHeight + 2 + 2, text2);
} else if (menuStage == 2) {
std::string text = "Press [m] key for melee hero, or [r] key for ranged hero.";
buffer->DrawString(buffer->GetWidth() / 2 - text.size() / 2, startY + logoHeight + 2, text);
}
}
std::string GetPath() {
char pBuf[255];
short len = 255;
char szTmp[32];
sprintf(szTmp, "/proc/%d/exe", getpid());
int bytes = MIN(readlink(szTmp, pBuf, len), len - 1);
if (bytes >= 0)
pBuf[bytes] = '\0';
for (int i = bytes; i > 0; --i) {
if (pBuf[i] == '/')
break;
else
pBuf[i] = '\0';
}
std::string path(pBuf);
return path;
}
| 24.567227
| 106
| 0.53489
|