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
0d9bc8513cb79f4b24611cb0a69591eabe60dbcd
1,958
ps1
PowerShell
azure-pipelines/vsixgallerytools.ps1
Youssef1313/dotnet-apiport
30b401bcad19f023d639d8bdac8b85b19d925990
[ "MIT" ]
694
2015-07-14T20:42:49.000Z
2019-04-24T14:24:02.000Z
azure-pipelines/vsixgallerytools.ps1
Youssef1313/dotnet-apiport
30b401bcad19f023d639d8bdac8b85b19d925990
[ "MIT" ]
445
2015-07-06T16:22:26.000Z
2019-04-16T20:58:06.000Z
azure-pipelines/vsixgallerytools.ps1
Youssef1313/dotnet-apiport
30b401bcad19f023d639d8bdac8b85b19d925990
[ "MIT" ]
122
2015-07-08T18:57:31.000Z
2019-04-17T10:26:37.000Z
# This is subset of VSIX Module for AppVeyor by Mads Kristensen from https://github.com/madskristensen/ExtensionScripts/tree/master/AppVeyor [cmdletbinding()] param() $vsixUploadEndpoint = "https://www.vsixgallery.com/api/upload" #$vsixUploadEndpoint = "https://localhost:44372/api/upload" function Vsix-GetRepoUrl { [cmdletbinding()] param () if ($env:BUILD_REPOSITORY_PROVIDER -contains "github") { $repoUrl = "https://github.com/" + $env:BUILD_REPOSITORY_NAME + "/" } else { $repoUrl = "" } return $repoUrl } function Vsix-PublishToGallery { [cmdletbinding()] param ( [Parameter(Position = 0, Mandatory = 0, ValueFromPipeline = $true)] [string[]]$path = "./*.vsix" ) foreach ($filePath in $path) { if ($env:APPVEYOR_PULL_REQUEST_NUMBER) { return } $repo = "" $issueTracker = "" $repoUrl = Vsix-GetRepoUrl if ($baseRepoUrl -ne "") { [Reflection.Assembly]::LoadWithPartialName("System.Web") | Out-Null $repo = [System.Web.HttpUtility]::UrlEncode($repoUrl) $issueTracker = [System.Web.HttpUtility]::UrlEncode(($repoUrl + "issues/")) } 'Publish to VSIX Gallery...' | Write-Host -ForegroundColor Cyan -NoNewline $fileNames = (Get-ChildItem $filePath -Recurse) foreach ($vsixFile in $fileNames) { [string]$url = ($vsixUploadEndpoint + "?repo=" + $repo + "&issuetracker=" + $issueTracker) [byte[]]$bytes = [System.IO.File]::ReadAllBytes($vsixFile) try { $webclient = New-Object System.Net.WebClient $webclient.UploadFile($url, $vsixFile) | Out-Null 'OK' | Write-Host -ForegroundColor Green } catch { 'FAIL' | Write-Error $_.Exception.Response.Headers["x-error"] | Write-Error } } } }
31.580645
140
0.580695
91f62c4893231507d7d289c903537f10d2af1d6c
6,361
py
Python
functions/tidy_clean.py
kaymal/price-project
20c9166c65b10da6e9ecd0475172a30483853781
[ "MIT" ]
2
2019-06-15T18:49:23.000Z
2019-06-20T12:21:42.000Z
functions/tidy_clean.py
kaymal/price-project
20c9166c65b10da6e9ecd0475172a30483853781
[ "MIT" ]
null
null
null
functions/tidy_clean.py
kaymal/price-project
20c9166c65b10da6e9ecd0475172a30483853781
[ "MIT" ]
2
2020-11-27T20:36:12.000Z
2020-12-09T23:10:28.000Z
def clean_t (data): # Select columns to clean df = data # Create dummies using the items in the list of 'safety&security' column ss = df['safety_security'].dropna() df_new = df.join(ss.str.join('|').str.get_dummies().add_prefix('ss_')) # Drop 'safety_security' column df_new.drop('safety_security', axis=1, inplace=True) # Clean the model column df_new['model'] = df.model.apply(lambda x: x[1]) # Strip "\n"s from the 'make' column df_new['make'] = df.make.str.strip("\n") # Drop unnecesary column 'make_model' df_new.drop(columns = "make_model", inplace = True) # Clean 'model_code' column df_new.loc[df_new.model_code.notnull(), "model_code"] = df.model_code[df.model_code.notnull()].apply(lambda x: str(x)[4:-4]) # Clean 'country_version' column df_new.loc[df_new.country_version.notnull(), "country_version"] = df.country_version[df.country_version.notnull()].apply(lambda x: str(x)[4:-4]) # Clean 'co2_emission' column df_new['co2_emission'] = df.co2_emission.str[0].str.extract(r'(\d+)') # Change the 'co2' columns data type to numeric df_new['co2_emission'] = pd.to_numeric(df_new.co2_emission) # Clean 'cylinders' column df_new['cylinders'] = df.cylinders.str[0].str.extract(r'(\d+)') # Change the 'cylinders' columns data type to numeric df_new['cylinders'] = pd.to_numeric(df_new['cylinders']) # Extract displacement values (and remove commas) df_new['displacement'] = df.displacement.str[0].str.replace(",","").str.extract(r'(\d+)') # Change the type of displacement from object to numeric df_new['displacement'] = pd.to_numeric(df_new['displacement']) # Extract 'next_inspection' values df_new.next_inspection = df.next_inspection.str[0].str.strip("\n") # Create a boolean column from `next_inspection` df_new['next_inspection_bool'] = df_new.next_inspection.notnull() # Drop 'non-smoking_vehicle' column df_new.drop("non_smoking_vehicle", axis=1, inplace=True) # Extract hp from 'hp' column df_new['hp'] = df.hp.str.extract(r'(\d+)') # Change datatype to numeric df_new['hp'] = pd.to_numeric(df_new['hp']) # Drop 'kw' column df_new.drop('kw', axis=1, inplace=True) # Clean 'km' column df_new['km'] = df.km.str.replace(",", "").str.extract(r'(\d+)') # Clean "offer_number' column df_new['offer_number'] = df.offer_number.str[0].str.replace("\n","") # Create a boolean for checking "combined" consumption comb_bool = df.consumption.str[0].str[0].str.contains("comb", na=False) # Create a new column for 'consumption_comb' df_new['consumption_comb'] = df[comb_bool].consumption.str[0].str[0].str.extract(r'(\d.\d|\d)') # Drop 'consumption' column df_new.drop('consumption', axis=1, inplace=True) # Tidy column names df_new.columns = name_columns(df_new) # Change description from list to string df_new['description'] = df['description'].str.join('').str.strip("\n")[0] return df_new def clean_m(data): df=data #cleaning registration column and convertinf it to age column reg_new = df.registration[~df.registration.str.contains("-")] reg_new = pd.to_datetime(reg_new, format='%m/%Y') reg_year = reg_new.apply(lambda x: x.year) df['age'] = 2019 - reg_year df['gearing_type'] = df['gearing_type'].apply(lambda x:x[1]) df.loc[df['body'].notnull(), 'body'] = df.loc[df['body'].notnull(), 'body'].apply(lambda x: x[1]) df.loc[df['body_color'].notnull(), 'body_color'] = df.loc[df['body_color'].notnull(), 'body_color'].apply(lambda x: x[1]) ent=df[['entertainment_media']].dropna() df=df.join(ent['entertainment_media'].str.join('|').str.get_dummies().add_prefix('ent_media_')) df['gears']=df.gears.str[0].str.replace("\n", "") df['gears'] = pd.to_numeric(df.gears) df['paint_type']=df.paint_type.str[0].str.replace("\n", "") # converting inspection_new column to 1 if it contains Yes expression, else: 0 df["inspection_new"] = df.inspection_new.str[0].str.contains("Yes", na=False)*1 # extracting the number of days in availabiltiy column and converting column name to available_after_days df['availability'] = df.availability.str.extract(r'(\d+)') df['available_after_days'] = df.availability.apply(pd.to_numeric) # finding right pattern for date in a mixed column: 2 digits/4 digits to extract the date df['last_service_date'] = df.last_service_date.str[0].str.extract(r'(\d{2}\/\d{4})') # converting to datetime object df['last_service_date'] = pd.to_datetime(df['last_service_date'], format='%m/%Y') #cleaning the available_from column and converting to datetime df['available_from'] = df.available_from.str.strip("\n") df['available_from'] = pd.to_datetime(df['available_from']) name_columns(df) drop_list=['entertainment_media', 'availability', 'body_color_original', 'full_service', 'last_timing_belt_service_date', 'null', 'registration'] df.drop(drop_list, axis=1, inplace=True) return df def clean_update(data): '''Additional cleaning after performing EDA''' df = data # Change wrong data types to numeric df['km'] = pd.to_numeric(df['km']) df['consumption_comb'] = pd.to_numeric(df['consumption_comb']) df['nr_of_doors'] = pd.to_numeric(df['nr_of_doors']) df['nr_of_seats'] = pd.to_numeric(df['nr_of_seats']) df['previous_owners'] = pd.to_numeric(df['previous_owners']) df['weight_kg'] = pd.to_numeric(df['weight_kg']) #df['gears'] = pd.to_numeric(df['gears']) # clean_m updated # Change wrong data type to date_time df['first_registration'] = pd.to_datetime(df.first_registration, format='%Y') # Replace " " with NaNs df.loc[df.next_inspection == "",'next_inspection'] = np.nan # Drop 'prev_owner' column df.drop('prev_owner', axis=1, inplace = True) # Drop 'body_type' column (duplicate of 'body') df.drop('body_type', axis=1, inplace = True) # Drop 'next_inspection' column (created a new column 'next_inspection_bool') df.drop('next_inspection', axis=1, inplace = True) return df
40.259494
148
0.654928
0a466f14720dbe1a8a90241c7f9bc4718640428f
1,669
rs
Rust
src/instructions/conversions/f2x.rs
comradeHsu/Must
7f4624518a10b34658d46a39b6acc4bdd4d47a33
[ "Apache-2.0" ]
null
null
null
src/instructions/conversions/f2x.rs
comradeHsu/Must
7f4624518a10b34658d46a39b6acc4bdd4d47a33
[ "Apache-2.0" ]
null
null
null
src/instructions/conversions/f2x.rs
comradeHsu/Must
7f4624518a10b34658d46a39b6acc4bdd4d47a33
[ "Apache-2.0" ]
null
null
null
use crate::instructions::base::bytecode_reader::BytecodeReader; use crate::instructions::base::instruction::{Instruction, NoOperandsInstruction}; use crate::runtime::frame::Frame; pub struct F2d(NoOperandsInstruction); impl F2d { #[inline] pub const fn new() -> F2d { return F2d(NoOperandsInstruction::new()); } } impl Instruction for F2d { fn fetch_operands(&mut self, reader: &mut BytecodeReader) { self.0.fetch_operands(reader); } fn execute(&mut self, frame: &mut Frame) { let stack = frame.operand_stack().expect("operand_stack is none"); let v1 = stack.pop_float(); stack.push_double(v1 as f64); } } pub struct F2i(NoOperandsInstruction); impl F2i { #[inline] pub const fn new() -> F2i { return F2i(NoOperandsInstruction::new()); } } impl Instruction for F2i { fn fetch_operands(&mut self, reader: &mut BytecodeReader) { self.0.fetch_operands(reader); } fn execute(&mut self, frame: &mut Frame) { let stack = frame.operand_stack().expect("operand_stack is none"); let v1 = stack.pop_float(); stack.push_int(v1 as i32); } } pub struct F2l(NoOperandsInstruction); impl F2l { #[inline] pub const fn new() -> F2l { return F2l(NoOperandsInstruction::new()); } } impl Instruction for F2l { fn fetch_operands(&mut self, reader: &mut BytecodeReader) { self.0.fetch_operands(reader); } fn execute(&mut self, frame: &mut Frame) { let stack = frame.operand_stack().expect("operand_stack is none"); let v1 = stack.pop_float(); stack.push_long(v1 as i64); } }
24.910448
81
0.639305
24b2ccb1169ffcef3296dee394d7abeaafb1ff36
728
php
PHP
app/Http/Data/Controllers/BackupSensorAveragesController.php
nocmatik/erm
daaecb03b02f28430bcf3cf8fb154bfa1d47cd05
[ "MIT" ]
1
2021-11-10T02:36:29.000Z
2021-11-10T02:36:29.000Z
app/Http/Data/Controllers/BackupSensorAveragesController.php
nocmatik/erm
daaecb03b02f28430bcf3cf8fb154bfa1d47cd05
[ "MIT" ]
5
2020-07-20T21:14:54.000Z
2022-02-27T05:32:41.000Z
app/Http/Data/Controllers/BackupSensorAveragesController.php
nocmatik/erm
daaecb03b02f28430bcf3cf8fb154bfa1d47cd05
[ "MIT" ]
1
2021-03-01T23:49:23.000Z
2021-03-01T23:49:23.000Z
<?php namespace App\Http\Data\Controllers; use App\Domain\WaterManagement\Device\Sensor\Sensor; use App\Http\Data\Events\BackupedAverages; use App\Http\Data\Events\BackupSensorAverages; use Illuminate\Http\Request; use App\App\Controllers\Controller; class BackupSensorAveragesController extends Controller { public function __invoke($sensor_id) { $sensor = Sensor::with('analogous_reports')->withCount('analogous_reports')->find($sensor_id); if($sensor->analogous_reports_count > 0) { event(new BackupSensorAverages($sensor)); event(new BackupedAverages($sensor_id)); } return back()->with('success','Se ha creado el proceso de respaldo de medias'); } }
29.12
102
0.715659
79847c992a01eb4fc8eb782d37de49b2872e009f
1,985
php
PHP
database/migrations/2022_01_07_000090_create_coins_table.php
mldanshin/coins
b881876adc95b1db2e7f160f9c077f5b7103e34f
[ "MIT" ]
null
null
null
database/migrations/2022_01_07_000090_create_coins_table.php
mldanshin/coins
b881876adc95b1db2e7f160f9c077f5b7103e34f
[ "MIT" ]
null
null
null
database/migrations/2022_01_07_000090_create_coins_table.php
mldanshin/coins
b881876adc95b1db2e7f160f9c077f5b7103e34f
[ "MIT" ]
null
null
null
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCoinsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('coins', function (Blueprint $table) { $table->id(); $table->foreignId('country_id') ->constrained() ->onUpdate('cascade') ->onDelete('cascade'); $table->foreignId('nominal_id') ->constrained() ->onUpdate('cascade') ->onDelete('cascade'); $table->foreignId('coinage_id') ->constrained() ->onUpdate('cascade') ->onDelete('cascade'); $table->foreignId('material_id') ->constrained() ->onUpdate('cascade') ->onDelete('cascade'); $table->foreignId('currency_id') ->constrained() ->onUpdate('cascade') ->onDelete('cascade'); $table->foreignId('shape_id') ->constrained() ->onUpdate('cascade') ->onDelete('cascade'); $table->foreignId('theme_id') ->constrained() ->onUpdate('cascade') ->onDelete('cascade'); $table->string('year'); $table->foreignId('quality_id') ->constrained() ->onUpdate('cascade') ->onDelete('cascade'); $table->foreignId('storage_id') ->constrained() ->onUpdate('cascade') ->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('coins'); } }
28.768116
61
0.46398
cd9879d62cb98f4d931d0b05cc168db8b27b7f39
253
cs
C#
src/MicroServices/StorageManagement/Core/StorageManagement.Application/Features/Contents/Queries/GetAllConents/GetAllContentsParameter.cs
mrgrayhat/CleanMicroserviceArchitecture
82f8002c3b3fc497f54c160c4e476d6cb87f04bc
[ "MIT" ]
4
2021-02-05T11:15:37.000Z
2022-01-19T05:56:51.000Z
src/MicroServices/StorageManagement/Core/StorageManagement.Application/Features/Contents/Queries/GetAllConents/GetAllContentsParameter.cs
mrgrayhat/CleanMicroserviceArchitecture
82f8002c3b3fc497f54c160c4e476d6cb87f04bc
[ "MIT" ]
null
null
null
src/MicroServices/StorageManagement/Core/StorageManagement.Application/Features/Contents/Queries/GetAllConents/GetAllContentsParameter.cs
mrgrayhat/CleanMicroserviceArchitecture
82f8002c3b3fc497f54c160c4e476d6cb87f04bc
[ "MIT" ]
null
null
null
using StorageManagement.Application.Parameters; namespace StorageManagement.Application.Features.Contents.Queries.GetAllContents { public class GetAllContentsParameter : RequestParameter { public string SortOrder { get; set; } } }
25.3
80
0.766798
dbd980173f9337a7867424d1e33a865bf0f2896d
4,732
php
PHP
src/Madalynn/Bundle/MainBundle/DataFixtures/ORM/QuickStartFixtures.php
blinkseb/website
7e5f1b4d1454e7ab4f4d69089e4fa2dd97ab2c64
[ "MIT" ]
1
2018-05-06T13:51:26.000Z
2018-05-06T13:51:26.000Z
src/Madalynn/Bundle/MainBundle/DataFixtures/ORM/QuickStartFixtures.php
blinkseb/website
7e5f1b4d1454e7ab4f4d69089e4fa2dd97ab2c64
[ "MIT" ]
1
2018-04-18T11:10:20.000Z
2018-04-18T11:10:20.000Z
src/Madalynn/Bundle/MainBundle/DataFixtures/ORM/QuickStartFixtures.php
blinkseb/website
7e5f1b4d1454e7ab4f4d69089e4fa2dd97ab2c64
[ "MIT" ]
1
2017-05-24T08:24:48.000Z
2017-05-24T08:24:48.000Z
<?php /* * This file is part of the AndroIRC website. * * (c) 2010-2012 Julien Brochet <mewt@androirc.com> * (c) 2010-2012 Sébastien Brochet <blinkseb@androirc.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Madalynn\Bundle\MainBundle\DataFixtures\ORM; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\FixtureInterface; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Madalynn\Bundle\MainBundle\Entity\QuickStart; /** * QuickStart Fixtures * * @author Julien Brochet <mewt@androirc.com> */ class QuickStartFixtures extends AbstractFixture implements FixtureInterface, OrderedFixtureInterface { /** * Load data fixtures with the passed EntityManager * * @param object $manager */ public function load(ObjectManager $em) { $french = new QuickStart(); $french->setVersionMin($this->getReference('androirc_version_1.0')); $french->setLanguage('fr'); $french->setContent(<<<EOF <h1>Bienvenue !</h1> <p> Bienvenue sur AndroIRC ! Cette fenêtre s'affiche seulement lors du premier lancement. Si IRC n'a plus de secrets pour vous, vous pouvez fermer cette page. Autrement, voici une petite introduction. </p> <h1>Introduction</h1> <p> AndroIRC vous permet de vous connecter rapidement et simplement à n'importe quel réseau IRC. Pour plus d'explication sur le protocole IRC, <a href="http://fr.wikipedia.org/wiki/Internet_Relay_Chat">la page wikipedia</a> est là ! AndroIRC intègre par défaut cinq serveurs : </p> <ul> <li>freenode (EN)</li> <li>EpiKnet (FR)</li> <li>QuakeNet (EN)</li> <li>UnderNet (EN)</li> <li>KottNet (EN)</li> </ul> <h1>Se connecter à un serveur</h1> <p> Pour se connecter, il suffit d'ouvrir le menu (touche <string>menu</string> de votre téléphone) et de sélectionner <strong>Connexion</strong>. EpiKnet étant le seul serveur francophone par défaut, nous vous conseillons de vous y connecter. </p> <h1>Rejoindre un salon</h1> <p> Une fois la connexion réussie, vous devez rejoindre un salon pour pouvoir commencer à discuter. Il existe deux manières : </p> <ul> <li> Dans le menu, sélectionnez <strong>Action</strong>, <strong>Rejoindre un salon</strong> et indiquez <strong>#dialogues</strong> (seulement pour EpiKnet) </li> <li>Tapez directement dans la barre <strong>/join #dialogues</strong>.</li> </ul> <p> Il est bien sûr possible de rejoindre plusieurs salons sur plusieurs serveurs différents ! Vous pouvez à tout moment voir et naviguer entre vos salons via le menu, rubrique <strong>Fenêtres</strong>. </p> <strong>Pour plus d'informations</strong> : <a href="http://wiki.androirc.com">wiki</a> [en] EOF ); $em->persist($french); $english = new QuickStart(); $english->setLanguage('en'); $english->setVersionMin($this->getReference('androirc_version_1.0')); $english->setContent(<<<EOF <h1>Welcome!</h1> <p> Welcome to AndroIRC! This window only appears at first launch. </p> <h1>Beginning</h1> <p> AndroIRC allows you to quickly and easily connect to any IRC network. For more explanation on the IRC protocol, <a href="http://en.wikipedia.org/wiki/Internet_Relay_Chat">the wikipedia page</a> is here! AndroIRC includes five servers by default: </p> <ul> <li>freenode (EN)</li> <li>EpiKnet (FR)</li> <li>QuakeNet (EN)</li> <li>UnderNet (EN)</li> <li>KottNet (EN)</li> </ul> <h1>Connect to a server</h1> <p> To connect, just open the menu (using the <strong>menu</strong> key of your phone) and select <strong>Connect</strong>. You can connect to any IRC network. If you do not know which to choose, use freenode. </p> <h1>Join a chan</h1> <p> Once the connection is successful, you must join a channel to begin to discuss. There are two ways: </p> <ul> <li> In the menu, select <strong>Action</strong>, <strong>Join a chan</strong> and indicate #freenode (only for freenode) </li> <li> Write directly into the textbar <strong>/join #freenode</strong> </li> </ul> <p> It is, of course, possible to join several chans on several servers at the same time! You can always view and navigate through your chans via the menu, item <strong>Windows</strong>. </p> EOF ); $em->persist($english); $em->flush(); } /** * Get the order of this fixture * * @return integer */ public function getOrder() { return 5; } }
30.333333
101
0.678783
2561028de91fb555fcfce754d63d79f6592eff40
331
js
JavaScript
doc/html/search/all_5.js
Bino3D/Bino_Stereo_SDK
9169ad395b1c5f354ea5abc1a92fa4ddab3eef09
[ "MIT" ]
5
2017-11-10T03:17:34.000Z
2020-09-03T08:09:35.000Z
doc/html/search/all_5.js
wuyou33/Bino_Stereo_SDK
9169ad395b1c5f354ea5abc1a92fa4ddab3eef09
[ "MIT" ]
1
2021-03-15T16:10:51.000Z
2021-03-15T16:10:51.000Z
doc/html/search/all_5.js
wuyou33/Bino_Stereo_SDK
9169ad395b1c5f354ea5abc1a92fa4ddab3eef09
[ "MIT" ]
7
2017-12-06T03:51:10.000Z
2020-11-26T14:13:35.000Z
var searchData= [ ['imudata',['ImuData',['../structImuData.html',1,'']]], ['imurect',['ImuRect',['../classBinoCamera.html#a5662fa1d861687af9577508be18ae29d',1,'BinoCamera']]], ['intparameterpath',['intParameterPath',['../structBinoCameraParameterList.html#ad2c8ebe70a244b212608d2a549c74b4a',1,'BinoCameraParameterList']]] ];
47.285714
147
0.73716
5cfd72e2d54563e1f5b83d29751516cd9958d061
894
php
PHP
resources/views/layouts/admin.blade.php
ynothan/social-robot
a17d8ca458f7f2246c5950c22bc76c0d7010e65b
[ "MIT" ]
null
null
null
resources/views/layouts/admin.blade.php
ynothan/social-robot
a17d8ca458f7f2246c5950c22bc76c0d7010e65b
[ "MIT" ]
null
null
null
resources/views/layouts/admin.blade.php
ynothan/social-robot
a17d8ca458f7f2246c5950c22bc76c0d7010e65b
[ "MIT" ]
null
null
null
<html> <head> <title>App Name - @yield('title')</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/css/materialize.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.0/js/materialize.min.js"></script> <link href="http://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body> <div class="container"> @include('partials.nav') <div class="row"> <div class="col s4"> @include('back.partials.sidebar') </div> <div class="col s8"> @yield('content') {{-- le contenu sera placé ici --}} </div> </div> </div> </body> <script> $(document).ready(function() { $('select').material_select(); $('#flash').delay(3000).fadeOut(); }) // end-ready; </script> </html>
23.526316
118
0.642058
27a49b1fab57753bfd4db18f685809aa40a169a8
73
rs
Rust
chronicle-cql/src/lib.rs
JakeSCahill/chronicle.rs
ac526a9348e648d3e97451d9bcecc47abb7ab3b5
[ "Apache-2.0" ]
null
null
null
chronicle-cql/src/lib.rs
JakeSCahill/chronicle.rs
ac526a9348e648d3e97451d9bcecc47abb7ab3b5
[ "Apache-2.0" ]
null
null
null
chronicle-cql/src/lib.rs
JakeSCahill/chronicle.rs
ac526a9348e648d3e97451d9bcecc47abb7ab3b5
[ "Apache-2.0" ]
null
null
null
pub mod compression; pub mod frame; pub mod murmur3; pub mod statements;
14.6
20
0.780822
437b22f2037c7a10b0d8799340ab377ce6db341d
1,998
swift
Swift
algorithms/swift/removeOutermostParentheses/removeOutermostParentheses.swift
Mylittleswift/leetcode
b49e6b89178a73e4a44d78f37910ee49797c42c4
[ "MIT" ]
3
2021-06-14T03:20:45.000Z
2021-07-06T08:30:47.000Z
algorithms/swift/removeOutermostParentheses/removeOutermostParentheses.swift
AnYuan/leetcode-swift
f04160efbfbc6e057c1cb6bbbc40de85e21d60fe
[ "MIT" ]
null
null
null
algorithms/swift/removeOutermostParentheses/removeOutermostParentheses.swift
AnYuan/leetcode-swift
f04160efbfbc6e057c1cb6bbbc40de85e21d60fe
[ "MIT" ]
null
null
null
/* 1021. Remove Outermost Parentheses A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings. A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings. Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings. Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S. Example 1: Input: "(()())(())" Output: "()()()" Explanation: The input string is "(()())(())", with primitive decomposition "(()())" + "(())". After removing outer parentheses of each part, this is "()()" + "()" = "()()()". Example 2: Input: "(()())(())(()(()))" Output: "()()()()(())" Explanation: The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))". After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())". Example 3: Input: "()()" Output: "" Explanation: The input string is "()()", with primitive decomposition "()" + "()". After removing outer parentheses of each part, this is "" + "" = "". Note: 1.S.length <= 10000 2.S[i] is "(" or ")" 3.S is a valid parentheses string https://leetcode.com/problems/remove-outermost-parentheses/ */ class Solution { func removeOuterParentheses(_ S: String) -> String { var result = "" var opened = 0 for s in S { if s == "(" { if opened > 0 { result.append(s) } opened += 1 } else if s == ")" { opened -= 1 if opened > 0 { result.append(s) } } } return result } }
33.864407
242
0.566066
032ce9d3577c4d420c9d6275e0c20934dd2546d1
2,050
ps1
PowerShell
AzureDevOps/.setup.ps1
thisjustin816/.dotfiles
dc7167d77c92445208c1082221dba6fac4bc38d8
[ "MIT" ]
null
null
null
AzureDevOps/.setup.ps1
thisjustin816/.dotfiles
dc7167d77c92445208c1082221dba6fac4bc38d8
[ "MIT" ]
null
null
null
AzureDevOps/.setup.ps1
thisjustin816/.dotfiles
dc7167d77c92445208c1082221dba6fac4bc38d8
[ "MIT" ]
3
2020-06-15T23:07:59.000Z
2020-07-21T15:54:23.000Z
if (!( Get-Command Import-PowerShellDataFile -ErrorAction SilentlyContinue )) { Import-Module -Name "C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Utility\Microsoft.PowerShell.Utility.psd1" } # This file will contain sensitive information and should not be committed to the repo. <# EXAMPLE @{ System_AccessToken = '*********************************************' System_CollectionUri = 'https://dev.azure.com/[organization]' System_TeamProject = 'PowerShellProject' Build_RequestedFor = 'Justin Beeson' Build_RequestedForEmail = 'jbeeson@organization.email' } #> $envVariables = @{} try { $envVariables = Import-PowerShellDataFile -Path $PSScriptRoot\.envVars.psd1 -ErrorAction Stop } catch { try { $envVarNames = ( 'System_AccessToken', 'System_CollectionUri', 'System_TeamProject', 'Build_RequestedFor', 'Build_RequestedForEmail' ) foreach ($var in $envVarNames) { $envVariables[$var] = ( Get-Item -Path "env:$var" -ErrorAction Stop ).Value } } catch { Write-Warning -Message ( "Couldn't import environment variables. Have you created " + "$PSScriptRoot\.envVars.psd1 or manually set the environment variables?" ) Write-Host -Object "Example:" Write-Host -Object @" @{ System_AccessToken = '*********************************************' System_CollectionUri = 'https://dev.azure.com/[organization]' System_TeamProject = 'PowerShellProject' Build_RequestedFor = 'Justin Beeson' Build_RequestedForEmail = 'jbeeson@organization.email' } "@ exit } } foreach ($var in $envVariables.Keys) { [System.Environment]::SetEnvironmentVariable($var, $envVariables[$var], 'User') New-Item -Path "env:$var" -Value $envVariables[$var] -Force | ForEach-Object -Process { if ($_.Name -match '[Tt]oken') { $_.Value = '***' } $_ } }
34.166667
139
0.606341
027819e961512efc5a5ec99005c2753ebcd04467
1,669
cpp
C++
velox/connectors/hive/tests/FileHandleTest.cpp
winningsix/velox-1
45c25f5ad58491ede2491b9406256535ce438b2d
[ "Apache-2.0" ]
null
null
null
velox/connectors/hive/tests/FileHandleTest.cpp
winningsix/velox-1
45c25f5ad58491ede2491b9406256535ce438b2d
[ "Apache-2.0" ]
null
null
null
velox/connectors/hive/tests/FileHandleTest.cpp
winningsix/velox-1
45c25f5ad58491ede2491b9406256535ce438b2d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "velox/connectors/hive/FileHandle.h" #include <string> #include "gtest/gtest.h" #include "velox/common/caching/SimpleLRUCache.h" #include "velox/common/file/File.h" #include "velox/common/memory/Arena.h" using namespace facebook::velox; TEST(FileHandleTest, localFile) { // TODO: use the appropriate test directory. // Use unique name for each process/thread execution to prevent cross // process/thread race condition auto pid = getpid(); auto tid = pthread_self(); const std::string filename = "/tmp/test" + std::to_string(pid) + "_" + std::to_string(tid); remove(filename.data()); { LocalWriteFile writeFile(filename); writeFile.append("foo"); } FileHandleFactory factory( std::make_unique<SimpleLRUCache<std::string, FileHandle>>(1000), std::make_unique<FileHandleGenerator>()); auto fileHandle = factory.generate(filename); ASSERT_EQ(fileHandle->file->size(), 3); Arena arena; ASSERT_EQ(fileHandle->file->pread(0, 3, &arena), "foo"); // Clean up remove(filename.data()); }
31.490566
75
0.714799
728bbeff96f624fefea262a25bb8db8eb24c50eb
2,862
h
C
include/helper/PrintHelper.h
Tobi2001/asr_psm
18f0959c4a69a6e254d7b53a4d6cc6e6b28f0ccc
[ "BSD-3-Clause" ]
1
2019-10-29T13:37:30.000Z
2019-10-29T13:37:30.000Z
include/helper/PrintHelper.h
Tobi2001/asr_psm
18f0959c4a69a6e254d7b53a4d6cc6e6b28f0ccc
[ "BSD-3-Clause" ]
null
null
null
include/helper/PrintHelper.h
Tobi2001/asr_psm
18f0959c4a69a6e254d7b53a4d6cc6e6b28f0ccc
[ "BSD-3-Clause" ]
1
2019-11-03T14:00:30.000Z
2019-11-03T14:00:30.000Z
/** Copyright (c) 2017, Braun Kai, Gaßner Nikolai, Gehrung Joachim, Heizmann Heinrich, Meißner Pascal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <string> namespace ProbabilisticSceneRecognition { /** * This class offers functionality to help printing to the screen. */ class PrintHelper { public: /** * Constructor. * @param pMarker Symbol used to mark output with dividers consisting of it. */ PrintHelper(char pMarker) { mDivider = std::string(60, pMarker); } /** * Destructor. */ ~PrintHelper() { } /** * Add a line to print. * @param pLine to print. */ void addLine(const std::string& pLine) { mLines.push_back(pLine); } /** * Print added lines as header, between two dividers, and reset lines. */ void printAsHeader() { ROS_INFO_STREAM(mDivider); for (std::string line: mLines) ROS_INFO_STREAM(line); ROS_INFO_STREAM(mDivider); mLines = std::vector<std::string>(); // reset mLines. } /** * Print a single line as a header. * @param pLine */ void printAsHeader(const std::string& pLine) { addLine(pLine); printAsHeader(); } private: /** * Divider used to mark output. */ std::string mDivider; /** * Lines to print. */ std::vector<std::string> mLines; }; }
31.8
755
0.697065
dd5990d9e0b2a75fa8cdefcf9caae2c1c938f60a
300
java
Java
patterns-base/src/test/java/com/github/bjlhx15/patterns/base/eg03action/eg03observale/PersonGuavaTest.java
bjlhx15/patterns
4c97a563a835023efe70517203449e0ad31b8dcb
[ "Apache-2.0" ]
null
null
null
patterns-base/src/test/java/com/github/bjlhx15/patterns/base/eg03action/eg03observale/PersonGuavaTest.java
bjlhx15/patterns
4c97a563a835023efe70517203449e0ad31b8dcb
[ "Apache-2.0" ]
1
2022-03-31T20:16:45.000Z
2022-03-31T20:16:45.000Z
patterns-base/src/test/java/com/github/bjlhx15/patterns/base/eg03action/eg03observale/PersonGuavaTest.java
bjlhx15/patterns
4c97a563a835023efe70517203449e0ad31b8dcb
[ "Apache-2.0" ]
null
null
null
package com.github.bjlhx15.patterns.base.eg03action.eg03observale; import org.junit.Test; public class PersonGuavaTest { @Test public void test() { PersonGuava person = new PersonGuava(); person.setName("李宏旭"); person.setAge(30); person.setSex("男"); } }
21.428571
66
0.646667
b712fbd5ae633a340b16a88f44043bb2741faa92
3,357
cs
C#
Runtime/request-interfaces/Request.cs
beatthat/unity-request-interfaces
80ec833b893358f013124c70213edcd4170b2845
[ "MIT" ]
null
null
null
Runtime/request-interfaces/Request.cs
beatthat/unity-request-interfaces
80ec833b893358f013124c70213edcd4170b2845
[ "MIT" ]
null
null
null
Runtime/request-interfaces/Request.cs
beatthat/unity-request-interfaces
80ec833b893358f013124c70213edcd4170b2845
[ "MIT" ]
null
null
null
using System; namespace BeatThat.Requests { /// <summary> /// A Request is an async op that may succeed, fail or be cancelled /// </summary> public interface Request : IDisposable, HasError { event Action StatusUpdated;// TODO: replace with UnityEvent RequestStatus status { get; } bool isCancelled { get; } /// <summary> /// Progress of the request /// </summary> float progress { get; } bool hasError { get; } void Cancel(); /// <summary> /// Execute the request and call the (optional) callback when the request terminates, successful or otherwise. /// </summary> void Execute(Action callback = null, bool callbackOnCancelled = false); ///<summary> /// often a web uri, but can be anything that helps identify the request ///</summary> string loggingName { get; } /// <summary> /// Signal to log debug info for a specific request. /// Ususally more useful than a global flag, because there can be so many requests running at a time, /// including multiples of the same type. /// </summary> bool debug { get; set; } } /// <summary> /// A request that retrieves an item /// </summary> public interface ItemRequest { object GetItem(); } /// <summary> /// A request that retrieves a typed item /// </summary> public interface Request<T> : Request, ItemRequest { T item { get; } } public static class RequestExt { public static bool CanExecuteFromCurrentStatus(this Request r) { if (r == null) { return false; } return ( r.status == RequestStatus.NONE || r.status == RequestStatus.QUEUED); } /// <summary> /// Utility for cases where a service stores the 'active' request, /// e.g. to prevent duplicate concurrent requests. /// If the passed request is the same ref as the passed ref, then nulls the ref /// If not, clears the request (this is why it's a ref arg) /// </summary> public static bool ClearIfMatches<T>(this Request r, ref T rRef) where T : class { if (r == null) { return false; } if (Object.ReferenceEquals(r, rRef)) { rRef = null; return true; } return false; } public static bool IsDoneOrCancelled(this Request r) { if (r == null) { return false; } return ( r.status == RequestStatus.DONE || r.status == RequestStatus.CANCELLED); } public static bool IsQueuedOrInProgress(this Request r) { return r.status == RequestStatus.QUEUED || r.status == RequestStatus.IN_PROGRESS; } public static T GetResult<T>(this Request r) { if (r == null) { return default(T); } var hasItem = r as ItemRequest; return hasItem != null ? (T)hasItem.GetItem() : default(T); } } }
27.516393
118
0.521597
72db2972514bf6bd1adbe29b2812a275582b31d7
710
cs
C#
ModelFramework/AsyncCommands/Handlers/IAsyncCommandHandler.cs
ChessOK/ModelFramework
e79be753748f9ba891f1acbb60770b8af9a47178
[ "MIT" ]
2
2015-11-09T14:37:00.000Z
2021-02-08T16:58:30.000Z
ModelFramework/AsyncCommands/Handlers/IAsyncCommandHandler.cs
ChessOK/ModelFramework
e79be753748f9ba891f1acbb60770b8af9a47178
[ "MIT" ]
null
null
null
ModelFramework/AsyncCommands/Handlers/IAsyncCommandHandler.cs
ChessOK/ModelFramework
e79be753748f9ba891f1acbb60770b8af9a47178
[ "MIT" ]
2
2016-02-20T17:51:47.000Z
2021-02-08T16:58:34.000Z
using ChessOk.ModelFramework.AsyncCommands.Workers; using ChessOk.ModelFramework.Commands; namespace ChessOk.ModelFramework.AsyncCommands.Handlers { /// <summary> /// Предоставляет интерфейс для обработчиков команд <see cref="CommandBase"/>, /// выполняемых асинхронно. /// <para> /// Обработчик вызывается после получания команды из очереди (см. /// пример в классе <see cref="BackgroundThreadWorker"/>). /// </para> /// </summary> public interface IAsyncCommandHandler { /// <summary> /// Обработать и выполнить команду <paramref name="asyncCommand"/>. /// </summary> void Handle(CommandBase asyncCommand); } }
33.809524
83
0.650704
23d825d9a7c32b439c53328dd4d9dcfd5cd550f2
293
js
JavaScript
app/containers/MovieDetailPage/constants.js
mykjmll/theMovieCodingChallenge
0d8aac5d65822132ca72516029a3005d353c4993
[ "MIT" ]
null
null
null
app/containers/MovieDetailPage/constants.js
mykjmll/theMovieCodingChallenge
0d8aac5d65822132ca72516029a3005d353c4993
[ "MIT" ]
null
null
null
app/containers/MovieDetailPage/constants.js
mykjmll/theMovieCodingChallenge
0d8aac5d65822132ca72516029a3005d353c4993
[ "MIT" ]
null
null
null
/* * * MovieDetailPage constants * */ export const FETCH_MOVIE_BY_ID = 'app/SearchPage/FETCH_MOVIE_BY_ID'; export const SET_SUCCESS_DATA = 'app/SearchPage/SET_SUCCESS_DATA'; export const FETCH_ERROR = 'app/SearchPage/FETCH_ERROR'; export const SET_LOADING = 'app/SearchPage/SET_LOADING';
26.636364
68
0.784983
df41b376c8cee6549112b89a2d7fc2e09123f860
1,086
cs
C#
src/Microsoft.AspNet.SignalR.Server/Hubs/DefaultHubActivator.cs
avdinfotech/SignalR-Server
4b47695cfd12650248d6b085c4899410efa5005a
[ "Apache-2.0" ]
3
2018-06-15T15:37:55.000Z
2021-01-22T12:17:45.000Z
src/Microsoft.AspNet.SignalR.Server/Hubs/DefaultHubActivator.cs
avdinfotech/SignalR-Server
4b47695cfd12650248d6b085c4899410efa5005a
[ "Apache-2.0" ]
null
null
null
src/Microsoft.AspNet.SignalR.Server/Hubs/DefaultHubActivator.cs
avdinfotech/SignalR-Server
4b47695cfd12650248d6b085c4899410efa5005a
[ "Apache-2.0" ]
2
2018-03-08T12:14:40.000Z
2020-05-30T02:23:40.000Z
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.Framework.DependencyInjection; namespace Microsoft.AspNet.SignalR.Hubs { public class DefaultHubActivator : IHubActivator { private readonly ITypeActivator _typeActivator; private readonly IServiceProvider _serviceProvider; public DefaultHubActivator(ITypeActivator typeActivator, IServiceProvider serviceProvider) { _typeActivator = typeActivator; _serviceProvider = _serviceProvider; } public IHub Create(HubDescriptor descriptor) { if (descriptor == null) { throw new ArgumentNullException("descriptor"); } if (descriptor.HubType == null) { return null; } return _typeActivator.CreateInstance(_serviceProvider, descriptor.HubType) as IHub; } } }
29.351351
111
0.650092
20adebe37d15e25c0207bb414c91f14d88ccb383
1,372
cs
C#
src/Nest/Document/Single/Get/GetResponse.cs
iSatishYadav/elasticsearch-net
ac9e96c02cd38c0033f3c4273d22113f56b57d94
[ "Apache-2.0" ]
null
null
null
src/Nest/Document/Single/Get/GetResponse.cs
iSatishYadav/elasticsearch-net
ac9e96c02cd38c0033f3c4273d22113f56b57d94
[ "Apache-2.0" ]
null
null
null
src/Nest/Document/Single/Get/GetResponse.cs
iSatishYadav/elasticsearch-net
ac9e96c02cd38c0033f3c4273d22113f56b57d94
[ "Apache-2.0" ]
null
null
null
using System; using Newtonsoft.Json; namespace Nest { public interface IGetResponse<out TDocument> : IResponse where TDocument : class { [JsonProperty("fields")] FieldValues Fields { get; } [JsonProperty("found")] bool Found { get; } [JsonProperty("_id")] string Id { get; } [JsonProperty("_index")] string Index { get; } [JsonProperty("_parent")] [Obsolete("No longer returned on indices created in Elasticsearch 6.0")] string Parent { get; } [JsonProperty("_routing")] string Routing { get; } [JsonProperty("_source")] [JsonConverter(typeof(SourceConverter))] TDocument Source { get; } [JsonProperty("_type")] string Type { get; } [JsonProperty("_version")] long Version { get; } } [JsonObject(MemberSerialization.OptIn)] public class GetResponse<TDocument> : ResponseBase, IGetResponse<TDocument> where TDocument : class { public FieldValues Fields { get; internal set; } = FieldValues.Empty; public bool Found { get; internal set; } public string Id { get; internal set; } public string Index { get; internal set; } public string Parent { get; internal set; } public string Routing { get; internal set; } public TDocument Source { get; internal set; } public string Type { get; internal set; } public long Version { get; internal set; } } }
26.384615
101
0.667638
e321d5a0da6e371dba69e19b71c6750fb598a635
700
dart
Dart
lib/src/schema.dart
ali2236/query_gen
d3ada0ebbe564b5b98b4ba4597c9dd9765e205b5
[ "BSD-3-Clause" ]
null
null
null
lib/src/schema.dart
ali2236/query_gen
d3ada0ebbe564b5b98b4ba4597c9dd9765e205b5
[ "BSD-3-Clause" ]
null
null
null
lib/src/schema.dart
ali2236/query_gen
d3ada0ebbe564b5b98b4ba4597c9dd9765e205b5
[ "BSD-3-Clause" ]
null
null
null
import 'package:code_builder/code_builder.dart'; import 'package:query_gen/src/Property.dart'; import 'package:query_gen/src/builders/builder_class.dart'; import 'json_object.dart'; class Schema { final String name; final JsonObject source; Schema(this.name, this.source); JsonObject get _properties => source['properties']; Iterable<String>? get required => source['required']?.cast<String>(); Iterable<Property>? get properties { var req = required?.toSet() ?? <String>{}; return _properties.entries.map((e) => Property(e.key, e.value, nullableParameter: !req.contains(e.key))); } Class get asClass => serializableClassBuilder(name: name, properties: properties!); }
29.166667
109
0.725714
a37b6dfa931bd46ffd8d2b55b01b0d35998566d6
5,435
java
Java
src/main/java/com/cgovern/governor/controller/UsersApiController.java
ravivamsi/governor
0b83267b2e32ea8442b629df7b69cf593d74dc34
[ "Apache-2.0" ]
null
null
null
src/main/java/com/cgovern/governor/controller/UsersApiController.java
ravivamsi/governor
0b83267b2e32ea8442b629df7b69cf593d74dc34
[ "Apache-2.0" ]
26
2019-12-14T05:01:17.000Z
2020-01-03T05:34:48.000Z
src/main/java/com/cgovern/governor/controller/UsersApiController.java
ravivamsi/governor
0b83267b2e32ea8442b629df7b69cf593d74dc34
[ "Apache-2.0" ]
null
null
null
package com.cgovern.governor.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import com.cgovern.governor.api.UsersApi; import com.cgovern.governor.models.User; import com.cgovern.governor.models.UserRepository; import com.fasterxml.jackson.databind.ObjectMapper; import io.swagger.annotations.ApiParam; @javax.annotation.Generated(value = "io.swagger.codegen.languages.SpringCodegen", date = "2019-12-22T04:22:26.530Z") @Controller public class UsersApiController implements UsersApi { private static final Logger log = LoggerFactory.getLogger(UsersApiController.class); private final ObjectMapper objectMapper; private final HttpServletRequest request; private final UserRepository userRepository; @org.springframework.beans.factory.annotation.Autowired public UsersApiController(ObjectMapper objectMapper, HttpServletRequest request, UserRepository userRepository) { this.objectMapper = objectMapper; this.request = request; this.userRepository = userRepository; } public ResponseEntity<User> createUser( @ApiParam(value = "Created user object", required = true) @Valid @RequestBody User body) { String accept = request.getHeader("Accept"); if (accept != null && accept.contains("application/json")) { List<User> userList = userRepository.findAll(); for (User currentUser : userList) { if (currentUser.getUsername().equalsIgnoreCase(body.getUsername())) { return new ResponseEntity<User>(HttpStatus.CONFLICT); } } return new ResponseEntity<User>(userRepository.save(body), HttpStatus.CREATED); } return new ResponseEntity<User>(HttpStatus.NOT_IMPLEMENTED); } public ResponseEntity<User> deleteUser( @ApiParam(value = "The name that needs to be deleted", required = true) @PathVariable("username") String username) { String accept = request.getHeader("Accept"); // TODO - Test User user = new User(); if (accept != null && accept.contains("application/json")) { List<User> userList = userRepository.findAll(); for (User currentUser : userList) { if (currentUser.getUsername().equalsIgnoreCase(username)) { user = currentUser; } } if (user.getId().isEmpty()) { userRepository.deleteById(user.getId()); } else { return new ResponseEntity<User>(user, HttpStatus.NOT_FOUND); } return new ResponseEntity<User>(user, HttpStatus.ACCEPTED); } else { return new ResponseEntity<User>(user, HttpStatus.BAD_REQUEST); } } public ResponseEntity<User> getUserByName( @ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ", required = true) @PathVariable("username") String username) { String accept = request.getHeader("Accept"); User user = new User(); if (accept != null && accept.contains("application/json")) { List<User> userList = userRepository.findAll(); for (User currentUser : userList) { if (currentUser.getUsername().equalsIgnoreCase(username)) { user = currentUser; } } if (user.getId().isEmpty()) { return new ResponseEntity<User>(user, HttpStatus.NOT_FOUND); } else { return new ResponseEntity<User>(user, HttpStatus.OK); } } else { return new ResponseEntity<User>(user, HttpStatus.BAD_REQUEST); } } public ResponseEntity<User> updateUser( @ApiParam(value = "name that need to be updated", required = true) @PathVariable("username") String username, @ApiParam(value = "Updated user object", required = true) @Valid @RequestBody User body) { String accept = request.getHeader("Accept"); User user = new User(); if (accept != null && accept.contains("application/json")) { List<User> userList = userRepository.findAll(); for (User currentUser : userList) { if (currentUser.getUsername().equalsIgnoreCase(username)) { user = currentUser; } } user.setEmail(body.getEmail()); user.setFirstName(body.getFirstName()); user.setLastName(body.getLastName()); user.setPassword(body.getPassword()); user.setPhone(body.getPhone()); user.setRoles(body.getRoles()); user.setStatus(body.getStatus()); user.setTier(body.getTier()); userRepository.save(user); return new ResponseEntity<User>(user, HttpStatus.ACCEPTED); } return new ResponseEntity<User>(HttpStatus.NOT_IMPLEMENTED); } public ResponseEntity<Void> getUserNameAvailability( @ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ", required = true) @PathVariable("username") String username) { String accept = request.getHeader("Accept"); User user = new User(); if (accept != null && accept.contains("application/json")) { List<User> userList = userRepository.findAll(); for (User currentUser : userList) { if (currentUser.getUsername().equalsIgnoreCase(username)) { user = currentUser; } } if (user.getUsername().isEmpty()) { return new ResponseEntity<Void>(HttpStatus.OK); } else { return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST); } } else { return new ResponseEntity<Void>(HttpStatus.BAD_REQUEST); } } }
30.706215
144
0.727139
0aa22698ba5f66a32011a7a09fc79a2b4437c73f
8,147
cs
C#
Assets/Scripts/GlobeViz/Covid19Viz.cs
ram66351/ARCoreViz
aa8660ecb7b3186109a31a35c5fe7d88681a611e
[ "Apache-2.0" ]
null
null
null
Assets/Scripts/GlobeViz/Covid19Viz.cs
ram66351/ARCoreViz
aa8660ecb7b3186109a31a35c5fe7d88681a611e
[ "Apache-2.0" ]
null
null
null
Assets/Scripts/GlobeViz/Covid19Viz.cs
ram66351/ARCoreViz
aa8660ecb7b3186109a31a35c5fe7d88681a611e
[ "Apache-2.0" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Globalization; public class Covid19Viz : MonoBehaviour { public TextAsset csvData; public bool isDataReceived = false; private string[,] Grid; public GameObject DataPointPrefab; public Covid19Data.Status status; public Color32 dataColor; public Transform Earth; public static Dictionary<string, GameObject> CovidLoc = new Dictionary<string, GameObject>(); // Start is called before the first frame update public static Covid19Viz Instance; public delegate void StopPlaneDetection(); public static StopPlaneDetection StopPlaneDetectionEvent; public static Dictionary<string, int> NoOfCasesConfirmed = new Dictionary<string, int>(); public static Dictionary<string, int> NoOfCasesDead = new Dictionary<string, int>(); public static Dictionary<string, int> NoOfCasesRecovered = new Dictionary<string, int>(); public static Dictionary<string, List<Covid19Data>> CountryConfirmedData = new Dictionary<string, List<Covid19Data>>(); public static Dictionary<string, List<Covid19Data>> CountryDeathData = new Dictionary<string, List<Covid19Data>>(); public static Dictionary<string, List<Covid19Data>> CountryRecoveredData = new Dictionary<string, List<Covid19Data>>(); void Start() { Init(); } public void Init() { Instance = this; Earth = transform; CSVLoader.CSVLoaderThread(csvData.text, ReceiveData); if (Application.platform == RuntimePlatform.Android) { StopPlaneDetectionEvent(); } } void ReceiveData(string[,] data) { Grid = data; Debug.Log("Received Data ! " + Grid.GetUpperBound(0) + ", " + Grid.GetUpperBound(1)); isDataReceived = true; } void LateUpdate() { if (isDataReceived) { PopulateData(); } } void PopulateData() { int row = Grid.GetUpperBound(0); int col = Grid.GetUpperBound(1); DateTime StartDt, EndDt; CultureInfo culture = new CultureInfo("en-US"); Debug.Log(Grid[4, 0] +", "+ Grid[row -2, 0]); DateTime.TryParse(Grid[4, 0], culture, DateTimeStyles.None, out StartDt); DateTime.TryParse(Grid[row - 2, 0], culture, DateTimeStyles.None, out EndDt); int totalDays = (EndDt - StartDt).Days; GraphMaster.Instance.SetupDates(StartDt, EndDt); Debug.Log(StartDt +", "+ EndDt +", days : "+totalDays); for (int i = 0; i < col; i++) { float lat, lon = 0; if (!float.TryParse(Grid[2, i], out lat)) { continue; } if (!float.TryParse(Grid[3, i], out lon)) { continue; } DateTime dt = DateTime.Now; int[] DayByDay = new int[totalDays]; for (int j = 4; j < row - 2; ++j) { int val = 0; int.TryParse(Grid[j, i], out val); DayByDay[j - 4] = val; } Covid19Data covidData = new Covid19Data(Grid[0, i], Grid[1, i], lat, lon, StartDt, EndDt, status, DayByDay ); string loc = covidData.CountryORRegion + lat.ToString() + lon.ToString(); //Order of Priority //Confirmed is the primary Data, then death and then recovered //so the 3Dinstance is created based on confirmed and then updating that instance with death and recovered if (status == Covid19Data.Status.confirmed) { if (NoOfCasesConfirmed.ContainsKey(covidData.CountryORRegion)) { NoOfCasesConfirmed[covidData.CountryORRegion] += covidData.DayByDayData[covidData.DayByDayData.Length - 1]; } else { NoOfCasesConfirmed.Add(covidData.CountryORRegion, covidData.DayByDayData[covidData.DayByDayData.Length - 1]); } if(CountryConfirmedData.ContainsKey(covidData.CountryORRegion)) { CountryConfirmedData[covidData.CountryORRegion].Add(covidData); } else { List<Covid19Data> list = new List<Covid19Data>(); list.Add(covidData); CountryConfirmedData[covidData.CountryORRegion] = list; } } else if(status == Covid19Data.Status.dead) { if (NoOfCasesDead.ContainsKey(covidData.CountryORRegion)) { NoOfCasesDead[covidData.CountryORRegion] += covidData.DayByDayData[covidData.DayByDayData.Length - 1]; } else { NoOfCasesDead.Add(covidData.CountryORRegion, covidData.DayByDayData[covidData.DayByDayData.Length - 1]); } if (CountryDeathData.ContainsKey(covidData.CountryORRegion)) { CountryDeathData[covidData.CountryORRegion].Add(covidData); } else { List<Covid19Data> list = new List<Covid19Data>(); list.Add(covidData); CountryDeathData[covidData.CountryORRegion] = list; } } else if (status == Covid19Data.Status.recovered) { if (NoOfCasesRecovered.ContainsKey(covidData.CountryORRegion)) { NoOfCasesRecovered[covidData.CountryORRegion] += covidData.DayByDayData[covidData.DayByDayData.Length - 1]; } else { NoOfCasesRecovered.Add(covidData.CountryORRegion, covidData.DayByDayData[covidData.DayByDayData.Length - 1]); } if (CountryRecoveredData.ContainsKey(covidData.CountryORRegion)) { CountryRecoveredData[covidData.CountryORRegion].Add(covidData); } else { List<Covid19Data> list = new List<Covid19Data>(); list.Add(covidData); CountryRecoveredData[covidData.CountryORRegion] = list; } } if (CovidLoc.ContainsKey(loc)) { //Debug.Log("Key Already Existing " + loc +", at : " + i); if(status == Covid19Data.Status.dead) { //Debug.Log("Adding Covid19 death data"); CovidLoc[loc].GetComponent<CovidData3DInstance>().CovidData_Death = covidData; } else if(status == Covid19Data.Status.recovered) { CovidLoc[loc].GetComponent<CovidData3DInstance>().CovidData_Recovered = covidData; } } else { GameObject dataPointClone = Instantiate(DataPointPrefab, transform) as GameObject; dataPointClone.GetComponent<CovidData3DInstance>().Init(covidData, transform, dataColor); CovidLoc.Add(loc, dataPointClone); if(covidData.CountryORRegion == "US") { if(i%10 != 0) { dataPointClone.SetActive(false); } } } } //foreach(var entry in CountryConfirmedData) //{ // Debug.Log(entry.Key +" "+entry.Value.Count); //} isDataReceived = false; } }
36.533632
129
0.524488
fa43f3aa4ae898aaebd7b7e07875120024a75ddc
395
cpp
C++
algo/Peak_Find/peak_1d.cpp
ishan-chaudhary/Algorithms
57dbc199e40634ac2d2fdbed123577f72e25a405
[ "MIT" ]
4
2020-10-20T09:30:34.000Z
2020-10-23T02:43:01.000Z
algo/Peak_Find/peak_1d.cpp
ishan-chaudhary/Algorithms
57dbc199e40634ac2d2fdbed123577f72e25a405
[ "MIT" ]
31
2020-10-17T07:31:46.000Z
2020-10-28T07:38:19.000Z
algo/Peak_Find/peak_1d.cpp
ishan-chaudhary/Algorithms
57dbc199e40634ac2d2fdbed123577f72e25a405
[ "MIT" ]
30
2020-10-19T04:48:57.000Z
2020-10-28T02:38:04.000Z
#include<iostream> using namespace std; //using divide and conquer approach //time complexity:O(logn) void peak_1d(int arr[],int size){ int mid=size/2; if(arr[mid]<arr[mid-1]){ peak_1d(arr,mid-1); } else if(arr[mid]<arr[mid+1]){ peak_1d(arr,size+mid/2); } else cout<<"Peak : "<<arr[mid]; } int main(){ int arr[9]={2,5,6,5,34,11,23,0,3}; peak_1d(arr,9); return 0; }
17.173913
36
0.61519
8efb955a5c8c7ba298b822a88bdb6801442bd8db
716
rb
Ruby
spec/integral_spec.rb
yamasolutions/integral
db83889c862167332c31254644c9de1d441b6577
[ "MIT" ]
22
2018-10-23T00:05:44.000Z
2022-01-26T04:02:02.000Z
spec/integral_spec.rb
yamasolutions/integral
db83889c862167332c31254644c9de1d441b6577
[ "MIT" ]
59
2018-10-08T08:02:46.000Z
2022-02-26T04:27:32.000Z
spec/integral_spec.rb
yamasolutions/integral
db83889c862167332c31254644c9de1d441b6577
[ "MIT" ]
5
2019-03-10T09:32:53.000Z
2021-09-20T17:29:43.000Z
require "rails_helper" module Integral describe "#configure" do let(:foo) { '' } context 'black_listed_paths' do context 'when setting is set' do let(:black_listed_paths) { [ '/test1', '/test2' ] } before do Integral.configure do |config| config.black_listed_paths = black_listed_paths end end it 'attempting to create a page under the black listed paths fails' do expect(build(:integral_page, path: '/test1/').valid?).to be false expect(build(:integral_page, path: '/test2/').valid?).to be false expect(build(:integral_page, path: '/admin/').valid?).to be true end end end end end
27.538462
78
0.604749
4b79b76caf9e2a044973e4f7a40247422f685420
1,163
kt
Kotlin
src/main/kotlin/com/deflatedpickle/bugmagic/common/networking/message/MessageSpellCaster.kt
DeflatedPickle/BugMagic
0a5eaf3ebdfabf106a232480f0ac6cde317257c2
[ "MIT" ]
3
2018-08-05T00:03:46.000Z
2020-06-06T13:26:13.000Z
src/main/kotlin/com/deflatedpickle/bugmagic/common/networking/message/MessageSpellCaster.kt
DeflatedPickle/BugMagic
0a5eaf3ebdfabf106a232480f0ac6cde317257c2
[ "MIT" ]
49
2018-08-09T23:27:40.000Z
2022-03-01T07:06:57.000Z
src/main/kotlin/com/deflatedpickle/bugmagic/common/networking/message/MessageSpellCaster.kt
DeflatedPickle/BugMagic
0a5eaf3ebdfabf106a232480f0ac6cde317257c2
[ "MIT" ]
2
2018-08-16T14:10:59.000Z
2018-10-06T00:17:13.000Z
/* Copyright (c) 2019-2020 DeflatedPickle under the MIT license */ package com.deflatedpickle.bugmagic.common.networking.message import io.netty.buffer.ByteBuf import net.minecraftforge.fml.common.network.ByteBufUtils import net.minecraftforge.fml.common.network.simpleimpl.IMessage /** * A packet that contains; an entity ID, their casting state and their casting progress * @see [MessageSpellCaster] */ class MessageSpellCaster( private var entityID: Int, private var isCasting: Boolean, private var castingCurrent: Float ) : IMessage { @Suppress("unused") constructor() : this(entityID = 1, isCasting = false, castingCurrent = -1f) operator fun component1() = this.entityID operator fun component2() = this.isCasting operator fun component3() = this.castingCurrent override fun toBytes(buf: ByteBuf) { ByteBufUtils.writeVarInt(buf, entityID, 5) buf.writeBoolean(isCasting) buf.writeFloat(castingCurrent) } override fun fromBytes(buf: ByteBuf) { entityID = ByteBufUtils.readVarInt(buf, 5) isCasting = buf.readBoolean() castingCurrent = buf.readFloat() } }
31.432432
87
0.71969
9052f243d9308ebbc29159d96f4fc468258afc1e
9,197
swift
Swift
WeiBo/WeiBo/Classes/Home/HomeViewController.swift
wangjiayu4657/Weibo
deb6d613b3dd50faea86b1000e93c9ab74e7a6ed
[ "Apache-2.0" ]
null
null
null
WeiBo/WeiBo/Classes/Home/HomeViewController.swift
wangjiayu4657/Weibo
deb6d613b3dd50faea86b1000e93c9ab74e7a6ed
[ "Apache-2.0" ]
null
null
null
WeiBo/WeiBo/Classes/Home/HomeViewController.swift
wangjiayu4657/Weibo
deb6d613b3dd50faea86b1000e93c9ab74e7a6ed
[ "Apache-2.0" ]
null
null
null
// // HomeController.swift // WeiBo // // Created by fangjs on 2016/11/2. // Copyright © 2016年 fangjs. All rights reserved. // import UIKit ///cell 的标识符 let homeCellIdentifier = "homeCellIdentifier" class HomeViewController: BaseViewController,UITableViewDataSourcePrefetching { ///缓存微博的行高 var cellHeight:[Int:CGFloat] = [Int:CGFloat]() ///数据模型 var models:[StatusesModel]?{ didSet { tableView.reloadData() } } override func viewDidLoad() { super.viewDidLoad() if !login { visitorView?.setupVisitorViewInfo(isHome: true, imageName: "visitordiscover_feed_image_house", message: "关注一些人,回这里看看有什么惊喜") navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.plain, target: self, action: #selector(registerBtnClick)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: UIBarButtonItemStyle.plain, target: self, action: #selector(loginBtnClick)) return } //注册 cell setUpTableView() //设置导航栏按钮 setupNavBarButton() //注册通知 NotificationCenter.default.addObserver(self, selector: #selector(changeTitleBtnState), name: NSNotification.Name(rawValue: PopoverAnimatorWillShowNotification), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(changeTitleBtnState), name: NSNotification.Name(rawValue: PopoverAnimatorWillDismissNotification), object: nil) //加载数据 loadData() promptLabel.isHidden = true } ///当有内容警告时清楚全部缓存 override func didReceiveMemoryWarning() { cellHeight.removeAll() } ///注册 cell private func setUpTableView() { tableView.register(HomeNormalCell.self, forCellReuseIdentifier: HomeTableViewCellType.normalCell.rawValue) tableView.register(HomeForwardCell.self, forCellReuseIdentifier: HomeTableViewCellType.forwardCell.rawValue) //预估高度 //tableView.estimatedRowHeight = 200 //自动计算高度 //tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorStyle = UITableViewCellSeparatorStyle.none tableView.prefetchDataSource = self //设置下拉刷新 refreshControl = HomeRefreshControl() refreshControl?.addTarget(self, action: #selector(loadData), for: UIControlEvents.valueChanged) } ///上拉或下拉的标志位 var pullRefreshFlag = false ///下拉刷新的 id private var since_id = 0 ///上拉刷新的 id private var max_id = 0 ///加载数据 func loadData() { // 1.默认最新返回20条数据 // 2.since_id : 会返回比since_id大的微博 // 3.max_id: 会返回小于等于max_id的微博 //每条微博都有一个微博ID, 而且微博ID越后面发送的微博, 它的微博ID越大递增 //判断是否为上拉刷新 if pullRefreshFlag { //将 since_id 置为 0,即在刷新数据时会根据所传递的参数判断是要请求上拉刷新的数据还是下拉刷新的数据 since_id = 0 //获取第一条微博的 max_id 如果为 models 为空则返回0 max_id = models?.last?.id ?? 0 } else { //获取第一条微博的 since_id 如果为 models 为空则返回0 since_id = models?.first?.id ?? 0 } //获取当前登录用户及其所关注(授权)用户的最新微博 StatusesModel.loadInfo (sinceId: since_id , maxId: max_id) { (statuse, error) in if error == nil { //结束刷新 self.refreshControl?.endRefreshing() //给数据源赋值 if self.since_id > 0 { // 如果是下拉刷新, 就将获取到的数据, 拼接在原有数据的前面 self.models = statuse! + self.models! //显示刷新状态 self.showRefreshPromptContent(count: self.models?.count ?? 0) } else if self.max_id > 0 { // 如果是上拉刷新, 就将获取到的数据, 拼接在原有数据的后面 self.models = self.models! + statuse! } else { self.models = statuse } } } } ///显示刷新状态 private func showRefreshPromptContent(count:Int) { self.promptLabel.isHidden = false self.promptLabel.text = count == 0 ? "没有刷新到新微薄" : "刷新了\(count)条微博" UIView.animate(withDuration: 1.5, animations: { self.promptLabel.transform = CGAffineTransform.init(translationX: 0, y: 21) }) { (_) in UIView.animate(withDuration:2.5, animations: { self.promptLabel.transform = CGAffineTransform.identity }, completion: { (_) in self.promptLabel.isHidden = true }) } } ///更改标题栏上的按钮的状态 func changeTitleBtnState() { let titleBtn = navigationItem.titleView as! TitleButton titleBtn.isSelected = !titleBtn.isSelected } ///设置导航栏按钮 private func setupNavBarButton() { navigationItem.leftBarButtonItem = UIBarButtonItem.createNavBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: #selector(leftBtnClick)) //快捷键 command + control + e 多行操作 navigationItem.rightBarButtonItem = UIBarButtonItem.createNavBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(rightBtnClick)) //设置导航栏上的标题按钮 let titleBtn = TitleButton() titleBtn.setTitle("极客江南 ", for: UIControlState.normal) titleBtn.addTarget(self, action: #selector(titleBtnClick), for: UIControlEvents.touchUpInside) navigationItem.titleView = titleBtn } ///当控制器销毁时,移除通知 deinit { NotificationCenter.default.removeObserver(self) } //MARK:- 懒加载 负责转场动画的对象 ///一定要定义一个属性来保存自定义转场动画的对象,否则会报错 private lazy var popoverAnimator:PopoverAnimator = { let popoverView = PopoverAnimator() //设置下拉菜单的尺寸 popoverView.presentedFrame = CGRect(x: 100, y: 50, width: 200, height: 300) return popoverView }() ///当刷新微博时用来提示用户刷新的状态 private lazy var promptLabel:UILabel = { let label = UILabel() label.backgroundColor = UIColor.orange label.textAlignment = NSTextAlignment.center label.font = UIFont.systemFont(ofSize: 13) label.textColor = UIColor.white label.frame = CGRect.init(x: 0, y: 23, width: Int(width), height: 21) label.isHidden = true self.navigationController?.navigationBar.insertSubview(label, at: 0) return label }() //MARK:- 按钮点击响应事件 ///标题菜单按钮 func titleBtnClick(btn:TitleButton) { //从 storyboard 中加载控制器 let sb = UIStoryboard.init(name: "PopoverViewController", bundle: nil) let vc = sb.instantiateInitialViewController() //设置转场代理,告诉系统谁来负责转场 //popoverAnimator:来负责转场动画的实现 vc?.transitioningDelegate = popoverAnimator //设置转场模式 vc?.modalPresentationStyle = UIModalPresentationStyle.custom present(vc!, animated: true, completion: nil) } ///注册按钮 func registerBtnClick(){ print(#function) } ///登录按钮 func loginBtnClick(){ print(#function) } ///导航栏上的左侧按钮 func leftBtnClick () { print(#function) } ///导航栏上的右侧按钮 func rightBtnClick () { let sb = UIStoryboard(name: "QRCodeViewController", bundle: nil) let vc = sb.instantiateInitialViewController() present(vc!, animated: true, completion: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return models?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let statues = models![indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: HomeTableViewCellType.cellIdentifier(statuse: statues)) as! HomeTableViewCell let count = models?.count ?? 0 if indexPath.row == (count - 1) { pullRefreshFlag = true loadData() } cell.statuse = statues return cell } //MARK:- Table view delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { //取出模型 let statuse = models![indexPath.row] //如果该条微博的行高以缓存,则直接取出使用,否则重新计算 if let height = cellHeight[statuse.id] { return height } //取出 cell let cell = tableView.dequeueReusableCell(withIdentifier: HomeTableViewCellType.cellIdentifier(statuse: statuse)) as! HomeTableViewCell let rowHeight = cell.caculateCellHeight(statuse: statuse) //缓存 cell 的行高 cellHeight[statuse.id] = rowHeight //返回 cell 的高度 return rowHeight } //MARK:- Table view daata source prefetching func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { //print(indexPaths) } }
34.70566
184
0.623355
dbcc775918d0341a4e21bfa2d0a2826723b15194
5,791
php
PHP
resources/views/administracion/pedidos/index.blade.php
beetlejuice96/UNLu-sip-2020
2a0d828441e7d6bfa786c7d9ff1d7eeb43fc836f
[ "MIT" ]
1
2020-04-03T16:55:57.000Z
2020-04-03T16:55:57.000Z
resources/views/administracion/pedidos/index.blade.php
beetlejuice96/UNLu-sip-2020
2a0d828441e7d6bfa786c7d9ff1d7eeb43fc836f
[ "MIT" ]
4
2021-02-02T17:41:06.000Z
2022-02-27T02:24:38.000Z
resources/views/administracion/pedidos/index.blade.php
beetlejuice96/UNLu-sip-2020
2a0d828441e7d6bfa786c7d9ff1d7eeb43fc836f
[ "MIT" ]
2
2020-04-04T12:57:39.000Z
2020-06-27T04:24:28.000Z
@extends('layouts.app') <script src="https://cdn.jsdelivr.net/npm/sweetalert2@9"></script> <script src="{{ asset('js/notifCartel.js') }}"></script> <script src="{{ asset('js/errorCartel.js') }}"></script> <script src="{{ asset('js/validarFiltros.js') }}"></script> @section('content') <section class="container"> <section> <div class="bs-example"> <nav> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="/">Home</a></li> <li class="breadcrumb-item"><a href="{{route('administracion.menu')}}">Administración</a></li> <li class="breadcrumb-item active">Gestión de Pedidos</li> </ol> </nav> </div> <div class="row justify-content-center mt-4"> <a class="btn btn-primary btn m-1 col-3" href="{{route('pedidos.create')}}">Nuevo Pedido</a> </div> <div class="row mt-4 border-top border-bottom py-3"> <form class="form-inline w-100"> <div class="col-2"> <a type="submit" class="btn btn-info btn-sm m-1 btn_pdf" href="{{route('pedido.pdf')}}" target="_blank">Descargar PDF</a> </div> <div class="col-8 text-center"> <input name="producto" class="form-control productojs" type="search" placeholder="Producto" aria-label="buscar por producto" value="{{$producto}}"> <input name="cliente" class="form-control clientejs" type="search" placeholder="Cliente" aria-label="buscar por cliente" value="{{$cliente}}"> <button class="btn btn-outline-success " type="submit">Buscar</button> </div> <a class="" href="{{route('pedidos.index')}}">Borrar búsqueda</a> </form> </div> </section> <section> <table class="table mt-5"> @if ($errors->any()) <div class="alert alert-danger"> {{$errors->first()}} <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> @endif @if (session('error')) <div class=""> <p class="errorjs" style="display:none">{{ session('error') }}</p> </div> @endif @if (session('message')) <div class="" role="alert"> <p class="alertajs" style="display:none">{{ session('message') }}</p> </div> @endif <thead> <tr> <th scope="col">#</th> <th scope="col">Cliente</th> <th scope="col">Fecha Entrega</th> <th scope="col">Producto</th> <th scope="col" class="">Cant. (kgs)</th> <th scope="col">Acciones</th> </tr> </thead> <tbody> @foreach ($ops as $op) <tr> <th scope="row">{{$op->op_id}}</th> <td>{{$op->empresa}}</td> <td>{{date('d-m-Y', strtotime($op->fecha_fabricacion))}}</td> <td id="producto">{{$op->producto}}</td> <td id="cantidad">{{$op->cantidad}}</td> @if ($op->descripcion == "Pendiente") <td> <form method="get" id="destroy-appointment" action="{{route('pedidos.cancel', $op->op_id)}}" onSubmit="return confirm('Desea eliminar?');"> <a class="btn btn-success btn-sm" href="{{route('pedidos.finalize', $op->op_id)}}">Finalizar</a> <a class="btn btn-warning btn-sm" href="{{route('pedidos.show', $op->op_id)}}">Ver</a> <button class="btn btn-danger btn-sm" type="submit" form="destroy-appointment">X </button> </form> </td> @else @if ($op->descripcion == "Finalizada") <td> {{--<span class="btn btn-sm btn-outline-success disabled">Finalizado</span>--}} <a href="{{ route('op.pdf', $op->op_id )}}" target="_blank" class="btn btn-outline-success btn-sm">Imprimir</a> </td> @else <td> <span class="btn btn-sm btn-outline-danger disabled">Anulado</span> </td> @endif @endif </tr> @endforeach </tbody> </table> <div class="row justify-content-center mt-5"> {{-- {{$ops->links()}}--}} </div> </section> <a class="btn btn-secondary btn-sm" href="{{route('administracion.menu')}}">Volver</a> </section> @endsection
47.467213
132
0.399413
a52d080be20e601060ddad027f07dd54ecd1aae1
51,329
asm
Assembly
examples/native/dots.asm
jamieleecho/mcbasic
b4c938497487109d2448894ce3fff8476c3e2f4e
[ "MIT" ]
null
null
null
examples/native/dots.asm
jamieleecho/mcbasic
b4c938497487109d2448894ce3fff8476c3e2f4e
[ "MIT" ]
null
null
null
examples/native/dots.asm
jamieleecho/mcbasic
b4c938497487109d2448894ce3fff8476c3e2f4e
[ "MIT" ]
null
null
null
; Assembly for dots.bas ; compiled with mcbasic -native ; Equates for MC-10 MICROCOLOR BASIC 1.0 ; ; Direct page equates DP_LNUM .equ $E2 ; current line in BASIC DP_TABW .equ $E4 ; current tab width on console DP_LPOS .equ $E6 ; current line position on console DP_LWID .equ $E7 ; current line width of console ; ; Memory equates M_PMSK .equ $423C ; pixel mask for SET, RESET and POINT M_IKEY .equ $427F ; key code for INKEY$ M_CRSR .equ $4280 ; cursor location M_LBUF .equ $42B2 ; line input buffer (130 chars) M_MSTR .equ $4334 ; buffer for small string moves M_CODE .equ $4346 ; start of program space ; ; ROM equates R_BKMSG .equ $E1C1 ; 'BREAK' string location R_ERROR .equ $E238 ; generate error and restore direct mode R_BREAK .equ $E266 ; generate break and restore direct mode R_RESET .equ $E3EE ; setup stack and disable CONT R_SPACE .equ $E7B9 ; emit " " to console R_QUEST .equ $E7BC ; emit "?" to console R_REDO .equ $E7C1 ; emit "?REDO" to console R_EXTRA .equ $E8AB ; emit "?EXTRA IGNORED" to console R_DMODE .equ $F7AA ; display OK prompt and restore direct mode R_KPOLL .equ $F879 ; if key is down, do KEYIN, else set Z CCR flag R_KEYIN .equ $F883 ; poll key for key-down transition set Z otherwise R_PUTC .equ $F9C9 ; write ACCA to console R_MKTAB .equ $FA7B ; setup tabs for console R_GETLN .equ $FAA4 ; get line, returning with X pointing to M_BUF-1 R_SETPX .equ $FB44 ; write pixel character to X R_CLRPX .equ $FB59 ; clear pixel character in X R_MSKPX .equ $FB7C ; get pixel screen location X and mask in R_PMSK R_CLSN .equ $FBC4 ; clear screen with color code in ACCB R_CLS .equ $FBD4 ; clear screen with space character R_SOUND .equ $FFAB ; play sound with pitch in ACCA and duration in ACCB R_MCXID .equ $FFDA ; ID location for MCX BASIC ; direct page registers .org $80 strbuf .block 2 strend .block 2 strfree .block 2 strstop .block 2 dataptr .block 2 inptptr .block 2 redoptr .block 2 letptr .block 2 .org $a3 r1 .block 5 r2 .block 5 r3 .block 5 rend rvseed .block 2 tmp1 .block 2 tmp2 .block 2 tmp3 .block 2 tmp4 .block 2 tmp5 .block 2 argv .block 10 ; main program .org M_CODE jsr progbegin jsr clear LINE_0 ; GOTO 100 ldx #LINE_100 jsr goto_ix LINE_16 ; C1=(PEEK(LC+32)<>96)+(PEEK(LC+1)<>96)+(PEEK(LC-32)<>96)+(PEEK(LC-1)<>96) ldx #INTVAR_LC jsr ld_ir1_ix ldab #32 jsr add_ir1_ir1_pb jsr peek_ir1_ir1 ldab #96 jsr ldne_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ir2_ix ldab #1 jsr add_ir2_ir2_pb jsr peek_ir2_ir2 ldab #96 jsr ldne_ir2_ir2_pb jsr add_ir1_ir1_ir2 ldx #INTVAR_LC jsr ld_ir2_ix ldab #32 jsr sub_ir2_ir2_pb jsr peek_ir2_ir2 ldab #96 jsr ldne_ir2_ir2_pb jsr add_ir1_ir1_ir2 ldx #INTVAR_LC jsr ld_ir2_ix ldab #1 jsr sub_ir2_ir2_pb jsr peek_ir2_ir2 ldab #96 jsr ldne_ir2_ir2_pb jsr add_ir1_ir1_ir2 ldx #INTVAR_C1 jsr ld_ix_ir1 ; RETURN jsr return ; REM FNBX(LC) LINE_17 ; C1=LC<>(INT(LC/2)*2) ldx #INTVAR_LC jsr ld_ir1_ix ldx #INTVAR_LC jsr ld_ir2_ix ldab #2 jsr div_fr2_ir2_pb ldab #2 jsr mul_ir2_ir2_pb jsr ldne_ir1_ir1_ir2 ldx #INTVAR_C1 jsr ld_ix_ir1 ; RETURN jsr return ; REM FNVH(LC) LINE_100 ; CLS 7 ldab #7 jsr clsn_pb ; PRINT @236, "d o t s"; ldab #236 jsr prat_pb jsr pr_ss .text 7, "d o t s" LINE_110 ; PRINT @357, "SKILL LEVEL (0-10)"; ldd #357 jsr prat_pw jsr pr_ss .text 18, "SKILL LEVEL (0-10)" ; INPUT SK jsr input ldx #FLTVAR_SK jsr readbuf_fx jsr ignxtra ; IF (SK<0) OR (SK>10) THEN ldx #FLTVAR_SK jsr ld_fr1_fx ldab #0 jsr ldlt_ir1_fr1_pb ldab #10 jsr ld_ir2_pb ldx #FLTVAR_SK jsr ldlt_ir2_ir2_fx jsr or_ir1_ir1_ir2 ldx #LINE_110 jsr jmpne_ir1_ix LINE_120 ; CLS jsr cls ; SK=(10-SK)/10 ldab #10 jsr ld_ir1_pb ldx #FLTVAR_SK jsr sub_fr1_ir1_fx ldab #10 jsr div_fr1_fr1_pb ldx #FLTVAR_SK jsr ld_fx_fr1 ; TS=200-(200*SK) ldab #200 jsr ld_ir1_pb ldab #200 jsr ld_ir2_pb ldx #FLTVAR_SK jsr mul_fr2_ir2_fx jsr sub_fr1_ir1_fr2 ldx #FLTVAR_TS jsr ld_fx_fr1 ; DT=TS+25 ldx #FLTVAR_TS jsr ld_fr1_fx ldab #25 jsr add_fr1_fr1_pb ldx #FLTVAR_DT jsr ld_fx_fr1 ; SC=16384 ldx #INTVAR_SC ldd #16384 jsr ld_ix_pw LINE_130 ; PRINT jsr pr_ss .text 1, "\r" ; FOR I=1 TO 7 ldx #INTVAR_I ldab #1 jsr for_ix_pb ldab #7 jsr to_ip_pb ; PRINT " O O O O O O O O O O" jsr pr_ss .text 21, " O O O O O O O O O O\r" ; PRINT jsr pr_ss .text 1, "\r" ; NEXT I ldx #INTVAR_I jsr nextvar_ix jsr next LINE_140 ; YS=0 ldx #INTVAR_YS ldab #0 jsr ld_ix_pb ; CS=0 ldx #INTVAR_CS ldab #0 jsr ld_ix_pb ; PRINT @87, "YOU:" ldab #87 jsr prat_pb jsr pr_ss .text 5, "YOU:\r" ; PRINT @278, "COMPUTER:" ldd #278 jsr prat_pw jsr pr_ss .text 10, "COMPUTER:\r" LINE_150 ; PRINT @152, STR$(YS);" " ldab #152 jsr prat_pb ldx #INTVAR_YS jsr str_sr1_ix jsr pr_sr1 jsr pr_ss .text 2, " \r" ; PRINT @344, STR$(CS);" " ldd #344 jsr prat_pw ldx #INTVAR_CS jsr str_sr1_ix jsr pr_sr1 jsr pr_ss .text 2, " \r" LINE_180 ; SL=SC+202 ldx #INTVAR_SC jsr ld_ir1_ix ldab #202 jsr add_ir1_ir1_pb ldx #INTVAR_SL jsr ld_ix_ir1 ; X=10 ldx #INTVAR_X ldab #10 jsr ld_ix_pb ; Y=7 ldx #INTVAR_Y ldab #7 jsr ld_ix_pb ; CC=PEEK(SL) ldx #INTVAR_SL jsr peek_ir1_ix ldx #INTVAR_CC jsr ld_ix_ir1 LINE_190 ; POKE SL,159 ldx #INTVAR_SL ldab #159 jsr poke_ix_pb ; F=0 ldx #INTVAR_F ldab #0 jsr ld_ix_pb LINE_200 ; GOSUB 910 ldx #LINE_910 jsr gosub_ix LINE_210 ; X+=J ldx #INTVAR_J jsr ld_ir1_ix ldx #INTVAR_X jsr add_ix_ix_ir1 ; Y+=K ldx #INTVAR_K jsr ld_ir1_ix ldx #INTVAR_Y jsr add_ix_ix_ir1 ; IF (X<1) OR (X>19) OR (Y<2) OR (Y>14) THEN ldx #INTVAR_X jsr ld_ir1_ix ldab #1 jsr ldlt_ir1_ir1_pb ldab #19 jsr ld_ir2_pb ldx #INTVAR_X jsr ldlt_ir2_ir2_ix jsr or_ir1_ir1_ir2 ldx #INTVAR_Y jsr ld_ir2_ix ldab #2 jsr ldlt_ir2_ir2_pb jsr or_ir1_ir1_ir2 ldab #14 jsr ld_ir2_pb ldx #INTVAR_Y jsr ldlt_ir2_ir2_ix jsr or_ir1_ir1_ir2 ldx #LINE_220 jsr jmpeq_ir1_ix ; X-=J ldx #INTVAR_J jsr ld_ir1_ix ldx #INTVAR_X jsr sub_ix_ix_ir1 ; Y-=K ldx #INTVAR_K jsr ld_ir1_ix ldx #INTVAR_Y jsr sub_ix_ix_ir1 ; GOTO 200 ldx #LINE_200 jsr goto_ix LINE_220 ; IF PC=99 THEN ldx #INTVAR_PC jsr ld_ir1_ix ldab #99 jsr ldeq_ir1_ir1_pb ldx #LINE_250 jsr jmpne_ir1_ix LINE_230 ; POKE SL,CC ldx #INTVAR_CC jsr ld_ir1_ix ldx #INTVAR_SL jsr poke_ix_ir1 ; SL+=PC ldx #INTVAR_PC jsr ld_ir1_ix ldx #INTVAR_SL jsr add_ix_ix_ir1 ; CC=PEEK(SL) ldx #INTVAR_SL jsr peek_ir1_ix ldx #INTVAR_CC jsr ld_ix_ir1 ; POKE SL,159 ldx #INTVAR_SL ldab #159 jsr poke_ix_pb LINE_240 ; GOTO 200 ldx #LINE_200 jsr goto_ix LINE_250 ; L=(PEEK(SL+1)=79)+(PEEK(SL-1)=79)+(PEEK(SL+32)=79)+(PEEK(SL-32)=79) ldx #INTVAR_SL jsr ld_ir1_ix ldab #1 jsr add_ir1_ir1_pb jsr peek_ir1_ir1 ldab #79 jsr ldeq_ir1_ir1_pb ldx #INTVAR_SL jsr ld_ir2_ix ldab #1 jsr sub_ir2_ir2_pb jsr peek_ir2_ir2 ldab #79 jsr ldeq_ir2_ir2_pb jsr add_ir1_ir1_ir2 ldx #INTVAR_SL jsr ld_ir2_ix ldab #32 jsr add_ir2_ir2_pb jsr peek_ir2_ir2 ldab #79 jsr ldeq_ir2_ir2_pb jsr add_ir1_ir1_ir2 ldx #INTVAR_SL jsr ld_ir2_ix ldab #32 jsr sub_ir2_ir2_pb jsr peek_ir2_ir2 ldab #79 jsr ldeq_ir2_ir2_pb jsr add_ir1_ir1_ir2 ldx #INTVAR_L jsr ld_ix_ir1 LINE_260 ; IF ((CC=96)+L)=-3 THEN ldx #INTVAR_CC jsr ld_ir1_ix ldab #96 jsr ldeq_ir1_ir1_pb ldx #INTVAR_L jsr add_ir1_ir1_ix ldab #-3 jsr ldeq_ir1_ir1_nb ldx #LINE_280 jsr jmpne_ir1_ix LINE_270 ; I=62 ldx #INTVAR_I ldab #62 jsr ld_ix_pb ; GOSUB 760 ldx #LINE_760 jsr gosub_ix ; GOTO 200 ldx #LINE_200 jsr goto_ix LINE_280 ; WH=1 ldx #INTVAR_WH ldab #1 jsr ld_ix_pb ; ML=SL ldx #INTVAR_SL jsr ld_ir1_ix ldx #INTVAR_ML jsr ld_ix_ir1 ; GOSUB 700 ldx #LINE_700 jsr gosub_ix ; LC=SL ldx #INTVAR_SL jsr ld_ir1_ix ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 17 ldx #LINE_17 jsr gosub_ix ; IF NOT C1 THEN ldx #INTVAR_C1 jsr com_ir1_ix ldx #LINE_330 jsr jmpne_ir1_ix LINE_290 ; LC=SL-1 ldx #INTVAR_SL jsr ld_ir1_ix ldab #1 jsr sub_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF (X>1) AND (C1=-4) THEN ldab #1 jsr ld_ir1_pb ldx #INTVAR_X jsr ldlt_ir1_ir1_ix ldx #INTVAR_C1 jsr ld_ir2_ix ldab #-4 jsr ldeq_ir2_ir2_nb jsr and_ir1_ir1_ir2 ldx #LINE_300 jsr jmpeq_ir1_ix ; BX=SL-1 ldx #INTVAR_SL jsr ld_ir1_ix ldab #1 jsr sub_ir1_ir1_pb ldx #INTVAR_BX jsr ld_ix_ir1 ; GOSUB 770 ldx #LINE_770 jsr gosub_ix ; F=-1 ldx #INTVAR_F ldab #-1 jsr ld_ix_nb LINE_300 ; LC=SL+1 ldx #INTVAR_SL jsr ld_ir1_ix ldab #1 jsr add_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF (X<19) AND (C1=-4) THEN ldx #INTVAR_X jsr ld_ir1_ix ldab #19 jsr ldlt_ir1_ir1_pb ldx #INTVAR_C1 jsr ld_ir2_ix ldab #-4 jsr ldeq_ir2_ir2_nb jsr and_ir1_ir1_ir2 ldx #LINE_310 jsr jmpeq_ir1_ix ; BX=SL+1 ldx #INTVAR_SL jsr ld_ir1_ix ldab #1 jsr add_ir1_ir1_pb ldx #INTVAR_BX jsr ld_ix_ir1 ; GOSUB 770 ldx #LINE_770 jsr gosub_ix ; GOTO 180 ldx #LINE_180 jsr goto_ix LINE_310 ; IF F THEN ldx #INTVAR_F jsr ld_ir1_ix ldx #LINE_180 jsr jmpne_ir1_ix LINE_320 ; GOTO 360 ldx #LINE_360 jsr goto_ix LINE_330 ; LC=SL-32 ldx #INTVAR_SL jsr ld_ir1_ix ldab #32 jsr sub_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF (Y>1) AND (C1=-4) THEN ldab #1 jsr ld_ir1_pb ldx #INTVAR_Y jsr ldlt_ir1_ir1_ix ldx #INTVAR_C1 jsr ld_ir2_ix ldab #-4 jsr ldeq_ir2_ir2_nb jsr and_ir1_ir1_ir2 ldx #LINE_340 jsr jmpeq_ir1_ix ; BX=SL-32 ldx #INTVAR_SL jsr ld_ir1_ix ldab #32 jsr sub_ir1_ir1_pb ldx #INTVAR_BX jsr ld_ix_ir1 ; GOSUB 770 ldx #LINE_770 jsr gosub_ix ; F=-1 ldx #INTVAR_F ldab #-1 jsr ld_ix_nb LINE_340 ; LC=SL+32 ldx #INTVAR_SL jsr ld_ir1_ix ldab #32 jsr add_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF (Y<13) AND (C1=-4) THEN ldx #INTVAR_Y jsr ld_ir1_ix ldab #13 jsr ldlt_ir1_ir1_pb ldx #INTVAR_C1 jsr ld_ir2_ix ldab #-4 jsr ldeq_ir2_ir2_nb jsr and_ir1_ir1_ir2 ldx #LINE_350 jsr jmpeq_ir1_ix ; BX=SL+32 ldx #INTVAR_SL jsr ld_ir1_ix ldab #32 jsr add_ir1_ir1_pb ldx #INTVAR_BX jsr ld_ix_ir1 ; GOSUB 770 ldx #LINE_770 jsr gosub_ix ; GOTO 180 ldx #LINE_180 jsr goto_ix LINE_350 ; IF F THEN ldx #INTVAR_F jsr ld_ir1_ix ldx #LINE_180 jsr jmpne_ir1_ix LINE_360 ; WH=2 ldx #INTVAR_WH ldab #2 jsr ld_ix_pb ; F=0 ldx #INTVAR_F ldab #0 jsr ld_ix_pb ; CN=0 ldx #INTVAR_CN ldab #0 jsr ld_ix_pb ; IF RND(0)<SK THEN ldab #0 jsr rnd_fr1_pb ldx #FLTVAR_SK jsr ldlt_ir1_fr1_fx ldx #LINE_440 jsr jmpne_ir1_ix LINE_370 ; FOR I=64 TO 384 STEP 64 ldx #INTVAR_I ldab #64 jsr for_ix_pb ldd #384 jsr to_ip_pw ldab #64 jsr ld_ir1_pb jsr step_ip_ir1 ; FOR J=2 TO 12 STEP 2 ldx #INTVAR_J ldab #2 jsr for_ix_pb ldab #12 jsr to_ip_pb ldab #2 jsr ld_ir1_pb jsr step_ip_ir1 ; K=SC+I+J ldx #INTVAR_SC jsr ld_ir1_ix ldx #INTVAR_I jsr add_ir1_ir1_ix ldx #INTVAR_J jsr add_ir1_ir1_ix ldx #INTVAR_K jsr ld_ix_ir1 LINE_380 ; LC=K ldx #INTVAR_K jsr ld_ir1_ix ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF (PEEK(K)=96) AND (C1=-3) THEN ldx #INTVAR_K jsr peek_ir1_ix ldab #96 jsr ldeq_ir1_ir1_pb ldx #INTVAR_C1 jsr ld_ir2_ix ldab #-3 jsr ldeq_ir2_ir2_nb jsr and_ir1_ir1_ir2 ldx #LINE_400 jsr jmpne_ir1_ix LINE_390 ; NEXT J,I ldx #INTVAR_J jsr nextvar_ix jsr next ldx #INTVAR_I jsr nextvar_ix jsr next ; GOTO 440 ldx #LINE_440 jsr goto_ix LINE_400 ; I=K ldx #INTVAR_K jsr ld_ir1_ix ldx #INTVAR_I jsr ld_ix_ir1 ; IF PEEK(I-32)=96 THEN ldx #INTVAR_I jsr ld_ir1_ix ldab #32 jsr sub_ir1_ir1_pb jsr peek_ir1_ir1 ldab #96 jsr ldeq_ir1_ir1_pb ldx #LINE_410 jsr jmpeq_ir1_ix ; I-=32 ldx #INTVAR_I ldab #32 jsr sub_ix_ix_pb ; GOTO 590 ldx #LINE_590 jsr goto_ix LINE_410 ; IF PEEK(I+32)=96 THEN ldx #INTVAR_I jsr ld_ir1_ix ldab #32 jsr add_ir1_ir1_pb jsr peek_ir1_ir1 ldab #96 jsr ldeq_ir1_ir1_pb ldx #LINE_420 jsr jmpeq_ir1_ix ; I+=32 ldx #INTVAR_I ldab #32 jsr add_ix_ix_pb ; GOTO 590 ldx #LINE_590 jsr goto_ix LINE_420 ; IF PEEK(I-1)<>96 THEN ldx #INTVAR_I jsr ld_ir1_ix ldab #1 jsr sub_ir1_ir1_pb jsr peek_ir1_ir1 ldab #96 jsr ldne_ir1_ir1_pb ldx #LINE_430 jsr jmpeq_ir1_ix ; I+=1 ldx #INTVAR_I ldab #1 jsr add_ix_ix_pb ; GOTO 650 ldx #LINE_650 jsr goto_ix LINE_430 ; IF PEEK(I+1)<>96 THEN ldx #INTVAR_I jsr ld_ir1_ix ldab #1 jsr add_ir1_ir1_pb jsr peek_ir1_ir1 ldab #96 jsr ldne_ir1_ir1_pb ldx #LINE_440 jsr jmpeq_ir1_ix ; I-=1 ldx #INTVAR_I ldab #1 jsr sub_ix_ix_pb ; GOTO 650 ldx #LINE_650 jsr goto_ix LINE_440 ; I=RND(19)+(RND(13)*32)+33+SC ldab #19 jsr irnd_ir1_pb ldab #13 jsr irnd_ir2_pb ldab #32 jsr mul_ir2_ir2_pb jsr add_ir1_ir1_ir2 ldab #33 jsr add_ir1_ir1_pb ldx #INTVAR_SC jsr add_ir1_ir1_ix ldx #INTVAR_I jsr ld_ix_ir1 ; CN+=1 ldx #INTVAR_CN ldab #1 jsr add_ix_ix_pb ; IF PEEK(I)<>96 THEN ldx #INTVAR_I jsr peek_ir1_ix ldab #96 jsr ldne_ir1_ir1_pb ldx #LINE_440 jsr jmpne_ir1_ix LINE_450 ; IF NOT (((PEEK(I+1)=79) AND (PEEK(I-1)=79)) OR ((PEEK(I+32)=79) AND (PEEK(I-32)=79))) THEN ldx #INTVAR_I jsr ld_ir1_ix ldab #1 jsr add_ir1_ir1_pb jsr peek_ir1_ir1 ldab #79 jsr ldeq_ir1_ir1_pb ldx #INTVAR_I jsr ld_ir2_ix ldab #1 jsr sub_ir2_ir2_pb jsr peek_ir2_ir2 ldab #79 jsr ldeq_ir2_ir2_pb jsr and_ir1_ir1_ir2 ldx #INTVAR_I jsr ld_ir2_ix ldab #32 jsr add_ir2_ir2_pb jsr peek_ir2_ir2 ldab #79 jsr ldeq_ir2_ir2_pb ldx #INTVAR_I jsr ld_ir3_ix ldab #32 jsr sub_ir3_ir3_pb jsr peek_ir3_ir3 ldab #79 jsr ldeq_ir3_ir3_pb jsr and_ir2_ir2_ir3 jsr or_ir1_ir1_ir2 jsr com_ir1_ir1 ldx #LINE_440 jsr jmpne_ir1_ix LINE_460 ; IF (SK>0.6) OR (CN>TS) THEN ldx #FLT_0p60000 jsr ld_fr1_fx ldx #FLTVAR_SK jsr ldlt_ir1_fr1_fx ldx #FLTVAR_TS jsr ld_fr2_fx ldx #INTVAR_CN jsr ldlt_ir2_fr2_ix jsr or_ir1_ir1_ir2 ldx #LINE_520 jsr jmpne_ir1_ix LINE_470 ; LC=I ldx #INTVAR_I jsr ld_ir1_ix ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 17 ldx #LINE_17 jsr gosub_ix ; IF C1 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldx #LINE_500 jsr jmpne_ir1_ix LINE_480 ; LC=I-32 ldx #INTVAR_I jsr ld_ir1_ix ldab #32 jsr sub_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF C1=-2 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-2 jsr ldeq_ir1_ir1_nb ldx #LINE_440 jsr jmpne_ir1_ix LINE_481 ; LC=I+32 ldx #INTVAR_I jsr ld_ir1_ix ldab #32 jsr add_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF C1=-2 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-2 jsr ldeq_ir1_ir1_nb ldx #LINE_440 jsr jmpne_ir1_ix LINE_490 ; GOTO 590 ldx #LINE_590 jsr goto_ix LINE_500 ; LC=I-1 ldx #INTVAR_I jsr ld_ir1_ix ldab #1 jsr sub_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF C1=-2 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-2 jsr ldeq_ir1_ir1_nb ldx #LINE_440 jsr jmpne_ir1_ix LINE_501 ; LC=I+1 ldx #INTVAR_I jsr ld_ir1_ix ldab #1 jsr add_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF C1=-2 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-2 jsr ldeq_ir1_ir1_nb ldx #LINE_440 jsr jmpne_ir1_ix LINE_510 ; GOTO 650 ldx #LINE_650 jsr goto_ix LINE_520 ; LC=I ldx #INTVAR_I jsr ld_ir1_ix ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 17 ldx #LINE_17 jsr gosub_ix ; IF C1 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldx #LINE_560 jsr jmpne_ir1_ix LINE_530 ; IF (SK>0.6) OR (CN>DT) THEN ldx #FLT_0p60000 jsr ld_fr1_fx ldx #FLTVAR_SK jsr ldlt_ir1_fr1_fx ldx #FLTVAR_DT jsr ld_fr2_fx ldx #INTVAR_CN jsr ldlt_ir2_fr2_ix jsr or_ir1_ir1_ir2 ldx #LINE_590 jsr jmpne_ir1_ix LINE_540 ; LC=I+32 ldx #INTVAR_I jsr ld_ir1_ix ldab #32 jsr add_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF C1=-2 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-2 jsr ldeq_ir1_ir1_nb ldx #LINE_550 jsr jmpeq_ir1_ix ; LC=I-32 ldx #INTVAR_I jsr ld_ir1_ix ldab #32 jsr sub_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; IF C1=-2 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-2 jsr ldeq_ir1_ir1_nb ldx #LINE_440 jsr jmpne_ir1_ix LINE_550 ; GOTO 590 ldx #LINE_590 jsr goto_ix LINE_560 ; IF (SK>0.6) OR (CN>DT) THEN ldx #FLT_0p60000 jsr ld_fr1_fx ldx #FLTVAR_SK jsr ldlt_ir1_fr1_fx ldx #FLTVAR_DT jsr ld_fr2_fx ldx #INTVAR_CN jsr ldlt_ir2_fr2_ix jsr or_ir1_ir1_ir2 ldx #LINE_650 jsr jmpne_ir1_ix LINE_570 ; LC=I+1 ldx #INTVAR_I jsr ld_ir1_ix ldab #1 jsr add_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF C1=-2 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-2 jsr ldeq_ir1_ir1_nb ldx #LINE_580 jsr jmpeq_ir1_ix ; LC=I-1 ldx #INTVAR_I jsr ld_ir1_ix ldab #1 jsr sub_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; IF C1=-2 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-2 jsr ldeq_ir1_ir1_nb ldx #LINE_440 jsr jmpne_ir1_ix LINE_580 ; GOTO 650 ldx #LINE_650 jsr goto_ix LINE_590 ; ML=I ldx #INTVAR_I jsr ld_ir1_ix ldx #INTVAR_ML jsr ld_ix_ir1 ; GOSUB 700 ldx #LINE_700 jsr gosub_ix LINE_600 ; LC=ML-32 ldx #INTVAR_ML jsr ld_ir1_ix ldab #32 jsr sub_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF C1=-4 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-4 jsr ldeq_ir1_ir1_nb ldx #LINE_610 jsr jmpeq_ir1_ix ; BX=ML-32 ldx #INTVAR_ML jsr ld_ir1_ix ldab #32 jsr sub_ir1_ir1_pb ldx #INTVAR_BX jsr ld_ix_ir1 ; GOSUB 770 ldx #LINE_770 jsr gosub_ix ; F=-1 ldx #INTVAR_F ldab #-1 jsr ld_ix_nb LINE_610 ; LC=ML+32 ldx #INTVAR_ML jsr ld_ir1_ix ldab #32 jsr add_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF C1=-4 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-4 jsr ldeq_ir1_ir1_nb ldx #LINE_620 jsr jmpeq_ir1_ix ; BX=ML+32 ldx #INTVAR_ML jsr ld_ir1_ix ldab #32 jsr add_ir1_ir1_pb ldx #INTVAR_BX jsr ld_ix_ir1 ; GOSUB 770 ldx #LINE_770 jsr gosub_ix ; GOTO 360 ldx #LINE_360 jsr goto_ix LINE_620 ; IF F THEN ldx #INTVAR_F jsr ld_ir1_ix ldx #LINE_360 jsr jmpne_ir1_ix LINE_630 ; GOTO 180 ldx #LINE_180 jsr goto_ix LINE_640 ; IF NOT ((PEEK(I-32)=79) AND (PEEK(I+32)=79)) THEN ldx #INTVAR_I jsr ld_ir1_ix ldab #32 jsr sub_ir1_ir1_pb jsr peek_ir1_ir1 ldab #79 jsr ldeq_ir1_ir1_pb ldx #INTVAR_I jsr ld_ir2_ix ldab #32 jsr add_ir2_ir2_pb jsr peek_ir2_ir2 ldab #79 jsr ldeq_ir2_ir2_pb jsr and_ir1_ir1_ir2 jsr com_ir1_ir1 ldx #LINE_440 jsr jmpne_ir1_ix LINE_650 ; ML=I ldx #INTVAR_I jsr ld_ir1_ix ldx #INTVAR_ML jsr ld_ix_ir1 ; GOSUB 700 ldx #LINE_700 jsr gosub_ix LINE_660 ; LC=ML-1 ldx #INTVAR_ML jsr ld_ir1_ix ldab #1 jsr sub_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF C1=-4 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-4 jsr ldeq_ir1_ir1_nb ldx #LINE_670 jsr jmpeq_ir1_ix ; BX=ML-1 ldx #INTVAR_ML jsr ld_ir1_ix ldab #1 jsr sub_ir1_ir1_pb ldx #INTVAR_BX jsr ld_ix_ir1 ; GOSUB 770 ldx #LINE_770 jsr gosub_ix ; F=-1 ldx #INTVAR_F ldab #-1 jsr ld_ix_nb LINE_670 ; LC=ML+1 ldx #INTVAR_ML jsr ld_ir1_ix ldab #1 jsr add_ir1_ir1_pb ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 16 ldx #LINE_16 jsr gosub_ix ; IF C1=-4 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldab #-4 jsr ldeq_ir1_ir1_nb ldx #LINE_680 jsr jmpeq_ir1_ix ; BX=ML+1 ldx #INTVAR_ML jsr ld_ir1_ix ldab #1 jsr add_ir1_ir1_pb ldx #INTVAR_BX jsr ld_ix_ir1 ; GOSUB 770 ldx #LINE_770 jsr gosub_ix ; GOTO 360 ldx #LINE_360 jsr goto_ix LINE_680 ; IF F THEN ldx #INTVAR_F jsr ld_ir1_ix ldx #LINE_360 jsr jmpne_ir1_ix LINE_690 ; GOTO 180 ldx #LINE_180 jsr goto_ix LINE_700 ; REM LINE_710 ; POKE ML,109 ldx #INTVAR_ML ldab #109 jsr poke_ix_pb LINE_720 ; LC=ML ldx #INTVAR_ML jsr ld_ir1_ix ldx #INTVAR_LC jsr ld_ix_ir1 ; GOSUB 17 ldx #LINE_17 jsr gosub_ix ; IF C1 THEN ldx #INTVAR_C1 jsr ld_ir1_ix ldx #LINE_730 jsr jmpeq_ir1_ix ; POKE ML,73 ldx #INTVAR_ML ldab #73 jsr poke_ix_pb LINE_730 ; I=185 ldx #INTVAR_I ldab #185 jsr ld_ix_pb ; IF WH=2 THEN ldx #INTVAR_WH jsr ld_ir1_ix ldab #2 jsr ldeq_ir1_ir1_pb ldx #LINE_740 jsr jmpeq_ir1_ix ; I=150 ldx #INTVAR_I ldab #150 jsr ld_ix_pb LINE_740 ; FOR J=1 TO WH ldx #INTVAR_J ldab #1 jsr for_ix_pb ldx #INTVAR_WH jsr to_ip_ix ; GOSUB 760 ldx #LINE_760 jsr gosub_ix LINE_750 ; FOR L=1 TO 200 ldx #INTVAR_L ldab #1 jsr for_ix_pb ldab #200 jsr to_ip_pb ; NEXT jsr next ; NEXT jsr next LINE_760 ; SOUND I,2 ldx #INTVAR_I jsr ld_ir1_ix ldab #2 jsr ld_ir2_pb jsr sound_ir1_ir2 ; RETURN jsr return ; REM NOISE LINE_770 ; YS+=1 ldx #INTVAR_YS ldab #1 jsr add_ix_ix_pb ; J=8 ldx #INTVAR_J ldab #8 jsr ld_ix_pb ; I=200 ldx #INTVAR_I ldab #200 jsr ld_ix_pb ; IF WH=2 THEN ldx #INTVAR_WH jsr ld_ir1_ix ldab #2 jsr ldeq_ir1_ir1_pb ldx #LINE_780 jsr jmpeq_ir1_ix ; J=4 ldx #INTVAR_J ldab #4 jsr ld_ix_pb ; I=150 ldx #INTVAR_I ldab #150 jsr ld_ix_pb ; YS-=1 ldx #INTVAR_YS ldab #1 jsr sub_ix_ix_pb ; CS+=1 ldx #INTVAR_CS ldab #1 jsr add_ix_ix_pb LINE_780 ; POKE BX,207 ldx #INTVAR_BX ldab #207 jsr poke_ix_pb LINE_790 ; FOR L=1 TO 3 ldx #INTVAR_L ldab #1 jsr for_ix_pb ldab #3 jsr to_ip_pb ; POKE BX,((J-1)*16)+143 ldx #INTVAR_J jsr ld_ir1_ix ldab #1 jsr sub_ir1_ir1_pb ldab #16 jsr mul_ir1_ir1_pb ldab #143 jsr add_ir1_ir1_pb ldx #INTVAR_BX jsr poke_ix_ir1 ; GOSUB 760 ldx #LINE_760 jsr gosub_ix ; POKE BX,((J-1)*16)+143 ldx #INTVAR_J jsr ld_ir1_ix ldab #1 jsr sub_ir1_ir1_pb ldab #16 jsr mul_ir1_ir1_pb ldab #143 jsr add_ir1_ir1_pb ldx #INTVAR_BX jsr poke_ix_ir1 ; FOR I=1 TO 200 ldx #INTVAR_I ldab #1 jsr for_ix_pb ldab #200 jsr to_ip_pb ; NEXT jsr next ; I+=18 ldx #INTVAR_I ldab #18 jsr add_ix_ix_pb ; POKE BX,((J-1)*16)+143 ldx #INTVAR_J jsr ld_ir1_ix ldab #1 jsr sub_ir1_ir1_pb ldab #16 jsr mul_ir1_ir1_pb ldab #143 jsr add_ir1_ir1_pb ldx #INTVAR_BX jsr poke_ix_ir1 ; NEXT jsr next LINE_800 ; PRINT @152, STR$(YS);" " ldab #152 jsr prat_pb ldx #INTVAR_YS jsr str_sr1_ix jsr pr_sr1 jsr pr_ss .text 2, " \r" ; PRINT @344, STR$(CS);" " ldd #344 jsr prat_pw ldx #INTVAR_CS jsr str_sr1_ix jsr pr_sr1 jsr pr_ss .text 2, " \r" LINE_810 ; IF (YS+CS)<54 THEN ldx #INTVAR_YS jsr ld_ir1_ix ldx #INTVAR_CS jsr add_ir1_ir1_ix ldab #54 jsr ldlt_ir1_ir1_pb ldx #LINE_820 jsr jmpeq_ir1_ix ; RETURN jsr return LINE_820 ; IF YS>CS THEN ldx #INTVAR_CS jsr ld_ir1_ix ldx #INTVAR_YS jsr ldlt_ir1_ir1_ix ldx #LINE_850 jsr jmpne_ir1_ix LINE_830 ; PRINT @487, "SORRY, YOU LOST."; ldd #487 jsr prat_pw jsr pr_ss .text 16, "SORRY, YOU LOST." LINE_840 ; SOUND 128,10 ldab #128 jsr ld_ir1_pb ldab #10 jsr ld_ir2_pb jsr sound_ir1_ir2 ; FOR I=1 TO 1500 ldx #INTVAR_I ldab #1 jsr for_ix_pb ldd #1500 jsr to_ip_pw ; NEXT I ldx #INTVAR_I jsr nextvar_ix jsr next ; GOTO 870 ldx #LINE_870 jsr goto_ix LINE_850 ; PRINT @490, "YOU WIN!!!!!"; ldd #490 jsr prat_pw jsr pr_ss .text 12, "YOU WIN!!!!!" LINE_860 ; FOR I=128 TO 255 ldx #INTVAR_I ldab #128 jsr for_ix_pb ldab #255 jsr to_ip_pb ; SOUND I,1 ldx #INTVAR_I jsr ld_ir1_ix ldab #1 jsr ld_ir2_pb jsr sound_ir1_ir2 ; NEXT jsr next LINE_870 ; PRINT @487, "PLAY AGAIN (y/n) ?"; ldd #487 jsr prat_pw jsr pr_ss .text 18, "PLAY AGAIN (y/n) ?" LINE_880 ; A$=INKEY$ jsr inkey_sr1 ldx #STRVAR_A jsr ld_sx_sr1 ; IF A$="" THEN ldx #STRVAR_A jsr ld_sr1_sx jsr ldeq_ir1_sr1_ss .text 0, "" ldx #LINE_880 jsr jmpne_ir1_ix LINE_890 ; IF LEFT$(A$,1)="Y" THEN ldx #STRVAR_A jsr ld_sr1_sx ldab #1 jsr left_sr1_sr1_pb jsr ldeq_ir1_sr1_ss .text 1, "Y" ldx #LINE_100 jsr jmpne_ir1_ix LINE_900 ; END jsr progend LINE_910 ; J=0 ldx #INTVAR_J ldab #0 jsr ld_ix_pb ; K=0 ldx #INTVAR_K ldab #0 jsr ld_ix_pb ; PC=0 ldx #INTVAR_PC ldab #0 jsr ld_ix_pb LINE_920 ; A$=INKEY$ jsr inkey_sr1 ldx #STRVAR_A jsr ld_sx_sr1 ; IF A$="" THEN ldx #STRVAR_A jsr ld_sr1_sx jsr ldeq_ir1_sr1_ss .text 0, "" ldx #LINE_920 jsr jmpne_ir1_ix LINE_930 ; IF A$="W" THEN ldx #STRVAR_A jsr ld_sr1_sx jsr ldeq_ir1_sr1_ss .text 1, "W" ldx #LINE_940 jsr jmpeq_ir1_ix ; PC=-32 ldx #INTVAR_PC ldab #-32 jsr ld_ix_nb ; K=-1 ldx #INTVAR_K ldab #-1 jsr ld_ix_nb ; RETURN jsr return LINE_940 ; IF A$="S" THEN ldx #STRVAR_A jsr ld_sr1_sx jsr ldeq_ir1_sr1_ss .text 1, "S" ldx #LINE_950 jsr jmpeq_ir1_ix ; J=1 ldx #INTVAR_J ldab #1 jsr ld_ix_pb ; PC=1 ldx #INTVAR_PC ldab #1 jsr ld_ix_pb ; RETURN jsr return LINE_950 ; IF A$="Z" THEN ldx #STRVAR_A jsr ld_sr1_sx jsr ldeq_ir1_sr1_ss .text 1, "Z" ldx #LINE_960 jsr jmpeq_ir1_ix ; K=1 ldx #INTVAR_K ldab #1 jsr ld_ix_pb ; PC=32 ldx #INTVAR_PC ldab #32 jsr ld_ix_pb ; RETURN jsr return LINE_960 ; IF A$="A" THEN ldx #STRVAR_A jsr ld_sr1_sx jsr ldeq_ir1_sr1_ss .text 1, "A" ldx #LINE_970 jsr jmpeq_ir1_ix ; J=-1 ldx #INTVAR_J ldab #-1 jsr ld_ix_nb ; PC=-1 ldx #INTVAR_PC ldab #-1 jsr ld_ix_nb ; RETURN jsr return LINE_970 ; IF ASC(A$)=13 THEN ldx #STRVAR_A jsr asc_ir1_sx ldab #13 jsr ldeq_ir1_ir1_pb ldx #LINE_980 jsr jmpeq_ir1_ix ; PC=99 ldx #INTVAR_PC ldab #99 jsr ld_ix_pb LINE_980 ; RETURN jsr return LLAST ; END jsr progend .module mdalloc ; alloc D bytes in array memory. ; then relink strings. alloc std tmp1 ldx strfree addd strfree std strfree ldd strend addd tmp1 std strend sts tmp2 subd tmp2 blo _ok ldab #OM_ERROR jmp error _ok lds strfree des _again dex dex ldd ,x pshb psha cpx strbuf bhi _again lds tmp2 ldx strbuf ldd strbuf addd tmp1 std strbuf clra _nxtz staa ,x inx cpx strbuf blo _nxtz ldx strbuf ; relink permanent strings ; ENTRY: X points to offending link word in strbuf ; EXIT: X points to strend strlink cpx strend bhs _rts stx tmp1 ldd tmp1 addd #2 ldx ,x std 1,x ldab 0,x ldx 1,x abx bra strlink _rts rts .module mddivflt ; divide X by Y ; ENTRY X contains dividend in (0,x 1,x 2,x 3,x 4,x) ; scratch in (5,x 6,x 7,x 8,x 9,x) ; Y in 0+argv, 1+argv, 2+argv, 3+argv, 4+argv ; EXIT X/Y in (0,x 1,x 2,x 3,x 4,x) ; uses tmp1,tmp1+1,tmp2,tmp2+1,tmp3,tmp3+1,tmp4 divflt clr tmp4 tst 0,x bpl _posX com tmp4 neg 4,x ngc 3,x ngc 2,x ngc 1,x ngc 0,x _posX tst 0+argv bpl _posA com tmp4 neg 4+argv ngc 3+argv ngc 2+argv ngc 1+argv ngc 0+argv divufl _posA ldd 3,x std 6,x ldd 1,x std 4,x ldab 0,x stab 3,x ldd #0 std 8,x std 1,x stab 0,x ldaa #41 staa tmp1 _nxtdiv ldd 3,x subd 3+argv std tmp3 ldd 1,x sbcb 2+argv sbca 1+argv std tmp2 ldab 0,x sbcb 0+argv stab tmp1+1 blo _shift ldd tmp3 std 3,x ldd tmp2 std 1,x ldab tmp1+1 stab 0,x _shift rol 9,x rol 8,x rol 7,x rol 6,x rol 5,x rol 4,x rol 3,x rol 2,x rol 1,x rol 0,x dec tmp1 bne _nxtdiv tst tmp4 bne _add1 ldd 8,x coma comb std 3,x ldd 6,x coma comb std 1,x ldab 5,x comb stab 0,x rts _add1 ldd 8,x addd #1 std 3,x ldd 6,x adcb #0 adca #0 std 1,x ldab 5,x adcb #0 stab 0,x rts .module mdgeteq geteq beq _1 ldd #0 rts _1 ldd #-1 rts .module mdgetlt getlt blt _1 ldd #0 rts _1 ldd #-1 rts .module mdgetne getne bne _1 ldd #0 rts _1 ldd #-1 rts .module mdinput inputqqs jsr R_QUEST inputqs jsr R_QUEST jsr R_SPACE jsr R_GETLN ldaa #',' staa ,x _done stx inptptr rts rdinit ldx inptptr ldaa ,x inx cmpa ',' beq _skpspc jsr inputqqs bra rdinit _skpspc ldaa ,x cmpa #' ' bne _done inx bra _skpspc rdredo ldx inptptr bsr _skpspc tsta beq _rts cmpa #',' beq _rts ldx #R_REDO ldab #6 jsr print ldx redoptr _rts rts .module mdmulflt mulfltx bsr mulflt ldab tmp1+1 stab 0,x ldd tmp2 std 1,x ldd tmp3 std 3,x rts mulflt jsr mulhlf clr tmp4 _4_3 ldaa 4+argv beq _3_4 ldab 3,x bsr _m43 _4_1 ldaa 4+argv ldab 1,x bsr _m41 _4_2 ldaa 4+argv ldab 2,x bsr _m42 _4_0 ldaa 4+argv ldab 0,x bsr _m40 ldab 0,x bpl _4_4 ldd tmp1+1 subb 4+argv sbca #0 std tmp1+1 _4_4 ldaa 4+argv ldab 4,x beq _rndup mul lslb adca tmp4 staa tmp4 bsr mulflt3 _3_4 ldab 4,x beq _rndup ldaa 3+argv bsr _m43 _1_4 ldab 4,x ldaa 1+argv bsr _m41 _2_4 ldab 4,x ldaa 2+argv bsr _m42 _0_4 ldab 4,x ldaa 0+argv bsr _m40 ldaa 0+argv bpl _rndup ldd tmp1+1 subb 4,x sbca #0 std tmp1+1 _rndup ldaa tmp4 lsla mulflt3 ldd tmp3 adcb #0 adca #0 std tmp3 ldd tmp2 adcb #0 adca #0 jmp mulhlf2 _m43 mul addd tmp3+1 std tmp3+1 rol tmp4+1 rts _m41 mul lsr tmp4+1 adcb tmp3 adca tmp2+1 std tmp2+1 ldd tmp1+1 adcb #0 adca #0 std tmp1+1 rts _m42 mul addd tmp3 std tmp3 rol tmp4+1 rts _m40 mul lsr tmp4+1 adcb tmp2+1 adca tmp2 bra mulhlf2 .module mdmulhlf mulhlf bsr mulint ldd #0 std tmp3 stab tmp4+1 _3_2 ldaa 3+argv beq _2_3 ldab 2,x bsr _m32 _3_0 ldaa 3+argv ldab 0,x bsr _m30 ldab 0,x bpl _3_3 ldab tmp1+1 subb 3+argv stab tmp1+1 _3_3 ldaa 3+argv ldab 3,x mul adda tmp3 std tmp3 rol tmp4+1 _3_1 ldaa 3+argv ldab 1,x bsr _m31 _2_3 ldab 3,x beq _rts ldaa 2+argv bsr _m32 _0_3 ldab 3,x ldaa 0+argv bsr _m30 ldaa 0+argv bpl _1_3 ldab tmp1+1 subb 3,x stab tmp1+1 _1_3 ldab 3,x ldaa 1+argv clr tmp4+1 _m31 mul lsr tmp4+1 adcb tmp2+1 adca tmp2 mulhlf2 std tmp2 ldab tmp1+1 adcb #0 stab tmp1+1 rts _m32 mul addd tmp2+1 std tmp2+1 rol tmp4+1 rts _m30 mul lsr tmp4+1 adcb tmp2 adca tmp1+1 std tmp1+1 _rts rts .module mdmulint mulint ldaa 2+argv ldab 2,x mul std tmp2 ldaa 1+argv ldab 1,x mul stab tmp1+1 ldaa 2+argv ldab 1,x mul addb tmp2 adca tmp1+1 std tmp1+1 ldaa 1+argv ldab 2,x mul addb tmp2 adca tmp1+1 std tmp1+1 ldaa 2+argv ldab 0,x mul addb tmp1+1 stab tmp1+1 ldaa 0+argv ldab 2,x mul addb tmp1+1 stab tmp1+1 rts mulintx bsr mulint ldab tmp1+1 stab 0,x ldd tmp2 std 1,x rts .module mdprat prat bita #$FE bne _fcerror anda #$01 oraa #$40 std M_CRSR rts _fcerror ldab #FC_ERROR jmp error .module mdprint print _loop ldaa ,x jsr R_PUTC inx decb bne _loop rts .module mdrnd rnd ldab tmp1+1 bpl gornd orab #1 pshb ldaa tmp2 mul std rvseed ldaa tmp2+1 pulb mul addd rvseed std rvseed gornd ldaa rvseed ldab #-2 mul std tmp3 ldaa rvseed+1 ldab #-2 mul addb #-2 adca tmp3+1 sbcb tmp3 sbca #0 adcb #0 adca #0 std rvseed rts irnd bsr rnd ldaa tmp2+1 ldab rvseed+1 mul staa tmp3+1 ldaa tmp2+1 ldab rvseed mul addb tmp3+1 adca #0 std tmp3 ldaa tmp2 ldab rvseed+1 mul addd tmp3 staa tmp3+1 ldaa #0 adca #0 staa tmp3 ldaa tmp2 ldab rvseed mul addd tmp3 std tmp3 ldaa #0 adca #0 staa tmp1 ldaa tmp1+1 beq _done ldab rvseed+1 mul addb tmp3 stab tmp3 adca tmp1 staa tmp1 ldaa tmp1+1 ldab rvseed mul addb tmp1 stab tmp1 _done ldd tmp3 addd #1 bcc _rts inc tmp1 _rts rts .module mdstrdel ; remove a permanent string ; then re-link trailing strings strdel ldd 1,x subd strbuf blo _rts ldd 1,x subd strend bhs _rts ldd strend subd #2 subb 0,x sbca #0 std strend ldab 0,x ldx 1,x dex dex stx tmp1 abx inx inx sts tmp2 txs ldx tmp1 _nxtwrd pula pulb std ,x inx inx cpx strend blo _nxtwrd lds tmp2 ldx tmp1 jmp strlink _rts rts .module mdstreqs ; compare string against stack ; ENTRY: top of stack is return to caller (ld<ne/eq>_ir1_sr1_ss) ; next two bytes address of string length+payload ; EXIT: we modify those two bytes to point to code beyond payload so caller can just RTS ; we return correct Z flag for caller streqs sts tmp3 tsx ldx 2,x ldab ,x cmpb tmp1+1 bne _ne tstb beq _eq tsx ldx 2,x inx txs ldx tmp2 _nxtchr pula cmpa ,x bne _ne inx decb bne _nxtchr _eq lds tmp3 bsr _fudge clra rts _ne lds tmp3 bsr _fudge rts _fudge tsx ldd 4,x ldx 4,x sec adcb ,x adca #0 tsx std 4,x rts .module mdstrflt strflt pshx tst tmp1+1 bmi _neg ldab ' ' bra _wdigs _neg neg tmp3+1 ngc tmp3 ngc tmp2+1 ngc tmp2 ngc tmp1+1 ldab '-' _wdigs ldx tmp3 pshx ldx strfree stab ,x clr tmp1 _nxtwdig inc tmp1 lsr tmp1+1 ror tmp2 ror tmp2+1 ror tmp3 ldaa tmp1+1 adda tmp2 adca tmp2+1 adca #0 adca #0 tab lsra lsra lsra lsra andb #$0F aba _dec suba #5 bhs _dec adda #5 staa tmp3+1 lsl tmp3 rola adda #'0' psha ldd tmp2 subb tmp3+1 sbca #0 std tmp2 ldab tmp1+1 sbcb #0 stab tmp1+1 pshb ldd tmp2 psha ldaa #$CC mul std tmp3 addd tmp2 std tmp2 ldab tmp1+1 adcb tmp3+1 stab tmp1+1 ldd tmp1+1 addd tmp3 std tmp1+1 pulb ldaa #$CC mul stab tmp3+1 addd tmp1+1 std tmp1+1 pulb ldaa #$CC mul addb tmp1+1 addb tmp3+1 stab tmp1+1 bne _nxtwdig ldd tmp2 bne _nxtwdig ldab tmp1 _nxtc pula inx staa ,x decb bne _nxtc inx inc tmp1 pula pulb subd #0 bne _fdo jmp _fdone _fdo std tmp2 ldab #'.' stab ,x inc tmp1 inx ldd #6 staa tmp1+1 stab tmp3 _nxtf ldd tmp2 lsl tmp2+1 rol tmp2 rol tmp1+1 lsl tmp2+1 rol tmp2 rol tmp1+1 addd tmp2 std tmp2 ldab tmp1+1 adcb #0 stab tmp1+1 lsl tmp2+1 rol tmp2 rol tmp1+1 ldd tmp1 addb #'0' stab ,x inx inc tmp1 clrb stab tmp1+1 dec tmp3 bne _nxtf tst tmp2 bmi _nxtrnd _nxtzero dex dec tmp1 ldaa ,x cmpa #'0' beq _nxtzero bra _zdone _nxtrnd dex dec tmp1 ldaa ,x cmpa #'.' beq _dot inca cmpa #'9' bhi _nxtrnd bra _rdone _dot ldaa #'0' staa ,x ldab tmp1 _ndot decb beq _dzero dex ldaa ,x inca cmpa #'9' bls _ddone bra _ndot _ddone staa ,x ldx strfree ldab tmp1 abx bra _fdone _dzero ldaa #'1' staa ,x ldx strfree ldab tmp1 abx ldaa #'0' _rdone staa ,x _zdone inx inc tmp1 _fdone ldd strfree stx strfree pulx rts .module mdstrprm ; make a permanent string ; ENTRY: argv - input string descriptor ; X - output string descriptor strprm stx tmp1 ldab 0+argv beq _null decb beq _char ldx 1+argv cpx #M_LBUF blo _const cpx #M_MSTR blo _trans cpx strbuf blo _const _trans ldx tmp1 ldab 0,x ldx 1,x cpx strbuf blo _nalloc cmpb 0+argv beq _copyip _nalloc cpx 1+argv bhs _notmp ldx 1+argv cpx strend bhs _notmp ldx strend inx inx stx strfree bsr _copy ldd strfree std 1+argv _notmp ldx tmp1 pshx jsr strdel pulx stx tmp1 ldx strend ldd tmp1 std ,x inx inx stx strfree cpx argv+1 beq _nocopy bsr _copy bra _ready _nocopy ldab 0+argv abx _ready stx strend ldd strfree inx inx stx strfree ldx tmp1 std 1,x ldab 0+argv stab 0,x rts _char ldaa #1 ldx 1+argv ldab ,x _null ldaa #1 std 1+argv _const ldx tmp1 pshx jsr strdel pulx ldab 0+argv stab 0,x ldd 1+argv std 1,x rts _copyip dex dex ldd tmp1 std ,x inx inx _copy sts tmp2 ldab 0+argv lds 1+argv des _nxtchr pula staa ,x inx decb bne _nxtchr lds tmp2 rts .module mdstrrel ; release a temporary string ; ENTRY: X holds string start ; EXIT: X holds new end of string space strrel cpx strend bls _rts cpx strstop bhs _rts stx strfree _rts rts .module mdstrval strval ldab 0,x ldx 1,x jsr strrel inptval clr tmp1 bsr _getsgn jsr _getint tstb beq _dosign ldaa ,x cmpa #'.' bne _dosign inx decb beq _dosign stab tmp5 ldd tmp2 pshb psha ldd tmp1 pshb psha ldab tmp5 bsr _getint stx tmp5 ldab tmp4 ldx #_tblten abx abx abx ldab ,x stab 0+argv ldd 1,x std 1+argv ldd #0 std 3+argv sts tmp4 ldd tmp4 subd #10 std tmp4 lds tmp4 tsx ldab tmp1+1 stab 0,x ldd tmp2 std 1,x ldd #0 std 3,x stab tmp4 jsr divufl ldd 3,x std tmp3 ldab #10 tsx abx txs pula pulb std tmp1 pula pulb std tmp2 ldx tmp5 _dosign tst tmp1 beq _rts neg tmp3+1 ngc tmp3 ngc tmp2+1 ngc tmp2 ngc tmp1+1 _rts rts _getsgn tstb beq _srts ldaa ,x cmpa #' ' bne _trysgn inx decb bra _getsgn _trysgn cmpa #'+' beq _prts cmpa #'-' bne _srts dec tmp1 _prts inx decb _srts rts _getint clra staa tmp1+1 staa tmp2 staa tmp2+1 staa tmp4 _nxtdig tstb beq _crts ldaa ,x suba #'0' blo _crts cmpa #10 bhs _crts inx decb pshb psha ldd tmp2 std tmp3 ldab tmp1+1 stab tmp4+1 bsr _dbl bsr _dbl ldd tmp3 addd tmp2 std tmp2 ldab tmp4+1 adcb tmp1+1 stab tmp1+1 bsr _dbl pulb clra addd tmp2 std tmp2 ldab tmp1+1 adcb #0 stab tmp1+1 pulb ldaa tmp4 inca staa tmp4 cmpa #6 blo _nxtdig _crts clra staa tmp3 staa tmp3+1 rts _dbl lsl tmp2+1 rol tmp2 rol tmp1+1 rts _tblten .byte $00,$00,$01 .byte $00,$00,$0A .byte $00,$00,$64 .byte $00,$03,$E8 .byte $00,$27,$10 .byte $00,$86,$80 .byte $0F,$42,$40 .module mdtonat ; push for-loop record on stack ; ENTRY: ACCB contains size of record ; r1 contains stopping variable and is always float. ; r1+3 must contain zero if an integer. to clra std tmp3 pulx stx tmp1 tsx clrb _nxtfor abx ldd 1,x subd letptr beq _oldfor ldab ,x cmpb #3 bhi _nxtfor sts tmp2 ldd tmp2 subd tmp3 std tmp2 lds tmp2 tsx ldab tmp3+1 stab 0,x ldd letptr std 1,x _oldfor ldd tmp1 std 3,x ldab r1 stab 5,x ldd r1+1 std 6,x ldd r1+3 std 8,x ldab tmp3+1 cmpb #15 beq _flt inca staa 10,x bra _done _flt ldd #0 std 10,x std 13,x inca staa 12,x _done ldx tmp1 jmp ,x add_fr1_fr1_pb ; numCalls = 1 .module modadd_fr1_fr1_pb clra addd r1+1 std r1+1 ldab #0 adcb r1 stab r1 rts add_ir1_ir1_ir2 ; numCalls = 7 .module modadd_ir1_ir1_ir2 ldd r1+1 addd r2+1 std r1+1 ldab r1 adcb r2 stab r1 rts add_ir1_ir1_ix ; numCalls = 5 .module modadd_ir1_ir1_ix ldd r1+1 addd 1,x std r1+1 ldab r1 adcb 0,x stab r1 rts add_ir1_ir1_pb ; numCalls = 22 .module modadd_ir1_ir1_pb clra addd r1+1 std r1+1 ldab #0 adcb r1 stab r1 rts add_ir2_ir2_pb ; numCalls = 4 .module modadd_ir2_ir2_pb clra addd r2+1 std r2+1 ldab #0 adcb r2 stab r2 rts add_ix_ix_ir1 ; numCalls = 3 .module modadd_ix_ix_ir1 ldd 1,x addd r1+1 std 1,x ldab 0,x adcb r1 stab 0,x rts add_ix_ix_pb ; numCalls = 6 .module modadd_ix_ix_pb clra addd 1,x std 1,x ldab #0 adcb 0,x stab 0,x rts and_ir1_ir1_ir2 ; numCalls = 7 .module modand_ir1_ir1_ir2 ldd r2+1 andb r1+2 anda r1+1 std r1+1 ldab r2 andb r1 stab r1 rts and_ir2_ir2_ir3 ; numCalls = 1 .module modand_ir2_ir2_ir3 ldd r3+1 andb r2+2 anda r2+1 std r2+1 ldab r3 andb r2 stab r2 rts asc_ir1_sx ; numCalls = 1 .module modasc_ir1_sx ldab 0,x beq _fc_error ldx 1,x ldab ,x _null stab r1+2 ldd #0 std r1 rts _fc_error ldab #FC_ERROR jmp error clear ; numCalls = 1 .module modclear clra ldx #bss bra _start _again staa ,x inx _start cpx #bes bne _again stx strbuf stx strend inx inx stx strfree ldx #$8FFF stx strstop ldx #startdata stx dataptr rts cls ; numCalls = 1 .module modcls jmp R_CLS clsn_pb ; numCalls = 1 .module modclsn_pb jmp R_CLSN com_ir1_ir1 ; numCalls = 2 .module modcom_ir1_ir1 com r1+2 com r1+1 com r1 rts com_ir1_ix ; numCalls = 1 .module modcom_ir1_ix ldd 1,x comb coma std r1+1 ldab 0,x comb stab r1 rts div_fr1_fr1_pb ; numCalls = 1 .module moddiv_fr1_fr1_pb stab 2+argv ldd #0 std 0+argv std 3+argv ldx #r1 jmp divflt div_fr2_ir2_pb ; numCalls = 1 .module moddiv_fr2_ir2_pb stab 2+argv ldd #0 std 0+argv std 3+argv std r2+3 ldx #r2 jmp divflt for_ix_pb ; numCalls = 9 .module modfor_ix_pb stx letptr clra staa 0,x std 1,x rts gosub_ix ; numCalls = 34 .module modgosub_ix ldab #3 pshb jmp ,x goto_ix ; numCalls = 21 .module modgoto_ix ins ins jmp ,x ignxtra ; numCalls = 1 .module modignxtra ldx inptptr ldaa ,x beq _rts ldx #R_EXTRA ldab #15 jmp print _rts rts inkey_sr1 ; numCalls = 2 .module modinkey_sr1 ldd #$0101 std r1 ldaa M_IKEY bne _gotkey jsr R_KEYIN _gotkey clr M_IKEY staa r1+2 bne _rts staa r1 _rts rts input ; numCalls = 1 .module modinput tsx ldd ,x subd #3 std redoptr jmp inputqs irnd_ir1_pb ; numCalls = 1 .module modirnd_ir1_pb clra staa tmp1+1 std tmp2 jsr irnd std r1+1 ldab tmp1 stab r1 rts irnd_ir2_pb ; numCalls = 1 .module modirnd_ir2_pb clra staa tmp1+1 std tmp2 jsr irnd std r2+1 ldab tmp1 stab r2 rts jmpeq_ir1_ix ; numCalls = 24 .module modjmpeq_ir1_ix ldd r1+1 bne _rts ldaa r1 bne _rts ins ins jmp ,x _rts rts jmpne_ir1_ix ; numCalls = 28 .module modjmpne_ir1_ix ldd r1+1 bne _go ldaa r1 bne _go rts _go ins ins jmp ,x ld_fr1_fx ; numCalls = 5 .module modld_fr1_fx ldd 3,x std r1+3 ldd 1,x std r1+1 ldab 0,x stab r1 rts ld_fr2_fx ; numCalls = 3 .module modld_fr2_fx ldd 3,x std r2+3 ldd 1,x std r2+1 ldab 0,x stab r2 rts ld_fx_fr1 ; numCalls = 3 .module modld_fx_fr1 ldd r1+3 std 3,x ldd r1+1 std 1,x ldab r1 stab 0,x rts ld_ir1_ix ; numCalls = 83 .module modld_ir1_ix ldd 1,x std r1+1 ldab 0,x stab r1 rts ld_ir1_pb ; numCalls = 7 .module modld_ir1_pb stab r1+2 ldd #0 std r1 rts ld_ir2_ix ; numCalls = 16 .module modld_ir2_ix ldd 1,x std r2+1 ldab 0,x stab r2 rts ld_ir2_pb ; numCalls = 7 .module modld_ir2_pb stab r2+2 ldd #0 std r2 rts ld_ir3_ix ; numCalls = 1 .module modld_ir3_ix ldd 1,x std r3+1 ldab 0,x stab r3 rts ld_ix_ir1 ; numCalls = 41 .module modld_ix_ir1 ldd r1+1 std 1,x ldab r1 stab 0,x rts ld_ix_nb ; numCalls = 8 .module modld_ix_nb stab 2,x ldd #-1 std 0,x rts ld_ix_pb ; numCalls = 24 .module modld_ix_pb stab 2,x ldd #0 std 0,x rts ld_ix_pw ; numCalls = 1 .module modld_ix_pw std 1,x ldab #0 stab 0,x rts ld_sr1_sx ; numCalls = 7 .module modld_sr1_sx ldd 1,x std r1+1 ldab 0,x stab r1 rts ld_sx_sr1 ; numCalls = 2 .module modld_sx_sr1 ldab r1 stab 0+argv ldd r1+1 std 1+argv jmp strprm ldeq_ir1_ir1_nb ; numCalls = 13 .module modldeq_ir1_ir1_nb cmpb r1+2 bne _done ldd r1 subd #-1 _done jsr geteq std r1+1 stab r1 rts ldeq_ir1_ir1_pb ; numCalls = 11 .module modldeq_ir1_ir1_pb cmpb r1+2 bne _done ldd r1 _done jsr geteq std r1+1 stab r1 rts ldeq_ir1_sr1_ss ; numCalls = 7 .module modldeq_ir1_sr1_ss ldab r1 stab tmp1+1 ldd r1+1 std tmp2 jsr streqs jsr geteq std r1+1 stab r1 rts ldeq_ir2_ir2_nb ; numCalls = 5 .module modldeq_ir2_ir2_nb cmpb r2+2 bne _done ldd r2 subd #-1 _done jsr geteq std r2+1 stab r2 rts ldeq_ir2_ir2_pb ; numCalls = 6 .module modldeq_ir2_ir2_pb cmpb r2+2 bne _done ldd r2 _done jsr geteq std r2+1 stab r2 rts ldeq_ir3_ir3_pb ; numCalls = 1 .module modldeq_ir3_ir3_pb cmpb r3+2 bne _done ldd r3 _done jsr geteq std r3+1 stab r3 rts ldlt_ir1_fr1_fx ; numCalls = 4 .module modldlt_ir1_fr1_fx ldd r1+3 subd 3,x ldd r1+1 sbcb 2,x sbca 1,x ldab r1 sbcb 0,x jsr getlt std r1+1 stab r1 rts ldlt_ir1_fr1_pb ; numCalls = 1 .module modldlt_ir1_fr1_pb clra std tmp1 ldd r1+1 subd tmp1 ldab r1 sbcb #0 jsr getlt std r1+1 stab r1 rts ldlt_ir1_ir1_ix ; numCalls = 3 .module modldlt_ir1_ir1_ix ldd r1+1 subd 1,x ldab r1 sbcb 0,x jsr getlt std r1+1 stab r1 rts ldlt_ir1_ir1_pb ; numCalls = 4 .module modldlt_ir1_ir1_pb clra std tmp1 ldd r1+1 subd tmp1 ldab r1 sbcb #0 jsr getlt std r1+1 stab r1 rts ldlt_ir2_fr2_ix ; numCalls = 3 .module modldlt_ir2_fr2_ix ldd r2+1 subd 1,x ldab r2 sbcb 0,x jsr getlt std r2+1 stab r2 rts ldlt_ir2_ir2_fx ; numCalls = 1 .module modldlt_ir2_ir2_fx ldd #0 subd 3,x ldd r2+1 sbcb 2,x sbca 1,x ldab r2 sbcb 0,x jsr getlt std r2+1 stab r2 rts ldlt_ir2_ir2_ix ; numCalls = 2 .module modldlt_ir2_ir2_ix ldd r2+1 subd 1,x ldab r2 sbcb 0,x jsr getlt std r2+1 stab r2 rts ldlt_ir2_ir2_pb ; numCalls = 1 .module modldlt_ir2_ir2_pb clra std tmp1 ldd r2+1 subd tmp1 ldab r2 sbcb #0 jsr getlt std r2+1 stab r2 rts ldne_ir1_ir1_ir2 ; numCalls = 1 .module modldne_ir1_ir1_ir2 ldd r1+1 subd r2+1 bne _done ldab r1 cmpb r2 _done jsr getne std r1+1 stab r1 rts ldne_ir1_ir1_pb ; numCalls = 4 .module modldne_ir1_ir1_pb cmpb r1+2 bne _done ldd r1 _done jsr getne std r1+1 stab r1 rts ldne_ir2_ir2_pb ; numCalls = 3 .module modldne_ir2_ir2_pb cmpb r2+2 bne _done ldd r2 _done jsr getne std r2+1 stab r2 rts left_sr1_sr1_pb ; numCalls = 1 .module modleft_sr1_sr1_pb tstb beq _zero cmpb r1 bhs _rts stab r1 rts _zero pshx ldx r1+1 jsr strrel pulx ldd #$0100 std r1+1 stab r1 _rts rts _fc_error ldab #FC_ERROR jmp error mul_fr2_ir2_fx ; numCalls = 1 .module modmul_fr2_ir2_fx ldab 0,x stab 0+argv ldd 1,x std 1+argv ldd 3,x std 3+argv ldd #0 std r2+3 ldx #r2 jmp mulfltx mul_ir1_ir1_pb ; numCalls = 3 .module modmul_ir1_ir1_pb stab 2+argv ldd #0 std 0+argv ldx #r1 jmp mulintx mul_ir2_ir2_pb ; numCalls = 2 .module modmul_ir2_ir2_pb stab 2+argv ldd #0 std 0+argv ldx #r2 jmp mulintx next ; numCalls = 9 .module modnext pulx stx tmp1 tsx ldab ,x cmpb #3 bhi _ok ldab #NF_ERROR jmp error _ok cmpb #11 bne _flt ldd 9,x std r1+1 ldab 8,x stab r1 ldx 1,x ldd r1+1 addd 1,x std r1+1 std 1,x ldab r1 adcb ,x stab r1 stab ,x tsx tst 8,x bpl _iopp ldd r1+1 subd 6,x ldab r1 sbcb 5,x blt _idone ldx 3,x jmp ,x _iopp ldd 6,x subd r1+1 ldab 5,x sbcb r1 blt _idone ldx 3,x jmp ,x _idone ldab #11 bra _done _flt ldd 13,x std r1+3 ldd 11,x std r1+1 ldab 10,x stab r1 ldx 1,x ldd r1+3 addd 3,x std r1+3 std 3,x ldd 1,x adcb r1+2 adca r1+1 std r1+1 std 1,x ldab r1 adcb ,x stab r1 stab ,x tsx tst 10,x bpl _fopp ldd r1+3 subd 8,x ldd r1+1 sbcb 7,x sbca 6,x ldab r1 sbcb 5,x blt _fdone ldx 3,x jmp ,x _fopp ldd 8,x subd r1+3 ldd 6,x sbcb r1+2 sbca r1+1 ldab 5,x sbcb r1 blt _fdone ldx 3,x jmp ,x _fdone ldab #15 _done abx txs ldx tmp1 jmp ,x nextvar_ix ; numCalls = 4 .module modnextvar_ix stx letptr pulx stx tmp1 tsx clrb _nxtvar abx ldd 1,x subd letptr beq _ok ldab ,x cmpb #3 bhi _nxtvar _ok txs ldx tmp1 jmp ,x or_ir1_ir1_ir2 ; numCalls = 8 .module modor_ir1_ir1_ir2 ldd r2+1 orab r1+2 oraa r1+1 std r1+1 ldab r2 orab r1 stab r1 rts peek_ir1_ir1 ; numCalls = 8 .module modpeek_ir1_ir1 ldx r1+1 cpx #M_IKEY bne _nostore jsr R_KPOLL beq _nostore staa M_IKEY _nostore ldab ,x stab r1+2 ldd #0 std r1 rts peek_ir1_ix ; numCalls = 4 .module modpeek_ir1_ix ldx 1,x cpx #M_IKEY bne _nostore jsr R_KPOLL beq _nostore staa M_IKEY _nostore ldab ,x stab r1+2 ldd #0 std r1 rts peek_ir2_ir2 ; numCalls = 9 .module modpeek_ir2_ir2 ldx r2+1 cpx #M_IKEY bne _nostore jsr R_KPOLL beq _nostore staa M_IKEY _nostore ldab ,x stab r2+2 ldd #0 std r2 rts peek_ir3_ir3 ; numCalls = 1 .module modpeek_ir3_ir3 ldx r3+1 cpx #M_IKEY bne _nostore jsr R_KPOLL beq _nostore staa M_IKEY _nostore ldab ,x stab r3+2 ldd #0 std r3 rts poke_ix_ir1 ; numCalls = 4 .module modpoke_ix_ir1 ldab r1+2 ldx 1,x stab ,x rts poke_ix_pb ; numCalls = 5 .module modpoke_ix_pb ldx 1,x stab ,x rts pr_sr1 ; numCalls = 4 .module modpr_sr1 ldab r1 beq _rts ldx r1+1 jsr print ldx r1+1 jmp strrel _rts rts pr_ss ; numCalls = 14 .module modpr_ss pulx ldab ,x beq _null inx jsr print jmp ,x _null jmp 1,x prat_pb ; numCalls = 4 .module modprat_pb ldaa #$40 std M_CRSR rts prat_pw ; numCalls = 7 .module modprat_pw jmp prat progbegin ; numCalls = 1 .module modprogbegin ldx R_MCXID cpx #'h'*256+'C' bne _mcbasic pulx clrb pshb pshb pshb jmp ,x _reqmsg .text "?MICROCOLOR BASIC ROM REQUIRED" _mcbasic ldx #_reqmsg ldab #30 jsr print pulx rts progend ; numCalls = 2 .module modprogend pulx pula pula pula jsr R_RESET jmp R_DMODE NF_ERROR .equ 0 RG_ERROR .equ 4 OD_ERROR .equ 6 FC_ERROR .equ 8 OM_ERROR .equ 12 BS_ERROR .equ 16 DD_ERROR .equ 18 error jmp R_ERROR readbuf_fx ; numCalls = 1 .module modreadbuf_fx stx letptr jsr rdinit ldab #128 jsr inptval stx inptptr ldaa ,x ldx letptr ldab tmp1+1 stab 0,x ldd tmp2 std 1,x ldd tmp3 std 3,x jsr rdredo beq _rts pulx jmp ,x _rts rts return ; numCalls = 9 .module modreturn pulx tsx clrb _nxt abx ldab ,x bne _ok ldab #RG_ERROR jmp error _ok cmpb #3 bne _nxt inx txs rts rnd_fr1_pb ; numCalls = 1 .module modrnd_fr1_pb clra staa tmp1+1 std tmp2 jsr rnd std r1+3 ldd #0 std r1+1 stab r1 rts sound_ir1_ir2 ; numCalls = 3 .module modsound_ir1_ir2 ldaa r1+2 ldab r2+2 jmp R_SOUND step_ip_ir1 ; numCalls = 2 .module modstep_ip_ir1 tsx ldab r1 stab 10,x ldd r1+1 std 11,x ldd ,x std 5,x rts str_sr1_ix ; numCalls = 4 .module modstr_sr1_ix ldd 1,x std tmp2 ldab 0,x stab tmp1+1 ldd #0 std tmp3 jsr strflt std r1+1 ldab tmp1 stab r1 rts sub_fr1_ir1_fr2 ; numCalls = 1 .module modsub_fr1_ir1_fr2 ldd #0 subd r2+3 std r1+3 ldd r1+1 sbcb r2+2 sbca r2+1 std r1+1 ldab r1 sbcb r2 stab r1 rts sub_fr1_ir1_fx ; numCalls = 1 .module modsub_fr1_ir1_fx ldd #0 subd 3,x std r1+3 ldd r1+1 sbcb 2,x sbca 1,x std r1+1 ldab r1 sbcb 0,x stab r1 rts sub_ir1_ir1_pb ; numCalls = 18 .module modsub_ir1_ir1_pb stab tmp1 ldd r1+1 subb tmp1 sbca #0 std r1+1 ldab r1 sbcb #0 stab r1 rts sub_ir2_ir2_pb ; numCalls = 5 .module modsub_ir2_ir2_pb stab tmp1 ldd r2+1 subb tmp1 sbca #0 std r2+1 ldab r2 sbcb #0 stab r2 rts sub_ir3_ir3_pb ; numCalls = 1 .module modsub_ir3_ir3_pb stab tmp1 ldd r3+1 subb tmp1 sbca #0 std r3+1 ldab r3 sbcb #0 stab r3 rts sub_ix_ix_ir1 ; numCalls = 2 .module modsub_ix_ix_ir1 ldd 1,x subd r1+1 std 1,x ldab 0,x sbcb r1 stab 0,x rts sub_ix_ix_pb ; numCalls = 3 .module modsub_ix_ix_pb stab tmp1 ldd 1,x subb tmp1 sbca #0 std 1,x ldab 0,x sbcb #0 stab 0,x rts to_ip_ix ; numCalls = 1 .module modto_ip_ix ldab 0,x stab r1 ldd 1,x std r1+1 ldd #0 std r1+3 ldab #11 jmp to to_ip_pb ; numCalls = 6 .module modto_ip_pb stab r1+2 ldd #0 std r1 std r1+3 ldab #11 jmp to to_ip_pw ; numCalls = 2 .module modto_ip_pw std r1+1 ldd #0 stab r1 std r1+3 ldab #11 jmp to ; data table startdata enddata symstart ; fixed-point constants FLT_0p60000 .byte $00, $00, $00, $99, $9a ; block started by symbol bss ; Numeric Variables INTVAR_BX .block 3 INTVAR_C1 .block 3 INTVAR_CC .block 3 INTVAR_CN .block 3 INTVAR_CS .block 3 INTVAR_F .block 3 INTVAR_I .block 3 INTVAR_J .block 3 INTVAR_K .block 3 INTVAR_L .block 3 INTVAR_LC .block 3 INTVAR_ML .block 3 INTVAR_PC .block 3 INTVAR_SC .block 3 INTVAR_SL .block 3 INTVAR_WH .block 3 INTVAR_X .block 3 INTVAR_Y .block 3 INTVAR_YS .block 3 FLTVAR_DT .block 5 FLTVAR_SK .block 5 FLTVAR_TS .block 5 ; String Variables STRVAR_A .block 3 ; Numeric Arrays ; String Arrays ; block ended by symbol bes .end
10.449715
93
0.69037
2cbe08957c92ee611c424155d14e29df8e876eed
8,890
py
Python
regseg/misc.py
oesteban/pyregseg
16639a048a6990465d460bfce65623556b104e51
[ "MIT" ]
null
null
null
regseg/misc.py
oesteban/pyregseg
16639a048a6990465d460bfce65623556b104e51
[ "MIT" ]
2
2017-10-13T23:15:31.000Z
2017-10-13T23:17:01.000Z
regseg/misc.py
oesteban/pyregseg
16639a048a6990465d460bfce65623556b104e51
[ "MIT" ]
null
null
null
#!/usr/bin/env python # coding: utf-8 # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Miscelaneous helpers """ from __future__ import print_function, division, absolute_import, unicode_literals import os.path as op import numpy as np import nibabel as nb from math import sqrt from scipy import ndimage def sort_surfs(surfs): import os.path as op if not isinstance(surfs, list): return surfs if len(surfs) == 1: return surfs out = [None] * len(surfs) inames = [op.basename(s).lower() for s in surfs] for fname, iname in zip(surfs, inames): index = -1 if 'white' in iname: if ('lh' in iname) or ('.l.' in iname): index = 0 elif ('rh' in iname) or ('.r' in iname): index = 1 elif 'pial' in iname: if ('lh' in iname) or ('.l.' in iname): index = 2 elif ('rh' in iname) or ('.r.' in iname): index = 3 out[index] = fname return out def ball(volsize, radius, dims=3): if not isinstance(volsize, (list, tuple)): volsize = [volsize] * dims assert np.all(volsize > 0) assert radius < min(volsize) * 0.5 result = np.zeros(shape=tuple(volsize), dtype=int) center = (np.array(volsize) - 1) * 0.5 for x in range(0, int(volsize[0])): for y in range(0, int(volsize[1])): for z in range(0, int(volsize[2])): if np.linalg.norm(center - [x, y, z]) < radius: result[x, y, z] = 1 return result def gen_noise(image, mask=None, snr_db=10.0): """ Generates a copy of an image with a certain amount of added gaussian noise (rayleigh for background in mask) """ snr = np.power(10.0, snr_db / 10.0) noise = np.random.normal(size=image.shape) bg_noise = np.random.rayleigh(size=image.shape) if mask is None: mask = np.ones_like(image) im_scaled = noise.std() / image.std() * (sqrt(snr)) * image im_noise = np.zeros_like(image) im_noise[mask > 0] = im_scaled[mask > 0] + noise[mask > 0] im_noise[mask == 0] = bg_noise[mask == 0] return im_noise def genNiftiVol(data, dtype=np.uint8): shape = np.array(np.shape(data), dtype=np.float32) if np.ndim(data) > 3: shape = shape[1:] affine = np.identity(4) affine[0:3, 3] = -0.5 * shape[:3] hdr = nb.Nifti1Header() hdr.set_data_dtype(np.uint8) hdr.set_xyzt_units('mm') hdr.set_data_dtype(dtype) hdr['data_type'] = 2 hdr['qform_code'] = 2 # aligned hdr['sform_code'] = 1 # scanner hdr['scl_slope'] = 1.0 hdr['regular'] = np.array('r', dtype='|S1') pixdim = np.ones(shape=(8,)) pixdim[4:] = 0 hdr['pixdim'] = pixdim if np.ndim(data) > 3: hdr.set_xyzt_units('mm', 'sec') # hdr['xyzt_units'] = 2 + 8 # mm + sec pixdim[4] = 1 hdr['pixdim'] = pixdim nii_array = [] for im in data: nii_array.append(nb.Nifti1Image(im.astype(dtype), affine, hdr)) nii = nb.concat_images(nii_array) else: nii = nb.Nifti1Image(data.astype(dtype), affine, hdr) return nii def genBall(datashape=(101, 101, 101), radius=17, cortex=True): wm = ball(datashape, radius) if cortex: ball2 = ball(11, 4.4) gm = ndimage.binary_dilation(wm, structure=ball2).astype(np.uint8) - wm bg = np.ones_like(wm) - (gm + wm) return [bg, wm, gm] else: bg = np.ones_like(wm) - wm return [bg, wm] def genGyrus(datashape=(101, 101, 101), radius=35, cortex=True): modelbase = ball(datashape, radius) center_pix = ((np.array(datashape) - 1) * 0.5).astype(np.uint8) displ_pix = ((np.array(datashape) - 1) * 0.25).astype(np.uint8) modelbase[center_pix[0], center_pix[1]:, :] = 0 modelbase[:displ_pix[0], center_pix[1], :] = 0 ball1 = ball(11, 4.5) wm = ndimage.binary_opening(ndimage.binary_erosion( modelbase, structure=ball1).astype(np.uint8), structure=ball1).astype(np.uint8) if cortex: ball2 = ball(11, 4.4) gm = ndimage.binary_dilation(wm, structure=ball2).astype(np.uint8) - wm bg = np.ones_like(modelbase) - (gm + wm) return [bg, wm, gm] else: bg = np.ones_like(modelbase) - wm return [bg, wm] def genBox(datashape=(101, 101, 101), coverage=0.4, cortex=True): modelbase = np.zeros(shape=datashape) extent = np.around(coverage * np.array(datashape)) padding = np.around(0.5 * (np.array(datashape) - extent)) end = np.array(datashape) - padding modelbase[padding[0]:end[0], padding[1]:end[1], padding[2]:end[2]] = 1 ball1 = ball(11, 4.5) wm = ndimage.binary_opening(ndimage.binary_erosion( modelbase, structure=ball1).astype(np.uint8), structure=ball1).astype(np.uint8) if cortex: ball2 = ball(11, 4.4) gm = ndimage.binary_dilation(wm, structure=ball2).astype(np.uint8) - wm bg = np.ones_like(modelbase) - (gm + wm) return [bg, wm, gm] else: bg = np.ones_like(modelbase) - wm return [bg, wm] def genL(datashape=(101, 101, 101), cortex=True): modelbase = np.zeros(shape=datashape) center = np.around(0.5 * np.array(datashape)) extent = np.around(0.4 * np.array(datashape)) padding = np.around(0.5 * (np.array(datashape) - extent)) end = np.array(datashape) - padding modelbase[padding[0]:end[0], padding[1]:end[1], padding[2]:end[2]] = 1 modelbase[center[0]:end[0], center[1]:end[1], center[2]:end[2]] = 0 ball1 = ball(11, 4.5) wm = ndimage.binary_opening(ndimage.binary_erosion( modelbase, structure=ball1).astype(np.uint8), structure=ball1).astype(np.uint8) if cortex: ball2 = ball(11, 4.4) gm = ndimage.binary_dilation(wm, structure=ball2).astype(np.uint8) - wm bg = np.ones_like(modelbase) - (gm + wm) return [bg, wm, gm] else: bg = np.ones_like(modelbase) - wm return [bg, wm] def genShape(name, datashape=(101, 101, 101), cortex=True): if name == 'box': return genBox(datashape=datashape, cortex=cortex) elif name == 'L': return genL(datashape=datashape, cortex=cortex) elif name == 'ball': return genBall(datashape=datashape, cortex=cortex) elif name == 'gyrus': return genGyrus(datashape=datashape, cortex=cortex) else: return genBox() def genContrast(model, values): assert(len(model) > 1) assert((len(model) - 1) <= len(values)) if((len(model) - 1) < len(values)): values = values[0:len(model)] contrast = np.zeros_like(model[0]) for c, v in zip(model[1:], values): contrast = contrast + c * v return contrast def draw_circle(grid, x0, y0, radius): """ http://stackoverflow.com/questions/9689173/shape-recognition-with-numpy-scipy-perhaps """ ny, nx = grid.shape y, x = np.ogrid[:ny, :nx] dist = np.hypot(x - x0, y - y0) grid[dist < radius] = True return grid def genSurface(data, fname): from tvtk.api import tvtk grid = tvtk.ImageData(spacing=(1, 1, 1), origin=(0, 0, 0)) grid.point_data.scalars = data.T.ravel() # It wants fortran order??? grid.point_data.scalars.name = 'scalars' grid.dimensions = data.shape iso = tvtk.ImageMarchingCubes(input=grid) w = tvtk.PolyDataWriter( input=iso.output, file_name=os.path.join(model_path, fname)) w.write() def nii2vtk(in_file, out_file=None): from evtk.hl import imageToVTK nii = nb.load(in_file) data = np.array(nii.get_data(), order='C') if out_file is None: out_file, ext = op.splitext(op.basename(in_file)) if ext == '.gz': out_file, _ = op.splitext(out_file) out_file = op.abspath(out_file) imageToVTK(out_file, pointData={'scalar': data}) return out_file def compute_mask(aparc, labels=[0, 5000]): import nibabel as nb import numpy as np import os.path as op import scipy.ndimage as nd segnii = nb.load(aparc) seg = segnii.get_data() mask = np.ones_like(seg, dtype=np.uint8) for l in labels: mask[seg == l] = 0 struct = nd.iterate_structure( nd.generate_binary_structure(3, 1), 4) mask = nd.binary_dilation(mask, structure=struct).astype(np.uint8) mask = nd.binary_closing(mask, structure=struct) mask = nd.binary_fill_holes(mask, structure=struct).astype(np.uint8) mask[mask > 0] = 1 mask[mask <= 0] = 0 hdr = segnii.get_header().copy() hdr.set_data_dtype(np.uint8) hdr.set_xyzt_units('mm', 'sec') out_file = op.abspath('nobstem_mask.nii.gz') nii = nb.Nifti1Image(mask, segnii.get_affine(), hdr).to_filename( out_file) return out_file
30.549828
89
0.605737
292ecb5abf4af300c80b85f47b8bb7d79e1e3019
3,074
rb
Ruby
vendor/bundle/ruby/2.3.0/gems/sawyer-0.8.1/lib/sawyer/serializer.rb
jai-singhal/djangopy
67f5a7479aabc9bf6f85e9c880d40855cc8324ff
[ "MIT" ]
null
null
null
vendor/bundle/ruby/2.3.0/gems/sawyer-0.8.1/lib/sawyer/serializer.rb
jai-singhal/djangopy
67f5a7479aabc9bf6f85e9c880d40855cc8324ff
[ "MIT" ]
4
2020-06-24T11:27:00.000Z
2021-09-27T23:17:00.000Z
vendor/bundle/ruby/2.3.0/gems/sawyer-0.8.1/lib/sawyer/serializer.rb
jai-singhal/djangopy
67f5a7479aabc9bf6f85e9c880d40855cc8324ff
[ "MIT" ]
null
null
null
require 'date' require 'time' module Sawyer class Serializer def self.any_json yajl || multi_json || json end def self.yajl require 'yajl' new(Yajl) rescue LoadError end def self.json require 'json' new(JSON) rescue LoadError end def self.multi_json require 'multi_json' new(MultiJson) rescue LoadError end def self.message_pack require 'msgpack' new(MessagePack, :pack, :unpack) rescue LoadError end # Public: Wraps a serialization format for Sawyer. Nested objects are # prepared for serialization (such as changing Times to ISO 8601 Strings). # Any serialization format that responds to #dump and #load will work. def initialize(format, dump_method_name = nil, load_method_name = nil) @format = format @dump = @format.method(dump_method_name || :dump) @load = @format.method(load_method_name || :load) end # Public: Encodes an Object (usually a Hash or Array of Hashes). # # data - Object to be encoded. # # Returns an encoded String. def encode(data) @dump.call(encode_object(data)) end alias dump encode # Public: Decodes a String into an Object (usually a Hash or Array of # Hashes). # # data - An encoded String. # # Returns a decoded Object. def decode(data) return nil if data.nil? || data.strip.empty? decode_object(@load.call(data)) end alias load decode def encode_object(data) case data when Hash then encode_hash(data) when Array then data.map { |o| encode_object(o) } else data end end def encode_hash(hash) hash.keys.each do |key| case value = hash[key] when Date then hash[key] = value.to_time.utc.xmlschema when Time then hash[key] = value.utc.xmlschema when Hash then hash[key] = encode_hash(value) end end hash end def decode_object(data) case data when Hash then decode_hash(data) when Array then data.map { |o| decode_object(o) } else data end end def decode_hash(hash) hash.keys.each do |key| hash[key.to_sym] = decode_hash_value(key, hash.delete(key)) end hash end def decode_hash_value(key, value) if time_field?(key, value) if value.is_a?(String) begin Time.parse(value) rescue ArgumentError value end elsif value.is_a?(Integer) || value.is_a?(Float) Time.at(value) else value end elsif value.is_a?(Hash) decode_hash(value) elsif value.is_a?(Array) value.map { |o| decode_hash_value(key, o) } else value end end def time_field?(key, value) value && (key =~ /_(at|on)\z/ || key =~ /(\A|_)date\z/) end end end
24.015625
79
0.573845
45bc175bd8d38c6fdecc96d60f33fa65e29416d4
3,520
py
Python
src/319.bulb-switcher.py
wisesky/LeetCode-Practice
65549f72c565d9f11641c86d6cef9c7988805817
[ "MIT" ]
null
null
null
src/319.bulb-switcher.py
wisesky/LeetCode-Practice
65549f72c565d9f11641c86d6cef9c7988805817
[ "MIT" ]
null
null
null
src/319.bulb-switcher.py
wisesky/LeetCode-Practice
65549f72c565d9f11641c86d6cef9c7988805817
[ "MIT" ]
null
null
null
# # @lc app=leetcode id=319 lang=python3 # # [319] Bulb Switcher # # https://leetcode.com/problems/bulb-switcher/description/ # # algorithms # Medium (45.82%) # Likes: 722 # Dislikes: 1353 # Total Accepted: 98.8K # Total Submissions: 214.5K # Testcase Example: '3' # # There are n bulbs that are initially off. You first turn on all the bulbs, # then you turn off every second bulb. # # On the third round, you toggle every third bulb (turning on if it's off or # turning off if it's on). For the i^th round, you toggle every i bulb. For the # n^th round, you only toggle the last bulb. # # Return the number of bulbs that are on after n rounds. # # # Example 1: # # # Input: n = 3 # Output: 1 # Explanation: At first, the three bulbs are [off, off, off]. # After the first round, the three bulbs are [on, on, on]. # After the second round, the three bulbs are [on, off, on]. # After the third round, the three bulbs are [on, off, off]. # So you should return 1 because there is only one bulb is on. # # Example 2: # # # Input: n = 0 # Output: 0 # # # Example 3: # # # Input: n = 1 # Output: 1 # # # # Constraints: # # # 0 <= n <= 10^9 # # # # @lc code=start class Solution: # def bulbSwitch(self, n: int) -> int: # """ # TLE: n=9999999 O(n**2) # """ # li = [1 for _ in range(n)] # for ith in range(1,n): # self.toggle(li, ith, n) # return sum(li) # def toggle(self, li, ith, n): # """ # switch bulb in ith round # """ # for i in range(ith,n,ith+1): # self.switch(li, i) # def switch(self, li, i): # """ # switch li[i] # """ # if li[i] == 0: # li[i] = 1 # else: # li[i] = 0 # def bulbSwitch(self, n): # """ # TLE: n=99999 O(n**2) # """ # # res = 0 # res = [] # for ith in range(1, n+1): # r = self.isOn(ith) # # res += r # res.append(r) # return res def isOn(self, ith): """ 得到 第 ith 个位置上的灯, 被重复toggle的次数 """ r = 0 for i in range(2,ith+1): if ith % i == 0: r += 1 # return 1 if r % 2 == 0 else 0 return (r+1) % 2 def bulbSwitch(self, n): """ 40ms(10%) 14.2MB(63%) 数学归纳发现:只有 i**2 的灯是亮的 eg: 1, 4, 9, 16, 25 ... 更进一步观察: 非平方根的数, 其 isOn 的结果永远是奇数 eg: 5: 5 1 6: 6 3 2 3 7: 7 1 8: 8 4 2 3 10: 10 5 2 3 11: 11 1 12: 12 6 4 3 2 5 ... 结论, 质数 isOn 个数一定是 1 由多个不同的质数混合而成的情况 a b a*b -> 3 a b c ab ac bc abc -> 7 假设是由m个不同个质数 组成的,那么 isOn 数目就是 C^(1)_(m) + C^(2)_(m) + C^(3)_(m) + ... + C^(m)_(m) = 2**m - 1 必然是奇数 只有平方数,会包含自身以及其平方根 构成偶数 9 : 9,3 16: 16, 4 81: 81, 9 """ r = 0 s = 1 while s**2 <= n: r += 1 s += 1 return r def bulbSwitch(self, n): """ Optim: 可根据n的平方根 直接取得结果 32ms(48%) 14.1MB(63%) """ return int(n**0.5) # @lc code=end so = Solution() n = 99999 # n=3 # n=0 # n=1 print(so.bulbSwitch(n)) # res = so.bulbSwitch(n) # for i in range(n): # if res[i] == 1: # print(i+1)
20.952381
79
0.451989
4bcaa9760337bdf94ec0c2b9bb29ea1c0e166b03
1,652
h
C
GCOriginal/AppAPI/AppAPI.h
yinanfang/GCOriginal
c12430d05d6a758b95f9853cb37bc9bae5c88d60
[ "MIT" ]
null
null
null
GCOriginal/AppAPI/AppAPI.h
yinanfang/GCOriginal
c12430d05d6a758b95f9853cb37bc9bae5c88d60
[ "MIT" ]
null
null
null
GCOriginal/AppAPI/AppAPI.h
yinanfang/GCOriginal
c12430d05d6a758b95f9853cb37bc9bae5c88d60
[ "MIT" ]
null
null
null
// // AppAPI.h // GCOriginal // // Created by Lucas Fang on 5/15/15. // Copyright (c) 2015 Lucas Fang. All rights reserved. // #import <Foundation/Foundation.h> // App #import "AppConfig.h" // PebbleKit #import "PebbleKit/PebbleKit.h" // AFNetworking #import <AFNetworking.h> // FlatUIKit #import <FlatUIKit/FlatUIKit.h> // Mantle #import <Mantle/Mantle.h> // Masonry #import <Masonry.h> // MBProgressHUD #import "MBProgressHUD.h" // POP #import <pop/POP.h> // ReactiveCocoa #import <ReactiveCocoa/ReactiveCocoa.h> // Shimmer #import <Shimmer/FBShimmeringView.h> @interface AppAPI : NSObject + (CGRect)getScreenBoundsDependOnOrientation; + (FUIButton *)ButtonWithTitle:(NSString *)title inBold:(BOOL)IsBold; + (UIColor *)getColorWithRGBAinHex:(NSUInteger)color; @end #pragma mark - UIkit and Foundation extention @interface UILabel (AdvancedInitialization) + (UILabel *)LabelTitleWithString:(NSString *)title align:(NSTextAlignment)alignment; + (UILabel *)LabelSubTitleWithString:(NSString *)title align:(NSTextAlignment)alignment; @end @interface UIButton (AdvancedInitialization) + (UIButton *)ButtonWithTitle:(NSString *)title inBold:(BOOL)IsBold horizontalAlign:(UIControlContentHorizontalAlignment)horizontalAlign; @end @interface FUIButton (AdvancedInitialization) + (FUIButton *)ButtonWithTitle:(NSString *)title inBold:(BOOL)IsBold; @end @interface UITextField (AdvancedInitialization) + (UITextField *)TextFieldWithPlaceHolder:(NSString *)placeHolder keyboardType:(UIKeyboardType)keyboardType; @end @interface UIImageView (AdvancedInitialization) + (UIImageView *)ImageViewWithDefaultBackgroundImage:(UIImage *)image; @end
24.656716
137
0.775424
dd5fe945d503fa9ac8f6b847ce8fc3bd547aefcf
4,532
java
Java
web/src/main/java/ru/ilnyrdiplom/bestedu/web/services/ErrorHandler.java
IlnyrNazargulov/best-edu-backend
42d9e91e99e995dbcdb6c08be1a4bd3d342fc9bc
[ "Apache-2.0" ]
null
null
null
web/src/main/java/ru/ilnyrdiplom/bestedu/web/services/ErrorHandler.java
IlnyrNazargulov/best-edu-backend
42d9e91e99e995dbcdb6c08be1a4bd3d342fc9bc
[ "Apache-2.0" ]
2
2021-01-24T17:29:41.000Z
2021-01-24T17:33:16.000Z
web/src/main/java/ru/ilnyrdiplom/bestedu/web/services/ErrorHandler.java
IlnyrNazargulov/best-edu-backend
42d9e91e99e995dbcdb6c08be1a4bd3d342fc9bc
[ "Apache-2.0" ]
null
null
null
package ru.ilnyrdiplom.bestedu.web.services; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import ru.ilnyrdiplom.bestedu.facade.exceptions.BaseException; import ru.ilnyrdiplom.bestedu.web.contracts.ErrorBody; import ru.ilnyrdiplom.bestedu.web.contracts.ErrorCodes; import ru.ilnyrdiplom.bestedu.web.contracts.responses.ApiResponse; import javax.validation.ConstraintViolationException; @Slf4j @ControllerAdvice @RequiredArgsConstructor public class ErrorHandler extends ResponseEntityExceptionHandler { private final ErrorRegister errorRegister; @Override protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { StringBuilder message = new StringBuilder(); boolean isFirst = true; for (Object error : ex.getBindingResult().getAllErrors()) { if (!isFirst) { message.append("\n"); } isFirst = false; if (error instanceof FieldError) { FieldError fieldError = (FieldError) error; message.append("Field '") .append(fieldError.getField()) .append("' has wrong value '") .append(fieldError.getRejectedValue()) .append("' because ") .append(fieldError.getDefaultMessage()); } else { log.warn("Unsupported MethodArgumentNotValid inner error class: {}.", error.getClass()); message.append("Unsupported error"); } } ErrorBody errorBody = new ErrorBody(ErrorCodes.NOT_VALID_ARGUMENT, message.toString(), ex, HttpStatus.BAD_REQUEST); return handleExceptionInternal(ex, errorBody, headers, status, request); } @Override protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { if (log.isDebugEnabled()) { log.warn("Handled exception occurs", ex); } else { // to avoid fill our log with traces log.warn("Handled exception occurs, {}: {}", ex.getClass(), ex.getMessage()); } if (body == null) { ErrorBody errorBody = createErrorBody(ex); status = errorBody.getHttpStatus(); body = errorBody; } ApiResponse apiResponse = ApiResponse.error((ErrorBody) body); return super.handleExceptionInternal(ex, apiResponse, headers, status, request); } @ExceptionHandler(ConstraintViolationException.class) public ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException ex, WebRequest request) { ErrorBody errorBody = new ErrorBody(ErrorCodes.NOT_VALID_ARGUMENT, ex.getMessage(), ex, HttpStatus.BAD_REQUEST); return handleExceptionInternal(ex, errorBody, null, errorBody.getHttpStatus(), request); } @ExceptionHandler(BaseException.class) public ResponseEntity<Object> handleBaseException(BaseException ex, WebRequest request) { final ErrorBody errorBody = createErrorBody(ex); return handleExceptionInternal(ex, errorBody, null, errorBody.getHttpStatus(), request); } @ExceptionHandler(RuntimeException.class) public ResponseEntity<Object> handleRuntimeException(RuntimeException ex, WebRequest request) { return handleExceptionInternal(ex, null, null, HttpStatus.INTERNAL_SERVER_ERROR, request); } private ErrorBody createErrorBody(Exception ex) { ErrorBody errorBody = errorRegister.lookup(ex); if (errorBody == null) { log.error("There is no error body for exception.", ex); errorBody = new ErrorBody(ErrorCodes.UNKNOWN_ERROR, "Unhandled exception occurs.", ex, HttpStatus.INTERNAL_SERVER_ERROR); } return errorBody; } }
45.777778
163
0.700794
2eba906f0040bed7c66eaa32aa0857af1d22b916
99
kt
Kotlin
reference/Swift Language/The Basics/Printing Constants and Variables.kt
TonnyTao/swift-kotlin-javascript
b399ebb6632b02f92a1e3c7129ce37881f2432bc
[ "MIT" ]
1
2017-03-01T22:10:16.000Z
2017-03-01T22:10:16.000Z
reference/Swift Language/The Basics/Printing Constants and Variables.kt
TonnyTao/swift-kotlin-javascript
b399ebb6632b02f92a1e3c7129ce37881f2432bc
[ "MIT" ]
null
null
null
reference/Swift Language/The Basics/Printing Constants and Variables.kt
TonnyTao/swift-kotlin-javascript
b399ebb6632b02f92a1e3c7129ce37881f2432bc
[ "MIT" ]
null
null
null
var friendlyWelcome = "Hello!" println(friendlyWelcome) println("The value is ${friendlyWelcome}")
24.75
42
0.777778
1aa73f2298aee0f4f8620fbbbd7fb82bbd5aa2d0
2,502
cs
C#
StabilityQualityControlSystem/Projects/StabilityBAL/bStabilityCheck.cs
UWAGLE/pharmacy-stability-quality-control-system
b9408b2dc2ab710e5351f3184000b0d470ebe586
[ "MIT" ]
null
null
null
StabilityQualityControlSystem/Projects/StabilityBAL/bStabilityCheck.cs
UWAGLE/pharmacy-stability-quality-control-system
b9408b2dc2ab710e5351f3184000b0d470ebe586
[ "MIT" ]
null
null
null
StabilityQualityControlSystem/Projects/StabilityBAL/bStabilityCheck.cs
UWAGLE/pharmacy-stability-quality-control-system
b9408b2dc2ab710e5351f3184000b0d470ebe586
[ "MIT" ]
null
null
null
using StabilityDAL; using StabilityInterface; using System; using System.Collections.Generic; using System.Data; namespace StabilityBAL { public partial class BAL { public List<StabilityCheck> bGetStabilityCheck(int id) { List<StabilityCheck> objListStabilityCheck = new List<StabilityCheck>(); DataSet ds = oD.dGetStabilityCheck(id); if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0) { foreach (DataRow Row in ds.Tables[0].Rows) // Loop over the rows. { StabilityCheck ob = new StabilityCheck(); ob.Id = Convert.ToInt16(Row["Id"]); ob.BatchId = Convert.ToInt16(Row["BatchId"]); ob.ChamberId = Convert.ToInt16(Row["ChamberId"]); ob.ProductId = Convert.ToInt16(Row["ProductId"]); ob.BatchNo = Row["BatchNo"].ToString(); ob.ChamberName = Row["ChamberName"].ToString(); ob.StudyReason = Row["StudyReason"].ToString(); ob.ProtocolNo = Row["ProtocolNo"].ToString(); ob.Remark = Row["Remark"].ToString(); ob.M1 = FormatDate(Row["M1"].ToString()); ob.M2 = FormatDate(Row["M2"].ToString()); ob.M3 = FormatDate(Row["M3"].ToString()); ob.M6 = FormatDate(Row["M6"].ToString()); ob.M9 = FormatDate(Row["M9"].ToString()); ob.M12 = FormatDate(Row["M12"].ToString()); ob.M18 = FormatDate(Row["M18"].ToString()); ob.M24 = FormatDate(Row["M24"].ToString()); ob.M30 = FormatDate(Row["M30"].ToString()); ob.M36 = FormatDate(Row["M36"].ToString()); ob.M42 = FormatDate(Row["M42"].ToString()); ob.M48 = FormatDate(Row["M48"].ToString()); ob.M60 = FormatDate(Row["M60"].ToString()); ob.M72 = FormatDate(Row["M72"].ToString()); objListStabilityCheck.Add(ob); } } return objListStabilityCheck; } public bool bInsertUpdateStabilityCheck(StabilityCheck o) { return oD.dInsertUpdateStabilityCheck(o); } public bool bDeleteStabilityCheck(int id) { return oD.dDeleteStabilityCheck(id); } } }
41.016393
84
0.511191
6569b05941bfd1e462af7d59fc53f5920c17d30a
3,368
dart
Dart
lib/main.dart
rahulsharmadev-community/LuxOutfit
64189e0c5d5f083fadac6e12702fe5a4c3d4e879
[ "Apache-2.0" ]
2
2021-12-05T08:26:19.000Z
2021-12-08T06:29:18.000Z
lib/main.dart
rahulsharmadev-community/LuxOutfit
64189e0c5d5f083fadac6e12702fe5a4c3d4e879
[ "Apache-2.0" ]
null
null
null
lib/main.dart
rahulsharmadev-community/LuxOutfit
64189e0c5d5f083fadac6e12702fe5a4c3d4e879
[ "Apache-2.0" ]
1
2021-12-06T08:08:00.000Z
2021-12-06T08:08:00.000Z
import 'package:flutter/material.dart'; import 'widgets/Drawer_widget.dart'; import 'BottomNavigationPages/myAccountPage.dart'; import 'widgets/custom_appbar.dart'; import 'widgets/floatingCart_button.dart'; import 'BottomNavigationPages/categoryPage.dart'; import 'BottomNavigationPages/favouritePage.dart'; import 'BottomNavigationPages/homePage.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'DemoOutlet', theme: ThemeData( primaryTextTheme: const TextTheme( headline5: TextStyle(fontSize: 20, color: Colors.black), headline6: TextStyle( fontSize: 15, color: Colors.black, wordSpacing: 2, letterSpacing: 0.8))), home: const MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { GlobalKey<ScaffoldState> _globleKey = GlobalKey<ScaffoldState>(); var navigationTab = const [ { 'icon': Icons.home_outlined, 'name': 'LuxOutfit', 'page': HomePage(), }, { 'icon': Icons.grid_view_outlined, 'name': 'Categories', 'page': CategoriesPage(), }, { 'icon': Icons.favorite_border_outlined, 'name': 'Liked', 'page': FavouritePage(), }, { 'icon': Icons.person_outline_outlined, 'name': 'Account', 'page': MyAccountPage(), } ]; int currentTab = 0; @override Widget build(BuildContext context) { return Scaffold( key: _globleKey, drawer: const DrawerWidget(), extendBodyBehindAppBar: true, appBar: PreferredSize( preferredSize: Size(MediaQuery.of(context).size.width, MediaQuery.of(context).padding.top + kToolbarHeight), child: CustomAppBar( title: navigationTab[currentTab]['name'] as String, isSerchBar: currentTab == 3 ? false : true, actionButton: () => _globleKey.currentState!.showSnackBar( const SnackBar(content: Text('Alert button is Pressed'))), leadingButton: () => _globleKey.currentState!.openDrawer())), bottomNavigationBar: BottomNavigationBar( selectedIconTheme: const IconThemeData(size: 28), type: BottomNavigationBarType.fixed, selectedItemColor: Colors.amber, unselectedItemColor: Colors.grey, showUnselectedLabels: true, showSelectedLabels: true, currentIndex: currentTab, onTap: (value) => setState(() => currentTab = value), items: List.generate( navigationTab.length, (index) => BottomNavigationBarItem( label: navigationTab[index]['name'] as String, icon: Icon(navigationTab[index]['icon'] as IconData)))), body: IndexedStack( index: currentTab, children: List.generate(navigationTab.length, (index) => navigationTab[currentTab]['page'] as Widget))); } }
33.019608
78
0.613124
2a57909fdca24589bf67c6464959b0c8433eee54
205
css
CSS
html-css/exercicios/breno001/style.css
vianabreno/estudos
8f0680f38d3f561bec10266a11c7afef60a09acc
[ "MIT" ]
null
null
null
html-css/exercicios/breno001/style.css
vianabreno/estudos
8f0680f38d3f561bec10266a11c7afef60a09acc
[ "MIT" ]
null
null
null
html-css/exercicios/breno001/style.css
vianabreno/estudos
8f0680f38d3f561bec10266a11c7afef60a09acc
[ "MIT" ]
null
null
null
@charset "UTF-8"; body { background-color: blue; } h1 { color: white; text-align: center; font-family: Georgia, 'Times New Roman', Times, serif; } h2 { color: white; } p { color: white; }
14.642857
92
0.604878
95423d402874a8c40110ddb0558d34fc6366dc43
4,202
dart
Dart
lib/ui/auth/recover/recover_master_pass.dart
Iamsdt/password_manager
097abb543148c63beaa2a29fdb9451de8499e4f9
[ "Apache-2.0" ]
15
2020-11-20T11:57:19.000Z
2022-03-27T16:07:35.000Z
lib/ui/auth/recover/recover_master_pass.dart
Iamsdt/password_manager
097abb543148c63beaa2a29fdb9451de8499e4f9
[ "Apache-2.0" ]
1
2021-12-02T17:15:07.000Z
2021-12-02T17:15:07.000Z
lib/ui/auth/recover/recover_master_pass.dart
Iamsdt/password_manager
097abb543148c63beaa2a29fdb9451de8499e4f9
[ "Apache-2.0" ]
4
2021-03-19T04:11:17.000Z
2022-02-25T11:21:39.000Z
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:password_manager/controller/auth/security_question_controller.dart'; import 'package:password_manager/di/config_inject.dart'; import 'package:password_manager/ui/shared/auth_helper_ui.dart'; import 'package:password_manager/ui/shared/widgets/app_clip_share.dart'; import 'package:password_manager/ui/shared/widgets/pass_apbar.dart'; import 'package:password_manager/ext/ext.dart'; class RecoverMasterPassUI extends StatelessWidget { late final RecoverQuestionController controller = Get.put(getIt<RecoverQuestionController>()); final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Scaffold( body: Container( height: Get.height, width: Get.width, margin: EdgeInsets.only(bottom: 5.h), child: SingleChildScrollView( child: Column( children: <Widget>[ const PassAppBar(), const PassClipShare(), SizedBox( height: 30.h, ), Container( padding: EdgeInsets.only(left: 20.w, right: 20.w), child: Text( "Verify Security Question?", style: Get.textTheme.headline5, ), ), questionForm(), SizedBox( height: 50.h, ), AuthHelper.getAuthButton("UPDATE", () { if (_formKey.currentState?.validate() == true) { controller.updateSecurityQuestion(); } }), //signInTextRow(), ], ), ), ), ); } Widget questionForm() { return Container( margin: EdgeInsets.only( left: 25.w, right: 25.w, top: 30.h, ), child: Form( key: _formKey, child: Column( children: <Widget>[ questionTextField(controller.controller1), SizedBox(height: 10.h), answerTextField(controller.controller2), ], ), ), ); } Widget questionTextField(TextEditingController editingController) { return Material( borderRadius: BorderRadius.circular(30.0), elevation: 5, child: TextFormField( controller: editingController, cursorColor: Colors.blue[200], enabled: false, validator: (value) => value?.isNotEmpty == true ? null : "Please add a valid question", decoration: InputDecoration( prefixIcon: Icon( Icons.question_answer, color: Colors.blue[500], size: 20, ), hintText: "Write question", border: OutlineInputBorder( borderRadius: BorderRadius.circular(30.0), borderSide: BorderSide.none, ), ), style: Get.textTheme.bodyText1, ), ); } Widget answerTextField(TextEditingController editingController) { return ObxValue<RxBool>( (data) => Material( borderRadius: BorderRadius.circular(30.0), elevation: 5, child: TextFormField( controller: editingController, cursorColor: Colors.blue[200], validator: (value) => value?.isNotEmpty != null ? null : "Please add a valid answer", decoration: InputDecoration( prefixIcon: Icon( Icons.chat_sharp, color: Colors.blue[500], size: 20, ), hintText: "Write answer", border: OutlineInputBorder( borderRadius: BorderRadius.circular(30.0), borderSide: BorderSide.none, ), suffixIcon: GestureDetector( onTap: () { data.value = !data.value; }, child: Icon( data.value ? Icons.visibility_off : Icons.visibility, ), ), ), obscureText: data.value, style: Get.textTheme.bodyText1, ), ), true.obs, ); } }
30.014286
84
0.544979
6d1f978ba24b0cbdcc2d31bc87b97971266b4c74
240
ts
TypeScript
src/it/It.d.ts
slavik57/mockjs
554a059599a053bddb54ee576d5866d32f5cd345
[ "MIT" ]
21
2015-04-10T07:10:04.000Z
2022-02-17T09:09:22.000Z
src/it/It.d.ts
slavik57/mockjs
554a059599a053bddb54ee576d5866d32f5cd345
[ "MIT" ]
1
2016-03-29T19:51:19.000Z
2016-04-01T20:34:53.000Z
src/it/It.d.ts
slavik57/mockjs
554a059599a053bddb54ee576d5866d32f5cd345
[ "MIT" ]
1
2015-04-12T19:58:09.000Z
2015-04-12T19:58:09.000Z
export declare class It { static isAny(type: Function): any; static is<T>(predicate: (argument: T) => boolean): any; static isInRange(minimumValue: number, maximumValue: number): any; static isRegExp(regExp: RegExp): any; }
34.285714
70
0.691667
46e51dee37fec3d2bb61cd07cf91f6d567781c97
5,170
py
Python
pycartool/source_space.py
apadee/PyCartool
d030ba80b5304ee0d4ab1ff37a240957fc165914
[ "BSD-3-Clause" ]
2
2020-08-29T01:56:13.000Z
2021-03-27T05:12:03.000Z
pycartool/source_space.py
apadee/PyCartool
d030ba80b5304ee0d4ab1ff37a240957fc165914
[ "BSD-3-Clause" ]
7
2019-10-18T14:55:57.000Z
2021-06-01T23:59:15.000Z
pycartool/source_space.py
apadee/PyCartool
d030ba80b5304ee0d4ab1ff37a240957fc165914
[ "BSD-3-Clause" ]
2
2019-11-09T10:02:18.000Z
2019-12-10T17:09:21.000Z
# -*- coding: utf-8 -*- # Authors: Victor Férat <victor.ferat@live.fr> # # License: BSD (3-clause) import numpy as np import csv import copy def _checkcoordinates(coordinates): if not isinstance(coordinates, np.ndarray): raise TypeError(f'coordinates must be a numpy array') if not coordinates.ndim == 2: raise ValueError(f'coordinates must have 2 dimension (ndim=2)') if not coordinates.shape[1] == 3: raise ValueError(f'coordinates must be of shape ' f'(n_solutions_points, 3)') return (coordinates) def _checknames(names): if not isinstance(names, list): raise TypeError(f'names must be a list of string') return(names) def _checksubject(subject): if subject is not None: if not isinstance(subject, str): raise ValueError(f'Subject must be a string but type ' f'{type(subject)} was found.') return(subject) def read_spi(filename, subject=None): """Create a SourceSpace instance from Cartool spi file. Parameters ---------- filename : str or file-like The spi file to read. subject : str The subject used to create the source space. Returns ------- SourceSpace : pycartool.source_space.SourceSpace The SourceSpace. """ with open(filename) as f: reader = csv.reader(f, delimiter='\t') d = list(reader) names = [elem[-1] for elem in d] coord = [elem[:-1] for elem in d] coord = np.array(coord) coord = coord.astype(np.float) Source_Space = SourceSpace(names, coord, filename=filename, subject=subject) return(Source_Space) def write_spi(filename, SourceSpace): """Write Cartool spi file. Parameters ---------- filename : str or file-like The spi file to write. SourceSpace : pycartool.source_space.SourceSpace The SourceSpace to save. """ names = SourceSpace.names x, y, z = SourceSpace.coordinates.T with open(filename, 'w', newline='') as f: writer = csv.writer(f, delimiter='\t') for s in enumerate(zip(x, y, z, names)): writer.writerow(s[1]) class SourceSpace(object): """Container for source space data. Parameters ---------- names : :obj:`list` of :obj:`str`, length (n_sources) The solutions point names. coordinates : numpy.ndarray, shape (n_sources, 3) The solutions point names coordinates. subject : str Subject from who the source space was created. filename : str or file-like If loaded from a file, the corresponding filename. Attributes ---------- n_sources : int Number of sources. names : :obj:`list` of :obj:`str`, length (n_sources) The solutions point names. coordinates : numpy.ndarray, shape (n_sources, 3) The solutions point names coordinates. subject : str Subject from who the source space was created. filename : str or file-like If loaded from a file, the corresponding filename. """ def __init__(self, names, coordinates, subject=None, filename=None): _checkcoordinates(coordinates) _checknames(names) if not len(names) == coordinates.shape[0]: raise ValueError(f'coordinates and names dimensions must match' f' but found {len(names)} names and ' f'{coordinates.shape[0]} solution points' f' coordinates') else: self.n_sources = len(names) self.subject = subject self.names = names self.coordinates = coordinates self.filename = filename def __repr__(self): s = f'{self.n_sources} sources' if self.subject is not None: s += f', subject : {self.subject}' if self.filename is not None: s += f', filename : {self.filename}' return(f'<SourceSpace or {s}>') def get_coordinates(self): """Return a copy of sources coordinates.""" return (copy.deepcopy(self.coordinates)) def get_names(self): """Return a copy of sources names.""" return(copy.deepcopy(self.names)) def save(self, filename): """Write SourceSpace to Cartool spi file. Parameters ---------- filename : str or file-like The spi file to write. """ write_spi(filename, self) def get_center_of_mass(self, method='mean'): """Compute the center of mass of the Source Space. Parameters ---------- method : str The method to use. Can be 'mean', or 'median'. Returns ------- center_of_mass : numpy.ndarray, shape(3) The x,y,z coordinates of the center of mass. """ if method == 'mean': center_of_mass = np.mean(self.coordinates, axis=0) elif method == 'median': center_of_mass = np.median(self.coordinates, axis=0) return(center_of_mass)
30.411765
75
0.586654
a49ad9b84f631d8e53b87212f8a3c3902e8f6a9e
2,397
php
PHP
app/cache/prod/twig/2e/2e1a8f2174e2c862031f41cea41690990b7c260ad0520c37f3f9ef5f014cbae4.php
hadrienvinay/Kolibri
e96892aee882df72c6ce28a2caabc9882dd05a24
[ "MIT" ]
null
null
null
app/cache/prod/twig/2e/2e1a8f2174e2c862031f41cea41690990b7c260ad0520c37f3f9ef5f014cbae4.php
hadrienvinay/Kolibri
e96892aee882df72c6ce28a2caabc9882dd05a24
[ "MIT" ]
null
null
null
app/cache/prod/twig/2e/2e1a8f2174e2c862031f41cea41690990b7c260ad0520c37f3f9ef5f014cbae4.php
hadrienvinay/Kolibri
e96892aee882df72c6ce28a2caabc9882dd05a24
[ "MIT" ]
null
null
null
<?php /* ::header.html.twig */ class __TwigTemplate_bbbd53b6ee3ce6c6abe9389e834ae46b0eb89e5ac511a505a9a5bc5565cd0f2c extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( 'title' => array($this, 'block_title'), 'stylesheets' => array($this, 'block_stylesheets'), ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <title>"; // line 4 $this->displayBlock('title', $context, $blocks); echo "</title> "; // line 6 $this->displayBlock('stylesheets', $context, $blocks); } // line 4 public function block_title($context, array $blocks = array()) { echo "Bienvenue"; } // line 6 public function block_stylesheets($context, array $blocks = array()) { // line 7 echo " "; // line 8 echo " <link rel=\"stylesheet\" href=\"//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css\"> <link rel=\"stylesheet\" type=\"text/css\" href=\""; // line 9 echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("css/style.css"), "html", null, true); echo "\"> <link rel='stylesheet' type='text/css' href='https://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700'> "; } public function getTemplateName() { return "::header.html.twig"; } public function getDebugInfo() { return array ( 49 => 9, 46 => 8, 44 => 7, 41 => 6, 35 => 4, 31 => 6, 26 => 4, 21 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("", "::header.html.twig", "C:\\MAMP\\htdocs\\Kolibri\\app/Resources\\views/header.html.twig"); } }
30.341772
168
0.595327
e94e5679e5ac7aacaf48ed7fa8301010c85b4fa3
563
css
CSS
torus-ui-angular/ClientApp/src/styles.css
torus-online/torus
fd31db4ff98d5e38b68249abaffeee53b33d5e31
[ "MIT" ]
3
2020-07-28T21:58:56.000Z
2020-10-31T19:33:13.000Z
torus-ui-angular/ClientApp/src/styles.css
torus-online/torus
fd31db4ff98d5e38b68249abaffeee53b33d5e31
[ "MIT" ]
4
2020-06-21T15:12:32.000Z
2022-03-02T09:11:13.000Z
torus-ui-angular/ClientApp/src/styles.css
torus-online/torus
fd31db4ff98d5e38b68249abaffeee53b33d5e31
[ "MIT" ]
2
2021-02-19T20:35:53.000Z
2022-02-11T02:52:26.000Z
/* You can add global styles to this file, and also import other style files */ /* Provide sufficient contrast against white background */ a { color: #0366d6; } code { color: #e01a76; } .btn-primary { color: #fff; background-color: #1b6ec2; border-color: #1861ac; } html, body { height: 100%; } body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; } .full-width-table { width: 100%; } button, a { text-transform: uppercase; } /* hide MetaMask iframe */ iframe#FORWARDER_ID { display: none; }
17.060606
80
0.626998
511be8e41535d5423fc06a0a0bfc42deb15315af
3,470
rs
Rust
crates/bytecode_derive/src/struct_derive.rs
YJDoc2/Bytecode
70aa1d94dff0efe9ab06f0b6010c305a02735295
[ "Apache-2.0", "MIT" ]
1
2022-01-11T13:05:22.000Z
2022-01-11T13:05:22.000Z
crates/bytecode_derive/src/struct_derive.rs
YJDoc2/Bytecode
70aa1d94dff0efe9ab06f0b6010c305a02735295
[ "Apache-2.0", "MIT" ]
null
null
null
crates/bytecode_derive/src/struct_derive.rs
YJDoc2/Bytecode
70aa1d94dff0efe9ab06f0b6010c305a02735295
[ "Apache-2.0", "MIT" ]
null
null
null
use proc_macro::TokenStream; use proc_macro2::Ident; use quote::quote; pub fn derive_struct(name: &syn::Ident, input_struct: &syn::DataStruct) -> TokenStream { let fields = &input_struct.fields; match fields { syn::Fields::Unit => panic!("Bytecode is not supported for Unit type structs"), syn::Fields::Unnamed(unnamed) => derive_unnamed(name, unnamed), syn::Fields::Named(named) => derive_named(name, named), } } fn derive_unnamed( struct_name: &syn::Ident, fields: &syn::FieldsUnnamed, ) -> proc_macro::TokenStream { let fields = &fields.unnamed; let parse_fn_param_name = syn::Ident::new("__bytes", struct_name.span()); let field_list = fields .iter() .enumerate() .map(|(i, _)| Ident::new(&format!("v{}", i), struct_name.span())); let fields_compiled = fields.iter().enumerate().map(|(i, _)| { let idx = syn::Index::from(i); quote! { self.#idx.compile() } }); let compiled = quote! { let mut _i = std::vec::Vec::new(); #(_i.extend(&#fields_compiled);)* return _i; }; let size_counter_var = syn::Ident::new("_count", struct_name.span()); let parsed = fields.iter().zip(field_list.clone()).map(|(f, v)| { quote! { let (#v,size) = #f::parse(&#parse_fn_param_name[#size_counter_var..])?; #size_counter_var += size; } }); let field_list_bracketed = quote! { (#(#field_list),*) }; let output = quote! { impl bytecode::Bytecodable for #struct_name{ fn compile(&self)->Vec<u8>{ #compiled } fn parse(#parse_fn_param_name:&[u8])->std::result::Result<(#struct_name,usize),bytecode::BytecodeError>{ let mut #size_counter_var = 0; #(#parsed)* std::result::Result::Ok((Self #field_list_bracketed,#size_counter_var)) } } }; output.into() } fn derive_named(struct_name: &Ident, fields: &syn::FieldsNamed) -> TokenStream { let fields = &fields.named; let fields_compiled = fields.iter().map(|f| { let ident = &f.ident; quote! { self.#ident.compile() } }); let compiled = quote! { let mut _i = std::vec::Vec::new(); #(_i.extend(&#fields_compiled);)* return _i; }; let size_counter_var = syn::Ident::new("_count", struct_name.span()); let parse_fn_param_name = syn::Ident::new("__bytes", struct_name.span()); let parsed = fields.iter().map(|f| { let ident = f.ident.as_ref().unwrap(); let ty = &f.ty; quote! { let (#ident,size) = #ty::parse(&#parse_fn_param_name[#size_counter_var..])?; #size_counter_var += size; } }); let field_name_list = fields.iter().map(|f| f.ident.as_ref().unwrap()); let output = quote! { impl bytecode::Bytecodable for #struct_name{ fn compile(&self)->Vec<u8>{ #compiled } fn parse(#parse_fn_param_name:&[u8])->std::result::Result<(#struct_name,usize),bytecode::BytecodeError>{ let mut #size_counter_var = 0; #(#parsed)* let _t = Self{ #(#field_name_list),* }; std::result::Result::Ok((_t,#size_counter_var)) } } }; output.into() }
30.707965
116
0.546398
2ca6529ab231195c808a52df906fcf332a93e392
15,362
py
Python
atlas/foundations_local_docker_scheduler_plugin/src/foundations_local_docker_scheduler_plugin/job_deployment.py
manesioz/atlas
4afb63b48f65b0765300dc8034403aeca8489520
[ "Apache-2.0" ]
1
2021-11-01T12:47:44.000Z
2021-11-01T12:47:44.000Z
atlas/foundations_local_docker_scheduler_plugin/src/foundations_local_docker_scheduler_plugin/job_deployment.py
manesioz/atlas
4afb63b48f65b0765300dc8034403aeca8489520
[ "Apache-2.0" ]
null
null
null
atlas/foundations_local_docker_scheduler_plugin/src/foundations_local_docker_scheduler_plugin/job_deployment.py
manesioz/atlas
4afb63b48f65b0765300dc8034403aeca8489520
[ "Apache-2.0" ]
null
null
null
from foundations_authentication.user_token import user_token class JobDeployment(object): def __init__(self, job_id, job, job_source_bundle): self._config = self._get_config() self._job_id = job_id self._job_bundler = None self._job = job @staticmethod def _get_config(): from foundations_contrib.global_state import config_manager config = {} config.update(config_manager.config()) config['_is_deployment'] = True return config @staticmethod def scheduler_backend(): raise NotImplementedError def config(self): return self._config def job_name(self): return self._job_id def _is_local_deployment(self): return '127.0.0.1' in self._config['scheduler_url'] or 'localhost' in self._config['scheduler_url'] def _get_paths(self): from pathlib import Path, PurePosixPath from sys import platform working_dir_root_path = Path(self._config['working_dir_root']) bundle_path = Path(self._job_bundler.job_archive()) job_mount_path = working_dir_root_path / bundle_path.stem if platform == 'win32': if self._is_local_deployment(): working_dir_root_path = convert_win_path_to_posix(working_dir_root_path) job_mount_path = convert_win_path_to_posix(job_mount_path) job_results_root_path = convert_win_path_to_posix(Path(self._config['job_results_root'])) container_config_root_path = convert_win_path_to_posix(Path(self._config['container_config_root'])) else: working_dir_root_path = PurePosixPath(self._config['working_dir_root']) bundle_path = PurePosixPath(self._job_bundler.job_archive()) job_mount_path = working_dir_root_path / bundle_path.stem job_mount_path = str(job_mount_path) working_dir_root_path = str(working_dir_root_path) job_results_root_path = self._config['job_results_root'] container_config_root_path = self._config['container_config_root'] else: job_mount_path = str(job_mount_path.absolute()) working_dir_root_path = str(working_dir_root_path.absolute()) job_results_root_path = self._config['job_results_root'] container_config_root_path = self._config['container_config_root'] return job_mount_path, working_dir_root_path, job_results_root_path, container_config_root_path def deploy(self): import requests from foundations_local_docker_scheduler_plugin.bundle_deployment import job_bundle, submit_job_bundle try: self._job_bundler = job_bundle(self._job_id) response = submit_job_bundle(self._job_bundler) if response.status_code != 200: raise RuntimeError(f'Unable to submit job bundle. {response.text}') project_name = self._job.pipeline_context().provenance.project_name username = self._job.pipeline_context().provenance.user_name job_mount_path, working_dir_root_path, job_results_root_path, container_config_root_path = self._get_paths() job_spec = self._create_job_spec(job_mount_path=job_mount_path, working_dir_root_path=working_dir_root_path, job_results_root_path=job_results_root_path, container_config_root_path=container_config_root_path, job_id=self._job_id, project_name=project_name, username=username, worker_container_overrides=self._config['worker_container_overrides']) gpu_spec = self._create_gpu_spec() queue_job_url = f"{self._config['scheduler_url']}/queued_jobs" payload = { 'job_id': self._job_id, 'spec': job_spec, 'metadata': { 'project_name': project_name, 'username': username }, 'gpu_spec': gpu_spec } response = requests.post(queue_job_url, json=payload, headers={"Authorization": f"bearer {user_token()}"}) if response.status_code != 201: raise RuntimeError(f'Unable to add job to the queue. {response.text}') except requests.exceptions.ConnectionError as e: raise ConnectionError('Cannot currently find Atlas server. Start Atlas server with `atlas-server start`.') finally: self._job_bundler.cleanup() def is_job_complete(self): return self.get_job_status() == 'completed' def fetch_job_results(self): raise NotImplementedError def get_job_status(self): return self._get_job_status(self._job_id) def _get_job_status(self, job_id): import requests responses = { "queued": "queued", "running": "running", "failed": "completed", "completed": "completed", "pending": "queued" } try: r = requests.get(f"{self._config['scheduler_url']}/jobs/{job_id}", headers={"Authorization": f"bearer {user_token()}"}) if r.status_code == requests.codes.ok: return responses[r.json()['status']] else: return None except: raise ConnectionError('Cannot currently find Atlas server. Start Atlas server with `atlas-server start`.') def get_true_job_status(self): import requests try: r = requests.get(f"{self._config['scheduler_url']}/jobs/{self._job_id}", headers={"Authorization": f"bearer {user_token()}"}) if r.status_code == requests.codes.ok: return r.json()['status'] else: return None except: raise ConnectionError('Cannot currently find Atlas server. Start Atlas server with `atlas-server start`.') def get_job_logs(self): import requests r = requests.get(f"{self._config['scheduler_url']}/jobs/{self._job_id}", headers={"Authorization": f"bearer {user_token()}"}) if r.status_code == requests.codes.ok: return r.json()['logs'] else: return "" def stream_job_logs(self, strip_new_line=True): import requests import time status = self.get_job_status() counter = 0 timeout = 15 while status == "queued" or status is None: time.sleep(1) if status is None: counter += 1 if counter >= timeout: raise TimeoutError('Job timed out') status = self.get_job_status() if status == "running": r = requests.get(f"{self._config['scheduler_url']}/running_jobs/{self._job_id}/container_id", headers={"Authorization": f"bearer {user_token()}"}) if r.status_code == requests.codes.ok: import docker from docker.errors import APIError from requests.exceptions import ConnectionError try: client = docker.from_env() container = client.containers.get(r.json()) log_stream = container.logs(stream=True) for line in log_stream: if strip_new_line: line = line.decode().strip('\n') else: line = line.decode() yield line except APIError as e: from foundations_contrib.global_state import log_manager logger = log_manager.get_logger(__name__) logger.warn(f"Could not find local container for job {self._job_id}. The job may have already completed or was submitted to a remote machine. Please see the GUI for full job logs and status.") except ConnectionError as e: from foundations_contrib.global_state import log_manager logger = log_manager.get_logger(__name__) logger.warn(f"Could not connect to local Docker engine for job {self._job_id}. You can ignore this warning if the job was submitted to a remote machine. Please see the GUI for full job logs and status.") else: # try and see if it completed in between requests status = "completed" if status == "completed": from io import StringIO log_stream = StringIO(self.get_job_logs()) for line in log_stream: if strip_new_line: line = line.strip('\n') yield line @staticmethod def cancel_jobs(jobs): from foundations_contrib.global_state import config_manager from pathlib import Path scheduler_url = config_manager['scheduler_url'] return {job: JobDeployment._cancel_job(job, scheduler_url) for job in jobs} @staticmethod def _cancel_job(job_id, scheduler_url): import os import requests try: requests.delete(f"{scheduler_url}/completed_jobs/{job_id}", headers={"Authorization": f"bearer {user_token()}"}).raise_for_status() return True except Exception as ex: return False def _job_resources(self): from foundations_contrib.global_state import current_foundations_context return current_foundations_context().job_resources() def _create_job_spec(self, job_mount_path, working_dir_root_path, job_results_root_path, container_config_root_path, job_id, project_name, username, worker_container_overrides): from foundations_contrib.global_state import current_foundations_context worker_container = { 'volumes': { job_mount_path: { "bind": "/job", "mode": "rw" }, job_results_root_path: { "bind": job_results_root_path, "mode": "rw" }, container_config_root_path: { "bind": "/root/.foundations/config", "mode": "rw" }, working_dir_root_path: { "bind": working_dir_root_path, "mode": "rw" } }, "working_dir": "/job/job_source", # [ # { # 'name': 'logging', # 'mountPath': '/root/.foundations/logs', # }, # { # 'name': 'execution-config', # 'mountPath': '/root/.foundations/config/execution' # } # ] 'environment': { "FOUNDATIONS_USER": username, "FOUNDATIONS_JOB_ID": job_id, "FOUNDATIONS_PROJECT_NAME": project_name, "PYTHONPATH": "/job/", "FOUNDATIONS_HOME": "/root/.foundations/", "FOUNDATIONS_TOKEN": user_token() }, "network": "foundations-atlas" } if current_foundations_context().job_resources().ram is not None: worker_container['mem_limit'] = int(current_foundations_context().job_resources().ram) if (current_foundations_context().job_resources().num_gpus is not None and current_foundations_context().job_resources().num_gpus > 0): worker_container['image'] = 'us.gcr.io/dessa-atlas/worker-gpu:latest' worker_container['runtime'] = 'nvidia' else: worker_container['image'] = 'us.gcr.io/dessa-atlas/worker:latest' worker_container['runtime'] = 'runc' for override_key in ['command', 'image', 'working_dir', 'entrypoint']: if override_key in worker_container_overrides: worker_container[override_key] = worker_container_overrides[override_key] if self._config['run_script_environment']['script_to_run']: worker_container['entrypoint'] = self._config['run_script_environment']['script_to_run'] if 'args' in worker_container_overrides: worker_container['command'] = worker_container_overrides['args'] # # if not has_gpus: # worker_container['env'] += [{'name': 'NVIDIA_VISIBLE_DEVICES', 'value': ''}] for override_key in ['environment', 'volumes']: if override_key in worker_container_overrides: worker_container[override_key] = {**worker_container[override_key], **worker_container_overrides[override_key]} if 'resources' in worker_container_overrides: for override_key in ['limits', 'requests']: if override_key in worker_container_overrides['resources']: worker_container['resources'][override_key].update( worker_container_overrides['resources'][override_key]) return worker_container def _create_gpu_spec(self): from foundations_contrib.global_state import foundations_context resources = foundations_context.job_resources() gpu_spec = { "num_gpus": resources.num_gpus } return gpu_spec def stop_running_job(self): import requests r = requests.delete(f"{self._config['scheduler_url']}/running_jobs/{self._job_id}", headers={"Authorization": f"bearer {user_token()}"}) return 200 <= r.status_code < 300 def get_job_archive(self): import requests import os res = requests.get(f"{self._config['scheduler_url']}/job_bundle/{self._job_id}", headers={"Authorization": f"bearer {user_token()}"}) if res.status_code in [401, 404]: return False else: with open(f"{os.getcwd()}/{self._job_id}.tgz", "wb") as file: file.write(res.content) return True @staticmethod def clear_queue(): import requests config = JobDeployment._get_config() num_removed = 0 status_code = requests.delete(f"{config['scheduler_url']}/queued_jobs/0", headers={"Authorization": f"bearer {user_token()}"}).status_code while status_code == 204: status_code = requests.delete(f"{config['scheduler_url']}/queued_jobs/0", headers={"Authorization": f"bearer {user_token()}"}).status_code num_removed += 1 return num_removed def convert_win_path_to_posix(win_path): win_path_full = str(win_path.absolute().as_posix()).split(':') win_drive = '/' + win_path_full[0].lower() win_path = win_path_full[1] posix_path = ''.join((win_drive, win_path)) return posix_path
40.21466
223
0.586903
a3b5e66667649b45ed730cc31be03946a5548f67
1,277
java
Java
AsyncOp/example/src/main/java/com/github/mguidi/asyncop/app/LongOp.java
mguidi/asyncop
c00af954fb61b2f4ea2dad239dfcd9333d2dc2c3
[ "Apache-2.0" ]
1
2017-10-27T08:10:42.000Z
2017-10-27T08:10:42.000Z
AsyncOp/example/src/main/java/com/github/mguidi/asyncop/app/LongOp.java
mguidi/asyncop
c00af954fb61b2f4ea2dad239dfcd9333d2dc2c3
[ "Apache-2.0" ]
null
null
null
AsyncOp/example/src/main/java/com/github/mguidi/asyncop/app/LongOp.java
mguidi/asyncop
c00af954fb61b2f4ea2dad239dfcd9333d2dc2c3
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2014 Marco Guidi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.mguidi.asyncop.app; import android.content.Context; import android.os.Bundle; import com.github.mguidi.asyncop.AsyncOp; /** * Created by marco on 21/07/14. */ public class LongOp extends AsyncOp { public static final String ARGS_TIMEOUT = "timeout"; public static final String RES_RESULT = "result"; @Override public Bundle execute(Context context, Bundle args) { long timeout = args.getLong(ARGS_TIMEOUT); try { Thread.sleep(timeout); } catch (InterruptedException e) { } Bundle result = new Bundle(1); result.putString(RES_RESULT, "hello"); return result; } }
26.061224
75
0.692247
0de1c099eec33fb884484b39c574fe00acc7ce34
557
podspec
Ruby
TSColorWheel.podspec
tamassengel/TSColorWheel
741e852b1eddf865655d633f84c711f191d9362e
[ "MIT" ]
9
2020-12-23T04:30:14.000Z
2022-01-12T04:30:31.000Z
TSColorWheel.podspec
tamassengel/TSColorWheel
741e852b1eddf865655d633f84c711f191d9362e
[ "MIT" ]
null
null
null
TSColorWheel.podspec
tamassengel/TSColorWheel
741e852b1eddf865655d633f84c711f191d9362e
[ "MIT" ]
3
2020-12-24T08:49:04.000Z
2021-12-11T20:29:07.000Z
Pod::Spec.new do |s| s.name = 'TSColorWheel' s.version = '2.0.2' s.summary = 'A color wheel for watchOS based on Colorful' s.homepage = 'https://github.com/tamassengel/TSColorWheel' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'Tamás Sengel' => 'info@tamassengel.ml' } s.source = { :git => 'https://github.com/tamassengel/TSColorWheel.git', :tag => s.version.to_s } s.watchos.deployment_target = '6.0' s.source_files = 'TSColorWheel/Classes/**/*' s.resources = 'TSColorWheel/Assets/**' s.swift_version = '5.3' end
39.785714
99
0.651706
0c500fa03cee2def7d8c99da4c2af8379e48f895
635
rb
Ruby
data/train/ruby/0c500fa03cee2def7d8c99da4c2af8379e48f895sessions_controller.rb
aliostad/deep-learning-lang-detection
d6b031f3ebc690cf2ffd0ae1b08ffa8fb3b38a62
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/train/ruby/0c500fa03cee2def7d8c99da4c2af8379e48f895sessions_controller.rb
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/train/ruby/0c500fa03cee2def7d8c99da4c2af8379e48f895sessions_controller.rb
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
class SessionsController < ApplicationController def new end def show render :new end def index render :new end def create session[:target_process_url] = params[:target_process][:url] session[:target_process_login] = params[:target_process][:login] session[:target_process_password] = params[:target_process][:password] TargetProcess.configure do |config| config.api_url = session[:target_process_url] + "/api/v1/" config.username = session[:target_process_login] config.password = session[:target_process_password] end redirect_to projects_path end end
22.678571
74
0.708661
84da7f68bced01ae17dc9c1af59303f950bd2244
9,518
cs
C#
Official Windows Platform Sample/Windows Phone 8.1 samples/[C#]-Windows Phone 8.1 samples/Bluetooth Rfcomm Chat/C#/Shared/Scenario1_ChatClient.xaml.cs
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
Official Windows Platform Sample/Windows Phone 8.1 samples/[C#]-Windows Phone 8.1 samples/Bluetooth Rfcomm Chat/C#/Shared/Scenario1_ChatClient.xaml.cs
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Official Windows Platform Sample/Windows Phone 8.1 samples/[C#]-Windows Phone 8.1 samples/Bluetooth Rfcomm Chat/C#/Shared/Scenario1_ChatClient.xaml.cs
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2015-12-25T11:15:10.000Z
2015-12-25T11:15:10.000Z
// Copyright (c) Microsoft. All rights reserved. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.Devices.Bluetooth.Rfcomm; using Windows.Devices.Enumeration; using Windows.Networking.Sockets; using Windows.Storage.Streams; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using SDKTemplate; namespace BluetoothRfcommChat { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class Scenario1_ChatClient : Page { // The Chat Server's custom service Uuid: 34B1CF4D-1069-4AD6-89B6-E161D79BE4D8 private static readonly Guid RfcommChatServiceUuid = Guid.Parse("34B1CF4D-1069-4AD6-89B6-E161D79BE4D8"); // The Id of the Service Name SDP attribute private const UInt16 SdpServiceNameAttributeId = 0x100; // The SDP Type of the Service Name SDP attribute. // The first byte in the SDP Attribute encodes the SDP Attribute Type as follows : // - the Attribute Type size in the least significant 3 bits, // - the SDP Attribute Type value in the most significant 5 bits. private const byte SdpServiceNameAttributeType = (4 << 3) | 5; private StreamSocket chatSocket; private DataWriter chatWriter; private RfcommDeviceService chatService; private DeviceInformationCollection chatServiceInfoCollection; private MainPage rootPage; public Scenario1_ChatClient() { this.InitializeComponent(); chatSocket = null; chatWriter = null; chatService = null; chatServiceInfoCollection = null; App.Current.Suspending += App_Suspending; } void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) { // Make sure we cleanup resources on suspend Disconnect(); } protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; } private async void RunButton_Click(object sender, RoutedEventArgs e) { // Clear any previous messages MainPage.Current.NotifyUser("", NotifyType.StatusMessage); // Find all paired instances of the Rfcomm chat service chatServiceInfoCollection = await DeviceInformation.FindAllAsync( RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommChatServiceUuid))); if (chatServiceInfoCollection.Count > 0) { List<string> items = new List<string>(); foreach (var chatServiceInfo in chatServiceInfoCollection) { items.Add(chatServiceInfo.Name); } cvs.Source = items; ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Visible; } else { MainPage.Current.NotifyUser( "No chat services were found. Please pair with a device that is advertising the chat service.", NotifyType.ErrorMessage); } } private async void ServiceList_Tapped(object sender, TappedRoutedEventArgs e) { try { RunButton.IsEnabled = false; ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Collapsed; var chatServiceInfo = chatServiceInfoCollection[ServiceList.SelectedIndex]; chatService = await RfcommDeviceService.FromIdAsync(chatServiceInfo.Id); if (chatService == null) { MainPage.Current.NotifyUser( "Access to the device is denied because the application was not granted access", NotifyType.StatusMessage); return; } var attributes = await chatService.GetSdpRawAttributesAsync(); if (!attributes.ContainsKey(SdpServiceNameAttributeId)) { MainPage.Current.NotifyUser( "The Chat service is not advertising the Service Name attribute (attribute id=0x100). " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); return; } var attributeReader = DataReader.FromBuffer(attributes[SdpServiceNameAttributeId]); var attributeType = attributeReader.ReadByte(); if (attributeType != SdpServiceNameAttributeType) { MainPage.Current.NotifyUser( "The Chat service is using an unexpected format for the Service Name attribute. " + "Please verify that you are running the BluetoothRfcommChat server.", NotifyType.ErrorMessage); return; } var serviceNameLength = attributeReader.ReadByte(); // The Service Name attribute requires UTF-8 encoding. attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8; ServiceName.Text = "Service Name: \"" + attributeReader.ReadString(serviceNameLength) + "\""; lock (this) { chatSocket = new StreamSocket(); } await chatSocket.ConnectAsync(chatService.ConnectionHostName, chatService.ConnectionServiceName); chatWriter = new DataWriter(chatSocket.OutputStream); ChatBox.Visibility = Windows.UI.Xaml.Visibility.Visible; DataReader chatReader = new DataReader(chatSocket.InputStream); ReceiveStringLoop(chatReader); } catch (Exception ex) { RunButton.IsEnabled = true; MainPage.Current.NotifyUser("Error: " + ex.HResult.ToString() + " - " + ex.Message, NotifyType.ErrorMessage); } } private async void ReceiveStringLoop(DataReader chatReader) { try { uint size = await chatReader.LoadAsync(sizeof(uint)); if (size < sizeof(uint)) { // The underlying socket was closed before we were able to read the whole data return; } uint stringLength = chatReader.ReadUInt32(); uint actualStringLength = await chatReader.LoadAsync(stringLength); if (actualStringLength != stringLength) { // The underlying socket was closed before we were able to read the whole data return; } ConversationList.Items.Add("Received: \"" + chatReader.ReadString(stringLength) + "\""); ReceiveStringLoop(chatReader); } catch (Exception ex) { lock (this) { if (chatSocket == null) { // Do not print anything here - the user closed the socket. } else { MainPage.Current.NotifyUser("Read stream failed with error: " + ex.Message, NotifyType.ErrorMessage); Disconnect(); } } } } private void Disconnect() { if (chatWriter != null) { chatWriter.DetachStream(); chatWriter = null; } lock (this) { if (chatSocket != null) { chatSocket.Dispose(); chatSocket = null; } } RunButton.IsEnabled = true; ServiceSelector.Visibility = Windows.UI.Xaml.Visibility.Collapsed; ChatBox.Visibility = Windows.UI.Xaml.Visibility.Collapsed; ConversationList.Items.Clear(); } private void DisconnectButton_Click(object sender, RoutedEventArgs e) { Disconnect(); MainPage.Current.NotifyUser("Disconnected", NotifyType.StatusMessage); } private async void SendButton_Click(object sender, RoutedEventArgs e) { try { chatWriter.WriteUInt32((uint)MessageTextBox.Text.Length); chatWriter.WriteString(MessageTextBox.Text); await chatWriter.StoreAsync(); ConversationList.Items.Add("Sent: " + MessageTextBox.Text); MessageTextBox.Text = ""; } catch (Exception ex) { MainPage.Current.NotifyUser("Error: " + ex.HResult.ToString() + " - " + ex.Message, NotifyType.StatusMessage); } } } }
36.891473
125
0.564509
4d9058f9589e1b6468567f3d1af6541d2fbd5f63
1,990
cs
C#
LookupAnything/Framework/ModConfigKeys.cs
sish101/StardewMods
8dc54f373aff897a4f5dfc6804d71449cbdd34dd
[ "MIT" ]
null
null
null
LookupAnything/Framework/ModConfigKeys.cs
sish101/StardewMods
8dc54f373aff897a4f5dfc6804d71449cbdd34dd
[ "MIT" ]
null
null
null
LookupAnything/Framework/ModConfigKeys.cs
sish101/StardewMods
8dc54f373aff897a4f5dfc6804d71449cbdd34dd
[ "MIT" ]
null
null
null
using StardewModdingAPI; namespace Pathoschild.Stardew.LookupAnything.Framework { /// <summary>A set of parsed key bindings.</summary> internal class ModConfigKeys { /********* ** Accessors *********/ /// <summary>The key which toggles the lookup UI for something under the cursor.</summary> public SButton[] ToggleLookup { get; } /// <summary>The key which toggles the lookup UI for something in front of the player.</summary> public SButton[] ToggleLookupInFrontOfPlayer { get; } /// <summary>The key which scrolls up long content.</summary> public SButton[] ScrollUp { get; } /// <summary>The key which scrolls down long content.</summary> public SButton[] ScrollDown { get; } /// <summary>The key which toggles the display of debug information.</summary> public SButton[] ToggleDebug { get; } /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="toggleLookup">The key which toggles the lookup UI for something under the cursor.</param> /// <param name="toggleLookupInFrontOfPlayer">The key which toggles the lookup UI for something in front of the player.</param> /// <param name="scrollUp">The key which scrolls up long content.</param> /// <param name="scrollDown">The key which scrolls down long content.</param> /// <param name="toggleDebug">The key which toggles the display of debug information.</param> public ModConfigKeys(SButton[] toggleLookup, SButton[] toggleLookupInFrontOfPlayer, SButton[] scrollUp, SButton[] scrollDown, SButton[] toggleDebug) { this.ToggleLookup = toggleLookup; this.ToggleLookupInFrontOfPlayer = toggleLookupInFrontOfPlayer; this.ScrollUp = scrollUp; this.ScrollDown = scrollDown; this.ToggleDebug = toggleDebug; } } }
43.26087
156
0.639196
1774020bd40865f61aca5ddfd774fe2813732453
149
sh
Shell
copy_to_shogi_extend.sh
akicho8/shogi_player
ef450c95234df6dccc48362f2723eea0cfe2e818
[ "MIT" ]
41
2018-04-16T16:07:27.000Z
2022-02-23T02:59:10.000Z
copy_to_shogi_extend.sh
akicho8/shogi_player
ef450c95234df6dccc48362f2723eea0cfe2e818
[ "MIT" ]
29
2020-04-18T14:27:28.000Z
2022-02-12T07:55:32.000Z
copy_to_shogi_extend.sh
akicho8/shogi_player
ef450c95234df6dccc48362f2723eea0cfe2e818
[ "MIT" ]
4
2018-11-15T06:20:16.000Z
2021-01-02T03:02:58.000Z
#!/bin/sh rsync -avzu --delete --exclude=".git" --exclude="node_modules" --exclude=".nuxt" . ~/src/shogi-extend/front_app/node_modules/shogi-player/
49.666667
138
0.711409
2174eb7c36b7a5625f44e2d7b33ff5addc96d6f3
13,271
js
JavaScript
src/modules/myScanScreens/OdishaScanComponent.js
project-anuvaad/saral-odisha
431721b72f4cb4559f6fa2fafd8c4b0e3e5a3c95
[ "MIT" ]
null
null
null
src/modules/myScanScreens/OdishaScanComponent.js
project-anuvaad/saral-odisha
431721b72f4cb4559f6fa2fafd8c4b0e3e5a3c95
[ "MIT" ]
null
null
null
src/modules/myScanScreens/OdishaScanComponent.js
project-anuvaad/saral-odisha
431721b72f4cb4559f6fa2fafd8c4b0e3e5a3c95
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import { View, ScrollView, Text, Image, TouchableOpacity, Platform, PermissionsAndroid, Alert, BackHandler } from 'react-native'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { StackActions, NavigationActions } from 'react-navigation'; import SystemSetting from 'react-native-system-setting' import RNOpenCvCameraModel from '../../utils/RNOpenCvCamera'; import Strings from '../../utils/Strings'; import AppTheme from '../../utils/AppTheme'; import Spinner from '../common/components/loadingIndicator'; import { OcrLocalResponseAction } from '../../flux/actions/apis/OcrLocalResponseAction' import { apkVersion } from '../../configs/config'; import HeaderComponent from '../common/components/HeaderComponent'; import { SCAN_TYPES } from '../../utils/CommonUtils'; class OdishaScanComponent extends Component { constructor(props) { super(props); this.state = { showFooter: true, oldBrightness: null, activityOpen: false, isLoading: false, } this.onBack = this.onBack.bind(this) } componentDidMount() { const { navigation } = this.props const { params } = navigation.state navigation.addListener('willFocus', payload => { BackHandler.addEventListener('hardwareBackPress', this.onBack) if (params && params.from_screen && params.from_screen == 'scanDetails') { this.setState({ showFooter: false }, () => this.onScanClick()) } else { this.setState({ showFooter: true }) } }) this.willBlur = navigation.addListener('willBlur', payload => BackHandler.removeEventListener('hardwareBackPress', this.onBack) ); } onBack = () => { if (this.state.activityOpen) { this.setState({ showFooter: true, activityOpen: false }) SystemSetting.setBrightnessForce(this.state.oldBrightness).then((success) => { if (success) { SystemSetting.saveBrightness(); } }) RNOpenCvCameraModel.cancelActivity().then(data => { if (data) { const resetAction = StackActions.reset({ index: 0, actions: [NavigationActions.navigate({ routeName: 'odishaScan', params: { from_screen: 'cameraActivity' } })], }); this.props.navigation.dispatch(resetAction); return true } }) return true } else { const { navigation } = this.props const { params } = navigation.state if (params && params.from_screen && params.from_screen == 'cameraActivity') { this.props.navigation.navigate('selectDetails', { from_screen: 'cameraActivity' }) return true } } } onScanClick = async () => { SystemSetting.getBrightness().then((brightness) => { this.setState({ oldBrightness: brightness }) }); if (Platform.OS !== 'ios') { const grantedRead = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE) const grantedWrite = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE) const grantedCamera = await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.CAMERA) if (grantedRead && grantedWrite && grantedCamera) { this.openCameraActivity() } else { PermissionsAndroid.requestMultiple( [ PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE, PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE, PermissionsAndroid.PERMISSIONS.CAMERA ], { title: Strings.permission_text, message: Strings.app_needs_permission } ).then((permRes) => { if ( permRes['android.permission.READ_EXTERNAL_STORAGE'] === PermissionsAndroid.RESULTS.GRANTED && permRes['android.permission.WRITE_EXTERNAL_STORAGE'] === PermissionsAndroid.RESULTS.GRANTED && permRes['android.permission.CAMERA'] === PermissionsAndroid.RESULTS.GRANTED ) { this.openCameraActivity() } else if(permRes['android.permission.READ_EXTERNAL_STORAGE'] == 'never_ask_again' || permRes['android.permission.WRITE_EXTERNAL_STORAGE'] == 'never_ask_again' || permRes['android.permission.CAMERA'] == 'never_ask_again') { Alert.alert(Strings.message_text, Strings.give_permission_from_settings, [ { 'text': Strings.ok_text, style: 'cancel' } ]); } else { Alert.alert(Strings.message_text, Strings.please_give_permission_to_use_app, [ { 'text': Strings.cancel_text, style: 'cancel' }, { 'text': Strings.ok_text, onPress: () => this.onScanClick() } ]); } }); } } } openCameraActivity = () => { const { scanTypeData } = this.props SystemSetting.setBrightnessForce(1).then(async (success) => { if (success) { SystemSetting.saveBrightness(); this.setState({ activityOpen: true }) let uniqStudentsList = ['1234567', '2345678' ] const scannerType = scanTypeData.scanType ? scanTypeData.scanType : SCAN_TYPES.PAT_TYPE RNOpenCvCameraModel.openOdishaScanCamera(JSON.stringify(uniqStudentsList), scannerType) .then(data => { console.log("imgArrSuccess", JSON.parse(data)); let scannerResponse = JSON.parse(data) scannerResponse.scannerType = scannerType this.props.OcrLocalResponseAction(scannerResponse) this.setState({ isLoading: false }) if(scannerType == SCAN_TYPES.PAT_TYPE) { this.props.navigation.navigate('odishaPatScanDetails', { oldBrightness: this.state.oldBrightness }) } // else if(scannerType == SCAN_TYPES.SAT_TYPE) { // this.props.navigation.navigate('satScanDetails', { oldBrightness: this.state.oldBrightness }) // } }) .catch((code, errorMessage) => { this.setState({ isLoading: false }) Alert.alert(Strings.message_text, Strings.table_image_is_not_proper) console.log("dataFailure", code, "Message", errorMessage); }); } else if (!success) { Alert.alert(Strings.permission_deny, Strings.you_have_no_permission_to_change_settings, [ { 'text': Strings.ok_text, style: Strings.cancel_text }, { 'text': Strings.open_settings, onPress: () => SystemSetting.grantWriteSettingPremission() } ]) } }); } render() { const { isLoading } = this.state; const { loginData } = this.props return ( <View style={{ flex: 1, backgroundColor: AppTheme.WHITE_OPACITY }}> <HeaderComponent title={Strings.odisha_saralData} /> {(loginData && loginData.data) && <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}> <Text style={{ fontSize: AppTheme.FONT_SIZE_REGULAR, color: AppTheme.BLACK, fontWeight: 'bold', paddingHorizontal: '5%', paddingVertical: '2%' }} > {Strings.school_name+' : '} <Text style={{ fontWeight: 'normal'}}> {loginData.data.school.name} </Text> </Text> <Text style={{ fontSize: AppTheme.FONT_SIZE_REGULAR, color: AppTheme.BLACK, fontWeight: 'bold', paddingHorizontal: '5%', paddingVertical: '2%' }} > {Strings.schoolId_text+' : '} <Text style={{ fontWeight: 'normal'}}> {loginData.data.school.schoolId} </Text> </Text> </View>} <Text style={{ fontSize: AppTheme.FONT_SIZE_REGULAR-3, color: AppTheme.BLACK, fontWeight: 'bold', paddingHorizontal: '5%', marginBottom: '4%' }} > {Strings.version_text+' : '} <Text style={{ fontWeight: 'normal'}}> {apkVersion} </Text> </Text> <ScrollView contentContainerStyle={{ paddingTop: '5%', paddingBottom: '35%' }} showsVerticalScrollIndicator={false} bounces={false} keyboardShouldPersistTaps={'handled'} > </ScrollView> <View style={styles.bottomTabStyle}> </View> <View style={[styles.bottomTabStyle, { height: 135, width: '50%', marginHorizontal: '25%', backgroundColor: 'transparent', justifyContent: 'center' }]}> <TouchableOpacity style={[styles.subTabContainerStyle]} onPress={this.onScanClick} > <TouchableOpacity style={[styles.scanTabContainerStyle,]} > <TouchableOpacity style={styles.scanSubTabContainerStyle} > <Image source={require('../../assets/images/scanIcon.jpeg')} style={styles.tabIconStyle} resizeMode={'contain'} /> </TouchableOpacity> </TouchableOpacity> <Text style={[styles.tabLabelStyle, { paddingTop: '71%' }]}> {Strings.scan_text} </Text> </TouchableOpacity> </View> {isLoading && <Spinner animating={isLoading} customContainer={{ opacity: 0.9, elevation: 15 }} />} </View> ); } } const styles = { container1: { flex: 1, marginHorizontal: '6%', alignItems: 'center' }, bottomTabStyle: { position: 'absolute', flexDirection: 'row', bottom: 0, height: 90, left: 0, right: 0, backgroundColor: AppTheme.WHITE, elevation: 10, paddingLeft: '5%', paddingRight: '5%', justifyContent: 'space-between' }, subTabContainerStyle: { height: 100, justifyContent: 'center', alignItems: 'center', }, tabIconStyle: { width: 40, height: 40 }, tabLabelStyle: { lineHeight: 40, textAlign: 'center', fontSize: AppTheme.FONT_SIZE_SMALL, color: AppTheme.BLACK, letterSpacing: 1, fontWeight: 'bold' }, scanTabContainerStyle: { width: 85, height: 85, backgroundColor: AppTheme.WHITE, position: 'absolute', borderRadius: 45, justifyContent: 'center', alignItems: 'center' }, scanSubTabContainerStyle: { width: '90%', height: '90%', backgroundColor: AppTheme.BLUE, borderRadius: 45, justifyContent: 'center', alignItems: 'center' } } const mapStateToProps = (state) => { return { ocrLocalResponse: state.ocrLocalResponse, loginData: state.loginData, filteredData: state.filteredData, scanTypeData: state.scanTypeData.response } } const mapDispatchToProps = (dispatch) => { return bindActionCreators({ OcrLocalResponseAction: OcrLocalResponseAction, }, dispatch) } export default (connect(mapStateToProps, mapDispatchToProps)(OdishaScanComponent));
41.086687
168
0.506367
05c5f0b25abbe65d5bb70b8d1b39197b8dced460
206
py
Python
tests/unit/test_ServiceDiscovery.py
giupo/ServiceDiscovery
c09ae4fe50d4e284fca0dc1a2c940fe316c80756
[ "BSD-3-Clause" ]
null
null
null
tests/unit/test_ServiceDiscovery.py
giupo/ServiceDiscovery
c09ae4fe50d4e284fca0dc1a2c940fe316c80756
[ "BSD-3-Clause" ]
null
null
null
tests/unit/test_ServiceDiscovery.py
giupo/ServiceDiscovery
c09ae4fe50d4e284fca0dc1a2c940fe316c80756
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_ServiceDiscovery ---------------------------------- Tests for `ServiceDiscovery` module. """ import unittest from ServiceDiscovery import discovery
15.846154
38
0.606796
2fe17e86af582dbd484c7f63f904a033cdc6d817
53,708
py
Python
GUI.py
georgesfarah4/INFO3-PROJECT
89e0c5a3efe9908f9a228c062ba970500bd936dc
[ "MIT" ]
null
null
null
GUI.py
georgesfarah4/INFO3-PROJECT
89e0c5a3efe9908f9a228c062ba970500bd936dc
[ "MIT" ]
null
null
null
GUI.py
georgesfarah4/INFO3-PROJECT
89e0c5a3efe9908f9a228c062ba970500bd936dc
[ "MIT" ]
null
null
null
from tkinter import * from tkinter import ttk import tkinter.font as font from tkinter.colorchooser import * from tkinter import messagebox from tkinter import filedialog from Model import * from PIL import Image as PILImage from PIL import ImageTk as PILImageTk import pickle from matplotlib import pyplot as plt class loadingWindow: def __init__(self,root): self.root=root root.title('Loading...') framepic=ttk.Frame(root) framepic.grid(row=0,sticky=(W,E)) load=PILImage.open("pics/background.png") self.render = PILImageTk.PhotoImage(load) img=Label(framepic,image=self.render) img.grid() self.root.after(1000,self.loaddata) self.center() def loaddata(self): refreshingData=FetchData() getlocation=Location.getLocation() if refreshingData==True: print('data updated!') else: print('could not update data will show older version') if getlocation==True: print('you are in',Location.country) else: print('could not get Location') self.root.destroy() def center(self): self.root.update_idletasks() # Update "requested size" from geometry manager windowWidth = self.root.winfo_reqwidth() windowHeight = self.root.winfo_reqheight() positionRight = int(self.root.winfo_screenwidth()/2 - windowWidth/2) positionDown = int(self.root.winfo_screenheight()/2 - windowHeight/2) self.root.geometry("+{}+{}".format(positionRight, positionDown)) self.root.overrideredirect(True) ######################################################################################## class adminPanel: def __init__(self,root,data): self.root=root self.feedbacks=data['feedbacks'] self.userpass=data['userpass'] root.title('Admin Panel') self.i=0 i=self.i self.frame=ttk.LabelFrame(root,padding=(5,10),text='review #'+str(self.i+1)) frame=self.frame ttk.Label(frame,text='Name:', font='Helvetica 13 bold').grid(sticky=(W)) self.labelName=ttk.Label(frame,text=self.feedbacks[i]['name'], font='Helvetica 13') self.labelName.grid(sticky=(W)) ttk.Label(frame,text='Email:', font='Helvetica 13 bold').grid(sticky=(W)) self.labelEmail=ttk.Label(frame,text=self.feedbacks[i]['emailaddress'], font='Helvetica 13') self.labelEmail.grid(sticky=(W)) ttk.Label(frame,text='Message:', font='Helvetica 13 bold').grid(sticky=(W)) self.labelMessage=ttk.Label(frame,text=self.feedbacks[i]['message'], font='Helvetica 13') self.labelMessage.grid(sticky=(W)) ttk.Label(frame,text='Stars:', font='Helvetica 13 bold').grid(sticky=(W)) self.labelStar=ttk.Label(frame,text=self.feedbacks[i]['stars'], font='Helvetica 13') self.labelStar.grid(sticky=(W)) frame.grid(padx=10,pady=10) frame2=ttk.Frame(root,padding=(5,10)) frame2.grid(padx=10,pady=10) btn3=ttk.Button(frame2,text='Send Message',command=self.SendMsg) btn3.grid(row=0,column=0,columnspan=2,sticky=(W,E)) self.btn1=ttk.Button(frame2,text='Back',state='disabled',command=self.Back) self.btn1.grid(row=1,column=0,sticky=(W,E)) self.btn2=ttk.Button(frame2,text='Next',command=self.Next) self.btn2.grid(row=1,column=1,sticky=(W,E)) root.rowconfigure(0,weight=1) root.columnconfigure(0,weight=1) root.rowconfigure(1,weight=1) root.columnconfigure(0,weight=1) def SendMsg(self): mail=self.labelEmail['text'] sendmail(mail,self.userpass['user'],self.userpass['pass']) def Next(self): if self.i<len(self.feedbacks)-1: self.i=self.i+1 self.refreshButtons() def Back(self): if self.i>0: self.i=self.i-1 self.refreshButtons() def refreshButtons(self): if self.i==0: self.btn1['state']='disabled' else: self.btn1['state']='normal' if self.i==len(self.feedbacks)-1: self.btn2['state']='disabled' else: self.btn2['state']='normal' self.labelName['text']=self.feedbacks[self.i]['name'] self.labelEmail['text']=self.feedbacks[self.i]['emailaddress'] self.labelMessage['text']=self.feedbacks[self.i]['message'] self.labelStar['text']=self.feedbacks[self.i]['stars'] self.frame['text']='review #'+str(self.i+1) #########################################################################################################################4 class baseWindow: def initSV(self): self.SV=[] for elm in self.language: self.SV.append(StringVar()) def french(self): for i in range(len(self.SV)): self.SV[i].set(self.language[i][1]) def english(self): for i in range(len(self.SV)): self.SV[i].set(self.language[i][0]) def checklanguage(self): if str(type(self))=="<class '__main__.locationWindow'>" or str(type(self))=="<class 'GUI.locationWindow'>": lang=self.preventionsWindow.configs['language'] elif str(type(self))=="<class '__main__.mainWindow'>" or str(type(self))=="<class 'GUI.mainWindow'>": lang=self.configs['language'] else: lang=self.mainWindowInstance.configs['language'] if lang=='english': self.english() if lang=='french': self.french() def goBack(self): self.fenetre.destroy() self.root.deiconify() def setIcon(self): self.fenetre.iconbitmap('pics/icon2.ico') def setStyle(self): s=ttk.Style() s.configure('TFrame', background='white') s.configure('TLabelframe', background='white') s.configure('TLabelframe.Label', foreground='black', background='white') s.configure('TLabel', background='white') s.configure('new.TFrame', background='SystemButtonFace') s.configure('new.TLabel', background='SystemButtonFace') def initTopWindows(self,mainWindowInstance,title=''): self.mainWindowInstance=mainWindowInstance self.root=mainWindowInstance.root self.fenetre=Toplevel(self.root) self.root.withdraw() self.fenetre.title(title) self.setIcon() self.fenetre.protocol('WM_DELETE_WINDOW', self.root.destroy) class introWindow(baseWindow): def __init__(self,mainWindowInstance): self.initTopWindows(mainWindowInstance,"Repartitions des cas du Covid-19 selon les pays") root=self.root fenetre=self.fenetre color=mainWindowInstance.configs['color'] fontSize=mainWindowInstance.configs['fontSize'] myFont = font.Font(fenetre,size=fontSize+2,weight='bold') myFont2 = font.Font(fenetre,size=fontSize) myFont3 = font.Font(fenetre,size=fontSize-7) self.language=[['Hello in this project we are going to do a quick study about the distribution of corona cases around the world', 'Salut dans ce projet on vas faire une etude rapide sur la repartition des nombres des corona dans le monde'], ['Go back','Retour'],['Here are some tips that will help you using this app:',"Voici des informations qui vont vous aider en utilisant l'application"], ['In the main window:','Dans la fenetre principale:'], ['Preventions: Important preventions', "Préventions: Préventions importantes"], ['Graphs: Graphs of the top5 countries in death ,recovered,confirmed numbers of corona', 'Graphes: Graphes des top5 pays dans la mort,confirmé,rétablie,cas de corona'], ['Symptoms: Symptoms of the virus','Symptomes: Symptomes de ce virus'], ['Table: Find all the countries and their statistics','Table: Trouver tous les pays avec leurs statistics'], ['Edit → Font: Choose the font size','Edit → Taille de police: Choisir la taille de police'], ['Edit → Color: Choose the font color','Edit → Couleur: Choisir la couleur du police'], ['Edit → Language: Choose french or english','Edit → Langage: Choisir francais ou englais'], ['About → Feedback: Rate the application!',"About → Feedback: Évaluer l'application!"], ['About → Help: Help how to use the application',"About → Help: Aide à utiliser l'application"], ["File → Export data: Save the selected country's statistics in a file","File → Export data: Enregistrer les statistiques du pays sélectionné dans un fichier"], ['File → Exit: Exit the application',"File → Exit: Sortir de l'appication"], ['Preventions → Hotline: Find the emergency numbers of the country you are in', "Preventions → Hotline: Trouver les numéros d'urgence du pays dans lequel vous vous trouvez"]] self.initSV() frame1=ttk.Frame(fenetre) frame1.grid(column=0,row=0,sticky=(N,S,W,E)) frame1['padding']=(15,10) labelA1=ttk.Label(frame1,text='A 1-',foreground=color,font=myFont) labelA1.grid(row=4,column=0) labelA2=ttk.Label(frame1,text='A 2-',foreground=color,font=myFont) labelA2.grid(row=5,column=0) labelB=ttk.Label(frame1,text='B-',foreground=color,font=myFont) labelB.grid(row=6,column=0,sticky=W) labelC=ttk.Label(frame1,text='C-',foreground=color,font=myFont) labelC.grid(row=7,column=0,sticky=W) labelD=ttk.Label(frame1,text='D-',foreground=color,font=myFont) labelD.grid(row=8,column=0,sticky=W) labelE=ttk.Label(frame1,text='E 1-',foreground=color,font=myFont) labelE.grid(row=9,column=0) labelE2=ttk.Label(frame1,text='E 2-',foreground=color,font=myFont) labelE2.grid(row=10,column=0) labelE3=ttk.Label(frame1,text='E 3-',foreground=color,font=myFont) labelE3.grid(row=11,column=0) labelG1=ttk.Label(frame1,text='G 1-',foreground=color,font=myFont) labelG1.grid(row=12,column=0) labelG2=ttk.Label(frame1,text='G 2-',foreground=color,font=myFont) labelG2.grid(row=13,column=0) labelF1=ttk.Label(frame1,text='F 1-',foreground=color,font=myFont) labelF1.grid(row=14,column=0) labelF2=ttk.Label(frame1,text='F 2-',foreground=color,font=myFont) labelF2.grid(row=15,column=0) label1=ttk.Label(frame1,textvariable=self.SV[0],font=myFont) label1.grid(row=0,column=1) label0=ttk.Label(frame1,textvariable=self.SV[2],font=myFont) label0.grid(row=1,column=1) label2=ttk.Label(frame1,textvariable=self.SV[3],font=myFont) label2.grid(row=3,column=1,sticky=W) label3=ttk.Label(frame1,textvariable=self.SV[4],font=myFont2) label3.grid(row=4,column=1,sticky=W) label3b=ttk.Label(frame1,textvariable=self.SV[15],font=myFont2) label3b.grid(row=5,column=1,sticky=W) label4=ttk.Label(frame1,textvariable=self.SV[5],font=myFont2) label4.grid(row=6,column=1,sticky=W) label5=ttk.Label(frame1,textvariable=self.SV[6],font=myFont2) label5.grid(row=7,column=1,sticky=W) label6=ttk.Label(frame1,textvariable=self.SV[7],font=myFont2) label6.grid(row=8,column=1,sticky=W) label7=ttk.Label(frame1,textvariable=self.SV[8],font=myFont2) label7.grid(row=9,column=1,sticky=W) label8=ttk.Label(frame1,textvariable=self.SV[9],font=myFont2) label8.grid(row=10,column=1,sticky=W) label9=ttk.Label(frame1,textvariable=self.SV[10],font=myFont2) label9.grid(row=11,column=1,sticky=W) label10=ttk.Label(frame1,textvariable=self.SV[11],font=myFont2) label10.grid(row=12,column=1,sticky=W) label11=ttk.Label(frame1,textvariable=self.SV[12],font=myFont2) label11.grid(row=13,column=1,sticky=W) label12=ttk.Label(frame1,textvariable=self.SV[13],font=myFont2) label12.grid(row=14,column=1,sticky=W) label13=ttk.Label(frame1,textvariable=self.SV[14],font=myFont2) label13.grid(row=15,column=1,sticky=W) frame2=ttk.LabelFrame(fenetre,text='More') frame2['padding']=(30,10) frame2.grid(row=1,sticky=(N,S,W,E)) bouton1=Button(frame2,textvariable=self.SV[1],bg=color,fg='white',width=10,font=myFont3,command=self.goBack) bouton1.grid(row=1,sticky=(W)) fenetre.rowconfigure(0,weight=3) fenetre.rowconfigure(1,weight=1) fenetre.columnconfigure(0,weight=1) self.checklanguage() class mainWindow(baseWindow): def __init__(self,root): self.getDataFromDB_By_Country() countryNames=self.countryNames data=self.data self.configs=self.getConfigs() self.root=root fenetre=root fenetre.iconbitmap('pics/icon2.ico') #root.minsize(300, 400) fenetre.title('Main Window') self.language=[['Choose a country','Choisissez un pays'], ['Death:','Mort:'],['Confirmed:','Confirmé:'],['Recovered:','Rétabli:'], [' Preventions ',' Préventions '],['Last updated:','Dernier mise a jour:'],['More','Plus'],[' Symptoms ',' Symptômes '],[' Graphs ',' Graphes '],[' Map ',' Carte ']] self.initSV() fenetre.option_add('#tearOff',FALSE) menubar = Menu(fenetre) fenetre['menu'] = menubar menu_file = Menu(menubar, tearoff=0) menu_edit = Menu(menubar, tearoff=0) menu_about = Menu(menubar, tearoff=0) menubar.add_cascade(menu=menu_file,label= 'File') menubar.add_cascade(menu=menu_edit,label = 'Edit') menubar.add_cascade(menu=menu_about,label = 'About') menu_file.add_command(label='Export Data',command=self.export) menu_file.add_command(label='Exit',command=root.destroy) menu_font = Menu(menu_edit, tearoff=0)#sous menus menu_font.add_command(label='Size',command=lambda:self.createWindow(sizeWindow)) menu_font.add_command(label='Colors',command=lambda:self.createWindow(colorWindow)) menu_language=Menu(menu_edit,tearoff=0) menu_language.add_command(label='Francais',command=self.french) menu_language.add_command(label='English',command=self.english) menu_edit.add_cascade(menu=menu_font,label='Font') menu_edit.add_command(label='Reset settings',command=self.resetPrompt) menu_edit.add_cascade(menu=menu_language,label='Language') menu_about.add_command(label='Feedback',command=lambda:self.createWindow(feedbackWindow)) menu_about.add_command(label='Help',command=lambda:self.createWindow(introWindow)) menu_about.add_command(label='Version 1.0') super().setStyle() btnColor=self.configs['color'] frame2=ttk.Frame(fenetre) frame2.grid(row=0,column=0,sticky=(N,S,W,E)) frame2['padding']=(30,10) self.label5=ttk.Label(frame2,textvariable=self.SV[0]) self.label5.grid(row=2,column=1,columnspan=2,sticky=(N),pady=6) self.cb=ttk.Combobox(frame2,values=countryNames, state="readonly") self.cb.bind('<<ComboboxSelected>>', self.cbModified) self.cb.grid(row=3,column=1,columnspan=2,sticky=(W,E),pady=2) self.label1=ttk.Label(frame2,textvariable=self.SV[1],foreground='black') self.label2=ttk.Label(frame2,textvariable=self.SV[2],foreground='black') self.label3=ttk.Label(frame2,textvariable=self.SV[3],foreground='black') self.label1.grid(row=4,column=1,sticky=E,pady=2) self.label2.grid(row=5,column=1,sticky=E,pady=2) self.label3.grid(row=6,column=1,sticky=E,pady=2) self.labelDeaths=ttk.Label(frame2,text='') self.labelConfirmed=ttk.Label(frame2,text='') self.labelRecovered=ttk.Label(frame2,text='') self.labelDeaths.grid(row=4,column=2,sticky=W,pady=2) self.labelConfirmed.grid(row=5,column=2,sticky=W,pady=2) self.labelRecovered.grid(row=6,column=2,sticky=W,pady=2) frame3=ttk.LabelFrame(fenetre,text='More') frame3.grid(row=1,column=0,sticky=(N,S,W,E)) frame3['padding']=(30,10) photo = PhotoImage(file = "pics/ploticon.png") self.plotimg = photo.subsample(2, 2) photo = PhotoImage(file = "pics/tableicon.png") self.tableimg = photo.subsample(2, 2) photo = PhotoImage(file = "pics/preventionsicon.png") self.preventionsimg = photo.subsample(2, 2) photo = PhotoImage(file = "pics/symptomsicon.png") self.symptomsimg = photo.subsample(2, 2) photo = PhotoImage(file = "pics/mapicon.png") self.mapimg = photo.subsample(2, 2) self.button1=Button(frame3,textvariable=self.SV[4], image = self.preventionsimg,compound=LEFT,command=lambda:self.createWindow(preventionsWindow))# self.button1.grid(row=0,column=0,sticky=(W,E),padx=2,pady=2) self.button2=Button(frame3,textvariable=self.SV[8], image = self.plotimg,compound=LEFT,command=lambda:self.createWindow(plotGraphs)) self.button2.grid(row=1,column=0,sticky=(W,E),padx=2,pady=2) self.button3=Button(frame3,textvariable=self.SV[7], image = self.symptomsimg,compound=LEFT,command=lambda:self.createWindow(symptomsWindow)) self.button3.grid(row=0,column=1,sticky=(W,E),padx=2,pady=2) self.button4=Button(frame3,text=' Table ',image = self.tableimg, compound=LEFT, command=lambda:self.createWindow(tableWindow)) self.button4.grid(row=1,column=1,sticky=(W,E),padx=2,pady=2) self.button5=Button(frame3,textvariable=self.SV[9],image = self.mapimg, compound=LEFT,command=lambda:self.createWindow(MapWindow)) self.button5.grid(row=2,column=0,columnspan=2,sticky=(W,E),padx=2,pady=2) self.labellastmoddate=ttk.Label(frame3,textvariable=self.SV[5],foreground='#333333') self.labellastmoddate.grid(row=3,column=0,columnspan=2,pady=2) self.labellastmoddate2=ttk.Label(frame3,text=data[0][-1].split('Last updated: ')[1],foreground='#333333') self.labellastmoddate2.grid(row=4,column=0,columnspan=2) self.cb.set(countryNames[0]) self.labelDeaths['text'] =str(data[0][2]) self.labelConfirmed['text'] = str(data[0][3]) self.labelRecovered['text'] = str(data[0][4]) fenetre.columnconfigure(0, weight=1) fenetre.rowconfigure(0, weight=3) fenetre.rowconfigure(1, weight=1) frame2.rowconfigure(2,weight=1) frame2.rowconfigure(3,weight=1) frame2.rowconfigure(4,weight=1) frame2.rowconfigure(5,weight=1) frame2.rowconfigure(6,weight=1) frame2.columnconfigure(1, weight=1) frame2.columnconfigure(2, weight=1) frame3.rowconfigure(1,weight=1) frame3.rowconfigure(2,weight=1) frame3.rowconfigure(3,weight=1) frame3.columnconfigure(0, weight=1) frame3.columnconfigure(1, weight=1) self.english() self.updateFont() def createWindow(self,Window): #tableWindow preventionsWindow feedbackWindow introWindow symptomsWindow Window(self) def french(self): self.configs['language']='french' super().french() def english(self): self.configs['language']='english' super().english() def export(self): country=self.cb.get() death=self.labelDeaths['text'] confirmed=self.labelConfirmed['text'] recovered=self.labelRecovered['text'] parag=country+":\n\nDeath: "+str(death)+"\nConfirmed: "+str(confirmed)+"\nRecovered: "+str(recovered)+'\n\nData Generated from Python Script(TP Info3)' file_path=filedialog.asksaveasfilename(initialfile='countryInfo.txt',defaultextension=".txt",filetypes=[("Text Documents","*.txt")]) if file_path: f=open(file_path,'w') f.write(parag) f.close() #data: id country death confirmed recovered lastchecked def cbModified(self,event): countryname=self.cb.get() for elm in self.data: if elm[1]==countryname: self.labelDeaths['text'] =str(elm[2]) self.labelConfirmed['text'] = str(elm[3]) self.labelRecovered['text'] = str(elm[4]) def resetPrompt(self): answer = messagebox.askyesno("Warning","Reset seetings?") if answer==True: self.setConfigs(('color','#70b570')) self.setConfigs(('fontSize',16)) self.updateFont() def updateFont(self): Labels=[self.label1,self.label2,self.label3,self.labelDeaths,self.labelRecovered,self.labelConfirmed] fontSize=self.configs['fontSize'] color=self.configs['color'] myFont = font.Font(self.root,size=fontSize,weight='bold') myFont2 = font.Font(self.root,size=fontSize-7) myFont3 = font.Font(self.root,size=fontSize) for elm in Labels: elm['font']=myFont self.labelDeaths['foreground']=color self.labelRecovered['foreground']=color self.labelConfirmed['foreground']=color self.labellastmoddate['font']=myFont2 self.labellastmoddate2['font']=myFont2 self.button1.config(bg=color,fg='white',font=myFont2) self.button2.config(bg=color,fg='white',font=myFont2) self.button3.config(bg=color,fg='white',font=myFont2) self.button4.config(bg=color,fg='white',font=myFont2) self.button5.config(fg=color,bg='white',font=myFont2) self.label5.config(font=myFont3) def getConfigs(self): with open('configs.txt','rb') as f: a=pickle.load(f) a['language']='english' return a #color fontSize language def setConfigs(self,value): #type(value)=tuple (param,newValue) if value[0]=='color' or value[0]=='fontSize' or value[0]=='language': self.configs[value[0]]=value[1] open('configs.txt', 'w').close() with open('configs.txt', 'wb') as f: pickle.dump(self.configs, f) def getDataFromDB_By_Country(self): self.countryNames=[] conn = create_connection() with conn: self.data=select_by_country(conn,'ASC') for elm in self.data: self.countryNames.append(elm[1]) #elm[1]=countryName class tableWindow(baseWindow): def __init__(self,mainWindowInstance): self.mainWindowInstance=mainWindowInstance self.root=mainWindowInstance.root root=mainWindowInstance.root fenetre=Toplevel(root) self.fenetre=fenetre fenetre.title('TableView') self.setIcon() self.language=[["Country",'Pays'],['Deaths','Mort'],['Confirmed','Confirmé'],['Recovered','Rétabli']] self.initSV() self.checklanguage() self.countryOrder='DESC' self.deathsOrder='DESC' self.confirmedOrder='DESC' self.recoveredOrder='DESC' frame=ttk.Frame(fenetre) frame.grid(sticky='nswe') fenetre.columnconfigure(0, weight=1) fenetre.rowconfigure(0, weight=1) tree=ttk.Treeview(frame) tree.pack(side='left',expand=True,fill='both') vsb = ttk.Scrollbar(frame, orient="vertical", command=tree.yview) vsb.pack(side='right',fill='y') tree.configure(yscrollcommand=vsb.set) tree["columns"]=("one","two","three") tree.column("#0",minwidth=200) tree.column("one",minwidth=150) tree.column("two",minwidth=150) tree.column("three",minwidth=150) tree.heading("#0",text=self.SV[0].get(),anchor=W,command=self.countryListener) tree.heading("one", text=self.SV[1].get(),anchor=W,command=self.deathsListener) tree.heading("two", text=self.SV[2].get(),anchor=W,command=self.confirmedListener) tree.heading("three", text=self.SV[3].get(),anchor=W,command=self.recoveredListener) self.tree=tree self.countryListener() def countryListener(self): self.tree.delete(*self.tree.get_children()) if self.countryOrder=="ASC": self.countryOrder="DESC" else: self.countryOrder="ASC" conn=create_connection() with conn: self.country=select_by_country(conn,self.countryOrder) for elm in self.country: self.tree.insert('', 'end', text=elm[1],values=(elm[2],elm[3],elm[4])) def deathsListener(self): self.tree.delete(*self.tree.get_children()) if self.deathsOrder=="ASC": self.deathsOrder="DESC" else: self.deathsOrder="ASC" conn=create_connection() with conn: self.deaths=select_by_deaths(conn,self.deathsOrder) for elm in self.deaths: self.tree.insert('', 'end', text=elm[1],values=(elm[2],elm[3],elm[4])) def confirmedListener(self): self.tree.delete(*self.tree.get_children()) if self.confirmedOrder=="ASC": self.confirmedOrder="DESC" else: self.confirmedOrder="ASC" conn=create_connection() with conn: self.confirmed=select_by_confirmed(conn,self.confirmedOrder) for elm in self.confirmed: self.tree.insert('', 'end', text=elm[1],values=(elm[2],elm[3],elm[4])) def recoveredListener(self): self.tree.delete(*self.tree.get_children()) if self.recoveredOrder=="ASC": self.recoveredOrder="DESC" else: self.recoveredOrder="ASC" conn=create_connection() with conn: self.recovered=select_by_recovered(conn,self.recoveredOrder) for elm in self.recovered: self.tree.insert('', 'end', text=elm[1],values=(elm[2],elm[3],elm[4])) class feedbackWindow(baseWindow): def __init__(self,mainWindowInstance): self.initTopWindows(mainWindowInstance,'Feedback') root=self.root fenetre=self.fenetre color=mainWindowInstance.configs['color'] fontSize=mainWindowInstance.configs['fontSize'] myFont = font.Font(fenetre,size=fontSize) myFont2 = font.Font(fenetre,size=fontSize-7) self.language=[['Name:','Prenom:'],['Submit','Soumettre'],['Go back','Retour']] self.initSV() frame1 = ttk.Frame(fenetre,padding=(30,30),style='new.TFrame') frame1.grid(column=0,row=0,sticky=(N,S,W,E)) photo = PhotoImage(file = "pics/nameicon.png") self.nameimg = photo.subsample(2, 2) photo = PhotoImage(file = "pics/emailicon.png") self.emailimg = photo.subsample(2, 2) photo = PhotoImage(file = "pics/msgicon.png") self.msgimg = photo.subsample(2, 2) photo = PhotoImage(file = "pics/submiticon.png") self.submitimg = photo.subsample(2, 2) label1=ttk.Label(frame1,textvariable =self.SV[0],image = self.nameimg, compound=LEFT,font=myFont,style='new.TLabel') label1.grid(row=1,column=1,sticky=(W)) self.entry1 = ttk.Entry(frame1) self.entry1.grid(row=2,column=1,sticky=(N,S,E,W)) label2=ttk.Label(frame1,text = 'Email :',image = self.emailimg, compound=LEFT,font=myFont,style='new.TLabel') label2.grid(row=3,column=1,sticky=(W)) self.entry2 = ttk.Entry(frame1) self.entry2.grid(row=4,column=1,sticky=(N,S,E,W)) label3=ttk.Label(frame1,text = 'Message :',image = self.msgimg, compound=LEFT,font=myFont,style='new.TLabel') label3.grid(row=5,column=1,sticky=(W)) self.entry3 = Text(frame1,width=30,height=10) self.entry3.grid(row=6,column=1,sticky=(N,S,E,W)) frame2 = ttk.Frame(fenetre,padding=(20,20),style='new.TFrame') frame2.grid(column=0,row=1,sticky=(N,S,W,E)) self.starwhite = PhotoImage(file = "pics/star.png") self.starorange = PhotoImage(file = "pics/starorange.png") self.starcount='' self.btn1star=Button(frame2, image = self.starwhite,relief='flat',command=lambda:self.stardef(1)) self.btn1star.grid(row=0,column=1,sticky=(W,E)) self.btn2star=Button(frame2, image = self.starwhite,relief='flat',command=lambda:self.stardef(2)) self.btn2star.grid(row=0,column=2,sticky=(W,E)) self.btn3star=Button(frame2, image = self.starwhite,relief='flat',command=lambda:self.stardef(3)) self.btn3star.grid(row=0,column=3,sticky=(W,E)) self.btn4star=Button(frame2, image = self.starwhite,relief='flat',command=lambda:self.stardef(4)) self.btn4star.grid(row=0,column=4,sticky=(W,E)) self.btn5star=Button(frame2, image = self.starwhite,relief='flat',command=lambda:self.stardef(5)) self.btn5star.grid(row=0,column=5,sticky=(W,E)) frame3 = ttk.Frame(fenetre,padding=(20,20),style='new.TFrame') frame3.grid(column=0,row=2,sticky=(N,S,W,E)) self.submit_button=Button(frame3, textvariable =self.SV[1],bg=color,fg='white',height=25,font=myFont2,command=self.SubmitForm,image = self.submitimg, compound=RIGHT) self.submit_button.grid(row=1,column=1,sticky=(W,E),pady=5) backbtn=Button(frame3, textvariable =self.SV[2],bg=color,fg='white',font=myFont2,command=self.goBack) backbtn.grid(row=2,column=1,sticky=(W,E),pady=5) fenetre.columnconfigure(0, weight=1) fenetre.rowconfigure(0, weight=6) fenetre.rowconfigure(1, weight=1) fenetre.rowconfigure(2, weight=2) frame1.rowconfigure(2,weight=1) frame1.rowconfigure(3,weight=1) frame1.rowconfigure(4,weight=1) frame1.rowconfigure(5,weight=1) frame1.rowconfigure(6,weight=1) frame1.columnconfigure(1, weight=1) frame2.rowconfigure(0,weight=1) frame2.columnconfigure(1, weight=1) frame2.columnconfigure(2, weight=1) frame2.columnconfigure(3, weight=1) frame2.columnconfigure(4, weight=1) frame2.columnconfigure(5, weight=1) self.checklanguage() frame3.rowconfigure(1,weight=1) frame3.rowconfigure(2,weight=1) frame3.columnconfigure(1, weight=1) def SubmitForm(self): name=self.entry1.get() email=self.entry2.get() themsg=self.entry3.get("1.0","end-1c") if name!='' and email!='' and themsg!='' and self.starcount!='': response=posttoserver(name,email,themsg,self.starcount) if response=='done': messagebox.showinfo("Information","Your feedback was sent successfully!") else: messagebox.showerror("Error", 'Could not send the feedback') else: messagebox.showerror("Error", 'empty fields') def stardef(self,n): self.starcount=n btns=[self.btn1star,self.btn2star,self.btn3star,self.btn4star,self.btn5star] for elm in btns: elm['image']=self.starwhite for i in range(n): btns[i]['image']=self.starorange class sizeWindow(baseWindow): def __init__(self,mainWindowInstance): self.initTopWindows(mainWindowInstance,'Choose font size') root=self.root fenetre=self.fenetre color=mainWindowInstance.configs['color'] fontSize=mainWindowInstance.configs['fontSize'] myFont = font.Font(fenetre,size=fontSize) self.language=[['Choose a font size:','Choisir une taille de police:'],[' Apply ',' Postuler '],[' Go back ',' Retour '],[' Preview ',' Apercu ']] self.initSV() frame1 = ttk.Frame(fenetre,padding=(15,15),style='new.TFrame') frame1.grid() label1=ttk.Label(frame1,textvariable=self.SV[0],style='new.TLabel') label1.grid(row=0,column=2,columnspan=2) self.scale=Scale(frame1,from_=5,to=30,orient=HORIZONTAL,command=self.updatevalue) self.scale.grid(row=1,column=2,columnspan=2,pady=5) initValue=mainWindowInstance.configs['fontSize'] self.scale.set(initValue) self.labelPreview=ttk.Label(frame1,textvariable=self.SV[3],font=myFont,style='new.TLabel') self.labelPreview.grid(row=2,column=2,columnspan=2,pady=5) bouton1=Button(frame1,textvariable=self.SV[1],fg='white',bg=color,width=10,command=self.applyFont) bouton1.grid(row=3,column=2,sticky=(W,E),padx=5,pady=5) bouton2=Button(frame1,textvariable=self.SV[2],fg='white',bg=color,width=10,command=self.goBack) bouton2.grid(row=3,column=3,sticky=(W,E),padx=5,pady=5) fenetre.columnconfigure(0, weight=1) fenetre.rowconfigure(0, weight=1) self.checklanguage() def updatevalue(self,event): self.labelPreview['font']=font.Font(self.fenetre,size=self.scale.get()) def applyFont(self): value=self.scale.get() self.mainWindowInstance.setConfigs(('fontSize',value)) self.mainWindowInstance.updateFont() self.goBack() class colorWindow(baseWindow): def __init__(self,mainWindowInstance): self.initTopWindows(mainWindowInstance,'choose font Color') root=self.root fenetre=self.fenetre color=mainWindowInstance.configs['color'] fontSize=mainWindowInstance.configs['fontSize'] frame1 = ttk.Frame(fenetre,padding=(15,15),style='new.TFrame') frame1.grid() self.language=[['Choose a color','Choisir la couleur'],[' Apply ',' Postuler '],[' Go back ',' Retour '],[' Preview ',' Apercu ']] self.initSV() label1=ttk.Label(frame1,textvariable=self.SV[0],style='new.TLabel') label1.grid(row=0,column=2,columnspan=2,pady=5) bouton3=ttk.Button(frame1,textvariable=self.SV[0], command=self.getColor) bouton3.grid(row=2,column=2,columnspan=2,pady=5) initValue=mainWindowInstance.configs['color'] self.labelPreview=ttk.Label(frame1,textvariable=self.SV[3],font=('bold'),style='new.TLabel',foreground=initValue) self.labelPreview.grid(row=3,column=2,columnspan=2,pady=5) bouton1=Button(frame1,textvariable=self.SV[1],fg='white',bg=color,width=10,command=self.setColor) bouton1.grid(row=4,column=2,sticky=(W,E),padx=5,pady=5) bouton2=Button(frame1,textvariable=self.SV[2],fg='white',bg=color,width=10,command=self.goBack) bouton2.grid(row=4,column=3,sticky=(W,E),padx=5,pady=5) fenetre.columnconfigure(0, weight=1) fenetre.rowconfigure(0, weight=1) self.checklanguage() def getColor(self): color = askcolor() self.labelPreview['foreground']=color[1] def setColor(self): value=str(self.labelPreview['foreground']) self.mainWindowInstance.setConfigs(('color',value)) self.mainWindowInstance.updateFont() self.goBack() class preventionsWindow(baseWindow): def __init__(self,mainWindowInstance): self.initTopWindows(mainWindowInstance,'Preventions') root=self.root fenetre=self.fenetre fontSize=mainWindowInstance.configs['fontSize'] color=mainWindowInstance.configs['color'] myFont = font.Font(fenetre,size=fontSize,weight='bold') myFont2 = font.Font(fenetre,size=fontSize-2) self.language=[['Keep','Garder'],['a safe distance','une distance de sécurité'], ['Wash','Se laver'],['your hands often','les mains souvent'], ['Cover','Couvrir'],['your cough more','votre toux plus'],['Stay','Rester'],['home as much as you can','à la maison autant que possible'], [' Go back ',' Retour ']] self.initSV() frame3=ttk.Frame(fenetre) frame3.grid(row=0,column=0,sticky=(N,S,W,E)) frame3['padding']=(30,10) label5=ttk.Label(frame3,text='1-',font=myFont,foreground=color) label5.grid(row=2,column=1) label8=ttk.Label(frame3,textvariable=self.SV[6],font=myFont,foreground='black') label8.grid(row=2,column=2) label9=ttk.Label(frame3,textvariable=self.SV[7],font=myFont2,foreground='black') label9.grid(row=2,column=3,sticky=W) label6=ttk.Label(frame3,text='2-',font=myFont,foreground=color) label6.grid(row=3,column=1) label10=ttk.Label(frame3,textvariable=self.SV[0],font=myFont,foreground='black') label10.grid(row=3,column=2) label11=ttk.Label(frame3,textvariable=self.SV[1],font=myFont2,foreground='black') label11.grid(row=3,column=3,sticky=W) label7=ttk.Label(frame3,text='3-',font=myFont,foreground=color) label7.grid(row=4,column=1) label12=ttk.Label(frame3,textvariable=self.SV[2],font=myFont,foreground='black') label12.grid(row=4,column=2) label13=ttk.Label(frame3,textvariable=self.SV[3],font=myFont2,foreground='black') label13.grid(row=4,column=3,sticky=W) label16=ttk.Label(frame3,text='4-',font=myFont,foreground=color) label16.grid(row=5,column=1) label14=ttk.Label(frame3,textvariable=self.SV[4],font=myFont,foreground='black') label14.grid(row=5,column=2) label15=ttk.Label(frame3,textvariable=self.SV[5],font=myFont2,foreground='black') label15.grid(row=5,column=3,sticky=W) frame4=ttk.LabelFrame(fenetre,text='More') frame4['padding']=(30,10) frame4.grid(row=1,column=0,sticky=(N,S,W,E)) button=Button(frame4,textvariable=self.SV[8],bg=color,fg='white',font=myFont2,command=self.goBack) button2=Button(frame4,text='Hotline',bg=color,fg='white',font=myFont2,command=self.createLocationWindow) button.grid(row=0,column=0,sticky=(W,E),padx=2,pady=2) button2.grid(row=0,column=1,sticky=(W,E),padx=2,pady=2) fenetre.columnconfigure(0, weight=1) fenetre.rowconfigure(0, weight=3) fenetre.rowconfigure(1, weight=1) frame3.rowconfigure(2,weight=1) frame3.rowconfigure(3,weight=1) frame3.rowconfigure(4,weight=1) frame3.rowconfigure(5,weight=1) frame3.columnconfigure(1, weight=1) frame3.columnconfigure(2, weight=1) frame3.columnconfigure(3, weight=1) frame4.rowconfigure(0,weight=1) frame4.columnconfigure(0, weight=1) frame4.columnconfigure(1, weight=1) self.checklanguage() def createLocationWindow(self): self.configs=self.mainWindowInstance.configs locationWindow(self) class locationWindow(baseWindow): def __init__(self,preventionsWindow): self.preventionsWindow=preventionsWindow self.root=preventionsWindow.fenetre root=self.root self.fenetre=Toplevel(root) fenetre=self.fenetre root.withdraw() self.setIcon() fenetre.title('Location') self.fenetre.protocol('WM_DELETE_WINDOW', preventionsWindow.root.destroy) fontSize=preventionsWindow.configs['fontSize'] color=preventionsWindow.configs['color'] myFont = font.Font(fenetre,size=fontSize-1,weight='bold') myFont2 = font.Font(fenetre,size=fontSize,weight='bold') myFont3 = font.Font(fenetre,size=fontSize-2) self.language=[['Your location is:','Votre emplacement est a:'],['More','Plus'],['Go back','Retour']] self.initSV() fenetre.title('Hotline') frame6=ttk.Frame(fenetre) frame6.grid(row=0,column=0,sticky=(N,S,W,E)) frame6['padding']=(30,10) label2=ttk.Label(frame6,textvariable=self.SV[0],font=myFont) label2.grid(row=0,column=0,sticky=(N)) LabelCountry=ttk.Label(frame6,text=Location.country,foreground=color,font=myFont2) LabelCountry.grid(row=1,column=0,sticky=(N)) self.LabelNumbers=ttk.Label(frame6,text='',font=myFont3) self.LabelNumbers.grid(row=2,column=0,sticky=(N)) frame7=ttk.LabelFrame(fenetre,text='More') frame7.grid(row=1,column=0,sticky=(N,S,W,E)) frame7['padding']=(30,10) button1=Button(frame7,textvariable=self.SV[2],bg=color,fg='white',width=10,font=myFont3,command=self.goBack) button1.grid(sticky=(W)) fenetre.columnconfigure(0, weight=1) fenetre.rowconfigure(0, weight=3) fenetre.rowconfigure(1, weight=1) frame6.columnconfigure(0, weight=1) frame6.rowconfigure(0,weight=1) frame6.rowconfigure(1,weight=1) frame6.rowconfigure(2,weight=1) frame7.rowconfigure(0,weight=1) frame7.columnconfigure(0, weight=1) self.checklanguage() self.getPhoneNumbers() def getPhoneNumbers(self): with open('phoneNumbers.txt','rb') as f: PhoneNumbers= pickle.load(f) selectedCountryNumbers=PhoneNumbers[Location.country] police=selectedCountryNumbers['police'] ambulance=selectedCountryNumbers['ambulance'] fire=selectedCountryNumbers['fire'] self.LabelNumbers['text']='Police: '+police+' Ambulance: '+ambulance+' Fire: '+fire class symptomsWindow(baseWindow): def __init__(self,mainWindowInstance): self.initTopWindows(mainWindowInstance,'Symptoms') root=self.root fenetre=self.fenetre fontSize=mainWindowInstance.configs['fontSize'] color=mainWindowInstance.configs['color'] myFont = font.Font(fenetre,size=fontSize+2,weight='bold') myFont2 = font.Font(fenetre,size=fontSize) myFont3 = font.Font(fenetre,size=fontSize-7) self.language=[['Common symptoms:','Symptomes communs:'],['Fever','Fièvre'],['Tiredness','Fatigue'], ['Dry cough','Toux sèche'],['Some people may experience:','Certaines personnes peuvent éprouver:'], ['Aches and pains','Maux et douleurs'],['Nasal congestion','Congestion nasale'], ['Runny nose','Nez qui coule'],['Sore throat','Gorge irritée'],['Diarrhoea','Diarhée'], ['On average it takes 5–6 days from when someone is infected',"Cela prend en moyenne 5-6 jours à partir du moment ou quelqu'un est infecté"], ['with the virus for symptoms to show, however it can take up to 14 days',"avec le virus pour que les symptomes apparaissent ,mais cela peut prendre jusqu'a 14 jours"], ['Back','Retourner']] self.initSV() frame2=ttk.Frame(fenetre,padding=(30,10)) frame2.grid(row=0,column=0,sticky=(N,W,S,E)) label1=ttk.Label(frame2,text='A-',font=myFont,foreground=color) label1.grid(row=0,column=0,sticky=(W)) label2=ttk.Label(frame2,textvariable=self.SV[0],font=myFont) label2.grid(row=0,column=1,sticky=W) label3=ttk.Label(frame2,text='1-',foreground=color,font=myFont2) label3.grid(row=1,column=0,sticky=W) label4=ttk.Label(frame2,textvariable=self.SV[1],font=myFont2)# label4.grid(row=1,column=1,sticky=W) label4=ttk.Label(frame2,text='2-',foreground=color,font=myFont2) label4.grid(row=2,column=0,sticky=W) label5=ttk.Label(frame2,textvariable=self.SV[2],font=myFont2)# label5.grid(row=2,column=1,sticky=W) label20=ttk.Label(frame2,text='3-',foreground=color,font=myFont2) label20.grid(row=3,column=0,sticky=W) label7=ttk.Label(frame2,textvariable=self.SV[3],font=myFont2)# label7.grid(row=3,column=1,sticky=W) label9=ttk.Label(frame2,text='B-',font=myFont,foreground=color) label9.grid(row=4,column=0,sticky=W) label8=ttk.Label(frame2,textvariable=self.SV[4],font=myFont) label8.grid(row=4,column=1,sticky=W) label15=ttk.Label(frame2,text='1-',foreground=color,font=myFont2) label15.grid(row=5,column=0,sticky=W) label10=ttk.Label(frame2,textvariable=self.SV[5],font=myFont2)# label10.grid(row=5,column=1,sticky=W) label16=ttk.Label(frame2,text='2-',foreground=color,font=myFont2) label16.grid(row=6,column=0,sticky=W) label11=ttk.Label(frame2,textvariable=self.SV[6],font=myFont2)# label11.grid(row=6,column=1,sticky=W) label17=ttk.Label(frame2,text='3-',foreground=color,font=myFont2) label17.grid(row=7,column=0,sticky=W) label12=ttk.Label(frame2,textvariable=self.SV[7],font=myFont2)# label12.grid(row=7,column=1,sticky=W) label18=ttk.Label(frame2,text='4-',foreground=color,font=myFont2) label18.grid(row=8,column=0,sticky=W) label13=ttk.Label(frame2,textvariable=self.SV[8],font=myFont2)# label13.grid(row=8,column=1,sticky=W) label19=ttk.Label(frame2,text='5-',foreground=color,font=myFont2) label19.grid(row=9,column=0,sticky=W) label14=ttk.Label(frame2,textvariable=self.SV[9],font=myFont2)# label14.grid(row=9,column=1,sticky=W) label22=ttk.Label(frame2,text='C-',font=myFont,foreground=color) label22.grid(row=10,column=0,sticky=W) label21=ttk.Label(frame2,textvariable=self.SV[10],font=myFont) label21.grid(row=10,column=1,sticky=W) label24=ttk.Label(frame2,textvariable=self.SV[11],font=myFont) label24.grid(row=11,column=1,sticky=W) frame3=ttk.Labelframe(fenetre,text='More') frame3.grid(row=1,column=0,sticky=(N,S,W,E)) frame3['padding']=(30,10) button1=Button(frame3,textvariable=self.SV[12],fg='white',bg=color,width=10,font=myFont3,command=self.goBack) button1.grid(row=0,column=0,columnspan=2,sticky=(W)) fenetre.columnconfigure(0, weight=1) fenetre.rowconfigure(0, weight=3) fenetre.rowconfigure(1, weight=1) frame2.rowconfigure(0,weight=1) frame2.rowconfigure(1,weight=1) frame2.rowconfigure(2,weight=1) frame2.rowconfigure(3,weight=1) frame2.rowconfigure(4,weight=1) frame2.rowconfigure(5,weight=1) frame2.rowconfigure(6,weight=1) frame2.rowconfigure(7,weight=1) frame2.rowconfigure(8,weight=1) frame2.rowconfigure(9,weight=1) frame2.rowconfigure(10,weight=1) frame2.rowconfigure(11,weight=1) frame2.columnconfigure(0, weight=1) frame2.columnconfigure(1, weight=1) frame3.rowconfigure(0,weight=1) frame3.rowconfigure(0, weight=1) self.checklanguage() def plotGraphs(mainWindowInstance): color=mainWindowInstance.configs['color'] plt.figure(figsize=(9,7)) plt.gcf().canvas.set_window_title('Graph Top5') data1=[] data2=[] data3=[] conn = create_connection() with conn: data1=select_top5_deaths(conn) data2=select_top5_confirmed(conn) data3=select_top5_recovered(conn) columns = list(zip(*data1)) countryNamesForDeathsDESC=columns[0] deathsDESC=columns[1] ay1 = plt.subplot(221) ax1=plt.bar(countryNamesForDeathsDESC,deathsDESC) plt.title('Top 5 Deaths') for elm in ax1: elm.set_color(color) ################################# columns = list(zip(*data2)) countryNamesForConfirmedDESC=columns[0] confirmedDESC=columns[1] y2=plt.subplot(212) ax2=plt.bar(countryNamesForConfirmedDESC,confirmedDESC) plt.ylabel('Top 5 Confirmed') for elm in ax2: elm.set_color(color) ################################# columns = list(zip(*data3)) countryNamesForRecoveredDESC=columns[0] recoveredDESC=columns[1] ay3=plt.subplot(222) ax3=plt.bar(countryNamesForRecoveredDESC,recoveredDESC) plt.title('Top 5 Recovered') for elm in ax3: elm.set_color(color) plt.show() class MapWindow(baseWindow): def __init__(self,mainWindowInstance): self.initTopWindows(mainWindowInstance,'Map Top5') root=self.root fenetre=self.fenetre fontSize=mainWindowInstance.configs['fontSize'] color=mainWindowInstance.configs['color'] myFont = font.Font(fenetre,size=fontSize-7) self.language=[[' Death ',' Mort '],[' Confirmed ',' Confirmé '],[' Recovered ',' Rétabli ']] self.initSV() frame1=Frame(fenetre) frame1.grid(row=0,column=0,sticky=(N,S,W,E)) self.canvas = Canvas(frame1,width=800,height=440) self.canvas.grid() img=PILImage.open("pics/map.png") self.imgrender = PILImageTk.PhotoImage(img) self.canvas.create_image(400,220,image=self.imgrender) self.canvas.image=self.imgrender frame2=ttk.LabelFrame(fenetre,text='More') frame2['padding']=(30,10) frame2.grid() btn1=Button(frame2,textvariable=self.SV[0],command=self.DeathsMarkers,bg=color,fg='white',font=myFont) btn1.grid(row=0,column=0,sticky=(W,E),padx=2,pady=2) btn2=Button(frame2,textvariable=self.SV[1],command=self.ConfirmedMarkers,bg=color,fg='white',font=myFont) btn2.grid(row=0,column=1,sticky=(W,E),padx=2,pady=2) btn3=Button(frame2,textvariable=self.SV[2],command=self.RecoveredMarkers,bg=color,fg='white',font=myFont) btn3.grid(row=0,column=2,sticky=(W,E),padx=2,pady=2) btn4=Button(frame2,text='Back',command=self.goBack,fg=color,bg='white',font=myFont) btn4.grid(row=1,column=0,columnspan=3,sticky=(W,E),padx=2,pady=2) self.LatLongDict=getLatLong() conn=create_connection() with conn: self.top5deaths=select_top5_deaths(conn) self.top5confirmed=select_top5_confirmed(conn) self.top5recovered=select_top5_recovered(conn) self.top5deaths=list(zip(*self.top5deaths))[0] self.top5confirmed=list(zip(*self.top5confirmed))[0] self.top5recovered=list(zip(*self.top5recovered))[0] self.Labels=[] self.checklanguage() def addMarker(self,lat,long,n=1,color='black'): lat=float(lat) long=float(long) widget = Label(self.canvas, text=n, fg='white', bg=color) y=-2.8008*lat+ 218.7668 x=2.2778*long+327.6441 self.canvas.create_window(x, y, window=widget) self.Labels.append(widget) def DeathsMarkers(self): self.deleteLabels() for i in range(len(self.top5deaths)): a=self.LatLongDict[self.top5deaths[i]] lat=a[1] long=a[2] self.addMarker(lat,long,i+1,'blue') widget = Label(self.canvas, textvariable=self.SV[0], fg='white', bg='blue') self.canvas.create_window(35, 20, window=widget) self.Labels.append(widget) def ConfirmedMarkers(self): self.deleteLabels() for i in range(len(self.top5confirmed)): a=self.LatLongDict[self.top5confirmed[i]] lat=a[1] long=a[2] self.addMarker(lat,long,i+1,'green') widget = Label(self.canvas, textvariable=self.SV[1], fg='white', bg='green') self.canvas.create_window(35, 20, window=widget) self.Labels.append(widget) def RecoveredMarkers(self): self.deleteLabels() for i in range(len(self.top5recovered)): a=self.LatLongDict[self.top5recovered[i]] lat=a[1] long=a[2] self.addMarker(lat,long,i+1,'orange') widget = Label(self.canvas, textvariable=self.SV[2], fg='white', bg='orange') self.canvas.create_window(35, 20, window=widget) self.Labels.append(widget) def deleteLabels(self): for elm in self.Labels: elm.destroy() if __name__ == "__main__": #Location.getLocation() root=Tk() mainWindow(root) root.mainloop()
37.245492
196
0.616705
753e8885bb96cf7132d33c19fa8069080a4c817c
416
swift
Swift
lab exercises/Lab01/UnitTests/TemperatureTests.swift
AboutObjectsTraining/swift-comp-reston-2017-01
d2e16dda3948b3048c9c041406144a932c61fa5b
[ "MIT" ]
null
null
null
lab exercises/Lab01/UnitTests/TemperatureTests.swift
AboutObjectsTraining/swift-comp-reston-2017-01
d2e16dda3948b3048c9c041406144a932c61fa5b
[ "MIT" ]
null
null
null
lab exercises/Lab01/UnitTests/TemperatureTests.swift
AboutObjectsTraining/swift-comp-reston-2017-01
d2e16dda3948b3048c9c041406144a932c61fa5b
[ "MIT" ]
null
null
null
import XCTest @testable import Lab01 //func convert(toCelsius: Double) -> Double { // // do something clever. // return 0.0 //} class TemperatureTests: XCTestCase { func testHelloWorld() { print("Hello World!") let s = String(format: "Temperature is %.1f°", convert(toCelsius:32.0)) print(s) } func testGoodbyeWorld() { print("Goodbye World!") } }
18.086957
79
0.588942
38d88983347fc10d92ce7282da7d746338c3f607
2,262
php
PHP
src/Traits/CanView.php
jaulz/laravel-acquaintances
4d0c5beaf2d669e66df10235c0b221ccc69cb125
[ "MIT" ]
null
null
null
src/Traits/CanView.php
jaulz/laravel-acquaintances
4d0c5beaf2d669e66df10235c0b221ccc69cb125
[ "MIT" ]
null
null
null
src/Traits/CanView.php
jaulz/laravel-acquaintances
4d0c5beaf2d669e66df10235c0b221ccc69cb125
[ "MIT" ]
null
null
null
<?php namespace Jaulz\Acquaintances\Traits; use Illuminate\Support\Facades\Event; use Jaulz\Acquaintances\Interaction; /** * Trait CanView. */ trait CanView { /** * View an item or items. * * @param int|array|\Illuminate\Database\Eloquent\Model $targets * @param string $class * * @return array * * @throws \Exception */ public function view($targets, $class = __CLASS__) { Event::dispatch('acq.views.view', [$this, $targets]); return Interaction::attachRelations($this, 'views', $targets, $class); } /** * Unview an item or items. * * @param int|array|\Illuminate\Database\Eloquent\Model $targets * @param string $class * * @return array */ public function unview($targets, $class = __CLASS__) { Event::dispatch('acq.views.unview', [$this, $targets]); return Interaction::detachRelations($this, 'views', $targets, $class); } /** * Toggle view an item or items. * * @param int|array|\Illuminate\Database\Eloquent\Model $targets * @param string $class * * @return array * * @throws \Exception */ public function toggleView($targets, $class = __CLASS__) { return Interaction::toggleRelations($this, 'views', $targets, $class); } /** * Check if a model has viewed a given model. * * @param int|array|\Illuminate\Database\Eloquent\Model $target * @param string $class * * @return bool */ public function hasViewed($target, $class = __CLASS__) { return Interaction::isRelationExists($this, 'views', $target, $class); } /** * Return item views. * * @param string $class * * @return \Illuminate\Database\Eloquent\Relations\MorphToMany */ public function views($class = __CLASS__) { return $this->morphedByMany($class, 'interactable', config('acquaintances.tables.interactions')) ->wherePivot('relation', '=', Interaction::RELATION_VIEW) ->withPivot(...Interaction::$pivotColumns) ->using(Interaction::getInteractionRelationModelName()); } }
25.133333
78
0.585323
2f366e5eb9cc228fc3a72ab89450500a76e3e49d
725
js
JavaScript
11_JS_Constructors/10_Classrooms/classroom.js
wdarsow/JavaScript-Practice
8ccc87aabf6bc976376fef764a771ad30c002b26
[ "MIT" ]
null
null
null
11_JS_Constructors/10_Classrooms/classroom.js
wdarsow/JavaScript-Practice
8ccc87aabf6bc976376fef764a771ad30c002b26
[ "MIT" ]
null
null
null
11_JS_Constructors/10_Classrooms/classroom.js
wdarsow/JavaScript-Practice
8ccc87aabf6bc976376fef764a771ad30c002b26
[ "MIT" ]
null
null
null
let Student = require('./student'); function ClassRoom(numStudents, profName, roomNum) { this.studentArray = []; this.numStudents = numStudents, this.profName = profName, this.roomNum = roomNum, this.addStudent = function(name, subject, gpa) { this.studentArray.push(new Student(name, subject, gpa)); this.numStudents++; // console.log("student array contains " + JSON.stringify(studentArray[0])); } } // ClassRoom(2); let fallClass = new ClassRoom(3, "Professor 2", 123); fallClass.addStudent("Jim", "math", 3.95); console.log("student array contains " + JSON.stringify(fallClass.studentArray[0])); console.log(fallClass.numStudents, fallClass.profName, fallClass.roomNum);
36.25
84
0.693793
44778e8b4fabbe63b8938bf8e8bca6342ace382a
3,792
py
Python
set2/challenge13.py
8u1a/my_matasano_crypto_challenges
0da1f7fc9445449d5d02867b659325ef5fe62c7d
[ "Unlicense" ]
null
null
null
set2/challenge13.py
8u1a/my_matasano_crypto_challenges
0da1f7fc9445449d5d02867b659325ef5fe62c7d
[ "Unlicense" ]
null
null
null
set2/challenge13.py
8u1a/my_matasano_crypto_challenges
0da1f7fc9445449d5d02867b659325ef5fe62c7d
[ "Unlicense" ]
null
null
null
__author__ = 'christianbuia' import random from Crypto.Cipher import AES def pkcs7_padding(message_bytes, block_size): pad_length = block_size - (len(message_bytes) % block_size) if pad_length != block_size: for i in range(0, pad_length): message_bytes += bytes([pad_length]) return message_bytes #----------------------------------------------------------------------------------------------------------------------- def generateRandom16bytes(): ints = [] for i in range(16): ints.append(random.randint(0,255)) return bytes(ints) #----------------------------------------------------------------------------------------------------------------------- #always 16 bytes def encrypt_aes128(message, key): decobj = AES.new(key, AES.MODE_ECB) return decobj.encrypt(pkcs7_padding(message, 16)) #----------------------------------------------------------------------------------------------------------------------- #always 16 bytes def decrypt_aes128(message, key): decobj = AES.new(key, AES.MODE_ECB) return strip_pkcs7_padding(decobj.decrypt(message), 16) #----------------------------------------------------------------------------------------------------------------------- def strip_pkcs7_padding(message, blocksize): number_of_blocks = len(message) / blocksize for i in range(1,blocksize): clean = True for j in range(i): if message[int(blocksize*(number_of_blocks-1) + (blocksize - 1 - j))] != i: clean=False if clean == True: return message[:-i] return message #----------------------------------------------------------------------------------------------------------------------- def parseKV(message): kv_dict = {} pairs = message.split("&") for p in pairs: items = p.split("=") kv_dict[items[0]] = items[1] return kv_dict #----------------------------------------------------------------------------------------------------------------------- def profile_for(email_address, uid=10, role='user'): if "@" not in email_address: print("not a valid email...quitting.") exit(1) email_address = email_address.replace("&", "").replace("=", "") return "email=" + email_address + "&uid=" + str(uid) + "&role=" + role #----------------------------------------------------------------------------------------------------------------------- def profile_for_encrypted(email_address, key, uid=10, role='user'): return encrypt_aes128(bytes(profile_for(email_address, uid, role), "ascii"), key) #----------------------------------------------------------------------------------------------------------------------- #*********************************************************************************************************************** ckey = generateRandom16bytes() #the admin block we want looks like this: #admin\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b #and we can snag that by making this the beginning of our email address, e.g.: #AAAAAAAAAAadmin\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b@bar.com #and grabbing the second block (since the first block will be "email=AAAAAAAAAA") #and then this can be appended to a message that is an exact multiple of block size, e.g.: #email=cbuia@bar.com&uid=10&role= #grab the second block of our special message, which is the admin block admin_block = profile_for_encrypted("AAAAAAAAAAadmin\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b\x0b@bar.com", ckey)[16:32] #get the target message we want to tamper with: cipher_target = profile_for_encrypted("cbuia@bar.com", ckey) #splice cipher_tampered = cipher_target[:len(cipher_target)-16] + admin_block #test print(decrypt_aes128(cipher_tampered, ckey).decode("ascii"))
36.114286
120
0.489188
b59d1bcaa7dc1ce90b8f39d10ada66ea2026eb08
2,168
rb
Ruby
spec/request_spec.rb
cheeyeo/Amazon-SNS-Ruby
e8ced9a74d8bb9b052ab18ae057f71b7cf196daf
[ "MIT", "Unlicense" ]
4
2015-04-30T17:54:13.000Z
2021-06-03T18:46:47.000Z
spec/request_spec.rb
cheeyeo/Amazon-SNS-Ruby
e8ced9a74d8bb9b052ab18ae057f71b7cf196daf
[ "MIT", "Unlicense" ]
null
null
null
spec/request_spec.rb
cheeyeo/Amazon-SNS-Ruby
e8ced9a74d8bb9b052ab18ae057f71b7cf196daf
[ "MIT", "Unlicense" ]
2
2015-07-09T11:50:05.000Z
2016-06-29T13:45:12.000Z
require File.dirname(__FILE__) + '/spec_helper.rb' describe Request do before :each do AmazeSNS.akey = '123456' AmazeSNS.skey = '123456' params={ 'Action' => "ListTopics", 'SignatureMethod' => 'HmacSHA256', 'SignatureVersion' => 2, 'Timestamp' => Time.now.iso8601, #Time.now.iso8601 makes tests fail 'AWSAccessKeyId' => AmazeSNS.akey } @data = <<-RESPONSE.gsub(/^ +/, '') <ListTopicsResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/"> <ListTopicsResult> <Topics> <member> <TopicArn>arn:aws:sns:us-east-1:123456789012:My-Topic</TopicArn> </member> </Topics> </ListTopicsResult> <ResponseMetadata> <RequestId>3f1478c7-33a9-11df-9540-99d0768312d3</RequestId> </ResponseMetadata> </ListTopicsResponse> RESPONSE @request = Request.new(params) end it 'should make a request successfully' do @regexp = %r{/?Action=ListTopics} stub_http_request(:get, @regexp).to_return(:body => @data, :status => 200, :headers => { 'Content-Type' => 'text/xml', 'Connection' => 'close' }) EM.run_block{ @request.process @request.callback{|data| data.response.should == @data } } WebMock.should have_requested(:get, %r{http://sns.us-east-1.amazonaws.com:80}) end it 'should throw an error if the request is not successful' do error_raised = nil @regexp = %r{/?Action=ListTopics} stub_http_request(:get, @regexp).to_return(:status => [500, "Internal Server Error"]) begin EM.run_block{ @request.process } rescue => e error_raised = e end e.class.should == InternalError e.message.should == 'An internal service error has occured on the Simple Notification Service' end end
31.42029
98
0.526753
570e4cb0438a61ac116bed7dc7121776a1e71b4a
3,489
js
JavaScript
modules/userrequests/client/controllers/userrequests.client.controller.js
pravinnayak/LibraryManagementSystem
085e26a2c99f82663fe876ad7b747d22560e57ee
[ "MIT" ]
null
null
null
modules/userrequests/client/controllers/userrequests.client.controller.js
pravinnayak/LibraryManagementSystem
085e26a2c99f82663fe876ad7b747d22560e57ee
[ "MIT" ]
null
null
null
modules/userrequests/client/controllers/userrequests.client.controller.js
pravinnayak/LibraryManagementSystem
085e26a2c99f82663fe876ad7b747d22560e57ee
[ "MIT" ]
null
null
null
(function () { 'use strict'; // Userrequests controller angular .module('userrequests') .controller('UserrequestsController', UserrequestsController); UserrequestsController.$inject = ['$scope', '$state', '$window', 'Authentication', "$rootScope", "$http", "$interval", "ArticlesService"]; function UserrequestsController($scope, $state, $window, Authentication, $rootScope, $http, $interval, ArticlesService) { var vm = this; vm.selectedObj = $rootScope.userrequest.selectedObj; console.log(vm.selectedObj) if (vm.selectedObj && vm.selectedObj.bookId._id && vm.selectedObj.issueStatus == "Approved") { vm.issueType = vm.selectedObj.issueType vm.issueStatus = vm.selectedObj.issueStatus vm.id = vm.selectedObj.bookId._id // vm.book = vm.selectedObj.bookId vm.getBook = () => { let url = "/api/articles/" + vm.id return $http.get(url) } vm.interval = $interval(function () { vm.conditionCheck() }, 1000 * 60) $scope.$on('$destroy', function () { $interval.cancel(vm.interval) }); vm.updateBook = () => { ArticlesService.update({ articleId: vm.id }, { title: vm.book.title, content: vm.book.content, issued: false, issuedTill: null }).$promise.then(() => { let url = "/api/userrequests/" + vm.selectedObj._id let data = { issueStatus: "Resolved" } $http.post(url, data).then(function (success) { // //console.log(success) // $state.reload() }) }) } vm.conditionCheck = () => { vm.getBook().then((res) => { vm.book = res.data if (vm.book.issued) { vm.tillDate = new Date(vm.book.issuedTill) let currDate = new Date() //console.log(vm.tillDate) if (vm.tillDate < currDate) { //console.log("not clear") $scope.checkVar = false vm.updateBook() } else { $scope.checkVar = true } } else { $scope.checkVar = false vm.updateBook() } }) } vm.conditionCheck() } // vm.authentication = Authentication; // vm.userrequest = userrequest; // vm.error = null; // vm.form = {}; // vm.remove = remove; // vm.save = save; // // Remove existing Userrequest // function remove() { // if ($window.confirm('Are you sure you want to delete?')) { // vm.userrequest.$remove($state.go('userrequests.list')); // } // } // // Save Userrequest // function save(isValid) { // if (!isValid) { // $scope.$broadcast('show-errors-check-validity', 'vm.form.userrequestForm'); // return false; // } // // TODO: move create/update logic to service // if (vm.userrequest._id) { // vm.userrequest.$update(successCallback, errorCallback); // } else { // vm.userrequest.$save(successCallback, errorCallback); // } // function successCallback(res) { // $state.go('userrequests.view', { // userrequestId: res._id // }); // } // function errorCallback(res) { // vm.error = res.data.message; // } // } } }());
26.431818
140
0.520206
5014546ee82d9da269a8238e13e0aa9270a108cd
251
swift
Swift
MusicCoreFramework/Responses/LoginResponse.swift
amrendra-roy/MusicCoreFramework
934f673e55553e4332ad10a211ca5a2852616e68
[ "MIT" ]
null
null
null
MusicCoreFramework/Responses/LoginResponse.swift
amrendra-roy/MusicCoreFramework
934f673e55553e4332ad10a211ca5a2852616e68
[ "MIT" ]
null
null
null
MusicCoreFramework/Responses/LoginResponse.swift
amrendra-roy/MusicCoreFramework
934f673e55553e4332ad10a211ca5a2852616e68
[ "MIT" ]
null
null
null
// // LoginResponse.swift // MusicCoreFramework // // Created by Amrendra on 16/10/21. // import Foundation public struct LoginResponse: Codable { public static func loginResponseMethod() { print("login Response Method") } }
15.6875
46
0.669323
e9c4b74111519cc6ba1bef05bf6f0245dd167c80
605
swift
Swift
Test/Test/Common Classes/Extensions.swift
MananKakadiya/PracticleTask
90ee6ad4a8f36e37174b9ad14ea43b1b358bc93c
[ "MIT" ]
null
null
null
Test/Test/Common Classes/Extensions.swift
MananKakadiya/PracticleTask
90ee6ad4a8f36e37174b9ad14ea43b1b358bc93c
[ "MIT" ]
null
null
null
Test/Test/Common Classes/Extensions.swift
MananKakadiya/PracticleTask
90ee6ad4a8f36e37174b9ad14ea43b1b358bc93c
[ "MIT" ]
null
null
null
// // Extensions.swift // Test // // Created by Manan Kakadiya on 08/03/22. // import Foundation extension String { var isBlank : Bool { return (self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } } extension NSObject { func Decode<T: Decodable>(modelClass: T.Type, from inputData: Data) -> T?{ do { let resultData = try JSONDecoder().decode(modelClass.self, from: inputData) return resultData } catch let message { print("JSON serialization error:" + "\(message)") return nil } } }
19.516129
87
0.593388
974118410167abf7e0787a9f9e311ef26bbfa122
4,184
ts
TypeScript
functions/src/index.ts
beepboop271/average-calculator-v2
0fa5ecfe92ba64975a8887f0970f45666e3c96a5
[ "MIT" ]
null
null
null
functions/src/index.ts
beepboop271/average-calculator-v2
0fa5ecfe92ba64975a8887f0970f45666e3c96a5
[ "MIT" ]
6
2020-06-08T02:24:59.000Z
2021-06-20T09:39:24.000Z
functions/src/index.ts
beepboop271/average-calculator-v2
0fa5ecfe92ba64975a8887f0970f45666e3c96a5
[ "MIT" ]
2
2020-04-16T09:04:04.000Z
2020-10-04T22:35:31.000Z
import { https, pubsub } from "firebase-functions"; import NestedError from "nested-error-stacks"; import { compareCourse, compareCourseStudent, CourseChange, CourseStudentChange, studentChangeToString, } from "./compare"; import { checkEvent, getCourses, getFcmTokens, getStudentDocs, getUsers, handleCourseChange, handleStudentChange, User, writeFcmTokens, WritePromise, } from "./db"; import { buildMessage, sendMessage } from "./notifications"; import { getFromTa } from "./taFetcher"; import { calculateCourseMark, Course } from "./taParser"; interface UserData { course: Course; courseChange?: CourseChange; studentChange?: CourseStudentChange; } const fetchUserData = async (user: User): Promise<UserData[]> => { const taCourses = await getFromTa(user); const dbCourses = await getCourses( taCourses.map((course): string => course.hash), ); const dbStudentDocs = await getStudentDocs(user, dbCourses); return taCourses.map((course, i): UserData => ({ course, courseChange: compareCourse(course, dbCourses[i]), studentChange: compareCourseStudent( course, dbCourses[i], dbStudentDocs[i], ), })); }; const processUser = async ( doc: FirebaseFirestore.QueryDocumentSnapshot, ): Promise<WritePromise[]> => { const user: User = doc.data() as User; if (doc.exists) { console.log(`retrieving user ${user.username}`); const ops: Array<WritePromise | WritePromise[]> = []; for (const { course, courseChange, studentChange } of await fetchUserData(user)) { const avg = calculateCourseMark(course); if (courseChange !== undefined) { const tokens = await sendMessage(buildMessage( user, `${course.name} Weights (${avg.average})`, `${course.weights?.toString()}`, )); if (tokens.length !== user.devices.length) { ops.push(writeFcmTokens({ devices: tokens, ref: doc.ref })); } ops.push(handleCourseChange(courseChange)); } if (studentChange !== undefined) { const tokens = await sendMessage(buildMessage( user, `${course.name} (${avg.average})`, `${avg.strands.toString()}\n${studentChangeToString(studentChange)}`, )); if (tokens.length !== user.devices.length) { ops.push(writeFcmTokens({ devices: tokens, ref: doc.ref })); } ops.push(handleStudentChange(studentChange)); } } return ops.flat(); } throw new Error(`User document does not exist: ${doc.ref.path}`); }; // 0 * * 1-6,9-12 0,6 // 0 0-8,16-23 * 1-6,9-12 1-5 // 0,20,40 9-15 * 1-6,9-12 1-5 export const fun = pubsub .topic("poll-ta") .onPublish(async (_msg, ctx): Promise<unknown> => { // idempotency check try { // either you await here so you can try/catch and rethrow // the error to end execution, or you don't await to // prevent wasted time but could end up killing the // process at a random time await checkEvent(ctx.eventId); } catch (err) { if (err instanceof Error) { throw new NestedError("Failed in event check", err); } throw new Error(`Failed in event check: ${err}`); } let users: FirebaseFirestore.QuerySnapshot; try { users = await getUsers(); } catch (e) { if (e instanceof Error) { throw new NestedError("Failed to retrieve users", e); } throw new Error(`Failed to retrieve users: ${e}`); } return Promise.all(users.docs.flatMap(processUser)).catch(console.error); }); export const addFcmToken = https.onCall( async (data: { token?: unknown }, ctx): WritePromise => { if (ctx.auth?.uid === undefined) { throw new https.HttpsError("unauthenticated", "No UID found"); } if (data.token === undefined || typeof data.token !== "string") { throw new https.HttpsError("invalid-argument", "invalid token"); } const { devices, ref } = await getFcmTokens(ctx.auth.uid); devices.push(data.token); const verifiedDevices = await sendMessage({ tokens: devices }, true); return writeFcmTokens({ devices: verifiedDevices, ref }); }, );
29.464789
86
0.638384
e2511d3ce58e976c7cef5f590a3dd8ff466fb854
134
py
Python
sample/mobile/steps/page_steps/pages/navigation_menu.py
Softeq/PyCats
c71d54ca7fa958c22ca8c78ba9889c6a32b827be
[ "Apache-2.0" ]
7
2020-06-12T15:16:10.000Z
2020-06-20T18:42:07.000Z
sample/mobile/steps/page_steps/pages/navigation_menu.py
Softeq/PyCats
c71d54ca7fa958c22ca8c78ba9889c6a32b827be
[ "Apache-2.0" ]
4
2020-06-15T20:08:32.000Z
2020-06-29T16:51:57.000Z
sample/mobile/steps/page_steps/pages/navigation_menu.py
Softeq/SCAF
c71d54ca7fa958c22ca8c78ba9889c6a32b827be
[ "Apache-2.0" ]
3
2020-07-27T10:45:36.000Z
2021-01-13T12:10:46.000Z
from sample.mobile.src.pages.navigation_menu_page import NavigationMenuPage class NavigationMenuSteps(NavigationMenuPage): pass
22.333333
75
0.850746
79998de93ffb7b049448cb454d95e3399bea466e
200
phpt
PHP
web-based-system/PHP_Compat-1.6.0a3/tests/function/ob_clean.phpt
chairiq/dlplatforms
1dea09b2f2b71c533115e8d7e19b255d61dc59ae
[ "MIT" ]
1
2021-08-16T07:49:19.000Z
2021-08-16T07:49:19.000Z
web-based-system/PHP_Compat-1.6.0a3/tests/function/ob_clean.phpt
chairiq/dlplatforms
1dea09b2f2b71c533115e8d7e19b255d61dc59ae
[ "MIT" ]
null
null
null
web-based-system/PHP_Compat-1.6.0a3/tests/function/ob_clean.phpt
chairiq/dlplatforms
1dea09b2f2b71c533115e8d7e19b255d61dc59ae
[ "MIT" ]
null
null
null
--TEST-- Function -- ob_clean --FILE-- <?php require_once 'PHP/Compat/Function/ob_clean.php'; ob_start(); echo 'foo'; php_compat_ob_clean(); echo 'foo'; ob_end_flush(); ?> --EXPECT-- foo
14.285714
49
0.645
d5cc2b72ae9a0c162fbd71db3a95ee6959966054
2,613
rb
Ruby
app/helpers/projects/project_members_helper.rb
HinchK/gitlabhq
a9720e77c10b98e427e54384b507683d4c4bfbbd
[ "MIT" ]
null
null
null
app/helpers/projects/project_members_helper.rb
HinchK/gitlabhq
a9720e77c10b98e427e54384b507683d4c4bfbbd
[ "MIT" ]
null
null
null
app/helpers/projects/project_members_helper.rb
HinchK/gitlabhq
a9720e77c10b98e427e54384b507683d4c4bfbbd
[ "MIT" ]
null
null
null
# frozen_string_literal: true module Projects::ProjectMembersHelper def project_members_app_data_json(project, members:, group_links:, invited:, access_requests:) { user: project_members_list_data(project, members, { param_name: :page, params: { search_groups: nil } }), group: project_group_links_list_data(project, group_links), invite: project_members_list_data(project, invited.nil? ? [] : invited), access_request: project_members_list_data(project, access_requests.nil? ? [] : access_requests), source_id: project.id, can_manage_members: Ability.allowed?(current_user, :admin_project_member, project) }.to_json end def project_member_header_subtext(project) if can?(current_user, :admin_project_member, project) share_project_description(project) else html_escape(_("Members can be added by project " \ "%{i_open}Maintainers%{i_close} or %{i_open}Owners%{i_close}")) % { i_open: '<i>'.html_safe, i_close: '</i>'.html_safe } end end private def share_project_description(project) share_with_group = project.allowed_to_share_with_group? share_with_members = !membership_locked? description = if share_with_group && share_with_members _("You can invite a new member to %{project_name} or invite another group.") elsif share_with_group _("You can invite another group to %{project_name}.") elsif share_with_members _("You can invite a new member to %{project_name}.") end html_escape(description) % { project_name: tag.strong(project.name) } end def project_members_serialized(project, members) MemberSerializer.new.represent(members, { current_user: current_user, group: project.group, source: project }) end def project_group_links_serialized(project, group_links) GroupLink::ProjectGroupLinkSerializer.new.represent(group_links, { current_user: current_user, source: project }) end def project_members_list_data(project, members, pagination = {}) { members: project_members_serialized(project, members), pagination: members_pagination_data(members, pagination), member_path: project_project_member_path(project, ':id') } end def project_group_links_list_data(project, group_links) { members: project_group_links_serialized(project, group_links), pagination: members_pagination_data(group_links), member_path: project_group_link_path(project, ':id') } end end Projects::ProjectMembersHelper.prepend_mod_with('Projects::ProjectMembersHelper')
37.328571
117
0.729812
ce4831423075bec8b62e7491aa175ee947f870f8
268
swift
Swift
6.TemplateMethodPattern/TemplateMethod/TemplateMethod/TemplateMethod/TextPaperB.swift
lei-wen/DesignPatterns
f8d9f47672d20a0ea65a53b3d9f11f7fb8759bb5
[ "MIT" ]
null
null
null
6.TemplateMethodPattern/TemplateMethod/TemplateMethod/TemplateMethod/TextPaperB.swift
lei-wen/DesignPatterns
f8d9f47672d20a0ea65a53b3d9f11f7fb8759bb5
[ "MIT" ]
null
null
null
6.TemplateMethodPattern/TemplateMethod/TemplateMethod/TemplateMethod/TextPaperB.swift
lei-wen/DesignPatterns
f8d9f47672d20a0ea65a53b3d9f11f7fb8759bb5
[ "MIT" ]
null
null
null
// // TextPaperB.swift // TemplateMethod // // Created by Navi on 2021/8/9. // import UIKit class TextPaperB: TextPaper { override func answerA() -> String { return "不知道" } override func answerB() -> String { return "不会" } }
13.4
39
0.567164
27afae2e1da12a3aa17a1a8029b74cd6aad3eb6a
2,550
dart
Dart
lib/src/datamatrix/encoder/base256_encoder.dart
winterdl/zxing-dart
5455eb20b9cdca122897dadcbe4fead2e321c42d
[ "Apache-2.0" ]
13
2021-05-30T10:12:46.000Z
2022-02-08T08:36:42.000Z
lib/src/datamatrix/encoder/base256_encoder.dart
winterdl/zxing-dart
5455eb20b9cdca122897dadcbe4fead2e321c42d
[ "Apache-2.0" ]
3
2021-06-15T18:58:55.000Z
2021-11-10T02:29:08.000Z
lib/src/datamatrix/encoder/base256_encoder.dart
winterdl/zxing-dart
5455eb20b9cdca122897dadcbe4fead2e321c42d
[ "Apache-2.0" ]
4
2021-06-27T19:21:15.000Z
2021-11-01T12:41:18.000Z
/* * Copyright 2006-2007 Jeremias Maerki. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import '../../common/string_builder.dart'; import 'encoder.dart'; import 'encoder_context.dart'; import 'high_level_encoder.dart'; class Base256Encoder implements Encoder { @override int get encodingMode => HighLevelEncoder.BASE256_ENCODATION; @override void encode(EncoderContext context) { StringBuilder buffer = StringBuilder(); buffer.write('\x00'); //Initialize length field while (context.hasMoreCharacters) { int c = context.currentChar; buffer.writeCharCode(c); context.pos++; int newMode = HighLevelEncoder.lookAheadTest( context.message, context.pos, encodingMode); if (newMode != encodingMode) { // Return to ASCII encodation, which will actually handle latch to new mode context.signalEncoderChange(HighLevelEncoder.ASCII_ENCODATION); break; } } int dataCount = buffer.length - 1; int lengthFieldSize = 1; int currentSize = context.codewordCount + dataCount + lengthFieldSize; context.updateSymbolInfo(currentSize); bool mustPad = (context.symbolInfo!.dataCapacity - currentSize) > 0; if (context.hasMoreCharacters || mustPad) { if (dataCount <= 249) { buffer.setCharAt(0, dataCount); } else if (dataCount <= 1555) { buffer.setCharAt(0, (dataCount ~/ 250) + 249); buffer.insert(1, dataCount % 250); } else { throw StateError("Message length not in valid ranges: $dataCount"); } } for (int i = 0, l = buffer.length; i < l; i++) { context.writeCodeword( _randomize255State(buffer.charAt(i), context.codewordCount + 1)); } } static int _randomize255State(String ch, int codewordPosition) { int pseudoRandom = ((149 * codewordPosition) % 255) + 1; int tempVariable = ch.codeUnitAt(0) + pseudoRandom; if (tempVariable <= 255) { return tempVariable; } else { return tempVariable - 256; } } }
34
83
0.678039
4d203dcb8c9c8238f970c971191c217f744f292a
3,938
cs
C#
AutoReservation.Service.Grpc.Testing/CustomerServiceTests.cs
hsrdev/AutoReservation
1947cacf27ff09715e5411d3c739fcb4f2e63f10
[ "Linux-OpenIB" ]
1
2019-11-19T16:30:59.000Z
2019-11-19T16:30:59.000Z
AutoReservation.Service.Grpc.Testing/CustomerServiceTests.cs
hsrdev/AutoReservation
1947cacf27ff09715e5411d3c739fcb4f2e63f10
[ "Linux-OpenIB" ]
null
null
null
AutoReservation.Service.Grpc.Testing/CustomerServiceTests.cs
hsrdev/AutoReservation
1947cacf27ff09715e5411d3c739fcb4f2e63f10
[ "Linux-OpenIB" ]
null
null
null
using System; using System.Threading.Tasks; using AutoReservation.Service.Grpc.Testing.Common; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using Xunit; using System.Collections.Generic; using AutoReservation.Dal.Entities; using Google.Protobuf; namespace AutoReservation.Service.Grpc.Testing { public class CustomerServiceTests : ServiceTestBase { private readonly KundeService.KundeServiceClient _target; public CustomerServiceTests(ServiceTestFixture serviceTestFixture) : base(serviceTestFixture) { _target = new KundeService.KundeServiceClient(Channel); } [Fact] public async Task GetCustomersTest() { // arrange var request = new Empty(); // act GetAllCustomersResponse reply = _target.GetAllCustomers(request); var list = reply.Data; // assert Assert.Equal(4, list.Count); } [Fact] public async Task GetCustomerByIdTest() { // arrange var requestId = new GetCustomerRequest { IdFilter = 2 }; // act CustomerDto reply = _target.GetCustomer(requestId); // assert Assert.Equal("Beil", reply.LastName); } [Fact] public async Task GetCustomerByIdWithIllegalIdTest() { // arrange var requestId = new GetCustomerRequest { IdFilter = 12 }; // act // assert Assert.Throws<RpcException>(() => _target.GetCustomer(requestId)); } [Fact] public async Task InsertCustomerTest() { // arrange DateTime date = new DateTime(2000, 1, 1, 0,0,0, DateTimeKind.Utc); CustomerDto cust = new CustomerDto { FirstName = "Niels", LastName = "Müller", BirthDate = date.ToTimestamp() }; // act var requestInsert = cust; CustomerDto customerToInsert = _target.InsertCustomer(requestInsert); // assert var requestId = new GetCustomerRequest { IdFilter = customerToInsert.Id }; CustomerDto insertedCustomer = _target.GetCustomer(requestId); Assert.Equal(customerToInsert.Id, insertedCustomer.Id); Assert.Equal("Müller", insertedCustomer.LastName); } [Fact] public async Task DeleteCustomerTest() { var requestId = new GetCustomerRequest { IdFilter = 4 }; CustomerDto toDelete = _target.GetCustomer(requestId); // act Empty emptyDelete = _target.DeleteCustomer(toDelete); // assert Assert.Throws<RpcException>(() => _target.GetCustomer(requestId)); } [Fact] public async Task UpdateCustomerTest() { //arrange var requestId = new GetCustomerRequest { IdFilter = 3 }; CustomerDto toUpdate = _target.GetCustomer(requestId); //act toUpdate.FirstName = "Anna-Lena"; Empty emptyUpdate = _target.UpdateCustomer(toUpdate); // assert toUpdate = _target.GetCustomer(requestId); Assert.Equal("Anna-Lena", toUpdate.FirstName); } [Fact] public async Task UpdateCustomerWithOptimisticConcurrencyTest() { //arrange var requestId = new GetCustomerRequest { IdFilter = 3 }; CustomerDto toUpdate = _target.GetCustomer(requestId); //act toUpdate.FirstName = "Anna-Lena"; Empty emptyUpdate = _target.UpdateCustomer(toUpdate); toUpdate.FirstName = "Anna-Lisa"; // assert Assert.Throws<RpcException>(() => _target.UpdateCustomer(toUpdate)); } } }
30.292308
86
0.575419
ff9c6a5f9973ba56ea83d876774915be42e46887
40,043
py
Python
custom_components/ferroamp/sensor.py
gitter-badger/ha-ferroamp
38275e489c8ca3108c2a906b91e9628819badd5e
[ "MIT" ]
null
null
null
custom_components/ferroamp/sensor.py
gitter-badger/ha-ferroamp
38275e489c8ca3108c2a906b91e9628819badd5e
[ "MIT" ]
null
null
null
custom_components/ferroamp/sensor.py
gitter-badger/ha-ferroamp
38275e489c8ca3108c2a906b91e9628819badd5e
[ "MIT" ]
null
null
null
"""Platform for Ferroamp sensors integration.""" import json import logging from datetime import datetime from homeassistant import config_entries, core from homeassistant.components import mqtt from homeassistant.const import ( CONF_NAME, CONF_PREFIX, ELECTRICAL_CURRENT_AMPERE, ENERGY_KILO_WATT_HOUR, ENERGY_WATT_HOUR, FREQUENCY_HERTZ, PERCENTAGE, POWER_WATT, TEMP_CELSIUS, VOLT ) from homeassistant.core import callback from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.util import slugify from .const import ( CONF_INTERVAL, CONF_PRECISION_BATTERY, CONF_PRECISION_CURRENT, CONF_PRECISION_ENERGY, CONF_PRECISION_FREQUENCY, CONF_PRECISION_TEMPERATURE, CONF_PRECISION_VOLTAGE, DATA_DEVICES, DATA_LISTENERS, DOMAIN, MANUFACTURER ) _LOGGER = logging.getLogger(__name__) EHUB_TOPIC = "data/ehub" SSO_TOPIC = "data/sso" ESO_TOPIC = "data/eso" ESM_TOPIC = "data/esm" CONTROL_REQUEST_TOPIC = "control/request" CONTROL_RESPONSE_TOPIC = "control/response" CONTROL_RESULT_TOPIC = "control/result" EHUB = "ehub" EHUB_NAME = "EnergyHub" async def async_setup_entry( hass: core.HomeAssistant, config_entry: config_entries.ConfigEntry, async_add_entities, ): """Setup sensors from a config entry created in the integrations UI.""" hass.data[DOMAIN].setdefault(DATA_DEVICES, {}) hass.data[DOMAIN].setdefault(DATA_LISTENERS, {}) hass.data[DOMAIN][DATA_DEVICES].setdefault(config_entry.unique_id, {}) hass.data[DOMAIN][DATA_LISTENERS].setdefault(config_entry.unique_id, []) listeners = hass.data[DOMAIN][DATA_LISTENERS].get(config_entry.unique_id) config = hass.data[DOMAIN][DATA_DEVICES][config_entry.unique_id] _LOGGER.debug( "Setting up ferroamp sensors for %(prefix)s", dict(prefix=config_entry.data[CONF_PREFIX]), ) config_id = config_entry.unique_id name = config_entry.data[CONF_NAME] slug = slugify(name) interval = config_entry.options.get(CONF_INTERVAL) if interval is None or interval == 0: interval = 30 precision_battery = config_entry.options.get(CONF_PRECISION_BATTERY) if precision_battery is None: precision_battery = 1 precision_current = config_entry.options.get(CONF_PRECISION_CURRENT) if precision_current is None: precision_current = 0 precision_energy = config_entry.options.get(CONF_PRECISION_ENERGY) if precision_energy is None: precision_energy = 1 precision_frequency = config_entry.options.get(CONF_PRECISION_FREQUENCY) if precision_frequency is None: precision_frequency = 2 precision_temperature = config_entry.options.get(CONF_PRECISION_TEMPERATURE) if precision_temperature is None: precision_temperature = 0 precision_voltage = config_entry.options.get(CONF_PRECISION_VOLTAGE) if precision_voltage is None: precision_voltage = 0 listeners.append(config_entry.add_update_listener(options_update_listener)) ehub = ehub_sensors(slug, name, interval, precision_battery, precision_energy, precision_frequency, config_id) eso_sensors = {} esm_sensors = {} sso_sensors = {} cmd_sensor = {} def get_store(store_name): store = config.get(store_name) new = False if store is None: store = config[store_name] = {} new = True return store, new def update_sensor_from_event(event, sensors, store): for sensor in sensors: if sensor.unique_id not in store: store[sensor.unique_id] = sensor _LOGGER.debug( "Registering new sensor %(unique_id)s => %(event)s", dict(unique_id=sensor.unique_id, event=event), ) async_add_entities((sensor,), True) sensor.hass = hass sensor.add_event(event) @callback def ehub_event_received(msg): event = json.loads(msg.payload) store, new = get_store(f"{slug}_{EHUB}") update_sensor_from_event(event, ehub, store) @callback def sso_event_received(msg): event = json.loads(msg.payload) sso_id = event["id"]["val"] device_id = f"{slug}_sso_{sso_id}" device_name = f"{name} SSO {sso_id}" store, new = get_store(device_id) sensors = sso_sensors.get(sso_id) if new: sensors = sso_sensors[sso_id] = [ VoltageFerroampSensor( f"{device_name} PV String Voltage", "upv", "mdi:current-dc", device_id, device_name, interval, precision_voltage, config_id, ), CurrentFerroampSensor( f"{device_name} PV String Current", "ipv", "mdi:current-dc", device_id, device_name, interval, precision_current, config_id ), CalculatedPowerFerroampSensor( f"{device_name} PV String Power", "upv", "ipv", "mdi:solar-power", device_id, device_name, interval, config_id, ), EnergyFerroampSensor( f"{device_name} Total Energy", "wpv", "mdi:solar-power", device_id, device_name, interval, precision_energy, config_id, ), StringValFerroampSensor( f"{device_name} Faultcode", "faultcode", "", "mdi:traffic-light", device_id, device_name, interval, config_id, ), RelayStatusFerroampSensor( f"{device_name} Relay Status", "relaystatus", device_id, device_name, interval, config_id, ), TemperatureFerroampSensor( f"{device_name} PCB Temperature", "temp", device_id, device_name, interval, precision_temperature, config_id ), ] update_sensor_from_event(event, sensors, store) @callback def eso_event_received(msg): event = json.loads(msg.payload) eso_id = event["id"]["val"] if eso_id == "": return device_id = f"{slug}_eso_{eso_id}" device_name = f"{name} ESO {eso_id}" store, new = get_store(device_id) sensors = eso_sensors.get(eso_id) if new: sensors = eso_sensors[eso_id] = [ VoltageFerroampSensor( f"{device_name} Battery Voltage", "ubat", "mdi:battery", device_id, device_name, interval, precision_voltage, config_id, ), CurrentFerroampSensor( f"{device_name} Battery Current", "ibat", "mdi:battery", device_id, device_name, interval, precision_current, config_id ), CalculatedPowerFerroampSensor( f"{device_name} Battery Power", "ubat", "ibat", "mdi:battery", device_id, device_name, interval, config_id, ), EnergyFerroampSensor( f"{device_name} Total Energy Produced", "wbatprod", "mdi:battery", device_id, device_name, interval, precision_energy, config_id, ), EnergyFerroampSensor( f"{device_name} Total Energy Consumed", "wbatcons", "mdi:battery", device_id, device_name, interval, precision_energy, config_id, ), BatteryFerroampSensor( f"{device_name} State of Charge", "soc", device_id, device_name, interval, precision_battery, config_id, ), StringValFerroampSensor( f"{device_name} Faultcode", "faultcode", "", "mdi:traffic-light", device_id, device_name, interval, config_id, ), RelayStatusFerroampSensor( f"{device_name} Relay Status", "relaystatus", device_id, device_name, interval, config_id, ), TemperatureFerroampSensor( f"{device_name} PCB Temperature", "temp", device_id, device_name, interval, precision_temperature, config_id ), ] update_sensor_from_event(event, sensors, store) @callback def esm_event_received(msg): event = json.loads(msg.payload) esm_id = event["id"]["val"] device_id = f"{slug}_esm_{esm_id}" device_name = f"{name} ESM {esm_id}" store, new = get_store(device_id) sensors = esm_sensors.get(esm_id) if new: sensors = esm_sensors[esm_id] = [ StringValFerroampSensor( f"{device_name} Status", "status", "", "mdi:traffic-light", device_id, device_name, interval, config_id, ), BatteryFerroampSensor( f"{device_name} State of Health", "soh", device_id, device_name, interval, precision_battery, config_id, ), BatteryFerroampSensor( f"{device_name} State of Charge", "soc", device_id, device_name, interval, precision_battery, config_id, ), IntValFerroampSensor( f"{device_name} Rated Capacity", "ratedCapacity", ENERGY_WATT_HOUR, "mdi:battery", device_id, device_name, interval, config_id, ), PowerFerroampSensor( f"{device_name} Rated Power", "ratedPower", "mdi:battery", device_id, device_name, interval, config_id, ) ] update_sensor_from_event(event, sensors, store) def get_cmd_sensor(store): sensor = cmd_sensor.get('sensor') if sensor is None: sensor = CommandFerroampSensor( f"{name} Control Status", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", config_id ) cmd_sensor['sensor'] = sensor if sensor.unique_id not in store: store[sensor.unique_id] = sensor _LOGGER.debug( "Registering new sensor %(unique_id)s", dict(unique_id=sensor.unique_id), ) async_add_entities((sensor,), True) sensor.hass = hass return sensor @callback def ehub_request_received(msg): command = json.loads(msg.payload) store, new = get_store(f"{slug}_{EHUB}") sensor = get_cmd_sensor(store) trans_id = command["transId"] cmd = command["cmd"] cmd_name = cmd["name"] arg = cmd.get("arg") sensor.add_request(trans_id, cmd_name, arg) @callback def ehub_response_received(msg): response = json.loads(msg.payload) store, new = get_store(f"{slug}_{EHUB}") sensor = get_cmd_sensor(store) trans_id = response["transId"] status = response["status"] message = response["msg"] sensor.add_response(trans_id, status, message) listeners.append(await mqtt.async_subscribe( hass, f"{config_entry.data[CONF_PREFIX]}/{EHUB_TOPIC}", ehub_event_received, 0 )) listeners.append(await mqtt.async_subscribe( hass, f"{config_entry.data[CONF_PREFIX]}/{SSO_TOPIC}", sso_event_received, 0 )) listeners.append(await mqtt.async_subscribe( hass, f"{config_entry.data[CONF_PREFIX]}/{ESO_TOPIC}", eso_event_received, 0 )) listeners.append(await mqtt.async_subscribe( hass, f"{config_entry.data[CONF_PREFIX]}/{ESM_TOPIC}", esm_event_received, 0 )) listeners.append(await mqtt.async_subscribe( hass, f"{config_entry.data[CONF_PREFIX]}/{CONTROL_REQUEST_TOPIC}", ehub_request_received, 0 )) listeners.append(await mqtt.async_subscribe( hass, f"{config_entry.data[CONF_PREFIX]}/{CONTROL_RESPONSE_TOPIC}", ehub_response_received, 0 )) listeners.append(await mqtt.async_subscribe( hass, f"{config_entry.data[CONF_PREFIX]}/{CONTROL_RESULT_TOPIC}", ehub_response_received, 0 )) return True async def options_update_listener(hass, entry): """Handle options update.""" config = hass.data[DOMAIN][DATA_DEVICES][entry.unique_id] for device in config.values(): for sensor in device.values(): sensor.handle_options_update(entry.options) class FerroampSensor(RestoreEntity): """Representation of a Ferroamp Sensor.""" def __init__(self, name, key, unit, icon, device_id, device_name, interval, config_id): """Initialize the sensor.""" self._state = None self._name = name self._state_key = key self._unit_of_measurement = unit self._icon = icon self._device_id = device_id self._device_name = device_name self._interval = interval self.config_id = config_id self.updated = datetime.min self.event = {} self.events = [] self.attrs = None @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self): """Return unique ID of entity.""" return f"{self.device_id}-{self._state_key}" @property def icon(self): return self._icon @property def device_id(self): return self._device_id @property def device_info(self): """Return the device_info of the device.""" device_info = { "identifiers": {(DOMAIN, self._device_id)}, "name": self._device_name, "manufacturer": MANUFACTURER, } return device_info def add_event(self, event): self.events.append(event) self.event.update(event) now = datetime.now() delta = (now - self.updated).total_seconds() if delta > self._interval and self.entity_id is not None: self.process_events(now) def process_events(self, now): temp = self.events self.events = [] self.updated = now self.update_state_from_events(temp) self.async_write_ha_state() def update_state_from_events(self, events): raise Exception("No implementation in base class") @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement.""" return self._unit_of_measurement @property def should_poll(self) -> bool: return False @property def state_attributes(self): return self.attrs async def async_added_to_hass(self) -> None: """Handle entity which will be added.""" await super().async_added_to_hass() state = await self.async_get_last_state() if not state: return self._state = state.state self.hass.data[DOMAIN][DATA_DEVICES][self.config_id][self.device_id][self.unique_id] = self self.process_events(datetime.now()) def handle_options_update(self, options): self._interval = options.get(CONF_INTERVAL) class IntValFerroampSensor(FerroampSensor): """Representation of a Ferroamp integer value Sensor.""" def __init__(self, name, key, unit, icon, device_id, device_name, interval, config_id): """Initialize the sensor.""" super().__init__(name, key, unit, icon, device_id, device_name, interval, config_id) def update_state_from_events(self, events): temp = 0 event = self.event for e in events: event.update(e) v = event.get(self._state_key, None) if v is not None: temp += float(v["val"]) self._state = int(temp / len(events)) class StringValFerroampSensor(FerroampSensor): """Representation of a Ferroamp string value Sensor.""" def __init__(self, name, key, unit, icon, device_id, device_name, interval, config_id): """Initialize the sensor.""" super().__init__(name, key, unit, icon, device_id, device_name, interval, config_id) def update_state_from_events(self, events): temp = None event = self.event for e in events: event.update(e) v = event.get(self._state_key, None) if v is not None: temp = v["val"] if temp is not None: self._state = temp class FloatValFerroampSensor(FerroampSensor): """Representation of a Ferroamp float value Sensor.""" def __init__(self, name, key, unit, icon, device_id, device_name, interval, precision, config_id): """Initialize the sensor.""" super().__init__(name, key, unit, icon, device_id, device_name, interval, config_id) self._precision = precision def update_state_from_events(self, events): temp = 0 event = self.event for e in events: event.update(e) v = event.get(self._state_key, None) if v is not None: temp += float(v["val"]) self._state = round(temp / len(events), self._precision) if self._precision == 0: self._state = int(self._state) class DcLinkFerroampSensor(FerroampSensor): """Representation of a Ferroamp DC Voltage value Sensor.""" def __init__(self, name, key, icon, device_id, device_name, interval, config_id): """Initialize the sensor.""" super().__init__(name, key, VOLT, icon, device_id, device_name, interval, config_id) def get_voltage(self, event): voltage = event.get(self._state_key, None) if voltage is not None: voltage = dict(neg=float(voltage["neg"]), pos=float(voltage["pos"])) return voltage def update_state_from_events(self, events): neg = pos = 0 event = self.event for e in events: event.update(e) voltage = self.get_voltage(event) if voltage is not None: neg += voltage["neg"] pos += voltage["pos"] self._state = int(neg / len(events) + pos / len(events)) self.attrs = dict(neg=round(float(neg / len(events)), 2), pos=round(float(pos / len(events)), 2)) class BatteryFerroampSensor(FloatValFerroampSensor): def __init__(self, name, key, device_id, device_name, interval, precision, config_id): super().__init__( name, key, PERCENTAGE, "mdi:battery-low", device_id, device_name, interval, precision, config_id ) @property def icon(self): if self.state is None: return self._icon pct = int(int(self.state) / 10) * 10 if pct <= 90: self._icon = f"mdi:battery-{pct}" else: self._icon = "mdi:battery" return self._icon def handle_options_update(self, options): super().handle_options_update(options) self._precision = options.get(CONF_PRECISION_BATTERY) class TemperatureFerroampSensor(FloatValFerroampSensor): def __init__(self, name, key, device_id, device_name, interval, precision, config_id): super().__init__( name, key, TEMP_CELSIUS, "mdi:thermometer", device_id, device_name, interval, precision, config_id ) def handle_options_update(self, options): super().handle_options_update(options) self._precision = options.get(CONF_PRECISION_TEMPERATURE) class CurrentFerroampSensor(FloatValFerroampSensor): def __init__(self, name, key, icon, device_id, device_name, interval, precision, config_id): super().__init__( name, key, ELECTRICAL_CURRENT_AMPERE, icon, device_id, device_name, interval, precision, config_id ) def handle_options_update(self, options): super().handle_options_update(options) self._precision = options.get(CONF_PRECISION_CURRENT) class VoltageFerroampSensor(FloatValFerroampSensor): def __init__(self, name, key, icon, device_id, device_name, interval, precision, config_id): super().__init__( name, key, VOLT, icon, device_id, device_name, interval, precision, config_id ) def handle_options_update(self, options): super().handle_options_update(options) self._precision = options.get(CONF_PRECISION_VOLTAGE) class EnergyFerroampSensor(FloatValFerroampSensor): """Representation of a Ferroamp energy in kWh value Sensor.""" def __init__(self, name, key, icon, device_id, device_name, interval, precision, config_id): """Initialize the sensor""" super().__init__(name, key, ENERGY_KILO_WATT_HOUR, icon, device_id, device_name, interval, precision, config_id) def update_state_from_events(self, events): temp = 0 event = self.event for e in events: event.update(e) v = event.get(self._state_key, None) if v is not None: temp += float(v["val"]) self._state = round(temp / len(events) / 3600000000, self._precision) if self._precision == 0: self._state = int(self._state) def handle_options_update(self, options): super().handle_options_update(options) self._precision = options.get(CONF_PRECISION_ENERGY) class RelayStatusFerroampSensor(FerroampSensor): def __init__(self, name, key, device_id, device_name, interval, config_id): """Initialize the sensor""" super().__init__(name, key, "", "", device_id, device_name, interval, config_id) def update_state_from_events(self, events): temp = None event = self.event for e in events: event.update(e) v = event.get(self._state_key, None) if v is not None: val = int(v["val"]) if val == 0: temp = "closed" elif val == 1: temp = "open/disconnected" elif val == 2: temp = "precharge" if temp is not None: self._state = temp class PowerFerroampSensor(FloatValFerroampSensor): """Representation of a Ferroamp Power Sensor.""" def __init__(self, name, key, icon, device_id, device_name, interval, config_id): super().__init__(name, key, POWER_WATT, icon, device_id, device_name, interval, 0, config_id) class CalculatedPowerFerroampSensor(FerroampSensor): """Representation of a Ferroamp Power Sensor based on V and A.""" def __init__(self, name, voltage_key, current_key, icon, device_id, device_name, interval, config_id): """Initialize the sensor.""" super().__init__( name, voltage_key, POWER_WATT, icon, device_id, device_name, interval, config_id ) self._voltage_key = voltage_key self._current_key = current_key @property def unique_id(self): """Return unique ID of entity.""" return f"{self.device_id}-{self._voltage_key}-{self._current_key}" def update_state_from_events(self, events): temp_voltage = temp_current = 0 event = self.event for e in events: event.update(e) voltage = event.get(self._voltage_key, None) current = event.get(self._current_key, None) if current is not None and voltage is not None: temp_voltage += float(voltage["val"]) temp_current += float(current["val"]) self._state = int(round(temp_voltage / len(events) * temp_current / len(events), 0)) class ThreePhaseFerroampSensor(FerroampSensor): """Representation of a Ferroamp ThreePhase Sensor.""" def __init__(self, name, key, unit, icon, device_id, device_name, interval, precision, config_id): """Initialize the sensor.""" super().__init__(name, key, unit, icon, device_id, device_name, interval, config_id) self._precision = precision def get_phases(self, event): phases = event.get(self._state_key, None) _LOGGER.debug(phases) if phases is not None: phases = dict( L1=float(phases["L1"]), L2=float(phases["L2"]), L3=float(phases["L3"]) ) return phases def update_state_from_events(self, events): l1 = l2 = l3 = 0 event = self.event for e in events: event.update(e) phases = self.get_phases(event) if phases is not None: l1 += phases["L1"] l2 += phases["L2"] l3 += phases["L3"] self._state = round(l1 / len(events) + l2 / len(events) + l3 / len(events), self._precision) if self._precision == 0: self._state = int(self._state) self.attrs = dict( L1=round(float(l1 / len(events)), 2), L2=round(float(l2 / len(events)), 2), L3=round(float(l3 / len(events)), 2), ) class ThreePhaseEnergyFerroampSensor(ThreePhaseFerroampSensor): def __init__(self, name, key, icon, device_id, device_name, interval, precision, config_id): """Initialize the sensor.""" super().__init__(name, key, ENERGY_KILO_WATT_HOUR, icon, device_id, device_name, interval, precision, config_id) def get_phases(self, event): phases = super().get_phases(event) if phases is not None: phases = dict( L1=round(phases["L1"] / 3600000000, 2), L2=round(phases["L2"] / 3600000000, 2), L3=round(phases["L3"] / 3600000000, 2), ) return phases def handle_options_update(self, options): super().handle_options_update(options) self._precision = options.get(CONF_PRECISION_ENERGY) class ThreePhasePowerFerroampSensor(ThreePhaseFerroampSensor): def __init__(self, name, key, icon, device_id, device_name, interval, config_id): """Initialize the sensor.""" super().__init__(name, key, POWER_WATT, icon, device_id, device_name, interval, 0, config_id) class CommandFerroampSensor(RestoreEntity): def __init__(self, name, device_id, device_name, config_id): self._state = None self._name = name self._icon = "mdi:cog-transfer-outline" self._device_id = device_id self._device_name = device_name self.config_id = config_id self.updated = datetime.min self.attrs = {} @property def name(self): """Return the name of the sensor.""" return self._name @property def unique_id(self): """Return unique ID of entity.""" return f"{self.device_id}_last_cmd" @property def icon(self): return self._icon @property def device_id(self): return self._device_id @property def device_info(self): """Return the device_info of the device.""" device_info = { "identifiers": {(DOMAIN, self._device_id)}, "name": self._device_name, "manufacturer": MANUFACTURER, } return device_info @property def state(self): """Return the state of the sensor.""" return self._state @property def unit_of_measurement(self): """Return the unit of measurement.""" return None @property def should_poll(self) -> bool: return False @property def state_attributes(self): return self.attrs async def async_added_to_hass(self) -> None: """Handle entity which will be added.""" await super().async_added_to_hass() state = await self.async_get_last_state() if not state: return self._state = state.state self.hass.data[DOMAIN][DATA_DEVICES][self.config_id][self.device_id][self.unique_id] = self def add_request(self, trans_id, cmd, arg): if arg is not None: self._state = f"{cmd} ({arg})" else: self._state = cmd self.attrs["transId"] = trans_id self.attrs["status"] = None self.attrs["message"] = None self.updated = datetime.now() if self.entity_id is not None: self.async_write_ha_state() def add_response(self, trans_id, status, message): if self.attrs["transId"] == trans_id: self.attrs["status"] = status self.attrs["message"] = message self.updated = datetime.now() if self.entity_id is not None: self.async_write_ha_state() def ehub_sensors(slug, name, interval, precision_battery, precision_energy, precision_frequency, config_id): return [ FloatValFerroampSensor( f"{name} Estimated Grid Frequency", "gridfreq", FREQUENCY_HERTZ, "mdi:sine-wave", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_frequency, config_id, ), ThreePhaseFerroampSensor( f"{name} External Voltage", "ul", VOLT, "mdi:current-ac", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, 0, config_id, ), ThreePhaseFerroampSensor( f"{name} Inverter RMS current", "il", ELECTRICAL_CURRENT_AMPERE, "mdi:current-dc", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, 0, config_id, ), ThreePhaseFerroampSensor( f"{name} Inverter reactive current", "ild", ELECTRICAL_CURRENT_AMPERE, "mdi:current-dc", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, 0, config_id, ), ThreePhaseFerroampSensor( f"{name} Grid Current", "iext", ELECTRICAL_CURRENT_AMPERE, "mdi:current-ac", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, 0, config_id, ), ThreePhaseFerroampSensor( f"{name} Grid Reactive Current", "iextd", ELECTRICAL_CURRENT_AMPERE, "mdi:current-ac", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, 0, config_id, ), ThreePhaseFerroampSensor( f"{name} External Active Current", "iextq", ELECTRICAL_CURRENT_AMPERE, "mdi:current-ac", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, 0, config_id, ), ThreePhaseFerroampSensor( f"{name} Adaptive Current Equalization", "iace", ELECTRICAL_CURRENT_AMPERE, "mdi:current-ac", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, 0, config_id, ), ThreePhasePowerFerroampSensor( f"{name} Grid Power", "pext", "mdi:transmission-tower", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), ThreePhasePowerFerroampSensor( f"{name} Grid Power Reactive", "pextreactive", "mdi:transmission-tower", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), ThreePhasePowerFerroampSensor( f"{name} Inverter Power, active", "pinv", "mdi:solar-power", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), ThreePhasePowerFerroampSensor( f"{name} Inverter Power, reactive", "pinvreactive", "mdi:solar-power", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), ThreePhasePowerFerroampSensor( f"{name} Consumption Power", "pload", "mdi:power-plug", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), ThreePhasePowerFerroampSensor( f"{name} Consumption Power Reactive", "ploadreactive", "mdi:power-plug", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), ThreePhaseEnergyFerroampSensor( f"{name} External Energy Produced", "wextprodq", "mdi:power-plug", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_energy, config_id, ), ThreePhaseEnergyFerroampSensor( f"{name} External Energy Consumed", "wextconsq", "mdi:power-plug", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_energy, config_id, ), ThreePhaseEnergyFerroampSensor( f"{name} Inverter Energy Produced", "winvprodq", "mdi:power-plug", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_energy, config_id, ), ThreePhaseEnergyFerroampSensor( f"{name} Inverter Energy Consumed", "winvconsq", "mdi:power-plug", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_energy, config_id, ), ThreePhaseEnergyFerroampSensor( f"{name} Load Energy Produced", "wloadprodq", "mdi:power-plug", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_energy, config_id, ), ThreePhaseEnergyFerroampSensor( f"{name} Load Energy Consumed", "wloadconsq", "mdi:power-plug", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_energy, config_id, ), EnergyFerroampSensor( f"{name} Total Solar Energy", "wpv", "mdi:solar-power", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_energy, config_id, ), EnergyFerroampSensor( f"{name} Battery Energy Produced", "wbatprod", "mdi:solar-power", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_energy, config_id, ), EnergyFerroampSensor( f"{name} Battery Energy Consumed", "wbatcons", "mdi:solar-power", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_energy, config_id, ), IntValFerroampSensor( f"{name} System State", "state", "", "mdi:traffic-light", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), DcLinkFerroampSensor( f"{name} DC Link Voltage", "udc", "mdi:current-ac", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), BatteryFerroampSensor( f"{name} System State of Charge", "soc", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_battery, config_id, ), BatteryFerroampSensor( f"{name} System State of Health", "soh", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, precision_battery, config_id, ), IntValFerroampSensor( f"{name} Apparent power", "sext", "VA", "mdi:transmission-tower", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), PowerFerroampSensor( f"{name} Solar Power", "ppv", "mdi:solar-power", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), PowerFerroampSensor( f"{name} Battery Power", "pbat", "mdi:battery", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), IntValFerroampSensor( f"{name} Total rated capacity of all batteries", "ratedcap", ENERGY_WATT_HOUR, "mdi:battery", f"{slug}_{EHUB}", f"{name} {EHUB_NAME}", interval, config_id, ), ]
32.060048
120
0.535624
df1869c3d5305e4df20d7592a6477b276b5e0cfa
226
cs
C#
Client/Studio/SLStudio.Core/Services/ToolManager/IToolManager.cs
adnan-54/SLStudio
7fdea531989f5181540e801130e93d8ed7854cd6
[ "MIT" ]
3
2019-08-24T18:06:59.000Z
2022-03-07T18:43:55.000Z
Client/Studio/SLStudio.Core/Services/ToolManager/IToolManager.cs
adnan-54/SLStudio
7fdea531989f5181540e801130e93d8ed7854cd6
[ "MIT" ]
3
2021-10-02T21:53:09.000Z
2021-10-04T14:02:37.000Z
Client/Studio/SLStudio.Core/Services/ToolManager/IToolManager.cs
adnan-54/SLStudio
7fdea531989f5181540e801130e93d8ed7854cd6
[ "MIT" ]
null
null
null
namespace SLStudio.Core { public interface IToolManager { void Register<TService, TTool>(TTool tool) where TService : class where TTool : TService, IToolItem; void Unregister(IToolItem tool); } }
22.6
108
0.681416
db926c88a781186e8216ad220c20032773258ea7
1,515
php
PHP
Redirect.php
leevels/router
8770ef41b345c75b1ffe9ace057a29550322c4ff
[ "MIT" ]
59
2017-09-04T01:09:37.000Z
2022-03-25T06:57:42.000Z
Redirect.php
leevels/router
8770ef41b345c75b1ffe9ace057a29550322c4ff
[ "MIT" ]
122
2017-05-24T01:15:29.000Z
2021-11-17T07:54:49.000Z
Redirect.php
leevels/router
8770ef41b345c75b1ffe9ace057a29550322c4ff
[ "MIT" ]
5
2018-01-16T01:56:47.000Z
2021-11-09T07:13:20.000Z
<?php declare(strict_types=1); namespace Leevel\Router; use Leevel\Http\RedirectResponse; use Leevel\Session\ISession; /** * Redirect. */ class Redirect { /** * SESSION 仓储. */ protected ISession $session; /** * 构造函数. */ public function __construct(protected IUrl $url) { } /** * 返回一个 URL 生成跳转响应. */ public function url(string $url, array $params = [], string $subdomain = 'www', null|bool|string $suffix = null, int $status = 302, array $headers = []): RedirectResponse { $url = $this->url->make($url, $params, $subdomain, $suffix); return $this->createRedirectResponse($url, $status, $headers); } /** * 返回一个跳转响应. */ public function raw(string $url, int $status = 302, array $headers = []): RedirectResponse { return $this->createRedirectResponse($url, $status, $headers); } /** * 取回 URL 生成实例. */ public function getUrl(): IUrl { return $this->url; } /** * 设置 SESSION 仓储. */ public function setSession(ISession $session): void { $this->session = $session; } /** * 返回一个跳转响应. */ protected function createRedirectResponse(string $url, int $status = 302, array $headers = []): RedirectResponse { $redirect = new RedirectResponse($url, $status, $headers); if (isset($this->session)) { $redirect->setSession($this->session); } return $redirect; } }
20.472973
174
0.563696
e2df672f0f055e562f71e906961839795338a245
33
py
Python
delivery/__main__.py
rafael-torraca/delivery
298db3c5d74938dc34687e7b65ee72a847e4deeb
[ "MIT" ]
null
null
null
delivery/__main__.py
rafael-torraca/delivery
298db3c5d74938dc34687e7b65ee72a847e4deeb
[ "MIT" ]
null
null
null
delivery/__main__.py
rafael-torraca/delivery
298db3c5d74938dc34687e7b65ee72a847e4deeb
[ "MIT" ]
null
null
null
print("hello this is delivery!")
16.5
32
0.727273
6e1c00f63c12cde90d6f588b7ae2f30e5b7d4027
266
lua
Lua
lua/jupyter-nvim/config.lua
ahmedkhalf/jupyter-nvim
90fdc9ba454189a1151b7c238bda58a9b78d29e7
[ "MIT" ]
75
2021-06-02T17:52:05.000Z
2022-03-23T03:09:38.000Z
lua/jupyter-nvim/config.lua
ahmedkhalf/jupyter-nvim
90fdc9ba454189a1151b7c238bda58a9b78d29e7
[ "MIT" ]
7
2021-06-13T03:41:28.000Z
2022-01-12T10:47:03.000Z
lua/jupyter-nvim/config.lua
ahmedkhalf/jupyter-nvim
90fdc9ba454189a1151b7c238bda58a9b78d29e7
[ "MIT" ]
4
2021-06-17T00:29:00.000Z
2022-02-23T08:48:07.000Z
local M = {} M.options = {} M.get_options = function () return M.options end local defaults = { -- There are currently no options } M.setup = function (options) M.options = vim.tbl_deep_extend("force", {}, defaults, options or {}) end M.setup() return M
13.3
71
0.657895
cd97aeeda73d3c9b70e90016a916cb3ff5fb69b9
9,110
cs
C#
Win10AppTool/Classes/ApplicationHelper.cs
mgw-dev/Win10AppTool
b1feaf84b4024bf9e8573fc7bd8f4b7631bdda61
[ "MIT" ]
10
2019-04-14T20:26:48.000Z
2022-03-13T03:17:25.000Z
Win10AppTool/Classes/ApplicationHelper.cs
mgw-dev/Win10AppTool
b1feaf84b4024bf9e8573fc7bd8f4b7631bdda61
[ "MIT" ]
null
null
null
Win10AppTool/Classes/ApplicationHelper.cs
mgw-dev/Win10AppTool
b1feaf84b4024bf9e8573fc7bd8f4b7631bdda61
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Text.Json; using System.Management.Automation; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Xml; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.Win32; using Image = System.Windows.Controls.Image; namespace Win10AppTool.Classes { public static class ApplicationHelper { #region Appx Stuff /// <summary> /// Remove AppxPackages /// </summary> /// <param name="apps">Collection of packages to remove</param> /// <param name="allUsers">Remove for all users</param> public static async Task RemoveAppx(IEnumerable<AppxPackage> apps) { await Task.Run(() => { foreach (AppxPackage app in apps) { string c = GetRemovalCommand(app); if (!string.IsNullOrEmpty(c)) { RunPsCommand(c); } } }); } /// <summary> /// Uses PowerShell to get list of AppxPackage Packages. /// </summary> /// <param name="allUsers"></param> /// <returns></returns> public static IEnumerable<AppxPackage> LoadAppx(bool allUsers, bool noStore) { StringBuilder argsBuilder = new StringBuilder(); argsBuilder.Append("Get-AppxPackage"); if (allUsers) { argsBuilder.Append(" -AllUsers"); } argsBuilder.Append(" | Where-Object {$_.IsFramework -Match 'false' -and $_.NonRemovable -Match 'false'} | select-object -property @{N='Name';E={$_.Name}}, @{N='FullName';E={$_.PackageFullName}}, @{N='InstallLocation';E={$_.InstallLocation}}, @{N='OnlineProvisioned';E={$false}} "); if (noStore) { argsBuilder.Append("| Where-Object {$_.Name -NotLike '*Microsoft.WindowsStore*' -and $_.Name -NotLike '*Microsoft.StorePurchaseApp*'}"); } return RunPsCommand(argsBuilder.ToString()).Select(obj => new AppxPackage(obj)).ToList(); } /// <summary> /// Uses PowerShell to get list of online AppxPackage Packages. /// </summary> /// <param name="allUsers"></param> /// <returns></returns> public static IEnumerable<AppxPackage> LoadAppxOnline(bool noStore) { StringBuilder argsBuilder = new StringBuilder(); argsBuilder.Append("Get-AppxProvisionedPackage -Online | select-object -property @{N='Name';E={$_.DisplayName}}, @{N='FullName';E={$_.PackageName}}, @{N='installLocation';E={$_.InstallLocation}}, @{N='OnlineProvisioned';E={$true}} "); if (noStore) { argsBuilder.Append("| Where-Object {$_.Name -NotLike '*Microsoft.WindowsStore*' -and $_.Name -NotLike '*Microsoft.StorePurchaseApp*'}"); } return RunPsCommand(argsBuilder.ToString()).Select(obj => new AppxPackage(obj)).ToList(); } #endregion /// <summary> /// Determine what PowerShell command to use /// </summary> /// <param name="app"></param> /// <param name="allUsers"></param> /// <returns></returns> private static string GetRemovalCommand(AppxPackage app) => (app.Remove, app.OnlineProvisioned) switch { (false, _) => "", (true, true) => $"Remove-AppxProvisionedPackage {app.FullName} -Online", (true, false) => $"Remove-AppxPackage {app.FullName}" }; private static string GetRemovalCommand(Win32App app) => (app.Remove, string.IsNullOrEmpty(app.QuietUninstallString), string.IsNullOrEmpty(app.UninstallString)) switch { (false, _, _) => string.Empty, (true, false, _) => app.QuietUninstallString, (true, true, false) => app.UninstallString, (true, true, true) => "!!!" }; /// <summary> /// Runs a PowerShell command. /// </summary> /// <param name="command"></param> /// <returns></returns> private static Collection<PSObject> RunPsCommand(string command) { PowerShell ps = PowerShell.Create(); ps.AddScript(command); Collection<PSObject> output = ps.Invoke(); return output; } public static IEnumerable<Win32App> LoadWin32Apps() { List<Win32App> output = new List<Win32App>(); output.AddRange(LoadAppsFromRegistry(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", RegistryHive.CurrentUser)); output.AddRange(LoadAppsFromRegistry(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall", RegistryHive.LocalMachine)); output.AddRange(LoadAppsFromRegistry(@"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall", RegistryHive.LocalMachine)); return output; } private static IEnumerable<Win32App> LoadAppsFromRegistry(string registryKey, RegistryHive hive) { List<Win32App> apps = new List<Win32App>(); RegistryKey key; switch (hive) { case RegistryHive.CurrentUser: key = Registry.CurrentUser.OpenSubKey(registryKey); break; case RegistryHive.LocalMachine: key = Registry.LocalMachine.OpenSubKey(registryKey); break; case RegistryHive.ClassesRoot: case RegistryHive.Users: case RegistryHive.PerformanceData: case RegistryHive.CurrentConfig: throw new NotImplementedException(); default: throw new ArgumentOutOfRangeException(nameof(hive), hive, null); } foreach (string subkeyName in key.GetSubKeyNames()) { using RegistryKey subKey = key.OpenSubKey(subkeyName); Win32App w32App = new Win32App(); if (visible(subKey)) { w32App.Name = subKey?.GetValue("DisplayName").ToString(); w32App.Remove = false; w32App.Img = new Image(); w32App.UninstallString = subKey?.GetValue("UninstallString")?.ToString(); w32App.QuietUninstallString = subKey?.GetValue("QuietUninstallString")?.ToString(); Icon icon = new Icon(SystemIcons.WinLogo, 64, 64); string displayIcon = (subKey?.GetValue("DisplayIcon") ?? string.Empty).ToString(); string exeMatch = Regex.Match(displayIcon ?? string.Empty, @"[A-Z]:.+\.exe", RegexOptions.IgnoreCase).Value; string icoMatch = Regex.Match(displayIcon ?? string.Empty, @"[A-Z]:.+\.ico", RegexOptions.IgnoreCase).Value; if (!string.IsNullOrEmpty(exeMatch)) { icon = Icon.ExtractAssociatedIcon(exeMatch); } if (!string.IsNullOrEmpty(icoMatch)) { icon = new Icon(icoMatch); } w32App.Img.Source = Imaging.CreateBitmapSourceFromHIcon(icon.Handle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); apps.Add(w32App); } } return apps; bool visible(RegistryKey subKey) { string name = (string)subKey.GetValue("DisplayName"); string releaseType = (string)subKey.GetValue("ReleaseType"); object systemComponent = subKey.GetValue("SystemComponent"); string parentName = (string)subKey.GetValue("ParentDisplayName"); return !string.IsNullOrEmpty(name) && string.IsNullOrEmpty(releaseType) && string.IsNullOrEmpty(parentName) && (systemComponent == null); } } public static async Task RemoveWin32(IEnumerable<Win32App> apps) { await Task.Run(() => { foreach (Win32App app in apps) { string c = GetRemovalCommand(app); if (!string.IsNullOrEmpty(c)) { if (c == "!!!") { } else { Debug.WriteLine(c); } //RunPsCommand(c); } } }); } } }
40.309735
293
0.548738
d2516c7a4a022df837069099a3e9b778f4e7be7e
1,211
rs
Rust
examples/window_run_return.rs
baysmith/winit
d07b9250434413a8ffbefd280267d8a3c78b77cf
[ "Apache-2.0" ]
1
2019-07-15T22:14:10.000Z
2019-07-15T22:14:10.000Z
examples/window_run_return.rs
baysmith/winit
d07b9250434413a8ffbefd280267d8a3c78b77cf
[ "Apache-2.0" ]
3
2019-06-22T09:40:32.000Z
2019-06-22T09:40:57.000Z
examples/window_run_return.rs
baysmith/winit
d07b9250434413a8ffbefd280267d8a3c78b77cf
[ "Apache-2.0" ]
1
2019-07-15T21:50:19.000Z
2019-07-15T21:50:19.000Z
use winit::{ event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, platform::desktop::EventLoopExtDesktop, window::WindowBuilder, }; fn main() { let mut event_loop = EventLoop::new(); let window = WindowBuilder::new() .with_title("A fantastic window!") .build(&event_loop) .unwrap(); println!("Close the window to continue."); event_loop.run_return(|event, _, control_flow| match event { Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => *control_flow = ControlFlow::Exit, _ => *control_flow = ControlFlow::Wait, }); drop(window); let _window_2 = WindowBuilder::new() .with_title("A second, fantasticer window!") .build(&event_loop) .unwrap(); println!("Wa ha ha! You thought that closing the window would finish this?!"); event_loop.run_return(|event, _, control_flow| match event { Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => *control_flow = ControlFlow::Exit, _ => *control_flow = ControlFlow::Wait, }); println!("Okay we're done now for real."); }
28.833333
82
0.60033
b0041e9cd05d1f7d1d72e22934e2919b7e364887
1,900
py
Python
src/app/forms.py
deadlock-delegate/arkdelegates
8a5262f51b519ba3bc10094756c8866fc550df65
[ "MIT" ]
2
2018-05-22T13:47:09.000Z
2018-05-23T12:45:05.000Z
src/app/forms.py
deadlock-delegate/arkdelegates
8a5262f51b519ba3bc10094756c8866fc550df65
[ "MIT" ]
21
2018-05-08T12:56:46.000Z
2020-06-05T18:59:38.000Z
src/app/forms.py
deadlock-delegate/arkdelegates
8a5262f51b519ba3bc10094756c8866fc550df65
[ "MIT" ]
4
2018-05-04T15:00:59.000Z
2019-02-13T02:39:07.000Z
import json from django import forms from django.contrib.auth import password_validation from django.core.validators import validate_email from app.models import Contribution, Delegate, Node, StatusUpdate class ClaimAccountForm(forms.Form): message_json = forms.CharField(widget=forms.Textarea(attrs={"rows": 2})) email = forms.CharField(widget=forms.EmailInput) password = forms.CharField(widget=forms.PasswordInput) def clean_email(self): email = self.cleaned_data.get("email") validate_email(email) return email def clean_password(self): password = self.cleaned_data.get("password") password_validation.validate_password(password) return password def clean_message_json(self): data = self.cleaned_data["message_json"] try: json_data = json.loads(data) except: # noqa raise forms.ValidationError("Invalid data") if not (json_data.get("message") and json_data.get("signature")): raise forms.ValidationError("JSON does not have an expected structure") return json_data class LoginForm(forms.Form): email = forms.CharField(widget=forms.EmailInput) password = forms.CharField(widget=forms.PasswordInput) def clean_email(self): email = self.cleaned_data.get("email") validate_email(email) return email class ContributionForm(forms.ModelForm): class Meta: model = Contribution fields = ["title", "description"] class NodeForm(forms.ModelForm): class Meta: model = Node fields = ["network", "cpu", "memory", "is_dedicated", "is_backup"] class ProposalForm(forms.ModelForm): class Meta: model = Delegate fields = ["proposal"] class StatusUpdateForm(forms.ModelForm): class Meta: model = StatusUpdate fields = ["message"]
27.142857
83
0.676842
438e95c9de2f88b60181a2b2f91929d218cbc6b5
481
ts
TypeScript
src/client/app/portfolio/portfolio-routing.module.ts
GabrielShabat/robinhood-ui
aced7567d69d4301f2fda7be8aafdad5c78594cf
[ "MIT" ]
25
2017-08-09T04:49:33.000Z
2022-03-11T07:35:58.000Z
src/client/app/portfolio/portfolio-routing.module.ts
GabrielShabat/robinhood-ui
aced7567d69d4301f2fda7be8aafdad5c78594cf
[ "MIT" ]
null
null
null
src/client/app/portfolio/portfolio-routing.module.ts
GabrielShabat/robinhood-ui
aced7567d69d4301f2fda7be8aafdad5c78594cf
[ "MIT" ]
15
2018-02-15T18:10:51.000Z
2020-12-31T13:42:56.000Z
import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { PortfolioComponent } from './portfolio.component'; import { InstrumentComponent } from './instrument/instrument.component'; @NgModule({ imports: [ RouterModule.forChild([ { path: 'portfolio', component: PortfolioComponent }, { path: 'portfolio/:id', component: InstrumentComponent } ]) ], exports: [RouterModule] }) export class PortfolioRoutingModule { }
32.066667
72
0.702703
126dee7c85ac3535d528ae3be1f73547f4a1a77e
186
rs
Rust
src/util/mod.rs
MichaelRawson/lazycop
a34d2e56365d1c79e0b3fc288fd60e7d4b2856ff
[ "MIT" ]
10
2020-07-01T18:40:13.000Z
2021-07-01T18:15:13.000Z
src/util/mod.rs
MichaelRawson/lazycop
a34d2e56365d1c79e0b3fc288fd60e7d4b2856ff
[ "MIT" ]
null
null
null
src/util/mod.rs
MichaelRawson/lazycop
a34d2e56365d1c79e0b3fc288fd60e7d4b2856ff
[ "MIT" ]
null
null
null
pub(crate) mod block; pub(crate) mod disjoint_set; pub(crate) mod id; pub(crate) mod length; pub(crate) mod lut; pub(crate) mod offset; pub(crate) mod range; pub(crate) mod unreachable;
20.666667
28
0.741935
a3180678424f4dff47e8f28b459424496ee89a27
2,653
h
C
TommyGun/Plugins/ImageEditor/CPCMode0Palette/CPCMode0Palette.h
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
34
2017-05-08T18:39:13.000Z
2022-02-13T05:05:33.000Z
TommyGun/Plugins/ImageEditor/CPCMode0Palette/CPCMode0Palette.h
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
null
null
null
TommyGun/Plugins/ImageEditor/CPCMode0Palette/CPCMode0Palette.h
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
6
2017-05-27T01:14:20.000Z
2020-01-20T14:54:30.000Z
/*--------------------------------------------------------------------------- (c) 2004 Scorpio Software 19 Wittama Drive Glenmore Park Sydney NSW 2745 Australia ----------------------------------------------------------------------------- $Workfile:: $ $Revision:: $ $Date:: $ $Author:: $ ---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- #ifndef ZXSpectrumPaletteH #define ZXSpectrumPaletteH //--------------------------------------------------------------------------- #include "..\ZXPalette.h" #include "..\ZXImage.h" //--------------------------------------------------------------------------- namespace Scorpio { //using namespace Imaging; namespace CPCMode0Palette { //--------------------------------------------------------------------------- class Mode0Palette : public ZXPalette { private: unsigned char m_iColor; void __fastcall Initialize(void); void __fastcall SetColor(unsigned char iColor); void __fastcall SetPixel(int iX, int iY, unsigned char iColor, bool bSet, ZXImage& Image); void __fastcall Loaded(void); public: __fastcall Mode0Palette(); void __fastcall SetTableColor(unsigned char iColor, TColor Color); void __fastcall SetColorAt(ZXImage& Image, int X, int Y); void __fastcall GetColorAt(ZXImage& Image, int X, int Y); unsigned char __fastcall GetColor(void); TColor __fastcall GetColor(unsigned char iColor); String __fastcall GetColorAsString(ZXImage& Image, int X, int Y); void __fastcall Write(int X, int Y, bool bSet, ZXImage& Image); void __fastcall Draw(ZXImage& Image, Graphics::TBitmap* Bitmap); void __fastcall Reset(void); unsigned char __property Color = { read = m_iColor, write = SetColor }; }; //--------------------------------------------------------------------------- } } //--------------------------------------------------------------------------- #endif
44.216667
114
0.352054
cf36e4402786dac5b93b143b07085186e298e2f4
482
php
PHP
app/Http/Controllers/Student/StudentNotificationController.php
hagios2/Internship-Managemenet-System-Web
e72f2d81723021abe6bc4b5a136b49c0987af943
[ "MIT" ]
null
null
null
app/Http/Controllers/Student/StudentNotificationController.php
hagios2/Internship-Managemenet-System-Web
e72f2d81723021abe6bc4b5a136b49c0987af943
[ "MIT" ]
20
2021-03-10T04:58:46.000Z
2022-02-26T22:37:52.000Z
app/Http/Controllers/Student/StudentNotificationController.php
hagios2/Internship-Managemenet-System-Web
e72f2d81723021abe6bc4b5a136b49c0987af943
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\Student; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\StudentNotification; use App\Http\Resources\StudentNotificationResource; class StudentNotificationController extends Controller { // public function __construct() { $this->middleware('auth'); } public function getNotifications() { return StudentNotificationResource::collection(StudentNotification::read()); } }
19.28
84
0.732365
cd727f4b72396962f489f508e83344dd79948dc3
1,016
cs
C#
samples/snippets/core/tutorials/creating-app-with-plugin-support/csharp/JsonPlugin/JsonPlugin.cs
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
3,294
2016-10-30T05:27:20.000Z
2022-03-31T15:59:30.000Z
samples/snippets/core/tutorials/creating-app-with-plugin-support/csharp/JsonPlugin/JsonPlugin.cs
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
16,739
2016-10-28T19:41:29.000Z
2022-03-31T22:38:48.000Z
samples/snippets/core/tutorials/creating-app-with-plugin-support/csharp/JsonPlugin/JsonPlugin.cs
BaruaSourav/docs
c288ed777de6b091f5e074d3488f7934683f3eb5
[ "CC-BY-4.0", "MIT" ]
6,701
2016-10-29T20:56:11.000Z
2022-03-31T12:32:26.000Z
using Newtonsoft.Json; using PluginBase; using System; using System.Reflection; namespace JsonPlugin { public class JsonPlugin : ICommand { public string Name => "json"; public string Description => "Outputs JSON value."; private struct Info { public string JsonVersion; public string JsonLocation; public string Machine; public string User; public DateTime Date; } public int Execute() { Assembly jsonAssembly = typeof(JsonConvert).Assembly; Info info = new Info() { JsonVersion = jsonAssembly.FullName, JsonLocation = jsonAssembly.Location, Machine = Environment.MachineName, User = Environment.UserName, Date = DateTime.Now }; Console.WriteLine(JsonConvert.SerializeObject(info, Formatting.Indented)); return 0; } } }
24.780488
86
0.558071
b351175b3982842561377d34a49cd98cea897393
1,881
py
Python
invenio_communities/fixtures/tasks.py
lhenze/invenio-communities
471abcf6b4429306ab39cc0c334cd78911a2dfb2
[ "MIT" ]
null
null
null
invenio_communities/fixtures/tasks.py
lhenze/invenio-communities
471abcf6b4429306ab39cc0c334cd78911a2dfb2
[ "MIT" ]
null
null
null
invenio_communities/fixtures/tasks.py
lhenze/invenio-communities
471abcf6b4429306ab39cc0c334cd78911a2dfb2
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2021 CERN. # Copyright (C) 2022 Graz University of Technology. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Celery tasks for fixtures.""" from datetime import datetime from celery import shared_task from elasticsearch_dsl import Q from invenio_access.permissions import system_identity from invenio_pidstore.errors import ( PIDAlreadyExists, PIDDeletedError, PIDDoesNotExistError, ) from invenio_records_resources.services.uow import RecordIndexOp, unit_of_work from ..proxies import current_communities @shared_task def create_demo_community(data): """Create a demo community.""" service = current_communities.service try: service.create(data=data, identity=system_identity) except PIDAlreadyExists: pass @shared_task def reindex_featured_entries(): """Reindexes records having at least one future entry which is now in the past.""" service = current_communities.service now = datetime.utcnow().isoformat() @unit_of_work() def reindex_community(hit, uow=None): community = service.record_cls.pid.resolve(hit["id"]) uow.register( RecordIndexOp(community, indexer=service.indexer, index_refresh=True) ) # using scan to get all communities record_list = service.scan( identity=system_identity, extra_filter=Q("range", **{"featured.future": {"lte": now}}), ) for hit in record_list.hits: try: reindex_community(hit) # community has been renamed or deleted in the meantime. # will be reindexed in the service method. except PIDDoesNotExistError: pass except PIDDeletedError: pass
28.938462
86
0.699628
e2a328ef160b7492a9254d51baf1418fd79dc470
1,831
py
Python
ivy/manages/faker.py
dmf-code/ivy
354eb20759168ff32516e630218c59f22122bdb7
[ "Apache-2.0" ]
1
2019-09-03T06:37:06.000Z
2019-09-03T06:37:06.000Z
ivy/manages/faker.py
dmf-code/ivy
354eb20759168ff32516e630218c59f22122bdb7
[ "Apache-2.0" ]
null
null
null
ivy/manages/faker.py
dmf-code/ivy
354eb20759168ff32516e630218c59f22122bdb7
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- from ivy.manages.context import Context from ivy.functions.faker import faker from ivy.functions import funcs from ivy.const import Const import copy class Faker(object): @staticmethod def custom_data_handle(_func, **kwargs): if funcs.get(_func, None) is None: raise Exception('func is not define') if not kwargs: res = funcs[_func]() else: res = funcs[_func](**kwargs) return res @staticmethod def faker_data_handle(_func, **kwargs): name = _func.split('|')[-1] language = kwargs.get('lang', 'zh_CN') new_faker = faker.select_faker(language) if not hasattr(new_faker, name): raise Exception('faker module not have this function') if not kwargs: res = getattr(new_faker, name, language)() else: res = getattr(new_faker, name, language)(**kwargs) return res def get(self, rules): data = {} for k, v in rules.items(): copy_value = copy.deepcopy(v) _func = copy_value.pop('func') if 'faker' in _func: insert_value = self.faker_data_handle(_func, **copy_value) else: insert_value = self.custom_data_handle(_func, **copy_value) data[k] = insert_value return data def get_line(self, line): line.reverse() while len(line) > 0: flag = line.pop() # 获取规则 rule = Context().get(Const.CLASS_VAR_RULES + '.' + flag) data = self.get(rule) # 保存数据 Context().set(data, Const.CLASS_VAR_CELLS + '.' + flag) cells = Context().get(Const.CLASS_VAR_CELLS) Context().clear(Const.CLASS_VAR_CELLS) return cells
29.063492
75
0.567449
387dcf2630db580c726ab5ef0c2c1d8e46f8a792
2,001
php
PHP
resources/views/frontend/blocks/banchay.blade.php
HungSonSN/book_shop
3c7d38981732b5605c660dd30d433f74fe274d26
[ "MIT" ]
null
null
null
resources/views/frontend/blocks/banchay.blade.php
HungSonSN/book_shop
3c7d38981732b5605c660dd30d433f74fe274d26
[ "MIT" ]
null
null
null
resources/views/frontend/blocks/banchay.blade.php
HungSonSN/book_shop
3c7d38981732b5605c660dd30d433f74fe274d26
[ "MIT" ]
null
null
null
<section class="section section-hot-new"> <div class="container"> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="block"> <h2 class="block-title">Sản phẩm bán chạy</h2> <div class="block-content"> <div class="owl-product owl-carousel"> @foreach ($product_banchays as $product_banchay) <!-- sản phẩm --> <div class="owl-item" style="width: 210px;" data-id="{!! $product_banchay->id !!}"> <div class="item"> <div class="product-item"> <div class="product-item-image"> <a href="{!! url('/'.$product_banchay->alias) !!}"> <img class="img-responsive" src="{!! asset('/upload/'.$product_banchay->image) !!}" > </a> </div> <a class="product-item-name" href="{!! url('/'.$product_banchay->alias) !!}">{!! $product_banchay->name !!}</a> <div> @if($product_banchay->pricesale > 0) <p class="product-item-price"> <?php echo number_format($product_banchay->price,0,',','.') ?>đ<span class="product-item-price-sale"> <?php echo number_format($product_banchay->pricesale,0,',','.') ?>đ </span> </p> @else <p class="product-item-price"><?php echo number_format($product_banchay->price,0,',','.') ?>đ </p> @endif <a class="product-item-cart add_to_cart" href="javascript:void(0)" data-id="{!! $product_banchay->id !!}"><span></span>Thêm vào giỏ</a> </div> @if($product_banchay->pricesale > 0) <span class="product-item-sale"></span> @endif </div> </div> </div> <!-- end sản phẩm --> @endforeach </div> </div> </div> </div> </div> </div> </div> </section>
48.804878
237
0.477261
be576f83aa6cd0d09ae5f55ae1160912ce4095ea
225
ts
TypeScript
packages/trade/exchange-core/src/OrderStatus.ts
Nick-Goorwah/origin
4945663039240fa7fa64357e787ae145671d7261
[ "MIT" ]
89
2019-06-07T12:00:46.000Z
2022-03-31T14:10:47.000Z
packages/trade/exchange-core/src/OrderStatus.ts
Nick-Goorwah/origin
4945663039240fa7fa64357e787ae145671d7261
[ "MIT" ]
329
2019-06-18T09:37:48.000Z
2022-03-18T15:33:22.000Z
packages/trade/exchange-core/src/OrderStatus.ts
Nick-Goorwah/origin
4945663039240fa7fa64357e787ae145671d7261
[ "MIT" ]
59
2019-06-04T19:24:10.000Z
2022-03-12T22:41:21.000Z
export enum OrderStatus { Active = 'Active', Cancelled = 'Cancelled', Filled = 'Filled', PartiallyFilled = 'PartiallyFilled', PendingCancellation = 'PendingCancellation', NotExecuted = 'NotExecuted' }
25
48
0.68
042329a67f6acfac4ad9922b800fff2a103a1cb6
777
cc
C++
chrome/browser/ash/policy/handlers/device_name_policy_handler.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ash/policy/handlers/device_name_policy_handler.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ash/policy/handlers/device_name_policy_handler.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2017 The Chromium 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 "chrome/browser/ash/policy/handlers/device_name_policy_handler.h" namespace policy { DeviceNamePolicyHandler::DeviceNamePolicyHandler() = default; DeviceNamePolicyHandler::~DeviceNamePolicyHandler() = default; void DeviceNamePolicyHandler::AddObserver(Observer* observer) { observer_list_.AddObserver(observer); } void DeviceNamePolicyHandler::RemoveObserver(Observer* observer) { observer_list_.RemoveObserver(observer); } void DeviceNamePolicyHandler::NotifyHostnamePolicyChanged() { for (auto& observer : observer_list_) observer.OnHostnamePolicyChanged(); } } // namespace policy
28.777778
74
0.796654
9a6c76557a00a757689c6bca0d1f5eb507f4cbca
1,703
ps1
PowerShell
Powershell Monitoring Examples/VMware vSphere/vmcreationdeletion2influxdb.ps1
micelshima/InfluxDB-Powershell-Module
0a1f0ba93750001601552cb29bcf5307ad52df35
[ "MIT" ]
29
2017-01-31T22:10:17.000Z
2021-09-25T22:24:25.000Z
Powershell Monitoring Examples/VMware vSphere/vmcreationdeletion2influxdb.ps1
micelshima/InfluxDB-Powershell-Module
0a1f0ba93750001601552cb29bcf5307ad52df35
[ "MIT" ]
2
2017-04-11T18:33:14.000Z
2019-07-03T08:15:30.000Z
Powershell Monitoring Examples/VMware vSphere/vmcreationdeletion2influxdb.ps1
micelshima/InfluxDB-Powershell-Module
0a1f0ba93750001601552cb29bcf5307ad52df35
[ "MIT" ]
6
2017-01-26T03:50:31.000Z
2018-03-20T00:39:52.000Z
#Check new VM's and deleted VM's in VCenter #Mikel V $scriptPath = split-path -parent $MyInvocation.MyCommand.Definition #load influxdb functions import-module "$PSscriptroot\..\..\InfluxDB-Powershell-Module" #load powercli snappin if (!(Get-PSSnapin VMware.VimAutomation.Core -ErrorAction SilentlyContinue)) { Add-PSSnapin VMware.VimAutomation.Core } $LastDays=60 $VC="servervc1.sistemaswin.com" Set-PowerCLIConfiguration -DefaultVIServerMode Single -InvalidCertificateAction Ignore -Confirm:$false $VCServer = Connect-VIserver -server $VC $EventFilterSpecByTime = New-Object VMware.Vim.EventFilterSpecByTime If ($LastDays) { $EventFilterSpecByTime.BeginTime = (get-date).AddDays(-$LastDays) } $EventFilterSpec = New-Object VMware.Vim.EventFilterSpec $EventFilterSpec.Time = $EventFilterSpecByTime $EventFilterSpec.DisableFullMessage = $False $EventFilterSpec.Type = "VmCreatedEvent","VmDeployedEvent","VmClonedEvent","VmDiscoveredEvent","VmRegisteredEvent","VmRemovedEvent" $EventManager = Get-View EventManager $NewVmTasks = $EventManager.QueryEvents($EventFilterSpec) Foreach ($Task in $NewVmTasks) { $unixtime=convertto-unixtime $Task.CreatedTime $username=$Task.UserName -replace("\\","/") $servername=$Task.Vm.name $event="creation" if ($servername -match "_"){$n="0i"}else{$n="1i"} if ($Task -is [Vmware.vim.VmRemovedEvent]) { $event="deletion" $n="-$n" } $body="vmcreationdeletion,location=Sarriguren,vcenter=$VC,servername=$servername,username=$username,event=$event n=$n $unixtime" $body write-influxDB "reportingdb" $body } Disconnect-VIServer $VC -Confirm:$False
38.704545
136
0.72754
854d6375319c6a66f4b9fdd98ed4b46defccc9c5
1,106
cs
C#
src/JobStreet.AdPostingApi.Client/AdPostingApiMessageHandler.cs
seekasia-oss/jobstreet-ad-posting-api-client
d77c69cf231624f4fb675b541d840297fb0b066d
[ "MIT" ]
1
2018-03-01T03:33:04.000Z
2018-03-01T03:33:04.000Z
src/JobStreet.AdPostingApi.Client/AdPostingApiMessageHandler.cs
seekasia-oss/jobstreet-ad-posting-api-client
d77c69cf231624f4fb675b541d840297fb0b066d
[ "MIT" ]
null
null
null
src/JobStreet.AdPostingApi.Client/AdPostingApiMessageHandler.cs
seekasia-oss/jobstreet-ad-posting-api-client
d77c69cf231624f4fb675b541d840297fb0b066d
[ "MIT" ]
1
2020-03-05T00:52:56.000Z
2020-03-05T00:52:56.000Z
using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; namespace JobStreet.AdPostingApi.Client { public class AdPostingApiMessageHandler : DelegatingHandler { static AdPostingApiMessageHandler() { SetProductVersion(typeof(AdPostingApiMessageHandler).Assembly.GetName().Version.ToString()); } internal static void SetProductVersion(string productVersion) { UserAgentProduct = new ProductInfoHeaderValue(typeof(AdPostingApiMessageHandler).Assembly.GetName().Name, productVersion); } private static ProductInfoHeaderValue UserAgentProduct { get; set; } public AdPostingApiMessageHandler(HttpMessageHandler innerHandler) : base(innerHandler) { } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { request.Headers.UserAgent?.Add(UserAgentProduct); return await base.SendAsync(request, cancellationToken); } } }
33.515152
134
0.712477
da5ac05deda39c119604d0d686894ce2746b1a74
1,438
php
PHP
resources/views/Admin/consume.blade.php
snowFragrance/Admin
e87d49f026e30b5baaf370cdfc99eca88f9b2e6c
[ "MIT" ]
null
null
null
resources/views/Admin/consume.blade.php
snowFragrance/Admin
e87d49f026e30b5baaf370cdfc99eca88f9b2e6c
[ "MIT" ]
null
null
null
resources/views/Admin/consume.blade.php
snowFragrance/Admin
e87d49f026e30b5baaf370cdfc99eca88f9b2e6c
[ "MIT" ]
null
null
null
@extends("layouts.main") @section("content") <form class="form-horizontal" method="post"> {{csrf_field()}} <div class="form-group"> <label for="username" class="col-sm-2 control-label">用户</label> <div class="col-sm-10"> <input type="text" class="form-control" id="name" placeholder="用户" name="name" value="{{$user->name}}" disabled> </div> </div> <div class="form-group"> <label for="username" class="col-sm-2 control-label">余额</label> <div class="col-sm-10"> <input type="text" class="form-control" id="name" placeholder="余额" name="moeny" value="{{$user->money}}" disabled> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">套餐</label> <div class="col-sm-10"> <select name="id" id="" class="form-control"> <option value=""> --请选择套餐--</option> @foreach($tc as $t) <option value="{{$t->id}}">{{$t->name}}</option> @endforeach </select> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-success">购买</button> </div> </div> </form> @endsection
35.95
130
0.486787
a34c59ff3d435b52db1d413f9896c8e97f7899c9
1,960
java
Java
23/src/main/java/com/luas/securitylearning/security/web/access/intercept/CustomFilterSecurityInterceptor.java
liuminglei/SpringSecurityLearning
71ec4a134564f12027d269bfb79f8170c5bc14d5
[ "Apache-2.0" ]
43
2020-06-18T09:35:03.000Z
2022-03-23T03:41:01.000Z
41/src/main/java/com/luas/securitylearning/security/web/access/intercept/CustomFilterSecurityInterceptor.java
suofang/SpringSecurityLearning
726d2f985aa6fde298d68f61598c977ff285a353
[ "Apache-2.0" ]
null
null
null
41/src/main/java/com/luas/securitylearning/security/web/access/intercept/CustomFilterSecurityInterceptor.java
suofang/SpringSecurityLearning
726d2f985aa6fde298d68f61598c977ff285a353
[ "Apache-2.0" ]
17
2020-09-03T02:58:22.000Z
2022-03-14T13:26:35.000Z
package com.luas.securitylearning.security.web.access.intercept; import org.springframework.security.access.intercept.InterceptorStatusToken; import org.springframework.security.web.FilterInvocation; import org.springframework.security.web.access.intercept.FilterSecurityInterceptor; import javax.servlet.ServletException; import java.io.IOException; public class CustomFilterSecurityInterceptor extends FilterSecurityInterceptor { private static final String FILTER_APPLIED = "__spring_security_customFilterSecurityInterceptor_filterApplied"; @Override public void invoke(FilterInvocation fi) throws IOException, ServletException { System.out.println(fi.getRequest().getAttribute(FILTER_APPLIED)); System.out.println(isObserveOncePerRequest()); if ((fi.getRequest() != null) && (fi.getRequest().getAttribute(FILTER_APPLIED) != null) && isObserveOncePerRequest()) { // filter already applied to this request and user wants us to observe // once-per-request handling, so don't re-do security checking fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); logger.info("request " + fi.getRequestUrl() + " has already been security checking."); } else { logger.info("request " + fi.getRequestUrl() + " will be security checking."); // first time this request being called, so perform security checking if (fi.getRequest() != null && isObserveOncePerRequest()) { fi.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE); } InterceptorStatusToken token = super.beforeInvocation(fi); try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.finallyInvocation(token); } super.afterInvocation(token, null); } } }
40
115
0.666327
057fe374c346a8027e66f4be3bec5171fd2777ab
540
dart
Dart
lib/enums/quality_enum.dart
JiangJuHong/FlutterTencentRtcPlugin
6b923c43807f72836dd3ad9e9ad324a951c399c0
[ "Apache-2.0" ]
67
2019-12-12T02:41:50.000Z
2022-02-17T12:31:01.000Z
lib/enums/quality_enum.dart
JiangJuHong/FlutterTencentRtcPlugin
6b923c43807f72836dd3ad9e9ad324a951c399c0
[ "Apache-2.0" ]
33
2020-03-13T05:55:09.000Z
2021-07-05T10:07:10.000Z
lib/enums/quality_enum.dart
JiangJuHong/FlutterTencentRtcPlugin
6b923c43807f72836dd3ad9e9ad324a951c399c0
[ "Apache-2.0" ]
22
2020-03-05T02:07:41.000Z
2021-06-10T07:58:55.000Z
/// 质量枚举 enum QualityEnum { // 流畅音质:采样率:16k;单声道;音频裸码率:16kbps;适合语音通话为主的场景,比如在线会议,语音通话。 Speech, // 默认音质:采样率:48k;单声道;音频裸码率:50kbps;SDK 默认的音频质量,如无特殊需求推荐选择之。 Default, // 高音质:采样率:48k;双声道 + 全频带;音频裸码率:128kbps;适合需要高保真传输音乐的场景,比如K歌、音乐直播等。 Music, } class QualityTool { /// 转换为常量类型 /// [value] 枚举 /// [Return] 转换结果 static int toInt(QualityEnum value) { switch (value) { case QualityEnum.Speech: return 1; case QualityEnum.Default: return 2; case QualityEnum.Music: return 3; } } }
20.769231
67
0.633333
87ce26291e3f19881425d5a4aea298c798727e3a
2,041
swift
Swift
WebServiceIOS/ViewController.swift
manelpz/WebServiceIOS
d9637f589e3c9398a7c417cb6d1a9fcda7a644e0
[ "Unlicense" ]
null
null
null
WebServiceIOS/ViewController.swift
manelpz/WebServiceIOS
d9637f589e3c9398a7c417cb6d1a9fcda7a644e0
[ "Unlicense" ]
null
null
null
WebServiceIOS/ViewController.swift
manelpz/WebServiceIOS
d9637f589e3c9398a7c417cb6d1a9fcda7a644e0
[ "Unlicense" ]
null
null
null
// // ViewController.swift // WebServiceIOS // // Created by Emmanuel Lopez Guerrero on 15/06/21. // import UIKit import WebKit class ViewController: UIViewController { var word: String? @IBOutlet var webView: WKWebView! @IBOutlet var SearchField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func SearchButton(_ sender: Any) { if SearchField.text?.isEmpty != nil { word = SearchField.text! } let urlComplete = "https://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&titles=\(word!.replacingOccurrences(of: " ", with: "%20"))" let urlObj = URL(string: urlComplete) let task = URLSession.shared.dataTask(with: urlObj!){ data, request, error in if error != nil { print(error!) }else{ do { let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String:Any] print(json) let querySubJson = json["query"] as! [String:Any] let pagesSubJson = querySubJson["pages"] as! [String: Any] let pageId = pagesSubJson.keys let firstKey = pageId.first! let idSubJson = pagesSubJson[firstKey] as! [String:Any] let extractStringHTML = idSubJson["extract"] as! String DispatchQueue.main.sync { self.webView.loadHTMLString(extractStringHTML, baseURL: nil) } }catch{ print("Json parse error") } } } task.resume() } }
28.746479
160
0.501225
249f0aa3febf2c4b9039e61c25bc6970a3f94a22
18,672
php
PHP
src/Header.php
oneFoldSoftware/php-imap
d6e2ac1c7384f18b854f6574e9da5989aa6d6412
[ "MIT" ]
1
2021-06-23T11:25:13.000Z
2021-06-23T11:25:13.000Z
src/Header.php
Slauta/php-imap
5ad1246e8a966610186208d57ca262686d23361c
[ "MIT" ]
null
null
null
src/Header.php
Slauta/php-imap
5ad1246e8a966610186208d57ca262686d23361c
[ "MIT" ]
null
null
null
<?php /* * File: Header.php * Category: - * Author: M.Goldenbaum * Created: 17.09.20 20:38 * Updated: - * * Description: * - */ namespace Webklex\PHPIMAP; use Carbon\Carbon; use Webklex\PHPIMAP\Exceptions\InvalidMessageDateException; use Webklex\PHPIMAP\Exceptions\MethodNotFoundException; /** * Class Header * * @package Webklex\PHPIMAP */ class Header { /** * Raw header * * @var string $raw */ public $raw = ""; /** * Attribute holder * * @var array $attributes */ protected $attributes = []; /** * Config holder * * @var array $config */ protected $config = []; /** * Fallback Encoding * * @var string */ public $fallback_encoding = 'UTF-8'; /** * Header constructor. * @param $raw_header * * @throws InvalidMessageDateException */ public function __construct($raw_header) { $this->raw = $raw_header; $this->config = ClientManager::get('options'); $this->parse(); } /** * Call dynamic attribute setter and getter methods * @param string $method * @param array $arguments * * @return mixed * @throws MethodNotFoundException */ public function __call($method, $arguments) { if(strtolower(substr($method, 0, 3)) === 'get') { $name = preg_replace('/(.)(?=[A-Z])/u', '$1_', substr(strtolower($method), 3)); if(in_array($name, array_keys($this->attributes))) { return $this->attributes[$name]; } } throw new MethodNotFoundException("Method ".self::class.'::'.$method.'() is not supported'); } /** * Magic getter * @param $name * * @return mixed|null */ public function __get($name) { return $this->get($name); } /** * Get a specific header attribute * @param $name * * @return mixed|null */ public function get($name) { if(isset($this->attributes[$name])) { return $this->attributes[$name]; } return null; } /** * Perform a regex match all on the raw header and return the first result * @param $pattern * * @return mixed|null */ public function find($pattern) { if (preg_match_all($pattern, $this->raw, $matches)) { if (isset($matches[1])) { if(count($matches[1]) > 0) { return $matches[1][0]; } } } return null; } /** * Parse the raw headers * * @throws InvalidMessageDateException */ protected function parse(){ $header = $this->rfc822_parse_headers($this->raw); $this->extractAddresses($header); if (property_exists($header, 'subject')) { $this->attributes["subject"] = $this->decode($header->subject); } if (property_exists($header, 'references')) { $this->attributes["references"] = $this->decode($header->references); } if (property_exists($header, 'message_id')) { $this->attributes["message_id"] = str_replace(['<', '>'], '', $header->message_id); } $this->parseDate($header); foreach ($header as $key => $value) { $key = trim(rtrim(strtolower($key))); if(!isset($this->attributes[$key])){ $this->attributes[$key] = $value; } } $this->extractHeaderExtensions(); $this->findPriority(); } /** * Parse mail headers from a string * @link https://php.net/manual/en/function.imap-rfc822-parse-headers.php * @param $raw_headers * * @return object */ public function rfc822_parse_headers($raw_headers){ $headers = []; $imap_headers = []; if (extension_loaded('imap')) { $imap_headers = (array) \imap_rfc822_parse_headers($this->raw); } $lines = explode("\r\n", $raw_headers); $prev_header = null; foreach($lines as $line) { if (substr($line, 0, 1) === "\t") { $line = substr($line, 2); if ($prev_header !== null) { $headers[$prev_header][] = $line; } }else{ if (($pos = strpos($line, ":")) > 0) { $key = strtolower(substr($line, 0, $pos)); $value = trim(rtrim(strtolower(substr($line, $pos + 1)))); $headers[$key] = [$value]; $prev_header = $key; } } } foreach($headers as $key => $values) { if (isset($imap_headers[$key])) continue; $value = null; switch($key){ case 'from': case 'to': case 'cc': case 'bcc': case 'reply_to': case 'sender': $value = $this->decodeAddresses($values); $headers[$key."address"] = implode(", ", $values); break; default: $value = isset($values[0]) ? $values[0] : $value; break; } $headers[$key] = $value; } return (object) array_merge($headers, $imap_headers); } /** * Decode MIME header elements * @link https://php.net/manual/en/function.imap-mime-header-decode.php * @param string $text The MIME text * * @return array The decoded elements are returned in an array of objects, where each * object has two properties, charset and text. */ public function mime_header_decode($text){ if (extension_loaded('imap')) { return \imap_mime_header_decode($text); } $charset = $this->getEncoding($text); return [(object)[ "charset" => $charset, "text" => $this->convertEncoding($text, $charset) ]]; } /** * Check if a given pair of strings has ben decoded * @param $encoded * @param $decoded * * @return bool */ private function notDecoded($encoded, $decoded) { return 0 === strpos($decoded, '=?') && strlen($decoded) - 2 === strpos($decoded, '?=') && false !== strpos($encoded, $decoded); } /** * Convert the encoding * @param $str * @param string $from * @param string $to * * @return mixed|string */ public function convertEncoding($str, $from = "ISO-8859-2", $to = "UTF-8") { $from = EncodingAliases::get($from, $this->fallback_encoding); $to = EncodingAliases::get($to, $this->fallback_encoding); if ($from === $to) { return $str; } // We don't need to do convertEncoding() if charset is ASCII (us-ascii): // ASCII is a subset of UTF-8, so all ASCII files are already UTF-8 encoded // https://stackoverflow.com/a/11303410 // // us-ascii is the same as ASCII: // ASCII is the traditional name for the encoding system; the Internet Assigned Numbers Authority (IANA) // prefers the updated name US-ASCII, which clarifies that this system was developed in the US and // based on the typographical symbols predominantly in use there. // https://en.wikipedia.org/wiki/ASCII // // convertEncoding() function basically means convertToUtf8(), so when we convert ASCII string into UTF-8 it gets broken. if (strtolower($from) == 'us-ascii' && $to == 'UTF-8') { return $str; } try { if (function_exists('iconv') && $from != 'UTF-7' && $to != 'UTF-7') { return iconv($from, $to, $str); } else { if (!$from) { return mb_convert_encoding($str, $to); } return mb_convert_encoding($str, $to, $from); } } catch (\Exception $e) { if (strstr($from, '-')) { $from = str_replace('-', '', $from); return $this->convertEncoding($str, $from, $to); } else { return $str; } } } /** * Get the encoding of a given abject * @param object|string $structure * * @return string */ public function getEncoding($structure) { if (property_exists($structure, 'parameters')) { foreach ($structure->parameters as $parameter) { if (strtolower($parameter->attribute) == "charset") { return EncodingAliases::get($parameter->value, $this->fallback_encoding); } } }elseif (property_exists($structure, 'charset')) { return EncodingAliases::get($structure->charset, $this->fallback_encoding); }elseif (is_string($structure) === true){ return mb_detect_encoding($structure); } return $this->fallback_encoding; } /** * Try to decode a specific header * @param $value * * @return string|null */ private function decode($value) { $original_value = $value; $decoder = $this->config['decoder']['message']; if ($value !== null) { if($decoder === 'utf-8' && extension_loaded('imap')) { $value = \imap_utf8($value); if (strpos(strtolower($value), '=?utf-8?') === 0) { $value = mb_decode_mimeheader($value); } if ($this->notDecoded($original_value, $value)) { $decoded_value = $this->mime_header_decode($value); if (count($decoded_value) > 0) { if(property_exists($decoded_value[0], "text")) { $value = $decoded_value[0]->text; } } } }elseif($decoder === 'iconv') { $value = iconv_mime_decode($value); }else{ $value = mb_decode_mimeheader($value); } if (strpos(strtolower($value), '=?utf-8?') === 0) { $value = mb_decode_mimeheader($value); } if ($this->notDecoded($original_value, $value)) { $value = $this->convertEncoding($original_value, $this->getEncoding($original_value)); } } return $value; } /** * Try to extract the priority from a given raw header string */ private function findPriority() { if(($priority = $this->get("x-priority")) === null) return; switch($priority){ case IMAP::MESSAGE_PRIORITY_HIGHEST; $priority = IMAP::MESSAGE_PRIORITY_HIGHEST; break; case IMAP::MESSAGE_PRIORITY_HIGH; $priority = IMAP::MESSAGE_PRIORITY_HIGH; break; case IMAP::MESSAGE_PRIORITY_NORMAL; $priority = IMAP::MESSAGE_PRIORITY_NORMAL; break; case IMAP::MESSAGE_PRIORITY_LOW; $priority = IMAP::MESSAGE_PRIORITY_LOW; break; case IMAP::MESSAGE_PRIORITY_LOWEST; $priority = IMAP::MESSAGE_PRIORITY_LOWEST; break; default: $priority = IMAP::MESSAGE_PRIORITY_UNKNOWN; break; } $this->attributes["priority"] = $priority; } /** * Extract a given part as address array from a given header * @param $values * * @return array */ private function decodeAddresses($values) { $addresses = []; foreach($values as $address) { if (preg_match( '/^(?:(?P<name>.+)\s)?(?(name)<|<?)(?P<email>[^\s]+?)(?(name)>|>?)$/', $address, $matches )){ $name = trim(rtrim($matches["name"])); $email = trim(rtrim($matches["email"])); list($mailbox, $host) = explode("@", $email); $addresses[] = (object) [ "personal" => $name, "mailbox" => $mailbox, "host" => $host, ]; } } return $addresses; } /** * Extract a given part as address array from a given header * @param object $header */ private function extractAddresses($header) { foreach(['from', 'to', 'cc', 'bcc', 'reply_to', 'sender', 'in_reply_to'] as $key){ if (property_exists($header, $key)) { $this->attributes[$key] = $this->parseAddresses($header->$key); } } } /** * Parse Addresses * @param $list * * @return array */ private function parseAddresses($list) { $addresses = []; foreach ($list as $item) { $address = (object) $item; if (!property_exists($address, 'mailbox')) { $address->mailbox = false; } if (!property_exists($address, 'host')) { $address->host = false; } if (!property_exists($address, 'personal')) { $address->personal = false; } else { $personalParts = $this->mime_header_decode($address->personal); if(is_array($personalParts)) { $address->personal = ''; foreach ($personalParts as $p) { $address->personal .= $this->convertEncoding($p->text, $this->getEncoding($p)); } } } $address->mail = ($address->mailbox && $address->host) ? $address->mailbox.'@'.$address->host : false; $address->full = ($address->personal) ? $address->personal.' <'.$address->mail.'>' : $address->mail; $addresses[] = $address; } return $addresses; } /** * Search and extract potential header extensions */ private function extractHeaderExtensions(){ foreach ($this->attributes as $key => $value) { if (is_string($value) === true) { if (($pos = strpos($value, ";")) !== false){ $original = substr($value, 0, $pos); $this->attributes[$key] = trim(rtrim($original)); $extensions = explode(";", substr($value, $pos + 1)); foreach($extensions as $extension) { if (($pos = strpos($extension, "=")) !== false){ $key = substr($extension, 0, $pos); $value = substr($extension, $pos + 1); $value = str_replace('"', "", $value); $this->attributes[trim(rtrim(strtolower($key)))] = trim(rtrim($value)); } } } } } } /** * Exception handling for invalid dates * * Currently known invalid formats: * ^ Datetime ^ Problem ^ Cause * | Mon, 20 Nov 2017 20:31:31 +0800 (GMT+8:00) | Double timezone specification | A Windows feature * | Thu, 8 Nov 2018 08:54:58 -0200 (-02) | * | | and invalid timezone (max 6 char) | * | 04 Jan 2018 10:12:47 UT | Missing letter "C" | Unknown * | Thu, 31 May 2018 18:15:00 +0800 (added by) | Non-standard details added by the | Unknown * | | mail server | * | Sat, 31 Aug 2013 20:08:23 +0580 | Invalid timezone | PHPMailer bug https://sourceforge.net/p/phpmailer/mailman/message/6132703/ * * Please report any new invalid timestamps to [#45](https://github.com/Webklex/php-imap/issues) * * @param object $header * * @throws InvalidMessageDateException */ private function parseDate($header) { if (property_exists($header, 'date')) { $parsed_date = null; $date = $header->date; if(preg_match('/\+0580/', $date)) { $date = str_replace('+0580', '+0530', $date); } $date = trim(rtrim($date)); try { $parsed_date = Carbon::parse($date); } catch (\Exception $e) { switch (true) { case preg_match('/([0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ UT)+$/i', $date) > 0: case preg_match('/([A-Z]{2,3}\,\ [0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ UT)+$/i', $date) > 0: $date .= 'C'; break; case preg_match('/([A-Z]{2,3}\,\ [0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ \+[0-9]{2,4}\ \(\+[0-9]{1,2}\))+$/i', $date) > 0: case preg_match('/([A-Z]{2,3}[\,|\ \,]\ [0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}.*)+$/i', $date) > 0: case preg_match('/([A-Z]{2,3}\,\ [0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ [\-|\+][0-9]{4}\ \(.*)\)+$/i', $date) > 0: case preg_match('/([A-Z]{2,3}\, \ [0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{4}\ [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\ [\-|\+][0-9]{4}\ \(.*)\)+$/i', $date) > 0: case preg_match('/([0-9]{1,2}\ [A-Z]{2,3}\ [0-9]{2,4}\ [0-9]{2}\:[0-9]{2}\:[0-9]{2}\ [A-Z]{2}\ \-[0-9]{2}\:[0-9]{2}\ \([A-Z]{2,3}\ \-[0-9]{2}:[0-9]{2}\))+$/i', $date) > 0: $array = explode('(', $date); $array = array_reverse($array); $date = trim(array_pop($array)); break; } try{ $parsed_date = Carbon::parse($date); } catch (\Exception $_e) { throw new InvalidMessageDateException("Invalid message date. ID:".$this->get("message_id"), 1100, $e); } } $this->attributes["date"] = $parsed_date; } } /** * Get all available attributes * * @return array */ public function getAttributes() { return $this->attributes; } }
33.224199
191
0.472526
4bdd63265ee2f575093b3577c47443e326ff3efd
22,724
dart
Dart
lib/screens/taskpage.dart
mguney788/my2to
f3bdfce9f4b9ba60edab56977e27a75995a236bc
[ "Apache-2.0" ]
null
null
null
lib/screens/taskpage.dart
mguney788/my2to
f3bdfce9f4b9ba60edab56977e27a75995a236bc
[ "Apache-2.0" ]
1
2021-09-24T17:22:36.000Z
2021-09-24T17:22:36.000Z
lib/screens/taskpage.dart
mguney788/my2to
f3bdfce9f4b9ba60edab56977e27a75995a236bc
[ "Apache-2.0" ]
null
null
null
import 'dart:ui'; import 'package:date_time_picker/date_time_picker.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:my2doapp/database_helper_fs.dart'; import 'package:my2doapp/googleAuth_helper.dart'; import 'package:my2doapp/models/task.dart'; import 'package:my2doapp/models/todo.dart'; import '../widgets.dart'; class TaskPage extends StatefulWidget { final Task task; TaskPage({@required this.task}); @override _TaskPageState createState() => _TaskPageState(); } class _TaskPageState extends State<TaskPage> { String _taskId = ""; String _taskTitle = ""; String _taskDescription = ""; DatabaseHelper_fs _dbHelper = DatabaseHelper_fs(); FocusNode _titleFocus; FocusNode _descFocus; FocusNode _dueDateFocus; FocusNode _priorityFocus; FocusNode _todoDescFocus; FocusNode _todoDueDateFocus; FocusNode _todoPriorityFocus; TextEditingController _titleController = TextEditingController(); TextEditingController _descController = TextEditingController(); TextEditingController _dueDateController = TextEditingController(); TextEditingController _priorityController = TextEditingController(text: "1"); TextEditingController _todoDescController = TextEditingController(); TextEditingController _todoDueDateController = TextEditingController(); TextEditingController _todoPriorityController = TextEditingController(text: "1"); bool _contentVisible = false; @override void initState() { print("initState method ran"); final DateTime now = DateTime.now(); final DateFormat formatter = DateFormat('yyyy-MM-dd'); _dueDateController.text = formatter.format(now); _todoDueDateController.text = formatter.format(now); print(_dueDateController.text); _titleFocus = FocusNode(); _descFocus = FocusNode(); _dueDateFocus = FocusNode(); _priorityFocus = FocusNode(); _todoDescFocus = FocusNode(); _todoDueDateFocus = FocusNode(); _todoPriorityFocus = FocusNode(); if (widget.task != null) { _taskId = widget.task.id; _taskTitle = widget.task.title; _taskDescription = widget.task.description; _titleController.text = widget.task.title; _descController.text = widget.task.description; _dueDateController.text = widget.task.dueDate; _priorityController.text = widget.task.priority.toString(); _contentVisible = true; } else _titleFocus.requestFocus(); super.initState(); } @override void dispose() { _titleFocus.dispose(); _descFocus.dispose(); _dueDateFocus.dispose(); _priorityFocus.dispose(); _todoDescFocus.dispose(); _todoDueDateFocus.dispose(); _todoPriorityFocus.dispose(); _titleController.dispose(); _descController.dispose(); _dueDateController.dispose(); _priorityController.dispose(); _todoDescController.dispose(); _todoDueDateController.dispose(); _todoPriorityController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Container( child: Stack( children: [ Container( padding: EdgeInsets.fromLTRB(10, 10, 10, 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ IconButton( icon: Icon(Icons.arrow_back), iconSize: 32, onPressed: () { Navigator.pop(context); }, ), SizedBox( width: 12, ), Expanded( child: TextField( focusNode: _titleFocus, onSubmitted: (value) async { //check if the field is not empty if (value != "") { //check if the task is null if (widget.task == null) { Task _newTask = Task( email: GoogleAuthHelper.userEmail, title: value, description: "", dueDate: _dueDateController.text, priority: int.parse(_priorityController.text), isDone: 0); _taskId = await _dbHelper.insertTask(_newTask); print("New Task Id:$_taskId"); setState(() { _taskTitle = value; _contentVisible = true; }); } else { print("Update the existing task"); _dbHelper.updateTaskTitle(_taskId, value); } _descFocus.requestFocus(); } }, controller: _titleController, decoration: InputDecoration( hintText: "Enter Task Title", border: InputBorder.none, ), style: TextStyle(fontSize: 26.0, /*color: Color(0xFF211551),*/ fontWeight: FontWeight.bold)), ), ], ), SizedBox( height: 10, ), Visibility( visible: _contentVisible, child: TextField( focusNode: _descFocus, onSubmitted: (value) async { if (value != "") { //check if the task is null if (_taskId != "") { print("taskid:$_taskId"); await _dbHelper.updateTaskDescription(_taskId, value); } } _dueDateFocus.requestFocus(); }, controller: _descController, decoration: InputDecoration( labelText: "Description", hintText: "Enter Description for the task", contentPadding: EdgeInsets.symmetric(horizontal: 24.0), ), ), ), SizedBox(height: 15), Row(mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Visibility( visible: _contentVisible, child: Expanded( child: DateTimePicker( type: DateTimePickerType.date, focusNode: _dueDateFocus, dateMask: 'dd/MM/yyyy', controller: _dueDateController, //initialValue: _initialValue, firstDate: DateTime(DateTime.monthsPerYear), lastDate: DateTime(2100), //icon: Icon(Icons.event), dateLabelText: 'Due Date', //locale: Locale('en', 'US'), onChanged: (val) async { if (val != "") { //check if the task is null if (_taskId != "") { await _dbHelper.updateTaskDueDate(_taskId, val); _priorityFocus.requestFocus(); } } }), ), ), SizedBox(width: 15), Visibility( visible: _contentVisible, child: Expanded( child: DropdownButtonFormField<String>( decoration: InputDecoration( labelText: 'Priority', //icon: Icon(Icons.priority_high), ), value: _priorityController.text, focusNode: _priorityFocus, //icon: const Icon(Icons.priority_high), iconSize: 34, elevation: 16, //style: const TextStyle(color: Colors.deepPurple), onChanged: (String value) async { await _dbHelper.updateTaskPriority(_taskId, int.parse(value)); setState(() { _priorityController.text = value; _todoDescFocus.requestFocus(); }); }, items: [ DropdownMenuItem( child: Text("P1"), value: "1", ), DropdownMenuItem( child: Text("P2"), value: "2", ), DropdownMenuItem( child: Text("P3"), value: "3", ), DropdownMenuItem( child: Text("P4"), value: "4", ) ], ), ), ) ]), SizedBox(height: 15), Visibility( visible: _contentVisible, child: FutureBuilder( initialData: [], future: _dbHelper.getTodos(_taskId), builder: (context, snapshot) { return Expanded( child: ListView.builder( itemCount: snapshot.data != null ? snapshot.data.length : 0, itemBuilder: (context, index) { return TodoWidget( text: snapshot.data[index].title, dueDate: snapshot.data[index].dueDate, priority: snapshot.data[index].priority, isDone: snapshot.data[index].isDone == 0 ? false : true, onDelete: () async { await _dbHelper.deleteTodoTask(_taskId, snapshot.data[index].id); setState(() {}); }, onUpdate: () async { if (snapshot.data[index].isDone == 0) { await _dbHelper.updateTodoDone(_taskId, snapshot.data[index].id, 1); final todoCompletedSnackBar = SnackBar( content: Text('The ToDo item was completed.'), action: SnackBarAction( label: 'Undo', onPressed: () async { await _dbHelper.updateTodoDone(_taskId, snapshot.data[index].id, 0); setState(() {}); })); ScaffoldMessenger.of(context).showSnackBar(todoCompletedSnackBar); } else { await _dbHelper.updateTodoDone(_taskId, snapshot.data[index].id, 0); ScaffoldMessenger.of(context).hideCurrentSnackBar(); } setState(() {}); }, ); }), ); }, ), ), Visibility( visible: _contentVisible, child: Builder(builder: (context) { return OutlinedButton.icon( label: Text('Add new ToDo item'), icon: Icon(Icons.add, size: 18), onPressed: () { _todoDescFocus.requestFocus(); showModalBottomSheet( context: context, builder: (context) { return Container( padding: EdgeInsets.symmetric(horizontal: 10.0), child: Column( children: [ Row( children: [ Expanded( child: TextField( focusNode: _todoDescFocus, controller: _todoDescController, onSubmitted: (val) async { if (val != "") { _todoDescController.text = val; _todoDueDateFocus.requestFocus(); } }, decoration: InputDecoration( hintText: "Enter new ToDo item...", border: InputBorder.none, ), ), ), ], ), Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Visibility( visible: _contentVisible, child: Expanded( child: DateTimePicker( type: DateTimePickerType.date, focusNode: _dueDateFocus, dateMask: 'dd/MM/yyyy', controller: _todoDueDateController, //initialValue: _initialValue, firstDate: DateTime(DateTime.monthsPerYear), lastDate: DateTime(2100), //icon: Icon(Icons.event), dateLabelText: 'ToDo - Due Date', //locale: Locale('en', 'US'), onChanged: (val) async { if (val != "") { _todoDueDateController.text = val; _todoPriorityFocus.requestFocus(); } }), ), ), SizedBox(width: 15.0), Visibility( visible: _contentVisible, child: Expanded( child: DropdownButtonFormField<String>( decoration: InputDecoration( labelText: 'ToDo - Priority', //icon: Icon(Icons.priority_high), ), value: _todoPriorityController.text, focusNode: _priorityFocus, //icon: const Icon(Icons.priority_high), iconSize: 34, elevation: 16, //style: const TextStyle(color: Colors.deepPurple), onChanged: (String val) async { if (val != "") { setState(() { _todoPriorityController.text = val; }); } }, items: [ DropdownMenuItem( child: Text("P1"), value: "1", ), DropdownMenuItem( child: Text("P2"), value: "2", ), DropdownMenuItem( child: Text("P3"), value: "3", ), DropdownMenuItem( child: Text("P4"), value: "4", ) ], ), ), ), SizedBox(width: 15.0), IconButton( icon: Icon( Icons.send, ), onPressed: () async { print("taskId:$_taskId"); if (_taskId != "") { if (_todoDescController.text == "") return; Todo _newTodo = Todo( title: _todoDescController.text, dueDate: _todoDueDateController.text, priority: int.parse(_todoPriorityController.text), isDone: 0, taskId: _taskId, ); await _dbHelper.insertTodo(_taskId, _newTodo); setDefaultValueForTodoElement(); Navigator.pop(context); print("New Task has been created"); setState(() { _todoDescFocus.requestFocus(); }); } }) ]), ], ), ); }); }); }), ), ], ), ), /*Visibility( visible: _contentVisible, child: Positioned( bottom: 20.0, right: 20.0, child: GestureDetector( onTap: () async { if (_taskId != 0) { await _dbHelper.deleteTask(_taskId); Navigator.pop(context); } }, child: Container( width: 60.0, height: 60.0, decoration: BoxDecoration(color: Color(0xFFFE3577), borderRadius: BorderRadius.circular(20.0)), child: Image( image: AssetImage("assets/images/delete_icon.png"), ), ), ), ), )*/ ], )), ), ); } void setDefaultValueForTodoElement() { _todoDescController.text = ""; _todoDueDateController.text = DateTime.now().toString(); _todoPriorityController.text = "1"; } }
46.950413
152
0.347738
23b2eacfd5f171f9c62e852484cf9a6cb8cbef67
626
js
JavaScript
src/payment/actions/payByPaypal.js
Ricky-Nz/knocknock-app
792aa82fa6e2135a6c758f00160ce6c7abc512ea
[ "BSD-3-Clause" ]
null
null
null
src/payment/actions/payByPaypal.js
Ricky-Nz/knocknock-app
792aa82fa6e2135a6c758f00160ce6c7abc512ea
[ "BSD-3-Clause" ]
null
null
null
src/payment/actions/payByPaypal.js
Ricky-Nz/knocknock-app
792aa82fa6e2135a6c758f00160ce6c7abc512ea
[ "BSD-3-Clause" ]
null
null
null
import fetch from '../../fetch'; export const ACTION_PAY_BY_PAYPAL = 'ACTION_PAY_BY_PAYPAL'; export function payByPaypal(orderId, amount) { return (dispatch, getState) => { const { session } = getState(); fetch({ dispatch, actionName: ACTION_PAY_BY_PAYPAL, method: 'POST', path: `orders/${orderId}/paypal`, headers: { 'Authorization': `${session.tokenType} ${session.token}` }, body: { id: orderId, payment_total: amount, return_url: 'http://www.knocknock.com', cancel_url: 'http://www.yahoo.com', payment_desc: `Knocknock Payment for Order ID-${orderId}` } }); }; }
23.185185
61
0.648562
e9b3ec4054e325aebd95a95584ffe4587f8e216d
2,846
rs
Rust
osnma-longan-nano-client/src/main.rs
daniestevez/galileo-osnma
daf38c081d764bac53854b12972972a3408f2d3e
[ "Apache-2.0", "MIT" ]
16
2022-03-26T17:51:19.000Z
2022-03-28T17:17:22.000Z
osnma-longan-nano-client/src/main.rs
daniestevez/galileo-osnma
daf38c081d764bac53854b12972972a3408f2d3e
[ "Apache-2.0", "MIT" ]
3
2022-03-28T15:40:47.000Z
2022-03-31T21:11:25.000Z
osnma-longan-nano-client/src/main.rs
daniestevez/galileo-osnma
daf38c081d764bac53854b12972972a3408f2d3e
[ "Apache-2.0", "MIT" ]
1
2022-03-26T19:26:19.000Z
2022-03-26T19:26:19.000Z
use galileo_osnma::galmon::{navmon::nav_mon_message::GalileoInav, transport::ReadTransport}; use galileo_osnma::{ types::{InavWord, OsnmaDataMessage}, Gst, Wn, }; use std::error::Error; use std::io::{BufRead, BufReader}; struct Serial { writer: Box<dyn serialport::SerialPort>, reader: BufReader<Box<dyn serialport::SerialPort>>, } impl Serial { fn new(port: &str) -> Result<Serial, Box<dyn Error>> { let port = serialport::new(port, 115_200) .timeout(std::time::Duration::from_secs(3600)) .open()?; let writer = port.try_clone()?; let reader = BufReader::new(port); Ok(Serial { writer, reader }) } fn read_until_ready(&mut self) -> Result<(), Box<dyn Error>> { loop { let mut line = String::new(); self.reader.read_line(&mut line)?; print!("{}", line); if line == "READY\r\n" { return Ok(()); } } } fn send_inav(&mut self, inav: &InavWord, svn: usize, gst: Gst) -> Result<(), Box<dyn Error>> { write!( &mut self.writer, "{} {} {} {}\r\n", svn, gst.wn(), gst.tow(), hex::encode(&inav) )?; Ok(()) } fn send_osnma( &mut self, osnma: &OsnmaDataMessage, svn: usize, gst: Gst, ) -> Result<(), Box<dyn Error>> { write!( &mut self.writer, "{} {} {} {}\r\n", svn, gst.wn(), gst.tow(), hex::encode(&osnma) )?; Ok(()) } } fn main() -> Result<(), Box<dyn Error>> { let args: Vec<_> = std::env::args().collect(); let port = &args[1]; let mut serial = Serial::new(port)?; let mut read_galmon = ReadTransport::new(std::io::stdin()); loop { let packet = read_galmon.read_packet()?; if let Some( inav @ GalileoInav { contents: inav_word, reserved1: osnma_data, .. }, ) = &packet.gi { // This is needed because sometimes we can see a TOW of 604801 let secs_in_week = 604800; let tow = inav.gnss_tow % secs_in_week; let wn = Wn::try_from(inav.gnss_wn).unwrap() + Wn::try_from(inav.gnss_tow / secs_in_week).unwrap(); let gst = Gst::new(wn, tow); let svn = usize::try_from(inav.gnss_sv).unwrap(); serial.read_until_ready()?; serial.send_inav(inav_word[..].try_into().unwrap(), svn, gst)?; if let Some(osnma_data) = osnma_data { serial.read_until_ready()?; serial.send_osnma(osnma_data[..].try_into().unwrap(), svn, gst)?; } } } }
29.040816
98
0.494027
af1375e385bc0012a5c7a57c5d3aa7b8ee300c49
2,532
py
Python
insanic/services/registry.py
crazytruth/insanic
f9b61611317d873fe7688a5fd13eecb9a496ead5
[ "MIT" ]
4
2020-10-13T04:34:21.000Z
2022-02-18T05:34:03.000Z
insanic/services/registry.py
crazytruth/insanic
f9b61611317d873fe7688a5fd13eecb9a496ead5
[ "MIT" ]
1
2020-09-29T06:59:36.000Z
2020-09-29T06:59:36.000Z
insanic/services/registry.py
crazytruth/insanic
f9b61611317d873fe7688a5fd13eecb9a496ead5
[ "MIT" ]
null
null
null
from collections.abc import Mapping from typing import Type from insanic.conf import settings from insanic.functional import LazyObject, empty from insanic.services import Service class LazyServiceRegistry(LazyObject): service_class = Service def _setup(self): self._wrapped = ServiceRegistry(self.service_class) def __repr__(self): if self._wrapped is empty: return "<LazyServiceRegistry> [Unevaluated]" return f"<LazyServiceRegistry> {self._wrapped.__class__.__name__}" def __getitem__(self, item): if self._wrapped is empty: self._setup() return self._wrapped[item] def __len__(self): # pragma: no cover if self._wrapped is empty: self._setup() return len(self._wrapped) def __iter__(self): # pragma: no cover if self._wrapped is empty: self._setup() return iter(self._wrapped) def reset(self): self._wrapped = empty class ServiceRegistry(Mapping): def __init__(self, service_class: Type[Service] = Service): for s in self.available_services: self.__dict__[s] = None self.service_class = service_class @property def available_services(self) -> set: return set( list(settings.SERVICE_CONNECTIONS) + list(settings.REQUIRED_SERVICE_CONNECTIONS) ) def __len__(self): # pragma: no cover return len(self.__dict__) def __getitem__(self, item): try: value = self.__dict__[item] except KeyError: if item not in self.available_services: raise RuntimeError( "{0} service does not exist. Only the following: {1}".format( item, ", ".join(self.keys()) ) ) else: # pragma: no cover raise LookupError( "Settings for either `SERVICE_CONNECTIONS` or " "`REQUIRED_SERVICE_CONNECTIONS` must have been modified after " "initialization." ) else: if value is None: value = self.service_class(item) self.__dict__[item] = value return value def __iter__(self): return iter( { k: v for k, v in self.__dict__.items() if k in self.available_services } ) registry = LazyServiceRegistry()
27.225806
83
0.574645
a9eeda6404371820055a6ccabbe7de7aba17cbf6
7,852
php
PHP
application/models/M_in_out.php
ferrynurr/alugara-fishinfo_dashboard
7ae87002c71c0e26ec90d409b2c5a3af4b90c400
[ "MIT" ]
null
null
null
application/models/M_in_out.php
ferrynurr/alugara-fishinfo_dashboard
7ae87002c71c0e26ec90d409b2c5a3af4b90c400
[ "MIT" ]
null
null
null
application/models/M_in_out.php
ferrynurr/alugara-fishinfo_dashboard
7ae87002c71c0e26ec90d409b2c5a3af4b90c400
[ "MIT" ]
null
null
null
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class M_in_out extends CI_Model { function __construct() { parent::__construct(); } private function query($uri) { $this->db->select('a.trader_name, a.tgl, a.komoditas_id, b.jenis_komoditas, b.komoditas_kel_id, c.nama_komoditas_kel, a.satuan_awal'); if($uri == 'dom_masuk') { $this->db->select('a.dom_masuk_id, a.asal'); $this->db->from('dash_dom_masuk as a'); } elseif($uri == 'dom_keluar') { $this->db->select('a.dom_keluar_id, a.tujuan'); $this->db->from('dash_dom_keluar as a'); } elseif($uri == 'ekspor') { $this->db->select('a.ekspor_id, a.tujuan'); $this->db->from('dash_ekspor as a'); } elseif($uri == 'impor') { $this->db->select('a.impor_id, a.asal'); $this->db->from('dash_impor as a'); } $this->db->join('dash_komoditas as b', 'b.komoditas_id = a.komoditas_id','left'); $this->db->join('dash_komoditas_kelompok as c', 'c.komoditas_kel_id = b.komoditas_kel_id','left'); $this->db->order_by('a.trader_name', 'asc'); } public function dataTablesNew($filter) { $this->query($filter['uri']); if(isset($filter['filter_all'])) { $datas = $filter['filter_all']; $dataarr = array(); foreach ($datas as $dat) { $dataarr[] = explode("|", $dat)[0]; } $i=0; $dataand=''; foreach ($dataarr as $da) { if ($i==0) $dataand = "(".$da.")"; else $dataand .= " AND (".$da.")"; $i +=1; } $saring = str_replace("~","%",$dataand); $saring2 = str_replace("^","<",$saring); $this->db->where($saring2); } #-- FILTER LANJUTAN --> if( isset($filter['selected_group'])) { $this->db->select('SUM(a.jumlah_awal) jumlah_awal, SUM(a.nilai) nilai'); $this->db->group_by($filter['selected_group']); }else{ $this->db->select('a.jumlah_awal, a.nilai'); } $data = $this->db->get(); return $data; } public function simpanDash($filter) { $selgrub = ''; $order =''; $grubby =''; $sel_from =''; $sel_filter= ''; $wherefile_all = ''; $uri = $filter['uri']; if(isset($filter['filter_all'])) { $datas = $filter['filter_all']; $dataarr = array(); foreach ($datas as $dat) { $dataarr[] = explode("|", $dat)[0]; } $i=0; $dataand=''; foreach ($dataarr as $da) { if ($i==0) $dataand = "(".$da.")"; else $dataand .= " AND (".$da.")"; $i +=1; } $saring = str_replace("~","%",$dataand); $saring2 = str_replace("^","<",$saring); //$this->db->where($saring2); $wherefile_all = "AND ".$dataand; } #-- FILTER LANJUTAN --> if( isset($filter['selected_group'])) { $selgrub = ",SUM(a.jumlah_awal) jumlah_awal, SUM(a.nilai) nilai"; $grubby = "GROUP BY ".implode(",", $filter['selected_group']); } else{ $selgrub = ",a.jumlah_awal, a.nilai"; $order = "ORDER BY a.trader_name ASC"; } if($uri == 'dom_masuk') { $sel_filter = ',a.dom_masuk_id, a.asal'; $sel_from = 'dash_dom_masuk'; } elseif($uri == 'dom_keluar') { $sel_filter = ',a.dom_keluar_id, a.tujuan'; $sel_from = 'dash_dom_keluar'; } elseif($uri == 'ekspor') { $sel_filter = ',a.ekspor_id, a.tujuan'; $sel_from = 'dash_ekspor'; } elseif($uri == 'impor') { $sel_filter = ',a.impor_id, a.asal'; $sel_from = 'dash_impor'; } $query = "SELECT a.trader_name, a.tgl, a.komoditas_id, b.jenis_komoditas, c.nama_komoditas_kel, a.satuan_awal ". $selgrub." ".$sel_filter." FROM ".$sel_from." AS a LEFT JOIN dash_komoditas as b ON b.komoditas_id = a.komoditas_id LEFT JOIN dash_komoditas_kelompok as C ON c.komoditas_kel_id = b.komoditas_kel_id WHERE a.trader_name IS NOT NULL ".$wherefile_all." ".$grubby." ".$order; return $query; } public function dataPivot($filter) { $uri = $filter['uri']; foreach ($filter['pengukuran'] as $key) { if(isset($key)){ // if ($key=='count') $this->db->select("count(*) as count"); if ($key!='count') { if ($filter['operator']=='sum') $this->db->select("sum(a.".$key.") as ".$key); if ($filter['operator']=='avg') $this->db->select("avg(a.".$key.") as ".$key); } } } if ($filter['baris']){ foreach ($filter['baris'] as $key) { if(isset($key) and $key!=''){ $this->db->select($key); } } } if($uri == 'dom_masuk') { //$this->db->select('a.dom_masuk_id, a.asal'); $this->db->from('dash_dom_masuk as a'); } elseif($uri == 'dom_keluar') { //$this->db->select('a.dom_keluar_id, a.tujuan'); $this->db->from('dash_dom_keluar as a'); } elseif($uri == 'ekspor') { //$this->db->select('a.ekspor_id, a.tujuan'); $this->db->from('dash_ekspor as a'); } elseif($uri == 'impor') { // $this->db->select('a.impor_id, a.asal'); $this->db->from('dash_impor as a'); } $this->db->join('dash_komoditas as b', 'b.komoditas_id = a.komoditas_id','left'); $this->db->join('dash_komoditas_kelompok as c', 'c.komoditas_kel_id = b.komoditas_kel_id','left'); $this->db->order_by('a.trader_name', 'asc'); if(isset($filter['filter_all']) and $filter['filter_all']!='') { $datas = $filter['filter_all']; $dataarr = array(); foreach ($datas as $dat) { $dataarr[] = explode("|", $dat)[0]; } $i=0; $dataand=''; foreach ($dataarr as $da) { if ($i==0) $dataand = "(".$da.")"; else $dataand .= " AND (".$da.")"; $i +=1; } //$this->db->where($dataand); $saring = str_replace("~","%",$dataand); $saring2 = str_replace("^","<",$saring); $this->db->where($saring2); } if ($filter['baris']){ foreach ($filter['baris'] as $key) { if(isset($filter['baris']) and $filter['baris']!=''){ $this->db->group_by($filter['baris']); } } } $data = $this->db->get(); return $data; } public function save($tbl, $data) { $this->db->insert($tbl, $data); } public function update($tbl, $data, $where) { $this->db->set($data); $this->db->where($where); $this->db->update($tbl); return $this->db->affected_rows(); } public function delete($tb, $data) { $this->db->where($data); $this->db->delete($tb); } public function get_byID($uri, $data) { $this->query($uri); $this->db->select('a.jumlah_awal, a.nilai'); $this->db->where($data); $data = $this->db->get(); return $data; } }
26.173333
391
0.458482
2f411fc69db0d4b587deda7916a6742fc93a78ec
1,814
js
JavaScript
src/js/modules/videoHideDanmu/UI/index.js
OpportunityLiu/bilibili-helper
c6c08d802c520391207fb431fe7c62422978251c
[ "MIT" ]
1
2020-11-26T02:07:58.000Z
2020-11-26T02:07:58.000Z
src/js/modules/videoHideDanmu/UI/index.js
3318193168/bilibili-helper
faa240996154587e82b5fa5704db6d369184e581
[ "MIT" ]
null
null
null
src/js/modules/videoHideDanmu/UI/index.js
3318193168/bilibili-helper
faa240996154587e82b5fa5704db6d369184e581
[ "MIT" ]
1
2020-12-06T13:27:19.000Z
2020-12-06T13:27:19.000Z
/** * Author: DrowsyFlesh * Create: 2018/11/22 * Description: */ import {UI} from 'Libs/UI'; import _ from 'lodash'; export class VideoHideDanmuUI extends UI { constructor() { super({ name: 'videoHideDanmu', dependencies: ['videoAnchor'], }); this.btn1 = null; this.btn2 = null; } load = (containers, settings) => { if (!settings.on) { return Promise.resolve(); } return new Promise(resolve => { this.hide(); const player = document.querySelector('#bofqi'); player && new MutationObserver((mutationList) => { mutationList.forEach((mutation) => { if (mutation.addedNodes.length > 0) { mutation.addedNodes.forEach((dom) => { if (dom.tagName === 'VIDEO' || dom.tagName === 'INPUT') { this.btn1 = document.querySelector('.bilibili-player-video-control .bilibili-player-iconfont.bilibili-player-iconfont-danmaku'); this.btn2 = document.querySelector('.bilibili-player-video-danmaku-switch input[type=checkbox]'); setTimeout(this.hide, 1000); } }); } }); }).observe(player, { subtree: true, childList: true, }); resolve(); }); }; hide = () => { if (this.btn1 && !this.btn1.getAttribute('bibili-helper-data')) { this.btn1.setAttribute('bibili-helper-data', true); this.btn1.click(); } else if (this.btn2 && this.btn2.checked) { this.btn2.click(); } }; }
32.981818
160
0.475193