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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
704d0e99305c46e61220db8ac17232c1c61a50e7 | 761 | swift | Swift | SwiftAudioPlayer/Extensions/FileManager+MusicFiles.swift | dun198/SwiftAudioPlayer | 3ec6da3b33dcff1823bd665441a6402be73773d5 | [
"MIT"
] | 34 | 2018-07-27T15:58:29.000Z | 2022-01-26T00:59:45.000Z | SwiftAudioPlayer/Extensions/FileManager+MusicFiles.swift | Dunkeeel/SwiftAudioPlayer | 3ec6da3b33dcff1823bd665441a6402be73773d5 | [
"MIT"
] | 2 | 2020-11-02T20:22:39.000Z | 2021-09-25T18:41:38.000Z | SwiftAudioPlayer/Extensions/FileManager+MusicFiles.swift | Dunkeeel/SwiftAudioPlayer | 3ec6da3b33dcff1823bd665441a6402be73773d5 | [
"MIT"
] | 12 | 2018-08-07T08:20:04.000Z | 2021-05-04T02:49:03.000Z | //
// FileManager.swift
// SwiftAudioPlayer
//
// Created by Tobias Dunkel on 01.04.18.
// Copyright © 2018 Tobias Dunkel. All rights reserved.
//
import Foundation
extension FileManager {
internal func filteredMusicFileURLs(inDirectory directory: String) -> [URL] {
guard let enumerator = enumerator(at: URL(fileURLWithPath: directory), includingPropertiesForKeys: nil, options: [], errorHandler: nil) else {
return []
}
var musicFiles = [URL]()
let enumeration: () -> Bool = {
guard let fileURL = enumerator.nextObject() as? URL else {
return false
}
if fileURL.isMusicFile {
musicFiles.append(fileURL)
}
return true
}
while enumeration() {}
return musicFiles
}
}
| 24.548387 | 146 | 0.647832 |
53d099e7c97e07131771d85d34b071ba1d91ab6c | 890 | java | Java | src/main/java/com/trsearch/trsearch/service/UserDetailsServiceImpl.java | Daniel-Fonseca-da-Silva/Tr-Search-Back | 6593529693da60666a33f94651a20ac490e941d5 | [
"MIT"
] | 1 | 2021-09-20T17:04:34.000Z | 2021-09-20T17:04:34.000Z | src/main/java/com/trsearch/trsearch/service/UserDetailsServiceImpl.java | Daniel-Fonseca-da-Silva/Tr-Search-Back | 6593529693da60666a33f94651a20ac490e941d5 | [
"MIT"
] | null | null | null | src/main/java/com/trsearch/trsearch/service/UserDetailsServiceImpl.java | Daniel-Fonseca-da-Silva/Tr-Search-Back | 6593529693da60666a33f94651a20ac490e941d5 | [
"MIT"
] | null | null | null | package com.trsearch.trsearch.service;
import com.trsearch.trsearch.model.UserCorp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service(value = "userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserCorpRepository userCorpRep;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserCorp userCorp = userCorpRep.findByLoginCorp(username);
if(userCorp != null)
return userCorp;
throw new UsernameNotFoundException("User not found");
}
}
| 32.962963 | 93 | 0.796629 |
de897c1092ff09aa7a5f0e5591308e89dc7d5d9c | 1,402 | rs | Rust | build.rs | bcully/wezterm | ea401e1f58ca5a088ac5d5e1d7963f36269afb76 | [
"MIT"
] | null | null | null | build.rs | bcully/wezterm | ea401e1f58ca5a088ac5d5e1d7963f36269afb76 | [
"MIT"
] | null | null | null | build.rs | bcully/wezterm | ea401e1f58ca5a088ac5d5e1d7963f36269afb76 | [
"MIT"
] | 1 | 2021-07-08T22:07:02.000Z | 2021-07-08T22:07:02.000Z | use vergen::{generate_cargo_keys, ConstantsFlags};
fn main() {
let mut flags = ConstantsFlags::all();
flags.remove(ConstantsFlags::SEMVER_FROM_CARGO_PKG);
// Generate the 'cargo:' key output
generate_cargo_keys(ConstantsFlags::all()).expect("Unable to generate the cargo keys!");
// If a file named `.tag` is present, we'll take its contents for the
// version number that we report in wezterm -h.
let mut ci_tag = String::new();
if let Ok(tag) = std::fs::read(".tag") {
if let Ok(s) = String::from_utf8(tag) {
ci_tag = s.trim().to_string();
println!("cargo:rerun-if-changed=.tag");
}
}
println!("cargo:rustc-env=WEZTERM_CI_TAG={}", ci_tag);
println!("cargo:rustc-env=MACOSX_DEPLOYMENT_TARGET=10.9");
#[cfg(windows)]
{
use std::path::Path;
let profile = std::env::var("PROFILE").unwrap();
let exe_output_dir = Path::new("target").join(profile);
let exe_src_dir = Path::new("assets/windows/conhost");
for name in &["conpty.dll", "OpenConsole.exe"] {
let dest_name = exe_output_dir.join(name);
let src_name = exe_src_dir.join(name);
if !dest_name.exists() {
std::fs::copy(src_name, dest_name).unwrap();
}
}
}
#[cfg(windows)]
embed_resource::compile("assets/windows/resource.rc");
}
| 34.195122 | 92 | 0.601284 |
9e3ef4e85b3a4f91b0a6e18916c28691493af965 | 457 | swift | Swift | Sources/sandbox/Sandbox/Models/Database/CompanyModelObject.swift | Incetro/service-autograph | 3a5fbc76e838743ee8184b1a20c12291cfa7f910 | [
"MIT"
] | null | null | null | Sources/sandbox/Sandbox/Models/Database/CompanyModelObject.swift | Incetro/service-autograph | 3a5fbc76e838743ee8184b1a20c12291cfa7f910 | [
"MIT"
] | null | null | null | Sources/sandbox/Sandbox/Models/Database/CompanyModelObject.swift | Incetro/service-autograph | 3a5fbc76e838743ee8184b1a20c12291cfa7f910 | [
"MIT"
] | null | null | null | //
// CompanyModelObject.swift
// Sandbox
//
// Generated automatically by dao-autograph
// https://github.com/Incetro/dao-autograph
//
// Copyright © 2020 Incetro Inc. All rights reserved.
//
import SDAO
import RealmSwift
// MARK: - CompanyModelObject
final class CompanyModelObject: RealmModel {
// MARK: - Properties
/// Company name
@objc dynamic var name = ""
/// Catch phrase string
@objc dynamic var catchPhrase = ""
}
| 17.576923 | 54 | 0.678337 |
1fcba09a49f28c15af86dba01622483b0e891ca8 | 168 | dart | Dart | lib/utils/variaveis.dart | wilkerdn/atividade-revisao | 34b6e925818d84a80ec5b0b79cf40df7cf87da63 | [
"MIT"
] | null | null | null | lib/utils/variaveis.dart | wilkerdn/atividade-revisao | 34b6e925818d84a80ec5b0b79cf40df7cf87da63 | [
"MIT"
] | null | null | null | lib/utils/variaveis.dart | wilkerdn/atividade-revisao | 34b6e925818d84a80ec5b0b79cf40df7cf87da63 | [
"MIT"
] | null | null | null | class Variaveis {
static const BACKURL = 'basemagic-d1744-default-rtdb.firebaseio.com';
static const KEYFIREBASE = 'AIzaSyAmBScDaOVjpC_KWf0jMphHn-EISMcxNGo';
}
| 33.6 | 72 | 0.77381 |
9f12153d910f6715be02d187d211cc7aa5d07aa7 | 3,092 | sql | SQL | metastore/scripts/upgrade/derby/046-HIVE-17566.derby.sql | zhihu/hive | 812d75718eacec4d086e987fcf1e575a8f5bbd9b | [
"Apache-2.0"
] | 2 | 2017-11-30T02:34:10.000Z | 2017-11-30T02:34:11.000Z | metastore/scripts/upgrade/derby/046-HIVE-17566.derby.sql | zhihu/hive | 812d75718eacec4d086e987fcf1e575a8f5bbd9b | [
"Apache-2.0"
] | null | null | null | metastore/scripts/upgrade/derby/046-HIVE-17566.derby.sql | zhihu/hive | 812d75718eacec4d086e987fcf1e575a8f5bbd9b | [
"Apache-2.0"
] | 1 | 2020-03-02T13:55:33.000Z | 2020-03-02T13:55:33.000Z | CREATE TABLE "APP"."WM_RESOURCEPLAN" (RP_ID BIGINT NOT NULL, NAME VARCHAR(128) NOT NULL, QUERY_PARALLELISM INTEGER, STATUS VARCHAR(20) NOT NULL, DEFAULT_POOL_ID BIGINT);
CREATE UNIQUE INDEX "APP"."UNIQUE_WM_RESOURCEPLAN" ON "APP"."WM_RESOURCEPLAN" ("NAME");
ALTER TABLE "APP"."WM_RESOURCEPLAN" ADD CONSTRAINT "WM_RESOURCEPLAN_PK" PRIMARY KEY ("RP_ID");
CREATE TABLE "APP"."WM_POOL" (POOL_ID BIGINT NOT NULL, RP_ID BIGINT NOT NULL, PATH VARCHAR(1024) NOT NULL, PARENT_POOL_ID BIGINT, ALLOC_FRACTION DOUBLE, QUERY_PARALLELISM INTEGER, SCHEDULING_POLICY VARCHAR(1024));
CREATE UNIQUE INDEX "APP"."UNIQUE_WM_POOL" ON "APP"."WM_POOL" ("RP_ID", "PATH");
ALTER TABLE "APP"."WM_POOL" ADD CONSTRAINT "WM_POOL_PK" PRIMARY KEY ("POOL_ID");
ALTER TABLE "APP"."WM_POOL" ADD CONSTRAINT "WM_POOL_FK1" FOREIGN KEY ("RP_ID") REFERENCES "APP"."WM_RESOURCEPLAN" ("RP_ID") ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE "APP"."WM_POOL" ADD CONSTRAINT "WM_POOL_FK2" FOREIGN KEY ("PARENT_POOL_ID") REFERENCES "APP"."WM_POOL" ("POOL_ID") ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE "APP"."WM_RESOURCEPLAN" ADD CONSTRAINT "WM_RESOURCEPLAN_FK1" FOREIGN KEY ("DEFAULT_POOL_ID") REFERENCES "APP"."WM_POOL" ("POOL_ID") ON DELETE NO ACTION ON UPDATE NO ACTION;
CREATE TABLE "APP"."WM_TRIGGER" (TRIGGER_ID BIGINT NOT NULL, RP_ID BIGINT NOT NULL, NAME VARCHAR(128) NOT NULL, TRIGGER_EXPRESSION VARCHAR(1024), ACTION_EXPRESSION VARCHAR(1024));
CREATE UNIQUE INDEX "APP"."UNIQUE_WM_TRIGGER" ON "APP"."WM_TRIGGER" ("RP_ID", "NAME");
ALTER TABLE "APP"."WM_TRIGGER" ADD CONSTRAINT "WM_TRIGGER_PK" PRIMARY KEY ("TRIGGER_ID");
ALTER TABLE "APP"."WM_TRIGGER" ADD CONSTRAINT "WM_TRIGGER_FK1" FOREIGN KEY ("RP_ID") REFERENCES "APP"."WM_RESOURCEPLAN" ("RP_ID") ON DELETE NO ACTION ON UPDATE NO ACTION;
CREATE TABLE "APP"."WM_POOL_TO_TRIGGER" (POOL_ID BIGINT NOT NULL, TRIGGER_ID BIGINT NOT NULL);
ALTER TABLE "APP"."WM_POOL_TO_TRIGGER" ADD CONSTRAINT "WM_POOL_TO_TRIGGER_PK" PRIMARY KEY ("POOL_ID", "TRIGGER_ID");
ALTER TABLE "APP"."WM_POOL_TO_TRIGGER" ADD CONSTRAINT "WM_POOL_TO_TRIGGER_FK1" FOREIGN KEY ("POOL_ID") REFERENCES "APP"."WM_POOL" ("POOL_ID") ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE "APP"."WM_POOL_TO_TRIGGER" ADD CONSTRAINT "WM_POOL_TO_TRIGGER_FK2" FOREIGN KEY ("TRIGGER_ID") REFERENCES "APP"."WM_TRIGGER" ("TRIGGER_ID") ON DELETE NO ACTION ON UPDATE NO ACTION;
CREATE TABLE "APP"."WM_MAPPING" (MAPPING_ID BIGINT NOT NULL, RP_ID BIGINT NOT NULL, ENTITY_TYPE VARCHAR(10) NOT NULL, ENTITY_NAME VARCHAR(128) NOT NULL, POOL_ID BIGINT, ORDERING INTEGER);
CREATE UNIQUE INDEX "APP"."UNIQUE_WM_MAPPING" ON "APP"."WM_MAPPING" ("RP_ID", "ENTITY_TYPE", "ENTITY_NAME");
ALTER TABLE "APP"."WM_MAPPING" ADD CONSTRAINT "WM_MAPPING_PK" PRIMARY KEY ("MAPPING_ID");
ALTER TABLE "APP"."WM_MAPPING" ADD CONSTRAINT "WM_MAPPING_FK1" FOREIGN KEY ("RP_ID") REFERENCES "APP"."WM_RESOURCEPLAN" ("RP_ID") ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE "APP"."WM_MAPPING" ADD CONSTRAINT "WM_MAPPING_FK2" FOREIGN KEY ("POOL_ID") REFERENCES "APP"."WM_POOL" ("POOL_ID") ON DELETE NO ACTION ON UPDATE NO ACTION;
| 114.518519 | 213 | 0.767464 |
0c9646550e91efca615eedc91a6895d4f88c0e06 | 276 | py | Python | fdk_client/common/date_helper.py | kavish-d/fdk-client-python | a1023eb530473322cb52e095fc4ceb226c1e6037 | [
"MIT"
] | null | null | null | fdk_client/common/date_helper.py | kavish-d/fdk-client-python | a1023eb530473322cb52e095fc4ceb226c1e6037 | [
"MIT"
] | null | null | null | fdk_client/common/date_helper.py | kavish-d/fdk-client-python | a1023eb530473322cb52e095fc4ceb226c1e6037 | [
"MIT"
] | null | null | null | from datetime import datetime
import pytz
from .constants import TIMEZONE
timezone = pytz.timezone(TIMEZONE)
def get_ist_now():
"""Returns Indian Standard Time datetime object.
Returns:
object -- Datetime object
"""
return datetime.now(timezone)
| 16.235294 | 52 | 0.710145 |
fa461c6aecd236b1093b9d05dd53074fd667bd27 | 2,001 | sql | SQL | sql/10073.sql | harsh481/stratascratch-daily | f4d5f190b5d89c4ed77d5243a727cdbc12894e1b | [
"MIT"
] | 3 | 2021-10-03T21:56:36.000Z | 2022-03-25T07:45:54.000Z | sql/10073.sql | harsh481/stratascratch-daily | f4d5f190b5d89c4ed77d5243a727cdbc12894e1b | [
"MIT"
] | null | null | null | sql/10073.sql | harsh481/stratascratch-daily | f4d5f190b5d89c4ed77d5243a727cdbc12894e1b | [
"MIT"
] | 9 | 2021-11-24T04:12:08.000Z | 2022-03-07T12:03:39.000Z | /*
Favorite Host Nationality
https://platform.stratascratch.com/coding/10073-favorite-host-nationality?python&utm_source=youtube&utm_medium=click&utm_campaign=YT+description+link
Difficulty: Medium
For each guest reviewer, find the nationality of the reviewer’s favorite host based on the guest’s highest review score given to a host. Output the user ID of the guest along with their favorite host’s nationality.
Tables:
<airbnb_reviews>
from_user int
to_user int
from_type varchar
to_type varchar
review_score int
<airbnb_hosts>
host_id int
nationality varchar
gender varchar
age int
*/
-- objective:
-- find the highest review score given by each guest user
-- find the host_id given the highest review
-- output the user id and the host nationality
-- assumption:
-- each user only has 1 highest review score
-- possibly more than 1 host has the same highest review score
-- if same country we can remove the duplicated host nationality
-- logic:
-- max(review_score) per user
-- filter host_id that received that the highest id
-- output the user id and their host nationality
-- retrieve the host nationality
-- remove duplicates as well
SELECT DISTINCT u.from_user,
h.nationality
FROM (
-- select the particular reviews that were given the highest score for each user
SELECT r.*
FROM airbnb_reviews r
JOIN (
-- select the highest review given by each guest user
SELECT from_user,
MAX(review_score) AS highest_score
FROM airbnb_reviews
WHERE from_type = 'guest'
GROUP BY 1
) highest_review_score
ON r.from_user = highest_review_score.from_user
AND r.review_score = highest_review_score.highest_score
-- ensure that score remains from a guest perspective
WHERE from_type = 'guest'
) u
JOIN airbnb_hosts h
ON u.to_user = h.host_id
ORDER BY 1
| 30.784615 | 214 | 0.697151 |
19cc666861c4d30a622deb74356faa8ffedf5dde | 1,490 | swift | Swift | Example/LvJing/AffineTransformFilter/AffineTransformFilter.swift | keyOfVv/LvJing | 19f38142de70a6c2a69d54289c54948f244cf3f3 | [
"MIT"
] | null | null | null | Example/LvJing/AffineTransformFilter/AffineTransformFilter.swift | keyOfVv/LvJing | 19f38142de70a6c2a69d54289c54948f244cf3f3 | [
"MIT"
] | null | null | null | Example/LvJing/AffineTransformFilter/AffineTransformFilter.swift | keyOfVv/LvJing | 19f38142de70a6c2a69d54289c54948f244cf3f3 | [
"MIT"
] | null | null | null | //
// AffineTransformFilter.swift
// LvJing_Example
//
// Created by Ke Yang on 2020/7/25.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import MetalKit
import LvJing
public final class AffineTransformFilter: LvJing {
public var transform: CGAffineTransform = .identity
public init(resolution: CGSize) {
super.init(
resolution: resolution,
libraryURL: nil,
vertexFunctionName: "vertex_main",
fragmentFunctionName: "fragment_affine")
}
public override func setFragmentBytesFor(encoder: MTLRenderCommandEncoder) {
var floatResolution = [Float(resolution.width), Float(resolution.height)]
encoder.setFragmentBytes(
&floatResolution,
length: MemoryLayout<SIMD2<Float>>.stride,
index: Int(AffineTransformFilterResolutionBufferIndex.rawValue))
let t3d = CATransform3DMakeAffineTransform(self.transform.inverted())
var transform4x4 = float4x4(
[Float(t3d.m11), Float(t3d.m12), Float(t3d.m13), Float(t3d.m14)], // col 1
[Float(t3d.m21), Float(t3d.m22), Float(t3d.m23), Float(t3d.m24)], // col 2
[Float(t3d.m31), Float(t3d.m32), Float(t3d.m33), Float(t3d.m34)], // col 3
[Float(t3d.m41), Float(t3d.m42), Float(t3d.m43), Float(t3d.m44)]) // col 4
encoder.setFragmentBytes(
&transform4x4,
length: MemoryLayout<float4x4>.stride,
index: Int(AffineTransformFilterTransformBufferIndex.rawValue))
}
}
| 34.651163 | 83 | 0.671812 |
53541d0919368fb2f1598ab113d67e954afcc62f | 4,074 | dart | Dart | lib/features/home/ui/widgets/file_explorer_table_row_tile.dart | ganeshrvel/squash_archiver | f5a457e2d321dbdfb10daef61a9a2caf73613b41 | [
"MIT"
] | null | null | null | lib/features/home/ui/widgets/file_explorer_table_row_tile.dart | ganeshrvel/squash_archiver | f5a457e2d321dbdfb10daef61a9a2caf73613b41 | [
"MIT"
] | null | null | null | lib/features/home/ui/widgets/file_explorer_table_row_tile.dart | ganeshrvel/squash_archiver | f5a457e2d321dbdfb10daef61a9a2caf73613b41 | [
"MIT"
] | null | null | null | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:squash_archiver/common/helpers/provider_helpers.dart';
import 'package:squash_archiver/features/home/data/enums/file_explorer_source.dart';
import 'package:squash_archiver/features/home/data/models/file_listing_response.dart';
import 'package:squash_archiver/features/home/ui/pages/file_explorer_keyboard_modifiers_store.dart';
import 'package:squash_archiver/features/home/ui/pages/file_explorer_screen_store.dart';
import 'package:squash_archiver/features/home/ui/widgets/file_explorer_table_row.dart';
import 'package:squash_archiver/utils/utils/functs.dart';
import 'package:squash_archiver/widgets/inkwell_extended/inkwell_extended.dart';
import 'package:squash_archiver/widgets/text/textography.dart';
class FileExplorerTableRow extends StatefulWidget {
final int rowIndex;
final FileListingResponse fileContainer;
const FileExplorerTableRow({
Key key,
@required this.fileContainer,
@required this.rowIndex,
}) : assert(fileContainer != null),
assert(rowIndex != null),
super(key: key);
@override
_FileExplorerTableRowState createState() => _FileExplorerTableRowState();
}
class _FileExplorerTableRowState extends State<FileExplorerTableRow> {
FileExplorerScreenStore get _fileExplorerScreenStore =>
readProvider<FileExplorerScreenStore>(context);
FileExplorerKeyboardModifiersStore get _fileExplorerKeyboardModifiersStore =>
readProvider<FileExplorerKeyboardModifiersStore>(context);
int get _rowIndex => widget.rowIndex;
FileListingResponse get _fileContainer => widget.fileContainer;
Future<void> _navigateToNextPath(FileListingResponse fileContainer) async {
if (fileContainer.file.isDir) {
return _fileExplorerScreenStore
.setCurrentPath(fileContainer.file.fullPath);
}
/// if the file extension is supported by the archiver then open the archive
if (fileContainer.isSupported) {
return _fileExplorerScreenStore.navigateToSource(
fullPath: '',
currentArchiveFilepath: fileContainer.file.fullPath,
source: FileExplorerSource.ARCHIVE,
clearStack: false,
);
}
}
@override
Widget build(BuildContext context) {
return Listener(
onPointerDown: (PointerDownEvent event) {
/// mouse right click
if (event.buttons == 2) {
showMenu(
elevation: 2,
context: context,
position: RelativeRect.fromLTRB(
event.position.dx,
event.position.dy,
event.position.dx,
event.position.dy,
),
items: const <PopupMenuItem<String>>[
PopupMenuItem(value: 'test1', child: Textography('test1')),
PopupMenuItem(value: 'test2', child: Textography('test2')),
],
);
}
},
child: InkWellExtended(
mouseCursor: SystemMouseCursors.basic,
onDoubleTap: () {
_navigateToNextPath(_fileContainer);
},
onTap: () {
final _activeKeyboardModifierIntent =
_fileExplorerKeyboardModifiersStore.activeKeyboardModifierIntent;
/// if meta key is pressed (in macos) then allow multiple selection
_fileExplorerScreenStore.setSelectedFile(
_fileContainer,
appendToList: _activeKeyboardModifierIntent?.isMetaPressed == true,
);
},
child: Observer(builder: (_) {
/// list of selected files
final _selectedFiles = _fileExplorerScreenStore.selectedFiles;
/// is file selected
final _isSelected = isNotNull(
_selectedFiles[_fileContainer.uniqueId],
);
return FileExplorerTableRowTile(
isSelected: _isSelected,
rowIndex: _rowIndex,
fileContainer: _fileContainer,
);
}),
),
);
}
}
| 35.12069 | 100 | 0.686794 |
21d4e7822b029725fa74b181074382404cb9840e | 4,987 | kt | Kotlin | app/src/main/java/com/divij/credittracker/view/HomeFragment.kt | divijgupta970/CreditTracker | 40f47c3cd97e8810c3614d9c36077eb09d779f9e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/divij/credittracker/view/HomeFragment.kt | divijgupta970/CreditTracker | 40f47c3cd97e8810c3614d9c36077eb09d779f9e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/divij/credittracker/view/HomeFragment.kt | divijgupta970/CreditTracker | 40f47c3cd97e8810c3614d9c36077eb09d779f9e | [
"Apache-2.0"
] | null | null | null | package com.divij.credittracker.view
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.divij.credittracker.R
import com.divij.credittracker.adapter.TransactionsAdapter
import com.divij.credittracker.databinding.FragmentHomeBinding
import com.divij.credittracker.model.Session
import com.divij.credittracker.model.Transaction
import com.divij.credittracker.util.Utils
import com.divij.credittracker.viewmodel.MainViewModel
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import java.util.*
import kotlin.collections.ArrayList
class HomeFragment : Fragment() {
private lateinit var binding: FragmentHomeBinding
private lateinit var adapter: TransactionsAdapter
private val viewModel: MainViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home, container, false)
binding.fabAdd.setOnClickListener {
addTransaction()
}
binding.btnDone.setOnClickListener{
endSession()
}
initRecyclerView()
getRecentSession()
return binding.root
}
private fun endSession() {
MaterialAlertDialogBuilder(requireContext()).setTitle("End Session")
.setMessage("Are you sure?")
.setPositiveButton("Yes") { dialog, _ ->
val currSession: Session? = viewModel.recentSession.value
if (currSession != null) {
currSession.endSession()
viewModel.saveSessions(currSession)
viewModel.saveSessions(Session(Date()))
}
dialog.dismiss()
}.setNegativeButton("No") {dialog, _ ->
dialog.dismiss()
}.show()
}
private fun initRecyclerView() {
binding.rvTransactions.layoutManager = LinearLayoutManager(context)
adapter = TransactionsAdapter()
binding.rvTransactions.adapter = adapter
binding.rvTransactions.itemAnimator = DefaultItemAnimator()
}
private fun getRecentSession() {
viewModel.getRecentSession().observe(viewLifecycleOwner, {
if (it != null) {
getTransactionsForSession(it)
}
})
}
private fun addTransaction() {
val customView: View =
LayoutInflater.from(context).inflate(R.layout.dialog_add_transaction, null, false)
val etName = customView.findViewById<TextInputEditText>(R.id.etName)
val etAmount = customView.findViewById<TextInputEditText>(R.id.etAmount)
val materialAlertDialogBuilder = MaterialAlertDialogBuilder(requireContext())
materialAlertDialogBuilder.setView(customView)
.setTitle("Add new item")
.setNegativeButton("Cancel"
) { dialog, which -> dialog.dismiss() }
.setPositiveButton("Add"
) { dialog, which ->
if (etAmount.text.isNullOrBlank()) {
etAmount.error = "Enter Amount!"
return@setPositiveButton
}
if (etName.text.isNullOrBlank()) {
etName.error = "Enter Name!"
return@setPositiveButton
}
val transaction = Transaction(etName.text.toString(), etAmount.text.toString().toInt())
var session : Session? = null
if (viewModel.recentSession.value == null) {
session = Session(Date())
viewModel.saveSessions(session)
viewModel.saveTransaction(transaction, session.id)
} else {
session = viewModel.recentSession.value
viewModel.saveTransaction(
transaction,
session!!.id
)
}
session.total += etAmount.text.toString().toInt()
viewModel.saveSessions(session)
dialog.dismiss()
}.show()
}
private fun getTransactionsForSession(session: Session) {
viewModel.getTransactions(session.id).observe(viewLifecycleOwner, {
if (it != null) {
adapter.setList(ArrayList(it))
binding.tvAmount.text = Utils.getTotalForTransactions(it)
adapter.notifyDataSetChanged()
}
})
}
} | 38.960938 | 103 | 0.632645 |
263c6440af2022ddcfaa154fa7160046219b27b7 | 902 | swift | Swift | Targets/TMBuddy/Sources/Checkpoints/Analytics/Standalone/AnalyticsCheckpoint+View.swift | grigorye/TMBuddy | b1358c5c7b0369e4f4bbe75b591ade7d55eef603 | [
"MIT"
] | 6 | 2022-01-17T04:52:42.000Z | 2022-03-28T20:29:12.000Z | Targets/TMBuddy/Sources/Checkpoints/Analytics/Standalone/AnalyticsCheckpoint+View.swift | grigorye/TMBuddy | b1358c5c7b0369e4f4bbe75b591ade7d55eef603 | [
"MIT"
] | null | null | null | Targets/TMBuddy/Sources/Checkpoints/Analytics/Standalone/AnalyticsCheckpoint+View.swift | grigorye/TMBuddy | b1358c5c7b0369e4f4bbe75b591ade7d55eef603 | [
"MIT"
] | 1 | 2022-02-17T03:21:28.000Z | 2022-02-17T03:21:28.000Z | import SwiftUI
struct AnalyticsCheckpointView: View {
struct State {
let analyticsEnabled: Bool
}
let state: State
let actions: AnalyticsCheckpointActions?
var body: some View {
CheckpointView(
title: "Analytics",
subtitle: "Let \(appName) gather information about its usage, for further improvements.",
value: state.analyticsEnabled ? "enabled" : "disabled",
readiness: .ready
) {
switch state.analyticsEnabled {
case false:
Button("Enable Analytics") {
actions?.setAnalyticsEnabled()
}
case true:
Button("Disable Analytics") {
actions?.setAnalyticsDisabled()
}
}
}
.onVisibilityChange(perform: actions?.track(visible:))
}
}
| 27.333333 | 101 | 0.533259 |
56dc9c7481bdcb5b4c0c0e38f89b791b453c8df8 | 2,329 | lua | Lua | build/premake4.lua | erwincoumans/enet | eea4dced9ae2c617857d7c221551f36a475582ac | [
"MIT"
] | 22 | 2015-02-01T15:31:09.000Z | 2021-03-17T16:19:07.000Z | build/premake4.lua | erwincoumans/enet | eea4dced9ae2c617857d7c221551f36a475582ac | [
"MIT"
] | 2 | 2017-04-23T11:48:33.000Z | 2017-04-23T15:17:20.000Z | build/premake4.lua | erwincoumans/enet | eea4dced9ae2c617857d7c221551f36a475582ac | [
"MIT"
] | 7 | 2016-02-26T00:53:37.000Z | 2021-03-17T16:19:10.000Z |
solution "0MySolution"
-- Multithreaded compiling
if _ACTION == "vs2010" or _ACTION=="vs2008" then
buildoptions { "/MP" }
end
act = ""
if _ACTION then
act = _ACTION
end
newoption
{
trigger = "ios",
description = "Enable iOS target (requires xcode4)"
}
newoption
{
trigger = "bullet2gpu",
description = "Enable Bullet 2.x GPU using b3GpuDynamicsWorld bridge to Bullet 3.x"
}
newoption
{
trigger = "enet",
description = "Enable enet NAT punchthrough test"
}
configurations {"Release", "Debug"}
configuration "Release"
flags { "Optimize", "EnableSSE","StaticRuntime", "NoMinimalRebuild", "FloatFast"}
configuration "Debug"
defines {"_DEBUG=1"}
flags { "Symbols", "StaticRuntime" , "NoMinimalRebuild", "NoEditAndContinue" ,"FloatFast"}
if os.is("Linux") then
if os.is64bit() then
platforms {"x64"}
else
platforms {"x32"}
end
else
platforms {"x32", "x64"}
end
configuration {"x32"}
targetsuffix ("_" .. act)
configuration "x64"
targetsuffix ("_" .. act .. "_64" )
configuration {"x64", "debug"}
targetsuffix ("_" .. act .. "_x64_debug")
configuration {"x64", "release"}
targetsuffix ("_" .. act .. "_x64_release" )
configuration {"x32", "debug"}
targetsuffix ("_" .. act .. "_debug" )
configuration{}
postfix=""
if _ACTION == "xcode4" then
if _OPTIONS["ios"] then
postfix = "ios";
xcodebuildsettings
{
'CODE_SIGN_IDENTITY = "iPhone Developer"',
"SDKROOT = iphoneos",
'ARCHS = "armv7"',
'TARGETED_DEVICE_FAMILY = "1,2"',
'VALID_ARCHS = "armv7"',
}
else
xcodebuildsettings
{
'ARCHS = "$(ARCHS_STANDARD_32_BIT) $(ARCHS_STANDARD_64_BIT)"',
'VALID_ARCHS = "x86_64 i386"',
}
end
end
flags { "NoRTTI", "NoExceptions"}
defines { "_HAS_EXCEPTIONS=0" }
targetdir "../bin"
location("./" .. act .. postfix)
projectRootDir = os.getcwd() .. "/../"
print("Project root directroy: " .. projectRootDir);
dofile ("findOpenCL.lua")
dofile ("findDirectX11.lua")
dofile ("findOpenGLGlewGlut.lua")
language "C++"
include "../btgui/enet"
include "../test/enet/server"
include "../test/enet/client"
| 22.180952 | 92 | 0.5921 |
6785249f8fbe96100a3bfbded141e1fa459f94dd | 773 | lua | Lua | stubs/wifi.lua | amolenaar/wort-warden | 91bffbb4f2f797a6af4ce89870c3acf259227379 | [
"MIT"
] | 2 | 2018-02-20T23:26:02.000Z | 2018-11-28T22:01:43.000Z | stubs/wifi.lua | amolenaar/wort-warden | 91bffbb4f2f797a6af4ce89870c3acf259227379 | [
"MIT"
] | null | null | null | stubs/wifi.lua | amolenaar/wort-warden | 91bffbb4f2f797a6af4ce89870c3acf259227379 | [
"MIT"
] | null | null | null | -- # Stub implementation for NodeMCU wifi module
--
-- https://nodemcu.readthedocs.io/en/master/en/modules/wifi/
--
-- Only part of the module has been implemented.
local wifi = {
STATION="STATION",
SOFTAP="SOFTAP",
STATIONAP="STATIONAP",
sta={},
ap={},
eventmon={
STA_CONNECTED="STA_CONNECTED"
}
}
local state = {}
wifi.stub_state = state
function wifi.setmode(mode, save)
state.mode = mode
end
function wifi.sta.autoconnect(auto)
state.sta_autoconnect = auto
end
function wifi.sta.config(station_config)
state.sta_station_config = station_config
end
function wifi.sta.connect()
end
function wifi.sta.getip()
return {"192.168.0.12"}
end
function wifi.eventmon.register(event, func)
state.eventmon_sta_connected = func
end
return wifi
| 16.804348 | 60 | 0.725744 |
ee7ddf02ab6d1e0cd5511886acdcca6540cf228a | 1,485 | asm | Assembly | src/draw/draw_board.asm | daullmer/tic-tac-toe | 2d84db8ca338a81eda7ab600dd1a9fff8df977a8 | [
"MIT"
] | 1 | 2021-11-09T21:34:20.000Z | 2021-11-09T21:34:20.000Z | src/draw/draw_board.asm | daullmer/tic-tac-toe | 2d84db8ca338a81eda7ab600dd1a9fff8df977a8 | [
"MIT"
] | null | null | null | src/draw/draw_board.asm | daullmer/tic-tac-toe | 2d84db8ca338a81eda7ab600dd1a9fff8df977a8 | [
"MIT"
] | 1 | 2021-11-08T12:55:44.000Z | 2021-11-08T12:55:44.000Z | #######
# DRAW GAME BOARD INCLUDING NUMBERS
# ------------
# inputs: none
#######
draw_board:
# save variables
addi sp, sp, -36
sw ra 32(sp)
sw a1 28(sp)
sw a2 24(sp)
sw a3 20(sp)
sw a4 16(sp)
sw a5 12(sp)
sw t1 8(sp)
sw t2 4(sp)
sw t3 0(sp)
li a3 0xffffff # store color white in a3
addi t1, zero, DISPLAY_WIDTH # t1=loop end größe
addi t2, zero, BORDER_SIZE # t2=loop für dicke end größe
addi t3, zero, 2 # 2 linien horizontal
# horizontale linien
li a2, CELL_SIZE
li a5, 0 # number of current line
hori_line_loop:
li a4, 0 # a4 current line width
line_height_loop:
li a1, 0
hori_hori_loop:
jal draw_pixel
addi a1, a1, 1
blt a1, t1, hori_hori_loop
addi a4, a4, 1
addi a2, a2, 1
blt a4, t2, line_height_loop
addi a5, a5, 1
addi a2, a2, CELL_SIZE # nächste linie CELL_SIZE pixel weiter zeichnen
blt a5, t3, hori_line_loop
# vertikale linien
li a1, CELL_SIZE
li a5, 0 # number of current line
verti_line_loop:
li a4, 0 # a4 current line width
line_width_loop:
li a2, 0
verti_verti_loop:
jal draw_pixel
addi a2, a2, 1
blt a2, t1, verti_verti_loop
addi a4, a4, 1
addi a1, a1, 1
blt a4, t2, line_width_loop
addi a5, a5, 1
addi a1, a1, CELL_SIZE # nächste linie CELL_SIZE pixel weiter zeichnen
blt a5, t3, verti_line_loop
jal draw_board_numbers
# restore variables
lw ra 32(sp)
lw a1 28(sp)
lw a2 24(sp)
lw a3 20(sp)
lw a4 16(sp)
lw a5 12(sp)
lw t1 8(sp)
lw t2 4(sp)
lw t3 0(sp)
addi sp, sp, 36
ret
.include "draw_board_numbers.asm"
| 19.038462 | 72 | 0.688889 |
fb8c8fa0dff4950678c9265b9d671490a9c9a8ba | 2,825 | java | Java | src/test/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloudTest.java | sixtyeight/kubernetes-plugin | 2bc877913ec79ee72ff7c5bdc42b03ee04893d2f | [
"Apache-2.0"
] | 2 | 2016-11-28T15:32:10.000Z | 2017-10-20T11:56:29.000Z | src/test/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloudTest.java | sixtyeight/kubernetes-plugin | 2bc877913ec79ee72ff7c5bdc42b03ee04893d2f | [
"Apache-2.0"
] | null | null | null | src/test/java/org/csanchez/jenkins/plugins/kubernetes/KubernetesCloudTest.java | sixtyeight/kubernetes-plugin | 2bc877913ec79ee72ff7c5bdc42b03ee04893d2f | [
"Apache-2.0"
] | 8 | 2016-12-06T11:49:22.000Z | 2020-12-02T09:32:29.000Z | package org.csanchez.jenkins.plugins.kubernetes;
import java.util.Arrays;
import java.util.Collections;
import jenkins.model.JenkinsLocationConfiguration;
import org.csanchez.jenkins.plugins.kubernetes.volumes.EmptyDirVolume;
import org.csanchez.jenkins.plugins.kubernetes.volumes.PodVolume;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.fail;
public class KubernetesCloudTest {
@Rule
public JenkinsRule j = new JenkinsRule();
@After
public void tearDown() {
System.getProperties().remove("KUBERNETES_JENKINS_URL");
}
@Test
public void testInheritance() {
ContainerTemplate jnlp = new ContainerTemplate("jnlp", "jnlp:1");
ContainerTemplate maven = new ContainerTemplate("maven", "maven:1");
maven.setTtyEnabled(true);
maven.setCommand("cat");
PodVolume podVolume = new EmptyDirVolume("/some/path", true);
PodTemplate parent = new PodTemplate();
parent.setName("parent");
parent.setLabel("parent");
parent.setContainers(Arrays.asList(jnlp));
parent.setVolumes(Arrays.asList(podVolume));
ContainerTemplate maven2 = new ContainerTemplate("maven", "maven:2");
PodTemplate withNewMavenVersion = new PodTemplate();
withNewMavenVersion.setContainers(Arrays.asList(maven2));
PodTemplate result = PodTemplateUtils.combine(parent, withNewMavenVersion);
}
@Test(expected = IllegalStateException.class)
public void getJenkinsUrlOrDie_NoJenkinsUrl() {
JenkinsLocationConfiguration.get().setUrl(null);
KubernetesCloud cloud = new KubernetesCloud("name");
String url = cloud.getJenkinsUrlOrDie();
fail("Should have thrown IllegalStateException at this point but got " + url + " instead.");
}
@Test
public void getJenkinsUrlOrDie_UrlInCloud() {
System.setProperty("KUBERNETES_JENKINS_URL", "http://mylocationinsysprop");
KubernetesCloud cloud = new KubernetesCloud("name");
cloud.setJenkinsUrl("http://mylocation");
assertEquals("http://mylocation/", cloud.getJenkinsUrlOrDie());
}
@Test
public void getJenkinsUrlOrDie_UrlInSysprop() {
System.setProperty("KUBERNETES_JENKINS_URL", "http://mylocation");
KubernetesCloud cloud = new KubernetesCloud("name");
assertEquals("http://mylocation/", cloud.getJenkinsUrlOrDie());
}
@Test
public void getJenkinsUrlOrDie_UrlInLocation() {
JenkinsLocationConfiguration.get().setUrl("http://mylocation");
KubernetesCloud cloud = new KubernetesCloud("name");
assertEquals("http://mylocation/", cloud.getJenkinsUrlOrDie());
}
}
| 34.876543 | 100 | 0.706195 |
968fb7905d0f916c41206880fde9fee596e369a9 | 1,047 | html | HTML | manuscript/page-715/body.html | marvindanig/Sense-and-Sensibility | 9ca3dbab123fde9ec42221daf9fc53446efac69f | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | manuscript/page-715/body.html | marvindanig/Sense-and-Sensibility | 9ca3dbab123fde9ec42221daf9fc53446efac69f | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | manuscript/page-715/body.html | marvindanig/Sense-and-Sensibility | 9ca3dbab123fde9ec42221daf9fc53446efac69f | [
"BlueOak-1.0.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | <div class="leaf "><div class="inner justify"><p class="no-indent ">proportion, as she soon acknowledged within herself—to his wishes than to his merits. She felt that his influence over her mind was heightened by circumstances which ought not in reason to have weight; by that person of uncommon attraction, that open, affectionate, and lively manner which it was no merit to possess; and by that still ardent love for Marianne, which it was not even innocent to indulge. But she felt that it was so, long, long before she could feel his influence less.</p><p class=" stretch-last-line ">When at last she returned to the unconscious Marianne, she found her just awaking, refreshed by so long and sweet a sleep to the extent of her hopes. Elinor's heart was full. The past, the present, the future, Willoughby's visit, Marianne's safety, and her mother's expected arrival, threw her altogether into an agitation of spirits which kept off every indication of fatigue, and made her only fearful of betraying herself to her sister.</p></div> </div> | 1,047 | 1,047 | 0.77937 |
ffe0a560908adfede56a8d6b771335669a4e6628 | 86 | html | HTML | assets/date.html | JuliaPackageMirrors/Escher.jl | 72c0f85c0908b1d08c47ebe75ef045462220a197 | [
"MIT"
] | null | null | null | assets/date.html | JuliaPackageMirrors/Escher.jl | 72c0f85c0908b1d08c47ebe75ef045462220a197 | [
"MIT"
] | null | null | null | assets/date.html | JuliaPackageMirrors/Escher.jl | 72c0f85c0908b1d08c47ebe75ef045462220a197 | [
"MIT"
] | null | null | null | <link rel="import" href="bower_components/paper-date-picker/paper-date-picker2.html">
| 43 | 85 | 0.790698 |
04a5091cc03c51403e7defdfdad6f680cede2592 | 2,001 | java | Java | OpenRobertaRobot/src/main/java/de/fhg/iais/roberta/syntax/lang/expr/FunctionExpr.java | Klkoenig217/openroberta-lab | eb2cab36809fe0d97f717c08588e4089bf8f2028 | [
"Apache-2.0"
] | 3 | 2020-01-24T18:29:16.000Z | 2020-09-30T10:54:09.000Z | OpenRobertaRobot/src/main/java/de/fhg/iais/roberta/syntax/lang/expr/FunctionExpr.java | rohit-bindal/openroberta-lab | 7ed823538e34b3dbee93a902b61630c39f8909a3 | [
"Apache-2.0"
] | 24 | 2020-04-19T20:12:22.000Z | 2020-08-02T09:13:04.000Z | OpenRobertaRobot/src/main/java/de/fhg/iais/roberta/syntax/lang/expr/FunctionExpr.java | rohit-bindal/openroberta-lab | 7ed823538e34b3dbee93a902b61630c39f8909a3 | [
"Apache-2.0"
] | 1 | 2020-05-08T20:06:23.000Z | 2020-05-08T20:06:23.000Z | package de.fhg.iais.roberta.syntax.lang.expr;
import de.fhg.iais.roberta.blockly.generated.Block;
import de.fhg.iais.roberta.syntax.BlockTypeContainer;
import de.fhg.iais.roberta.syntax.Phrase;
import de.fhg.iais.roberta.syntax.lang.functions.Function;
import de.fhg.iais.roberta.typecheck.BlocklyType;
import de.fhg.iais.roberta.util.dbc.Assert;
import de.fhg.iais.roberta.visitor.IVisitor;
import de.fhg.iais.roberta.visitor.lang.ILanguageVisitor;
/**
* Wraps subclasses of the class {@link Function} so they can be used as {@link Expr} in expressions.
*/
public class FunctionExpr<V> extends Expr<V> {
private final Function<V> function;
private FunctionExpr(Function<V> function) {
super(BlockTypeContainer.getByName("FUNCTION_EXPR"), function.getProperty(), function.getComment());
Assert.isTrue(function.isReadOnly());
this.function = function;
setReadOnly();
}
/**
* Create object of the class {@link FunctionExpr}.
*
* @param function that we want to wrap,
* @return expression with wrapped function inside
*/
public static <V> FunctionExpr<V> make(Function<V> function) {
return new FunctionExpr<V>(function);
}
/**
* @return function that is wrapped in the expression
*/
public Function<V> getFunction() {
return this.function;
}
@Override
public int getPrecedence() {
return 999;
}
@Override
public Assoc getAssoc() {
return Assoc.NONE;
}
@Override
public BlocklyType getVarType() {
return this.function.getReturnType();
}
@Override
protected V acceptImpl(IVisitor<V> visitor) {
return ((ILanguageVisitor<V>) visitor).visitFunctionExpr(this);
}
@Override
public String toString() {
return "FunctionExpr [" + this.function + "]";
}
@Override
public Block astToBlock() {
Phrase<V> p = this.getFunction();
return p.astToBlock();
}
}
| 27.410959 | 108 | 0.665167 |
047f21d496e9b8595428f122f3d65db0832eca39 | 778 | java | Java | net.lecousin.core/src/main/java/net/lecousin/framework/io/AbstractIO.java | lecousin/java-framework-core | 6f177baf44e1275f77caf770c6c278f32739d771 | [
"Apache-2.0"
] | 3 | 2018-01-02T01:17:47.000Z | 2020-03-08T11:41:02.000Z | net.lecousin.core/src/main/java/net/lecousin/framework/io/AbstractIO.java | lecousin/java-framework-core | 6f177baf44e1275f77caf770c6c278f32739d771 | [
"Apache-2.0"
] | 1 | 2020-10-12T17:54:30.000Z | 2020-10-12T18:14:36.000Z | net.lecousin.core/src/main/java/net/lecousin/framework/io/AbstractIO.java | lecousin/java-framework-core | 6f177baf44e1275f77caf770c6c278f32739d771 | [
"Apache-2.0"
] | 1 | 2022-02-24T14:36:35.000Z | 2022-02-24T14:36:35.000Z | package net.lecousin.framework.io;
import java.io.IOException;
import net.lecousin.framework.concurrent.threads.Task.Priority;
import net.lecousin.framework.util.ConcurrentCloseable;
/** Utility class as a base for IO implementations. */
public abstract class AbstractIO extends ConcurrentCloseable<IOException> implements IO {
/** Constructor. */
public AbstractIO(String description, Priority priority) {
this.description = description;
this.priority = priority;
}
protected String description;
protected Priority priority;
@Override
public String getSourceDescription() {
return description;
}
@Override
public Priority getPriority() {
return priority;
}
@Override
public void setPriority(Priority priority) {
this.priority = priority;
}
}
| 21.611111 | 89 | 0.769923 |
2f27ce045fa457c04dd1daab6b92b6928b8882ce | 15,124 | php | PHP | app/Http/Controllers/TrialBalanceController.php | fmunashe/Insta | 56394be613717275e73782149e88cc48c30eb901 | [
"MIT"
] | null | null | null | app/Http/Controllers/TrialBalanceController.php | fmunashe/Insta | 56394be613717275e73782149e88cc48c30eb901 | [
"MIT"
] | null | null | null | app/Http/Controllers/TrialBalanceController.php | fmunashe/Insta | 56394be613717275e73782149e88cc48c30eb901 | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers;
use App\Product;
use App\PurchaseOrder;
use App\Requisition;
use App\Revenue;
use App\Sale;
use Carbon\Carbon;
use Illuminate\Http\Request;
class TrialBalanceController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$this->authorize('viewAny', Product::class);
$date = Carbon::now();
$sales = Sale::query()->sum('amount');
$rent = Requisition::query()->where('description', "Rent")->where('processed', true)->sum('total_amount');
$stationery = Requisition::query()->where('description', "Stationery")->where('processed', true)->sum('total_amount');
$telephone = Requisition::query()->where('description', "Telephone")->where('processed', true)->sum('total_amount');
$consultation = Requisition::query()->where('description', "Consultation")->where('processed', true)->sum('total_amount');
$salaries = Requisition::query()->where('description', "Salaries and Wages")->where('processed', true)->sum('total_amount');
$water = Requisition::query()->where('description', "Water Bills")->where('processed', true)->sum('total_amount');
$zesa = Requisition::query()->where('description', "Heating and Lighting")->where('processed', true)->sum('total_amount');
$internet = Requisition::query()->where('description', "Internet")->where('processed', true)->sum('total_amount');
$fuel = Requisition::query()->where('description', "Fuels and Oils")->where('processed', true)->sum('total_amount');
$welfare = Requisition::query()->where('description', "Staff Welfare")->where('processed', true)->sum('total_amount');
$transport = Requisition::query()->where('description', "Transport")->where('processed', true)->sum('total_amount');
$license = Requisition::query()->where('description', "Licenses")->where('processed', true)->sum('total_amount');
$repairs = Requisition::query()->where('description', "Repairs and Maintenance")->where('processed', true)->sum('total_amount');
$research = Requisition::query()->where('description', "Research and Development")->where('processed', true)->sum('total_amount');
$foreign = Requisition::query()->where('description', "Foreign Exchange Differences")->where('processed', true)->sum('total_amount');
$bankCharges = Requisition::query()->where('description', "Bank Charges")->where('processed', true)->sum('total_amount');
$bankInterest = Requisition::query()->where('description', "Bank Interest")->where('processed', true)->sum('total_amount');
$loanInterest = Requisition::query()->where('description', "Loan Interest")->where('processed', true)->sum('total_amount');
$fines = Requisition::query()->where('description', "Fines")->where('processed', true)->sum('total_amount');
$travel = Requisition::query()->where('description', "Travel and Subsistence")->where('processed', true)->sum('total_amount');
$export = Requisition::query()->where('description', "Export Marketing Expenses")->where('processed', true)->sum('total_amount');
$local = Requisition::query()->where('description', "Local Marketing Expenses")->where('processed', true)->sum('total_amount');
$other = Requisition::query()->where('description', "Other")->where('processed', true)->sum('total_amount');
$debtors = Requisition::query()->where('description', "Debtors")->where('processed', true)->sum('total_amount');
$purchases = Requisition::query()->where('description', "Purchases")->where('processed', true)->sum('total_amount');
$inventory=PurchaseOrder::query()->sum('cost_price');
$totalExpenses=Requisition::query()->where('processed',true)->sum('total_amount')+$inventory;
$capital=Revenue::query()->where('name',"Capital")->sum('amount');
$bankLoan=Revenue::query()->where('name',"Bank Loan")->sum('amount');
$creditors=Revenue::query()->where('name',"Creditors")->sum('amount');
$otherRevenue=Revenue::query()->where('name',"Other")->sum('amount');
$totalRevenue=$sales+$creditors+$capital+$bankLoan+$otherRevenue;
//$rent+$stationery+$telephone+$consultation+$salaries+$water+$zesa+$internet+$fuel+$welfare+$travel+$transport+$license+$repairs+$research+$foreign+$bankCharges+$bankInterest+$loanInterest+$fines+$export+$local+$other;
return view('trial_balance.index', compact(
'date', 'sales','inventory', 'rent', 'stationery', 'telephone', 'consultation', 'salaries', 'water', 'zesa', 'internet',
'fuel','welfare','transport','license','repairs','research','foreign','bankCharges','bankInterest','loanInterest',
'fines','export','travel','local','other','totalExpenses','totalRevenue','capital','bankLoan','otherRevenue','creditors','debtors','purchases'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function search(Request $request)
{
$this->authorize('viewAny', Product::class);
if ($request->start_date > $request->end_date) {
return back()->withStatus("Start date cannot be greater than end date");
} else {
$dat = $request->input('end_date');
$date=Carbon::createFromFormat("Y-m-d",$dat);
$sales = Sale::query()->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('amount');
$rent = Requisition::query()->where('description', "Rent")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$stationery = Requisition::query()->where('description', "Stationery")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$telephone = Requisition::query()->where('description', "Telephone")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$consultation = Requisition::query()->where('description', "Consultation")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$salaries = Requisition::query()->where('description', "Salaries and Wages")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$water = Requisition::query()->where('description', "Water Bills")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$zesa = Requisition::query()->where('description', "Heating and Lighting")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$internet = Requisition::query()->where('description', "Internet")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$fuel = Requisition::query()->where('description', "Fuels and Oils")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$welfare = Requisition::query()->where('description', "Staff Welfare")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$transport = Requisition::query()->where('description', "Transport")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$license = Requisition::query()->where('description', "Licenses")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$repairs = Requisition::query()->where('description', "Repairs and Maintenance")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$research = Requisition::query()->where('description', "Research and Development")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$foreign = Requisition::query()->where('description', "Foreign Exchange Differences")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$bankCharges = Requisition::query()->where('description', "Bank Charges")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$bankInterest = Requisition::query()->where('description', "Bank Interest")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$loanInterest = Requisition::query()->where('description', "Loan Interest")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$fines = Requisition::query()->where('description', "Fines")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$travel = Requisition::query()->where('description', "Travel and Subsistence")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$export = Requisition::query()->where('description', "Export Marketing Expenses")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$local = Requisition::query()->where('description', "Local Marketing Expenses")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$other = Requisition::query()->where('description', "Other")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$debtors = Requisition::query()->where('description', "Debtors")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$purchases = Requisition::query()->where('description', "Purchases")->where('processed', true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount');
$inventory=PurchaseOrder::query()->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('cost_price');
$totalExpenses=Requisition::query()->where('processed',true)->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('total_amount')+$inventory;
$capital=Revenue::query()->where('name',"Capital")->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('amount');
$bankLoan=Revenue::query()->where('name',"Bank Loan")->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('amount');
$creditors=Revenue::query()->where('name',"Bank Loan")->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('amount');
$otherRevenue=Revenue::query()->where('name',"Other")->whereDate('created_at','>=',$request->input('start_date'))->whereDate('created_at','<=',$request->input('end_date'))->sum('amount');
$totalRevenue=$sales+$creditors+$capital+$bankLoan+$otherRevenue;
//$rent+$stationery+$telephone+$consultation+$salaries+$water+$zesa+$internet+$fuel+$welfare+$travel+$transport+$license+$repairs+$research+$foreign+$bankCharges+$bankInterest+$loanInterest+$fines+$export+$local+$other;
return view('trial_balance.index', compact(
'date', 'sales','inventory', 'rent', 'stationery', 'telephone', 'consultation', 'salaries', 'water', 'zesa', 'internet',
'fuel','welfare','transport','license','repairs','research','foreign','bankCharges','bankInterest','loanInterest',
'fines','export','travel','local','other','totalExpenses','totalRevenue','capital','bankLoan','otherRevenue','creditors','debtors','purchases'));
}
}
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$sources=Revenue::query()->where('name','Other')->get();
return view('trial_balance.show',compact('sources'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
| 83.558011 | 263 | 0.644538 |
170538124442bdee46cd8f3c476403b6d804f2b3 | 5,683 | h | C | host/src/cc3x_sbromlib/bsv_crypto_driver.h | QPC-database/cryptocell-312-runtime | 91539d62a67662e40e7d925694e55bbc7e679f84 | [
"BSD-3-Clause"
] | 1 | 2021-07-04T00:08:54.000Z | 2021-07-04T00:08:54.000Z | host/src/cc3x_sbromlib/bsv_crypto_driver.h | QPC-database/cryptocell-312-runtime | 91539d62a67662e40e7d925694e55bbc7e679f84 | [
"BSD-3-Clause"
] | null | null | null | host/src/cc3x_sbromlib/bsv_crypto_driver.h | QPC-database/cryptocell-312-runtime | 91539d62a67662e40e7d925694e55bbc7e679f84 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2001-2019, Arm Limited and Contributors. All rights reserved.
*
* SPDX-License-Identifier: BSD-3-Clause OR Arm’s non-OSI source license
*/
#ifndef _BSV_CRYPTO_DRIVER_H
#define _BSV_CRYPTO_DRIVER_H
#ifdef __cplusplus
extern "C"
{
#endif
#include "cc_sec_defs.h"
#include "bsv_crypto_defs.h"
/*! @file
@brief This file contains crypto driver definitions: SH256, CMAC KDF, and CCM.
*/
/************************ Defines ******************************/
/*! SHA256 digest result in words. */
#define CC_BSV_SHA256_DIGEST_SIZE_IN_WORDS 8
/*! SHA256 digest result in bytes. */
#define CC_BSV_SHA256_DIGEST_SIZE_IN_BYTES CC_BSV_SHA256_DIGEST_SIZE_IN_WORDS*sizeof(uint32_t)
/*! SHA256 maximal data size to be hashed */
#define CC_BSV_SHA256_MAX_DATA_SIZE_IN_BYTES 0x00010000 /* 64KB */
/*! The derived key size for 128 bits. */
#define CC_BSV_128BITS_KEY_SIZE_IN_BYTES 16
/*! The derived key size for 256 bits. */
#define CC_BSV_256BITS_KEY_SIZE_IN_BYTES 32
/*! Maximal label length in bytes. */
#define CC_BSV_MAX_LABEL_LENGTH_IN_BYTES 8
/*! Maximal context length in bytes. */
#define CC_BSV_MAX_CONTEXT_LENGTH_IN_BYTES 32
/*! KDF 128 bits key fixed data size in bytes. */
#define CC_BSV_KDF_DATA_128BITS_SIZE_IN_BYTES 3 /*!< \internal 0x01, 0x00, lengt(-0x80) */
/*! KDF 256 bits key fixed data size in bytes. */
#define CC_BSV_KDF_DATA_256BITS_SIZE_IN_BYTES 4 /*!< \internal 0x02, 0x00, lengt(-0x0100) */
/*! KDF data maximal size in bytes. */
#define CC_BSV_KDF_MAX_SIZE_IN_BYTES (CC_BSV_KDF_DATA_256BITS_SIZE_IN_BYTES + CC_BSV_MAX_LABEL_LENGTH_IN_BYTES + CC_BSV_MAX_CONTEXT_LENGTH_IN_BYTES)
/*! Maximal AES CCM associated data size in bytes. */
#define CC_BSV_CCM_MAX_ASSOC_DATA_SIZE_IN_BYTES 0xff00 /* 2^16-2^8 */
/*! Maximal AES CCM text data size in bytes. */
#define CC_BSV_CCM_MAX_TEXT_DATA_SIZE_IN_BYTES 0x00010000 /* 64KB */
/*! AES block size in bytes. */
#define BSV_AES_BLOCK_SIZE_IN_BYTES 16
/*! AES IV size in bytes. */
#define BSV_AES_IV_SIZE_IN_BYTES 16
/*! AES IV size in words. */
#define BSV_AES_IV_SIZE_IN_WORDS 4
/*! HASH SHA256 control value. */
#define BSV_HASH_CTL_SHA256_VAL 0x2UL
/*! HASH SHA256 padding configuration. */
#define BSV_HASH_PAD_CFG_VAL 0x4UL
/************************ Typedefs *****************************/
/*! Definitions of cryptographic mode. */
typedef enum bsvCryptoMode {
/*! AES.*/
BSV_CRYPTO_AES = 1,
/*! AES and HASH.*/
BSV_CRYPTO_AES_AND_HASH = 3,
/*! HASH.*/
BSV_CRYPTO_HASH = 7,
/*! AES to HASH and to DOUT.*/
BSV_CRYPTO_AES_TO_HASH_AND_DOUT = 10,
/*! Reserved.*/
BSV_CRYPTO_RESERVE32B = INT32_MAX
}bsvCryptoMode_t;
/*! Definitions for AES modes. */
typedef enum bsvAesMode {
/*! AES CTR mode.*/
BSV_AES_CIPHER_CTR = 2,
/*! AES CBC MAC mode.*/
BSV_AES_CIPHER_CBC_MAC = 3,
/*! AES CMAC mode.*/
BSV_AES_CIPHER_CMAC = 7,
/*! AES CCM PE mode.*/
BSV_AES_CIPHER_CCMPE = 9,
/*! AES CCM PD mode.*/
BSV_AES_CIPHER_CCMPD = 10,
/*! Reserved.*/
BSV_AES_CIPHER_RESERVE32B = INT32_MAX
}bsvAesMode_t;
/*! Definitions for AES directions. */
typedef enum bsvAesDirection {
/*! Encrypt.*/
BSV_AES_DIRECTION_ENCRYPT = 0,
/*! Decrypt.*/
BSV_AES_DIRECTION_DECRYPT = 1,
/*! Reserved.*/
BSV_AES_DIRECTION_RESERVE32B = INT32_MAX
}bsvAesDirection_t;
/*! Defintions for AES key sizes. */
typedef enum bsvAesKeySize {
/*! 128 bits AES key. */
BSV_AES_KEY_SIZE_128BITS = 0,
/*! 256 bits AES key. */
BSV_AES_KEY_SIZE_256BITS = 2,
/*! Reserved.*/
BSV_AES_KEY_SIZE_RESERVE32B = INT32_MAX
}bsvAesKeySize_t;
/***************************** function declaration **************************/
CCError_t BsvAes(unsigned long hwBaseAddress,
bsvAesMode_t mode,
CCBsvKeyType_t keyType,
uint32_t *pUserKey,
size_t userKeySize,
uint32_t *pIvBuf,
uint8_t *pDataIn,
uint8_t *pDataOut,
size_t dataSize,
CCBsvCmacResult_t cmacResBuf);
CCError_t BsvCryptoImageInit( unsigned long hwBaseAddress,
bsvCryptoMode_t mode,
CCBsvKeyType_t keyType);
CCError_t BsvCryptoImageUpdate( unsigned long hwBaseAddress,
bsvCryptoMode_t mode,
CCBsvKeyType_t keyType,
uint32_t *pCtrStateBuf,
uint8_t *pDataIn,
uint8_t *pDataOut,
size_t dataSize,
CCHashResult_t hashBuff,
uint8_t isLoadIV);
CCError_t BsvCryptoImageFinish( unsigned long hwBaseAddress,
bsvCryptoMode_t mode,
CCHashResult_t hashBuff);
/* SHA256 */
void InitBsvHash(unsigned long hwBaseAddress);
void FreeBsvHash(unsigned long hwBaseAddress);
CCError_t ProcessBsvHash(unsigned long hwBaseAddress, uint32_t inputDataAddr, uint32_t dataInSize);
void FinishBsvHash(unsigned long hwBaseAddress, CCHashResult_t HashBuff);
/* AES (CTR, CMAC ) */
void InitBsvAes(unsigned long hwBaseAddress);
void FreeBsvAes(unsigned long hwBaseAddress);
CCError_t ProcessBsvAes(unsigned long hwBaseAddress,
bsvAesMode_t mode,
CCBsvKeyType_t keyType,
uint32_t *pUserKey,
size_t userKeySize,
uint32_t *pCtrStateBuf,
uint32_t inputDataAddr,
uint32_t outputDataAddr,
uint32_t blockSize,
uint8_t isLoadIv);
void FinishBsvAes(unsigned long hwBaseAddress,
bsvAesMode_t mode,
CCBsvCmacResult_t cmacResBuf);
/* AES-CCM */
CCError_t ProcessBsvAesCcm(unsigned long hwBaseAddress,
bsvAesMode_t mode,
uint32_t *pKeyBuf,
uint32_t *pIvBuf,
uint32_t *pCtrStateBuf,
uint32_t inputDataAddr,
uint32_t outputDataAddr,
uint32_t blockSize);
void FinishBsvAesCcm(unsigned long hwBaseAddress,
bsvAesMode_t mode,
uint32_t *pIvBuf,
uint32_t *pCtrStateBuf);
#ifdef __cplusplus
}
#endif
#endif
| 27.454106 | 148 | 0.710892 |
fb95cc8e851efb92c6880291e1f69232ff643dff | 649 | java | Java | src/main/java/com/github/ansonliao/selenium/utils/AnnotationUtils.java | ansonliao/Selenium-Extensions | c5e37b68c33993b403cc2d4d715d541094a2843e | [
"Apache-2.0"
] | 15 | 2017-07-03T04:01:39.000Z | 2021-05-02T06:41:55.000Z | src/main/java/com/github/ansonliao/selenium/utils/AnnotationUtils.java | ansonliao/Selenium-Extensions | c5e37b68c33993b403cc2d4d715d541094a2843e | [
"Apache-2.0"
] | 20 | 2017-09-15T09:35:31.000Z | 2021-10-07T08:40:49.000Z | src/main/java/com/github/ansonliao/selenium/utils/AnnotationUtils.java | ansonliao/Selenium-Extensions | c5e37b68c33993b403cc2d4d715d541094a2843e | [
"Apache-2.0"
] | 7 | 2017-09-27T05:39:47.000Z | 2019-08-30T15:34:02.000Z | package com.github.ansonliao.selenium.utils;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Set;
public class AnnotationUtils {
private static Logger logger = LoggerFactory.getLogger(AnnotationUtils.class);
public static synchronized Set<Annotation> getClassAnnotations(Class clazz) {
return Sets.newHashSet(clazz.getAnnotations());
}
public static synchronized Set<Annotation> getMethodAnnotations(Method method) {
return Sets.newHashSet(method.getAnnotations());
}
}
| 29.5 | 84 | 0.773498 |
2dbb7fc0e4400e5c0d3dbeea1a9f1c96282af2a0 | 1,571 | html | HTML | application/wap/view/index/index.html | Catfeeds/xiaowu | 541ef71ca6c50ef7705e2654dba814b0e652ec47 | [
"Apache-2.0"
] | null | null | null | application/wap/view/index/index.html | Catfeeds/xiaowu | 541ef71ca6c50ef7705e2654dba814b0e652ec47 | [
"Apache-2.0"
] | null | null | null | application/wap/view/index/index.html | Catfeeds/xiaowu | 541ef71ca6c50ef7705e2654dba814b0e652ec47 | [
"Apache-2.0"
] | 1 | 2019-06-11T06:21:35.000Z | 2019-06-11T06:21:35.000Z | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>学习资料</title>
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="stylesheet" href="__WAP__/css/mui.min.css">
<style>
h5{
padding-top: 8px;
padding-bottom: 8px;
text-indent: 12px;
}
.mui-table-view.mui-grid-view .mui-table-view-cell .mui-media-body{
font-size: 15px;
margin-top:8px;
color: #333;
}
</style>
</head>
<body>
<header class="mui-bar mui-bar-nav">
<h1 class="mui-title">学习资料</h1>
<a class="mui-icon mui-icon-gear mui-icon-right-nav mui-pull-right" href="<?=url('index/person')?>"></a>
</header>
<div class="mui-content" style="background-color:#fff">
<ul class="mui-table-view mui-grid-view">
{volist name="lesson" id="les" empty="暂无相关课程"}
<li class="mui-table-view-cell mui-media mui-col-xs-6">
<a href="<?=url('index/chapter')?>?ls_id={$les.ls_id}">
<img class="mui-media-object" src="{$les.ls_img}" alt="{$les.ls_img_alt}">
<div class="mui-media-body">{$les.ls_title}</div>
</a>
</li>
{/volist}
</ul>
</div>
</body>
<script src="__WAP__/js/mui.min.js"></script>
<script>
mui.init({
swipeBack:true //启用右滑关闭功能
});
</script>
</html> | 31.42 | 108 | 0.562062 |
c1b67ce9a5f8358de8ac7da035c3397b666830ff | 4,279 | rs | Rust | src/config.rs | hioki/gatekeeper | 90f4fcf40fe6be0a45f35d96d2c8aa4e61d087ea | [
"Apache-2.0"
] | null | null | null | src/config.rs | hioki/gatekeeper | 90f4fcf40fe6be0a45f35d96d2c8aa4e61d087ea | [
"Apache-2.0"
] | null | null | null | src/config.rs | hioki/gatekeeper | 90f4fcf40fe6be0a45f35d96d2c8aa4e61d087ea | [
"Apache-2.0"
] | null | null | null | use std::fs::File;
use std::path::Path;
use std::time::Duration;
use crate::error::{Error, ErrorKind};
use crate::model::{ConnectRule, IpAddr, Ipv4Addr, SocketAddr};
use failure::ResultExt;
use serde_yaml;
/// Server configuration
#[derive(Debug, Clone)]
pub struct ServerConfig {
/// ip address for listening connections. (default: 0.0.0.0)
pub server_ip: IpAddr,
/// port number for listening connections. (default: 1080)
pub server_port: u16,
/// rule set for filtering connection requests (default: allow any connection)
pub conn_rule: ConnectRule,
/// timeout of relaying data chunk from client to external network. (default: 2000ms)
pub client_rw_timeout: Option<Duration>,
/// timeout of relaying data chunk from external network to client. (default: 5000ms)
pub server_rw_timeout: Option<Duration>,
/// timeout of accpet connection from client. (default 3s)
pub accept_timeout: Option<Duration>,
}
impl ServerConfig {
pub fn new(server_ip: IpAddr, server_port: u16, conn_rule: ConnectRule) -> Self {
Self {
server_ip,
server_port,
conn_rule,
..Self::default()
}
}
/// Config with filter rule from file
///
/// * `server_ip`
/// Listening ip address of the Server.
/// * `server_port`
/// Listening port number of the Server.
/// * `rulefile`
/// Path to file specify filtering rules in yaml.
///
/// # Example
///
/// Here is an example of filtering rule written in yaml.
///
/// ```
/// use std::fs;
/// # use std::path::Path;
/// # use gatekeeper::error::Error;
/// # use gatekeeper::model::L4Protocol::*;
/// use gatekeeper::config::ServerConfig;
/// # fn main() -> Result<(), Error> {
/// fs::write("rule.yml", r#"
/// ---
/// # # default deny
/// - Deny:
/// address: Any
/// port: Any
/// protocol: Any
/// # # allow local ipv4 network 192.168.0.1/16
/// - Allow:
/// address:
/// Specif:
/// IpAddr:
/// addr: 192.168.0.1
/// prefix: 16
/// port: Any
/// protocol: Any
/// "#.as_bytes())?;
/// let config = ServerConfig::with_file("192.168.0.1".parse().unwrap(), 1080, Path::new("rule.yml"))?;
/// assert!(config.conn_rule.check("192.168.0.2:80".parse().unwrap(), Tcp));
/// assert!(!config.conn_rule.check("192.167.0.2:80".parse().unwrap(), Udp));
/// # Ok(())
/// # }
/// ```
///
pub fn with_file(server_ip: IpAddr, server_port: u16, rulefile: &Path) -> Result<Self, Error> {
let path = File::open(rulefile)?;
let conn_rule = serde_yaml::from_reader(path).context(ErrorKind::Config)?;
Ok(ServerConfig {
server_ip,
server_port,
conn_rule,
..Self::default()
})
}
}
impl Default for ServerConfig {
fn default() -> Self {
ServerConfig {
server_ip: Ipv4Addr::new(0, 0, 0, 0).into(),
server_port: 1080,
conn_rule: ConnectRule::any(),
client_rw_timeout: Some(Duration::from_millis(2000)),
server_rw_timeout: Some(Duration::from_millis(5000)),
accept_timeout: Some(Duration::from_secs(3)),
}
}
}
impl ServerConfig {
pub fn server_addr(&self) -> SocketAddr {
SocketAddr::new(self.server_ip, self.server_port)
}
pub fn connect_rule(&self) -> ConnectRule {
self.conn_rule.clone()
}
pub fn set_server_addr(&mut self, addr: SocketAddr) -> &mut Self {
self.server_ip = addr.ip();
self.server_port = addr.port();
self
}
pub fn set_connect_rule(&mut self, rule: ConnectRule) -> &mut Self {
self.conn_rule = rule;
self
}
pub fn set_client_rw_timeout(&mut self, dur: Option<Duration>) -> &mut Self {
self.client_rw_timeout = dur;
self
}
pub fn set_server_rw_timeout(&mut self, dur: Option<Duration>) -> &mut Self {
self.server_rw_timeout = dur;
self
}
pub fn set_accept_timeout(&mut self, dur: Option<Duration>) -> &mut Self {
self.accept_timeout = dur;
self
}
}
| 30.133803 | 107 | 0.574667 |
95c80bdfbe44391eabecd23ea583305c7373ec0e | 1,823 | html | HTML | src/blocks/main-nav/main-nav.html | des-yogi/utels | ede23fbd9f1be56c8ddd8b60ff8461edc2c3931a | [
"WTFPL"
] | null | null | null | src/blocks/main-nav/main-nav.html | des-yogi/utels | ede23fbd9f1be56c8ddd8b60ff8461edc2c3931a | [
"WTFPL"
] | 1 | 2021-08-20T15:25:21.000Z | 2021-08-20T15:25:21.000Z | src/blocks/main-nav/main-nav.html | des-yogi/utels | ede23fbd9f1be56c8ddd8b60ff8461edc2c3931a | [
"WTFPL"
] | null | null | null | <!--DEV
@ @include('blocks/main-nav/main-nav.html')
-->
<nav id="main-nav" class="container main-nav">
<ul class="list-nostyled main-nav__list">
<li class="main-nav__item">
<a href="#" class="main-nav__link">Для дому</a>
</li>
<li class="main-nav__item main-nav__item--has-children active">
<a class="main-nav__link main-nav__link--arrow">Для бізнесу</a>
<ul class="list-nostyled main-nav__sublist">
<li><a href="#">Очень длинный пункт меню номер один</a></li>
<li class="active"><a>Пункт меню 2</a></li>
<li><a href="#">Пункт меню 3</a></li>
<li><a href="#">Пункт меню 4</a></li>
<li><a href="#">Пункт меню 5</a></li>
</ul>
</li>
<li class="main-nav__item main-nav__item--has-children">
<a href="#" class="main-nav__link main-nav__link--arrow">Сервіси</a>
<ul class="list-nostyled main-nav__sublist">
<li><a href="#">Пункт меню 1</a></li>
<li><a href="#">Пункт меню 2</a></li>
<li><a href="#">Пункт меню 3</a></li>
<li class="active"><a>Пункт меню 4</a></li>
<li><a href="#">Пункт меню 5</a></li>
</ul>
</li>
<li class="main-nav__item">
<a href="#" class="main-nav__link">Послуги</a>
</li>
<li class="main-nav__item">
<a href="#" class="main-nav__link">Акції</a>
</li>
<li class="main-nav__item">
<a href="#" class="main-nav__link">Підтримка</a>
</li>
<li class="main-nav__item">
<a href="#" class="main-nav__link">Обладнання</a>
</li>
<li class="main-nav__item">
<a href="#" class="main-nav__link">Покриття</a>
</li>
<li class="main-nav__item">
<a href="#" class="main-nav__link">Мій УТЕЛС</a>
</li>
</ul>
@@include('../../blocks/contact-widget/contact-widget.html')
</nav>
| 35.745098 | 75 | 0.562809 |
5d7e89ecc21b42634102f6c6e559b8a4a6c8b0d0 | 864 | go | Go | main.go | NexClipper/curlbee | 6276ac1e6974012a4bb2847a8918db3ca75d0707 | [
"Apache-2.0"
] | 1 | 2021-09-03T23:00:14.000Z | 2021-09-03T23:00:14.000Z | main.go | NexClipper/curlbee | 6276ac1e6974012a4bb2847a8918db3ca75d0707 | [
"Apache-2.0"
] | null | null | null | main.go | NexClipper/curlbee | 6276ac1e6974012a4bb2847a8918db3ca75d0707 | [
"Apache-2.0"
] | null | null | null | package main
import (
"flag"
"io/ioutil"
"log"
"gopkg.in/yaml.v2"
"github.com/nexclipper/curlbee/cmd"
"github.com/nexclipper/curlbee/pkg/config"
)
func main() {
fileName := flag.String("filename", "", "yaml file name")
execType := flag.String("type", "cli", "specifies the type of execution process[cli(default)|http]")
param := flag.String("param", "", "parameters can be transferred")
flag.Parse()
//*execType = "http"
//*fileName = "./example/policy4.yml"
//fmt.Println(*fileName)
//fmt.Println(*param)
yamlBuf, err := ioutil.ReadFile(*fileName)
if err != nil {
panic(err)
}
cfg := &config.BeeConfig{}
err = yaml.Unmarshal(yamlBuf, cfg)
if err != nil {
panic(err)
}
bee := cmd.NewBee(*execType, *param)
if bee != nil {
err := bee.Run(cfg)
if err != nil {
panic(err)
}
} else {
log.Println("type is not valid")
}
}
| 19.2 | 101 | 0.636574 |
0cb626407dc59dff1be601a5e0499c7a012ea0ad | 75 | py | Python | app/database/base.py | CabetoDP/fastapi-crud | bbeef58b74b7a010037ca8503a7f05f8b4db2ab4 | [
"MIT"
] | null | null | null | app/database/base.py | CabetoDP/fastapi-crud | bbeef58b74b7a010037ca8503a7f05f8b4db2ab4 | [
"MIT"
] | null | null | null | app/database/base.py | CabetoDP/fastapi-crud | bbeef58b74b7a010037ca8503a7f05f8b4db2ab4 | [
"MIT"
] | null | null | null | from app.database.base_class import Base
from app.models.place import Place | 37.5 | 40 | 0.853333 |
5423049a0cff9d9e8c8ae9caac54386b38c07570 | 6,225 | go | Go | roxctl/common/printer/objectprinter_factory_test.go | stackrox/stackrox | 3b2929fd5f2bc68d5742bd958a22e03202ae6be4 | [
"Apache-2.0"
] | 22 | 2022-03-31T14:32:18.000Z | 2022-03-31T22:11:30.000Z | roxctl/common/printer/objectprinter_factory_test.go | stackrox/stackrox | 3b2929fd5f2bc68d5742bd958a22e03202ae6be4 | [
"Apache-2.0"
] | 5 | 2022-03-31T14:35:28.000Z | 2022-03-31T22:40:13.000Z | roxctl/common/printer/objectprinter_factory_test.go | stackrox/stackrox | 3b2929fd5f2bc68d5742bd958a22e03202ae6be4 | [
"Apache-2.0"
] | 4 | 2022-03-31T16:33:58.000Z | 2022-03-31T22:19:26.000Z | package printer
import (
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/stackrox/rox/pkg/errox"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewObjectPrinterFactory(t *testing.T) {
cases := map[string]struct {
defaultFormat string
shouldFail bool
error error
printerFactory []CustomPrinterFactory
}{
"should fail when no CustomPrinterFactory is added": {
defaultFormat: "table",
shouldFail: true,
error: errox.InvariantViolation,
printerFactory: []CustomPrinterFactory{nil},
},
"should not fail if format is supported by registered CustomPrinterFactory": {
defaultFormat: "table",
printerFactory: []CustomPrinterFactory{NewTabularPrinterFactory(nil, "")},
},
"should not fail if format is supported and valid values for CustomPrinterFactory": {
defaultFormat: "table",
printerFactory: []CustomPrinterFactory{NewTabularPrinterFactory([]string{"a", "b"}, "a,b")},
},
"should fail if default output format is not supported by registered CustomPrinterFactory": {
defaultFormat: "table",
shouldFail: true,
error: errox.InvalidArgs,
printerFactory: []CustomPrinterFactory{NewJSONPrinterFactory(false, false)},
},
"should fail if duplicate CustomPrinterFactory is being registered": {
defaultFormat: "json",
shouldFail: true,
error: errox.InvariantViolation,
printerFactory: []CustomPrinterFactory{NewJSONPrinterFactory(false, false), NewJSONPrinterFactory(false, false)},
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
_, err := NewObjectPrinterFactory(c.defaultFormat, c.printerFactory...)
if c.shouldFail {
require.Error(t, err)
assert.ErrorIs(t, err, c.error)
} else {
require.NoError(t, err)
}
})
}
}
func TestObjectPrinterFactory_AddFlags(t *testing.T) {
o := ObjectPrinterFactory{
OutputFormat: "table",
RegisteredPrinterFactories: map[string]CustomPrinterFactory{
"json": NewJSONPrinterFactory(false, false),
"table,csv": NewTabularPrinterFactory(nil, ""),
},
}
cmd := &cobra.Command{
Use: "test",
}
o.AddFlags(cmd)
formatFlag := cmd.Flag("output")
require.NotNil(t, formatFlag)
assert.Equal(t, "o", formatFlag.Shorthand)
assert.Equal(t, "table", formatFlag.DefValue)
assert.True(t, strings.Contains(formatFlag.Usage, "json"))
assert.True(t, strings.Contains(formatFlag.Usage, "table"))
assert.True(t, strings.Contains(formatFlag.Usage, "csv"))
}
func TestObjectPrinterFactory_validateOutputFormat(t *testing.T) {
cases := map[string]struct {
o ObjectPrinterFactory
shouldFail bool
error error
}{
"should not return an error when output format is supported": {
o: ObjectPrinterFactory{
OutputFormat: "table",
RegisteredPrinterFactories: map[string]CustomPrinterFactory{
"table,csv": NewTabularPrinterFactory(nil, ""),
"json": NewJSONPrinterFactory(false, false),
},
},
shouldFail: false,
},
"should return an error when output format is not supported": {
o: ObjectPrinterFactory{
OutputFormat: "junit",
RegisteredPrinterFactories: map[string]CustomPrinterFactory{
"table,csv": NewTabularPrinterFactory(nil, ""),
"json": NewJSONPrinterFactory(false, false),
},
},
shouldFail: true,
error: errox.InvalidArgs,
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
err := c.o.validateOutputFormat()
if c.shouldFail {
require.Error(t, err)
assert.ErrorIs(t, err, c.error)
} else {
require.NoError(t, err)
}
})
}
}
func TestObjectPrinterFactory_IsStandardizedFormat(t *testing.T) {
cases := map[string]struct {
res bool
format string
}{
"should be true for JSON format": {
res: true,
format: "json",
},
"should be true for CSV format": {
res: true,
format: "csv",
},
"should be false for table format": {
res: false,
format: "table",
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
o := ObjectPrinterFactory{OutputFormat: c.format}
assert.Equal(t, c.res, o.IsStandardizedFormat())
})
}
}
func TestObjectPrinterFactory_CreatePrinter(t *testing.T) {
cases := map[string]struct {
o ObjectPrinterFactory
error error
}{
"should return an error when the output format is not supported": {
o: ObjectPrinterFactory{
OutputFormat: "table",
RegisteredPrinterFactories: map[string]CustomPrinterFactory{
"json": NewJSONPrinterFactory(false, false),
},
},
error: errox.InvalidArgs,
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
printer, err := c.o.CreatePrinter()
require.Error(t, err)
assert.ErrorIs(t, err, c.error)
assert.Nil(t, printer)
})
}
}
func TestObjectPrinterFactory_validate(t *testing.T) {
cases := map[string]struct {
o ObjectPrinterFactory
shouldFail bool
error error
}{
"should not fail with valid CustomPrinterFactory and valid output format": {
o: ObjectPrinterFactory{
RegisteredPrinterFactories: map[string]CustomPrinterFactory{
"json": NewJSONPrinterFactory(false, false),
},
OutputFormat: "json",
},
},
"should fail with invalid CustomPrinterFactory": {
o: ObjectPrinterFactory{
RegisteredPrinterFactories: map[string]CustomPrinterFactory{
"table": &TabularPrinterFactory{
Headers: []string{"a", "b"},
RowJSONPathExpression: "a",
NoHeader: true,
HeaderAsComment: true,
},
},
OutputFormat: "table",
},
shouldFail: true,
error: errox.InvalidArgs,
},
"should fail with unsupported OutputFormat": {
o: ObjectPrinterFactory{
RegisteredPrinterFactories: map[string]CustomPrinterFactory{
"json": NewJSONPrinterFactory(false, false),
},
OutputFormat: "table",
},
shouldFail: true,
error: errox.InvalidArgs,
},
}
for name, c := range cases {
t.Run(name, func(t *testing.T) {
err := c.o.validate()
if c.shouldFail {
require.Error(t, err)
assert.ErrorIs(t, err, c.error)
} else {
assert.NoError(t, err)
}
})
}
}
| 27.065217 | 116 | 0.670361 |
37c90d322cec845bf7ba001c6a51daf7aa9b5cc0 | 913 | kt | Kotlin | src/main/kotlin/com/xfastgames/witness/utils/Collections.kt | prodzpod/fabric-witness | 72ac307406307a26d44f271f3865da3a6bd8aaec | [
"Apache-2.0"
] | 3 | 2020-09-11T09:38:02.000Z | 2022-03-18T18:22:53.000Z | src/main/kotlin/com/xfastgames/witness/utils/Collections.kt | prodzpod/fabric-witness | 72ac307406307a26d44f271f3865da3a6bd8aaec | [
"Apache-2.0"
] | 8 | 2020-05-10T12:51:29.000Z | 2021-01-27T22:54:59.000Z | src/main/kotlin/com/xfastgames/witness/utils/Collections.kt | prodzpod/fabric-witness | 72ac307406307a26d44f271f3865da3a6bd8aaec | [
"Apache-2.0"
] | 1 | 2021-08-08T01:43:11.000Z | 2021-08-08T01:43:11.000Z | package com.xfastgames.witness.utils
fun <T> Collection<T>.containsOnly(vararg others: T): Boolean =
this.containsAll(others.toSet()) &&
this.subtract(others.toList()).isEmpty()
/**
* Zip the collection with itself where each entry is paired with the next element.
* Pairs are returned in the order of first element [T] and second element [T]
* @return listOf(first to second, second to third, third to fourth etc.)
*/
fun <T> Collection<T>.zipSelf(): List<Pair<T, T>> {
val offset: List<T?> = listOf(null).plus(this)
return offset.zip(this)
.filter { (previous, _) -> previous != null }
.filterIsInstance<Pair<T, T>>()
}
fun <T> Collection<T>.paired(): List<Pair<T, T>> =
this.chunked(2)
.map { items -> items.first() to items.last() }
fun <T : Comparable<T>> Collection<T>.closest(value: T): T? =
this.minByOrNull { item -> value.compareTo(item) } | 38.041667 | 83 | 0.651698 |
59987bf7c002955fb668cd2550422e80916138ff | 2,244 | sql | SQL | system-database/test-data/h2_create_tables.sql | deleidos/digitaledge-platform | 1eafdb92f6a205936ab4e08ef62be6bb0b9c9ec9 | [
"Apache-2.0"
] | 4 | 2015-07-09T14:57:07.000Z | 2022-02-23T17:48:24.000Z | system-database/test-data/h2_create_tables.sql | deleidos/digitaledge-platform | 1eafdb92f6a205936ab4e08ef62be6bb0b9c9ec9 | [
"Apache-2.0"
] | 1 | 2016-04-20T01:13:29.000Z | 2016-04-20T01:13:29.000Z | system-database/test-data/h2_create_tables.sql | deleidos/digitaledge-platform | 1eafdb92f6a205936ab4e08ef62be6bb0b9c9ec9 | [
"Apache-2.0"
] | 4 | 2016-03-10T00:23:17.000Z | 2022-03-02T11:17:02.000Z | CREATE TABLE IF NOT EXISTS APPLICATION.H2_TYPE_TEST(
PK_COL_1 NUMBER NOT NULL PRIMARY KEY,
INT_COL_1_INT INT,
INT_COL_2_INTEGER INTEGER,
INT_COL_3_MEDIUMINT MEDIUMINT,
INT_COL_4_INT4 INT4,
INT_COL_5_SIGNED SIGNED,
BOOL_COL_1_BOOLEAN BOOLEAN,
BOOL_COL_2_BIT BIT,
BOOL_COL_3_BOOL BOOL,
TINYINT_COL_1 TINYINT,
SMALLINT_COL_1_SMALLINT SMALLINT,
SMALLINT_COL_2_INT2 INT2,
SMALLINT_COL_3_YEAR YEAR,
BIGINT_COL_1_BIGINT BIGINT,
BIGINT_COL_2_INT8 INT8,
DECIMAL_COL_1_DECIMAL DECIMAL,
DECIMAL_COL_2_NUMBER NUMBER,
DECIMAL_COL_3_NUMBER_10_3 NUMBER(10, 3),
DECIMAL_COL_4_DEC DEC,
DECIMAL_COL_5_NUMERIC NUMERIC,
DOUBLE_COL_1_DOUBLE DOUBLE,
DOUBLE_COL_2_DOUBLE_10 DOUBLE(10),
DOUBLE_COL_3_FLOAT FLOAT,
DOUBLE_COL_4_FLOAT4 FLOAT4,
DOUBLE_COL_5_FLOAT8 FLOAT8,
REAL_COL_1_REAL REAL,
TIME_COL_1_TIME TIME,
DATE_COL_1_DATE DATE,
TIMESTAMP_COL_1_TIMESTAMP TIMESTAMP,
TIMESTAMP_COL_2_DATETIME DATETIME,
TIMESTAMP_COL_3_SMALLDATETIME SMALLDATETIME,
BINARY_COL_1_BINARY BINARY,
BINARY_COL_2_BINARY_1000 BINARY(1000),
BINARY_COL_3_VARBINARY VARBINARY,
BINARY_COL_4_LONGVARBINARY LONGVARBINARY,
BINARY_COL_5_RAW RAW,
BINARY_COL_6_BYTEA BYTEA,
OTHER_COL_1_OTHER OTHER,
VARCHAR_COL_1_VARCHAR VARCHAR,
VARCHAR_COL_2_VARCHAR_255 VARCHAR(255),
VARCHAR_COL_3_LONGVARCHAR LONGVARCHAR,
VARCHAR_COL_4_VARCHAR2 VARCHAR2,
VARCHAR_COL_5_NVARCHAR NVARCHAR,
VARCHAR_COL_6_NVARCHAR2 NVARCHAR2,
VARCHAR_COL_7_VARCHAR_CASESENSITIVE VARCHAR_CASESENSITIVE,
VARCHARIGNORECASE_COL_1_VARCHARIGNORECASE VARCHAR_IGNORECASE,
VARCHARIGNORECASE_COL_2_VARCHARIGNORECASE_10 VARCHAR_IGNORECASE(10),
CHAR_COL_1_CHAR CHAR,
CHAR_COL_2_CHAR_10 CHAR(10),
CHAR_COL_3_CHARACTER CHARACTER,
CHAR_COL_4_NCHAR NCHAR,
BLOB_COL_1_BLOB BLOB,
BLOB_COL_2_BLOB_500 BLOB(500),
BLOB_COL_3_TINYBLOB TINYBLOB,
BLOB_COL_4_MEDIUMBLOB MEDIUMBLOB,
BLOB_COL_5_LONGBLOB LONGBLOB,
BLOB_COL_6_IMAGE IMAGE,
BLOB_COL_7_OID OID,
CLOB_COL_1_CLOB CLOB,
CLOB_COL_2_CLOB_500 CLOB(500),
CLOB_COL_3_TINYTEXT TINYTEXT,
CLOB_COL_4_TEXT TEXT,
CLOB_COL_5_MEDIUMTEXT MEDIUMTEXT,
CLOB_COL_6_LONGTEXT LONGTEXT,
CLOB_COL_7_NTEXT NTEXT,
CLOB_COL_8_NCLOB NCLOB,
UUID_COL_1_UUID UUID,
ARRAY_COL_1_ARRAY ARRAY
); | 32.057143 | 70 | 0.83467 |
f05b41f74caaec27151fc5801f63f5f0ab734624 | 2,086 | js | JavaScript | src/ChipWithPopover.js | GCHQDeveloper911/material-multi-picker | a2a15f8818b3368630dddac53269abd804db16d3 | [
"MIT"
] | null | null | null | src/ChipWithPopover.js | GCHQDeveloper911/material-multi-picker | a2a15f8818b3368630dddac53269abd804db16d3 | [
"MIT"
] | null | null | null | src/ChipWithPopover.js | GCHQDeveloper911/material-multi-picker | a2a15f8818b3368630dddac53269abd804db16d3 | [
"MIT"
] | null | null | null | import React, { PureComponent } from "react";
import { Popover, Chip } from "@material-ui/core";
import { func } from "prop-types";
const TOP_MIDDLE = { vertical: "top", horizontal: "center" };
const BOTTOM_MIDDLE = { vertical: "bottom", horizontal: "center" };
class ChipWithPopover extends PureComponent {
constructor(props) {
super(props);
this.state = { targetElement: undefined };
}
handleMouseOver(mouseOverEvent) {
this.setState({ targetElement: mouseOverEvent.currentTarget });
}
closePopover() {
this.setState({ targetElement: undefined });
}
render() {
const { targetElement } = this.state;
const { getPopoverContent, ...chipProps } = this.props;
if ( getPopoverContent ) {
const popoverContent = Boolean(targetElement) && getPopoverContent();
const isOpen = Boolean(popoverContent);
return (
<>
<Chip
onMouseEnter={ mouseOverEvent => this.handleMouseOver(mouseOverEvent) }
onMouseLeave={ () => this.closePopover() }
{ ...chipProps }
aria-owns={ isOpen ? "material-multi-picker-mouse-popover" : undefined }
aria-haspopup="true"
/>
<Popover
id="material-multi-picker-mouse-popover"
style={ { pointerEvents: "none" }}
onClose={ () => this.closePopover() }
anchorOrigin={ TOP_MIDDLE }
transformOrigin={ BOTTOM_MIDDLE }
anchorEl={ targetElement }
open={ isOpen }
disableRestoreFocus
>
{ popoverContent }
</Popover>
</>
);
}
return <Chip {...chipProps} />;
}
}
ChipWithPopover.propTypes = {
getPopoverContent: func
};
export default ChipWithPopover;
| 34.196721 | 96 | 0.50767 |
128d88c636205bc9d37b9990dc05b115ed32da29 | 434 | lua | Lua | lua/gf/utils.lua | chau-bao-long/java-kotlin-gf | e8be1e94c5a552a414ebad17e724d8ef5541ba04 | [
"Apache-2.0"
] | 3 | 2020-05-29T14:09:10.000Z | 2020-06-09T15:57:16.000Z | lua/gf/utils.lua | chau-bao-long/java-kotlin-gf | e8be1e94c5a552a414ebad17e724d8ef5541ba04 | [
"Apache-2.0"
] | null | null | null | lua/gf/utils.lua | chau-bao-long/java-kotlin-gf | e8be1e94c5a552a414ebad17e724d8ef5541ba04 | [
"Apache-2.0"
] | null | null | null | local M = {}
function M.file_exists(name)
local f = io.open(name, "r")
return f ~= nil and io.close(f)
end
function M.esc(x)
return (x:gsub('%%', '%%%%')
:gsub('^%^', '%%^')
:gsub('%$$', '%%$')
:gsub('%(', '%%(')
:gsub('%)', '%%)')
:gsub('%.', '%%.')
:gsub('%[', '%%[')
:gsub('%]', '%%]')
:gsub('%*', '%%*')
:gsub('%+', '%%+')
:gsub('%-', '%%-')
:gsub('%?', '%%?'))
end
return M
| 18.083333 | 34 | 0.343318 |
8cab27cede900697c385551fc11266c14ea4179c | 3,445 | swift | Swift | validation-test/stdlib/StringBreadcrumbs.swift | patmosxx-v2/swift | cbce1608733d7c707699666d114590b1b2f756ad | [
"Apache-2.0"
] | 2 | 2017-04-26T19:33:07.000Z | 2022-03-28T05:43:08.000Z | validation-test/stdlib/StringBreadcrumbs.swift | saeta/swift | 1c91dd4933f805b9b2510c49127db8e437803b55 | [
"Apache-2.0"
] | null | null | null | validation-test/stdlib/StringBreadcrumbs.swift | saeta/swift | 1c91dd4933f805b9b2510c49127db8e437803b55 | [
"Apache-2.0"
] | 1 | 2019-10-31T04:48:41.000Z | 2019-10-31T04:48:41.000Z | // RUN: %target-run-stdlib-swift
// REQUIRES: executable_test
// Some targetted tests for the breadcrumbs path. There is some overlap with
// UTF16View tests for huge strings, but we want a simpler suite that targets
// some corner cases specifically.
import Swift
import StdlibUnittest
let smallASCII = "abcdefg"
let smallUnicode = "abéÏ𓀀"
let largeASCII = "012345678901234567890"
let largeUnicode = "abéÏ012345678901234567890𓀀"
let emoji = "😀😃🤢🤮👩🏿🎤🧛🏻♂️🧛🏻♂️👩👩👦👦"
let chinese = "Swift 是面向 Apple 平台的编程语言,功能强大且直观易用,而本次更新对其进行了全面优化。"
let nonBMP = String(repeating: "𓀀", count: 1 + (64 / 2))
let largeString: String = {
var result = ""
result += smallASCII
result += smallUnicode
result += largeASCII
result += chinese
result += largeUnicode
result += emoji
result += smallASCII
result += result.reversed()
return result
}()
extension FixedWidthInteger {
var hexStr: String { return "0x\(String(self, radix: 16, uppercase: true))" }
}
let StringBreadcrumbsTests = TestSuite("StringBreadcrumbsTests")
func validateBreadcrumbs(_ str: String) {
var utf16CodeUnits = Array(str.utf16)
var outputBuffer = Array<UInt16>(repeating: 0, count: utf16CodeUnits.count)
// Include the endIndex, so we can test end conversions
var utf16Indices = Array(str.utf16.indices) + [str.utf16.endIndex]
for i in 0...utf16CodeUnits.count {
for j in i...utf16CodeUnits.count {
let range = Range(uncheckedBounds: (i, j))
let indexRange = str._toUTF16Indices(range)
// Range<String.Index> <=> Range<Int>
expectEqual(utf16Indices[i], indexRange.lowerBound)
expectEqual(utf16Indices[j], indexRange.upperBound)
expectEqualSequence(
utf16CodeUnits[i..<j], str.utf16[indexRange])
let roundTripOffsets = str._toUTF16Offsets(indexRange)
expectEqualSequence(range, roundTripOffsets)
// Single Int <=> String.Index
expectEqual(indexRange.lowerBound, str._toUTF16Index(i))
expectEqual(indexRange.upperBound, str._toUTF16Index(j))
expectEqual(i, str._toUTF16Offset(indexRange.lowerBound))
expectEqual(j, str._toUTF16Offset(indexRange.upperBound))
// Copy characters
outputBuffer.withUnsafeMutableBufferPointer {
str._copyUTF16CodeUnits(into: $0, range: range)
}
expectEqualSequence(utf16CodeUnits[i..<j], outputBuffer[..<range.count])
}
}
}
StringBreadcrumbsTests.test("uniform strings") {
validateBreadcrumbs(smallASCII)
validateBreadcrumbs(largeASCII)
validateBreadcrumbs(smallUnicode)
validateBreadcrumbs(largeUnicode)
}
StringBreadcrumbsTests.test("largeString") {
validateBreadcrumbs(largeString)
}
// Test various boundary conditions with surrogate pairs aligning or not
// aligning
StringBreadcrumbsTests.test("surrogates-heavy") {
// Mis-align the hieroglyphics by 1,2,3 UTF-8 and UTF-16 code units
validateBreadcrumbs(nonBMP)
validateBreadcrumbs("a" + nonBMP)
validateBreadcrumbs("ab" + nonBMP)
validateBreadcrumbs("abc" + nonBMP)
validateBreadcrumbs("é" + nonBMP)
validateBreadcrumbs("是" + nonBMP)
validateBreadcrumbs("aé" + nonBMP)
}
// Test bread-crumb invalidation
StringBreadcrumbsTests.test("stale breadcrumbs") {
var str = nonBMP + "𓀀"
let oldLen = str.utf16.count
str.removeLast()
expectEqual(oldLen - 2, str.utf16.count)
str += "a"
expectEqual(oldLen - 1, str.utf16.count)
str += "𓀀"
expectEqual(oldLen + 1, str.utf16.count)
}
runAllTests()
| 29.956522 | 79 | 0.722787 |
43b8694b66a7b17db4481a3bb1447c77a4e00c25 | 3,104 | go | Go | handlers/http.go | shuoyenl/floop | 0477a66a373abf1356543a4dd0dcdd2390fd6f24 | [
"Apache-2.0"
] | 2 | 2018-03-26T09:38:28.000Z | 2018-03-26T09:56:38.000Z | handlers/http.go | shuoyenl/floop | 0477a66a373abf1356543a4dd0dcdd2390fd6f24 | [
"Apache-2.0"
] | null | null | null | handlers/http.go | shuoyenl/floop | 0477a66a373abf1356543a4dd0dcdd2390fd6f24 | [
"Apache-2.0"
] | null | null | null | package handlers
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/d3sw/floop/resolver"
"github.com/d3sw/floop/types"
)
var (
errInvalidURI = "invalid uri: %s"
errInvalidMethod = "invalid method: %d"
)
type endpointConfig struct {
//URI string
Method string
//Body string
Headers map[string]string
}
// HTTPClientHandler implements a HTTP client handler for events
type HTTPClientHandler struct {
conf *endpointConfig
client *http.Client
resolv *resolver.Resolver
}
// NewHTTPClientHandler instantiates a new HTTPClientHandler
func NewHTTPClientHandler(resolver *resolver.Resolver) *HTTPClientHandler {
return &HTTPClientHandler{
client: &http.Client{Timeout: 3 * time.Second},
resolv: resolver,
}
}
// Init initializes the http handler with the its specific config
func (handler *HTTPClientHandler) Init(conf *types.HandlerConfig) error {
config := conf.Options
handler.conf = &endpointConfig{
//URI: config["uri"].(string),
//URI: conf.URI,
Method: config["method"].(string),
Headers: make(map[string]string),
}
//if _, ok := config["body"]; ok {
//handler.conf.Body = config["body"].(string)
//handler.conf.Body = string(conf.Body)
//}
if hdrs, ok := config["headers"]; ok {
hm, ok := hdrs.(map[interface{}]interface{})
if !ok {
return fmt.Errorf("invalid header data type %#v", config["headers"])
}
for k, v := range hm {
key := k.(string)
value := v.(string)
handler.conf.Headers[key] = value
}
}
return nil
}
// Handle handles an event by making an http call per the config. Event is the raw event and
// HandlerConfig is the normalized config after interpolations have been applied.
func (handler *HTTPClientHandler) Handle(event *types.Event, conf *types.HandlerConfig) (map[string]interface{}, error) {
resp, err := handler.httpDo(conf)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, fmt.Errorf(resp.Status)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
if err == io.EOF {
return nil, nil
}
return nil, err
}
defer resp.Body.Close()
var r map[string]interface{}
if err = json.Unmarshal(b, &r); err != nil {
return nil, err
}
return r, nil
}
func (handler *HTTPClientHandler) httpDo(conf *types.HandlerConfig) (*http.Response, error) {
buff := bytes.NewBuffer([]byte(conf.Body))
discoveredURI, err := handler.resolv.Discover(conf.URI)
if err != nil {
log.Printf("[ERROR] Discovering URI [%s]: %s\n", conf.URI, err.Error())
log.Println("[DEBUG] Will be used system DNS server")
} else {
conf.URI = discoveredURI
}
req, err := http.NewRequest(handler.conf.Method, conf.URI, buff)
if err == nil {
if handler.conf.Headers != nil {
for k, v := range handler.conf.Headers {
req.Header.Set(k, v)
}
}
log.Printf("[DEBUG] handler=http uri='%s' body='%s'", conf.URI, conf.Body)
return handler.client.Do(req)
}
return nil, err
}
// CloseConnection - not implemented
func (handler *HTTPClientHandler) CloseConnection() error {
//not implemented
return nil
}
| 22.823529 | 121 | 0.679124 |
e1f839acbe9622797a0a6b683dd7b25da334697c | 369 | asm | Assembly | oeis/106/A106043.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/106/A106043.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/106/A106043.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A106043: First digit other than 9 in the fractional part of the decimal expansion of (1/1000^n)^(1/1000^n).
; 0,3,8,7,7,6,5,5,4,3,3,2,1,1,0,8,8,8,8,8,8,8,8,8,8,8,8,8,8,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,6,6,6,6,6,6,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4
mul $0,62298
lpb $0
mov $2,$0
div $0,10
mod $2,10
add $0,$2
lpe
mov $0,$2
| 30.75 | 175 | 0.571816 |
ccfa36b98a99d714e7b02775dd6d509e3180293c | 12,922 | ps1 | PowerShell | source/Classes/003.AzDevOpsDscResourceBase.ps1 | kilasuit/AzureDevOpsDsc | 5cd23a05bbf64c2e91ee1f535bda25d799939465 | [
"MIT"
] | 1 | 2020-07-05T15:07:27.000Z | 2020-07-05T15:07:27.000Z | source/Classes/003.AzDevOpsDscResourceBase.ps1 | johlju/AzureDevOpsDsc | f1d8097305621a8915eb51c31a25451389144330 | [
"MIT"
] | 30 | 2020-07-05T08:33:51.000Z | 2022-02-23T16:49:07.000Z | source/Classes/003.AzDevOpsDscResourceBase.ps1 | johlju/AzureDevOpsDsc | f1d8097305621a8915eb51c31a25451389144330 | [
"MIT"
] | 6 | 2020-07-05T08:49:52.000Z | 2022-01-07T03:13:04.000Z | <#
.SYNOPSIS
Defines a base class from which other AzureDevOps DSC resources inherit from.
#>
class AzDevOpsDscResourceBase : AzDevOpsApiDscResourceBase
{
[DscProperty()]
[Alias('Uri')]
[System.String]
$ApiUri
[DscProperty()]
[Alias('PersonalAccessToken')]
[System.String]
$Pat
[DscProperty()]
[Ensure]
$Ensure
hidden [Hashtable]GetDscCurrentStateObjectGetParameters()
{
# Setup a default set of parameters to pass into the resource/object's 'Get' method
$getParameters = @{
ApiUri = $this.ApiUri
Pat = $this.Pat
"$($this.GetResourceKeyPropertyName())" = $this.GetResourceKey()
}
# If there is an available 'ResourceId' value, add it to the parameters/hashtable
if (![System.String]::IsNullOrWhiteSpace($this.GetResourceId()))
{
$getParameters."$($this.GetResourceIdPropertyName())" = $this.GetResourceId()
}
return $getParameters
}
hidden [PsObject]GetDscCurrentStateResourceObject([Hashtable]$GetParameters)
{
# Obtain the 'Get' function name for the object, then invoke it
$thisResourceGetFunctionName = $this.GetResourceFunctionName(([RequiredAction]::Get))
return $(& $thisResourceGetFunctionName @GetParameters)
}
hidden [System.Management.Automation.PSObject]GetDscCurrentStateObject()
{
$getParameters = $this.GetDscCurrentStateObjectGetParameters()
$dscCurrentStateResourceObject = $this.GetDscCurrentStateResourceObject($getParameters)
# If no object was returned (i.e it does not exist), create a default/empty object
if ($null -eq $dscCurrentStateResourceObject)
{
return New-Object -TypeName 'System.Management.Automation.PSObject' -Property @{
Ensure = [Ensure]::Absent
}
}
return $dscCurrentStateResourceObject
}
hidden [Hashtable]GetDscCurrentStateProperties()
{
# Obtain 'CurrentStateResourceObject' and pass into overidden function of inheriting class
return $this.GetDscCurrentStateProperties($this.GetDscCurrentStateObject())
}
# This method must be overidden by inheriting class(es)
hidden [Hashtable]GetDscCurrentStateProperties([PSCustomObject]$CurrentResourceObject)
{
# Obtain the type of $this object. Throw an exception if this is being called from the base class method.
$thisType = $this.GetType()
if ($thisType -eq [AzDevOpsDscResourceBase])
{
$errorMessage = "Method 'GetCurrentState()' in '$($thisType.Name)' must be overidden and called by an inheriting class."
New-InvalidOperationException -Message $errorMessage
}
return $null
}
hidden [Hashtable]GetDscDesiredStateProperties()
{
[Hashtable]$dscDesiredStateProperties = @{}
# Obtain all DSC-related properties, and add them and their values to the hashtable output
$this.GetDscResourcePropertyNames() | ForEach-Object {
$dscDesiredStateProperties."$_" = $this."$_"
}
return $dscDesiredStateProperties
}
hidden [RequiredAction]GetDscRequiredAction()
{
[Hashtable]$currentProperties = $this.GetDscCurrentStateProperties()
[Hashtable]$desiredProperties = $this.GetDscDesiredStateProperties()
[System.String[]]$dscPropertyNamesWithNoSetSupport = $this.GetDscResourcePropertyNamesWithNoSetSupport()
[System.String[]]$dscPropertyNamesToCompare = $this.GetDscResourcePropertyNames()
# Update 'Id' property:
# Set $desiredProperties."$IdPropertyName" to $currentProperties."$IdPropertyName" if it's desired
# value is blank/null but it's current/existing value is known (and can be recovered from $currentProperties).
#
# This ensures that alternate keys (typically ResourceIds) not provided in the DSC configuration do not flag differences
[System.String]$IdPropertyName = $this.GetResourceIdPropertyName()
if ([System.String]::IsNullOrWhiteSpace($desiredProperties[$IdPropertyName]) -and
![System.String]::IsNullOrWhiteSpace($currentProperties[$IdPropertyName]))
{
$desiredProperties."$IdPropertyName" = $currentProperties."$IdPropertyName"
}
# Perform logic with 'Ensure' (to determine whether resource should be created or dropped (or updated, if already [Ensure]::Present but property values differ)
$dscRequiredAction = [RequiredAction]::None
switch ($desiredProperties.Ensure)
{
([Ensure]::Present) {
# If not already present, or different to expected/desired - return [RequiredAction]::New (i.e. Resource needs creating)
if ($null -eq $currentProperties -or $($currentProperties.Ensure) -ne [Ensure]::Present)
{
$dscRequiredAction = [RequiredAction]::New
Write-Verbose "DscActionRequired='$dscRequiredAction'"
break
}
# Changes made by DSC to the following properties are unsupported by the resource (other than when creating a [RequiredAction]::New resource)
if ($dscPropertyNamesWithNoSetSupport.Count -gt 0)
{
$dscPropertyNamesWithNoSetSupport | ForEach-Object {
if ($($currentProperties[$_].ToString()) -ne $($desiredProperties[$_].ToString()))
{
$errorMessage = "The '$($this.GetType().Name)', DSC Resource does not support changes for/to the '$_' property."
New-InvalidOperationException -Message $errorMessage
}
}
}
# Compare all properties ('Current' vs 'Desired')
if ($dscPropertyNamesToCompare.Count -gt 0)
{
$dscPropertyNamesToCompare | ForEach-Object {
if ($($currentProperties."$_") -ne $($desiredProperties."$_"))
{
Write-Verbose "DscPropertyValueMismatch='$_'"
$dscRequiredAction = [RequiredAction]::Set
}
}
if ($dscRequiredAction -eq [RequiredAction]::Set)
{
Write-Verbose "DscActionRequired='$dscRequiredAction'"
break
}
}
# Otherwise, no changes to make (i.e. The desired state is already achieved)
return $dscRequiredAction
break
}
([Ensure]::Absent) {
# If currently/already present - return $false (i.e. state is incorrect)
if ($null -ne $currentProperties -and $currentProperties.Ensure -ne [Ensure]::Absent)
{
$dscRequiredAction = [RequiredAction]::Remove
Write-Verbose "DscActionRequired='$dscRequiredAction'"
break
}
# Otherwise, no changes to make (i.e. The desired state is already achieved)
Write-Verbose "DscActionRequired='$dscRequiredAction'"
return $dscRequiredAction
break
}
default {
$errorMessage = "Could not obtain a valid 'Ensure' value within '$($this.GetResourceName())' Test() function. Value was '$($desiredProperties.Ensure)'."
New-InvalidOperationException -Message $errorMessage
}
}
return $dscRequiredAction
}
hidden [Hashtable]GetDesiredStateParameters([Hashtable]$CurrentStateProperties, [Hashtable]$DesiredStateProperties, [RequiredAction]$RequiredAction)
{
[Hashtable]$desiredStateParameters = $DesiredStateProperties
[System.String]$IdPropertyName = $this.GetResourceIdPropertyName()
# If actions required are 'None' or 'Error', return a $null value
if ($RequiredAction -in @([RequiredAction]::None, [RequiredAction]::Error))
{
return $null
}
# If the desired state/action is to remove the resource, generate/return a minimal set of parameters required to remove the resource
elseif ($RequiredAction -eq [RequiredAction]::Remove)
{
return @{
ApiUri = $DesiredStateProperties.ApiUri
Pat = $DesiredStateProperties.Pat
Force = $true
# Set this from the 'Current' state as we would expect this to have an existing key/ID value to use
"$IdPropertyName" = $CurrentStateProperties."$IdPropertyName"
}
}
# If the desired state/action is to add/new or update/set the resource, start with the values in the $DesiredStateProperties variable, and amend
elseif ($RequiredAction -in @([RequiredAction]::New, [RequiredAction]::Set))
{
# Set $desiredParameters."$IdPropertyName" to $CurrentStateProperties."$IdPropertyName" if it's known and can be recovered from existing resource
if ([System.String]::IsNullOrWhiteSpace($desiredStateParameters."$IdPropertyName") -and
![System.String]::IsNullOrWhiteSpace($CurrentStateProperties."$IdPropertyName"))
{
$desiredStateParameters."$IdPropertyName" = $CurrentStateProperties."$IdPropertyName"
}
# Alternatively, if $desiredParameters."$IdPropertyName" is null/empty, remove the key (as we don't want to pass an empty/null parameter)
elseif ([System.String]::IsNullOrWhiteSpace($desiredStateParameters."$IdPropertyName"))
{
$desiredStateParameters.Remove($IdPropertyName)
}
# Do not need/want this passing as a parameter (the action taken will determine the desired state)
$desiredStateParameters.Remove('Ensure')
# Add this to 'Force' subsequent function call
$desiredStateParameters.Force = $true
# Some DSC properties are only supported for 'New' and 'Remove' actions, but not 'Set' ones (these need to be removed)
[System.String[]]$unsupportedForSetPropertyNames = $this.GetDscResourcePropertyNamesWithNoSetSupport()
if ($RequiredAction -eq [RequiredAction]::Set -and
$unsupportedForSetPropertyNames.Count -gt 0)
{
$unsupportedForSetPropertyNames | ForEach-Object {
$desiredStateParameters.Remove($_)
}
}
}
else
{
$errorMessage = "A required action of '$RequiredAction' has not been catered for in GetDesiredStateParameters() method."
New-InvalidOperationException -Message $errorMessage
}
return $desiredStateParameters
}
hidden [System.Boolean]TestDesiredState()
{
return ($this.GetDscRequiredAction() -eq [RequiredAction]::None)
}
[System.Boolean] Test()
{
# TestDesiredState() will throw an exception in certain expected circumstances. Return $false if this occurs.
try
{
return $this.TestDesiredState()
}
catch
{
return $false
}
}
[Int32]GetPostSetWaitTimeMs()
{
return 2000
}
[void] SetToDesiredState()
{
[RequiredAction]$dscRequiredAction = $this.GetDscRequiredAction()
if ($dscRequiredAction -in @([RequiredAction]::'New', [RequiredAction]::'Set', [RequiredAction]::'Remove'))
{
$dscCurrentStateProperties = $this.GetDscCurrentStateProperties()
$dscDesiredStateProperties = $this.GetDscDesiredStateProperties()
$dscRequiredActionFunctionName = $this.GetResourceFunctionName($dscRequiredAction)
$dscDesiredStateParameters = $this.GetDesiredStateParameters($dscCurrentStateProperties, $dscDesiredStateProperties, $dscRequiredAction)
& $dscRequiredActionFunctionName @dscDesiredStateParameters | Out-Null
Start-Sleep -Milliseconds $($this.GetPostSetWaitTimeMs())
}
}
[void] Set()
{
$this.SetToDesiredState()
}
}
| 41.022222 | 169 | 0.595651 |
83ebf27cd5f12d7a23756c3f01768b2ec85fa41a | 12,171 | go | Go | db/sql-parser.go | prorochestvo/grest | efebd6011e1cd9920ddc5af4b3516036bcfeb2b6 | [
"MIT"
] | null | null | null | db/sql-parser.go | prorochestvo/grest | efebd6011e1cd9920ddc5af4b3516036bcfeb2b6 | [
"MIT"
] | null | null | null | db/sql-parser.go | prorochestvo/grest | efebd6011e1cd9920ddc5af4b3516036bcfeb2b6 | [
"MIT"
] | null | null | null | package db
import (
"github.com/prorochestvo/grest/internal/helper"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
)
//func SQLSelect(r *http.Request) string {
// result := ""
// return result
//}
var instructions = []string{
"between",
"is_null",
"like",
"cmp_be", ">=",
"cmp_b", ">",
"cmp_l", "<",
"cmp_le", "<=",
"group",
"sort",
"offset",
"limit",
"in",
}
func SQLParserEx(r *http.Request, parsers map[string]func(value string) (interface{}, error), quote func(value string) string) (where []SQLWhere, groupBy []SQLGroupBy, orderBy []SQLOrderBy, having []SQLHaving, limit SQLLimit, offset SQLOffset) {
where, groupBy, orderBy, having, limit, offset = SQLParser(r.URL.Query())
if where != nil && len(where) > 0 {
tmp := make([]SQLWhere, 0)
for _, w := range where {
// check field name
parser, ok := parsers[w.Field()]
if !ok || parser == nil {
continue
}
// check field value
var value interface{} = nil
if text, ok := w.Value().(string); ok {
val, err := parser(text)
if err != nil {
continue
}
value = val
} else if slice, ok := w.Value().([]interface{}); ok && slice != nil && len(slice) > 0 {
val := make([]interface{}, 0)
for _, s := range slice {
if text, ok := s.(string); ok {
v, err := parser(text)
if err != nil {
continue
}
val = append(val, v)
}
}
if l := len(val); len(slice) != l {
continue
}
value = val
} else {
continue
}
// save new instruction
tmp = append(tmp, &sqlWhere{
instruction: w.Instruction(),
field: quote(w.Field()),
separator: w.Separator(),
value: value,
negative: w.Negative(),
})
}
where = tmp
}
if groupBy != nil && len(groupBy) > 0 {
tmp := make([]SQLGroupBy, 0)
for _, g := range groupBy {
// check field name
parser, ok := parsers[g.Field()]
if !ok || parser == nil {
continue
}
// save new instruction
tmp = append(tmp, NewSQLGroupBy(quote(g.Field())))
}
groupBy = tmp
}
if orderBy != nil && len(orderBy) > 0 {
tmp := make([]SQLOrderBy, 0)
for _, o := range orderBy {
// check field name
parser, ok := parsers[o.Field()]
if !ok || parser == nil {
continue
}
// save new instruction
tmp = append(tmp, NewSQLOrderBy(quote(o.Field()), o.Sort()))
}
orderBy = tmp
}
if having != nil && len(having) > 0 {
tmp := make([]SQLHaving, 0)
for _, h := range having {
// check field name
parser, ok := parsers[h.Field()]
if !ok || parser == nil {
continue
}
// check field value
var value interface{} = nil
if text, ok := h.Value().(string); ok {
val, err := parser(text)
if err != nil {
continue
}
value = val
} else if slice, ok := h.Value().([]interface{}); ok && slice != nil && len(slice) > 0 {
val := make([]interface{}, 0)
for _, s := range slice {
if text, ok := s.(string); ok {
v, err := parser(text)
if err != nil {
continue
}
val = append(val, v)
}
}
if len(slice) != len(val) {
continue
}
value = val
} else {
continue
}
// save new instruction
tmp = append(tmp, &sqlHaving{
sqlWhere: sqlWhere{
instruction: h.Instruction(),
field: quote(h.Field()),
separator: h.Separator(),
value: value,
negative: h.Negative(),
},
})
}
having = tmp
}
return where, groupBy, orderBy, having, limit, offset
}
/*
* http://127.0.0.1:8080/user?:test=1&:|arg[]=t1&:|arg[]=t2&0:!|between[FIELD][]=1&0:!|between[FIELD][]=2
*
* SELECT fields
* FROM table
* WHERE
*
* COMMAND // AND
* |COMMAND // OR
* !COMMAND // NOT
* NUM:COMMAND // NUM сордировки
*
* FIELD_NAME=VALUE // field=value
* !FIELD_NAME=VALUE // field<>value
* FIELD_NAME[]=VALUE // field in (value)
* !FIELD_NAME[]=VALUE // NOT(field IN (value))
* :between[FIELD_NAME][]=VALUE // field BETWEEN value:first AND value:last
* :!between[FIELD_NAME][]=VALUE // NOT(field BETWEEN value:first AND value:last)
* :is_null[FIELD_NAME] // IS NULL field
* :!is_null[FIELD_NAME] // IS NOT NULL field
* :like[FIELD_NAME]=VALUE // field LIKE value
* :!like[FIELD_NAME]=VALUE // NOT(field LIKE value)
* :cmp_be[FIELD_NAME]=VALUE // field >= value
* :!cmp_be[FIELD_NAME]=VALUE // NOT(field >= value)
* :cmp_b[FIELD_NAME]=VALUE // field > value
* :!cmp_b[FIELD_NAME]=VALUE // NOT(field > value)
* :cmp_l[FIELD_NAME]=VALUE // field < value
* :!cmp_l[FIELD_NAME]=VALUE // NOT(field < value)
* :cmp_le[FIELD_NAME]=VALUE // field <= value
* :!cmp_le[FIELD_NAME]=VALUE // NOT(field <= value)
* GROUP BY
* :group[FIELD_NAME] // Групперовать по FIELD и включая его в SELECT
* ORDER BY
* :sort[FIELD_NAME]=ASC|DESC
* OFFSET
* :offset=VALUE
* LIMIT
* :limit=VALUE
*/
func SQLParser(query url.Values) (where []SQLWhere, groupBy []SQLGroupBy, orderBy []SQLOrderBy, having []SQLHaving, limit SQLLimit, offset SQLOffset) {
where = make([]SQLWhere, 0)
groupBy = make([]SQLGroupBy, 0)
orderBy = make([]SQLOrderBy, 0)
having = make([]SQLHaving, 0)
limit = nil
offset = nil
// parser url values
rx := regexp.MustCompile(`(?i)^(\d+)*([:!|]*)([0-9A-Za-z<_=->]+)(?:\[(.*)\])*$`)
var index uint64 = 0xFFFFFFFFFFFFFFFF
options := make([]struct {
Number uint64
Separator string
Instruction string
Negative bool
Field string
Value interface{}
}, 0)
for key, val := range query {
var number uint64
var separator string
var negative bool
var instruction string
var field string
var value interface{}
for _, match := range rx.FindAllStringSubmatch(key, -1) {
if len(match) != 5 {
continue
}
if n, err := strconv.ParseUint(match[1], 10, 64); len(match[1]) > 0 && err == nil {
number = n
} else {
index--
number = index
}
separator = "AND"
negative = false
for _, c := range match[2] {
switch c {
case '!':
negative = true
case '|':
separator = "OR"
case ':':
fields := strings.Split(match[4], "][")
if n := strings.ToLower(match[3]); helper.StringsIndexOf(instructions, n) >= 0 {
// :between[FIELD_NAME][]=VALUE
// :!between[FIELD_NAME][]=VALUE
if n == "between" {
if len(val) >= 2 && len(fields) > 0 && len(fields[0]) > 0 {
instruction = n
value = []interface{}{val[0], val[len(val)-1]}
field = fields[0]
}
} else
// :is_null[FIELD_NAME]
// :!is_null[FIELD_NAME]
if n == "is_null" {
if len(val) > 0 && len(fields) > 0 && len(fields[0]) > 0 {
instruction = n
value = val[0]
field = fields[0]
}
} else
// :like[FIELD_NAME]=VALUE
// :!like[FIELD_NAME]=VALUE
if n == "like" {
if len(val) > 0 && len(fields) > 0 && len(fields[0]) > 0 {
instruction = n
value = val[0]
field = fields[0]
}
} else
// :cmp_be[FIELD_NAME]=VALUE
// :!cmp_be[FIELD_NAME]=VALUE
if n == "cmp_be" || n == ">=" {
if len(val) > 0 && len(fields) > 0 && len(fields[0]) > 0 {
instruction = ">="
value = val[0]
field = fields[0]
}
} else
// :cmp_b[FIELD_NAME]=VALUE
// :!cmp_b[FIELD_NAME]=VALUE
if n == "cmp_b" || n == ">" {
if len(val) > 0 && len(fields) > 0 && len(fields[0]) > 0 {
instruction = ">"
value = val[0]
field = fields[0]
}
} else
// :cmp_l[FIELD_NAME]=VALUE
// :!cmp_l[FIELD_NAME]=VALUE
if n == "cmp_l" || n == "<" {
if len(val) > 0 && len(fields) > 0 && len(fields[0]) > 0 {
instruction = "<"
value = val[0]
field = fields[0]
}
} else
// :cmp_le[FIELD_NAME]=VALUE
// :!cmp_le[FIELD_NAME]=VALUE
if n == "cmp_le" || n == "<=" {
if len(val) > 0 && len(fields) > 0 && len(fields[0]) > 0 {
instruction = "<="
value = val[0]
field = fields[0]
}
} else
// :group[FIELD_NAME]
// :group[FIELD_NAME]=VALUE
if n == "group" || n == "group-by" {
if len(val) > 0 && len(fields) > 0 && len(fields[0]) > 0 {
instruction = "group"
field = fields[0]
}
if val != nil && len(val) > 0 {
value = val[0]
}
} else
// :sort[FIELD_NAME]=ASC|DESC
if n == "sort" || n == "order" || n == "order-by" {
if len(val) == 0 {
val = []string{"ASC"}
} else if val[0] != "ASC" && val[0] != "DESC" {
val[0] = "ASC"
}
if len(fields) > 0 && len(fields[0]) > 0 {
instruction = "sort"
value = val[0]
field = fields[0]
}
} else
// :offset=VALUE
if n == "offset" && val != nil && len(val[0]) > 0 {
if v, err := strconv.ParseInt(val[0], 10, 64); err == nil && v >= 0 {
instruction = n
value = v
}
} else
// :limit=VALUE
if n == "limit" && val != nil && len(val[0]) > 0 {
if v, err := strconv.ParseInt(val[0], 10, 64); err == nil && v >= 0 {
instruction = n
value = v
}
} else
// :IN[FIELD_NAME][]=VALUE
// :!IN[FIELD_NAME][]=VALUE
if n == "in" {
if len(val) > 0 && len(fields) > 0 && len(fields[0]) > 0 {
tmp := make([]interface{}, 0)
for _, v := range val {
tmp = append(tmp, v)
}
instruction = n
value = tmp
field = fields[0]
}
}
}
}
}
if strings.Index(match[2], ":") < 0 && val != nil && len(val) > 0 {
field = match[3]
value = val[0]
}
if len(instruction) == 0 && len(field) == 0 {
continue
}
options = append(options, struct {
Number uint64
Separator string
Instruction string
Negative bool
Field string
Value interface{}
}{
Number: number,
Separator: separator,
Instruction: instruction,
Negative: negative,
Field: field,
Value: value,
})
}
}
// sort options
sort.Slice(options, func(i, j int) bool {
return options[i].Number < options[j].Number
})
// parser options
for _, option := range options {
if len(option.Instruction) > 0 && helper.StringsIndexOf(instructions, option.Instruction) >= 0 {
if option.Instruction == "group" {
g := &sqlGroupBy{}
g.field = option.Field
groupBy = append(groupBy, g)
g.field = option.Field
w := &sqlHaving{}
w.instruction = option.Instruction
w.field = option.Field
w.separator = option.Separator
w.value = option.Value
w.negative = option.Negative
having = append(having, w)
} else if option.Instruction == "sort" {
if t, ok := option.Value.(string); ok && len(t) > 0 {
s := &sqlOrderBy{}
s.sort = t
s.field = option.Field
orderBy = append(orderBy, s)
}
} else if option.Instruction == "offset" {
if i, ok := option.Value.(int64); ok && i > 0 {
o := &sqlOffset{}
o.value = i
offset = o
}
} else if option.Instruction == "limit" {
if i, ok := option.Value.(int64); ok && i > 0 {
l := &sqlLimit{}
l.value = i
limit = l
}
} else {
w := &sqlWhere{}
w.instruction = option.Instruction
w.field = option.Field
w.separator = option.Separator
w.value = option.Value
w.negative = option.Negative
where = append(where, w)
}
} else if len(option.Instruction) == 0 && len(option.Field) > 0 && option.Value != nil {
w := &sqlWhere{}
w.field = option.Field
w.separator = option.Separator
w.value = option.Value
w.negative = option.Negative
where = append(where, w)
}
}
return
}
| 27.661364 | 245 | 0.518938 |
7632a63e5367763204fcdc4dae4b0e3764d4bbe1 | 3,215 | go | Go | test/outputgenerator_test/output_generator_test.go | Jungbusch-Softwareschmiede/jungbusch-auditorium | caac4fba9dd3af3c5fad6f8d2d62c1c290253fc2 | [
"MIT"
] | null | null | null | test/outputgenerator_test/output_generator_test.go | Jungbusch-Softwareschmiede/jungbusch-auditorium | caac4fba9dd3af3c5fad6f8d2d62c1c290253fc2 | [
"MIT"
] | null | null | null | test/outputgenerator_test/output_generator_test.go | Jungbusch-Softwareschmiede/jungbusch-auditorium | caac4fba9dd3af3c5fad6f8d2d62c1c290253fc2 | [
"MIT"
] | null | null | null | package outputgenerator_test
import (
"github.com/Jungbusch-Softwareschmiede/jungbusch-auditorium/auditorium/auditconfig/interpreter"
"github.com/Jungbusch-Softwareschmiede/jungbusch-auditorium/auditorium/modulecontroller"
"github.com/Jungbusch-Softwareschmiede/jungbusch-auditorium/auditorium/outputgenerator"
. "github.com/Jungbusch-Softwareschmiede/jungbusch-auditorium/models"
"github.com/Jungbusch-Softwareschmiede/jungbusch-auditorium/static"
"github.com/Jungbusch-Softwareschmiede/jungbusch-auditorium/util/logger"
"os"
s "strings"
"testing"
"time"
)
func initVarMap() VariableMap {
varSlice := make(VariableMap)
varSlice["%result%"] = Variable{Name: "%result%", IsEnv: true}
varSlice["%passed%"] = Variable{Name: "%passed%", IsEnv: true}
varSlice["%unsuccessful%"] = Variable{Name: "%unsuccessful%", IsEnv: true}
varSlice["%os%"] = Variable{Name: "%os%", Value: static.OperatingSystem, IsEnv: true}
varSlice["%currentmodule%"] = Variable{Name: "%currentmodule%", IsEnv: true}
return varSlice
}
func TestGenerateReport(t *testing.T) {
gopath := os.Getenv("gopath") + `\src\github.com\Jungbusch-Softwareschmiede\jungbusch-auditorium\`
if err := logger.InitializeLogger(&ConfigStruct{}, []LogMsg{}); err != nil {
t.Errorf(err.Error())
}
e := AuditModule{
ModuleName: "ExecuteCommand",
StepID: "Hostname",
Passed: "true",
Variables: initVarMap(),
ModuleParameters: ParameterMap{"command": "hostname"},
}
u := AuditModule{
ModuleName: "FileContent",
StepID: "Film-Inhalt3",
Passed: "%result% === 'Porco Rosso'",
Variables: initVarMap(),
ModuleParameters: ParameterMap{"file": "test"},
}
n := AuditModule{
ModuleName: "FileContent",
StepID: "Film-Inhalt2",
Passed: "false",
Variables: initVarMap(),
ModuleParameters: ParameterMap{"file": gopath + "test\\testdata\\filme.txt", "grep": "Porco"},
NestedModules: []AuditModule{u},
}
p := AuditModule{
ModuleName: "FileContent",
StepID: "Film-Inhalt1",
Passed: "%result% === 'Porco Rosso'",
Variables: initVarMap(),
ModuleParameters: ParameterMap{"file": gopath + "test\\testdata\\filme.txt", "grep": "Porco"},
NestedModules: []AuditModule{n},
}
a := AuditModule{
ModuleName: "Script",
StepID: "TestScript",
Passed: "true",
Variables: initVarMap(),
ModuleParameters: ParameterMap{
"script": `function runModule() {
params.file = "` + s.ReplaceAll(gopath, "\\", "\\\\") + `test\\testdata\\filme.txt";
params.grep = "Rosso";
r = FileContent(params);
if (r.result == 'Porco Rosso') {
params.command = "ipconfig";
params.grep = ""
r = ExecuteCommand(params);
}
return r;
}
runModule();
`,
},
}
static.OperatingSystem, _ = modulecontroller.GetOS()
ms := []AuditModule{p, e, a}
r, err := interpreter.InterpretAudit(ms, 5, true)
if err != nil {
t.Error(err)
} else {
if err = outputgenerator.GenerateOutput(r, gopath+"ProgrammOutput/testoutput", 5, false, time.Now(), time.Since(time.Now())); err != nil {
t.Errorf(err.Error())
}
}
_ = os.RemoveAll(gopath + "ProgrammOutput/testoutput")
t.Log("Success")
}
| 31.519608 | 140 | 0.66563 |
9a6b2a0b8f6eb39b88fd00e7ab3d308255c35f7c | 294 | sql | SQL | docker/sql/users.sql | rchavarria/driftphp-homework | f6d60ec19ed70d1272a7371609cc4daacdcac0bb | [
"MIT"
] | null | null | null | docker/sql/users.sql | rchavarria/driftphp-homework | f6d60ec19ed70d1272a7371609cc4daacdcac0bb | [
"MIT"
] | null | null | null | docker/sql/users.sql | rchavarria/driftphp-homework | f6d60ec19ed70d1272a7371609cc4daacdcac0bb | [
"MIT"
] | null | null | null | --
-- Create database and table for Users
--
create database usersdb;
use usersdb;
create table users
(
uid varchar(64) default '' not null primary key,
name varchar(255) not null
);
-- initial users
insert into users (uid, name)
values ('plnctn', 'Plancton, el origen');
| 17.294118 | 53 | 0.666667 |
03956e219cbe560bec5807cbdd3335ee3c9342e4 | 9,912 | kt | Kotlin | android/beagle/src/test/java/br/com/zup/beagle/android/data/serializer/serializerDataFactory.kt | BizarreNULL/beagle | e1b0a87f9d1fd8c0c123aac7d5fb98b0bfdb7d2c | [
"Apache-2.0"
] | null | null | null | android/beagle/src/test/java/br/com/zup/beagle/android/data/serializer/serializerDataFactory.kt | BizarreNULL/beagle | e1b0a87f9d1fd8c0c123aac7d5fb98b0bfdb7d2c | [
"Apache-2.0"
] | null | null | null | android/beagle/src/test/java/br/com/zup/beagle/android/data/serializer/serializerDataFactory.kt | BizarreNULL/beagle | e1b0a87f9d1fd8c0c123aac7d5fb98b0bfdb7d2c | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA
*
* 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 br.com.zup.beagle.android.data.serializer
import br.com.zup.beagle.android.testutil.RandomData
fun makeUnitValueJson() = """
{
"value": 100.0,
"type": "PERCENT"
}
"""
fun makeFlexJson() = """
{
"direction": "LTR",
"flexWrap": "NO_WRAP",
"justifyContent": "FLEX_START",
"alignItems": "STRETCH",
"alignSelf": "AUTO",
"alignContent": "FLEX_START",
"basis": ${makeUnitValueJson()},
"grow": 1.0,
"shrink": 1
}
"""
fun makeScreenJson() = """
{
"_beagleComponent_": "beagle:screenComponent",
"navigationBar": {
"title": "${RandomData.string()}",
"showBackButton": true
},
"child": ${makeContainerJson()}
}
"""
fun makeContainerJson() = """
{
"_beagleComponent_": "beagle:container",
"flex": ${makeFlexJson()},
"children": [${makeButtonJson()}, ${makeButtonJson()}]
}
"""
fun makeButtonJson() = """
{
"_beagleComponent_": "beagle:button",
"text": "Test"
}
"""
fun makeTextJson() = """
{
"_beagleComponent_": "beagle:text",
"text": "Test"
}
"""
fun makeImageJson() = """
{
"_beagleComponent_" : "beagle:image",
"path" : {
"_beagleImagePath_" : "local",
"mobileId" : "imageBeagle"
}
}
"""
fun makeNetworkImageJson() = """
{
"_beagleComponent_" : "beagle:image",
"path" : {
"_beagleImagePath_" : "remote",
"url": "http://test.com/test.png"
}
}
"""
fun makeListViewJson() = """
{
"_beagleComponent_": "beagle:listView",
"context": {
"id": "context",
"value": {
"categories": [
"stub 1",
"stub 2",
"stub 3"
]
}
},
"dataSource": "@{context.categories}",
"iteratorName": "category",
"template": {
"_beagleComponent_": "beagle:text",
"text": "@{category}"
}
}
"""
fun makeTabViewJson() = """
{
"_beagleComponent_": "beagle:tabView",
"children":[${makeTabItemJson()},${makeTabItemJson()},${makeTabItemJson()}]
}
"""
fun makeTabItemJson() = """
{
"title": "Tab 1",
"child": ${makeButtonJson()}
}
"""
fun makeCustomJson() = """
{
"arrayList": [
{
"names": [
"text"
]
}
],
"pair": {
"first": {
"names": [
"text"
]
},
"second": "second"
},
"charSequence": "text",
"charArray": "text",
"personInterface": {
"names": [
"text"
]
},
"_beagleComponent_": "custom:customWidget"
}
"""
fun makeLazyComponentJson() = """
{
"_beagleComponent_": "beagle:lazyComponent",
"path": "${RandomData.httpUrl()}",
"initialState": ${makeButtonJson()}
}
"""
fun makeScrollViewJson() = """
{
"_beagleComponent_": "beagle:scrollView",
"children": [
{
"_beagleComponent_": "beagle:container",
"flex": {
"flexDirection": "ROW"
},
"children": [
${makeTextJson()},
${makeTextJson()},
${makeTextJson()},
${makeTextJson()},
${makeTextJson()},
${makeTextJson()}
]
}
],
"scrollDirection": "HORIZONTAL"
}
"""
fun makePageViewJson() = """
{
"_beagleComponent_": "beagle:pageView",
"children": [
${makeButtonJson()},
${makeButtonJson()},
${makeButtonJson()}
]
}
"""
fun makePageIndicatorJson() = """
{
"_beagleComponent_": "beagle:pageIndicator",
"selectedColor": "#FFFFFF",
"unselectedColor": "#888888"
}
"""
fun makeNavigationActionJson() = """
{
"_beagleAction_": "beagle:pushView",
"route": {
"url": "${RandomData.httpUrl()}",
"shouldPrefetch": true
}
}
"""
fun makeNavigationActionJsonWithExpression() = """
{
"_beagleAction_": "beagle:pushView",
"route": {
"url": "@{test}",
"shouldPrefetch": false
}
}
"""
fun makeNavigationActionJsonWithUrlHardcoded() = """
{
"_beagleAction_": "beagle:pushView",
"route": {
"url": "http://localhost:8080/test/example",
"shouldPrefetch": false
}
}
"""
fun makeAlertActionJson() = """
{
"_beagleAction_": "beagle:alert",
"title": "${RandomData.string()}",
"message": "${RandomData.string()}",
"labelOk": "Ok",
"onPressOk": {
"_beagleAction_": "beagle:alert",
"title": "${RandomData.string()}",
"message": "${RandomData.string()}",
"labelOk": "Ok"
}
}
"""
fun makeConfirmActionJson() = """
{
"_beagleAction_": "beagle:confirm",
"title": "${RandomData.string()}",
"message": "${RandomData.string()}",
"labelOk": "Ok",
"onPressOk": {
"_beagleAction_": "beagle:alert",
"title": "${RandomData.string()}",
"message": "${RandomData.string()}",
"labelOk": "Ok"
},
"labelCancel": "Cancel",
"onPressCancel": {
"_beagleAction_": "beagle:alert",
"title": "${RandomData.string()}",
"message": "${RandomData.string()}",
"labelOk": "Ok"
}
}
"""
fun makeConditionalActionJson() = """
{
"_beagleAction_":"beagle:condition",
"condition":"@{sum(user, 21)}",
"onTrue":[
{
"_beagleAction_":"beagle:alert",
"title":"",
"message":"onTrue"
}
],
"onFalse":[
{
"_beagleAction_":"beagle:alert",
"title":"",
"message":"onFalse"
}
]
}
"""
fun makeAddChildrenJson() = """
{
"_beagleAction_":"beagle:addChildren",
"componentId":"",
"value":[
{
"_beagleComponent_":"beagle:text",
"text":"Ola"
}
],
"mode":"APPEND"
}
"""
fun makeFormLocalActionJson() = """
{
"_beagleAction_": "beagle:formLocalAction",
"name": "${RandomData.string()}",
"data": {}
}
"""
fun makeCustomAndroidActionJson() = """
{
"_beagleAction_": "custom:customandroidaction",
"value": "${RandomData.string()}",
"intValue": ${RandomData.int()}
}
"""
fun makeFormValidationJson() = """
{
"_beagleAction_": "beagle:formValidation",
"errors": []
}
"""
fun makeCustomInputWidgetJson() = """
{
"_beagleComponent_": "custom:customInputWidget"
}
"""
fun makeFormInputJson() = """
{
"_beagleComponent_": "beagle:formInput",
"name": "${RandomData.string()}",
"child": ${makeCustomInputWidgetJson()}
}
"""
fun makeFormSubmitJson() = """
{
"_beagleComponent_": "beagle:formSubmit",
"child": ${makeButtonJson()}
}
"""
fun makeFormJson() = """
{
"_beagleComponent_": "beagle:form",
"action": {
"_beagleAction_": "beagle:formRemoteAction",
"path": "${RandomData.string()}",
"method": "POST"
},
"child": ${makeButtonJson()}
}
"""
fun makeUndefinedComponentJson() = """
{
"_beagleComponent_": "custom:new"
}
"""
fun makeUndefinedActionJson() = """
{
"_beagleAction_": "custom:new"
}
"""
fun makeInternalObject() = """{"value1": "hello", "value2": 123}"""
fun makeBindComponent() = """
{
"_beagleComponent_": "custom:componentbinding",
"value1": null,
"value2": "Hello",
"value3": true,
"value4": ${makeInternalObject()},
"value5": {"test1":"a","test2":"b"},
"value6": ["test1", "test2"]
}
"""
fun makeBindComponentExpression() = """
{
"_beagleComponent_": "custom:componentbinding",
"value1": "@{intExpression}",
"value2": "Hello @{context.name}",
"value3": "@{booleanExpression}",
"value4": "@{objectExpression}",
"value5": "@{mapExpression}",
"value6": "@{listExpression}"
}
"""
fun makeContextWithJsonObject() = """
{
"id": "contextId",
"value": {
"a": true,
"b": "a"
}
}
"""
fun makeContextWithJsonArray() = """
{
"id": "contextId",
"value": [
{
"a": true,
"b": "a"
}
]
}
"""
fun makeContextWithPrimitive() = """
{
"id": "contextId",
"value": true
}
"""
fun makeContextWithNumber(number: Number) = """
{
"id": "contextId",
"value": $number
}
""" | 22.578588 | 79 | 0.475585 |
dc09e31490cc94606b01c53b7cb11dab4c2f38ce | 1,012 | py | Python | payment/migrations/0001_initial.py | Nezale/Cloud_Warehouse_Project | 505dd073862b9f2e49ae76eea255dc7a38175f79 | [
"MIT"
] | 2 | 2018-12-05T00:17:35.000Z | 2018-12-05T00:17:41.000Z | payment/migrations/0001_initial.py | Nezale/Cloud_Warehouse_Project | 505dd073862b9f2e49ae76eea255dc7a38175f79 | [
"MIT"
] | 12 | 2019-01-14T22:57:23.000Z | 2022-03-11T23:38:37.000Z | payment/migrations/0001_initial.py | Nezale/Cloud_Warehouse_Project | 505dd073862b9f2e49ae76eea255dc7a38175f79 | [
"MIT"
] | 3 | 2019-01-24T11:32:09.000Z | 2019-08-26T11:30:31.000Z | # Generated by Django 2.1.4 on 2019-01-23 15:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('payment_method', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Payment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('paymentAmount', models.DecimalField(decimal_places=2, max_digits=5)),
('paymentDate', models.DateTimeField(auto_now_add=True)),
('creditCardMember', models.CharField(max_length=50)),
('creditCardEXPCode', models.CharField(max_length=7)),
('cardHoldersName', models.CharField(max_length=30)),
('paymentMethod', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='payment_method.PaymentMethod')),
],
),
]
| 34.896552 | 133 | 0.621542 |
9c22561b07a7107112198fbcf7e19bbc4234d960 | 896 | js | JavaScript | src/components/Dialog/Dialog.js | georgemunyoro/nonagon | 9e9491cc759a188c257d5c5380b9452f1fa86814 | [
"MIT"
] | null | null | null | src/components/Dialog/Dialog.js | georgemunyoro/nonagon | 9e9491cc759a188c257d5c5380b9452f1fa86814 | [
"MIT"
] | 5 | 2021-10-30T10:22:07.000Z | 2022-02-19T11:55:54.000Z | src/components/Dialog/Dialog.js | georgemunyoro/nonagon | 9e9491cc759a188c257d5c5380b9452f1fa86814 | [
"MIT"
] | null | null | null | import React from "react";
import { Backdrop, Box, Container, Hidden } from "../index";
import "./Dialog.css";
const Dialog = ({
isOpen = false,
onClose = () => {},
children,
width = "50%",
height = "initial",
containerComponentProps,
hiddenComponentProps,
backdropComponentProps,
dialogMessageContainerProps,
dialogMessageBoxProps,
}) => {
return (
<Container {...containerComponentProps}>
<Hidden hidden={!isOpen} {...hiddenComponentProps}>
<Backdrop
{...backdropComponentProps}
onClickAway={() => {
onClose();
}}
>
<Container {...dialogMessageContainerProps} style={{ width, height }}>
<Box {...dialogMessageBoxProps} elevated>
{children}
</Box>
</Container>
</Backdrop>
</Hidden>
</Container>
);
};
export default Dialog;
| 23.578947 | 80 | 0.575893 |
aeb41288fb17a1cd5ad71720350b37b2d9209012 | 9,651 | swift | Swift | Sabbath School/Read/View/ReadView.swift | perdodi/sabbath-school-ios | 6c56fad6c19db35cf464926d429cb363bdeee1b3 | [
"MIT"
] | null | null | null | Sabbath School/Read/View/ReadView.swift | perdodi/sabbath-school-ios | 6c56fad6c19db35cf464926d429cb363bdeee1b3 | [
"MIT"
] | null | null | null | Sabbath School/Read/View/ReadView.swift | perdodi/sabbath-school-ios | 6c56fad6c19db35cf464926d429cb363bdeee1b3 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2017 Adventech <info@adventech.io>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import AsyncDisplayKit
import SwiftDate
import UIKit
protocol ReadViewOutputProtocol: class {
func didTapCopy()
func didTapShare()
func didTapClearHighlight()
func didTapHighlight(color: String)
func didClickVerse(read: Read, verse: String)
func didScrollView(readCellNode: ReadView, scrollView: UIScrollView)
func didLoadWebView(webView: UIWebView)
func didReceiveHighlights(readHighlights: ReadHighlights)
func didReceiveComment(readComments: ReadComments)
func didReceiveCopy(text: String)
func didReceiveShare(text: String)
func didTapExternalUrl(url: URL)
}
class ReadView: ASCellNode {
weak var delegate: ReadViewOutputProtocol?
let coverNode = ASNetworkImageNode()
let coverOverlayNode = ASDisplayNode()
let coverTitleNode = ASTextNode()
let readDateNode = ASTextNode()
let webNode = ASDisplayNode { Reader() }
var read: Read?
var highlights: ReadHighlights?
var comments: ReadComments?
var initialCoverNodeHeight: CGFloat = 0
var parallaxCoverNodeHeight: CGFloat = 0
var webView: Reader { return webNode.view as! Reader }
init(lessonInfo: LessonInfo, read: Read, highlights: ReadHighlights, comments: ReadComments, delegate: ReadViewOutputProtocol) {
self.delegate = delegate
super.init()
self.read = read
self.highlights = highlights
self.comments = comments
coverNode.url = lessonInfo.lesson.cover
coverNode.placeholderEnabled = true
coverNode.placeholderFadeDuration = 0.6
coverNode.contentMode = .scaleAspectFill
coverNode.clipsToBounds = true
coverOverlayNode.alpha = 0
coverTitleNode.alpha = 1
coverTitleNode.maximumNumberOfLines = 2
coverTitleNode.pointSizeScaleFactors = [0.9, 0.8]
coverTitleNode.attributedText = TextStyles.h1(string: read.title)
readDateNode.alpha = 1
readDateNode.maximumNumberOfLines = 1
readDateNode.attributedText = TextStyles.uppercaseHeader(string: read.date.string(custom: "EEEE, MMMM dd"))
automaticallyManagesSubnodes = true
}
override func layout() {
super.layout()
if self.parallaxCoverNodeHeight >= 0 {
self.coverOverlayNode.alpha = 1 - ((self.parallaxCoverNodeHeight-80) * (1/(self.initialCoverNodeHeight-80)))
if self.parallaxCoverNodeHeight <= self.initialCoverNodeHeight {
self.coverNode.frame.origin.y -= (self.initialCoverNodeHeight - parallaxCoverNodeHeight) / 2
self.coverTitleNode.frame.origin.y -= (self.initialCoverNodeHeight - parallaxCoverNodeHeight) / 1.3
self.coverTitleNode.alpha = self.parallaxCoverNodeHeight * (1/self.initialCoverNodeHeight)
self.readDateNode.frame.origin.y -= (self.initialCoverNodeHeight - parallaxCoverNodeHeight) / 1.3
self.readDateNode.alpha = self.parallaxCoverNodeHeight * (1/self.initialCoverNodeHeight)
} else {
self.coverOverlayNode.frame.size = CGSize(width: coverOverlayNode.calculatedSize.width, height: parallaxCoverNodeHeight)
self.coverNode.frame.size = CGSize(width: coverNode.calculatedSize.width, height: parallaxCoverNodeHeight)
self.coverTitleNode.alpha = 1-((self.parallaxCoverNodeHeight - self.coverTitleNode.frame.origin.y) - 101)/self.coverTitleNode.frame.origin.y*1.6
self.coverTitleNode.frame.origin.y += (parallaxCoverNodeHeight - self.initialCoverNodeHeight)
self.readDateNode.alpha = self.coverTitleNode.alpha
self.readDateNode.frame.origin.y += (parallaxCoverNodeHeight - self.initialCoverNodeHeight)
}
}
}
override func didLoad() {
super.didLoad()
let theme = currentTheme()
coverNode.backgroundColor = theme.navBarColor
coverOverlayNode.backgroundColor = theme.navBarColor
initialCoverNodeHeight = coverNode.calculatedSize.height
webView.backgroundColor = .clear
webView.scrollView.delegate = self
webView.delegate = self
webView.alpha = 0
if #available(iOS 11.0, *) {
webView.scrollView.contentInsetAdjustmentBehavior = .never
}
webView.scrollView.contentInset = UIEdgeInsets(top: initialCoverNodeHeight, left: 0, bottom: 0, right: 0)
webView.readerViewDelegate = self
webView.loadContent(content: read!.content)
}
override func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
coverNode.style.preferredSize = CGSize(width: constrainedSize.max.width, height: constrainedSize.max.height*0.4)
webNode.style.preferredSize = CGSize(width: constrainedSize.max.width, height: constrainedSize.max.height)
coverTitleNode.style.preferredLayoutSize = ASLayoutSizeMake(ASDimensionMake(constrainedSize.max.width-40), ASDimensionMake(.auto, 0))
readDateNode.style.preferredLayoutSize = ASLayoutSizeMake(ASDimensionMake(constrainedSize.max.width-40), ASDimensionMake(.auto, 0))
let titleDateSpec = ASStackLayoutSpec(
direction: .vertical,
spacing: 0,
justifyContent: .end,
alignItems: .center,
children: [readDateNode, coverTitleNode]
)
titleDateSpec.style.preferredLayoutSize = ASLayoutSizeMake(ASDimensionMake(constrainedSize.max.width), ASDimensionMake(constrainedSize.max.height*0.4-20))
let coverNodeOverlaySpec = ASOverlayLayoutSpec(child: coverNode, overlay: ASAbsoluteLayoutSpec(children: [titleDateSpec, coverOverlayNode]))
let layoutSpec = ASAbsoluteLayoutSpec(
sizing: .sizeToFit,
children: [coverNodeOverlaySpec, webNode]
)
return layoutSpec
}
}
extension ReadView: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.delegate?.didScrollView(readCellNode: self, scrollView: scrollView)
self.parallaxCoverNodeHeight = -scrollView.contentOffset.y
self.setNeedsLayout()
}
}
extension ReadView: UIWebViewDelegate {
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
return (webView as! Reader).shouldStartLoad(request: request, navigationType: navigationType)
}
func webViewDidFinishLoad(_ webView: UIWebView) {
(webView as! Reader).contextMenuEnabled = true
if !webView.isLoading {
self.delegate?.didLoadWebView(webView: webView)
}
}
}
extension ReadView: ReaderOutputProtocol {
func ready() {
if self.highlights != nil {
webView.setHighlights((self.highlights?.highlights)!)
}
guard let comments = self.comments?.comments, !comments.isEmpty else { return }
for comment in comments {
webView.setComment(comment)
}
}
func didLoadContent(content: String) {}
func didTapClearHighlight() {
self.delegate?.didTapClearHighlight()
}
func didTapCopy() {
self.delegate?.didTapCopy()
}
func didTapShare() {
self.delegate?.didTapShare()
}
func didTapHighlight(color: String) {
self.delegate?.didTapHighlight(color: color)
}
func didClickVerse(verse: String) {
self.delegate?.didClickVerse(read: self.read!, verse: verse)
}
func didReceiveHighlights(highlights: String) {
self.delegate?.didReceiveHighlights(readHighlights: ReadHighlights(readIndex: (read?.index)!, highlights: highlights))
}
func didReceiveComment(comment: String, elementId: String) {
var found = false
guard let comments = comments?.comments else { return }
for (index, readComment) in comments.enumerated() where readComment.elementId == elementId {
found = true
self.comments?.comments[index].comment = comment
}
if !found {
self.comments?.comments.append(Comment(elementId: elementId, comment: comment))
}
self.delegate?.didReceiveComment(readComments: self.comments!)
}
func didReceiveCopy(text: String) {
self.delegate?.didReceiveCopy(text: text)
}
func didReceiveShare(text: String) {
self.delegate?.didReceiveShare(text: text)
}
func didTapExternalUrl(url: URL) {
self.delegate?.didTapExternalUrl(url: url)
}
}
| 38.604 | 162 | 0.695265 |
ea631c77eb722c66820b070c743a4cd5dd9e0bd0 | 552 | asm | Assembly | Chapter_4/Program 4.2/x86/Program_4.2_MASM.asm | chen150182055/Assembly | e5e76bea438a3752b59775098205a77aa7087110 | [
"MIT"
] | 272 | 2016-12-28T02:24:21.000Z | 2022-03-30T21:05:37.000Z | Chapter_4/Program 4.2/x86/Program_4.2_MASM.asm | chen150182055/Assembly | e5e76bea438a3752b59775098205a77aa7087110 | [
"MIT"
] | 1 | 2018-04-17T19:47:52.000Z | 2018-04-17T19:47:52.000Z | Chapter_4/Program 4.2/x86/Program_4.2_MASM.asm | chen150182055/Assembly | e5e76bea438a3752b59775098205a77aa7087110 | [
"MIT"
] | 62 | 2017-02-02T14:39:37.000Z | 2022-01-04T09:02:07.000Z | ; Program 4.2
; Multiplication and Division - MASM (32-bit)
; Copyright (c) 2017 Hall & Slonka
.386
.MODEL FLAT, stdcall
.STACK 4096
ExitProcess PROTO, dwExitCode:DWORD
.data
mval DWORD 664751
dval DWORD 8
.code
_main PROC
; MUL 1-op
mov eax, mval
mov ebx, 8
mul ebx
; IMUL 1-op
mov eax, mval
mov ebx, 8
imul ebx
; IMUL 2-op
mov eax, 8
imul eax, mval
; IMUL 3-op
imul eax, mval, 8
; DIV 1-op
mov edx, 0
mov eax, 5318008
mov ecx, dval
div ecx
; IDIV 1-op
mov edx, 0
mov eax, 5318008
mov ecx, dval
idiv ecx
INVOKE ExitProcess, 0
_main ENDP
END
| 11.265306 | 45 | 0.702899 |
0be4f6082ce5383431a1aa70d5e37fef310a8c77 | 536 | js | JavaScript | src/index.js | classmatewu/toy-webpack-hmr | b2020b293cd0ad83d35845c271cd13f2973bbcbe | [
"MIT"
] | 4 | 2021-10-31T14:21:32.000Z | 2021-12-09T16:04:31.000Z | src/index.js | classmatewu/toy-webpack-hmr | b2020b293cd0ad83d35845c271cd13f2973bbcbe | [
"MIT"
] | null | null | null | src/index.js | classmatewu/toy-webpack-hmr | b2020b293cd0ad83d35845c271cd13f2973bbcbe | [
"MIT"
] | null | null | null | const content1 = require('./content1')
const content2 = require('./content2')
// 输入框
const inputDom = document.createElement('input')
document.body.appendChild(inputDom)
// div1
const div1Dom = document.createElement('div')
document.body.appendChild(div1Dom)
const setDiv1DomInnerHTML = () => {
div1Dom.innerHTML = content1
}
setDiv1DomInnerHTML()
// div2
const div2Dom = document.createElement('div')
document.body.appendChild(div2Dom)
const setDiv2DomInnerHTML = () => {
div2Dom.innerHTML = content2
}
setDiv2DomInnerHTML() | 20.615385 | 48 | 0.751866 |
045b95ef7494abe5d2d71997f2ac1b841869094c | 2,171 | java | Java | test/mireka/transmission/immediate/UpstreamTest.java | pablomelo/mireka | 8001494df592e6f5ff692410b98f1dfbaf1518a7 | [
"Apache-2.0"
] | 39 | 2015-03-31T00:09:30.000Z | 2021-11-01T10:15:35.000Z | test/mireka/transmission/immediate/UpstreamTest.java | pablomelo/mireka | 8001494df592e6f5ff692410b98f1dfbaf1518a7 | [
"Apache-2.0"
] | 2 | 2016-02-21T08:05:02.000Z | 2018-03-21T10:58:57.000Z | test/mireka/transmission/immediate/UpstreamTest.java | pablomelo/mireka | 8001494df592e6f5ff692410b98f1dfbaf1518a7 | [
"Apache-2.0"
] | 18 | 2015-04-02T20:06:31.000Z | 2021-11-01T10:15:38.000Z | package mireka.transmission.immediate;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.List;
import mireka.smtp.client.BackendServer;
import org.junit.Test;
public class UpstreamTest {
private BackendServer server66 = new BackendServer();
private BackendServer server33 = new BackendServer();
private BackendServer backupServer66 = new BackendServer();
private BackendServer backupServer33 = new BackendServer();
public UpstreamTest() {
server66.setWeight(66);
server66.setHost("server66");
server33.setWeight(33);
server33.setHost("server33");
backupServer66.setWeight(66);
backupServer66.setBackup(true);
backupServer66.setHost("backup66");
backupServer33.setWeight(33);
backupServer33.setBackup(true);
backupServer33.setHost("backup33");
}
@Test
public void testOrderedServerList() {
testList(server66, server33, backupServer66, backupServer33);
testList(backupServer33, server33, backupServer66, server66);
}
private void testList(BackendServer... server) {
Upstream upstream = new Upstream();
upstream.setServers(Arrays.asList(server));
int[] counters = new int[4];
for (int i = 0; i < 1000; i++) {
List<BackendServer> list = upstream.orderedServerList();
System.out.println(list);
if (list.get(0) == server66)
counters[0]++;
if (list.get(1) == server33)
counters[1]++;
if (list.get(2) == backupServer66)
counters[2]++;
if (list.get(3) == backupServer33)
counters[3]++;
assertTrue(list.get(2) == backupServer66
|| list.get(3) == backupServer66);
assertTrue(list.get(2) == backupServer33
|| list.get(3) == backupServer33);
}
assertTrue(counters[0] > 600);
assertTrue(counters[1] > 600);
assertTrue(counters[2] > 600);
assertTrue(counters[3] > 600);
System.out.println(Arrays.toString(counters));
}
}
| 32.893939 | 69 | 0.6117 |
a17878099cabaf3d92dc0a903be4194caba2029c | 332 | go | Go | pkg/mock/deployment.go | Meetic/blackbeard | 540a46789704f828a2d1a8b0ea46f1cb051202dc | [
"Apache-2.0"
] | 27 | 2018-01-10T12:55:26.000Z | 2021-08-30T15:42:32.000Z | pkg/mock/deployment.go | Meetic/blackbeard | 540a46789704f828a2d1a8b0ea46f1cb051202dc | [
"Apache-2.0"
] | 63 | 2017-12-05T09:51:28.000Z | 2021-01-27T17:05:57.000Z | pkg/mock/deployment.go | Meetic/blackbeard | 540a46789704f828a2d1a8b0ea46f1cb051202dc | [
"Apache-2.0"
] | 2 | 2018-09-06T16:09:04.000Z | 2018-12-06T14:59:04.000Z | package mock
import (
"github.com/stretchr/testify/mock"
"github.com/Meetic/blackbeard/pkg/resource"
)
type DeploymentRepository struct {
mock.Mock
}
func (m *DeploymentRepository) List(namespace string) (resource.Deployments, error) {
args := m.Called(namespace)
return args.Get(0).(resource.Deployments), args.Error(1)
}
| 19.529412 | 85 | 0.753012 |
90e8e040bbdfbbcacec9bcc13ff915c618c92313 | 133 | py | Python | stages/apps.py | mohamedba01/RH_SOlution_-StagePFE | 0638b889f4fb75e714a470d18907720fa37b2d14 | [
"Unlicense"
] | null | null | null | stages/apps.py | mohamedba01/RH_SOlution_-StagePFE | 0638b889f4fb75e714a470d18907720fa37b2d14 | [
"Unlicense"
] | null | null | null | stages/apps.py | mohamedba01/RH_SOlution_-StagePFE | 0638b889f4fb75e714a470d18907720fa37b2d14 | [
"Unlicense"
] | null | null | null | from django.apps import AppConfig
class StagesConfig(AppConfig):
name = 'stages'
verbose_name = 'Pratique professionnelle'
| 19 | 45 | 0.75188 |
ebc118c36be60570da3d57a721bd5c9fc6366a36 | 16,975 | lua | Lua | kong/plugins/keystone/fernet.lua | lenaaxenova/keystone_plugin | 912498905dae39da3a687ae95d5d13a436bf05c3 | [
"Apache-2.0"
] | 2 | 2018-12-11T02:48:56.000Z | 2019-04-15T07:53:36.000Z | kong/plugins/keystone/fernet.lua | ispras/keystone_plugin | 912498905dae39da3a687ae95d5d13a436bf05c3 | [
"Apache-2.0"
] | null | null | null | kong/plugins/keystone/fernet.lua | ispras/keystone_plugin | 912498905dae39da3a687ae95d5d13a436bf05c3 | [
"Apache-2.0"
] | 3 | 2017-10-27T07:03:36.000Z | 2018-04-27T13:07:41.000Z | local responses = require "kong.tools.responses"
local struct = require "struct"
local os = require "os"
local urandom = require 'randbytes'
local kutils = require ("kong.plugins.keystone.utils")
local msgpack = require "MessagePack"
local methods_represent = {oauth1 = 1, password = 2, token = 3}
local uuid_default = '00000000-0000-0000-0000-000000000000'
local function touuid(str)
str = str:gsub('.', function (c)
return string.format('%02x', string.byte(c))
end)
local uuids = {}
for i = 1, #str, 32 do
uuids[#uuids + 1] = str(i, i+7)..'-'..str(i+8, i+11)..'-'..str(i+12, i+15)..'-'..str(i+16, i+19)..'-'..str(i+20, i+31)
if uuids[#uuids] == uuid_default then
uuids[#uuids] = 'default'
end
end
return uuids
end
local function from_uuid_to_bytes(uuid)
if uuid == 'default' then
uuid = '00000000-0000-0000-0000-000000000000'
end
local format = '(..)(..)(..)(..)-(..)(..)-(..)(..)-(..)(..)-(..)(..)(..)(..)(..)(..)'
local temp = { uuid:match(format) }
local str = ''
for _, v in ipairs(temp) do
str = str..string.char(tonumber(v, 16))
end
return str
end
local function methods_to_int(methods)
local result = 0
for i = 1, #methods do
result = result + methods_represent[methods[i]]
end
return result
end
local function int_to_methods(int_methods)
local methods = {}
local j = 1
for i = #methods_represent, 1 do
if int_methods - i >= 0 then
methods[j] = methods_represent[i]
j = j + 1
end
end
return methods
end
local function random_urlsafe_str_to_bytes(str)
return ngx.decode_base64(str .. '==')
end
local function base64_encode(raw_payload)
local token_str = ngx.encode_base64(raw_payload)
token_str = token_str:gsub("+", "-"):gsub("/", "_")
token_str = ngx.unescape_uri(token_str)
return token_str
end
local function from_hex_to_bytes(hex_str)
local len = string.len(hex_str)
if len < 16 then
hex_str = string.rep('0', 16-len)..hex_str
end
local byte_str = ''
for i = 1, #hex_str, 2 do
byte_str = byte_str..string.char(tonumber(hex_str(i, i+1), 16))
end
return byte_str
end
local function from_number_to_bytes(num)
local hex_str = string.format('%02X', num)
return from_hex_to_bytes(hex_str)
end
--Keystone fernet token is the base64 encoding of a collection of the following fields:
--Version: Fixed versioning by keystone:
--Unscoped Payload : 0
--Domain Scoped Payload : 1
--Project Scoped Payload : 2
--Trust Scoped Payload : 3
--Federated:
--Unscoped Payload : 4
--Domain Scoped Payload : 6
--Project Scoped Payload : 5
--User ID: Byte representation of User ID, uuid.UUID(user_id).bytes
--Methods: Integer representation of list of methods, a unique integer is assigned to each method,
-- for example, 1 to oauth1, 2 to password, 3 to token, etc. Now the sum of list of methods in the token generation
-- request is calculated, for example, for “methods”: [“password”], result is 2. For “methods”: [“password”, “token”],
-- result is 2 + 3 = 5.
--Project ID: Byte representation of Project ID, uuid.UUID(project_id).bytes
--Expiration Time: Timestamp integer of expiration time in UTC
--Audit IDs: Byte representation of URL-Safe string, restoring padding (==) at the end of the string
local UnscopedPayload = {}
UnscopedPayload.version = 0
UnscopedPayload.create_arguments_apply = function (kwargs)
return true
end
UnscopedPayload.assemble = function (user_id, methods, project_id, domain_id, expires_at, --expires_at must be a number
audit_ids, trust_id, federated_info, access_token_id)
local b_user_id = from_uuid_to_bytes(user_id)
local int_methods = methods_to_int(methods)
local b_audit_ids = {}
for i = 1, #audit_ids do
b_audit_ids[i] = random_urlsafe_str_to_bytes(audit_ids[i])
end
return b_user_id, int_methods, expires_at, b_audit_ids
end
UnscopedPayload.disassemble = function (payload)
local user_id = touuid(payload[1])[1]
local methods = int_to_methods(payload[2])
local expires_at_str = payload[3]
local audit_ids = {}
for i = 1, #payload[4] do
audit_ids[i] = base64_encode(payload[4][i])
end
local project_id = nil
local domain_id = nil
local trust_id = nil
local federated_info = nil
local access_token_id = nil
return user_id, methods, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_info, access_token_id
end
local DomainScopedPayload = {}
DomainScopedPayload.version = 1
DomainScopedPayload.create_arguments_apply = function (kwargs)
return kwargs.domain_id
end
DomainScopedPayload.assemble = function (user_id, methods, project_id, domain_id, expires_at, --expires_at must be a number
audit_ids, trust_id, federated_info, access_token_id)
local b_user_id = from_uuid_to_bytes(user_id)
local int_methods = methods_to_int(methods)
local b_domain_id = from_uuid_to_bytes(domain_id)
local b_audit_ids = {}
for i = 1, #audit_ids do
b_audit_ids[i] = random_urlsafe_str_to_bytes(audit_ids[i])
end
return b_user_id, int_methods, b_domain_id, expires_at, b_audit_ids
end
DomainScopedPayload.disassemble = function (payload)
local user_id = touuid(payload[1])[1]
local methods = int_to_methods(payload[2])
local domain_id = touuid(payload[3])[1]
local expires_at_str = payload[4]
local audit_ids = {}
for i = 1, #payload[5] do
audit_ids[i] = base64_encode(payload[5][i])
end
local project_id = nil
local trust_id = nil
local federated_info = nil
local access_token_id = nil
return user_id, methods, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_info, access_token_id
end
local ProjectScopedPayload = {}
ProjectScopedPayload.version = 2
ProjectScopedPayload.create_arguments_apply = function (kwargs)
return kwargs.project_id
end
ProjectScopedPayload.assemble = function (user_id, methods, project_id, domain_id, expires_at, --expires_at must be a number
audit_ids, trust_id, federated_info, access_token_id)
local b_user_id = from_uuid_to_bytes(user_id)
local int_methods = methods_to_int(methods)
local b_project_id = from_uuid_to_bytes(project_id)
local b_audit_ids = {}
for i = 1, #audit_ids do
b_audit_ids[i] = random_urlsafe_str_to_bytes(audit_ids[i])
end
return b_user_id, int_methods, b_project_id, expires_at, b_audit_ids
end
ProjectScopedPayload.disassemble = function (payload)
local user_id = touuid(payload[1])[1]
local methods = int_to_methods(payload[2])
local project_id = touuid(payload[3])[1]
local expires_at_str = payload[4]
local audit_ids = {}
for i = 1, #payload[5] do
audit_ids[i] = base64_encode(payload[5][i])
end
local domain_id = nil
local trust_id = nil
local federated_info = nil
local access_token_id = nil
return user_id, methods, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_info, access_token_id
end
local TrustScopedPayload = {}
TrustScopedPayload.version = 3
TrustScopedPayload.create_arguments_apply = function (kwargs)
return kwargs.trust_id
end
TrustScopedPayload.assemble = function (user_id, methods, project_id, domain_id, expires_at, --expires_at must be a number
audit_ids, trust_id, federated_info, access_token_id)
local b_user_id = from_uuid_to_bytes(user_id)
local int_methods = methods_to_int(methods)
local b_project_id = from_uuid_to_bytes(domain_id)
local b_trust_id = from_uuid_to_bytes(trust_id)
local b_audit_ids = {}
for i = 1, #audit_ids do
b_audit_ids[i] = random_urlsafe_str_to_bytes(audit_ids[i])
end
return b_user_id, int_methods, b_project_id, expires_at, b_audit_ids, b_trust_id
end
TrustScopedPayload.disassemble = function (payload)
local user_id = touuid(payload[1])[1]
local methods = int_to_methods(payload[2])
local project_id = touuid(payload[3])[1]
local expires_at_str = payload[4]
local audit_ids = {}
for i = 1, #payload[5] do
audit_ids[i] = base64_encode(payload[5][i])
end
local trust_id = touuid(payload[6])[1]
local domain_id = nil
local federated_info = nil
local access_token_id = nil
return user_id, methods, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_info, access_token_id
end
local FederatedUnscopedPayload = {}
FederatedUnscopedPayload.version = 4
FederatedUnscopedPayload.create_arguments_apply = function (kwargs)
return kwargs.federated_info
end
FederatedUnscopedPayload.assemble = function (user_id, methods, project_id, domain_id, expires_at, --expires_at must be a number
audit_ids, trust_id, federated_info, access_token_id)
local b_user_id = from_uuid_to_bytes(user_id)
local int_methods = methods_to_int(methods)
local b_group_ids = {}
for i = 1, #federated_info.group_ids do
b_group_ids[i] = from_uuid_to_bytes(federated_info.group_ids[i].id)
end
local b_idp_id = from_uuid_to_bytes(federated_info.idp_id)
local protocol_id = federated_info.protocol_id
local b_audit_ids = {}
for i = 1, #audit_ids do
b_audit_ids[i] = random_urlsafe_str_to_bytes(audit_ids[i])
end
return b_user_id, int_methods, b_group_ids, b_idp_id, protocol_id, expires_at, b_audit_ids
end
FederatedUnscopedPayload.disassemble = function (payload)
local user_id = touuid(payload[1])[1]
local methods = int_to_methods(payload[2])
local group_ids = {}
for i = 1, #payload[3] do
group_ids[i] = touuid(payload[3][i])[1]
end
local idp_id = touuid(payload[4])[1]
local protocol_id = payload[5]
local expires_at_str = payload[6]
local audit_ids = {}
for i = 1, #payload[7] do
audit_ids[i] = base64_encode(payload[7][i])
end
local federated_info = {group_ids = group_ids, idp_id = idp_id, protocol_id = protocol_id}
local project_id = nil
local trust_id = nil
local domain_id = nil
local access_token_id = nil
return user_id, methods, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_info, access_token_id
end
local FederatedScopedPayload = {}
FederatedScopedPayload.version = nil
FederatedScopedPayload.assemble = function (user_id, methods, project_id, domain_id, expires_at, --expires_at must be a number
audit_ids, trust_id, federated_info, access_token_id)
local b_user_id = from_uuid_to_bytes(user_id)
local int_methods = methods_to_int(methods)
local b_scope_id = from_uuid_to_bytes(project_id or domain_id)
local b_group_ids = {}
for i = 1, #federated_info.group_ids do
b_group_ids[i] = from_uuid_to_bytes(federated_info.group_ids[i].id)
end
local b_idp_id = from_uuid_to_bytes(federated_info.idp_id)
local protocol_id = federated_info.protocol_id
local b_audit_ids = {}
for i = 1, #audit_ids do
b_audit_ids[i] = random_urlsafe_str_to_bytes(audit_ids[i])
end
return b_user_id, int_methods, b_scope_id, b_group_ids, b_idp_id, protocol_id, expires_at, b_audit_ids
end
local FederatedProjectScopedPayload = {}
FederatedProjectScopedPayload.version = 5
FederatedProjectScopedPayload.create_arguments_apply = function (kwargs)
FederatedScopedPayload.version = FederatedProjectScopedPayload.version
return kwargs.project_id and kwargs.federated_info
end
FederatedProjectScopedPayload.assemble = FederatedScopedPayload.assemble
FederatedProjectScopedPayload.disassemble = FederatedScopedPayload.disassemble
local FederatedDomainScopedPayload = {}
FederatedDomainScopedPayload.version = 6
FederatedDomainScopedPayload.create_arguments_apply = function (kwargs)
FederatedScopedPayload.version = FederatedDomainScopedPayload.version
return kwargs.domain_id and kwargs.federated_info
end
FederatedDomainScopedPayload.assemble = FederatedScopedPayload.assemble
FederatedDomainScopedPayload.disassemble = FederatedScopedPayload.disassemble
local OauthScopedPayload = {}
OauthScopedPayload.version = 7
OauthScopedPayload.create_arguments_apply = function (kwargs)
return kwargs.access_token_id
end
FederatedScopedPayload.disassemble = function (payload)
local user_id = touuid(payload[1])[1]
local methods = int_to_methods(payload[2])
local scope_id = touuid(payload[3])[1]
local project_id = nil
local domain_id = nil
if FederatedScopedPayload.version == FederatedProjectScopedPayload.version then
project_id = scope_id
elseif FederatedScopedPayload.version == FederatedDomainScopedPayload.version then
domain_id = scope_id
end
local group_ids = {}
for i = 1, #payload[4] do
group_ids[i] = touuid(payload[4][i])[1]
end
local idp_id = touuid(payload[5])[1]
local protocol_id = payload[6]
local expires_at_str = payload[7]
local audit_ids = {}
for i = 1, #payload[8] do
audit_ids[i] = base64_encode(payload[8][i])
end
local federated_info = {group_ids = group_ids, idp_id = idp_id, protocol_id = protocol_id}
local trust_id = nil
local access_token_id = nil
return user_id, methods, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_info, access_token_id
end
OauthScopedPayload.assemble = function (user_id, methods, project_id, domain_id, expires_at, --expires_at must be a number
audit_ids, trust_id, federated_info, access_token_id)
local b_user_id = from_uuid_to_bytes(user_id)
local int_methods = methods_to_int(methods)
local b_project_id = from_uuid_to_bytes(project_id)
local b_audit_ids = {}
for i = 1, #audit_ids do
b_audit_ids[i] = random_urlsafe_str_to_bytes(audit_ids[i])
end
local b_access_token_id = from_uuid_to_bytes(access_token_id)
return b_user_id, int_methods, b_project_id, b_access_token_id, expires_at, b_audit_ids
end
OauthScopedPayload.disassemble = function (payload)
local user_id = touuid(payload[1])[1]
local methods = int_to_methods(payload[2])
local project_id = touuid(payload[3])[1]
local access_token_id = touuid(payload[4])[1]
local expires_at_str = payload[5]
local audit_ids = {}
for i = 1, #payload[6] do
audit_ids[i] = base64_encode(payload[6][i])
end
local federated_info = nil
local trust_id = nil
local domain_id = nil
return user_id, methods, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_info, access_token_id
end
local PayloadClasses = {
OauthScopedPayload,
TrustScopedPayload,
FederatedProjectScopedPayload,
FederatedDomainScopedPayload,
FederatedUnscopedPayload,
ProjectScopedPayload,
DomainScopedPayload,
UnscopedPayload
}
local function create_payload(info_obj) --user_id, expires_at, audit_ids, methods=None, domain_id=None, project_id=None, trust_id=None, federated_info=None, access_token_id=None
local payload
for i = 1, #PayloadClasses do
if PayloadClasses[i].create_arguments_apply(info_obj) then
payload = {PayloadClasses[i].version, PayloadClasses[i].assemble(info_obj.user_id, info_obj.methods, info_obj.project_id,
info_obj.domain_id, info_obj.expires_at, info_obj.audit_ids, info_obj.trust_id,
info_obj.federated_info, info_obj.access_token_id) }
break
end
end
return msgpack.pack(payload)
end
local function parse_payload(payload)
payload = msgpack.unpack(payload)
local version = payload[1]
local not_versioned_payload = {}
for i = 1, #payload - 1 do
not_versioned_payload[i] = payload[i + 1]
end
local info_obj
for i = 1, #PayloadClasses do
if PayloadClasses[i].version == version then
info_obj = {PayloadClasses[i].disassemble(not_versioned_payload)}
break
end
end
local result_obj = {user_id = info_obj[1], methods = info_obj[2], project_id = info_obj[3],
domain_id = info_obj[4], expires_at = info_obj[5], audit_ids = info_obj[6],
trust_id = info_obj[7], federated_info = info_obj[8], access_token_id = info_obj[9]} --user_id, methods, project_id, domain_id, expires_at_str, audit_ids, trust_id, federated_info, access_token_id
return result_obj
end
return {
create_payload = create_payload,
parse_payload = parse_payload,
touuid = touuid,
from_uuid_to_bytes = from_uuid_to_bytes,
base64_encode = base64_encode,
from_hex_to_bytes = from_hex_to_bytes,
from_number_to_bytes = from_number_to_bytes
} | 36.349036 | 224 | 0.708159 |
79fce73342b067facd92ede7bcd79888bd15b1d9 | 2,376 | ps1 | PowerShell | tests/Unit/Private/Assert-TimeSpan.Tests.ps1 | matthew-dupre/DnsServerDsc | 9ac3399e026e51e0ea4f06fed8c34484dd9a6eb3 | [
"MIT"
] | 37 | 2015-06-24T06:08:45.000Z | 2019-09-26T18:18:33.000Z | tests/Unit/Private/Assert-TimeSpan.Tests.ps1 | matthew-dupre/DnsServerDsc | 9ac3399e026e51e0ea4f06fed8c34484dd9a6eb3 | [
"MIT"
] | 126 | 2019-12-10T17:08:47.000Z | 2021-03-26T19:43:43.000Z | tests/Unit/Private/Assert-TimeSpan.Tests.ps1 | matthew-dupre/DnsServerDsc | 9ac3399e026e51e0ea4f06fed8c34484dd9a6eb3 | [
"MIT"
] | 80 | 2015-04-21T19:38:39.000Z | 2019-09-24T19:49:08.000Z | $ProjectPath = "$PSScriptRoot\..\..\.." | Convert-Path
$ProjectName = (Get-ChildItem $ProjectPath\*\*.psd1 | Where-Object -FilterScript {
($_.Directory.Name -match 'source|src' -or $_.Directory.Name -eq $_.BaseName) -and
$(try
{
Test-ModuleManifest $_.FullName -ErrorAction Stop
}
catch
{
$false
}) }
).BaseName
Import-Module $ProjectName -Force
InModuleScope $ProjectName {
Describe 'Assert-TimeSpan' -Tag 'Private' {
Context 'When asserting a valid time' {
Context 'When passing value with named parameter' {
It 'Should not throw an exception' {
{ Assert-TimeSpan -PropertyName 'MyProperty' -Value '1.00:00:00' } | Should -Not -Throw
}
}
Context 'When passing value in pipeline' {
It 'Should not throw an exception' {
{ '1.00:00:00' | Assert-TimeSpan -PropertyName 'MyProperty' } | Should -Not -Throw
}
}
}
Context 'When asserting a invalid string' {
It 'Should throw the correct error message' {
$mockExpectedErrorMessage = $script:localizedData.PropertyHasWrongFormat -f 'MyProperty', 'a.00:00:00'
{ 'a.00:00:00' | Assert-TimeSpan -PropertyName 'MyProperty' } | Should -Throw $mockExpectedErrorMessage
}
}
Context 'When time is above maximum allowed value' {
It 'Should throw the correct error message' {
$mockExpectedErrorMessage = $script:localizedData.TimeSpanExceedMaximumValue -f 'MyProperty', '1.00:00:00', '00:30:00'
{ '1.00:00:00' | Assert-TimeSpan -PropertyName 'MyProperty' -Maximum '0.00:30:00' } | Should -Throw $mockExpectedErrorMessage
}
}
Context 'When time is below minimum allowed value' {
It 'Should throw the correct error message' {
$mockExpectedErrorMessage = $script:localizedData.TimeSpanBelowMinimumValue -f 'MyProperty', '1.00:00:00', '2.00:00:00'
{ '1.00:00:00' | Assert-TimeSpan -PropertyName 'MyProperty' -Minimum '2.00:00:00' } | Should -Throw $mockExpectedErrorMessage
}
}
}
}
| 41.684211 | 142 | 0.559343 |
133b9cab94d10b93b25cd2acec06eaac55b4a581 | 5,068 | h | C | include/Config.h | avenhaus/ESP32_ROS_Robot_Remote | 07aa878590f95699e0bb7ac7f4bd52368c7a1f6b | [
"BSD-Source-Code"
] | null | null | null | include/Config.h | avenhaus/ESP32_ROS_Robot_Remote | 07aa878590f95699e0bb7ac7f4bd52368c7a1f6b | [
"BSD-Source-Code"
] | null | null | null | include/Config.h | avenhaus/ESP32_ROS_Robot_Remote | 07aa878590f95699e0bb7ac7f4bd52368c7a1f6b | [
"BSD-Source-Code"
] | null | null | null | #ifndef CONFIG_H
#define CONFIG_H
#include <Arduino.h>
/********************************************\
|* Pin Definitions
\********************************************/
/*
https://drive.google.com/file/d/1gbKM7DA7PI7s1-ne_VomcjOrb0bE2TPZ/view
---+------+----+-----+-----+-----------+---------------------------
No.| GPIO | IO | RTC | ADC | Default | Function
---+------+----+-----+-----+-----------+---------------------------
25 | 0* | IO | R11 | 2_1 | Boot | INPUT_CLK
35 | 1 | IO | | | UART0_TXD | USB Programming/Debug
24 | 2* | IO | R12 | 2_2 | | LCD_DC
34 | 3 | IO | | | UART0_RXD | USB Programming/Debug
26 | 4* | IO | R10 | 2_0 | | INPUT_LOAD
29 | 5* | IO | | | SPI0_SS | SD_CS (LED)
14 | 12* | IO | R15 | 2_5 | | LCD_LED
16 | 13 | IO | R14 | 2_4 | | INPUT_IN (or INPUT_CS)
13 | 14 | IO | R16 | 2_6 | | TOUCH_CS
23 | 15* | IO | R13 | 2_3 | | LCD_CS
27 | 16+ | IO | | | UART2_RXD |
28 | 17+ | IO | | | UART2_TXD |
30 | 18 | IO | | | SPI0_SCK | SCK LCD,Touch,SD
31 | 19 | IO | | | SPI0_MISO | MISO Touch, SD
33 | 21 | IO | | | I2C0_SDA | Buzzer
36 | 22 | IO | | | I2C0_SCL |
37 | 23 | IO | | | SPI0_MOSI | MOSI LCD, SD
10 | 25 | IO | R06 | 2_8 |DAC1/I2S-DT| Battery
11 | 26 | IO | R07 | 2_9 |DAC2/I2S-WS|
12 | 27 | IO | R17 | 2_7 | I2S-BCK |
8 | 32 | IO | R09 | 1_4 | | Pot_R
9 | 33 | IO | R08 | 1_5 | | R_JOY_Y
6 | 34 | I | R04 | 1_6 | | R_JOY_X
7 | 35 | I | R05 | 1_7 | | Pot_L
4 | 36 | I | R00 | 1_0 | SENSOR_VP | L_JOY_Y
5 | 39 | I | R03 | 1_3 | SENSOR_VN | L_JOY_X
3 | EN | I | | | RESET | Reset LCD
---+------+----+-----+-----+-----------+---------------------------
(IO6 to IO11 are used by the internal FLASH and are not useable)
22 x I/O + 4 x input only = 26 usable pins
GPIO_34 - GPIO_39 have no internal pullup / pulldown.
- ADC2 can not be used with WIFI/BT (easily)
+ GPIO 16 and 17 are not available on WROVER (PSRAM)
* Strapping pins: IO0, IO2, IO4, IO5 (HIGH), IO12 (LOW), IO15 (HIGH)
*/
#define LCD_SCK_PIN 18
#define LCD_MOSI_PIN 23
#define LCD_MISO_PIN 19
#define LCD_RST_PIN -1
#define LCD_DC_PIN 2
#define LCD_CS_PIN 15
#define LCD_LED_PIN 12
#define LCD_LED_PWM_CHANNEL 0
#define TOUCH_CS_PIN 14
#define TOUCH_CS_IRQ -1
#define SD_CS_PIN 5
#define LED_PIN 5
#define BUZZER_PIN 21
#define INPUT_SPI_CHANNEL VSPI
#define INPUT_SPI_SPEED 10000000
#define INPUT_SCK_PIN 0
#define INPUT_LOAD_PIN 4 // 74HC165 HIGH during shifting
#define INPUT_MISO_PIN 13
#define ADC_VREF 1100
#define BATTERY_PIN -1
#define R_POT1_PIN 34
#define L_POT1_PIN 33
#define R_JOY_X_PIN 36
#define R_JOY_Y_PIN 39
#define R_JOY_R_PIN -1
#define L_JOY_X_PIN 35
#define L_JOY_Y_PIN 32
#define L_JOY_R_PIN -1
/* ============================================== *\
* Extended Inputs (from shift registers 74HC165)
\* ============================================== */
#define LEFT_ENCODER1_A_BIT 22
#define LEFT_ENCODER1_B_BIT 23
#define LEFT_ENCODER1_BUTTON_BIT 21
#define RIGHT_ENCODER1_A_BIT 18
#define RIGHT_ENCODER1_B_BIT 19
#define RIGHT_ENCODER1_BUTTON_BIT 20
#define LEFT_BUTTON_JOY_BIT 17
#define LEFT_BUTTON_I1_BIT 28
#define LEFT_BUTTON_I2_BIT 29
#define LEFT_BUTTON_T1_BIT 30
#define LEFT_BUTTON_T2_BIT 31
#define LEFT_BUTTON_SW1_BIT 10
#define LEFT_BUTTON_SW2_BIT 11
#define LEFT_BUTTON_DSW1A_BIT 24
#define LEFT_BUTTON_DSW1B_BIT 25
#define RIGHT_BUTTON_JOY_BIT 16
#define RIGHT_BUTTON_I1_BIT 12
#define RIGHT_BUTTON_I2_BIT 13
#define RIGHT_BUTTON_T1_BIT 14
#define RIGHT_BUTTON_T2_BIT 15
#define RIGHT_BUTTON_SW1_BIT 26
#define RIGHT_BUTTON_SW2_BIT 27
#define RIGHT_BUTTON_DSW1A_BIT 9
#define RIGHT_BUTTON_DSW1B_BIT 8
#define EX_INPUT(BIT) (BIT < 0 ? 0 : (extended_inputs >> BIT) & 1)
/* ============================================== *\
* Constants
\* ============================================== */
#define ENABLE_DISPLAY 1
#define ROS1_HOST "192.168.0.155"
#define ROS1_PORT 11411
typedef enum JoyAxis {
L_JOY_AXIS_X,
L_JOY_AXIS_Y,
L_JOY_AXIS_R,
L_JOY_AXIS_P,
R_JOY_AXIS_X,
R_JOY_AXIS_Y,
R_JOY_AXIS_R,
R_JOY_AXIS_P,
JOY_AXIS_SIZE
} JoyAxis;
extern float joyAxes[JOY_AXIS_SIZE];
typedef enum JoyButton {
L_JOY_BUTTON_JOY,
L_JOY_BUTTON_I1,
L_JOY_BUTTON_I2,
L_JOY_BUTTON_T1,
L_JOY_BUTTON_T2,
L_JOY_BUTTON_SW1,
L_JOY_BUTTON_SW2,
L_JOY_BUTTON_DSW1,
L_JOY_BUTTON_ENC,
L_JOY_BUTTON_ENCB,
R_JOY_BUTTON_JOY,
R_JOY_BUTTON_I1,
R_JOY_BUTTON_I2,
R_JOY_BUTTON_T1,
R_JOY_BUTTON_T2,
R_JOY_BUTTON_SW1,
R_JOY_BUTTON_SW2,
R_JOY_BUTTON_DSW1,
R_JOY_BUTTON_ENC,
R_JOY_BUTTON_ENCB,
JOY_BUTTON_SIZE
} JoyButton;
extern int32_t joyButtons[JOY_BUTTON_SIZE];
#endif
| 29.126437 | 71 | 0.576559 |
0c93992159c77c279e8541bafd3b789955b4b418 | 473 | py | Python | 3/node.py | Pavel3P/Machine-Learning | 441da7de69ebf6cef9ebe54a0b3992918faf1d40 | [
"MIT"
] | null | null | null | 3/node.py | Pavel3P/Machine-Learning | 441da7de69ebf6cef9ebe54a0b3992918faf1d40 | [
"MIT"
] | null | null | null | 3/node.py | Pavel3P/Machine-Learning | 441da7de69ebf6cef9ebe54a0b3992918faf1d40 | [
"MIT"
] | null | null | null | import numpy as np
class Node:
def __init__(self,
gini: float,
num_samples_per_class: np.ndarray,
) -> None:
self.gini: float = gini
self.num_samples_per_class: np.ndarray = num_samples_per_class
self.predicted_class: int = np.argmax(num_samples_per_class)
self.feature_index: int = 0
self.threshold: float = 0
self.left: Node = None
self.right: Node = None
| 26.277778 | 70 | 0.587738 |
169bacf9d121404c4650553fc0f4ae2c6145d9e5 | 1,267 | ts | TypeScript | utils/parseTitle.ts | staddi99/AdventOfCode | a44e6d5288d82543f2e789584eb8a40c0e7ca1d7 | [
"Unlicense"
] | null | null | null | utils/parseTitle.ts | staddi99/AdventOfCode | a44e6d5288d82543f2e789584eb8a40c0e7ca1d7 | [
"Unlicense"
] | null | null | null | utils/parseTitle.ts | staddi99/AdventOfCode | a44e6d5288d82543f2e789584eb8a40c0e7ca1d7 | [
"Unlicense"
] | null | null | null | const axios = require('axios');
const cheerio = require('cheerio');
const args = process.argv.slice(2);
let year = args[0] ? args[0] : 2020;
let day = args[1] ? args[1] : 1;
let only = args[2] ? args[2] : 0;
const getTitle = async (year, day) => {
let postTitle;
try {
const { status, data } = await axios.get(
'https://adventofcode.com/' + year + '/day/' + day
);
if (status === 404) {
return;
}
const $ = cheerio.load(data);
$('body > main > article > h2').each((_idx, el) => {
postTitle = $(el).text().split(': ')[1].split(' -')[0];
});
} catch (error) {
return;
}
if (only == 1) return postTitle;
return '* [❌ Day ' + day + ': ' + postTitle + ']()';
};
const getTitles = async () => {
const titles = [];
if (day != 0 && day != null) {
await getTitle(year, day).then((title) => {
if (title != null) titles.push(title);
});
} else {
for (let i = 1; i <= 25; i++) {
await getTitle(year, i).then((title) => {
if (title != null) {
titles.push(title);
} else {
titles.push('* [❔ Day ' + i + ': TBD]()');
}
});
}
}
return titles;
};
getTitles().then((postTitles) => postTitles.forEach((e) => console.log(e)));
| 23.462963 | 76 | 0.497238 |
e8ef256cd90a45f756f9b6bac7615546b4352096 | 7,475 | py | Python | app/wall_e/models/canvas_api.py | dbwebb-se/umbridge | 76dd1a15f2f481c1fc3819990ab41e20ca65afe3 | [
"MIT"
] | null | null | null | app/wall_e/models/canvas_api.py | dbwebb-se/umbridge | 76dd1a15f2f481c1fc3819990ab41e20ca65afe3 | [
"MIT"
] | 12 | 2021-09-07T12:11:31.000Z | 2022-03-22T10:05:03.000Z | app/wall_e/models/canvas_api.py | dbwebb-se/umbridge | 76dd1a15f2f481c1fc3819990ab41e20ca65afe3 | [
"MIT"
] | null | null | null | """
"""
import os
from flask import current_app
from canvasapi import submission, requester
from app.wall_e.models.requester import Requester
from app.settings import settings
class Canvas(Requester):
"""
Model class for wall_e.fetch
"""
def __init__(self, base_url, api_token, course_id, course_name):
super().__init__(base_url, api_token)
self.course_id = course_id
self._course_name = course_name
self._config = settings.get_course_map()
self.set_assignments_and_users()
def set_assignments_and_users(self):
""" Caches assignments and students in a course """
self.users = self.get_users_in_course()
current_app.logger.debug(f"Course {self._course_name} has the following users: {self.users}")
self.assignments = self.get_assignments()
current_app.logger.debug(f"Course {self._course_name} has the following assignments: {self.assignments}")
def get_users_in_course(self):
"""
Returns users in course by course_id
"""
data = self.request_get_paging(
f"/api/v1/courses/{self.course_id}/users?page={{page}}&per_page=100")
return data
def get_assignments(self):
"""
Return assignments
based on course_id
"""
return self._request_get(
f"/api/v1/courses/{self.course_id}/assignments?per_page=100").json()
def get_course(self):
"""
Return a single course
based on course_id
"""
return self._request_get(f"/api/v1/courses/{self.course_id}").json()
def users_and_acronyms(self):
"""
Returns users in course by course_id
"""
formatted_users = {}
for u in self.users:
try:
formatted_users[u["id"]] = u["login_id"].split("@")[0]
except TypeError:
current_app.logger.error(f"could not extract acronym for user {u}")
return formatted_users
def get_user_by_acronym(self, acronym):
"""
Returns a single user in course
by acronym and course_id
"""
return [
u for u in self.users if "login_id" in u and acronym in u["login_id"]
][0]
def get_assignment_by_name(self, name):
"""
Return a single assignment
based on name
"""
return [a for a in self.assignments if a["name"] == name][0]
def get_assignment_name_by_id(self, assignment_id):
"""
Return a single assignment
based on its id
"""
for assignment in self.assignments:
if assignment["id"] == assignment_id:
name = self._config[self._course_name]['canvas_name_to_assignment'].get(
assignment["name"],
assignment["name"]
)
current_app.logger.debug(f"Found the name {name} for assignment {assignment['name']}")
return name
current_app.logger.error(f"could not find a matching assignment id to {assignment['id']}")
return None
def get_gradeable_submissions(self):
"""
Return gradeable submissions
based on assignment_id
"""
# submitted = all assignments that has not been graded on canvas
submissions = self.request_get_paging(
f"/api/v1/courses/{self.course_id}/students/submissions?page={{page}}&per_page=100", payload={
"student_ids": ["all"],
"workflow_state": ["submitted"],
}
)
current_app.logger.info(f"Course {self._course_name} has {len(submissions)} submissions")
current_app.logger.debug(f"Course {self._course_name} has the following submissions: {submissions}")
try:
ignore = self._config[self._course_name]['ignore_assignments']
except KeyError:
ignore = self._config['default']['ignore_assignments']
if ignore:
submissions = [
s for s in submissions if self.get_assignment_name_by_id(s['assignment_id']) not in ignore
]
return submissions
class Grader(Requester):
"""
Model class for wall_e.grade
"""
def __init__(self, base_url, api_token):
super().__init__(base_url, api_token)
def grade_submission(self, sub, url):
"""
Grade submission
"""
passed_comment = "Testerna har passerat. En rättare kommer läsa din redovisningstext, kolla på koden och sätta betyg."
failed_comment = "Tyvärr gick något fel i testerna. Läs igenom loggfilen för att se vad som gick fel. Lös felet och gör en ny inlämning."
error_comment = "Något gick fel i umbridge, kontakta kursansvarig."
respons = self.send_zip_archive(sub)
if respons is not None:
if sub.grade.lower() == "pg":
feedback = passed_comment
elif sub.grade.lower() == "ux":
feedback = failed_comment
else:
feedback = error_comment
id_ = respons["id"]
uuid = respons["uuid"]
feedback_text = (
"Automatiska rättningssystemet 'Umbridge' har gått igenom din inlämning.\n\n"
f"{feedback}\n\n"
f"Loggfilen för alla tester kan du se via följande länk: {url}/results/feedback/{sub.uuid}-{sub.id}\n\n"
f"Du kan inspektera filerna som användes vid rättning via följande länk: {url}/results/inspect/{id_}/{uuid}\n\n"
"Kontakta en av de kursansvariga om resultatet är felaktigt."
)
else:
feedback_text = (
"Automatiska rättningssystemet 'Umbridge' har gått igenom din inlämning.\n\n"
f"Umbridge kunde inte hitta filerna efter rättningen, försök göra en ny inlämning. Om det inte hjälper, kontakta kursansvarig.\n\n"
f"Loggfilen för alla tester kan du se via följande länk: {url}/results/feedback/{sub.uuid}-{sub.id}\n\n"
)
payload = {
"comment": {
"text_comment": feedback_text,
},
"submission": {
"posted_grade": sub.grade
}
}
current_app.logger.debug(f"Set grade {sub.grade} for {sub.user_acronym} in assignment {sub.assignment_id}")
self._request_put(
f"/api/v1/courses/{sub.course_id}/assignments/{sub.assignment_id}/submissions/{sub.user_id}",
payload=payload)
def send_zip_archive(self, sub):
"""
Sends archive as a comment
"""
file_name = sub.zip_file_path
r = requester.Requester(self._url, self._key)
s = submission.Submission(
r, attributes={
"course_id": sub.course_id,
"assignment_id": sub.assignment_id,
"user_id": sub.user_id
})
current_app.logger.debug(f"Sending zip as comment to {sub.user_acronym} in assignment {sub.assignment_id}")
try:
respons = s.upload_comment(file_name)
except IOError:
current_app.logger.error(f"File {file_name} is missing, can't upload file for {sub.user_acronym} in {sub.assignment_name}.")
sub.grade = "U"
return None
current_app.logger.debug(f"zip respons: {respons}")
os.remove(file_name)
return respons[1]
| 34.447005 | 147 | 0.597458 |
4a2a1a8072ddc682f0648e0ee2b2660f462c8c1d | 6,091 | js | JavaScript | assets/angular/ng-movies.js | octopuscart/mticketmanage | 6882bbcc208fbf3d78dd68f0b058937ccc840730 | [
"MIT"
] | null | null | null | assets/angular/ng-movies.js | octopuscart/mticketmanage | 6882bbcc208fbf3d78dd68f0b058937ccc840730 | [
"MIT"
] | null | null | null | assets/angular/ng-movies.js | octopuscart/mticketmanage | 6882bbcc208fbf3d78dd68f0b058937ccc840730 | [
"MIT"
] | null | null | null |
Admin.controller('theaterController', function ($scope, $http, $timeout, $interval, $filter) {
$scope.theaterLayout = {"layout": {}, "suggetion": [], "wheelchair": {}};
var url = rootBaseUrl + "Api/" + layoutgbl;
$http.get(url).then(function (rdata) {
$scope.theaterLayout.layout = rdata.data;
$scope.theaterLayout.wheelchair = rdata.data.wheelchair;
$timeout(function () {
for (wc in $scope.theaterLayout.wheelchair) {
$("#" + wc).addClass("wheelchairseat");
}
}, 1000);
}, function () {
})
$scope.seatSelection = {"selected": {}, "total": 0, "reserved": ""};
$scope.selectSeat = function (seatobj, price) {
console.log(seatobj, price);
var seatlist = Object.keys($scope.seatSelection.selected);
if ($scope.seatSelection.selected[seatobj]) {
delete $scope.seatSelection.selected[seatobj];
} else {
$scope.seatSelection.selected[seatobj] = {'price': price, 'seat': seatobj};
}
const seatarray = [];
for (sit in $scope.seatSelection.selected) {
seatarray.push(sit);
}
$scope.seatSelection.reserved = seatarray.join(", ");
}
$scope.selectRemoveClass = function (seatobj, sclass) {
$(".seaticon").removeClass("suggestion");
}
})
Admin.controller('booknowEventController', function ($scope, $http, $timeout, $interval, $filter) {
$scope.booking = {"no_of_seats": 1, "event_id": ""};
$scope.selectBookingSeats = function (event_id) {
$scope.booking.event_id = event_id;
}
})
Admin.controller('updateEventController', function ($scope, $http, $timeout, $interval, $filter) {
$scope.eventselectionSelection = {"templatelist": {}, "selected_template": "0", "datetimelist": {"100": {"event_time": event_time, "event_date": event_date}}};
var tempdata = {"event_time": event_time, "event_date": event_date};
var url = rootBaseUrl + "Api/getTheaterTemplate/" + theater_id;
$http.get(url).then(function (rdata) {
$scope.eventselectionSelection.templatelist = rdata.data;
}, function () {
});
$scope.addNewDate = function () {
var randomeno = Math.floor((Math.random() * 1000) + 1);
$scope.eventselectionSelection.datetimelist[randomeno] = tempdata;
$timeout(function () {
jQuery('#datepicker' + randomeno).datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
startDate: new Date(),
todayHighlight: true
});
}, 1000);
}
$scope.removeLastDate = function (removeid) {
delete $scope.eventselectionSelection.datetimelist[removeid];
}
})
Admin.controller('sitSelectContoller', function ($scope, $http, $timeout, $interval, $filter) {
$scope.theaterLayout = {"layout": {}, "seatscount": seatsgbl, "suggetion": [], "wheelchair": {}};
var url = rootBaseUrl + "Api/" + layoutgbl + "/1?event_id=" + event_id + "&template_id=" + template_id;
$http.get(url).then(function (rdata) {
$scope.theaterLayout.layout = rdata.data;
$scope.theaterLayout.wheelchair = rdata.data.wheelchair;
$timeout(function () {
for (wc in $scope.theaterLayout.wheelchair) {
console.log(("#" + wc));
$("#" + wc).addClass("wheelchairseat");
}
}, 1000);
}, function () {
})
$scope.seatSelection = {"selected": {}, "total": 0};
$scope.getTotalPrice = function () {
var total = 0;
for (k in $scope.seatSelection.selected) {
var temp = $scope.seatSelection.selected[k].price;
console.log(temp)
total += Number(temp);
}
console.log(total)
$scope.seatSelection.total = total;
var seatlist = Object.keys($scope.seatSelection.selected);
};
$scope.selectSeat = function (seatobj, price) {
swal({
title: 'Choosing Seat(s)',
onOpen: function () {
swal.showLoading()
}
})
var seatlist = Object.keys($scope.seatSelection.selected);
if (seatlist.length == seatsgbl) {
$scope.seatSelection.selected = {};
}
$timeout(function () {
for (st in $scope.theaterLayout.suggetion) {
var sgobj = $scope.theaterLayout.suggetion[st];
if ($scope.seatSelection.selected[sgobj]) {
delete $scope.seatSelection.selected[sgobj];
} else {
$scope.seatSelection.selected[sgobj] = {'price': price, 'seat': sgobj};
}
}
swal.close();
$scope.getTotalPrice();
}, 500)
}
$scope.selectRemoveClass = function (seatobj, sclass) {
$(".seaticon").removeClass("suggestion");
}
$scope.selectSeatSuggest = function (seatobj, sclass) {
var seatcount = Number($scope.theaterLayout.seatscount);
var seatlistselected = Object.keys($scope.seatSelection.selected);
var selectedseatlength = seatlistselected.length;
var seatcount_n = Number(seatsgbl);
var avl_seatno = seatcount_n - selectedseatlength;
if (selectedseatlength == seatcount_n) {
avl_seatno = seatcount_n;
}
$scope.theaterLayout.suggetion = [];
$(".seaticon").removeClass("suggestion");
var prefix = seatobj.split("-")[0];
var listofrow = $scope.theaterLayout.layout.sitclass[sclass].row[prefix];
var count = 0;
var seatlist = Object.keys(listofrow);
var seatindex = seatlist.indexOf(seatobj);
var slimit = (seatindex + avl_seatno);
var suggestion = [];
for (i = seatindex; i < slimit; i++) {
var stobj = seatlist[i];
if (listofrow[stobj] == 'A') {
$scope.theaterLayout.suggetion.push(stobj);
$("#" + stobj).addClass("suggestion");
}
}
}
})
| 34.412429 | 163 | 0.571499 |
3b27cec2befa6572d4a1ba293087ad1983b74297 | 1,968 | swift | Swift | ForecastModuleTests/Presenter/ForecastModulePresenterTests.swift | menabebawy/Weather-For-Three-Days | 2f808464a05d6394a3f446f13991463c26d37b29 | [
"MIT"
] | null | null | null | ForecastModuleTests/Presenter/ForecastModulePresenterTests.swift | menabebawy/Weather-For-Three-Days | 2f808464a05d6394a3f446f13991463c26d37b29 | [
"MIT"
] | null | null | null | ForecastModuleTests/Presenter/ForecastModulePresenterTests.swift | menabebawy/Weather-For-Three-Days | 2f808464a05d6394a3f446f13991463c26d37b29 | [
"MIT"
] | null | null | null | //
// ForecastModulePresenterTests.swift
// ForecastModuleTests
//
// Created by Mena Bebawy on 2/9/20.
// Copyright © 2020 Mena. All rights reserved.
//
import XCTest
import Entities
class ForecastModulePresenterTests: XCTestCase {
let presenter = ForecastModulePresenter()
var interactor: MockInteractor = MockInteractor()
var view: MockView = MockView()
override func setUp() {
super.setUp()
presenter.interactor = interactor
presenter.view = view
}
func testSetTitle() {
XCTAssertFalse(view.isSetTitle)
presenter.viewIsReady()
XCTAssertTrue(view.isSetTitle)
}
func testConfiguredForecastsTableView() {
XCTAssertFalse(view.configuredTableView)
presenter.viewIsReady()
XCTAssertTrue(view.configuredTableView)
}
func testShowAlert() {
XCTAssertFalse(view.showedError)
presenter.fetchedError("error")
XCTAssertTrue(view.showedError)
}
func testFetchingCities() {
presenter.viewIsLoading(cityId: 1)
XCTAssertTrue(interactor.fetchingForecast)
}
class MockInteractor: ForecastModulePresenterToInteractor {
var fetchingForecast = false
func fetchForecast(cityId: String) {
fetchingForecast = true
}
}
class MockView: ForecastModulePresenterToView {
var isSetTitle = false
var configuredTableView = false
var showedError = false
func setTitle() {
isSetTitle = true
}
func configureTableView() {
configuredTableView = true
}
func loadHourlyForecasts(_ forecoasts: [Forecast]) {
}
func loadNextDaysForecasts(_ forecasts: [Forecast]) {
}
func showErrorAlert(withMessage message: String) {
showedError = true
}
}
}
| 24.296296 | 63 | 0.613821 |
9b7a7fdcd1fbad3e58c002fa12626ccaf4d6f16c | 1,849 | kts | Kotlin | data/RF02482/rnartist.kts | fjossinet/Rfam-for-RNArtist | 3016050675602d506a0e308f07d071abf1524b67 | [
"MIT"
] | null | null | null | data/RF02482/rnartist.kts | fjossinet/Rfam-for-RNArtist | 3016050675602d506a0e308f07d071abf1524b67 | [
"MIT"
] | null | null | null | data/RF02482/rnartist.kts | fjossinet/Rfam-for-RNArtist | 3016050675602d506a0e308f07d071abf1524b67 | [
"MIT"
] | null | null | null | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF02482"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
6 to 9
32 to 35
}
value = "#027195"
}
color {
location {
57 to 61
78 to 82
}
value = "#25c28d"
}
color {
location {
63 to 67
72 to 76
}
value = "#1345b9"
}
color {
location {
115 to 121
125 to 131
}
value = "#7aea43"
}
color {
location {
10 to 31
}
value = "#8a6e37"
}
color {
location {
62 to 62
77 to 77
}
value = "#54eaf2"
}
color {
location {
68 to 71
}
value = "#3388f9"
}
color {
location {
122 to 124
}
value = "#d314f6"
}
color {
location {
1 to 5
}
value = "#e22c8e"
}
color {
location {
36 to 56
}
value = "#b93ff3"
}
color {
location {
83 to 114
}
value = "#3714f6"
}
color {
location {
132 to 150
}
value = "#a74972"
}
}
} | 15.408333 | 48 | 0.273121 |
5fa1cb5f3ff403c76eb777e33c74f10e35dd2e50 | 245 | h | C | AnyThinkUnitySDK/Assets/AnyThinkAds/Platform/iOS/Internal/C/ATRewardedVideoWrapper.h | anythinkteam/demo_unity | f9f5d2bac265b7e313662a4bc0a1225073d6f5bb | [
"Apache-2.0"
] | 9 | 2019-11-28T07:26:34.000Z | 2020-09-24T05:15:41.000Z | AnyThinkUnitySDK/Assets/AnyThinkAds/Platform/iOS/Internal/C/ATRewardedVideoWrapper.h | anythinkteam/demo_unity | f9f5d2bac265b7e313662a4bc0a1225073d6f5bb | [
"Apache-2.0"
] | null | null | null | AnyThinkUnitySDK/Assets/AnyThinkAds/Platform/iOS/Internal/C/ATRewardedVideoWrapper.h | anythinkteam/demo_unity | f9f5d2bac265b7e313662a4bc0a1225073d6f5bb | [
"Apache-2.0"
] | 1 | 2020-06-27T05:37:32.000Z | 2020-06-27T05:37:32.000Z | //
// ATRewardedVideoWrapper.h
// UnityContainer
//
// Created by Martin Lau on 08/08/2018.
// Copyright © 2018 Martin Lau. All rights reserved.
//
#import "ATBaseUnityWrapper.h"
@interface ATRewardedVideoWrapper : ATBaseUnityWrapper
@end
| 18.846154 | 54 | 0.738776 |
292399f9c3b97ec85618deebdfd297911dcc17cc | 316 | py | Python | pyamg/krylov/__init__.py | Alexey-Voronin/pyamg-1 | 59d35010e4bd660aae3526e8a206a42cb1a54bfa | [
"MIT"
] | null | null | null | pyamg/krylov/__init__.py | Alexey-Voronin/pyamg-1 | 59d35010e4bd660aae3526e8a206a42cb1a54bfa | [
"MIT"
] | null | null | null | pyamg/krylov/__init__.py | Alexey-Voronin/pyamg-1 | 59d35010e4bd660aae3526e8a206a42cb1a54bfa | [
"MIT"
] | null | null | null | "Krylov Solvers"
from .info import __doc__
from ._gmres import *
from ._fgmres import *
from ._cg import *
from ._cr import *
from ._cgnr import *
from ._cgne import *
from ._bicgstab import *
from ._steepest_descent import *
from ._minimal_residual import *
__all__ = [s for s in dir() if not s.startswith('_')]
| 19.75 | 53 | 0.727848 |
777d6ca62638a67ce4e2bd5ccbb52e1f5ee75b34 | 1,858 | rs | Rust | src/lib.rs | mihirsamdarshi/rust-core-video-sys | a5c566961dd1d4066d9ae2039b2108f38ecc9ca4 | [
"MIT"
] | null | null | null | src/lib.rs | mihirsamdarshi/rust-core-video-sys | a5c566961dd1d4066d9ae2039b2108f38ecc9ca4 | [
"MIT"
] | null | null | null | src/lib.rs | mihirsamdarshi/rust-core-video-sys | a5c566961dd1d4066d9ae2039b2108f38ecc9ca4 | [
"MIT"
] | null | null | null | #![allow(
non_snake_case,
non_camel_case_types,
non_upper_case_globals,
improper_ctypes
)]
#[macro_use]
extern crate cfg_if;
pub use self::base::*;
pub use self::buffer::*;
pub use self::image_buffer::*;
pub use self::open_gl_es_texture::*;
pub use self::open_gl_es_texture_cache::*;
pub use self::pixel_buffer::*;
pub use self::pixel_buffer_pool::*;
pub use self::pixel_format_description::*;
pub use self::return_::*;
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[link(name = "CoreVideo", kind = "framework")]
extern "C" {}
pub(crate) type OSType = u32;
pub(crate) type GLenum = libc::c_uint;
pub(crate) type GLsizei = libc::c_int;
pub(crate) type GLint = libc::c_int;
pub(crate) type GLuint = libc::c_uint;
pub mod base;
pub mod buffer;
pub mod image_buffer;
pub mod pixel_buffer;
pub mod pixel_buffer_pool;
pub mod pixel_format_description;
pub mod return_;
cfg_if! {
if #[cfg(feature = "metal")] {
pub mod metal_texture;
pub mod metal_texture_cache;
pub use self::metal_texture::*;
pub use self::metal_texture_cache::*;
}
}
cfg_if! {
if #[cfg(feature = "display_link")] {
pub mod host_time;
pub mod display_link;
pub use self::host_time::*;
pub use self::display_link::*;
}
}
cfg_if! {
if #[cfg(feature = "opengl")] {
pub mod opengl_buffer;
pub mod opengl_buffer_pool;
pub mod opengl_texture;
pub mod opengl_texture_cache;
pub use self::opengl_buffer::*;
pub use self::opengl_buffer_pool::*;
pub use self::opengl_texture::*;
pub use self::opengl_texture_cache::*;
}
}
cfg_if! {
if #[cfg(feature = "io_suface")] {
pub mod pixel_buffer_io_surface;
pub use self::pixel_buffer_io_surface::*;
}
}
pub mod open_gl_es_texture;
pub mod open_gl_es_texture_cache;
| 22.119048 | 51 | 0.658773 |
968718dfcf3015161c5b6847e51225e4c1e895a1 | 8,720 | php | PHP | app/Controllers/Member/Jawabantryout.php | lutfiarfianto/ci4crud | efb0222695071aec0f86fffd458275e40bcdd79e | [
"MIT"
] | null | null | null | app/Controllers/Member/Jawabantryout.php | lutfiarfianto/ci4crud | efb0222695071aec0f86fffd458275e40bcdd79e | [
"MIT"
] | null | null | null | app/Controllers/Member/Jawabantryout.php | lutfiarfianto/ci4crud | efb0222695071aec0f86fffd458275e40bcdd79e | [
"MIT"
] | null | null | null | <?php
namespace App\Controllers\Member;
use App\Controllers\BaseController;
class Jawabantryout extends BaseController
{
public function __construct()
{
$this->jawabantryoutModel = new \App\Models\JawabantryoutModel();
}
/*
public function session($id)
{
$soal_tryout_id = id_decode($id);
session()->set('soal_tryout_id',$soal_tryout_id);
return redirect()->to('/Member/Soaltryout/');
}
*/
public function filter()
{
$this->index();
}
/*
public function index()
{
// ** if you want to build query manually, refer to CI4 query builder **
// $this->jawabantryoutModel->select('*, sp_jawaban_soal_tryout.id ', FALSE );
$table_filters = (object) ["soal_tryout_id" => null];
foreach ($table_filters as $field => &$value) {
$value = refine_var($this->request->getGet($field));
};
if ($table_filters->soal_tryout_id) {
$this->jawabantryoutModel->where('soal_tryout_id', $table_filters->soal_tryout_id);
};
$this->jawabantryoutModel->orderBy('sp_jawaban_soal_tryout.id desc');
$rows = $this->jawabantryoutModel->paginate(10);
$data = [
'rows' => $rows,
'pager' => $this->jawabantryoutModel->pager,
'breadcrumb' => [
'title' => 'List of Jawaban Tryout',
],
'per_page' => 1000,
'table_filter' => $table_filters,
];
$filter_label = ["soal_tryout_id" => "Soal Tryout Id"];
$filter_info = [];
$table_filters_txt = (object) [];
foreach ($filter_label as $fld => $label) {
if (!$table_filters->$fld) {
continue;
}
$filter_info[$fld] = '<span class="badge badge-primary">' . $label . ' = ' . (isset($table_filters_txt->$fld) ? $table_filters_txt->$fld : $table_filters->$fld) . '</span>';
}
$data['filter_info'] = implode("\n", $filter_info);
echo view('Member/Jawabantryout/Index', $data);
}
public function show($id = null)
{
try {
$jawabantryout = $this->jawabantryoutModel->find($id);
$data = [
'jawabantryout' => $jawabantryout,
'breadcrumb' => [
'title' => 'View Jawaban Tryout',
],
];
echo view('Member/Jawabantryout/Show', $data);
} catch (\Exception $e) {
die($e->getMessage());
}
}
public function edit($id = null)
{
try {
$jawabantryout = null;
if (!$id && old('id')) {
$jawabantryout = $this->jawabantryoutModel->getOld();
} else {
$jawabantryout = $this->jawabantryoutModel->find($id);
}
$data = [
'jawabantryout' => $jawabantryout,
'breadcrumb' => [
'title' => 'Edit Jawaban Tryout',
],
];
if (!$this->validate([])) {
$data['validation'] = $this->validator;
};
echo view('Member/Jawabantryout/Edit', $data);
} catch (\Exception $e) {
die($e->getMessage());
}
}
function new () {
try {
$jawabantryout = new \App\Entities\Jawabantryout();
$data = [
'jawabantryout' => $jawabantryout,
'breadcrumb' => [
'title' => 'New Jawaban Tryout',
],
];
echo view('Member/Jawabantryout/Edit', $data);
} catch (\Exception $e) {
die($e->getMessage());
}
}
*/
public function store()
{
$request = service('request');
// setting rules
$rules = [
// "siswa_id" => "required",
"judul_tryout_id" => "required",
"lembar_tryout_id" => "required",
];
if (!$this->validate($rules)) {
return redirect()->to('/Member/Soaltryout/')->withInput()->with('errors', service('validation')->getErrors());
}
$soaltryoutModel = new \App\Models\SoaltryoutModel();
$jawaban_soal_id = $this->request->getPost('jawaban_soal_id');
$insert_data = [];
$lembar_id = $this->request->getPost('lembar_tryout_id');
$total_skor = 0;
foreach ($jawaban_soal_id as $soal_id => $jawaban) {
$soaltryout = $soaltryoutModel->find($soal_id);
$skor = 0;
if($jawaban == $soaltryout->jawaban_soal_ganda){
$skor = 1;
}
$total_skor += $skor;
$siswa_id = 3;
$insert_data[] = [
'siswa_id' => $siswa_id,
'judul_tryout_id' => session()->get('tryout_id'),
'lembar_tryout_id' => $lembar_id,
'soal_tryout_id' => $soal_id,
'jawaban_pilihan' => $jawaban,
'skor_pilihan' => $skor,
];
}
// insert to db
foreach($insert_data as $k => $data){
$test = $this->jawabantryoutModel->where([
'siswa_id' => $siswa_id,
'judul_tryout_id' => session()->get('tryout_id'),
'lembar_tryout_id' => $lembar_id,
'soal_tryout_id' => $soal_id,
])->get();
if(!$test->getResult()){
$this->jawabantryoutModel->insert($data);
}
}
$lembartryoutModel = new \App\Models\LembartryoutModel();
$lembartryoutModel->where('id',$lembar_id);
if($total_skor>0){
$data = [
'skor_tryout' => $total_skor,
];
$lembartryoutModel->set($data);
$lembartryoutModel->update();
}
return redirect()->to('/Member/Jawabantryout/skor')->with('message', 'success');
}
public function skor()
{
$lembar_id = session()->get('lembar_id');
$tryout_id = session()->get('tryout_id');
$siswa_id = 3;
$table_filters = (object) ["soal" => null];
foreach ($table_filters as $field => &$value) {
$value = refine_var($this->request->getGet($field));
};
$this->jawabantryoutModel->select('*,sp_jawaban_soal_tryout.id');
$this->jawabantryoutModel->join('sp_soal_tryout','sp_soal_tryout.id=sp_jawaban_soal_tryout.soal_tryout_id','left');
if ($table_filters->soal) {
$this->jawabantryoutModel->like('sp_soal_tryout.soal', $table_filters->soal);
};
$this->jawabantryoutModel->where([
'sp_soal_tryout.judul_tryout_id' => $tryout_id,
'sp_jawaban_soal_tryout.lembar_tryout_id' => $lembar_id,
'siswa_id' => $siswa_id,
]);
$this->jawabantryoutModel->orderBy('sp_jawaban_soal_tryout.id desc');
$rows = $this->jawabantryoutModel->findAll();
$tryoutModel = new \App\Models\TryoutModel();
$tryout = $tryoutModel->find( $tryout_id );
$diskusiModel = new \App\Models\DiskusiModel();
$diskusi = $diskusiModel
->select('*,sp_diskusi.id')
->where('tipe_diskusi','tryout')
->where('post_id',$tryout_id)
->join('users','users.id=sp_diskusi.user_id')
->orderBy('sp_diskusi.id','desc')
->findAll();
$data = [
'rows' => $rows,
'pager' => $this->jawabantryoutModel->pager,
'breadcrumb' => [
'title' => 'List of Jawaban Tryout',
],
'table_filter' => $table_filters,
'tryout' => $tryout,
'diskusi' => $diskusi,
'per_page' => 1000,
];
$filter_label = ["soal" => "Soal"];
$filter_info = [];
$table_filters_txt = (object) [];
foreach ($filter_label as $fld => $label) {
// d($label);
if (!$table_filters->$fld) {
continue;
}
$filter_info[$fld] = '<span class="badge badge-primary">' . $label . ' = ' . (isset($table_filters_txt->$fld) ? $table_filters_txt->$fld : $table_filters->$fld) . '</span>';
}
$data['filter_info'] = implode("\n", $filter_info);
echo view('Member/Jawabantryout/Skor', $data);
}
}
/* End of file Jawabantryout.php */
/* Location: ./app/Controllers/Member/Jawabantryout.php */
| 26.107784 | 185 | 0.494954 |
beefcf92978672f26e181cdf204603f0ca58aa3d | 3,554 | lua | Lua | Modules/Network/Protocol.lua | HeladoDeBrownie/Nexus | c0bc3fe34b50bbb429eb73699bfd72dbc42aff2f | [
"MIT"
] | 4 | 2020-06-16T23:49:47.000Z | 2020-12-05T03:54:11.000Z | Modules/Network/Protocol.lua | HeladoDeBrownie/Nexus | c0bc3fe34b50bbb429eb73699bfd72dbc42aff2f | [
"MIT"
] | 114 | 2020-09-15T01:54:26.000Z | 2021-05-18T17:51:25.000Z | Modules/Network/Protocol.lua | HeladoDeBrownie/Nexus | c0bc3fe34b50bbb429eb73699bfd72dbc42aff2f | [
"MIT"
] | 1 | 2020-11-24T19:48:32.000Z | 2020-11-24T19:48:32.000Z | local NetworkProtocol = {}
--# Helpers
--## Renderers
local function render_hello_message(sprite_byte_string)
return ('HELLO %s'):format(sprite_byte_string)
end
local function render_welcome_message(origin)
return ('WELCOME %s'):format(origin)
end
local function render_place_message(x, y)
return ('PLACE %d %d'):format(x, y)
end
local function render_scene_message(data)
return ('SCENE %s'):format(data)
end
local function render_sprite_message(sprite_byte_string)
return ('SPRITE %s'):format(sprite_byte_string)
end
--## Parsers
local function parse_hello_message(message)
local sprite_byte_string = message:match'^HELLO (.*)$'
if sprite_byte_string ~= nil then
return {
type = 'hello',
sprite_byte_string = sprite_byte_string,
}
end
end
local function parse_welcome_message(message)
local origin = message:match'^WELCOME (.*)$'
if origin ~= nil then
return {
type = 'welcome',
origin = origin,
}
end
end
local function parse_place_message(message)
local x, y = message:match'^PLACE (-?%d+) (-?%d+)$'
if x ~= nil then
return {
type = 'place',
x = x,
y = y,
}
end
end
local function parse_scene_message(message)
local scene_data = message:match'^SCENE (.*)$'
if scene_data ~= nil then
return {
type = 'scene',
data = scene_data,
}
end
end
local function parse_sprite_message(message)
local sprite_byte_string = message:match'^SPRITE (.*)$'
if sprite_byte_string ~= nil then
return {
type = 'sprite',
sprite_byte_string = sprite_byte_string,
}
end
end
--# Interface
function NetworkProtocol.render_message(message_table)
local origin_prefix = ''
if message_table.origin ~= nil then
origin_prefix = ('[%s]'):format(tostring(message_table.origin))
end
if message_table.type == 'hello' then
local sprite_byte_string = message_table.sprite_byte_string
return origin_prefix .. render_hello_message(sprite_byte_string)
elseif message_table.type == 'welcome' then
local origin = message_table.origin
return origin_prefix .. render_welcome_message(origin)
elseif message_table.type == 'place' then
local x, y = message_table.x, message_table.y
return origin_prefix .. render_place_message(x, y)
elseif message_table.type == 'scene' then
local data = message_table.data
return origin_prefix .. render_scene_message(data)
elseif message_table.type == 'sprite' then
local sprite_byte_string = message_table.sprite_byte_string
return origin_prefix .. render_sprite_message(sprite_byte_string)
else
error(('could not render message of type %q'):format(tostring(message_table.type)))
end
end
function NetworkProtocol.parse_message(raw_message)
local origin, message = raw_message:match'^%[([^]]*)](.*)$'
if origin == nil then
message = raw_message
end
local message_table =
parse_hello_message(message) or
parse_welcome_message(message) or
parse_place_message(message) or
parse_scene_message(message) or
parse_sprite_message(message)
if message_table == nil then
error(('could not parse message %q'):format(raw_message))
else
message_table.origin = origin
return message_table
end
end
--#
return NetworkProtocol
| 25.568345 | 91 | 0.658413 |
56d5a9e61ca016f989b065ea375c99d05bc5645a | 2,853 | go | Go | device/gpio/relay/relay.go | disaster37/go-arest | e3d25729875d7c4990f257049d5f3c3393d044e1 | [
"MIT"
] | null | null | null | device/gpio/relay/relay.go | disaster37/go-arest | e3d25729875d7c4990f257049d5f3c3393d044e1 | [
"MIT"
] | null | null | null | device/gpio/relay/relay.go | disaster37/go-arest | e3d25729875d7c4990f257049d5f3c3393d044e1 | [
"MIT"
] | null | null | null | package relay
import (
"github.com/disaster37/go-arest"
)
// Relay represent relay device
type Relay interface {
// On enable the relay output
On() (err error)
// Off disable the relay output
Off() (err error)
// State return the current relay state
State() (state State)
// OutputState return the current output state
OutputState() (state State)
// Reset permit to reconfigure relay. It usefull when board reboot
Reset() (err error)
}
// RelayImp implement the relay interface
type RelayImp struct {
pin int
client arest.Arest
signal arest.Level
output Output
state State
outputState State
}
// NewRelay return new relay object
func NewRelay(c arest.Arest, pin int, signal arest.Level, output Output, defaultState State) (relay Relay, err error) {
relay = &RelayImp{
client: c,
pin: pin,
signal: signal,
output: output,
state: NewState(),
outputState: defaultState,
}
err = relay.Reset()
return relay, err
}
// On enable the relay output
func (r *RelayImp) On() (err error) {
level := arest.NewLevel()
state := NewState()
if r.output.IsNO() {
if r.signal.IsHigh() {
level.SetLevelHigh()
state.SetStateOn()
} else {
level.SetLevelLow()
state.SetStateOff()
}
} else {
if r.signal.IsHigh() {
level.SetLevelLow()
state.SetStateOff()
} else {
level.SetLevelHigh()
state.SetStateOn()
}
}
err = r.client.DigitalWrite(r.pin, level)
if err != nil {
return err
}
r.outputState.SetStateOn()
if state.IsOn() {
r.state.SetStateOn()
} else {
r.state.SetStateOff()
}
return nil
}
// Off disable the relay output
func (r *RelayImp) Off() (err error) {
level := arest.NewLevel()
state := NewState()
if r.output.IsNO() {
if r.signal.IsHigh() {
level.SetLevelLow()
state.SetStateOff()
} else {
level.SetLevelHigh()
state.SetStateOn()
}
} else {
if r.signal.IsHigh() {
level.SetLevelHigh()
state.SetStateOn()
} else {
level.SetLevelLow()
state.SetStateOff()
}
}
err = r.client.DigitalWrite(r.pin, level)
if err != nil {
return err
}
r.outputState.SetStateOff()
if state.IsOn() {
r.state.SetStateOn()
} else {
r.state.SetStateOff()
}
return nil
}
// State return the current relay state
func (r *RelayImp) State() State {
return r.state
}
// OutputState return the current output state
func (r *RelayImp) OutputState() State {
return r.outputState
}
// Reset permit to reconfigure relay. It usefull when board reboot
// It apply the desired state
func (r *RelayImp) Reset() (err error) {
mode := arest.NewMode()
mode.SetModeOutput()
// Set pin mode
err = r.client.SetPinMode(r.pin, mode)
if err != nil {
return err
}
// Set relay on right state
if r.outputState.IsOn() {
err = r.On()
} else {
err = r.Off()
}
return err
}
| 17.503067 | 119 | 0.654048 |
5672365f70a896cb7ba4e2e808ae289505f1406a | 891 | go | Go | vendor/github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/web/parse/function_app_slot.go | suhanime/installer | 9c8baf2f69c50a9d745d86f4784bdd6b426040af | [
"Apache-2.0"
] | 3 | 2021-03-03T17:50:29.000Z | 2022-03-04T16:25:57.000Z | vendor/github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/web/parse/function_app_slot.go | suhanime/installer | 9c8baf2f69c50a9d745d86f4784bdd6b426040af | [
"Apache-2.0"
] | 9 | 2021-03-10T18:24:13.000Z | 2021-05-27T21:58:26.000Z | vendor/github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/web/parse/function_app_slot.go | suhanime/installer | 9c8baf2f69c50a9d745d86f4784bdd6b426040af | [
"Apache-2.0"
] | 3 | 2020-05-28T11:02:15.000Z | 2021-03-16T13:23:04.000Z | package parse
import (
"fmt"
"github.com/terraform-providers/terraform-provider-azurerm/azurerm/helpers/azure"
)
type FunctionAppSlotResourceID struct {
ResourceGroup string
FunctionAppName string
Name string
}
func FunctionAppSlotID(input string) (*FunctionAppSlotResourceID, error) {
id, err := azure.ParseAzureResourceID(input)
if err != nil {
return nil, fmt.Errorf("[ERROR] Unable to parse App Service Slot ID %q: %+v", input, err)
}
slot := FunctionAppSlotResourceID{
ResourceGroup: id.ResourceGroup,
FunctionAppName: id.Path["sites"],
Name: id.Path["slots"],
}
if slot.FunctionAppName, err = id.PopSegment("sites"); err != nil {
return nil, err
}
if slot.Name, err = id.PopSegment("slots"); err != nil {
return nil, err
}
if err := id.ValidateNoEmptySegments(input); err != nil {
return nil, err
}
return &slot, nil
}
| 21.731707 | 91 | 0.689113 |
bfa5bbc413a9d4109af8bd5c41764e29f71a08c5 | 973 | asm | Assembly | data/templates/src/pe/exe/template_x64_windows.asm | OsmanDere/metasploit-framework | b7a014a5d22d3b57157e301d4af57e3a31ad03a9 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 26,932 | 2015-01-01T00:04:51.000Z | 2022-03-31T22:51:38.000Z | data/templates/src/pe/exe/template_x64_windows.asm | Kilo-411/metasploit-framework | aaf27d7fa51390895dea63c58cb3b76e959d36f8 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 11,048 | 2015-01-01T00:05:44.000Z | 2022-03-31T21:49:52.000Z | data/templates/src/pe/exe/template_x64_windows.asm | Kilo-411/metasploit-framework | aaf27d7fa51390895dea63c58cb3b76e959d36f8 | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 12,593 | 2015-01-01T01:01:20.000Z | 2022-03-31T22:13:32.000Z | ; Author: Stephen Fewer (stephen_fewer[at]harmonysecurity[dot]com)
; Architecture: x64
;
; Assemble and link with the following command:
; "C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\x86_amd64\ml64" template_x64_windows.asm /link /subsystem:windows /defaultlib:"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Lib\x64\kernel32.lib" /entry:main
extrn ExitProcess : proc
extrn VirtualAlloc : proc
.code
main proc
sub rsp, 40 ;
mov r9, 40h ;
mov r8, 3000h ;
mov rdx, 4096 ;
xor rcx, rcx ;
call VirtualAlloc ; lpPayload = VirtualAlloc( NULL, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE );
mov rcx, 4096 ;
mov rsi, payload ;
mov rdi, rax ;
rep movsb ; memcpy( lpPayload, payload, 4096 );
call rax ; lpPayload();
xor rcx, rcx ;
call ExitProcess ; ExitProcess( 0 );
main endp
payload proc
A byte 'PAYLOAD:'
B db 4096-8 dup ( 0 )
payload endp
end
| 29.484848 | 214 | 0.655704 |
62ca2ed7f63ab1a58d64de032d246fb309480fa7 | 7,462 | lua | Lua | power_meters/mercury_230/firmware.lua | JDEnapter/marketplace | 2ca307ca785b6a453892d7b248b144755d63aa45 | [
"MIT"
] | null | null | null | power_meters/mercury_230/firmware.lua | JDEnapter/marketplace | 2ca307ca785b6a453892d7b248b144755d63aa45 | [
"MIT"
] | null | null | null | power_meters/mercury_230/firmware.lua | JDEnapter/marketplace | 2ca307ca785b6a453892d7b248b144755d63aa45 | [
"MIT"
] | null | null | null | function main()
local result_comm = rs485.init(9600, 8, 'N', 2)
if result_comm ~= 0 then
enapter.log("RS485 init failed: " .. rs485.err_to_str(result_comm), "error")
end
scheduler.add(30000, properties)
scheduler.add(1000, metrics)
end
function properties()
enapter.send_properties({vendor = "Mercury", model = "230"})
end
function metrics()
local ADDRESS = 0
local TIMEOUT = 1000
local TRANSFORMATION_COEFFICIENT = 120
local telemetry = {}
local alerts = {}
local status = "ok"
local login = {0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01}
read_data(ADDRESS, login, TIMEOUT) -- 00 00 01 B0 - valid response for login
local voltage_l1 = {0x08, 0x11, 0x11}
local voltage_l2 = {0x08, 0x11, 0x12}
local voltage_l3 = {0x08, 0x11, 0x13}
local current_l1 = {0x08, 0x11, 0x21}
local current_l2 = {0x08, 0x11, 0x22}
local current_l3 = {0x08, 0x11, 0x23}
local frequency = {0x08, 0x11, 0x40}
local active_power = {0x08, 0x16, 0x00}
local total_energy = {0x05, 0x00, 0x00}
local total_energy_by_phases = {0x05, 0x60, 0x00}
local ok, err = pcall(function()
local data = read_data(ADDRESS, voltage_l1, TIMEOUT)
local bytes = totable(data)
telemetry["l1n_volt"] = parse_4_bytes(bytes) / 100
end)
if not ok then
enapter.log("Phase 1 voltage reading failed: "..err, "error")
alerts = {"communication_failed"}
status = "read_error"
end
local ok, err = pcall(function()
local data = read_data(ADDRESS, voltage_l2, TIMEOUT)
local bytes = totable(data)
telemetry["l2n_volt"] = parse_4_bytes(bytes) / 100
end)
if not ok then
enapter.log("Phase 2 voltage reading failed: "..err, "error")
alerts = {"communication_failed"}
status = "read_error"
end
local ok, err = pcall(function()
local data = read_data(ADDRESS, voltage_l3, TIMEOUT)
local bytes = totable(data)
telemetry["l3n_volt"] = parse_4_bytes(bytes) / 100
end)
if not ok then
enapter.log("Phase 3 voltage reading failed: "..err, "error")
alerts = {"communication_failed"}
status = "read_error"
end
local ok, err = pcall(function()
local data = read_data(ADDRESS, current_l1, TIMEOUT)
local bytes = totable(data)
telemetry["current_l1"] = parse_4_bytes(bytes) / 1000 * TRANSFORMATION_COEFFICIENT
end)
if not ok then
enapter.log("Phase 1 current reading failed: "..err, "error")
alerts = {"communication_failed"}
status = "read_error"
end
local ok, err = pcall(function()
local data = read_data(ADDRESS, current_l2, TIMEOUT)
local bytes = totable(data)
telemetry["current_l2"] = parse_4_bytes(bytes) / 1000 * TRANSFORMATION_COEFFICIENT
end)
if not ok then
enapter.log("Phase 2 current reading failed: "..err, "error")
alerts = {"communication_failed"}
status = "read_error"
end
local ok, err = pcall(function()
local data = read_data(ADDRESS, current_l3, TIMEOUT)
local bytes = totable(data)
telemetry["current_l3"] = parse_4_bytes(bytes) / 1000 * TRANSFORMATION_COEFFICIENT
end)
if not ok then
enapter.log("Phase 3 current reading failed: "..err, "error")
alerts = {"communication_failed"}
status = "read_error"
end
local ok, err = pcall(function()
local data = read_data(ADDRESS, frequency, TIMEOUT)
local bytes = totable(data)
telemetry["frequency"] = parse_4_bytes(bytes) / 100
end)
if not ok then
enapter.log("Frequency reading failed: "..err, "error")
alerts = {"communication_failed"}
status = "read_error"
end
local ok, err = pcall(function()
local data = read_data(ADDRESS, active_power, TIMEOUT)
local bytes = totable(data)
local bytes_total = slice(bytes, 2, 4)
table.insert(bytes_total, 1, 0)
local bytes_l1 = slice(bytes, 5, 7)
table.insert(bytes_l1, 1, 0)
local bytes_l2 = slice(bytes, 8, 10)
table.insert(bytes_l2, 1, 0)
local bytes_l3 = slice(bytes, 11, 13)
table.insert(bytes_l3, 1, 0)
telemetry["total_power"] = parse_4_bytes(bytes_total) * TRANSFORMATION_COEFFICIENT / 100
telemetry["power_l1"] = parse_4_bytes(bytes_l1) * TRANSFORMATION_COEFFICIENT / 100
telemetry["power_l2"] = parse_4_bytes(bytes_l2) * TRANSFORMATION_COEFFICIENT / 100
telemetry["power_l3"] = parse_4_bytes(bytes_l3) * TRANSFORMATION_COEFFICIENT / 100
end)
if not ok then
enapter.log("Power reading failed: "..err, "error")
alerts = {"communication_failed"}
status = "read_error"
end
local ok, err = pcall(function()
local data = read_data(ADDRESS, total_energy, TIMEOUT)
local bytes = totable(data)
local bytes_total = slice(bytes, 2, 5)
telemetry["total_energy_since_reset"] = parse_4_bytes(bytes_total) * TRANSFORMATION_COEFFICIENT
end)
if not ok then
enapter.log("Total energy reading failed: "..err, "error")
alerts = {"communication_failed"}
status = "read_error"
end
local ok, err = pcall(function()
local data = read_data(ADDRESS, total_energy_by_phases, TIMEOUT)
local bytes = totable(data)
local bytes_l1 = slice(bytes, 2, 5)
local bytes_l2 = slice(bytes, 6, 9)
local bytes_l3 = slice(bytes, 10, 13)
telemetry["total_energy_l1"] = parse_4_bytes(bytes_l1) * TRANSFORMATION_COEFFICIENT
telemetry["total_energy_l2"] = parse_4_bytes(bytes_l2) * TRANSFORMATION_COEFFICIENT
telemetry["total_energy_l3"] = parse_4_bytes(bytes_l3) * TRANSFORMATION_COEFFICIENT
end)
if not ok then
enapter.log("Total energy by phases reading failed: "..err, "error")
alerts = {"communication_failed"}
status = "read_error"
end
telemetry["alerts"] = alerts
telemetry["status"] = status
enapter.send_telemetry(telemetry)
end
function read_data(ADDRESS, command, TIMEOUT)
-- sample request: string.pack('<BBBBBBBBBBB', 00, 01, 01, 01, 01, 01, 01, 01, 01, 0x77, 0x81)
local cmd = {}
table.insert(cmd, ADDRESS)
for _, query in pairs(command) do
table.insert(cmd, query)
end
local crc = crc16(cmd)
local request = ''
for _, byte in pairs(cmd) do
request = request .. string.pack('B', byte)
end
request = request .. string.pack('B', crc & 0x00FF)
request = request .. string.pack('B', (crc & 0xFF00) >> 8)
local result = rs485.send(request)
if result ~= 0 then
enapter.log("RS485 send command failed: " .. rs485.err_to_str(result), "error")
return
end
local data, result = rs485.receive(TIMEOUT)
if result ~= 0 then
enapter.log("RS485 receive command failed: " .. rs485.err_to_str(result), "error")
return
end
if not data then
enapter.log('No data received: result='..tostring(result)..' data='..tostring(data), 'error')
return
end
return data
end
function totable(data)
local bytes = { string.byte(data, 1, -1) }
return bytes
end
function slice(t, start_i, stop_i)
local new_table = {}
for i = start_i, stop_i do
table.insert(new_table, t[i])
end
return new_table
end
function parse_4_bytes(bytes)
local result = 0x00000000
result = result | (bytes[2] << 24)
result = result | ((bytes[1] << 16) & 0x00ff0000)
result = result | ((bytes[4] << 8) & 0x0000ff00)
result = result | bytes[3]
return result
end
function crc16(pck)
local result = 0xFFFF
for i = 1, #pck do
result = result ~ pck[i]
for _ = 1, 8 do
if ((result & 0x01) == 1) then
result = (result >> 1) ~ 0xA001
else
result = result >> 1
end
end
end
return result
end
main()
| 29.967871 | 99 | 0.676494 |
b95c6e0d2ea6c800b96ee5d94033fc15b085e9a1 | 1,654 | h | C | lean/header/lean/concurrent/semaphore.h | dgu123/lean-cpp-lib | e4698699a743e567f287f5592af0f23219657929 | [
"MIT"
] | null | null | null | lean/header/lean/concurrent/semaphore.h | dgu123/lean-cpp-lib | e4698699a743e567f287f5592af0f23219657929 | [
"MIT"
] | null | null | null | lean/header/lean/concurrent/semaphore.h | dgu123/lean-cpp-lib | e4698699a743e567f287f5592af0f23219657929 | [
"MIT"
] | null | null | null | /*****************************************************/
/* lean Concurrent (c) Tobias Zirr 2011 */
/*****************************************************/
#pragma once
#ifndef LEAN_CONCURRENT_SEMAPHORE
#define LEAN_CONCURRENT_SEMAPHORE
#include "../lean.h"
#include "../tags/noncopyable.h"
#include <windows.h>
namespace lean
{
namespace concurrent
{
/// Implements a semaphore.
class semaphore : public noncopyable
{
private:
HANDLE m_semaphore;
public:
/// Constructs a critical section. Throws a runtime_error on failure.
explicit semaphore(long initialCount = 1)
: m_semaphore( ::CreateSemaphoreW(NULL, initialCount, LONG_MAX, NULL) )
{
LEAN_ASSERT(m_semaphore != NULL);
}
/// Destructor.
~semaphore()
{
::CloseHandle(m_semaphore);
}
/// Tries to acquire this semaphore, returning false if currenty unavailable.
LEAN_INLINE bool try_lock()
{
return (::WaitForSingleObject(m_semaphore, 0) == WAIT_OBJECT_0);
}
/// Acquires this semaphore, returning immediately on success, otherwise waiting for the semaphore to become available.
LEAN_INLINE void lock()
{
DWORD result = ::WaitForSingleObject(m_semaphore, INFINITE);
LEAN_ASSERT(result == WAIT_OBJECT_0);
}
/// Releases this semaphore, permitting waiting threads to continue execution.
LEAN_INLINE void unlock()
{
BOOL result = ::ReleaseSemaphore(m_semaphore, 1, NULL);
LEAN_ASSERT(result != FALSE);
}
/// Gets the native handle.
LEAN_INLINE HANDLE native_handle() const
{
return m_semaphore;
}
};
} // namespace
using concurrent::semaphore;
} // namespace
#endif | 23.628571 | 121 | 0.64873 |
04a5c666b0b7fb655fbc20e8da635f99d2833a8a | 1,143 | java | Java | src/control/ControlNumpad.java | alkolhar/OST_Sudoku | 8419c889b0c3f73543b2f80d0e71c4ff55d415b3 | [
"MIT"
] | null | null | null | src/control/ControlNumpad.java | alkolhar/OST_Sudoku | 8419c889b0c3f73543b2f80d0e71c4ff55d415b3 | [
"MIT"
] | null | null | null | src/control/ControlNumpad.java | alkolhar/OST_Sudoku | 8419c889b0c3f73543b2f80d0e71c4ff55d415b3 | [
"MIT"
] | null | null | null | package control;
import java.util.EventListener;
import java.util.Hashtable;
import control.listener.ControlNumpadListener;
import enums.ListenerKey1D;
/**
* class for controlling the events concerning the numpad
*/
public class ControlNumpad {
private ControlNumpadListener[] listeners;
private final ControlMain parent;
private final int BUTTONCOUNT = 10;
/**
* constructor for ControlNumpad, generates 10 ControlNumpadListeners with this
* as parent
*
* @param p ControlMain, the parent of this class
*/
public ControlNumpad(ControlMain p) {
this.parent = p;
listeners = new ControlNumpadListener[BUTTONCOUNT];
for (int i = 0; i < BUTTONCOUNT; i++) {
listeners[i] = new ControlNumpadListener(parent, i);
}
}
/**
* generates a Hashtable of the listeners
*
* @return Hashtable with the listeners
*/
public Hashtable<String, EventListener> getListeners() {
Hashtable<String, EventListener> table = new Hashtable<String, EventListener>();
for (int i = 0; i < listeners.length; i++) {
String k = ListenerKey1D.NUMPADLISTENER.getKey(i);
table.put(k, listeners[i]);
}
return table;
}
}
| 25.4 | 82 | 0.72266 |
74b12893fcae6d5ddffb818dc44e559596d7ba07 | 1,791 | js | JavaScript | app/modules/modules/supporters.js | thehelvijs/Caffeinated | 387287df666cc554bbbe8c5bcf03b366896e78fe | [
"MIT"
] | 10 | 2020-04-21T01:06:04.000Z | 2021-04-23T14:00:33.000Z | app/modules/modules/supporters.js | thehelvijs/Caffeinated | 387287df666cc554bbbe8c5bcf03b366896e78fe | [
"MIT"
] | 7 | 2020-05-06T15:59:48.000Z | 2021-03-19T00:30:40.000Z | app/modules/modules/supporters.js | thehelvijs/Caffeinated | 387287df666cc554bbbe8c5bcf03b366896e78fe | [
"MIT"
] | 3 | 2020-05-15T05:22:10.000Z | 2020-10-04T22:49:47.000Z |
MODULES.uniqueModuleClasses["casterlabs_supporters"] = class {
constructor(id) {
this.namespace = "casterlabs_supporters";
this.displayname = "caffeinated.supporters.title";
this.type = "application";
this.id = id;
this.icon = "star";
this.persist = true;
}
init() {
this.page.innerHTML = `
<br />
<p style="text-align: center;">
Loving Caffeinated? Feel free to support the project <a style="color: #e94b4b;" onclick="openLink('https://ko-fi.com/casterlabs')">here</a>.
</p>
<p style="text-align: center;">
Looking for a custom made overlay design?<br />Get your own at <a style="color: #ff94db;" onclick="openLink('https://reyana.org')">Reyana.org <img style="height: .85em; vertical-align: middle;" src="https://assets.casterlabs.co/butterfly.png" /></a>
</p>
<br />
<h5 style="text-align: center;">
★ Our Supporters ★
</h5>
<div style="text-align: center;" id="supporters"></div>
<br />
<br />
<br />
`;
setInterval(this.update, 360000); // Every 6 min
this.update();
}
update() {
fetch("https://api.casterlabs.co/v1/caffeinated/supporters").then((response) => response.json()).then((donations) => {
const div = document.querySelector("#supporters");
div.innerHTML = "";
donations.forEach((donation) => {
const text = document.createElement("pre");
text.innerHTML = donation;
text.style = "padding: 0; margin: 0;";
div.appendChild(text);
});
});
}
};
| 31.982143 | 265 | 0.521496 |
1658133e1d3513f4890fd1c1cd4e662d8c38b4e0 | 7,433 | ts | TypeScript | HTML5SharedGUI/SimulationViewer/Scripts/Spatial2DTableView.ts | Biological-Computation/crn-engine | a03387ff9c7042339dc54cf3c7177955e924e6d3 | [
"MIT"
] | 10 | 2021-09-27T10:13:27.000Z | 2021-11-19T06:45:34.000Z | HTML5SharedGUI/SimulationViewer/Scripts/Spatial2DTableView.ts | Biological-Computation/crn-engine | a03387ff9c7042339dc54cf3c7177955e924e6d3 | [
"MIT"
] | 3 | 2022-03-09T14:19:05.000Z | 2022-03-21T18:18:32.000Z | HTML5SharedGUI/SimulationViewer/Scripts/Spatial2DTableView.ts | microsoft/crn-engine | 2d470206e8929e5719d473919e926c4d536d181a | [
"MIT"
] | 3 | 2021-09-27T10:13:57.000Z | 2021-10-09T13:30:05.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// (FP) This file implements the table view (specifically for simulation results). Note that this does not implement the actual table: it makes use of the table component that's implemented in KnockoutGrid.js (found in HTML5SharedGUI).
import "../../KnockoutGrid/knockoutgrid";
import * as ko from "knockout";
import * as $ from "jquery";
import { saveAs } from "file-saver";
import * as Papa from "papaparse";
import * as Framework from "./SimulationViewerFramework";
import * as ProgressView from "./ProgressView";
import * as tableTemplate from 'raw-loader!../html/TableView.html';
import * as rowsTemplate from 'raw-loader!../html/Spatial2DTableRows.html';
import * as I from "../../GenericComponents/Scripts/Interfaces";
$('head').append(rowsTemplate);
ko.components.register("spatial-2d-table-view", {
template: tableTemplate,
viewModel: {
createViewModel: function (params: any, componentInfo: KnockoutComponentTypes.ComponentInfo) {
// Return the parent VM.
var context = ko.contextFor(componentInfo.element);
return context === null ? {} : context.$data;
}
}
});
interface Record {
y: number;
values: number[];
}
function transposeArray(array: number[][]): number[][] {
let newArray: number[][] = [];
for (let j in array[0]) {
newArray.push([]);
}
for (let i in array) {
for (let j in array[i]) {
newArray[j].push(array[i][j]);
}
}
return newArray;
}
class InstanceData {
constructor(public ID: number) { }
public RawData: KnockoutObservable<number[][][]> = ko.observableArray([]);
}
// (FP) This class is the VM for the table viewer. It contains the data that gets displayed and any relative configuration (names, choice of sim, etc).
class TableVM {
public Progress: ProgressView.ProgressView = new ProgressView.ProgressView();
xAxis: KnockoutObservableArray<number> = ko.observableArray([]);
yAxis: KnockoutObservableArray<number> = ko.observableArray([]);
instances: KnockoutObservable<InstanceData[]> = ko.observable([]);
currentInstance: KnockoutObservable<number> = ko.observable(0);
currentSpecies: KnockoutObservable<number> = ko.observable(0);
records: KnockoutComputed<Record[]> = ko.pureComputed(() => {
let instance = this.currentInstance();
let instanceData = this.instances()[instance];
if (instanceData == null)
return [];
let arr: Record[] = [];
let xAxis = this.xAxis();
let yAxis = this.yAxis();
let species = this.currentSpecies();
let rawData = instanceData.RawData();
let spData = rawData[species];
if (spData == null)
return [];
let data = transposeArray(spData);
for (let it in data) {
let record: Record = {
y: yAxis[it] ? yAxis[it] : NaN,
values: data[it]
};
arr.push(record);
}
return arr;
}).extend({ rateLimit: 1000 });
SupportsStructural = ko.observable(false);
SupportsBounds = ko.observable(false);
AreBoundsEnabled = ko.observable(false);
tableConfig: any;
constructor() {
// (FP) The table config is the object that gets used by the KnockoutGrid component to know what to show.
this.tableConfig = {
data: this.records,
headerTemplate: 'spatial-2d-table-view-header',
columnTemplate: 'spatial-2d-table-view-template',
ViewModel: this,
last: false,
};
}
// (FP) This function generates a CSV file with the current data.
Save() {
let results = this.records;
let xAxis: string[] = [];
xAxis.push("Y\\X");
this.xAxis().forEach(val => xAxis.push(val.toString()));
var csv = Papa.unparse({
data: results().map((val) => {
var arr = new Array();
arr.push(val.y);
val.values.forEach(val => arr.push(val));
return arr;
}),
fields: xAxis
},
{
quotes: false,
delimiter: ",",
newline: "\r\n"
});
var blob = new Blob([csv], { type: "text/csv" });
saveAs(blob, "Spatial2DSimulationResult.csv");
}
public Filter: any = null;
}
export class View implements Rx.IObserver<Framework.IVisualizationUpdateMessage> {
private vm: TableVM;
constructor() {
this.vm = new TableVM();
}
public ShowInstance(id: number) {
this.vm.currentInstance(id);
}
public ShowSpecies(idx: number) {
this.vm.currentSpecies(idx);
}
// (FP) Constructs the component in the provided element.
// (FP) Constructs the component in the provided element.
public Bind(elementToBindTo: HTMLElement) {
if (elementToBindTo == null)
throw "attempt to bind Spatial2DTableView to null";
ko.applyBindings(this.vm, elementToBindTo)
};
// (FP) The caller needs to use this function to provide a source of simulation data.
public onNext(update: Framework.IVisualizationUpdateMessage) {
var vm = this.vm;
vm.Progress.onNext(update);
switch (update.MessageType) {
case Framework.VisualizationUpdateMessageType.TraceDefinitions:
var traces = <I.ITraceDefinitions>update.EncapsulatedUpdate;
// Create the observable arrays for each instance.
var instances: InstanceData[] = [];
for (let crn of traces.CRNs)
for (let settings of crn.Settings)
for (let sweep of settings.Sweeps)
for (let instance of sweep.Instances)
instances[instance.ID] = new InstanceData(instance.ID);
this.vm.instances(instances);
break;
case Framework.VisualizationUpdateMessageType.SpatialSpace:
var sp = <Framework.ISpatialSpace>update.EncapsulatedUpdate;
vm.xAxis(sp.XAxis);
vm.yAxis(sp.YAxis);
break;
case Framework.VisualizationUpdateMessageType.AdditionalPlottable:
console.log("JIT plots not currently supported in spatial view");
break;
case Framework.VisualizationUpdateMessageType.SimulationStep2D:
var data = <Framework.I2DSimStepData>update.EncapsulatedUpdate;
var instance = this.vm.instances()[data.Instance];
instance.RawData(data.Data);
break;
case Framework.VisualizationUpdateMessageType.PlotSettingsInfo:
var settings = <Framework.PlotSettings>update.EncapsulatedUpdate;
break;
case Framework.VisualizationUpdateMessageType.Reset:
this.Reset();
break;
default:
break;
}
}
public onError(exception: any) {
console.log("Spatial2DTableView exception: " + JSON.stringify(exception));
throw exception;
}
public onCompleted() {
}
private Reset() {
this.vm.instances([]);
this.vm.xAxis([]);
this.vm.yAxis([]);
}
}
| 36.258537 | 235 | 0.597471 |
b6be2556d0722653e7e9f2a36fbe3ba04028fbc9 | 361 | rb | Ruby | db/migrate/20191220085352_create_compose_projects.rb | yunbowang328/gitlink | 4fa10a3683f8079ac877fa2b12b0ab767164f30f | [
"MulanPSL-1.0"
] | null | null | null | db/migrate/20191220085352_create_compose_projects.rb | yunbowang328/gitlink | 4fa10a3683f8079ac877fa2b12b0ab767164f30f | [
"MulanPSL-1.0"
] | null | null | null | db/migrate/20191220085352_create_compose_projects.rb | yunbowang328/gitlink | 4fa10a3683f8079ac877fa2b12b0ab767164f30f | [
"MulanPSL-1.0"
] | null | null | null | class CreateComposeProjects < ActiveRecord::Migration[5.2]
def change
# create_table :compose_projects do |t|
# t.integer :user_id
# t.integer :project_id
# t.integer :compose_id
# t.integer :position , default: 0
#
# t.timestamps
# end
# add_index :compose_projects, [:user_id, :project_id, :compose_id]
end
end
| 25.785714 | 71 | 0.65374 |
86391661ff4fc90157132c5c386cfe48c7c20bba | 8,977 | go | Go | data/types/insulin/concentration_test.go | mdblp/platform | e4b64e58e4aa26a2d43ba4f1013b4038828d7750 | [
"BSD-2-Clause"
] | 27 | 2016-04-14T01:02:58.000Z | 2022-01-27T05:07:55.000Z | data/types/insulin/concentration_test.go | tidepool-org/platform | b4bfe923daa083642d4778795734fd8906e1d048 | [
"BSD-2-Clause"
] | 423 | 2015-12-13T23:20:53.000Z | 2022-03-10T14:57:58.000Z | data/types/insulin/concentration_test.go | mdblp/platform | e4b64e58e4aa26a2d43ba4f1013b4038828d7750 | [
"BSD-2-Clause"
] | 9 | 2015-12-11T01:03:49.000Z | 2019-08-29T15:33:13.000Z | package insulin_test
import (
"math"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
dataNormalizer "github.com/tidepool-org/platform/data/normalizer"
"github.com/tidepool-org/platform/data/types/insulin"
dataTypesInsulinTest "github.com/tidepool-org/platform/data/types/insulin/test"
dataTypesTest "github.com/tidepool-org/platform/data/types/test"
errorsTest "github.com/tidepool-org/platform/errors/test"
"github.com/tidepool-org/platform/pointer"
"github.com/tidepool-org/platform/structure"
structureValidator "github.com/tidepool-org/platform/structure/validator"
)
var _ = Describe("Concentration", func() {
It("ConcentrationUnitsUnitsPerML is expected", func() {
Expect(insulin.ConcentrationUnitsUnitsPerML).To(Equal("Units/mL"))
})
It("ConcentrationValueUnitsPerMLMaximum is expected", func() {
Expect(insulin.ConcentrationValueUnitsPerMLMaximum).To(Equal(10000.0))
})
It("ConcentrationValueUnitsPerMLMinimum is expected", func() {
Expect(insulin.ConcentrationValueUnitsPerMLMinimum).To(Equal(0.0))
})
It("ConcentrationUnits returns expected", func() {
Expect(insulin.ConcentrationUnits()).To(Equal([]string{"Units/mL"}))
})
Context("ParseConcentration", func() {
// TODO
})
Context("NewConcentration", func() {
It("is successful", func() {
Expect(insulin.NewConcentration()).To(Equal(&insulin.Concentration{}))
})
})
Context("Concentration", func() {
Context("Parse", func() {
// TODO
})
Context("Validate", func() {
DescribeTable("validates the datum",
func(mutator func(datum *insulin.Concentration), expectedErrors ...error) {
datum := dataTypesInsulinTest.NewConcentration()
mutator(datum)
dataTypesTest.ValidateWithExpectedOrigins(datum, structure.Origins(), expectedErrors...)
},
Entry("succeeds",
func(datum *insulin.Concentration) {},
),
Entry("units missing",
func(datum *insulin.Concentration) { datum.Units = nil },
errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/units"),
),
Entry("units invalid",
func(datum *insulin.Concentration) { datum.Units = pointer.FromString("invalid") },
errorsTest.WithPointerSource(structureValidator.ErrorValueStringNotOneOf("invalid", []string{"Units/mL"}), "/units"),
),
Entry("units Units/mL",
func(datum *insulin.Concentration) {
datum.Units = pointer.FromString("Units/mL")
datum.Value = pointer.FromFloat64(0.0)
},
),
Entry("units missing; value missing",
func(datum *insulin.Concentration) {
datum.Units = nil
datum.Value = nil
},
errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/units"),
errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/value"),
),
Entry("units missing; value out of range (lower)",
func(datum *insulin.Concentration) {
datum.Units = nil
datum.Value = pointer.FromFloat64(-0.1)
},
errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/units"),
),
Entry("units missing; value in range (lower)",
func(datum *insulin.Concentration) {
datum.Units = nil
datum.Value = pointer.FromFloat64(0.0)
},
errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/units"),
),
Entry("units missing; value in range (upper)",
func(datum *insulin.Concentration) {
datum.Units = nil
datum.Value = pointer.FromFloat64(10000.0)
},
errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/units"),
),
Entry("units missing; value out of range (upper)",
func(datum *insulin.Concentration) {
datum.Units = nil
datum.Value = pointer.FromFloat64(10000.1)
},
errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/units"),
),
Entry("units invalid; value missing",
func(datum *insulin.Concentration) {
datum.Units = pointer.FromString("invalid")
datum.Value = nil
},
errorsTest.WithPointerSource(structureValidator.ErrorValueStringNotOneOf("invalid", []string{"Units/mL"}), "/units"),
errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/value"),
),
Entry("units invalid; value out of range (lower)",
func(datum *insulin.Concentration) {
datum.Units = pointer.FromString("invalid")
datum.Value = pointer.FromFloat64(-0.1)
},
errorsTest.WithPointerSource(structureValidator.ErrorValueStringNotOneOf("invalid", []string{"Units/mL"}), "/units"),
),
Entry("units invalid; value in range (lower)",
func(datum *insulin.Concentration) {
datum.Units = pointer.FromString("invalid")
datum.Value = pointer.FromFloat64(0.0)
},
errorsTest.WithPointerSource(structureValidator.ErrorValueStringNotOneOf("invalid", []string{"Units/mL"}), "/units"),
),
Entry("units invalid; value in range (upper)",
func(datum *insulin.Concentration) {
datum.Units = pointer.FromString("invalid")
datum.Value = pointer.FromFloat64(10000.0)
},
errorsTest.WithPointerSource(structureValidator.ErrorValueStringNotOneOf("invalid", []string{"Units/mL"}), "/units"),
),
Entry("units invalid; value out of range (upper)",
func(datum *insulin.Concentration) {
datum.Units = pointer.FromString("invalid")
datum.Value = pointer.FromFloat64(10000.1)
},
errorsTest.WithPointerSource(structureValidator.ErrorValueStringNotOneOf("invalid", []string{"Units/mL"}), "/units"),
),
Entry("units Units/mL; value missing",
func(datum *insulin.Concentration) {
datum.Units = pointer.FromString("Units/mL")
datum.Value = nil
},
errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/value"),
),
Entry("units Units/mL; value out of range (lower)",
func(datum *insulin.Concentration) {
datum.Units = pointer.FromString("Units/mL")
datum.Value = pointer.FromFloat64(-0.1)
},
errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(-0.1, 0.0, 10000.0), "/value"),
),
Entry("units Units/mL; value in range (lower)",
func(datum *insulin.Concentration) {
datum.Units = pointer.FromString("Units/mL")
datum.Value = pointer.FromFloat64(0.0)
},
),
Entry("units Units/mL; value in range (upper)",
func(datum *insulin.Concentration) {
datum.Units = pointer.FromString("Units/mL")
datum.Value = pointer.FromFloat64(10000.0)
},
),
Entry("units Units/mL; value out of range (upper)",
func(datum *insulin.Concentration) {
datum.Units = pointer.FromString("Units/mL")
datum.Value = pointer.FromFloat64(10000.1)
},
errorsTest.WithPointerSource(structureValidator.ErrorValueNotInRange(10000.1, 0.0, 10000.0), "/value"),
),
Entry("multiple errors",
func(datum *insulin.Concentration) {
datum.Units = nil
datum.Value = nil
},
errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/units"),
errorsTest.WithPointerSource(structureValidator.ErrorValueNotExists(), "/value"),
),
)
})
Context("Normalize", func() {
DescribeTable("normalizes the datum",
func(mutator func(datum *insulin.Concentration)) {
for _, origin := range structure.Origins() {
datum := dataTypesInsulinTest.NewConcentration()
mutator(datum)
expectedDatum := dataTypesInsulinTest.CloneConcentration(datum)
normalizer := dataNormalizer.New()
Expect(normalizer).ToNot(BeNil())
datum.Normalize(normalizer.WithOrigin(origin))
Expect(normalizer.Error()).To(BeNil())
Expect(normalizer.Data()).To(BeEmpty())
Expect(datum).To(Equal(expectedDatum))
}
},
Entry("does not modify the datum",
func(datum *insulin.Concentration) {},
),
Entry("does not modify the datum; units missing",
func(datum *insulin.Concentration) { datum.Units = nil },
),
Entry("does not modify the datum; value missing",
func(datum *insulin.Concentration) { datum.Value = nil },
),
)
})
})
Context("ConcentrationValueRangeForUnits", func() {
It("returns expected range for units missing", func() {
minimum, maximum := insulin.ConcentrationValueRangeForUnits(nil)
Expect(minimum).To(Equal(-math.MaxFloat64))
Expect(maximum).To(Equal(math.MaxFloat64))
})
It("returns expected range for units invalid", func() {
minimum, maximum := insulin.ConcentrationValueRangeForUnits(pointer.FromString("invalid"))
Expect(minimum).To(Equal(-math.MaxFloat64))
Expect(maximum).To(Equal(math.MaxFloat64))
})
It("returns expected range for units Units/mL", func() {
minimum, maximum := insulin.ConcentrationValueRangeForUnits(pointer.FromString("Units/mL"))
Expect(minimum).To(Equal(0.0))
Expect(maximum).To(Equal(10000.0))
})
})
})
| 37.404167 | 122 | 0.687312 |
bf38abd328d7349d215cb9fe31280ed077ee6b80 | 5,824 | sql | SQL | Databases/Set-FKConstraints.sql | reubensultana/DBAScripts | 5ffae3a1d46bd72aae0cc390c16d8a888fe58928 | [
"MIT"
] | 2 | 2021-11-12T13:22:47.000Z | 2022-03-04T09:33:47.000Z | Databases/Set-FKConstraints.sql | reubensultana/DBAScripts | 5ffae3a1d46bd72aae0cc390c16d8a888fe58928 | [
"MIT"
] | null | null | null | Databases/Set-FKConstraints.sql | reubensultana/DBAScripts | 5ffae3a1d46bd72aae0cc390c16d8a888fe58928 | [
"MIT"
] | 2 | 2018-11-23T18:12:44.000Z | 2020-10-12T05:50:23.000Z | /* Source: https://github.com/reubensultana/DBAScripts/blob/master/Databases/Set-FKConstraints.sql */
-- Enable, Disable, Drop and Recreate FKs based on Primary Key table
-- Written 2007-11-18
-- Edgewood Solutions / MSSQLTips.com
-- Works for SQL Server 2005
SET NOCOUNT ON
DECLARE @operation VARCHAR(10)
DECLARE @tableName sysname
DECLARE @schemaName sysname
SET @operation = 'CREATE' --ENABLE, DISABLE, DROP, CREATE
--SET @tableName = NULL
--SET @schemaName = 'dbo'
DECLARE @cmd NVARCHAR(1000)
DECLARE
@FK_NAME sysname,
@FK_OBJECTID INT,
@FK_DISABLED INT,
@FK_NOT_FOR_REPLICATION INT,
@DELETE_RULE smallint,
@UPDATE_RULE smallint,
@FKTABLE_NAME sysname,
@FKTABLE_OWNER sysname,
@PKTABLE_NAME sysname,
@PKTABLE_OWNER sysname,
@FKCOLUMN_NAME sysname,
@PKCOLUMN_NAME sysname,
@CONSTRAINT_COLID INT
DECLARE cursor_fkeys CURSOR FOR
SELECT Fk.name,
Fk.OBJECT_ID,
Fk.is_disabled,
Fk.is_not_for_replication,
Fk.delete_referential_action,
Fk.update_referential_action,
OBJECT_NAME(Fk.parent_object_id) AS Fk_table_name,
schema_name(Fk.schema_id) AS Fk_table_schema,
TbR.name AS Pk_table_name,
schema_name(TbR.schema_id) Pk_table_schema
FROM sys.foreign_keys Fk LEFT OUTER JOIN
sys.tables TbR ON TbR.OBJECT_ID = Fk.referenced_object_id --inner join
WHERE schema_name(TbR.schema_id) = ISNULL(@schemaName, schema_name(TbR.schema_id))
AND TbR.name = ISNULL(@tableName, TbR.name)
ORDER BY schema_name(TbR.schema_id) ASC, TbR.name ASC, Fk.name ASC
OPEN cursor_fkeys
FETCH NEXT FROM cursor_fkeys
INTO @FK_NAME,@FK_OBJECTID,
@FK_DISABLED,
@FK_NOT_FOR_REPLICATION,
@DELETE_RULE,
@UPDATE_RULE,
@FKTABLE_NAME,
@FKTABLE_OWNER,
@PKTABLE_NAME,
@PKTABLE_OWNER
WHILE @@FETCH_STATUS = 0
BEGIN
-- create statement for enabling FK
IF @operation = 'ENABLE'
BEGIN
SET @cmd = 'ALTER TABLE [' + @FKTABLE_OWNER + '].[' + @FKTABLE_NAME
+ '] CHECK CONSTRAINT [' + @FK_NAME + ']'
PRINT @cmd
END
-- create statement for disabling FK
IF @operation = 'DISABLE'
BEGIN
SET @cmd = 'ALTER TABLE [' + @FKTABLE_OWNER + '].[' + @FKTABLE_NAME
+ '] NOCHECK CONSTRAINT [' + @FK_NAME + ']'
PRINT @cmd
END
-- create statement for dropping FK and also for recreating FK
IF @operation = 'DROP'
BEGIN
-- drop statement
SET @cmd = 'ALTER TABLE [' + @FKTABLE_OWNER + '].[' + @FKTABLE_NAME
+ '] DROP CONSTRAINT [' + @FK_NAME + ']'
PRINT @cmd
END
IF @operation = 'CREATE'
BEGIN
-- create process
DECLARE @FKCOLUMNS VARCHAR(1000), @PKCOLUMNS VARCHAR(1000), @COUNTER INT
-- create cursor to get FK columns
DECLARE cursor_fkeyCols CURSOR FOR
SELECT COL_NAME(Fk.parent_object_id, Fk_Cl.parent_column_id) AS Fk_col_name,
COL_NAME(Fk.referenced_object_id, Fk_Cl.referenced_column_id) AS Pk_col_name
FROM sys.foreign_keys Fk LEFT OUTER JOIN
sys.tables TbR ON TbR.OBJECT_ID = Fk.referenced_object_id INNER JOIN
sys.foreign_key_columns Fk_Cl ON Fk_Cl.constraint_object_id = Fk.OBJECT_ID
WHERE schema_name(TbR.schema_id) = ISNULL(@schemaName, schema_name(TbR.schema_id))
AND TbR.name = ISNULL(@tableName, TbR.name)
AND Fk_Cl.constraint_object_id = @FK_OBJECTID -- added 6/12/2008
ORDER BY Fk_Cl.constraint_column_id
OPEN cursor_fkeyCols
FETCH NEXT FROM cursor_fkeyCols INTO @FKCOLUMN_NAME,@PKCOLUMN_NAME
SET @COUNTER = 1
SET @FKCOLUMNS = ''
SET @PKCOLUMNS = ''
WHILE @@FETCH_STATUS = 0
BEGIN
IF @COUNTER > 1
BEGIN
SET @FKCOLUMNS = @FKCOLUMNS + ','
SET @PKCOLUMNS = @PKCOLUMNS + ','
END
SET @FKCOLUMNS = @FKCOLUMNS + '[' + @FKCOLUMN_NAME + ']'
SET @PKCOLUMNS = @PKCOLUMNS + '[' + @PKCOLUMN_NAME + ']'
SET @COUNTER = @COUNTER + 1
FETCH NEXT FROM cursor_fkeyCols INTO @FKCOLUMN_NAME,@PKCOLUMN_NAME
END
CLOSE cursor_fkeyCols
DEALLOCATE cursor_fkeyCols
-- generate create FK statement
SET @cmd = 'ALTER TABLE [' + @FKTABLE_OWNER + '].[' + @FKTABLE_NAME + '] WITH ' +
CASE @FK_DISABLED
WHEN 0 THEN ' CHECK '
WHEN 1 THEN ' NOCHECK '
END + ' ADD CONSTRAINT [' + @FK_NAME
+ '] FOREIGN KEY (' + @FKCOLUMNS
+ ') REFERENCES [' + @PKTABLE_OWNER + '].[' + @PKTABLE_NAME + '] ('
+ @PKCOLUMNS + ') ON UPDATE ' +
CASE @UPDATE_RULE
WHEN 0 THEN ' NO ACTION '
WHEN 1 THEN ' CASCADE '
WHEN 2 THEN ' SET_NULL '
END + ' ON DELETE ' +
CASE @DELETE_RULE
WHEN 0 THEN ' NO ACTION '
WHEN 1 THEN ' CASCADE '
WHEN 2 THEN ' SET_NULL '
END + '' +
CASE @FK_NOT_FOR_REPLICATION
WHEN 0 THEN ''
WHEN 1 THEN ' NOT FOR REPLICATION '
END
PRINT @cmd
END
FETCH NEXT FROM cursor_fkeys
INTO @FK_NAME,@FK_OBJECTID,
@FK_DISABLED,
@FK_NOT_FOR_REPLICATION,
@DELETE_RULE,
@UPDATE_RULE,
@FKTABLE_NAME,
@FKTABLE_OWNER,
@PKTABLE_NAME,
@PKTABLE_OWNER
END
CLOSE cursor_fkeys
DEALLOCATE cursor_fkeys
| 31.311828 | 101 | 0.580872 |
71ef26647facd3305caf0c9a73dcea7a8def2f13 | 56,619 | swift | Swift | EasyGameCenter.swift | psmejkal/Easy-Game-Center-Swift | 33414d0aaea1fe2f936514d15dca3d1795e70829 | [
"MIT"
] | null | null | null | EasyGameCenter.swift | psmejkal/Easy-Game-Center-Swift | 33414d0aaea1fe2f936514d15dca3d1795e70829 | [
"MIT"
] | null | null | null | EasyGameCenter.swift | psmejkal/Easy-Game-Center-Swift | 33414d0aaea1fe2f936514d15dca3d1795e70829 | [
"MIT"
] | null | null | null | //
// GameCenter.swift
//
// Created by Yannick Stephan DaRk-_-D0G on 19/12/2014.
// YannickStephan.com
//
// iOS 7.0+ & iOS 8.0+ & iOS 9.0+ & TvOS 9.0+
//
// The MIT License (MIT)
// Copyright (c) 2015 Red Wolf Studio & Yannick Stephan
// http://www.redwolfstudio.fr
// http://yannickstephan.com
// Version 2.3 for Swift 2.0
import Foundation
import GameKit
import SystemConfiguration
/**
TODO List
- REMEMBER report plusieur score pour plusieur leaderboard en array
*/
// Protocol Easy Game Center
@objc public protocol EGCDelegate:NSObjectProtocol {
/**
Authentified, Delegate Easy Game Center
*/
optional func EGCAuthentified(authentified:Bool)
/**
Not Authentified, Delegate Easy Game Center
*/
//optional func EGCNotAuthentified()
/**
Achievementes in cache, Delegate Easy Game Center
*/
optional func EGCInCache()
/**
Method called when a match has been initiated.
*/
optional func EGCMatchStarted()
/**
Method called when the device received data about the match from another device in the match.
- parameter match: GKMatch
- parameter didReceiveData: NSData
- parameter fromPlayer: String
*/
optional func EGCMatchRecept(match: GKMatch, didReceiveData: NSData, fromPlayer: String)
/**
Method called when the match has ended.
*/
optional func EGCMatchEnded()
/**
Cancel match
*/
optional func EGCMatchCancel()
}
// MARK: - Public Func
extension EGC {
/**
CheckUp Connection the new
- returns: Bool Connection Validation
*/
static var isConnectedToNetwork: Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}) else {
return false
}
var flags : SCNetworkReachabilityFlags = []
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == false {
return false
}
let isReachable = flags.contains(.Reachable)
let needsConnection = flags.contains(.ConnectionRequired)
return (isReachable && !needsConnection)
}
}
/// Easy Game Center Swift
public class EGC: NSObject, GKGameCenterControllerDelegate, GKMatchmakerViewControllerDelegate, GKMatchDelegate, GKLocalPlayerListener {
/*####################################################################################################*/
/* Private Instance */
/*####################################################################################################*/
/// Achievements GKAchievement Cache
private var achievementsCache:[String:GKAchievement] = [String:GKAchievement]()
/// Achievements GKAchievementDescription Cache
private var achievementsDescriptionCache = [String:GKAchievementDescription]()
/// Save for report late when network working
private var achievementsCacheShowAfter = [String:String]()
/// Checkup net and login to GameCenter when have Network
private var timerNetAndPlayer:NSTimer?
/// Debug mode for see message
private var debugModeGetSet:Bool = false
static var showLoginPage:Bool = true
/// The match object provided by GameKit.
private var match: GKMatch?
private var playersInMatch = Set<GKPlayer>()
public var invitedPlayer: GKPlayer?
public var invite: GKInvite?
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
/*####################################################################################################*/
/* Singleton Public Instance */
/*####################################################################################################*/
override init() {
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(EGC.authenticationChanged), name: GKPlayerAuthenticationDidChangeNotificationName, object: nil)
}
/**
Static EGC
*/
struct Static {
/// Async EGC
static var onceToken: dispatch_once_t = 0
/// Instance of EGC
static var instance: EGC? = nil
/// Delegate of UIViewController
static weak var delegate: UIViewController? = nil
}
/**
Start Singleton GameCenter Instance
*/
public class func sharedInstance(delegate:UIViewController)-> EGC {
if Static.instance == nil {
dispatch_once(&Static.onceToken) {
Static.instance = EGC()
Static.delegate = delegate
Static.instance!.loginPlayerToGameCenter()
}
}
return Static.instance!
}
/// Delegate UIViewController
class var delegate: UIViewController {
get {
do {
let delegateInstance = try EGC.sharedInstance.getDelegate()
return delegateInstance
} catch {
EGCError.NoDelegate.errorCall()
fatalError("Dont work\(error)")
}
}
set {
guard newValue != EGC.delegate else {
return
}
Static.delegate = EGC.delegate
EGC.printLogEGC("New delegate UIViewController is (String(Static.delegate.dynamicType))\n")
}
}
/*####################################################################################################*/
/* Public Func / Object */
/*####################################################################################################*/
public class var debugMode:Bool {
get {
return EGC.sharedInstance.debugModeGetSet
}
set {
EGC.sharedInstance.debugModeGetSet = newValue
}
}
/**
If player is Identified to Game Center
- returns: Bool is identified
*/
public static var isPlayerIdentified: Bool {
get {
return GKLocalPlayer.localPlayer().authenticated
}
}
/**
Get local player (GKLocalPlayer)
- returns: Bool True is identified
*/
static var localPayer: GKLocalPlayer {
get {
return GKLocalPlayer.localPlayer()
}
}
// class func getLocalPlayer() -> GKLocalPlayer { }
/**
Get local player Information (playerID,alias,profilPhoto)
:completion: Tuple of type (playerID:String,alias:String,profilPhoto:UIImage?)
*/
class func getlocalPlayerInformation(completion completionTuple: (playerInformationTuple:(playerID:String,alias:String,profilPhoto:UIImage?)?) -> ()) {
guard EGC.isConnectedToNetwork else {
completionTuple(playerInformationTuple: nil)
EGCError.NoConnection.errorCall()
return
}
guard EGC.isPlayerIdentified else {
completionTuple(playerInformationTuple: nil)
EGCError.NotLogin.errorCall()
return
}
EGC.localPayer.loadPhotoForSize(GKPhotoSizeNormal, withCompletionHandler: {
(image, error) in
var playerInformationTuple:(playerID:String,alias:String,profilPhoto:UIImage?)
playerInformationTuple.profilPhoto = nil
playerInformationTuple.playerID = EGC.localPayer.playerID!
playerInformationTuple.alias = EGC.localPayer.alias!
if error == nil { playerInformationTuple.profilPhoto = image }
completionTuple(playerInformationTuple: playerInformationTuple)
})
}
/*####################################################################################################*/
/* Public Func Show */
/*####################################################################################################*/
/**
Show Game Center
- parameter completion: Viod just if open Game Center Achievements
*/
public class func showGameCenter(completion: ((isShow:Bool) -> Void)? = nil) {
guard EGC.isConnectedToNetwork else {
if completion != nil { completion!(isShow:false) }
EGCError.NoConnection.errorCall()
return
}
guard EGC.isPlayerIdentified else {
if completion != nil { completion!(isShow:false) }
EGCError.NotLogin.errorCall()
return
}
EGC.printLogEGC("Show Game Center")
let gc = GKGameCenterViewController()
gc.gameCenterDelegate = Static.instance
#if !os(tvOS)
gc.viewState = GKGameCenterViewControllerState.Default
#endif
var delegeteParent:UIViewController? = EGC.delegate.parentViewController
if delegeteParent == nil {
delegeteParent = EGC.delegate
}
delegeteParent!.presentViewController(gc, animated: true, completion: {
if completion != nil { completion!(isShow:true) }
})
}
/**
Show Game Center Player Achievements
- parameter completion: Viod just if open Game Center Achievements
*/
public class func showGameCenterAchievements(completion: ((isShow:Bool) -> Void)? = nil) {
guard EGC.isConnectedToNetwork else {
if completion != nil { completion!(isShow:false) }
EGCError.NoConnection.errorCall()
return
}
guard EGC.isPlayerIdentified else {
if completion != nil { completion!(isShow:false) }
EGCError.NotLogin.errorCall()
return
}
let gc = GKGameCenterViewController()
gc.gameCenterDelegate = Static.instance
#if !os(tvOS)
gc.viewState = GKGameCenterViewControllerState.Achievements
#endif
var delegeteParent:UIViewController? = EGC.delegate.parentViewController
if delegeteParent == nil {
delegeteParent = EGC.delegate
}
delegeteParent!.presentViewController(gc, animated: true, completion: {
if completion != nil { completion!(isShow:true) }
})
}
/**
Show Game Center Leaderboard
- parameter leaderboardIdentifier: Leaderboard Identifier
- parameter completion: Viod just if open Game Center Leaderboard
*/
public class func showGameCenterLeaderboard(leaderboardIdentifier leaderboardIdentifier :String, completion: ((isShow:Bool) -> Void)? = nil) {
guard leaderboardIdentifier != "" else {
EGCError.Empty.errorCall()
if completion != nil { completion!(isShow:false) }
return
}
guard EGC.isConnectedToNetwork else {
EGCError.NoConnection.errorCall()
if completion != nil { completion!(isShow:false) }
return
}
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
if completion != nil { completion!(isShow:false) }
return
}
let gc = GKGameCenterViewController()
gc.gameCenterDelegate = Static.instance
#if !os(tvOS)
gc.leaderboardIdentifier = leaderboardIdentifier
gc.viewState = GKGameCenterViewControllerState.Leaderboards
#endif
var delegeteParent:UIViewController? = EGC.delegate.parentViewController
if delegeteParent == nil {
delegeteParent = EGC.delegate
}
delegeteParent!.presentViewController(gc, animated: true, completion: {
if completion != nil { completion!(isShow:true) }
})
}
/**
Show Game Center Challenges
- parameter completion: Viod just if open Game Center Challenges
*/
public class func showGameCenterChallenges(completion: ((isShow:Bool) -> Void)? = nil) {
guard EGC.isConnectedToNetwork else {
if completion != nil { completion!(isShow:false) }
EGCError.NoConnection.errorCall()
return
}
guard EGC.isPlayerIdentified else {
if completion != nil { completion!(isShow:false) }
EGCError.NotLogin.errorCall()
return
}
let gc = GKGameCenterViewController()
gc.gameCenterDelegate = Static.instance
#if !os(tvOS)
gc.viewState = GKGameCenterViewControllerState.Challenges
#endif
var delegeteParent:UIViewController? = EGC.delegate.parentViewController
if delegeteParent == nil {
delegeteParent = EGC.delegate
}
delegeteParent!.presentViewController(gc, animated: true, completion: {
() -> Void in
if completion != nil { completion!(isShow:true) }
})
}
/**
Show banner game center
- parameter title: title
- parameter description: description
- parameter completion: When show message
*/
public class func showCustomBanner(title title:String, description:String,completion: (() -> Void)? = nil) {
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return
}
GKNotificationBanner.showBannerWithTitle(title, message: description, completionHandler: completion)
}
/**
Show page Authentication Game Center
- parameter completion: Viod just if open Game Center Authentication
*/
public class func showGameCenterAuthentication(completion: ((result:Bool) -> Void)? = nil) {
if completion != nil {
completion!(result: UIApplication.sharedApplication().openURL(NSURL(string: "gamecenter:")!))
}
}
/*####################################################################################################*/
/* Public Func LeaderBoard */
/*####################################################################################################*/
/**
Get Leaderboards
- parameter completion: return [GKLeaderboard] or nil
*/
public class func getGKLeaderboard(completion completion: ((resultArrayGKLeaderboard:Set<GKLeaderboard>?) -> Void)) {
guard EGC.isConnectedToNetwork else {
completion(resultArrayGKLeaderboard: nil)
EGCError.NoConnection.errorCall()
return
}
guard EGC.isPlayerIdentified else {
completion(resultArrayGKLeaderboard: nil)
EGCError.NotLogin.errorCall()
return
}
GKLeaderboard.loadLeaderboardsWithCompletionHandler {
(leaderboards, error) in
guard EGC.isPlayerIdentified else {
completion(resultArrayGKLeaderboard: nil)
EGCError.NotLogin.errorCall()
return
}
guard let leaderboardsIsArrayGKLeaderboard = leaderboards as [GKLeaderboard]? else {
completion(resultArrayGKLeaderboard: nil)
EGCError.Error(error?.localizedDescription).errorCall()
return
}
completion(resultArrayGKLeaderboard: Set(leaderboardsIsArrayGKLeaderboard))
}
}
/**
Reports a score to Game Center
- parameter The: score Int
- parameter Leaderboard: identifier
- parameter completion: (bool) when the score is report to game center or Fail
*/
public class func reportScoreLeaderboard(leaderboardIdentifier leaderboardIdentifier:String, score: Int) {
guard EGC.isConnectedToNetwork else {
EGCError.NoConnection.errorCall()
return
}
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return
}
let gkScore = GKScore(leaderboardIdentifier: leaderboardIdentifier)
gkScore.value = Int64(score)
gkScore.shouldSetDefaultLeaderboard = true
GKScore.reportScores([gkScore], withCompletionHandler: nil)
}
/**
Get High Score for leaderboard identifier
- parameter leaderboardIdentifier: leaderboard ID
- parameter completion: Tuple (playerName: String, score: Int, rank: Int)
*/
public class func getHighScore(
leaderboardIdentifier leaderboardIdentifier:String,
completion:((playerName:String, score:Int,rank:Int)? -> Void)
) {
EGC.getGKScoreLeaderboard(leaderboardIdentifier: leaderboardIdentifier, completion: {
(resultGKScore) in
guard let valGkscore = resultGKScore else {
completion(nil)
return
}
let rankVal = valGkscore.rank
let nameVal = EGC.localPayer.alias!
let scoreVal = Int(valGkscore.value)
completion((playerName: nameVal, score: scoreVal, rank: rankVal))
})
}
/**
Get GKScoreOfLeaderboard
- parameter completion: GKScore or nil
*/
public class func getGKScoreLeaderboard(leaderboardIdentifier leaderboardIdentifier:String, completion:((resultGKScore:GKScore?) -> Void)) {
guard leaderboardIdentifier != "" else {
EGCError.Empty.errorCall()
completion(resultGKScore:nil)
return
}
guard EGC.isConnectedToNetwork else {
EGCError.NoConnection.errorCall()
completion(resultGKScore: nil)
return
}
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
completion(resultGKScore: nil)
return
}
let leaderBoardRequest = GKLeaderboard()
leaderBoardRequest.identifier = leaderboardIdentifier
leaderBoardRequest.loadScoresWithCompletionHandler {
(resultGKScore, error) in
guard error == nil && resultGKScore != nil else {
completion(resultGKScore: nil)
return
}
completion(resultGKScore: leaderBoardRequest.localPlayerScore)
}
}
/*####################################################################################################*/
/* Public Func Achievements */
/*####################################################################################################*/
/**
Get Tuple ( GKAchievement , GKAchievementDescription) for identifier Achievement
- parameter achievementIdentifier: Identifier Achievement
- returns: (gkAchievement:GKAchievement,gkAchievementDescription:GKAchievementDescription)?
*/
public class func getTupleGKAchievementAndDescription(achievementIdentifier achievementIdentifier:String,completion completionTuple: ((tupleGKAchievementAndDescription:(gkAchievement:GKAchievement,gkAchievementDescription:GKAchievementDescription)?) -> Void)) {
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
completionTuple(tupleGKAchievementAndDescription: nil)
return
}
let achievementGKScore = EGC.sharedInstance.achievementsCache[achievementIdentifier]
let achievementGKDes = EGC.sharedInstance.achievementsDescriptionCache[achievementIdentifier]
guard let aGKS = achievementGKScore, let aGKD = achievementGKDes else {
completionTuple(tupleGKAchievementAndDescription: nil)
return
}
completionTuple(tupleGKAchievementAndDescription: (aGKS,aGKD))
}
/**
Get Achievement
- parameter identifierAchievement: Identifier achievement
- returns: GKAchievement Or nil if not exist
*/
public class func getAchievementForIndentifier(identifierAchievement identifierAchievement : NSString) -> GKAchievement? {
guard identifierAchievement != "" else {
EGCError.Empty.errorCall()
return nil
}
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return nil
}
guard let achievementFind = EGC.sharedInstance.achievementsCache[identifierAchievement as String] else {
return nil
}
return achievementFind
}
/**
Add progress to an achievement
- parameter progress: Progress achievement Double (ex: 10% = 10.00)
- parameter achievementIdentifier: Achievement Identifier
- parameter showBannnerIfCompleted: if you want show banner when now or not when is completed
- parameter completionIsSend: Completion if is send to Game Center
*/
public class func reportAchievement( progress progress : Double, achievementIdentifier : String, showBannnerIfCompleted : Bool = true ,addToExisting: Bool = false) {
guard achievementIdentifier != "" else {
EGCError.Empty.errorCall()
return
}
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return
}
guard !EGC.isAchievementCompleted(achievementIdentifier: achievementIdentifier) else {
EGC.printLogEGC("Achievement is already completed")
return
}
guard let achievement = EGC.getAchievementForIndentifier(identifierAchievement: achievementIdentifier) else {
EGC.printLogEGC("No Achievement for identifier")
return
}
let currentValue = achievement.percentComplete
let newProgress: Double = !addToExisting ? progress : progress + currentValue
achievement.percentComplete = newProgress
/* show banner only if achievement is fully granted (progress is 100%) */
if achievement.completed && showBannnerIfCompleted {
EGC.printLogEGC("Achievement \(achievementIdentifier) completed")
if EGC.isConnectedToNetwork {
achievement.showsCompletionBanner = true
} else {
//oneAchievement.showsCompletionBanner = true << Bug For not show two banner
// Force show Banner when player not have network
EGC.getTupleGKAchievementAndDescription(achievementIdentifier: achievementIdentifier, completion: {
(tupleGKAchievementAndDescription) -> Void in
if let tupleIsOK = tupleGKAchievementAndDescription {
let title = tupleIsOK.gkAchievementDescription.title
let description = tupleIsOK.gkAchievementDescription.achievedDescription
EGC.showCustomBanner(title: title!, description: description!)
}
})
}
}
if achievement.completed && !showBannnerIfCompleted {
EGC.sharedInstance.achievementsCacheShowAfter[achievementIdentifier] = achievementIdentifier
}
EGC.sharedInstance.reportAchievementToGameCenter(achievement: achievement)
}
/**
Get GKAchievementDescription
- parameter completion: return array [GKAchievementDescription] or nil
*/
public class func getGKAllAchievementDescription(completion completion: ((arrayGKAD:Set<GKAchievementDescription>?) -> Void)){
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return
}
guard EGC.sharedInstance.achievementsDescriptionCache.count > 0 else {
EGCError.NoAchievement.printError()
return
}
var tempsEnvoi = Set<GKAchievementDescription>()
for achievementDes in EGC.sharedInstance.achievementsDescriptionCache {
tempsEnvoi.insert(achievementDes.1)
}
completion(arrayGKAD: tempsEnvoi)
}
/**
If achievement is Completed
- parameter Achievement: Identifier
:return: (Bool) if finished
*/
public class func isAchievementCompleted(achievementIdentifier achievementIdentifier: String) -> Bool{
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return false
}
guard let achievement = EGC.getAchievementForIndentifier(identifierAchievement: achievementIdentifier)
where achievement.completed || achievement.percentComplete == 100.00 else {
return false
}
return true
}
/**
Get Achievements Completes during the game and banner was not showing
- returns: [String : GKAchievement] or nil
*/
public class func getAchievementCompleteAndBannerNotShowing() -> [GKAchievement]? {
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return nil
}
let achievements : [String:String] = EGC.sharedInstance.achievementsCacheShowAfter
var achievementsTemps = [GKAchievement]()
if achievements.count > 0 {
for achievement in achievements {
if let achievementExtract = EGC.getAchievementForIndentifier(identifierAchievement: achievement.1) {
if achievementExtract.completed && achievementExtract.showsCompletionBanner == false {
achievementsTemps.append(achievementExtract)
}
}
}
return achievementsTemps
}
return nil
}
/**
Show all save achievement Complete if you have ( showBannerAchievementWhenComplete = false )
- parameter completion: if is Show Achievement banner
(Bug Game Center if you show achievement by showsCompletionBanner = true when you report and again you show showsCompletionBanner = false is not show)
*/
public class func showAllBannerAchievementCompleteForBannerNotShowing(completion: ((achievementShow:GKAchievement?) -> Void)? = nil) {
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
if completion != nil { completion!(achievementShow: nil) }
return
}
guard let achievementNotShow: [GKAchievement] = EGC.getAchievementCompleteAndBannerNotShowing() else {
if completion != nil { completion!(achievementShow: nil) }
return
}
for achievement in achievementNotShow {
EGC.getTupleGKAchievementAndDescription(achievementIdentifier: achievement.identifier!, completion: {
(tupleGKAchievementAndDescription) in
guard let tupleOK = tupleGKAchievementAndDescription else {
if completion != nil { completion!(achievementShow: nil) }
return
}
//oneAchievement.showsCompletionBanner = true
let title = tupleOK.gkAchievementDescription.title
let description = tupleOK.gkAchievementDescription.achievedDescription
EGC.showCustomBanner(title: title!, description: description!, completion: {
if completion != nil { completion!(achievementShow: achievement) }
})
})
}
EGC.sharedInstance.achievementsCacheShowAfter.removeAll(keepCapacity: false)
}
/**
Get progress to an achievement
- parameter Achievement: Identifier
- returns: Double or nil (if not find)
*/
public class func getProgressForAchievement(achievementIdentifier achievementIdentifier:String) -> Double? {
guard achievementIdentifier != "" else {
EGCError.Empty.errorCall()
return nil
}
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return nil
}
if let achievementInArrayInt = EGC.sharedInstance.achievementsCache[achievementIdentifier]?.percentComplete {
return achievementInArrayInt
} else {
EGCError.Error("No Achievement for achievementIdentifier : \(achievementIdentifier)").errorCall()
EGCError.NoAchievement.errorCall()
return nil
}
}
/**
Remove All Achievements
completion: return GKAchievement reset or Nil if game center not work
sdsds
*/
public class func resetAllAchievements( completion: ((achievementReset:GKAchievement?) -> Void)? = nil) {
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
if completion != nil { completion!(achievementReset: nil) }
return
}
GKAchievement.resetAchievementsWithCompletionHandler({
(error:NSError?) in
guard error == nil else {
EGC.printLogEGC("Couldn't Reset achievement (Send data error)")
return
}
for lookupAchievement in Static.instance!.achievementsCache {
let achievementID = lookupAchievement.0
let achievementGK = lookupAchievement.1
achievementGK.percentComplete = 0
achievementGK.showsCompletionBanner = false
if completion != nil { completion!(achievementReset:achievementGK) }
EGC.printLogEGC("Reset achievement (\(achievementID))")
}
})
}
/*####################################################################################################*/
/* Mutliplayer */
/*####################################################################################################*/
/**
Find player By number
- parameter minPlayers: Int
- parameter maxPlayers: Max
*/
public class func findMatchWithMinPlayers(minPlayers: Int, maxPlayers: Int) {
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return
}
do {
let delegatVC = try EGC.sharedInstance.getDelegate()
EGC.disconnectMatch()
let request = GKMatchRequest()
request.minPlayers = minPlayers
request.maxPlayers = maxPlayers
let controlllerGKMatch = GKMatchmakerViewController(matchRequest: request)
controlllerGKMatch!.matchmakerDelegate = EGC.sharedInstance
var delegeteParent:UIViewController? = delegatVC.parentViewController
if delegeteParent == nil {
delegeteParent = delegatVC
}
delegeteParent!.presentViewController(controlllerGKMatch!, animated: true, completion: nil)
} catch EGCError.NoDelegate {
EGCError.NoDelegate.errorCall()
} catch {
fatalError("Dont work\(error)")
}
}
/**
Get Player in match
- returns: Set<GKPlayer>
*/
public class func getPlayerInMatch() -> Set<GKPlayer>? {
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return nil
}
guard EGC.sharedInstance.match != nil && EGC.sharedInstance.playersInMatch.count > 0 else {
EGC.printLogEGC("No Match")
return nil
}
return EGC.sharedInstance.playersInMatch
}
/**
Deconnect the Match
*/
public class func disconnectMatch() {
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return
}
guard let match = EGC.sharedInstance.match else {
return
}
EGC.printLogEGC("Disconnect from match")
match.disconnect()
EGC.sharedInstance.match = nil
(self.delegate as? EGCDelegate)?.EGCMatchEnded?()
}
/**
Get match
- returns: GKMatch or nil if haven't match
*/
public class func getMatch() -> GKMatch? {
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return nil
}
guard let match = EGC.sharedInstance.match else {
EGC.printLogEGC("No Match")
return nil
}
return match
}
/**
player in net
*/
@available(iOS 8.0, *)
private func lookupPlayers() {
guard let match = EGC.sharedInstance.match else {
EGC.printLogEGC("No Match")
return
}
let playerIDs = match.players.map { $0.playerID }
guard let hasePlayerIDS = playerIDs as? [String] else {
EGC.printLogEGC("No Player")
return
}
/* Load an array of player */
GKPlayer.loadPlayersForIdentifiers(hasePlayerIDS) {
(players, error) in
guard error == nil else {
EGC.printLogEGC("Error retrieving player info: \(error!.localizedDescription)")
EGC.disconnectMatch()
return
}
guard let players = players else {
EGC.printLogEGC("Error retrieving players; returned nil")
return
}
if EGC.debugMode {
for player in players {
EGC.printLogEGC("Found player: \(player.alias)")
}
}
if let arrayPlayers = players as [GKPlayer]? { self.playersInMatch = Set(arrayPlayers) }
GKMatchmaker.sharedMatchmaker().finishMatchmakingForMatch(match)
(Static.delegate as? EGCDelegate)?.EGCMatchStarted?()
}
}
/**
Transmits data to all players connected to the match.
- parameter data: NSData
- parameter modeSend: GKMatchSendDataMode
:GKMatchSendDataMode Reliable: a.s.a.p. but requires fragmentation and reassembly for large messages, may stall if network congestion occurs
:GKMatchSendDataMode Unreliable: Preferred method. Best effort and immediate, but no guarantees of delivery or order; will not stall.
*/
public class func sendDataToAllPlayers(data: NSData!, modeSend:GKMatchSendDataMode) {
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return
}
guard let match = EGC.sharedInstance.match else {
EGC.printLogEGC("No Match")
return
}
do {
try match.sendDataToAllPlayers(data, withDataMode: modeSend)
EGC.printLogEGC("Succes sending data all Player")
} catch {
EGC.disconnectMatch()
(Static.delegate as? EGCDelegate)?.EGCMatchEnded?()
EGC.printLogEGC("Fail sending data all Player")
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
/*####################################################################################################*/
/* Singleton Private Instance */
/*####################################################################################################*/
/// ShareInstance Private
class private var sharedInstance : EGC {
guard let instance = Static.instance else {
EGCError.Error("No Instance, please sharedInstance of EasyGameCenter").errorCall()
fatalError("No Instance, please sharedInstance of EasyGameCenter")
}
return instance
}
/**
Delegate UIViewController
- throws: .NoDelegate
- returns: UIViewController
*/
private func getDelegate() throws -> UIViewController {
guard let delegate = Static.delegate else {
throw EGCError.NoDelegate
}
return delegate
}
/*####################################################################################################*/
/* private Start */
/*####################################################################################################*/
/**
Init Implemented by subclasses to initialize a new object
- returns: An initialized object
*/
//override init() { super.init() }
/**
Completion for cachin Achievements and AchievementsDescription
- parameter achievementsType: GKAchievement || GKAchievementDescription
*/
private static func completionCachingAchievements(achievementsType :[AnyObject]?) {
func finish() {
if EGC.sharedInstance.achievementsCache.count > 0 &&
EGC.sharedInstance.achievementsDescriptionCache.count > 0 {
(Static.delegate as? EGCDelegate)?.EGCInCache?()
}
}
// Type GKAchievement
if achievementsType is [GKAchievement] {
guard let arrayGKAchievement = achievementsType as? [GKAchievement] where arrayGKAchievement.count > 0 else {
EGCError.CantCachingGKAchievement.errorCall()
return
}
for anAchievement in arrayGKAchievement where anAchievement.identifier != nil {
EGC.sharedInstance.achievementsCache[anAchievement.identifier!] = anAchievement
}
finish()
// Type GKAchievementDescription
} else if achievementsType is [GKAchievementDescription] {
guard let arrayGKAchievementDes = achievementsType as? [GKAchievementDescription] where arrayGKAchievementDes.count > 0 else {
EGCError.CantCachingGKAchievementDescription.errorCall()
return
}
for anAchievementDes in arrayGKAchievementDes where anAchievementDes.identifier != nil {
// Add GKAchievement
if EGC.sharedInstance.achievementsCache.indexForKey(anAchievementDes.identifier!) == nil {
EGC.sharedInstance.achievementsCache[anAchievementDes.identifier!] = GKAchievement(identifier: anAchievementDes.identifier!)
}
// Add CGAchievementDescription
EGC.sharedInstance.achievementsDescriptionCache[anAchievementDes.identifier!] = anAchievementDes
}
GKAchievement.loadAchievementsWithCompletionHandler({
(allAchievements, error) in
guard (error == nil) && allAchievements!.count != 0 else {
finish()
return
}
EGC.completionCachingAchievements(allAchievements)
})
}
}
/**
Load achievements in cache
(Is call when you init EGC, but if is fail example for cut connection, you can recall)
And when you get Achievement or all Achievement, it shall automatically cached
*/
private func cachingAchievements() {
guard EGC.isConnectedToNetwork else {
EGCError.NoConnection.errorCall()
return
}
guard EGC.isPlayerIdentified else {
EGCError.NotLogin.errorCall()
return
}
// Load GKAchievementDescription
GKAchievementDescription.loadAchievementDescriptionsWithCompletionHandler({
(achievementsDescription, error) in
guard error == nil else {
EGCError.Error(error?.localizedDescription).errorCall()
return
}
EGC.completionCachingAchievements(achievementsDescription)
})
}
/**
Login player to GameCenter With Handler Authentification
This function is recall When player connect to Game Center
- parameter completion: (Bool) if player login to Game Center
*/
/// Authenticates the user with their Game Center account if possible
// MARK: Internal functions
internal func authenticationChanged() {
guard let delegateEGC = Static.delegate as? EGCDelegate else {
return
}
if EGC.isPlayerIdentified {
delegateEGC.EGCAuthentified?(true)
EGC.sharedInstance.cachingAchievements()
} else {
delegateEGC.EGCAuthentified?(false)
}
}
private func loginPlayerToGameCenter() {
guard !EGC.isPlayerIdentified else {
return
}
guard let delegateVC = Static.delegate else {
EGCError.NoDelegate.errorCall()
return
}
guard EGC.isConnectedToNetwork else {
EGCError.NoConnection.errorCall()
return
}
GKLocalPlayer.localPlayer().authenticateHandler = {
(gameCenterVC, error) in
guard error == nil else {
EGCError.Error("User has canceled authentication").errorCall()
return
}
guard let gcVC = gameCenterVC else {
return
}
if EGC.showLoginPage {
dispatch_async(dispatch_get_main_queue()) {
delegateVC.presentViewController(gcVC, animated: true, completion: nil)
}
}
}
}
/*####################################################################################################*/
/* Private Timer checkup */
/*####################################################################################################*/
/**
Function checkup when he have net work login Game Center
*/
func checkupNetAndPlayer() {
dispatch_async(dispatch_get_main_queue()) {
if self.timerNetAndPlayer == nil {
self.timerNetAndPlayer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(EGC.checkupNetAndPlayer), userInfo: nil, repeats: true)
}
if EGC.isConnectedToNetwork {
self.timerNetAndPlayer!.invalidate()
self.timerNetAndPlayer = nil
EGC.sharedInstance.loginPlayerToGameCenter()
}
}
}
/*####################################################################################################*/
/* Private Func Achievements */
/*####################################################################################################*/
/**
Report achievement classic
- parameter achievement: GKAchievement
*/
private func reportAchievementToGameCenter(achievement achievement:GKAchievement) {
/* try to report the progress to the Game Center */
GKAchievement.reportAchievements([achievement], withCompletionHandler: {
(error:NSError?) -> Void in
if error != nil { /* Game Center Save Automatique */ }
})
}
/*####################################################################################################*/
/* Public Delagate Game Center */
/*####################################################################################################*/
/**
Dismiss Game Center when player open
- parameter GKGameCenterViewController:
Override of GKGameCenterControllerDelegate
*/
public func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
/*####################################################################################################*/
/* GKMatchDelegate */
/*####################################################################################################*/
/**
Called when data is received from a player.
- parameter theMatch: GKMatch
- parameter data: NSData
- parameter playerID: String
*/
public func match(theMatch: GKMatch, didReceiveData data: NSData, fromPlayer playerID: String) {
guard EGC.sharedInstance.match == theMatch else {
return
}
(Static.delegate as? EGCDelegate)?.EGCMatchRecept?(theMatch, didReceiveData: data, fromPlayer: playerID)
}
/**
Called when a player connects to or disconnects from the match.
Echange avec autre players
- parameter theMatch: GKMatch
- parameter playerID: String
- parameter state: GKPlayerConnectionState
*/
public func match(theMatch: GKMatch, player playerID: String, didChangeState state: GKPlayerConnectionState) {
/* recall when is desconnect match = nil */
guard self.match == theMatch else {
return
}
switch state {
/* Connected */
case .StateConnected where self.match != nil && theMatch.expectedPlayerCount == 0:
if #available(iOS 8.0, *) {
self.lookupPlayers()
}
/* Lost deconnection */
case .StateDisconnected:
EGC.disconnectMatch()
default:
break
}
}
/**
Called when the match cannot connect to any other players.
- parameter theMatch: GKMatch
- parameter error: NSError
*/
public func match(theMatch: GKMatch, didFailWithError error: NSError?) {
guard self.match == theMatch else {
return
}
guard error == nil else {
EGCError.Error("Match failed with error: \(error?.localizedDescription)").errorCall()
EGC.disconnectMatch()
return
}
}
/*####################################################################################################*/
/* GKMatchmakerViewControllerDelegate */
/*####################################################################################################*/
/**
Called when a peer-to-peer match is found.
- parameter viewController: GKMatchmakerViewController
- parameter theMatch: GKMatch
*/
public func matchmakerViewController(viewController: GKMatchmakerViewController, didFindMatch theMatch: GKMatch) {
viewController.dismissViewControllerAnimated(true, completion: nil)
self.match = theMatch
self.match!.delegate = self
if match!.expectedPlayerCount == 0 {
if #available(iOS 8.0, *) {
self.lookupPlayers()
}
}
}
/*####################################################################################################*/
/* GKLocalPlayerListener */
/*####################################################################################################*/
/**
Called when another player accepts a match invite from the local player
- parameter player: GKPlayer
- parameter inviteToAccept: GKPlayer
*/
public func player(player: GKPlayer, didAcceptInvite inviteToAccept: GKInvite) {
guard let gkmv = GKMatchmakerViewController(invite: inviteToAccept) else {
EGCError.Error("GKMatchmakerViewController invite to accept nil").errorCall()
return
}
gkmv.matchmakerDelegate = self
var delegeteParent:UIViewController? = EGC.delegate.parentViewController
if delegeteParent == nil {
delegeteParent = EGC.delegate
}
delegeteParent!.presentViewController(gkmv, animated: true, completion: nil)
}
/**
Initiates a match from Game Center with the requested players
- parameter player: The GKPlayer object containing the current player’s information
- parameter playersToInvite: An array of GKPlayer
*/
public func player(player: GKPlayer, didRequestMatchWithOtherPlayers playersToInvite: [GKPlayer]) { }
/**
Called when the local player starts a match with another player from Game Center
- parameter player: The GKPlayer object containing the current player’s information
- parameter playerIDsToInvite: An array of GKPlayer
*/
public func player(player: GKPlayer, didRequestMatchWithPlayers playerIDsToInvite: [String]) { }
/*####################################################################################################*/
/* GKMatchmakerViewController */
/*####################################################################################################*/
/**
Called when the user cancels the matchmaking request (required)
- parameter viewController: GKMatchmakerViewController
*/
public func matchmakerViewControllerWasCancelled(viewController: GKMatchmakerViewController) {
viewController.dismissViewControllerAnimated(true, completion: nil)
(Static.delegate as? EGCDelegate)?.EGCMatchCancel?()
EGC.printLogEGC("Player cancels the matchmaking request")
}
/**
Called when the view controller encounters an unrecoverable error.
- parameter viewController: GKMatchmakerViewController
- parameter error: NSError
*/
public func matchmakerViewController(viewController: GKMatchmakerViewController, didFailWithError error: NSError) {
viewController.dismissViewControllerAnimated(true, completion: nil)
(Static.delegate as? EGCDelegate)?.EGCMatchCancel?()
EGCError.Error("Error finding match: \(error.localizedDescription)\n").errorCall()
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////
/*####################################################################################################*/
/* Debug */
/*####################################################################################################*/
// MARK: - Extension EGC Debug
extension EGC {
/**
Print
- parameter object: Any
*/
private class func printLogEGC(object: Any) {
if EGC.debugMode {
dispatch_async(dispatch_get_main_queue()) {
Swift.print("\n[Easy Game Center] \(object)\n")
}
}
}
}
// MARK: - Debug / Error Func
extension EGC {
/**
ErrorType debug
- Error: Some Error
- CantCachingGKAchievementDescription: Cant caching GKAchievements Des
- CantCachingGKAchievement: Cant caching GKAchievements
- NoAchievement: No Achievement create
- Empty: Param empty
- NoConnection: No internet
- NotLogin: No login
- NoDelegate: No Delegate
*/
private enum EGCError : ErrorType {
case Error(String?)
case CantCachingGKAchievementDescription
case CantCachingGKAchievement
case NoAchievement
case Empty
case NoConnection
case NotLogin
case NoDelegate
/// Description
var description : String {
switch self {
case .Error(let error):
return (error != nil) ? "\(error!)" : "\(error)"
case .CantCachingGKAchievementDescription:
return "Can't caching GKAchievementDescription\n( Have you create achievements in ItuneConnect ? )"
case .CantCachingGKAchievement:
return "Can' t caching GKAchievement\n( Have you create achievements in ItuneConnect ? )"
case .NoAchievement:
return "No GKAchievement and GKAchievementDescription\n\n( Have you create achievements in ItuneConnect ? )"
case .NoConnection:
return "No internet connection"
case .NotLogin:
return "User is not identified to game center"
case .NoDelegate :
return "\nDelegate UIViewController not added"
case .Empty:
return "\nThe parameter is empty"
}
}
/**
Print Debug Enum error
- parameter error: EGCError
*/
private func printError(error: EGCError) {
EGC.printLogEGC(error.description)
}
/**
Print self enum error
*/
private func printError() {
EGC.printLogEGC(self.description)
}
/**
Handler error
*/
private func errorCall() {
defer { self.printError() }
switch self {
case .NotLogin:
(EGC.delegate as? EGCDelegate)?.EGCAuthentified?(false)
break
case .CantCachingGKAchievementDescription:
EGC.sharedInstance.checkupNetAndPlayer()
break
case .CantCachingGKAchievement:
break
default:
break
}
}
}
}
| 36.364162 | 265 | 0.529893 |
dd841d372155e054c075c44ed9d2c7b851501d51 | 1,011 | php | PHP | web/profiles/opigno_lms/modules/contrib/entity_print/src/Renderer/RendererFactory.php | andyhawks/cmcschools-d8 | 83efdc42e4262f4cc4164cb07efbaf577a0e1f04 | [
"MIT"
] | null | null | null | web/profiles/opigno_lms/modules/contrib/entity_print/src/Renderer/RendererFactory.php | andyhawks/cmcschools-d8 | 83efdc42e4262f4cc4164cb07efbaf577a0e1f04 | [
"MIT"
] | 4 | 2020-04-07T06:37:51.000Z | 2022-03-26T07:01:46.000Z | web/profiles/opigno_lms/modules/contrib/entity_print/src/Renderer/RendererFactory.php | andyhawks/cmcschools-d8 | 83efdc42e4262f4cc4164cb07efbaf577a0e1f04 | [
"MIT"
] | null | null | null | <?php
namespace Drupal\entity_print\Renderer;
use Drupal\Core\Entity\EntityInterface;
use Drupal\entity_print\PrintEngineException;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
/**
* The RendererFactory class.
*/
class RendererFactory implements RendererFactoryInterface {
use ContainerAwareTrait;
/**
* {@inheritdoc}
*/
public function create($item, $context = 'entity') {
$entity_type_manager = $this->container->get('entity_type.manager');
// If we get an array or something, just look at the first one.
if (is_array($item)) {
$item = array_pop($item);
}
if ($item instanceof EntityInterface && $entity_type_manager->hasHandler($item->getEntityTypeId(), 'entity_print')) {
return $entity_type_manager->getHandler($item->getEntityTypeId(), 'entity_print');
}
throw new PrintEngineException(sprintf('Rendering not yet supported for "%s". Entity Print context "%s"', is_object($item) ? get_class($item) : $item, $context));
}
}
| 28.885714 | 166 | 0.714144 |
bfe10b241c59ac21cee0dc5fa358ae3f0720bf21 | 688 | rs | Rust | src/board.rs | Robotics-BUT/DCMotor-firmware | ac88b29e103717a73370015dfe0f3ce805ea8998 | [
"MIT"
] | null | null | null | src/board.rs | Robotics-BUT/DCMotor-firmware | ac88b29e103717a73370015dfe0f3ce805ea8998 | [
"MIT"
] | null | null | null | src/board.rs | Robotics-BUT/DCMotor-firmware | ac88b29e103717a73370015dfe0f3ce805ea8998 | [
"MIT"
] | null | null | null | use stm32f0xx_hal::gpio::gpioa::*;
use stm32f0xx_hal::gpio::gpiob::*;
use stm32f0xx_hal::gpio::{Alternate, Output, PushPull, AF1, AF2, AF4};
use stm32f0xx_hal::stm32;
pub type PWM1P = PA8<Alternate<AF2>>;
pub type PWM1N = PB13<Alternate<AF2>>;
pub type PWM2P = PA9<Alternate<AF2>>;
pub type PWM2N = PB14<Alternate<AF2>>;
pub type ENC1 = PB4<Alternate<AF1>>;
pub type ENC2 = PB5<Alternate<AF1>>;
pub type ENCI = PB0<Alternate<AF1>>; // is PB3 AF2 on REVA boards
pub type LED = PB2<Output<PushPull>>;
pub type LED2 = PB10<Output<PushPull>>;
pub type CanRx = PB8<Alternate<AF4>>;
pub type CanTx = PB9<Alternate<AF4>>;
pub type ControlTimer = stm32::TIM2;
pub type NMTTimer = stm32::TIM6;
| 32.761905 | 70 | 0.71657 |
c36829716665f6be9c7dfb9aacf6b9be8642d242 | 1,514 | go | Go | cmd/examples/firespiral/main.go | johnfercher/taleslab | 40a3e2a25dc531ec576d5b55acf1ca31c99c0f5b | [
"MIT"
] | 10 | 2021-04-24T04:32:05.000Z | 2021-06-02T14:03:03.000Z | cmd/examples/firespiral/main.go | johnfercher/taleslab | 40a3e2a25dc531ec576d5b55acf1ca31c99c0f5b | [
"MIT"
] | 11 | 2021-05-01T18:44:00.000Z | 2021-05-09T22:31:40.000Z | cmd/examples/firespiral/main.go | johnfercher/taleslab | 40a3e2a25dc531ec576d5b55acf1ca31c99c0f5b | [
"MIT"
] | 1 | 2021-04-26T01:49:01.000Z | 2021-04-26T01:49:01.000Z | package main
import (
"fmt"
"github.com/johnfercher/taleslab/internal/bytecompressor"
"github.com/johnfercher/taleslab/internal/talespireadapter/talespirecoder"
"github.com/johnfercher/taleslab/pkg/taleslab/taleslabdomain/taleslabentities"
"github.com/johnfercher/taleslab/pkg/taleslab/taleslabmappers"
"github.com/johnfercher/taleslab/pkg/taleslab/taleslabrepositories"
"log"
"math"
)
func main() {
propRepository := taleslabrepositories.NewPropRepository()
compressor := bytecompressor.New()
encoder := talespirecoder.NewEncoder(compressor)
assets := taleslabentities.Assets{}
asset := propRepository.GetProp("fire")
radius := 8
for i := 0.0; i < 4.0*3.14; i += 0.02 {
cos := math.Cos(i)
sin := math.Sin(i)
xRounded := fix(float64(radius)*cos, 1)
yRounded := fix(float64(radius)*sin, 1)
xPositiveTranslated := radius + xRounded
yPositiveTranslated := radius + yRounded
asset := &taleslabentities.Asset{
Id: asset.Parts[0].Id,
Coordinates: &taleslabentities.Vector3d{
X: xPositiveTranslated,
Y: yPositiveTranslated,
Z: int(i),
},
Rotation: 0,
}
assets = append(assets, asset)
}
taleSpireSlab := taleslabmappers.TaleSpireSlabFromAssets(assets)
base64, err := encoder.Encode(taleSpireSlab)
if err != nil {
log.Fatal(err)
}
fmt.Println(base64)
}
func fix(value float64, fixValue int) int {
division := value / float64(fixValue)
divisionRounded := math.Round(division)
top := int(divisionRounded * float64(fixValue))
return top
}
| 22.264706 | 79 | 0.72325 |
2e86067cbd23fe1cd133fbee7263609da8c8add0 | 5,742 | swift | Swift | Example/JKSwiftExtension/Class/UIKitExtensionViewController/Controller/UIControlExtensionViewController.swift | lilin87788/JKSwiftExtension | 096cb83699a7736ef3aa7ee67cd1dc1597eb5a02 | [
"Apache-2.0"
] | null | null | null | Example/JKSwiftExtension/Class/UIKitExtensionViewController/Controller/UIControlExtensionViewController.swift | lilin87788/JKSwiftExtension | 096cb83699a7736ef3aa7ee67cd1dc1597eb5a02 | [
"Apache-2.0"
] | null | null | null | Example/JKSwiftExtension/Class/UIKitExtensionViewController/Controller/UIControlExtensionViewController.swift | lilin87788/JKSwiftExtension | 096cb83699a7736ef3aa7ee67cd1dc1597eb5a02 | [
"Apache-2.0"
] | null | null | null | //
// UIControlExtensionViewController.swift
// JKSwiftExtension_Example
//
// Created by IronMan on 2020/11/9.
// Copyright © 2020 CocoaPods. All rights reserved.
//
import UIKit
class UIControlExtensionViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
headDataArray = ["一、基本的链式编程", "二、基本的扩展"]
dataArray = [["设置是否可用", "设置 点击状态", "是否高亮状态", "设置 垂直方向 对齐方式", "设置 水平方向 对齐方式", "添加事件(默认点击事件:touchUpInside)", "移除事件(默认移除 点击事件:touchUpInside)"], ["多少秒内不可重复点击"]]
}
@objc func click(sender: UIButton) {
JKPrint("点击测试")
}
}
// MARK: - 二、基本的扩展
extension UIControlExtensionViewController {
// MARK: 2.1、多少秒内不可重复点击
@objc func test21() {
let hitTime : Double = 5
let btn = UIButton(frame: CGRect(x: 50, y: jk_kScreenH - 250, width: 200, height: 100))
btn.backgroundColor = .randomColor
btn.addTarget(self, action: #selector(click), for: .touchUpInside)
btn.tag = 20
btn.setTitle("\(hitTime)秒内不可重复点击", for: .normal)
btn.jk.preventDoubleHit(hitTime)
btn.jk.setHandleClick { (btn) in
guard let weakBtn = btn else { return }
print("button的点击事件", "tag:\(weakBtn.tag)")
}
btn.addTo(self.view)
JKAsyncs.asyncDelay(10, {
}) {
btn.removeFromSuperview()
}
}
}
// MARK: - 一、基本的链式编程
extension UIControlExtensionViewController {
// MARK: 1.1、设置是否可用(测试这里设置不可用)
@objc func test11() {
let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
btn.backgroundColor = .randomColor
btn.addTarget(self, action: #selector(click), for: .touchUpInside)
btn.isEnabled(false)
btn.addTo(self.view)
JKAsyncs.asyncDelay(5, {
}) {
}
}
// MARK: 1.2、设置 点击状态
@objc func test12() {
let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
btn.backgroundColor = .yellow
btn.setTitleColor(.red, for: .normal)
btn.setTitleColor(.green, for: .selected)
btn.setTitle("2秒后消失", for: .normal)
btn.addTarget(self, action: #selector(click), for: .touchUpInside)
// 设置选中状态
btn.isSelected(true)
btn.addTo(self.view)
JKAsyncs.asyncDelay(2, {
}) {
btn.removeFromSuperview()
}
}
// MARK: 1.3、是否高亮状态
@objc func test13() {
let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
btn.backgroundColor = .yellow
btn.setTitleColor(.red, for: .normal)
btn.setTitleColor(.green, for: .selected)
btn.setTitleColor(.black, for: .highlighted)
btn.setTitle("2秒后消失", for: .normal)
btn.addTarget(self, action: #selector(click), for: .touchUpInside)
// 设置选中状态
btn.isHighlighted(true)
btn.addTo(self.view)
JKAsyncs.asyncDelay(2, {
}) {
btn.removeFromSuperview()
}
}
// MARK: 1.4、设置垂直方向对齐方式
@objc func test14() {
let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
btn.backgroundColor = .yellow
btn.setTitleColor(.red, for: .normal)
btn.setTitleColor(.green, for: .selected)
btn.setTitleColor(.black, for: .highlighted)
btn.setTitle("2秒后消失", for: .normal)
btn.addTarget(self, action: #selector(click), for: .touchUpInside)
btn.contentVerticalAlignment(.bottom)
btn.addTo(self.view)
JKAsyncs.asyncDelay(2, {
}) {
btn.removeFromSuperview()
}
}
// MARK: 1.5、设置水平方向对齐方式
@objc func test15() {
let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
btn.backgroundColor = .yellow
btn.setTitleColor(.red, for: .normal)
btn.setTitleColor(.green, for: .selected)
btn.setTitleColor(.black, for: .highlighted)
btn.setTitle("2秒后消失", for: .normal)
btn.addTarget(self, action: #selector(click), for: .touchUpInside)
btn.contentHorizontalAlignment(.left)
btn.addTo(self.view)
JKAsyncs.asyncDelay(2, {
}) {
btn.removeFromSuperview()
}
}
// MARK: 1.6、添加事件(默认点击事件:touchUpInside)
@objc func test16() {
let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
btn.backgroundColor = .yellow
btn.setTitleColor(.red, for: .normal)
btn.setTitleColor(.green, for: .selected)
btn.setTitleColor(.black, for: .highlighted)
btn.setTitle("5秒后消失", for: .normal)
btn.add(self, action: #selector(click))
btn.addTo(self.view)
JKAsyncs.asyncDelay(2, {
}) {
btn.removeFromSuperview()
}
}
// MARK: 1.7、移除事件(默认移除 点击事件:touchUpInside)
@objc func test17() {
let btn = UIButton(frame: CGRect(x: 50, y: 100, width: 200, height: 100))
btn.backgroundColor = .yellow
btn.setTitleColor(.red, for: .normal)
btn.setTitleColor(.green, for: .selected)
btn.setTitleColor(.black, for: .highlighted)
btn.setTitle("5秒后无法点击", for: .normal)
btn.setTitle("现在无法点击", for: .selected)
btn.add(self, action: #selector(click))
btn.addTo(self.view)
JKAsyncs.asyncDelay(5, {
}) { [weak self] in
btn.isSelected(true)
guard let weakSelf = self else { return }
btn.remove(weakSelf, action: #selector(weakSelf.click))
JKAsyncs.asyncDelay(5, {
}) {
btn.removeFromSuperview()
}
}
}
}
| 32.811429 | 164 | 0.577325 |
da6ec1ed5f8ab9ba4a9bda6d9fff4f4d99d43e43 | 4,568 | lua | Lua | Data/Scripts/AI/SpaceMode/SpaceScout.lua | UEaWDevTeam/ultimate-empire-at-war | e6a874d6d7f2c84c4c4b2eb8e508d7fff8e645b9 | [
"CC-BY-3.0"
] | null | null | null | Data/Scripts/AI/SpaceMode/SpaceScout.lua | UEaWDevTeam/ultimate-empire-at-war | e6a874d6d7f2c84c4c4b2eb8e508d7fff8e645b9 | [
"CC-BY-3.0"
] | null | null | null | Data/Scripts/AI/SpaceMode/SpaceScout.lua | UEaWDevTeam/ultimate-empire-at-war | e6a874d6d7f2c84c4c4b2eb8e508d7fff8e645b9 | [
"CC-BY-3.0"
] | null | null | null | --[[
The contents of this file are subject to the Common Public Attribution
License Version 1.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://ultimate-empire-at-war.com/cpal. The License is based on the Mozilla
Public License Version 1.1 but Sections 14 and 15 have been added to cover
use of software over a computer network and provide for limited attribution
for the Original Developer. In addition, Exhibit A has been modified to be
consistent with Exhibit B.
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
The Original Code is Ultimate Empire at War.
The Original Developer is the Initial Developer. The Initial Developer of the
Original Code is the Ultimate Empire at War team. All portions of the code
written by the Ultimate Empire at War team are Copyright (c) 2012.
All Rights Reserved. ]]
-- $Id: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/SpaceMode/SpaceScout.lua#2 $
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- (C) Petroglyph Games, Inc.
--
--
-- ***** ** * *
-- * ** * * *
-- * * * * *
-- * * * * * * * *
-- * * *** ****** * ** **** *** * * * ***** * ***
-- * ** * * * ** * ** ** * * * * ** ** ** *
-- *** ***** * * * * * * * * ** * * * *
-- * * * * * * * * * * * * * * *
-- * * * * * * * * * * ** * * * *
-- * ** * * ** * ** * * ** * * * *
-- ** **** ** * **** ***** * ** *** * *
-- * * *
-- * * *
-- * * *
-- * * * *
-- **** * *
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
-- C O N F I D E N T I A L S O U R C E C O D E -- D O N O T D I S T R I B U T E
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- $File: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/SpaceMode/SpaceScout.lua $
--
-- Original Author: James Yarrow
--
-- $Author: James_Yarrow $
--
-- $Change: 44927 $
--
-- $DateTime: 2006/05/23 17:53:49 $
--
-- $Revision: #2 $
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
require("pgevents")
function Definitions()
Category = "Space_Scout"
IgnoreTarget = true
TaskForce =
{
{
"MainForce",
"Fighter | Corvette = 1"
}
}
end
function MainForce_Thread()
BlockOnCommand(MainForce.Produce_Force())
MainForce.Set_As_Goal_System_Removable(false)
QuickReinforce(PlayerObject, AITarget, MainForce)
MainForce.Activate_Ability("Turbo", true)
MainForce.Activate_Ability("SPOILER_LOCK", true)
Try_Ability(MainForce, "STEALTH")
-- Removing this loop to give other plans a chance. If the AI still wants to scout, the plan will be proposed again.
-- while AITarget do
if TestValid(AITarget) then
BlockOnCommand(MainForce.Move_To(AITarget))
MainForce.Set_As_Goal_System_Removable(true)
BlockOnCommand(MainForce.Explore_Area(AITarget), 10)
MainForce.Set_Plan_Result(true)
else
DebugMessage("%s -- Unable to find a target for MainForce.", tostring(Script))
end
-- AITarget = FindTarget(MainForce, "Space_Area_Needs_Scouting", "Tactical_Location", 0.8, 3000.0)
-- end
ScriptExit()
end
function MainForce_No_Units_Remaining()
DebugMessage("%s -- All units dead or non-buildable. Abandonning plan.", tostring(Script))
ScriptExit()
end
function MainForce_Target_Destroyed()
DebugMessage("%s -- Target destroyed! Exiting Script.", tostring(Script))
ScriptExit()
end | 40.070175 | 119 | 0.468914 |
85bc7d881eb880e0325f016a48abaf8b775e846d | 1,335 | js | JavaScript | back/model.js | tigran-bayburtsyan/oneday | e293b371c2f782468a7fde3e1ad9a0c9f51f1174 | [
"MIT"
] | null | null | null | back/model.js | tigran-bayburtsyan/oneday | e293b371c2f782468a7fde3e1ad9a0c9f51f1174 | [
"MIT"
] | null | null | null | back/model.js | tigran-bayburtsyan/oneday | e293b371c2f782468a7fde3e1ad9a0c9f51f1174 | [
"MIT"
] | null | null | null | /**
* Created by tigran on 7/20/15.
*/
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/oneday');
var Country = mongoose.model("Country", {
name: String,
code: String,
// TODO: Add some additional fields to describe country
});
var City = mongoose.model('City', {
short: String,
name: String,
latitude: Number,
longitude: Number,
country: { type: Schema.Types.ObjectId, ref: 'Country' }
});
var Token = mongoose.model('Token', {
social: String, // Name of social network: Using as a Key
token_data: Object // Custom data for specific social network
});
var SocialUser = mongoose.model("SocialUser", {
user_id: String, // User Social ID
username: String,
name: String, // First Name and Lats Name combination
photo: String, // Profile Photo URL
social_name: String, // Name for social network
url: String // Profile URL
});
var SocialPost = mongoose.model('SocialPost', {
content: String,
user: { type: Schema.Types.ObjectId, ref: 'SocialUser' },
city: { type: Schema.Types.ObjectId, ref: 'City' },
inserted: { type: Date, default: Date.now },
date: String,
post_id: String,
url: String,
image: String // Url of image in post
}); | 29.021739 | 67 | 0.629963 |
6b4a9769f89dda21439c6562f9a6ff41bc493c33 | 1,083 | htm | HTML | Teensy41/src/home.htm | lovettchris/SmartGarden | fd2e06102548ffeac80f8fc0dffc84767f778938 | [
"MIT"
] | null | null | null | Teensy41/src/home.htm | lovettchris/SmartGarden | fd2e06102548ffeac80f8fc0dffc84767f778938 | [
"MIT"
] | null | null | null | Teensy41/src/home.htm | lovettchris/SmartGarden | fd2e06102548ffeac80f8fc0dffc84767f778938 | [
"MIT"
] | null | null | null | <!DOCTYPE HTML>
<html>
<meta name='viewport' content='width=device-width, minimum-scale=1.0, maximum-scale=1.0' />
<style>
body { background-color: #1E1E1E; color: #D4D4D4;}
button { min-width:80px; min-height:30px; -webkit-appearence: button; padding: 5px;}
.big { font-size:48pt; border-style: solid; border-width: 1px; border-color: #D4D4D4; padding: 10px; }
</style>
<script>
function sendCommand(cmd) {
var xhr = new XMLHttpRequest();
xhr.open('GET', '/' + cmd, true);
xhr.onload = function(e) {
if (this.status == 200) {
document.getElementById('result').innerHTML = this.responseText;
}
};
xhr.send();
}
function read() { sendCommand('r'); }
function info() { sendCommand('i'); }
function status() { sendCommand('status'); }
</script>
<body>
<h1>Smart Garden</h1>
<span>
<button onclick='read()'>Read</button>
<button onclick='info()'>Info</button>
<button onclick='status()'>Status</button>
</span>
<br/><br/><br/>
<span class='big' id='result'>0.000</span>
</body>
<script>
window.addEventListener('load', read);
</script>
</html> | 27.075 | 102 | 0.65928 |
fb9f0cbbf4ae1ee8b360094ce052e1d339ad9b83 | 726 | lua | Lua | Script/Lua/ui/ui_util.lua | gitter-badger/ZeloEngine | 22a15783d58a9c1d5b2bad30d1544f13ac07ce2b | [
"MIT"
] | 98 | 2019-09-13T16:00:57.000Z | 2022-03-25T05:15:36.000Z | Script/Lua/ui/ui_util.lua | gitter-badger/ZeloEngine | 22a15783d58a9c1d5b2bad30d1544f13ac07ce2b | [
"MIT"
] | 269 | 2019-08-22T01:47:09.000Z | 2021-12-01T14:47:47.000Z | Script/Lua/ui/ui_util.lua | gitter-badger/ZeloEngine | 22a15783d58a9c1d5b2bad30d1544f13ac07ce2b | [
"MIT"
] | 5 | 2021-05-07T11:11:40.000Z | 2022-03-29T08:38:33.000Z | -- ui_util
-- created on 2021/8/24
-- author @zoloypzuo
function ParseFlags(enumTable, flag)
local names = {}
for name, val in pairs(enumTable) do
if bit.band(flag, val) ~= 0 then
names[#names + 1] = name
end
end
return names
end
function GenFlagFromTable(imguiFlags, setting, default)
if default then
-- use default
for k, v in pairs(default) do
if setting[k] ~= nil then
setting[k] = v
end
end
end
local flag = 0
for k, v in pairs(setting) do
assert(imguiFlags[k], "flag not exists")
if v then
flag = bit.bor(flag, imguiFlags[k])
end
end
return flag
end
| 22 | 55 | 0.553719 |
05abda051465ec58445bc5e8e24a49ef1f9be888 | 19 | asm | Assembly | src/main/fragment/mos6502-common/vwum1=vbuyy_word_vbuxx.asm | jbrandwood/kickc | d4b68806f84f8650d51b0e3ef254e40f38b0ffad | [
"MIT"
] | 2 | 2022-03-01T02:21:14.000Z | 2022-03-01T04:33:35.000Z | src/main/fragment/mos6502-common/vwum1=vbuyy_word_vbuxx.asm | jbrandwood/kickc | d4b68806f84f8650d51b0e3ef254e40f38b0ffad | [
"MIT"
] | null | null | null | src/main/fragment/mos6502-common/vwum1=vbuyy_word_vbuxx.asm | jbrandwood/kickc | d4b68806f84f8650d51b0e3ef254e40f38b0ffad | [
"MIT"
] | null | null | null | sty {m1}+1
stx {m1} | 9.5 | 10 | 0.578947 |
145c50978f8c398db72f002c4e688a61a40a0959 | 852 | swift | Swift | SmartColony/Nodes/TouchableSpriteNode.swift | mrommel/Colony | 7cd79957baffa56e098324eef7ed8a8bf6e33644 | [
"MIT"
] | 9 | 2020-03-10T05:22:09.000Z | 2022-02-08T09:53:43.000Z | SmartColony/Nodes/TouchableSpriteNode.swift | mrommel/Colony | 7cd79957baffa56e098324eef7ed8a8bf6e33644 | [
"MIT"
] | 117 | 2020-07-20T11:28:07.000Z | 2022-03-31T18:51:17.000Z | SmartColony/Nodes/TouchableSpriteNode.swift | mrommel/Colony | 7cd79957baffa56e098324eef7ed8a8bf6e33644 | [
"MIT"
] | null | null | null | //
// TouchableSpriteNode.swift
// SmartColony
//
// Created by Michael Rommel on 04.04.20.
// Copyright © 2020 Michael Rommel. All rights reserved.
//
import SpriteKit
protocol TouchableDelegate: class {
func clicked(on identifier: String)
}
class TouchableSpriteNode: SKSpriteNode {
var touchHandler: (() -> Void)?
weak var delegate: TouchableDelegate?
var identifier: String?
convenience init(imageNamed imageName: String, size: CGSize) {
let texture = SKTexture(imageNamed: imageName)
self.init(texture: texture, size: size)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let handler = self.touchHandler {
handler()
} else if let identifier = self.identifier {
self.delegate?.clicked(on: identifier)
}
}
}
| 23.666667 | 79 | 0.660798 |
134dfe2a918da567786cd48d5a70082588b58500 | 632 | c | C | C/myPrintf/mpfMain.c | afatom/core-program | 7886acf67f6b81bd06edef41f6ddab83cc993927 | [
"MIT"
] | null | null | null | C/myPrintf/mpfMain.c | afatom/core-program | 7886acf67f6b81bd06edef41f6ddab83cc993927 | [
"MIT"
] | null | null | null | C/myPrintf/mpfMain.c | afatom/core-program | 7886acf67f6b81bd06edef41f6ddab83cc993927 | [
"MIT"
] | null | null | null | #include "mpf.h"
#include <string.h> /*string manpulation functions*/
#include <stdio.h> /*puts func*/
#include <stdarg.h>
int main (int argc, char* argv[])
{
int numOfChars1, numOfChars2;
char str[7]="adham";
char sstr[25] = "C language Programming";
double f = 100000.212;
int x = 32;
numOfChars1 = MyPrintf("my name is %s and i love the %s and i am %d years old! i need %f ILS\t",str,sstr,x,f);
numOfChars2 = printf("my name is %s and i love the %s and i am %d years old! i need %f ILS\t", str, sstr, x, f);
printf("\nnum1 %d \nnum2 %d\n", numOfChars1, numOfChars2);
return 0;
} | 28.727273 | 116 | 0.620253 |
7ac5497bd1ad6150f8d0bf91764410a776e3f0a5 | 484 | rb | Ruby | test/helper.rb | h3h/serum | 119534c35569a209650ebf4dc2b9b3716571e4cb | [
"MIT"
] | 1 | 2015-01-30T16:36:18.000Z | 2015-01-30T16:36:18.000Z | test/helper.rb | h3h/serum | 119534c35569a209650ebf4dc2b9b3716571e4cb | [
"MIT"
] | null | null | null | test/helper.rb | h3h/serum | 119534c35569a209650ebf4dc2b9b3716571e4cb | [
"MIT"
] | null | null | null | require 'rubygems'
require 'test/unit'
require 'serum'
require 'redgreen' if RUBY_VERSION < '1.9'
require 'shoulda'
require 'rr'
include Serum
# Send STDERR into the void to suppress program output messages
STDERR.reopen(test(?e, '/dev/null') ? '/dev/null' : 'NUL:')
class Test::Unit::TestCase
include RR::Adapters::TestUnit
def source_dir(*subdirs)
test_dir('source', *subdirs)
end
def test_dir(*subdirs)
File.join(File.dirname(__FILE__), *subdirs)
end
end
| 17.925926 | 63 | 0.706612 |
4985fbb0b5241d37cf3127201ecb3628ed086786 | 1,356 | html | HTML | _jobs/other-teachers-and-instructors.html | LesterGallagher/salary-comparison | d6f7bba18575bc6b04c2eb1fe2245d3ec1f1015b | [
"CC-BY-4.0"
] | null | null | null | _jobs/other-teachers-and-instructors.html | LesterGallagher/salary-comparison | d6f7bba18575bc6b04c2eb1fe2245d3ec1f1015b | [
"CC-BY-4.0"
] | null | null | null | _jobs/other-teachers-and-instructors.html | LesterGallagher/salary-comparison | d6f7bba18575bc6b04c2eb1fe2245d3ec1f1015b | [
"CC-BY-4.0"
] | null | null | null | ---
occupation_code: 25-3000
occupation_title: Other Teachers and Instructors
level: minor
employment: 1,204,930
employment_rse: 0.9%
employment_per_jobs: "8.453"
median_hourly_wage: $15.60
mean_hourly_wage: $18.89
annual_mean_wage: $39,290
mean_wage_rse: 0.7%
parent:
title: Education, Training, and Library Occupations
slug: education-training-and-library-occupations
children:
- title: Adult Basic and Secondary Education and Literacy Teachers and Instructors
slug: adult-basic-and-secondary-education-and-literacy-teachers-and-instructors
- title: Self-Enrichment Education Teachers
slug: self-enrichment-education-teachers
- title: Miscellaneous Teachers and Instructors
slug: miscellaneous-teachers-and-instructors
parents:
- slug: other-teachers-and-instructors
title: Other Teachers and Instructors
- slug: education-training-and-library-occupations
title: Education, Training, and Library Occupations
- slug: all-occupations
title: All Occupations
slug: other-teachers-and-instructors
title: How much money do "Other Teachers and Instructors" make?
description: How much money do "Other Teachers and Instructors" make? The average pay for
"Other Teachers and Instructors" is $39,290 annually. There is an estimate of
1,204,930 "Other Teachers and Instructors" employed in the united states
alone.
---
| 37.666667 | 89 | 0.784661 |
9164bea21eba985dd79272b6ede26c125444d531 | 14,201 | html | HTML | 2-resources/BLOG/ciriculumn/Extra/html-files/media-queries.html | impastasyndrome/Lambda-Resource-Static-Assets | 7070672038620d29844991250f2476d0f1a60b0a | [
"MIT"
] | null | null | null | 2-resources/BLOG/ciriculumn/Extra/html-files/media-queries.html | impastasyndrome/Lambda-Resource-Static-Assets | 7070672038620d29844991250f2476d0f1a60b0a | [
"MIT"
] | null | null | null | 2-resources/BLOG/ciriculumn/Extra/html-files/media-queries.html | impastasyndrome/Lambda-Resource-Static-Assets | 7070672038620d29844991250f2476d0f1a60b0a | [
"MIT"
] | 1 | 2021-11-05T07:48:26.000Z | 2021-11-05T07:48:26.000Z | <h1 id="media-queries">Media Queries</h1>
<h3 id="projected-time">Projected Time</h3>
<p>45-60 minutes</p>
<ul>
<li>20-30 min interactive lesson</li>
<li>10-15 min for independent practice</li>
<li>20-30 min check for understanding</li>
</ul>
<h3 id="prerequisites">Prerequisites</h3>
<ul>
<li><a href="/web/html.md">HTML Lesson</a></li>
<li><a href="/web/css.md">CSS Lesson</a></li>
</ul>
<h3 id="motivation">Motivation</h3>
<ul>
<li>When websites need to change their design depending on whether they’re on a phone, tablet, or giant screen, they use media queries.</li>
<li>Media Queries make your website look more professional (and less 1995), and make you look css-savvy to employers.</li>
<li>It is simply an extra section added to your css file; the only challenge lies in visualizing what you want before you write your rule.</li>
</ul>
<p><strong>Which companies use media queries?</strong> Everyone. Some companies with very responsive sites are <a href="https://www.etsy.com/">Etsy</a> and <a href="http://www.hitachi.us/">Hitachi</a>.</p>
<h4 id="looking-at-an-example-website">Looking at an example website</h4>
<ul>
<li>Have you ever noticed that some websites change their design depending on whether they’re on a phone, tablet, or giant monitor?</li>
<li><strong>Go to bbc.com</strong> and see what happens when you change the window size.</li>
<li>What changes do you notice when the window widens and narrows? - Some sections are hidden or shown (like the article descriptions). - The same article links can be presented as images or text - Images are organized in grids, or take up the whole width of the window - The image sizes adjust as a percentage of the window, as opposed to a set number of pixels - BBC’s navigation bar options change</li>
</ul>
<h3 id="objectives">Objectives</h3>
<p><strong>Participants will be able to:</strong></p>
<ul>
<li>understand what media query parameters mean.</li>
<li>use min (minimum size and higher) and max (maximum size and lower) for query parameters.</li>
<li>understand that later styles will override styles earlier in the code</li>
<li>troubleshoot override issues</li>
</ul>
<h3 id="specific-things-to-learn">Specific Things to Learn</h3>
<ul>
<li>Practice implementing a Media Query</li>
<li>Practice using min and max width</li>
<li>Practice overriding styles and troubleshooting any unexpected overrides</li>
<li>Media Query Syntax</li>
</ul>
<h3 id="materials">Materials</h3>
<ul>
<li><a href="https://docs.google.com/presentation/d/1ANf64yQ_Nxtul45xofh8cpjWF23UM6c8m8kJQHQyx_Q/edit?usp=sharing">Media Query Lesson Slideshow</a></li>
<li><a href="https://youtu.be/2KL-z9A56SQ">5 min Video: What is a media query?</a></li>
<li><a href="https://youtu.be/4Av7ma4v46Y">15 min Video: https://www.youtube.com/watch?v=4Av7ma4v46Y</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries">MDN view on using media query</a></li>
</ul>
<h3 id="lesson-guided-practice">Lesson / Guided Practice</h3>
<h4 id="practice-implementing-a-media-query">Practice implementing a Media Query</h4>
<ol type="1">
<li>Create a very simple project, or follow along in an existing project.</li>
<li><p>Create an HTML file with a linked css file, a title, 3 images, and a paragraph like this:</p>
<pre><code><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="index.css">
<title></title>
</head>
<body>
<h1>Under the Sea</h1>
<p>
Halfbeak Blind shark, Australian herring filefish elver bent-tooth Russian sturgeon koi, mud cat; Celebes rainbowfish tilapia swordtail. Tang flagtail, pompano dolphinfish jewel tetra thornyhead; mako shark. Wallago hussar, longnose whiptail catfish, "scup, yellow perch cutthroat trout Blind shark driftwood catfish Atlantic cod Blenny river loach?" Splitfin rocket danio barbeled houndshark velvetfish sand tiger golden shiner cowfish snake mackerel, "baikal oilfish porgy fusilier fish creek chub mud catfish." Coelacanth bent-tooth spearfish: soapfish mahseer Russian sturgeon fire bar danio kelp perch. Blind goby shortnose greeneye Celebes rainbowfish bigmouth buffalo: yellowtail, earthworm eel ghost knifefish amur pike. Gray mullet aholehole steelhead Australasian salmon barfish Siamese fighting fish shortnose chimaera inanga yellow bass opaleye.
Leopard danio pencilsmelt thorny catfish razorfish boarfish barreleye, sand tiger. Walking catfish tailor--cuchia prickly shark chain pickerel Port Jackson shark sawtooth eel turkeyfish slimehead South American Lungfish torrent catfish. Ayu bull trout trumpeter; hussar, buri shad, lanternfish coolie loach, "mud cat: crappie pike eel; man-of-war fish." Shiner bamboo shark Black angelfish Rabbitfish Russian sturgeon coolie loach sablefish king-of-the-salmon. Brook lamprey Pacific herring prickly shark shiner sawtooth eel eel cod medaka. Redfish bala shark flounder, Old World knifefish Black prickleback large-eye bream. Long-whiskered catfish Manta Ray paradise fish deep sea smelt vendace skilfish sea raven brotula. Hagfish Long-finned sand diver tilefish knifefish Ganges shark New Zealand smelt."
</p>
<img src="humpback.jpg" alt="whale">
<img src="yellow-fish.jpg" alt="yellow fish">
<img src="red-fish.jpg" alt="red fish">
</body>
</html></code></pre></li>
<li><p>Create a CSS file, and style your images:</p>
<pre><code>img {
width: 32%
}</code></pre></li>
<li>Refresh your page, and then change the window width to see how the page is affected. (spoiler: all widths follow the same rules)
<ul>
<li>Default styles: - h1 and p are 100% width - Everything is left-aligned</li>
<li>Specified styles: - Each image is 32% of the window width in every case.</li>
</ul></li>
<li><p>Add a media query section:</p>
<div class="sourceCode" id="cb3"><pre class="sourceCode css"><code class="sourceCode css"><a class="sourceLine" id="cb3-1" title="1">img {</a>
<a class="sourceLine" id="cb3-2" title="2"> <span class="kw">width</span>: <span class="dv">32</span><span class="dt">%</span><span class="op">;</span></a>
<a class="sourceLine" id="cb3-3" title="3">}</a>
<a class="sourceLine" id="cb3-4" title="4"></a>
<a class="sourceLine" id="cb3-5" title="5"><span class="im">@media</span>() {</a>
<a class="sourceLine" id="cb3-6" title="6">}</a></code></pre></div></li>
<li><p>Give it the parameter of max-width: 1080px. That means from 0 to the max of 1080px window width, this rule will apply. Anything over 1080 will fall back to the rules before the media query.</p>
<div class="sourceCode" id="cb4"><pre class="sourceCode css"><code class="sourceCode css"><a class="sourceLine" id="cb4-1" title="1"><span class="im">@media</span> (<span class="kw">max-width</span>: <span class="dv">1080</span><span class="dt">px</span>) {</a>
<a class="sourceLine" id="cb4-2" title="2">}</a></code></pre></div></li>
<li><p>Let’s have the views less that 1080px wide show a full-width photo.</p>
<div class="sourceCode" id="cb5"><pre class="sourceCode css"><code class="sourceCode css"><a class="sourceLine" id="cb5-1" title="1"><span class="im">@media</span> (<span class="kw">max-width</span>: <span class="dv">1080</span><span class="dt">px</span>) {</a>
<a class="sourceLine" id="cb5-2" title="2"> img {</a>
<a class="sourceLine" id="cb5-3" title="3"> <span class="kw">width</span>: <span class="dv">100</span><span class="dt">%</span><span class="op">;</span></a>
<a class="sourceLine" id="cb5-4" title="4"> }</a>
<a class="sourceLine" id="cb5-5" title="5">}</a></code></pre></div></li>
<li>Refresh your webpage and change the width to see your media query in action!</li>
<li><p>See the dimensions of your window by pressing <em>command+option+i</em>. Keep an eye on the upper right of your window as you change its width and a little dimensions box should appear.</p>
<h4 id="min-v-max-width">min v max width</h4></li>
<li>OK, we got to try “max-width”, now let’s experiment with min-width. Since we have everything 1080px width and less specified, we’ll add something crazy for “min-width: 1081px”, that is, everything 1081px and wider. <code>css @media (max-width: 1080px) { img { width: 100%; } } @media (min-width: 1081px) { body { background-color: red; } }</code></li>
<li><p>Save and change your html page window width again to see your red background at 1081px and wider.</p>
<h4 id="overriding">Overriding</h4></li>
<li><p>Add another media query after your red one, but make the background green starting at min-width: 1200px.</p>
<div class="sourceCode" id="cb6"><pre class="sourceCode css"><code class="sourceCode css"><a class="sourceLine" id="cb6-1" title="1"><span class="im">@media</span> (<span class="kw">min-width</span>: <span class="dv">1081</span><span class="dt">px</span>) {</a>
<a class="sourceLine" id="cb6-2" title="2"> body {</a>
<a class="sourceLine" id="cb6-3" title="3"> <span class="kw">background-color</span>: <span class="cn">red</span><span class="op">;</span></a>
<a class="sourceLine" id="cb6-4" title="4"> }</a>
<a class="sourceLine" id="cb6-5" title="5">}</a>
<a class="sourceLine" id="cb6-6" title="6"><span class="im">@media</span> (<span class="kw">min-width</span>: <span class="dv">1200</span><span class="dt">px</span>) {</a>
<a class="sourceLine" id="cb6-7" title="7"> body {</a>
<a class="sourceLine" id="cb6-8" title="8"> <span class="kw">background-color</span>: <span class="cn">green</span><span class="op">;</span></a>
<a class="sourceLine" id="cb6-9" title="9"> }</a>
<a class="sourceLine" id="cb6-10" title="10">}</a></code></pre></div></li>
<li>Refresh you webpage and change the width to see your new styles. You should see:
<ul>
<li>widths 0 - 1080 have a default white background</li>
<li>widths 1081-1199 have a red background</li>
<li>1200 and over has a green background, since this style starts to override the red rule after 1200px.</li>
</ul></li>
<li><p>Next, highlight that 1200 media query, hold <em>command+ctrl</em>, and use the up arrow to move it before the 1081 rule. Refresh and try your webpage now.</p>
<div class="sourceCode" id="cb7"><pre class="sourceCode css"><code class="sourceCode css"><a class="sourceLine" id="cb7-1" title="1"><span class="im">@media</span> (<span class="kw">min-width</span>: <span class="dv">1200</span><span class="dt">px</span>) {</a>
<a class="sourceLine" id="cb7-2" title="2"> body {</a>
<a class="sourceLine" id="cb7-3" title="3"> <span class="kw">background-color</span>: <span class="cn">green</span><span class="op">;</span></a>
<a class="sourceLine" id="cb7-4" title="4"> }</a>
<a class="sourceLine" id="cb7-5" title="5">}</a>
<a class="sourceLine" id="cb7-6" title="6"><span class="im">@media</span> (<span class="kw">min-width</span>: <span class="dv">1081</span><span class="dt">px</span>) {</a>
<a class="sourceLine" id="cb7-7" title="7"> body {</a>
<a class="sourceLine" id="cb7-8" title="8"> <span class="kw">background-color</span>: <span class="cn">red</span><span class="op">;</span></a>
<a class="sourceLine" id="cb7-9" title="9"> }</a>
<a class="sourceLine" id="cb7-10" title="10">}</a></code></pre></div>
<ul>
<li>The green media query no longer applies because styles that come after will override any styles that come earlier in the css file. The red rule is applying to <em>everything</em> wider than 1081px, including 1200px and up.</li>
<li>The browser reads css and js from top to bottom, so if it applies different styles to the same screen width, <em>the one that is applied last wins</em>.</li>
<li>When the media query styles you expect are not appearing, overriding is a common culprit.</li>
</ul></li>
<li>Practice now by going to your site window. Press <em>command+option+i</em> to open the inspector to check out what styles are being applied in the <em>Elements</em> tab. The green rule is not being applied.</li>
<li><p>Click the ‘index.css:’ link by your style to see where the rule being followed is in your code. This should take you to to <em>Sources</em> tab, and show you which line it’s on.</p></li>
</ol>
<h4 id="media-query-syntax">Media Query Syntax</h4>
<ul>
<li>Last but not least, let’s look at media query syntax options. Check out the <strong>CSS Syntax</strong> and <strong>Media Types</strong> sections at <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries#Syntax">the developer.mozilla.org media query reference guide.</a></li>
<li>You will most likely see this syntax in css files for compatibility with old browsers: <code>css @media only screen and () { }</code></li>
<li>Remember, you can put anything in your media queries that you can put into CSS.</li>
</ul>
<h3 id="independent-practice">Independent Practice</h3>
<ul>
<li>add 3 more experimental media queries, each with a different width and a different class or element being styled. Change your window width and see if they appear when expected.</li>
</ul>
<h3 id="challenge">Challenge</h3>
<ol type="1">
<li>Pair up with a peer and discuss what changes you would like to make to your recipe page project using media queries. Be specific about which widths you would like to use, which elements you’d change. Sketch your ideas to help you remember.</li>
<li>Spend about 20 minutes applying your media queries to your recipe page!</li>
</ol>
<h3 id="check-for-understanding">Check for Understanding</h3>
<p>Form small groups and discuss:</p>
<ul>
<li>When should you use max and min query parameters?</li>
<li>If you had a style <code>body {color: red}</code> on line 5, and <code>body {color: green}</code> on line 6, what color would the text be when the window is 700px wide?</li>
<li>If you had a regular style body <code>{color: red} on line 5</code>, and the media query <code>@media only screen and (min-width: 600px) {color: blue}</code> on line 6, what color would the text be when the window is 700px wide? What color would it be at 500px wide? 600px wide?</li>
</ul>
| 88.204969 | 883 | 0.715372 |
0f00d32165a03e49168ca5bc94cab3adc32fe0be | 193 | kt | Kotlin | app/src/main/java/io/redgreen/benchpress/hellostranger/HelloStrangerEvent.kt | Aryan210/bench-mark | 51335bba348794403cca58d0aa9bcea224daeb8b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/io/redgreen/benchpress/hellostranger/HelloStrangerEvent.kt | Aryan210/bench-mark | 51335bba348794403cca58d0aa9bcea224daeb8b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/io/redgreen/benchpress/hellostranger/HelloStrangerEvent.kt | Aryan210/bench-mark | 51335bba348794403cca58d0aa9bcea224daeb8b | [
"Apache-2.0"
] | null | null | null | package io.redgreen.benchpress.hellostranger
sealed class HelloStrangerEvent
data class EnterNameEvent(val name : String) : HelloStrangerEvent()
object DeleteNameEvent : HelloStrangerEvent() | 27.571429 | 67 | 0.839378 |
899378847bf54d999d34bb903918bfc0fd073207 | 1,182 | kt | Kotlin | app/src/main/java/com/gram/pictory/adapter/FeedAdapter.kt | notmyfault02/Pictory_Master | 503ee703d906ee61c90ac737f3cfad86d662c20d | [
"MIT"
] | 1 | 2019-10-25T10:41:07.000Z | 2019-10-25T10:41:07.000Z | app/src/main/java/com/gram/pictory/adapter/FeedAdapter.kt | notmyfault02/Pictory_Master | 503ee703d906ee61c90ac737f3cfad86d662c20d | [
"MIT"
] | 1 | 2019-06-11T16:43:26.000Z | 2019-09-14T14:17:38.000Z | app/src/main/java/com/gram/pictory/adapter/FeedAdapter.kt | notmyfault02/Pictory_Master | 503ee703d906ee61c90ac737f3cfad86d662c20d | [
"MIT"
] | 1 | 2019-05-09T12:49:02.000Z | 2019-05-09T12:49:02.000Z | package com.gram.pictory.adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.gram.pictory.databinding.ItemFeedRecyclerviewBinding
import com.gram.pictory.model.FeedModel
import com.gram.pictory.ui.main.feed.FeedViewModel
class FeedAdapter(val viewModel: FeedViewModel) : RecyclerView.Adapter<FeedAdapter.FeedViewHolder>() {
var item = arrayListOf<FeedModel>()
set(value) {
field = value
notifyDataSetChanged()
}
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): FeedViewHolder {
val binding = ItemFeedRecyclerviewBinding.inflate(LayoutInflater.from(p0.context), p0, false)
return FeedViewHolder(binding)
}
override fun getItemCount(): Int = item.size
override fun onBindViewHolder(p0: FeedViewHolder, p1: Int) = p0.bind()
inner class FeedViewHolder(val binding: ItemFeedRecyclerviewBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind() {
binding.index = adapterPosition
binding.viewModel = viewModel
binding.feedModel = item[adapterPosition]
}
}
} | 35.818182 | 114 | 0.71912 |
ddb950564ba8cec4ae1bee6e2b75c4776c2173e9 | 816 | php | PHP | resources/views/home.blade.php | FSPZ/Perpustakaan | 9dfa5975f321eb826d9457e8c6e3c106bb34016b | [
"MIT"
] | null | null | null | resources/views/home.blade.php | FSPZ/Perpustakaan | 9dfa5975f321eb826d9457e8c6e3c106bb34016b | [
"MIT"
] | null | null | null | resources/views/home.blade.php | FSPZ/Perpustakaan | 9dfa5975f321eb826d9457e8c6e3c106bb34016b | [
"MIT"
] | null | null | null | @extends('layouts.app')
@section('content')
<div class="home">
<style>
html, body {
background-image: url("https://static.republika.co.id/uploads/images/inpicture_slide/buku_200723162025-452.jpg");
background-size: 100% 100%;
color: #636b6f;
font-family: 'Nunito', sans-serif;
font-weight: 200;
height: 100vh;
margin: 0;
}
p {
font-size:60px;
font-family: Garamond;
color:black;
text-align: right;
}
</style>
<b><p>A room without books is like <br> a body without a soul.
Life without <br> books is like a dark room without lights.</p></b>
@endsection
| 30.222222 | 129 | 0.487745 |
43b2e56bbae6502f8a13955cb8f81b67784090a5 | 1,495 | go | Go | test/e2e/controller_plugins_test.go | hcp-sre-cq/argo-workflows | 2680956ffc06404988dce3cc9307c725a5609eed | [
"Apache-2.0"
] | null | null | null | test/e2e/controller_plugins_test.go | hcp-sre-cq/argo-workflows | 2680956ffc06404988dce3cc9307c725a5609eed | [
"Apache-2.0"
] | null | null | null | test/e2e/controller_plugins_test.go | hcp-sre-cq/argo-workflows | 2680956ffc06404988dce3cc9307c725a5609eed | [
"Apache-2.0"
] | null | null | null | //go:build plugins
// +build plugins
package e2e
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
wfv1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
"github.com/argoproj/argo-workflows/v3/test/e2e/fixtures"
)
type ControllerPluginsSuite struct {
fixtures.E2ESuite
}
func (s *ControllerPluginsSuite) TestParameterSubstitutionPlugin() {
s.Given().
Workflow("@testdata/plugins/controller/params-workflow.yaml").
When().
SubmitWorkflow().
WaitForWorkflow(fixtures.ToBeSucceeded)
}
func (s *ControllerPluginsSuite) TestWorkflowLifecycleHook() {
s.Given().
Workflow("@testdata/plugins/controller/workflow-lifecycle-hook-workflow.yaml").
When().
SubmitWorkflow().
WaitForWorkflow(fixtures.ToBeSucceeded).
Then().
ExpectWorkflow(func(t *testing.T, md *metav1.ObjectMeta, _ *wfv1.WorkflowStatus) {
assert.Equal(t, "good morning", md.Annotations["hello"])
})
}
func (s *ControllerPluginsSuite) TestNodeLifecycleHook() {
s.Given().
Workflow("@testdata/plugins/controller/controller-plugin-template-workflow.yaml").
When().
SubmitWorkflow().
WaitForWorkflow(fixtures.ToBeSucceeded).
Then().
ExpectWorkflow(func(t *testing.T, md *metav1.ObjectMeta, s *wfv1.WorkflowStatus) {
n := s.Nodes[md.Name]
assert.Contains(t, n.Message, "Hello")
})
}
func TestControllerPluginsSuite(t *testing.T) {
suite.Run(t, new(ControllerPluginsSuite))
}
| 26.22807 | 84 | 0.744482 |
0c4e89cc27333630ebd2fa00c3198a2cb03eba20 | 667 | lua | Lua | resources/[qb]/qb-policejob/fxmanifest.lua | p4zinee/server-data | b523650fc4b5a3465c7ffc1dde7330a16bb62d05 | [
"CC0-1.0"
] | 1 | 2022-01-05T15:17:06.000Z | 2022-01-05T15:17:06.000Z | resources/[qb]/qb-policejob/fxmanifest.lua | p4zinee/server-data | b523650fc4b5a3465c7ffc1dde7330a16bb62d05 | [
"CC0-1.0"
] | null | null | null | resources/[qb]/qb-policejob/fxmanifest.lua | p4zinee/server-data | b523650fc4b5a3465c7ffc1dde7330a16bb62d05 | [
"CC0-1.0"
] | null | null | null | fx_version 'cerulean'
game 'gta5'
description 'QB-PoliceJob'
version '1.0.0'
shared_script {
'config.lua',
'@qb-core/import.lua'
}
client_scripts {
'client/main.lua',
'client/camera.lua',
'client/interactions.lua',
'client/job.lua',
'client/gui.lua',
'client/heli.lua',
--'client/anpr.lua',
'client/evidence.lua',
'client/objects.lua',
'client/tracker.lua'
}
server_script 'server/main.lua'
ui_page 'html/index.html'
files {
'html/index.html',
'html/vue.min.js',
'html/script.js',
'html/tablet-frame.png',
'html/fingerprint.png',
'html/main.css',
'html/vcr-ocd.ttf'
}
exports {
'IsHandcuffed',
'IsArmoryWhitelist'
}
dependency 'qb-core'
| 14.822222 | 31 | 0.685157 |
2c7bb952966b2a8c8b9472d9920de28bbc6a5c8c | 135 | swift | Swift | first_project/Model/User.swift | tk-daisuke/swift_ui_halloworld | 301559244f9b75f174bede4e76d0487d85dd2929 | [
"MIT"
] | null | null | null | first_project/Model/User.swift | tk-daisuke/swift_ui_halloworld | 301559244f9b75f174bede4e76d0487d85dd2929 | [
"MIT"
] | null | null | null | first_project/Model/User.swift | tk-daisuke/swift_ui_halloworld | 301559244f9b75f174bede4e76d0487d85dd2929 | [
"MIT"
] | null | null | null | //
// User.swift
// first_project
//
// Created by 佐藤 大輔 on 2021/12/19.
//
import Foundation
struct User {
var name: String
}
| 10.384615 | 35 | 0.622222 |
5fd91b1892045b15c4b50961dfd43ffc9c045864 | 311 | sql | SQL | src/main/resources/db/migration/V06__create_bloqueio.sql | MarciaMartins/orange-talents-06-template-proposta | 3c979e32eb9fd4c5e608d0d679b38429b75cea73 | [
"Apache-2.0"
] | 1 | 2021-07-23T22:10:53.000Z | 2021-07-23T22:10:53.000Z | src/main/resources/db/migration/V06__create_bloqueio.sql | MarciaMartins/orange-talents-06-template-proposta | 3c979e32eb9fd4c5e608d0d679b38429b75cea73 | [
"Apache-2.0"
] | null | null | null | src/main/resources/db/migration/V06__create_bloqueio.sql | MarciaMartins/orange-talents-06-template-proposta | 3c979e32eb9fd4c5e608d0d679b38429b75cea73 | [
"Apache-2.0"
] | null | null | null | CREATE TABLE bloqueio(
id BIGINT(20) PRIMARY KEY AUTO_INCREMENT,
codigo_proposta BIGINT(20),
IP VARCHAR(200),
criacao datetime not null
) ENGINE=InnoDB DEFAULT charset=utf8;
ALTER TABLE `bloqueio` ADD CONSTRAINT `fk_codigo_cartao_bloqueio` FOREIGN KEY ( `codigo_proposta` )
REFERENCES `proposta` ( `id` ); | 34.555556 | 100 | 0.77492 |
1691d954564578a88feede8aeb8fdc164034aa47 | 533 | ts | TypeScript | src/AppModule/app.module.ts | HelloThien/DADN | e8d2ef1d5deb5df902f311060feff8752b520e9f | [
"MIT"
] | null | null | null | src/AppModule/app.module.ts | HelloThien/DADN | e8d2ef1d5deb5df902f311060feff8752b520e9f | [
"MIT"
] | null | null | null | src/AppModule/app.module.ts | HelloThien/DADN | e8d2ef1d5deb5df902f311060feff8752b520e9f | [
"MIT"
] | null | null | null | import { MongoModule } from '../mongo';
import { Module } from '@nestjs/common';
import { AppController } from './controllers';
import { AppService } from './services'
import { CommonModule } from '../common';
import { MQTTModule } from '../mqtt';
import { AppRepository } from './repositories';
import { AuthModule } from './auth';
@Module({
imports: [CommonModule, MongoModule, MQTTModule, AuthModule],
controllers: [...AppController],
providers: [...AppService, ...AppRepository],
})
export class AppModule {}
| 35.533333 | 64 | 0.673546 |
70f38a7244641bfb5ab49cd2619d66bc39dd7284 | 830 | go | Go | 092.reverse-linked-list-ii/solution.go | ZacharyChang/leetcode | 82090587c7b9a943989e1a8120d46057583d5b7f | [
"MIT"
] | 1 | 2018-03-14T12:38:00.000Z | 2018-03-14T12:38:00.000Z | 092.reverse-linked-list-ii/solution.go | ZacharyChang/leetcode | 82090587c7b9a943989e1a8120d46057583d5b7f | [
"MIT"
] | 2 | 2020-03-09T02:46:02.000Z | 2022-02-11T03:02:00.000Z | 092.reverse-linked-list-ii/solution.go | ZacharyChang/leetcode | 82090587c7b9a943989e1a8120d46057583d5b7f | [
"MIT"
] | null | null | null | package leetcode
/**
* Definition for singly-linked list.
*
*/
type ListNode struct {
Val int
Next *ListNode
}
func reverseBetween(head *ListNode, m int, n int) *ListNode {
if m == n {
return head
}
count := 0
cur := head
var start, end, pre, after *ListNode
for cur != nil {
count++
if count < m {
pre = cur
} else if count == m {
start = cur
}
if count == n {
end = cur
after = end.Next
}
cur = cur.Next
}
if m == 1 {
end.Next = nil
reverseList(head)
start.Next = after
return end
}
end.Next = nil
pre.Next = reverseList(start)
start.Next = after
return head
}
// Recursion
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
next := head.Next
list := reverseList(next)
next.Next = head
head.Next = nil
return list
}
| 15.090909 | 61 | 0.615663 |
a189ab0a9a5289071c297e46006d8d454e4b98aa | 2,862 | asm | Assembly | programs/oeis/214/A214944.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/214/A214944.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | programs/oeis/214/A214944.asm | karttu/loda | 9c3b0fc57b810302220c044a9d17db733c76a598 | [
"Apache-2.0"
] | null | null | null | ; A214944: Number of squarefree words of length 5 in an (n+1)-ary alphabet.
; 0,30,264,1140,3480,8610,18480,35784,64080,107910,172920,265980,395304,570570,803040,1105680,1493280,1982574,2592360,3343620,4259640,5366130,6691344,8266200,10124400,12302550,14840280,17780364,21168840,25055130,29492160,34536480,40248384,46692030,53935560,62051220,71115480,81209154,92417520,104830440,118542480,133653030,150266424,168492060,188444520,210243690,234014880,259888944,288002400,318497550,351522600,387231780,425785464,467350290,512099280,560211960,611874480,667279734,726627480,790124460,857984520,930428730,1007685504,1089990720,1177587840,1270728030,1369670280,1474681524,1586036760,1704019170,1828920240,1961039880,2100686544,2248177350,2403838200,2568003900,2741018280,2923234314,3115014240,3316729680,3528761760,3751501230,3985348584,4230714180,4488018360,4757691570,5040174480,5335918104,5645383920,5969043990,6307381080,6660888780,7030071624,7415445210,7817536320,8236883040,8674034880,9129552894,9604009800,10097990100,10612090200,11146918530,11703095664,12281254440,12882040080,13506110310,14154135480,14826798684,15524795880,16248836010,16999641120,17777946480,18584500704,19420065870,20285417640,21181345380,22108652280,23068155474,24060686160,25087089720,26148225840,27244968630,28378206744,29548843500,30757797000,32006000250,33294401280,34623963264,35995664640,37410499230,38869476360,40373620980,41923973784,43521591330,45167546160,46862926920,48608838480,50406402054,52256755320,54161052540,56120464680,58136179530,60209401824,62341353360,64533273120,66786417390,69102059880,71481491844,73926022200,76436977650,79015702800,81663560280,84381930864,87172213590,90035825880,92974203660,95988801480,99081092634,102252569280,105504742560,108839142720,112257319230,115760840904,119351296020,123030292440,126799457730,130660439280,134614904424,138664540560,142811055270,147056176440,151401652380,155849251944,160400764650,165058000800,169822791600,174696989280,179682467214,184781120040,189994863780,195325635960,200775395730,206346123984,212039823480,217858518960,223804257270,229879107480,236085161004,242424531720,248899356090,255511793280,262264025280,269158257024,276196716510,283381654920,290715346740,298200089880,305838205794,313632039600,321583960200,329696360400,337971657030,346412291064,355020727740,363799456680,372750992010,381877872480,391182661584,400667947680,410336344110
mov $1,$0
mul $1,2
mov $3,$0
mov $4,$0
mov $6,$0
lpb $3,1
sub $3,1
add $5,$6
lpe
mov $2,9
mov $6,$5
lpb $2,1
add $1,$6
sub $2,1
lpe
mov $3,$4
mov $5,0
lpb $3,1
sub $3,1
add $5,$6
lpe
mov $2,12
mov $6,$5
lpb $2,1
add $1,$6
sub $2,1
lpe
mov $3,$4
mov $5,0
lpb $3,1
sub $3,1
add $5,$6
lpe
mov $2,6
mov $6,$5
lpb $2,1
add $1,$6
sub $2,1
lpe
mov $3,$4
mov $5,0
lpb $3,1
sub $3,1
add $5,$6
lpe
mov $2,1
mov $6,$5
lpb $2,1
add $1,$6
sub $2,1
lpe
| 52.036364 | 2,313 | 0.837876 |
fb6d1ec77614013dda226744412a80ebcbe903c6 | 268 | java | Java | leylines/src/main/java/oxy/leylines/item/ItemMaterial.java | oxyCabhru/leylines | 44dfc5fce5d7c9ec715db2e3684b8b768d457e02 | [
"MIT"
] | null | null | null | leylines/src/main/java/oxy/leylines/item/ItemMaterial.java | oxyCabhru/leylines | 44dfc5fce5d7c9ec715db2e3684b8b768d457e02 | [
"MIT"
] | null | null | null | leylines/src/main/java/oxy/leylines/item/ItemMaterial.java | oxyCabhru/leylines | 44dfc5fce5d7c9ec715db2e3684b8b768d457e02 | [
"MIT"
] | null | null | null | package oxy.leylines.item;
public class ItemMaterial extends ItemBase {
private String name; private final double source = 100;
public ItemMaterial(String name) {
super(name);
}
public double getSource() {
return this.source;
}
}
| 20.615385 | 59 | 0.664179 |