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
36bdfd62e0bd6436c89e7552ea40e00fc636b668
1,164
swift
Swift
SearchController/SearchController/DetailViewController.swift
victorchee/SearchController
6364714344090832823ae6572f741030d3249929
[ "MIT" ]
null
null
null
SearchController/SearchController/DetailViewController.swift
victorchee/SearchController
6364714344090832823ae6572f741030d3249929
[ "MIT" ]
null
null
null
SearchController/SearchController/DetailViewController.swift
victorchee/SearchController
6364714344090832823ae6572f741030d3249929
[ "MIT" ]
null
null
null
// // DetailViewController.swift // SearchController // // Created by qihaijun on 1/8/16. // Copyright © 2016 VictorChee. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var detailDescriptionLabel: UILabel! @IBOutlet weak var imageView: UIImageView! var detailItem: Candy? { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. if let detail = self.detailItem { if let label = self.detailDescriptionLabel, let imageView = imageView { label.text = detail.name imageView.image = UIImage(named: detail.name) title = detail.category } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
24.765957
83
0.613402
2627de2ef3a5f8b1a57283c32f3330c923c8a068
297
java
Java
src/com/example/zhbj/global/GlobalConstants.java
SunshineXyq/wisdombj
f0c2320ea62016c4e8c8cd2b9244efad7da0dc9b
[ "Apache-2.0" ]
null
null
null
src/com/example/zhbj/global/GlobalConstants.java
SunshineXyq/wisdombj
f0c2320ea62016c4e8c8cd2b9244efad7da0dc9b
[ "Apache-2.0" ]
null
null
null
src/com/example/zhbj/global/GlobalConstants.java
SunshineXyq/wisdombj
f0c2320ea62016c4e8c8cd2b9244efad7da0dc9b
[ "Apache-2.0" ]
null
null
null
package com.example.zhbj.global; public class GlobalConstants { // public static final String SERVER_URL = "http://zhihuibj.sinaapp.com/zhbj"; public static final String SERVER_URL = "http://192.168.191.1:8080/zhbj"; public static final String CATEGORY_URL = SERVER_URL + "/categories.json"; }
37.125
78
0.760943
9842b811a9765bd83310449af9088d4a5c154b37
330
sql
SQL
backend/de.metas.swat/de.metas.swat.base/src/main/sql/postgresql/system/40-sw01_swat/5485020_sys_gh3409_IsCreateDistributionOrder_ProductPlanningSchema_DDL.sql
dram/metasfresh
a1b881a5b7df8b108d4c4ac03082b72c323873eb
[ "RSA-MD" ]
1,144
2016-02-14T10:29:35.000Z
2022-03-30T09:50:41.000Z
backend/de.metas.swat/de.metas.swat.base/src/main/sql/postgresql/system/40-sw01_swat/5485020_sys_gh3409_IsCreateDistributionOrder_ProductPlanningSchema_DDL.sql
vestigegroup/metasfresh
4b2d48c091fb2a73e6f186260a06c715f5e2fe96
[ "RSA-MD" ]
8,283
2016-04-28T17:41:34.000Z
2022-03-30T13:30:12.000Z
backend/de.metas.swat/de.metas.swat.base/src/main/sql/postgresql/system/40-sw01_swat/5485020_sys_gh3409_IsCreateDistributionOrder_ProductPlanningSchema_DDL.sql
vestigegroup/metasfresh
4b2d48c091fb2a73e6f186260a06c715f5e2fe96
[ "RSA-MD" ]
441
2016-04-29T08:06:07.000Z
2022-03-28T06:09:56.000Z
-- 2018-02-09T15:23:16.491 -- I forgot to set the DICTIONARY_ID_COMMENTS System Configurator /* DDL */ SELECT public.db_alter_table('M_Product_PlanningSchema','ALTER TABLE public.M_Product_PlanningSchema ADD COLUMN IsCreateDistributionOrder CHAR(1) DEFAULT ''N'' CHECK (IsCreateDistributionOrder IN (''Y'',''N'')) NOT NULL') ;
41.25
231
0.769697
74672592a99f82fa0084edcd5e209be22c21a319
171
h
C
Kernel/include/idtLoader.h
apodgornyitba/TPE-Arqui
07213657de67bcfb8f83befa28fbc89641eabb41
[ "BSD-3-Clause" ]
null
null
null
Kernel/include/idtLoader.h
apodgornyitba/TPE-Arqui
07213657de67bcfb8f83befa28fbc89641eabb41
[ "BSD-3-Clause" ]
null
null
null
Kernel/include/idtLoader.h
apodgornyitba/TPE-Arqui
07213657de67bcfb8f83befa28fbc89641eabb41
[ "BSD-3-Clause" ]
null
null
null
#ifndef IDTLOADER_H #define IDTLOADER_H #include <lib.h> #include <defs.h> #include <naiveConsole.h> #include <stdint.h> #include <interrupts.h> void load_idt(); #endif
14.25
25
0.736842
ba0f9dd5b9f9d19aaef66241f3f7894dd0904d08
1,128
dart
Dart
lib/app/home_page.dart
Jictyvoo/TallyCounterFlutter
96e1a0712d62448ec433ea3ff3e933361d1e5873
[ "MIT" ]
null
null
null
lib/app/home_page.dart
Jictyvoo/TallyCounterFlutter
96e1a0712d62448ec433ea3ff3e933361d1e5873
[ "MIT" ]
null
null
null
lib/app/home_page.dart
Jictyvoo/TallyCounterFlutter
96e1a0712d62448ec433ea3ff3e933361d1e5873
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:flutter_modular/flutter_modular.dart'; import 'package:tally_counter/app/shared/routes.dart'; import 'pages/counter/counter_page.dart'; import 'shared/widgets/popup_trailing.dart'; class HomePage extends StatefulWidget { const HomePage({Key? key, required this.title}) : super(key: key); final String title; @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), actions: [ PopupTrailing( onTap: (options) { if (options == PopupOptions.showAll) { Modular.to.pushNamed(AppRoutes.REGISTER_LIST.route); } else { Modular.to.pushNamed( AppRoutes.REGISTER_LIST.route, arguments: DateTime.now(), ); } }, ) ], ), body: const Center( child: CounterPage(), ), ); } }
25.636364
68
0.590426
5dd2fff2624467ca6b633964751700a65c686608
476
dart
Dart
lib/src/layout.dart
mariposa-dart/material
283200a52dd00b9a834531a69393af644117c268
[ "MIT" ]
2
2018-06-18T05:06:29.000Z
2018-06-28T15:01:33.000Z
lib/src/layout.dart
mariposa-dart/material
283200a52dd00b9a834531a69393af644117c268
[ "MIT" ]
2
2017-04-04T10:24:29.000Z
2018-08-31T14:39:50.000Z
lib/src/layout.dart
mariposa-dart/material
283200a52dd00b9a834531a69393af644117c268
[ "MIT" ]
null
null
null
import 'package:mariposa/mariposa.dart'; import 'widget.dart'; /* class Layout extends MaterialWidget { final bool fixedHeader; Layout({this.fixedHeader: true}); @override Node render() { return h( 'div', { 'class': [ 'mdl-layout', 'mdl-js-layout', fixedHeader ? 'mdl-layout--fixed-header' : null ].where((clazz) => clazz?.isNotEmpty == true).toList() }, content); } } */
19.833333
64
0.537815
2f667161ba85fe7fcff1bd4bf0d5b7174080cc02
178
php
PHP
chap10/HetareBusinessPerson.php
mryshk/basic-training-at_PHP
c328f1ac5b45f528c4fd276a3da8bd9dd6990e9b
[ "MIT" ]
null
null
null
chap10/HetareBusinessPerson.php
mryshk/basic-training-at_PHP
c328f1ac5b45f528c4fd276a3da8bd9dd6990e9b
[ "MIT" ]
null
null
null
chap10/HetareBusinessPerson.php
mryshk/basic-training-at_PHP
c328f1ac5b45f528c4fd276a3da8bd9dd6990e9b
[ "MIT" ]
null
null
null
<?php require_once 'BusinessPerson.php'; class HetareBusinessPerson extends BusinessPerson { public function work() : void { parent::work(); print 'ただし、ボチボチと…'; } }
17.8
51
0.691011
26346016b98592b9e7a98d7e9cbab40f141ed70d
3,435
dart
Dart
lib/templates/rdf-project/lib/src/project/view/element/navigation_sidebar.dart
acanvas/acanvas-generator
05dbf5a7639e946680dfc5572d32a0fa19d66745
[ "BSD-3-Clause" ]
9
2018-09-18T08:19:49.000Z
2020-09-10T03:33:36.000Z
lib/templates/rdf-project/lib/src/project/view/element/navigation_sidebar.dart
block-forest/rockdot-generator
05dbf5a7639e946680dfc5572d32a0fa19d66745
[ "BSD-3-Clause" ]
null
null
null
lib/templates/rdf-project/lib/src/project/view/element/navigation_sidebar.dart
block-forest/rockdot-generator
05dbf5a7639e946680dfc5572d32a0fa19d66745
[ "BSD-3-Clause" ]
1
2020-07-27T01:02:05.000Z
2020-07-27T01:02:05.000Z
part of acanvas_template; /** * @author Nils Doehring (nilsdoehring(gmail as at).com) */ class NavigationSidebar extends AcanvasLifecycleSprite implements IStateModelAware { StateModel _stateModel; ImageSprite _logo; MdMenu _itemList; MdMenu _subList; bool _blockSelectionByAddressCallback = false; SelectableButton _selectedCell; NavigationSidebar(String id) : super(id) { inheritSpan = true; } @override void init({Map<String, String> params: null}) { super.init(params: params); _logo = new ImageSprite() ..bitmapData = Assets.acanvas_logotype_white ..inheritSpan = false ..autoSpan = false ..useHandCursor = true ..addEventListener(Ac.TOUCH ? TouchEvent.TOUCH_END : MouseEvent.MOUSE_UP, (e) { new AcSignal(StateEvents.ADDRESS_SET, getProperty("${ScreenIDs.HOME}.url", true)) .dispatch(); }); addChild(_logo); _itemList = _createList( _stateModel.getStateVOList(true, 0), _sideBarCellSelectAction); addChild(_itemList); onInitComplete(); } @override void span(num spanWidth, num spanHeight, {bool refresh: true}) { super.span(Dimensions.WIDTH_SIDEBAR, spanHeight); } @override void refresh() { super.refresh(); AcGraphics.rectangle(0, 0, spanWidth, spanHeight, sprite: this, color: Colors.GREY_DARK); _logo.y = 0; _logo.x = 0; _logo.scaleToHeight(MdDimensions.HEIGHT_APP_BAR); _itemList.y = MdDimensions.HEIGHT_APP_BAR + Dimensions.SPACER; _itemList.span(spanWidth, spanHeight - _itemList.y); _subList?.y = MdDimensions.HEIGHT_APP_BAR + Dimensions.SPACER; _subList?.span(spanWidth, spanHeight - _itemList.y); } _sideBarCellSelectAction(SelectableButton cell) { _selectedCell = cell; StateVO vo = cell.data; _blockSelectionByAddressCallback = true; new AcSignal(StateEvents.ADDRESS_SET, vo.url).dispatch(); } void setVO(StateVO vo) { // if (!_blockSelectionByAddressCallback) { // _itemList.selectCellByVO(vo); _subList?.selectCellByVO(vo); //} _blockSelectionByAddressCallback = false; /* if(_itemList.visible){ //todo itemList animate left var children = _stateModel.getStateVOList(true, vo.tree_order); if(children.length > 0){ //todo scroll _itemList cell to top, then flyout _subList.dispose(); _subList = _createList(_stateModel.getStateVOList(true, 0), _sideBarCellSelectAction); addChild(_subList); } }*/ } @override void set stateModel(StateModel stateModel) { _stateModel = stateModel; } MdMenu _createList(List<StateVO> stateVOList, Function(SelectableButton cell) cellSelectAction) { var itemList = new MdMenu(stateVOList, cell: new ListMenuCell(), shadow: false, backgroundColor: Colors.GREY_DARK); itemList.submitCallback = cellSelectAction; return itemList; } void openSubmenu(List<StateVO> subPageList) { //TODO create submenu, animate out rootmenu _itemList.visible = false; //todo scroll _itemList cell to top, then flyout _subList?.dispose(); _subList = _createList(subPageList, _sideBarCellSelectAction); addChild(_subList); _subList.init(); refresh(); } void closeSubmenu() { //TODO destroy submenu, animate rootmenu _subList?.dispose(); _itemList.visible = true; } }
27.047244
94
0.682387
0bd059c0036c9553eaaadaaa6118d5ba10dae7bd
4,965
js
JavaScript
libraries/botframework-streaming-extensions/lib/NamedPipe/NamedPipeServer.js
t-comin/botbuilder-js.old.cldialog
ed8fc3c123174a36f5ff450aa547b405de525499
[ "MIT" ]
null
null
null
libraries/botframework-streaming-extensions/lib/NamedPipe/NamedPipeServer.js
t-comin/botbuilder-js.old.cldialog
ed8fc3c123174a36f5ff450aa547b405de525499
[ "MIT" ]
null
null
null
libraries/botframework-streaming-extensions/lib/NamedPipe/NamedPipeServer.js
t-comin/botbuilder-js.old.cldialog
ed8fc3c123174a36f5ff450aa547b405de525499
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * @module botframework-streaming-extensions */ /** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ const net_1 = require("net"); const ProtocolAdapter_1 = require("../ProtocolAdapter"); const Payloads_1 = require("../Payloads"); const PayloadTransport_1 = require("../PayloadTransport"); const NamedPipeTransport_1 = require("./NamedPipeTransport"); /// <summary> /// A server for use with the Bot Framework Protocol V3 with Streaming Extensions and an underlying Named Pipe transport. /// </summary> class NamedPipeServer { /// <summary> /// Initializes a new instance of the <see cref="NamedPipeServer"/> class. /// </summary> /// <param name="baseName">The named pipe to connect to.</param> /// <param name="requestHandler">A <see cref="RequestHandler"/> to process incoming messages received by this server.</param> /// <param name="autoReconnect">Optional setting to determine if the server sould attempt to reconnect /// automatically on disconnection events. Defaults to true. /// </param> constructor(baseName, requestHandler, autoReconnect = true) { this._baseName = baseName; this._requestHandler = requestHandler; this._autoReconnect = autoReconnect; this._requestManager = new Payloads_1.RequestManager(); this._sender = new PayloadTransport_1.PayloadSender(); this._receiver = new PayloadTransport_1.PayloadReceiver(); this._protocolAdapter = new ProtocolAdapter_1.ProtocolAdapter(this._requestHandler, this._requestManager, this._sender, this._receiver); this._sender.disconnected = this.onConnectionDisconnected.bind(this); this._receiver.disconnected = this.onConnectionDisconnected.bind(this); } /// <summary> /// Used to establish the connection used by this server and begin listening for incoming messages. /// </summary> /// <returns>A promised string that will not resolve as long as the server is running.</returns> async start() { if (this._receiver.isConnected || this._sender.isConnected || this._incomingServer || this._outgoingServer) { this.disconnect(); } const incoming = new Promise(resolve => { this._incomingServer = new net_1.Server((socket) => { this._receiver.connect(new NamedPipeTransport_1.NamedPipeTransport(socket)); resolve(); }); }); const outgoing = new Promise(resolve => { this._outgoingServer = new net_1.Server((socket) => { this._sender.connect(new NamedPipeTransport_1.NamedPipeTransport(socket)); resolve(); }); }); await Promise.all([incoming, outgoing]); const { PipePath, ServerIncomingPath, ServerOutgoingPath } = NamedPipeTransport_1.NamedPipeTransport; const incomingPipeName = PipePath + this._baseName + ServerIncomingPath; const outgoingPipeName = PipePath + this._baseName + ServerOutgoingPath; this._incomingServer.listen(incomingPipeName); this._outgoingServer.listen(outgoingPipeName); return 'connected'; } // Allows for manually disconnecting the server. disconnect() { this._sender.disconnect(); this._receiver.disconnect(); if (this._incomingServer) { this._incomingServer.close(); this._incomingServer = null; } if (this._outgoingServer) { this._outgoingServer.close(); this._outgoingServer = null; } } /// <summary> /// Task used to send data over this server connection. /// </summary> /// <param name="request">The <see cref="StreamingRequest"/> to send.</param> /// <param name="cancellationToken">Optional <see cref="CancellationToken"/> used to signal this operation should be cancelled.</param> /// <returns>A <see cref="Task"/> of type <see cref="ReceiveResponse"/> handling the send operation.</returns> async send(request) { return this._protocolAdapter.sendRequest(request); } onConnectionDisconnected() { if (!this._isDisconnecting) { this._isDisconnecting = true; try { if (this._sender.isConnected) { this._sender.disconnect(); } if (this._receiver.isConnected) { this._receiver.disconnect(); } if (this._autoReconnect) { this.start() .catch((err) => { throw (new Error(`Unable to reconnect: ${err.message}`)); }); } } finally { this._isDisconnecting = false; } } } } exports.NamedPipeServer = NamedPipeServer; //# sourceMappingURL=NamedPipeServer.js.map
45.136364
144
0.638268
eff19d5c9d465e2e723bc4e51111959222ef3e7d
4,849
lua
Lua
dataLoader.lua
kui-jia/svb
9deb8f9682d0a2ffcda0c9c49acdcdf940dd42fe
[ "BSD-3-Clause" ]
10
2017-04-28T07:23:18.000Z
2018-12-24T13:39:55.000Z
dataLoader.lua
kui-jia/svb
9deb8f9682d0a2ffcda0c9c49acdcdf940dd42fe
[ "BSD-3-Clause" ]
1
2019-01-25T10:19:07.000Z
2019-01-25T10:19:07.000Z
dataLoader.lua
kui-jia/svb
9deb8f9682d0a2ffcda0c9c49acdcdf940dd42fe
[ "BSD-3-Clause" ]
2
2018-09-11T16:31:32.000Z
2019-12-05T12:04:29.000Z
--[[ Multi-threaded data loader to make loading of large-size images efficient Kui Jia, Dacheng Tao, Shenghua Gao, and Xiangmin Xu, "Improving training of deep neural networks via Singular Value Bounding", CVPR 2017. http://www.aperture-lab.net/research/svb This code is based on the fb.resnet.torch package (https://github.com/facebook/fb.resnet.torch) Copyright (c) 2016, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. --]] local imdbTrnVal = require 'cifar10Init' local threads = require 'threads' threads.serialization('threads.sharedserialize') -- Specify which serialization scheme should be used local M = {} local dataLoader = torch.class('dataLoader', M) function dataLoader.create(opts) local trnValDataLoaders = {} for iKey, value in ipairs({'train', 'val'}) do local imdb = imdbTrnVal.create(opts, value) trnValDataLoaders[iKey] = M.dataLoader(imdb, opts, value) end return table.unpack(trnValDataLoaders) end function dataLoader:__init(imdb, opts, trnValSplit) --[[ imdb contains data and info. for either 'train' or 'val' samples trnValSplit = 'train' or 'val' --]] local manualSeed = opts.manualSeed local function init() require(opts.dataset .. 'Init') end local function main(threadid) torch.manualSeed(manualSeed + threadid) torch.setnumthreads(1) _G.imdb = imdb _G.preprocess = imdb:preprocess() return imdb:size() end -- initialize a pool of threads local threadPool, nImgInIMDBTable = threads.Threads(opts.nThreads, init, main) self.nCrops = 1 self.threadPool = threadPool self.nImgInIMDB = nImgInIMDBTable[1][1] self.batchSize = math.floor(opts.batchSize / self.nCrops) end function dataLoader:epochIterNum() return math.ceil(self.nImgInIMDB / self.batchSize) end function dataLoader:run() -- callback function for data loading during training/inference local threadPool = self.threadPool local nImgInIMDB, batchSize = self.nImgInIMDB, self.batchSize local tmpindices = torch.randperm(nImgInIMDB) local batchImgSamples local idx = 1 local iter = 0 local function enqueue() -- distributing the jobs of loading and pre-processing an epoch of mini-batches of image samples over a pool of threads while idx <= nImgInIMDB and threadPool:acceptsjob() do -- acceptsjob() return true if the pool of thread queues is not full local tmpbatchindices = tmpindices:narrow(1, idx, math.min(batchSize, nImgInIMDB-idx+1)) -- distributing the following jobs of mini-batches to the pool of threads threadPool:addjob( function(tmpindices, nCrops) -- callback function, executed on each threads local nImgSample = tmpindices:size(1) local target = torch.IntTensor(nImgSample) -- variable for hosting training targets/labels of image samples local batchImgData, tmpsizes for iKey, idxValue in ipairs(tmpindices:totable()) do local currImgSample = _G.imdb:get(idxValue) local currInput = _G.preprocess(currImgSample.input) -- do data augmentation on the fly if not batchImgData then tmpsizes = currInput:size():totable() batchImgData = torch.FloatTensor(nImgSample, nCrops, table.unpack(tmpsizes)) end batchImgData[iKey]:copy(currInput) target[iKey] = currImgSample.target end collectgarbage() -- automtic management/freeing of garbage memory oppupied by the preceding operations return {input = batchImgData:view(nImgSample*nCrops, table.unpack(tmpsizes)), target = target} end, function(_batchImgSamples_) -- endcallback function whose argument is from the return of callback function, executed on the main thread, batchImgSamples = _batchImgSamples_ -- pass the mini-batch of image samples to the main thread end, tmpbatchindices, -- arguments of callback function self.nCrops ) idx = idx + batchSize end end local function loop() enqueue() -- loading and processing a mini-batch of image samples over a free thread if not threadPool:hasjob() then -- true if there is still any job unfinished return nil -- finish the 'loop' function when all jobs are done end threadPool:dojob() -- to tell the main thread to execute the next endcallback in the queue if threadPool:haserror() then threadPool:synchronize() end enqueue() iter = iter + 1 return iter, batchImgSamples end return loop end return M.dataLoader
37.015267
153
0.701382
c5bcb0e34e9e551b818e6d300797e7ed782cc220
3,900
cpp
C++
src/png/images.cpp
rl337/bust
c27b3ac242dea33bfcf69b51f2e8161832dc91f0
[ "Apache-2.0" ]
null
null
null
src/png/images.cpp
rl337/bust
c27b3ac242dea33bfcf69b51f2e8161832dc91f0
[ "Apache-2.0" ]
null
null
null
src/png/images.cpp
rl337/bust
c27b3ac242dea33bfcf69b51f2e8161832dc91f0
[ "Apache-2.0" ]
null
null
null
#include "images.h" namespace bust::png { void TestImage::draw() { setCurrentColor(bust::util::colors::White); clear(); setCurrentColor(bust::util::colors::Blue); uint64_t width = getWidth(); uint64_t height = getHeight(); uint64_t shortedge = width < height ? width : height; uint32_t r = shortedge / 10; circle(r/2, r/2, r/2); circle(width-r/2-1, r/2, r/2); circle(width-r/2-1, height-r/2-1, r/2); circle(r/2, height-r/2-1, r/2); circle(r/2, height/2, r/2); circle(width-r/2-1, height/2, r/2); circle(width/2, r/2, r/2); circle(width/2, height-r/2-1, r/2); circle(width/2, height/2, r); line(width/2, height/2-r*2, width/2, height/2+r*2); line(width/2-r*2, height/2, width/2 + r*2, height/2); } void ColorBars::draw() { uint64_t width = getWidth(); uint64_t height = getHeight(); for (uint32_t x = 0; x < width; x++) { for (uint32_t y = 0; y < height; y++) { bust::util::Color color; if (y < height * 25 / 40) { switch (x * 7 / width) { case 0: color = bust::util::vga16::Silver; break; case 1: color = bust::util::vga16::Yellow; break; case 2: color = bust::util::vga16::Aqua; break; case 3: color = bust::util::vga16::Lime; break; case 4: color = bust::util::vga16::Fuchsia; break; case 5: color = bust::util::vga16::Red; break; case 6: color = bust::util::vga16::Blue; break; } } else if (y >= height * 25 / 40 && y < height * 29/40) { switch (x * 7 / width) { case 0: color = bust::util::vga16::Blue; break; case 1: color = bust::util::vga16::Black; break; case 2: color = bust::util::vga16::Fuchsia; break; case 3: color = bust::util::vga16::Black; break; case 4: color = bust::util::vga16::Aqua; break; case 5: color = bust::util::vga16::Black; break; case 6: color = bust::util::vga16::Silver; break; } } else { switch (x * 18 / width) { case 0: color = bust::util::vga16::Navy; break; case 1: color = bust::util::vga16::Navy; break; case 2: color = bust::util::vga16::Navy; break; case 3: color = bust::util::vga16::White; break; case 4: color = bust::util::vga16::White; break; case 5: color = bust::util::vga16::White; break; case 6: color = bust::util::vga16::Purple; break; case 7: color = bust::util::vga16::Purple; break; case 8: color = bust::util::vga16::Purple; break; case 9: color = bust::util::vga16::Black; break; case 10: color = bust::util::vga16::Black; break; case 11: color = bust::util::vga16::Black; break; case 12: color = bust::util::vga16::White; break; case 13: color = bust::util::vga16::Silver; break; case 14: color = bust::util::vga16::Gray; break; case 15: color = bust::util::vga16::Black; break; case 16: color = bust::util::vga16::Black; break; case 17: color = bust::util::vga16::Black; break; } } set(x, y, color); } } } }
43.820225
74
0.446667
3bac23b67f7047f89d27b10f58fbccaf7aab729d
2,092
html
HTML
docs/index.html
Project-Universe/support
3130270276cc5ef8596027930d61e3e7479b2835
[ "MIT" ]
188
2021-02-05T18:45:49.000Z
2022-03-31T12:07:17.000Z
docs/index.html
pranv-sonawane/support
7aaac9d79ff0546853011a6641db14f8de83d695
[ "MIT" ]
2,548
2021-02-01T14:18:59.000Z
2022-03-31T20:23:31.000Z
docs/index.html
pranv-sonawane/support
7aaac9d79ff0546853011a6641db14f8de83d695
[ "MIT" ]
137
2021-02-02T07:43:00.000Z
2022-03-31T16:56:40.000Z
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/docsify-themeable@0/dist/css/theme-simple-dark.css" /> <style> :root { --theme-color: #202328; --mono-hue: 255; --theme-hue: 255; --mono-tint3: #202328; --mono-tint2: #202328; --mono-tint1: #202328; --base-color: #202328; --heading-color: #202328; --base-background-color: #D4D1C5; --sidebar-background: #D4D1C5; --sidebar-nav-link-color: #202328; --code-inline-background: #202328; --table-row-odd-background: #D4D1C5; } .sidebar-nav > h1 { font-size: var(--modular-scale-2); } </style> <title>EddieHub Support</title> </head> <body> <div id="app"> <h1>EddieHub Support Repo</h1> <p>Resources to help our community grow and thrive.</p> </div> </body> <script> window.$docsify = { name: "", repo: "eddiehubcommunity/support", loadSidebar: "_navbar.md", homepage: "index.md", auto2top: true, // Plugins "flexible-alerts": { style: "flat", }, copyCode: { buttonText: "Copy this snippet", errorText: "Could not copy!", successText: "Copied to clipboard", }, maxLevel: 2, }; </script> <!-- Docsify v4 --> <script src="https://cdnjs.cloudflare.com/ajax/libs/docsify/4.12.1/docsify.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/docsify-plugin-flexible-alerts@1"></script> <script src="https://unpkg.com/docsify-copy-code@2"></script> <!-- Prism (syntax highlighting) --> <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.25.0/components/prism-typescript.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.25.0/components/prism-markdown.min.js"></script> </html>
31.223881
112
0.586998
049ed8c1baadea1c8d83a837ce844e1e80c30e52
4,872
java
Java
streams-contrib/streams-provider-datasift/src/main/java/org/apache/streams/datasift/csdl/DatasiftCsdlUtil.java
sieverssj/incubator-streams
e13617d384dec1a6c6231cd1bdaf5a3a6bbfc2b3
[ "Apache-2.0" ]
null
null
null
streams-contrib/streams-provider-datasift/src/main/java/org/apache/streams/datasift/csdl/DatasiftCsdlUtil.java
sieverssj/incubator-streams
e13617d384dec1a6c6231cd1bdaf5a3a6bbfc2b3
[ "Apache-2.0" ]
null
null
null
streams-contrib/streams-provider-datasift/src/main/java/org/apache/streams/datasift/csdl/DatasiftCsdlUtil.java
sieverssj/incubator-streams
e13617d384dec1a6c6231cd1bdaf5a3a6bbfc2b3
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * * 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 org.apache.streams.datasift.csdl; import com.google.common.collect.Lists; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.ListIterator; public class DatasiftCsdlUtil { private static final Logger log = LoggerFactory .getLogger(DatasiftCsdlUtil.class); public static String csdlFromTwitterUserIds(List<String> list) throws Exception { StringBuilder csdlBuilder = new StringBuilder(); csdlBuilder.append("twitter.user.id in ["); ListIterator<String> listIterator = Lists.newArrayList(list).listIterator(); while( listIterator.hasNext() ) { csdlBuilder.append(listIterator.next()); if (listIterator.hasNext()) csdlBuilder.append(","); } csdlBuilder.append("]\n"); csdlBuilder.append(" OR\n"); csdlBuilder.append("twitter.in_reply_to_user_id contains_any \""); listIterator = Lists.newArrayList(list).listIterator(); while( listIterator.hasNext() ) { csdlBuilder.append(listIterator.next()); if (listIterator.hasNext()) csdlBuilder.append(","); } csdlBuilder.append("\"\n"); csdlBuilder.append(" OR\n"); csdlBuilder.append("twitter.mention_ids in ["); listIterator = Lists.newArrayList(list).listIterator(); while( listIterator.hasNext() ) { csdlBuilder.append(listIterator.next()); if (listIterator.hasNext()) csdlBuilder.append(","); } csdlBuilder.append("]\n"); log.debug(csdlBuilder.toString()); return csdlBuilder.toString(); } public static String csdlFromTwitterUserNames(List<String> list) throws Exception { StringBuilder csdlBuilder = new StringBuilder(); csdlBuilder.append("twitter.user.screen_name contains_any \""); ListIterator<String> listIterator = Lists.newArrayList(list).listIterator(); while( listIterator.hasNext() ) { csdlBuilder.append(listIterator.next()); if (listIterator.hasNext()) csdlBuilder.append(","); } csdlBuilder.append("\"\n"); csdlBuilder.append(" OR\n"); csdlBuilder.append("twitter.in_reply_to_screen_name contains_any \""); listIterator = Lists.newArrayList(list).listIterator(); while( listIterator.hasNext() ) { csdlBuilder.append(listIterator.next()); if (listIterator.hasNext()) csdlBuilder.append(","); } csdlBuilder.append("\"\n"); csdlBuilder.append(" OR\n"); csdlBuilder.append("twitter.mentions contains_any \""); listIterator = Lists.newArrayList(list).listIterator(); while( listIterator.hasNext() ) { csdlBuilder.append(listIterator.next()); if (listIterator.hasNext()) csdlBuilder.append(","); } csdlBuilder.append("\"\n"); log.debug(csdlBuilder.toString()); return csdlBuilder.toString(); } public static String csdlFromKeywords(List<String> include, List<String> exclude) throws Exception { StringBuilder csdlBuilder = new StringBuilder(); csdlBuilder.append("interaction.content contains_any \""); ListIterator<String> listIterator = Lists.newArrayList(include).listIterator(); while( listIterator.hasNext() ) { csdlBuilder.append(listIterator.next()); if (listIterator.hasNext()) csdlBuilder.append(","); } csdlBuilder.append("\"\n"); csdlBuilder.append(" AND NOT ( \n"); csdlBuilder.append("interaction.content \""); listIterator = Lists.newArrayList(exclude).listIterator(); while( listIterator.hasNext() ) { csdlBuilder.append(listIterator.next()); if (listIterator.hasNext()) csdlBuilder.append(","); } csdlBuilder.append("\"\n"); csdlBuilder.append(")\n"); log.debug(csdlBuilder.toString()); return csdlBuilder.toString(); } }
36.631579
104
0.64101
f775e07678744e78cf1d7c8e92ad3b99d9c7323e
1,269
h
C
plugins/bbInterface/src/AgentType_SystemMonitor.h
mojmir-svoboda/BlackBoxTT
0c87b989827107695538e1bf1266c08b083dda44
[ "MIT" ]
11
2017-06-19T14:21:15.000Z
2020-03-04T06:43:16.000Z
plugins/bbInterface/src/AgentType_SystemMonitor.h
mojmir-svoboda/BlackBoxTT
0c87b989827107695538e1bf1266c08b083dda44
[ "MIT" ]
null
null
null
plugins/bbInterface/src/AgentType_SystemMonitor.h
mojmir-svoboda/BlackBoxTT
0c87b989827107695538e1bf1266c08b083dda44
[ "MIT" ]
3
2017-07-23T18:08:55.000Z
2019-09-16T16:28:18.000Z
#pragma once #include "AgentMaster.h" //Define these function pointer types typedef BOOL (__stdcall *agenttype_systemmonitor_NtQuerySystemInformation)(DWORD SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength); //Defines from the original const int agenttype_systemmonitor_SystemBasicInformation = 0; const int agenttype_systemmonitor_SystemPerformanceInformation = 2; const int agenttype_systemmonitor_SystemTimeInformation = 3; //Define these functions internally int agenttype_systemmonitor_startup(); int agenttype_systemmonitor_shutdown(); int agenttype_systemmonitor_create(agent *a, wchar_t *parameterstring); int agenttype_systemmonitor_destroy(agent *a); int agenttype_systemmonitor_message(agent *a, int tokencount, wchar_t *tokens[]); void agenttype_systemmonitor_notify(agent *a, int notifytype, void *messagedata); void* agenttype_systemmonitor_getdata(agent *a, int datatype); void agenttype_systemmonitor_menu_set(std::shared_ptr<bb::MenuConfig> m, control *c, agent *a, wchar_t *action, int controlformat); void agenttype_systemmonitor_menu_context(std::shared_ptr<bb::MenuConfig> m, agent *a); void agenttype_systemmonitor_notifytype(int notifytype, void *messagedata);
48.807692
182
0.822695
46b00ffc4603e75dde9a89637fcb46de0c1efc00
14,270
html
HTML
index.html
RffaNunes/seo-simple-profile
a5c0085e0e4ba21560708e46dafd65c6037cf32d
[ "MIT" ]
null
null
null
index.html
RffaNunes/seo-simple-profile
a5c0085e0e4ba21560708e46dafd65c6037cf32d
[ "MIT" ]
null
null
null
index.html
RffaNunes/seo-simple-profile
a5c0085e0e4ba21560708e46dafd65c6037cf32d
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <title>Rafa Nunes · UX/UI Design · Front-end Dev · SEO Analyst · PO/SM</title> <meta property="og:title" content="Rafa Nunes · UX/UI Design · Front-end Dev · SEO Analyst · PO/SM" /> <meta property="og:site_name" content="Rafa Nunes · UX/UI Design · Front-end Dev · SEO Analyst · PO/SM" /> <meta name="description" content="Especialista em UX/UI, Front-end e SEO, trabalha com Produtos em Startups como Tech Lead, Product Owner e Scrum Master. Head de Engenharia com liderança, coaching de processos de desenvolvimento, R&S e T&D. Apaixonado por metodologias ágeis, professor de mais de 15 cursos de tecnologia e palestrante." /> <meta property="og:description" content="Especialista em UX/UI, Front-end e SEO, trabalha com Produtos em Startups como Tech Lead, Product Owner e Scrum Master. Head de Engenharia com liderança, coaching de processos de desenvolvimento, R&S e T&D. Apaixonado por metodologias ágeis, professor de mais de 15 cursos de tecnologia e palestrante." /> <meta name="DC.Creator" content="Rafael Nunes Corrêa" /> <meta name="copyright" content="Rafael Nunes Corrêa" /> <meta name="Designer" content="Rafael Nunes Corrêa" /> <meta name="Publisher" content="Rafael Nunes Corrêa" /> <meta property="og:type" content="website" /> <meta name="robots" content="index, follow" /> <meta name="googlebot" content="index, follow" /> <meta name="Language" content="Portuguese" /> <meta name="distribution" content="Global" /> <meta name="country" content="Brazil" /> <meta name="city" content="São Paulo" /> <meta name="google-site-verification" content="XuK0rxUSNyPL_C54HnstWypfrIw_BDChgGB3NS73WHw" /> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=2" /> <meta name="HandheldFriendly" content="true" /> <meta name="MobileOptimized" content="480" /> <meta name="format-detection" content="telephone=no" /> <link rel="apple-touch-icon" sizes="57x57" href="/img/favicon/apple-icon-57x57.png" /> <link rel="apple-touch-icon" sizes="60x60" href="/img/favicon/apple-icon-60x60.png" /> <link rel="apple-touch-icon" sizes="72x72" href="/img/favicon/apple-icon-72x72.png" /> <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon/apple-icon-76x76.png" /> <link rel="apple-touch-icon" sizes="114x114" href="/img/favicon/apple-icon-114x114.png" /> <link rel="apple-touch-icon" sizes="120x120" href="/img/favicon/apple-icon-120x120.png" /> <link rel="apple-touch-icon" sizes="144x144" href="/img/favicon/apple-icon-144x144.png" /> <link rel="apple-touch-icon" sizes="152x152" href="/img/favicon/apple-icon-152x152.png" /> <link rel="apple-touch-icon" sizes="180x180" href="/img/favicon/apple-icon-180x180.png" /> <link rel="icon" type="image/png" sizes="192x192" href="/img/favicon/android-icon-192x192.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="96x96" href="/img/favicon/favicon-96x96.png" /> <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon/favicon-16x16.png" /> <link rel="manifest" href="/img/favicon/manifest.json" /> <meta name="msapplication-TileColor" content="#ffffff" /> <meta name="msapplication-TileImage" content="/img/favicon/ms-icon-144x144.png" /> <meta name="theme-color" content="#ffffff" /> <link rel="shortcut icon" href="/img/favicon/favicon.ico" type="image/x-icon"> <link rel="icon" href="/img/favicon/favicon.ico" type="image/x-icon"> <meta property="og:url" content="https://rafanunes.com" /> <link rel="canonical" href="https://rafanunes.com" /> <link rel="stylesheet" href="css/reset.min.css" /> <link rel="stylesheet" href="css/home.min.css" /> <link rel="stylesheet" href="css/slider.min.css" /> <script src="js/change-bg-color.min.js"></script> <script src="js/google-analytics.min.js"></script> </head> <body> <main class="wrapper"> <article class="box"> <header class="box-header-profile"> <img class="bhp-img" src="img/profile/rafael-nunes.jpg" alt="Rafael Nunes · UX/UI · Front · SEO · PO/SM" onclick="window.location.href=window.location.href" /> <h1 class="bhp-title"> <b class="bhp-title-name">Rafael Nunes</b> <small class="bhp-title-sub p-color-gray">UX/UI · Front · SEO · PO/SM</small> </h1> </header> <div class="social-links"> <a href="https://linkedin.com/in/RffaNunes" aria-label="Perfil do Rafael Nunes no LinkedIn" target="_blank" rel="nofollow noopener external"><i class="icon icon-linkedin" aria-hidden="true"></i></a> <a href="https://instagram.com/RffaNunes" aria-label="Perfil do Rafael Nunes no Instagram" target="_blank" rel="nofollow noopener external"><i class="icon icon-instagram" aria-hidden="true"></i></a> <a href="https://facebook.com/RffaNunes" aria-label="Perfil do Rafael Nunes no Facebook" target="_blank" rel="nofollow noopener external"><i class="icon icon-facebook" aria-hidden="true"></i></a> <a href="https://twitter.com/RffaNunes" aria-label="Perfil do Rafael Nunes no Twitter" target="_blank" rel="nofollow noopener external"><i class="icon icon-twitter" aria-hidden="true"></i></a> <a href="https://github.com/RffaNunes" aria-label="Perfil do Rafael Nunes no GitHub" target="_blank" rel="nofollow noopener external"><i class="icon icon-github" aria-hidden="true"></i></a> <a href="mailto:rafael@rafaweb.com.br" aria-label="Enviar e-mail para o Rafael Nunes" target="_blank" rel="nofollow noopener external"><i class="icon icon-email" aria-hidden="true"></i></a> </div> <pre class="text-dexcription"> Há 13 anos na área de TI, especialista em UX/UI Design, Front-end e SEO, trabalha com Produtos em Startups desde 2011 atuando como Tech Lead, Product Owner e Scrum Master. Já foi Head de Engenharia e de People Ops trabalhando com liderança, coaching de processos de desenvolvimento, R&S e T&D. Adora pensar no cliente e encontrar as melhores soluções orgânicas. Apaixonado por metodologias ágeis, criou duas, uma para eficiência no desenvolvimento de Front-end e outra para controle de prazos. Professor de mais de 15 cursos de tecnologia e palestrante nas horas vagas. </pre> <h2 class="text-attention"> <b class="p-color-gray">Disponível para:</b> Eventos · Palestras · Workshops · Mentorias </h2> </article> <section class="slider"> <h2 class="slider-title">Recomendações:</h2> <article class="slider-wrapper"> <div class="sw-content"> <div class="swc-profile"> <img class="swc-profile-img" src="img/profile/edmundo-mizutani.jpg" alt="Edmundo Mizutani - Engenheiro de Software"/> <h3 class="swc-profile-title"> <b>Edmundo Mizutani</b> <small>Engenheiro de Software</small> </h3> </div> <pre class="swc-text"> Confio muito no Rafael Nunes para desenvolver SEO, Front-end e CSS. Foi uma das peças chaves para o sucesso do Eduqo - QMágico e temos uma enorme gratidão pelo legado que ele deixou. Obrigado! </pre> </div> <div class="sw-content"> <div class="swc-profile"> <img class="swc-profile-img" src="img/profile/felipe-braga.jpg" alt="Felipe Braga - Quality Assurance" /> <h3 class="swc-profile-title"> <b>Felipe Braga</b> <small>Quality Assurance</small> </h3> </div> <pre class="swc-text"> Tive o prazer de trabalhar com o Rafael Nunes por 1 ano e aprendi muito com a sua determinação. Comprometido com prazos e qualidade, sempre lembrando o foco das atividades. Sua visão e compreensão de negócio são admiráveis, motiva a equipe e os impulsiona a melhorar. Trabalhar ao seu lado foi gratificante e inspirador. </pre> </div> <div class="sw-content"> <div class="swc-profile"> <img class="swc-profile-img" src="img/profile/louise-santos.jpg" alt="Louise Santos - UX/UI Design - Front-end" /> <h3 class="swc-profile-title"> <b>Louise Santos</b> <small>UX/UI Design - Front-end</small> </h3> </div> <pre class="swc-text"> Possui conhecimentos sólidos na área de Front-end, sendo responsável pela arquitetura, manutenibilidade e boas práticas do projeto. Se preocupa desde a interface/experiência ao acompanhamento final do produto. Como líder sabe explorar as habilidades da equipe. Possui talento para planejamento de projetos, é criativo e direto na resolução de problemas. Excelente mentoria, compreensão, comunicação e respeito. </pre> </div> <div class="sw-content"> <div class="swc-profile"> <img class="swc-profile-img" src="img/profile/matheus-carvalho.jpg" alt="Matheus Carvalho - Engenheiro de Software" /> <h3 class="swc-profile-title"> <b>Matheus Carvalho</b> <small>Engenheiro de Software</small> </h3> </div> <pre class="swc-text"> Rafael Nunes é um profissional com espírito de liderança. Possui vasto conhecimento em SEO, Design e desenvolvimento de produto. Possui ótimas habilidades de coordenação e tomadas de decisão. É um ótimo líder com capacidade de relacionamento profissional e mediação da equipe. </pre> </div> <div class="sw-content"> <div class="swc-profile"> <img class="swc-profile-img" src="img/profile/vivian-oliveira.jpg" alt="Vivian Oliveira - Quality Assurance" /> <h3 class="swc-profile-title"> <b>Vivian Oliveira</b> <small>Quality Assurance</small> </h3> </div> <pre class="swc-text"> Rafael Nunes é um profissional curinga, com capacidade para atuar em diversas áreas, pois se adapta fácil a novos desafios e faz de tudo para concluí-los com sucesso. É persistente e não desiste fácil. Possui sólidos conhecimentos em desenvolvimento Front-end e grandes habilidades de planejamento de atividades, prazos e priorização. </pre> </div> <div class="sw-content"> <div class="swc-profile"> <img class="swc-profile-img" src="img/profile/rodrigo-barbosa.jpg" alt="Rodrigo Barbosa - CTO" /> <h3 class="swc-profile-title"> <b>Rodrigo Barbosa</b> <small>CTO</small> </h3> </div> <pre class="swc-text"> Fez parte de um período importante do Guichê Virtual. Desde a criação das primeiras equipes, dando conta de boa parte dos processos seletivos e, liderando o Front-end com padrões visando a qualidade do produto. Como Head de Engenharia se envolveu com diversas áreas, interagiu com diversos times e ajudou alguns projetos entrarem nos eixos. Muito comprometido e sempre trazendo sugestões de melhorias em geral. </pre> </div> <div class="sw-content"> <div class="swc-profile"> <img class="swc-profile-img" src="img/profile/bruna-goncalves.jpg" alt="Bruna Gonçalves - Engenheira de Produto" /> <h3 class="swc-profile-title"> <b>Bruna Gonçalves</b> <small>Engenheira de Produto</small> </h3> </div> <pre class="swc-text"> Rafael Nunes é um profissional gabaritado na área de TI, que não se importa em compartilhar seus conhecimentos. Vi o Rafael como um ótimo líder, puxando as responsabilidades para si, além de ser uma pessoa de enorme humildade, deixando o ambiente ao seu redor agradável. A empresa que o tem com certeza está muito bem! </pre> </div> <div class="sw-content"> <div class="swc-profile"> <img class="swc-profile-img" src="img/profile/diego-costa.jpg" alt="Diego Costa - Full-stack Developer" /> <h3 class="swc-profile-title"> <b>Diego Costa</b> <small>Full-stack Developer</small> </h3> </div> <pre class="swc-text"> Mais que um colaborador, possui espírito de dono e disposição para liderar equipes de desenvolvimento de produto, como se tivesse nascido para isso. Referência técnica e criador da metodologia CSS Pro, ajudou muito na arquitetura e design dos projetos. Resumindo o Rafael em duas palavras: profissional e amigo. </pre> </div> </article> </section> </main> </body> </html>
69.271845
350
0.59075
414df6a7f4610e0a21757428f18254a5f7ab1093
586
h
C
HuiShengHuo2.0/youxianjiaofei/youxianjiaofeimodel.h
lianwentao/huachengshequhuishenghuo
76b42ad11e90892af0e8ba308a0ec84226faea74
[ "Apache-2.0" ]
null
null
null
HuiShengHuo2.0/youxianjiaofei/youxianjiaofeimodel.h
lianwentao/huachengshequhuishenghuo
76b42ad11e90892af0e8ba308a0ec84226faea74
[ "Apache-2.0" ]
null
null
null
HuiShengHuo2.0/youxianjiaofei/youxianjiaofeimodel.h
lianwentao/huachengshequhuishenghuo
76b42ad11e90892af0e8ba308a0ec84226faea74
[ "Apache-2.0" ]
null
null
null
// // youxianjiaofeimodel.h // HuiShengHuo2.0 // // Created by 晋中华晟 on 2018/6/14. // Copyright © 2018年 晋中华晟. All rights reserved. // #import <Foundation/Foundation.h> @interface youxianjiaofeimodel : NSObject @property (nonatomic,copy)NSString *addtime; @property (nonatomic,copy)NSString *amount; @property (nonatomic,copy)NSString *order_number; @property (nonatomic,copy)NSString *pay_type; @property (nonatomic,copy)NSString *wired_num; @property (nonatomic,copy)NSString *fullname; @property (nonatomic,copy)NSString *staus; @property (nonatomic,copy)NSString *uptime; @end
26.636364
49
0.766212
d1a5eb4939b93dbbe3be0d6bb851c08508891b28
70
rs
Rust
src/lib.rs
igaryhe/Raytracer
51f9b6f52cc24a4bc791a920c9c2b78e315db8c4
[ "BSD-3-Clause" ]
1
2020-04-18T15:59:10.000Z
2020-04-18T15:59:10.000Z
src/lib.rs
igaryhe/Raytracer
51f9b6f52cc24a4bc791a920c9c2b78e315db8c4
[ "BSD-3-Clause" ]
null
null
null
src/lib.rs
igaryhe/Raytracer
51f9b6f52cc24a4bc791a920c9c2b78e315db8c4
[ "BSD-3-Clause" ]
null
null
null
pub mod structure; pub mod hitable; pub mod material; pub mod camera;
14
18
0.771429
20b03ce0d7ed8fbff2362e0fa06c863f8b94dc45
538
asm
Assembly
oeis/037/A037571.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/037/A037571.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/037/A037571.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A037571: Base 6 digits are, in order, the first n terms of the periodic sequence with initial period 2,1,2. ; Submitted by Jamie Morken(s4) ; 2,13,80,482,2893,17360,104162,624973,3749840,22499042,134994253,809965520,4859793122,29158758733,174952552400,1049715314402,6298291886413,37789751318480,226738507910882,1360431047465293 add $0,1 mov $2,2 lpb $0 mov $3,$2 lpb $3 mod $0,30 add $2,1 mod $3,5 div $3,2 add $2,$3 add $4,1 lpe sub $0,1 add $2,1 mul $4,6 lpe mov $0,$4 sub $0,12 div $0,6 add $0,2
21.52
187
0.685874
f15cee8de98a92103d615ff030d4a508269ac620
1,653
lua
Lua
code/vector.lua
gabri-16/RobotExploration
1eebf7cb489ec019421206130d327accac241aad
[ "MIT" ]
null
null
null
code/vector.lua
gabri-16/RobotExploration
1eebf7cb489ec019421206130d327accac241aad
[ "MIT" ]
null
null
null
code/vector.lua
gabri-16/RobotExploration
1eebf7cb489ec019421206130d327accac241aad
[ "MIT" ]
null
null
null
local vector = {} -- Summing two 2D vectors in cartesian coordinates function vector.vec2_sum(v1, v2) local v3 = {x = 0 , y = 0} v3.x = v1.x + v2.x v3.y = v1.y + v2.y return v3 end function vector.zero() return {length = 0.0 , angle = 0.0} end -- From polar to cartesian coordinates function vector.polar_to_cart(v) local z = {x = v.length * math.cos(v.angle) , y = v.length * math.sin(v.angle)} return z end -- Getting the angle of a 2D vector function vector.vec2_angle(v) return math.atan2(v.y, v.x) end -- Getting the length of a 2D vector function vector.vec2_length(v) return math.sqrt(math.pow(v.x,2) + math.pow(v.y,2)) end -- From cartesian to polar coordinates function vector.cart_to_polar(v) local z = {length = vector.vec2_length(v) , angle = vector.vec2_angle(v)} return z end -- Setting a 2D vector from length and angle function vector.vec2_new_polar(length, angle) local vec2 = { x = length * math.cos(angle) , y = length * math.sin(angle) } return vec2 end -- Summing two 2D vectors in polar coordinates function vector.vec2_polar_sum(v1, v2) local w1 = vector.polar_to_cart(v1) local w2 = vector.polar_to_cart(v2) local w3 = vector.vec2_sum(w1,w2) local v3 = vector.cart_to_polar(w3) return v3 end -- Reduce an array of polar vectors by summing them function reduce_vec2_array_polar(array) local res = vector.zero() for i=1, #array do res = vector.vec2_polar_sum(res, array[i]) end return res end -- Nice representation of a polar vector function polar_vector_to_string(vector) return "length: " .. vector.length .. "; angle: " .. vector.angle end return vector
22.04
80
0.701149
044fbb06545379b075015ee76c3fef3f5bc1ac48
372
lua
Lua
resources/[local]/[SCRIPTS]/skinchanger/fxmanifest.lua
szymczakovv/AriviRP
e1b9425b242586da551ee4909954a98a7c7aa2de
[ "MIT" ]
10
2021-03-09T23:17:02.000Z
2021-10-03T12:47:03.000Z
resources/[local]/[SCRIPTS]/skinchanger/fxmanifest.lua
szymczakovv/AriviRP
e1b9425b242586da551ee4909954a98a7c7aa2de
[ "MIT" ]
null
null
null
resources/[local]/[SCRIPTS]/skinchanger/fxmanifest.lua
szymczakovv/AriviRP
e1b9425b242586da551ee4909954a98a7c7aa2de
[ "MIT" ]
33
2021-03-09T09:49:35.000Z
2022-03-15T01:17:05.000Z
fx_version "bodacious" games {"gta5"} description 'Skin Changer' version '1.0.3' client_scripts { 'locale.lua', 'locales/br.lua', 'locales/de.lua', 'locales/en.lua', 'locales/fi.lua', 'locales/fr.lua', 'locales/pl.lua', 'locales/sv.lua', 'config.lua', 'client/main.lua' } server_scripts { '@mysql-async/lib/MySQL.lua', 'server.lua' }
15.5
31
0.626344
fc5466e7342eb0d409b563234a6af16f9864f916
668
dart
Dart
beers/lib/controllers/service.controller.dart
neetjn/dart-beers
524d9b035c94b189c06bf784a60a1dad11ab352c
[ "MIT" ]
2
2019-03-15T20:10:39.000Z
2019-06-09T23:10:03.000Z
beers/lib/controllers/service.controller.dart
neetjn/dart-beers
524d9b035c94b189c06bf784a60a1dad11ab352c
[ "MIT" ]
6
2019-03-12T20:01:11.000Z
2019-03-20T19:45:45.000Z
beers/lib/controllers/service.controller.dart
neetjn/dart-beers
524d9b035c94b189c06bf784a60a1dad11ab352c
[ "MIT" ]
null
null
null
library beers.controllers.service; import 'dart:core'; import 'package:aqueduct/aqueduct.dart'; import 'package:beers/constants.dart' as constants; import 'package:beers/beers/utils.dart'; import 'package:beers/mediatypes/apiroot.dart'; import 'package:beers/controllers/base.controller.dart'; @Resource(route: constants.ServiceRouteDef.ROOT, rel: constants.ServiceRelDef.ROOT) class ServiceController extends BaseResourceController { @Operation.get() Future<Response> getBeerCollection() async { String protocol = protocolFromRequest(request); ApiRootDto apiroot = app.getServiceDescription(protocol: protocol); return Response.ok(apiroot); } }
31.809524
83
0.787425
e85dc2225ca6f4f8a7ef87af75f2d2b205c0b1d1
2,342
cpp
C++
other/mapping_core2switch.cpp
vsskarthik/noxim-new
c5fcb547f172390cfa06988f66c3e89a2ba008af
[ "BSD-4-Clause-UC" ]
127
2015-07-08T14:39:34.000Z
2022-03-25T08:00:38.000Z
other/mapping_core2switch.cpp
pakeunji/noxim
dbe0b8991b28a44df7c47d940bd59a11cfcc4dd2
[ "BSD-4-Clause-UC" ]
124
2015-08-03T11:32:05.000Z
2022-03-24T16:03:02.000Z
other/mapping_core2switch.cpp
pakeunji/noxim
dbe0b8991b28a44df7c47d940bd59a11cfcc4dd2
[ "BSD-4-Clause-UC" ]
100
2015-07-29T15:08:12.000Z
2022-03-25T08:00:42.000Z
#include <stdio.h> #include <cmath> #include <iostream> using namespace std; int main(int argc, char* argv[]) { int n; // n: number of tiles in butterfly cout << "give tile number n = "; cin >> n; int stg = log2(n); // stg: stage number int sw = n/2; // sw: number of switche in each stage /* EXPLE: // --First Stage-- // sw(0,0) connected to core(0) -> dir 3 (NB.the wire signal is the same) t[0][0]->flit_rx[3](flit[0][3].west); core[0]->flit_tx[0](flit[0][3].west); // sw(0,0) connected to core(1) -> dir 2 t[0][0]->flit_rx[2](flit[0][2].south); core[1]->flit_tx[0](flit[0][2].south); */ /* // --Last Stage-- // sw(2,0) connected to core(0) -> dir 0 (NB.the wire signal is the same) t[2][0]->flit_rx[0](flit[2][0].north); core[0]->flit_tx[1](flit[2][0].north); // sw(2,0) connected to core(1) -> dir 1 t[2][0]->flit_rx[1](flit[2][0].east); core[1]->flit_tx[1](flit[2][0].east); */ for (int i = 0; i < sw ; i++) { // t : means switch cout << "t[" << 0 << "][" << i << "] -> flit_rx[3](flit[" << 0<< "][" << i << "].west)"<< "\n"; //t[0][i]->flit_rx[3](flit[0][3].west); cout << "core[" << i*2 << "]" << " -> flit_tx[0](flit[" << 0<< "][" << i << "].west)"<< "\n"; //core[sw*2]->flit_tx[0](flit[0][3].west); cout << "t[" << 0 << "][" << i << "] -> flit_rx[2](flit[" << 0<< "][" << i << "].south)"<< "\n"; //t[0][i]->flit_rx[2](flit[0][2].south); cout << "core[" << (i*2)+1 << "]" << " -> flit_tx[0](flit[" << 0<< "][" << i << "].south)"<< "\n\n\n"; //core[(sw*2)+1]->flit_tx[0](flit[0][2].south); } for (int i = 0; i < sw ; i++) { cout << "t[" << stg-1 << "][" << i << "] -> flit_tx[0](flit[" << stg-1<< "][" << i << "].north)"<< "\n"; //t[stg-1][i]->flit_tx[0](flit[stg-1][i].north); cout << "core[" << i*2 << "]-> flit_rx[1](flit[" << stg-1<< "][" << i << "].north)"<< "\n"; //core[sw*2]->flit_rx[1](flit[stg-1][i].north); cout << "t[" << stg-1 << "][" << i << "] -> flit_tx[1](flit[" << stg-1<< "][" << i << "].east)"<< "\n"; //t[stg-1][i]->flit_tx[1](flit[stg-1][i].east); cout << "core[" << (i*2)+1 << "]-> flit_rx[1](flit[" << stg-1<< "][" << i << "].east)"<< "\n\n\n"; //core[(sw*2)+1]->flit_rx[1](flit[stg-1][i].east); } return 0; }
32.527778
106
0.443211
8e8d10bdad20e39f81a77ae435bc596de3919bb8
2,501
swift
Swift
Test/YoutubeVideoPlayerTests.swift
edx/edx-app-ios
b4e941b7d57ddff831acc76828881d7515428ac3
[ "Apache-2.0" ]
227
2015-01-17T05:23:31.000Z
2021-12-10T12:57:58.000Z
Test/YoutubeVideoPlayerTests.swift
edx/edx-app-ios
b4e941b7d57ddff831acc76828881d7515428ac3
[ "Apache-2.0" ]
1,387
2015-01-16T00:04:06.000Z
2021-12-06T06:58:08.000Z
Test/YoutubeVideoPlayerTests.swift
edx/edx-app-ios
b4e941b7d57ddff831acc76828881d7515428ac3
[ "Apache-2.0" ]
213
2015-01-15T04:38:19.000Z
2021-12-14T22:45:43.000Z
// // YoutubeVideoPlayerTests.swift // edXTests // // Created by AndreyCanon on 9/28/18. // Copyright © 2018 edX. All rights reserved. // import XCTest @testable import edX class YoutubeVideoPlayerTests: XCTestCase { let course = OEXCourse.freshCourse() var outline: CourseOutline! var environment: TestRouterEnvironment! var youtubeVideoPlayer : YoutubeVideoPlayer? let networkManager = MockNetworkManager(baseURL: URL(string: "www.example.com")!) override func setUp() { super.setUp() outline = CourseOutlineTestDataFactory.freshCourseOutline(course.course_id!) let youtubeConfig = ["ENABLED": false] as [String: Any] let config = OEXConfig(dictionary: ["COURSE_VIDEOS_ENABLED": true, "YOUTUBE_VIDEO": youtubeConfig]) let interface = OEXInterface.shared() environment = TestRouterEnvironment(config: config, interface: interface) environment.mockCourseDataManager.querier = CourseOutlineQuerier(courseID: outline.root, interface: interface, outline: outline) youtubeVideoPlayer = YoutubeVideoPlayer(environment: environment) } func testVideoPlay() { let summary = OEXVideoSummary(videoID: "some-video", name: "Youtube Video", encodings: [ OEXVideoEncodingYoutube: OEXVideoEncoding(name: OEXVideoEncodingYoutube, url: "https://some-youtube-url/watch?v=abc123", size: 12)]) let video = OEXHelperVideoDownload() video.summary = summary youtubeVideoPlayer?.play(video: video) XCTAssertEqual("abc123", youtubeVideoPlayer?.videoID) } func testVideoPlayerProtraitView() { let screenSize: CGRect = UIScreen.main.bounds youtubeVideoPlayer?.setVideoPlayerMode(isPortrait: false) var landScapeSize = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height - (youtubeVideoPlayer?.viewHeightOffset ?? 0)) XCTAssertEqual(landScapeSize, youtubeVideoPlayer?.playerView.frame) landScapeSize = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.width * CGFloat(STANDARD_VIDEO_ASPECT_RATIO)) youtubeVideoPlayer?.setVideoPlayerMode(isPortrait: true) XCTAssertEqual(landScapeSize, youtubeVideoPlayer?.playerView.frame) } func testViewDidLoad() { youtubeVideoPlayer?.viewDidLoad() XCTAssertTrue((youtubeVideoPlayer?.playerView.isDescendant(of: (youtubeVideoPlayer?.view)!))!) } }
42.389831
144
0.702119
806a3870d995109893188afedc8e36ee23ae8bb5
2,202
java
Java
systests/uncategorized/src/test/java/org/apache/cxf/systest/clustering/LoadDistributorSequentialStrategy.java
kimjand/cxf
7dbef5304979fd2e864e0b9643d9e1c5e7da163b
[ "Apache-2.0" ]
839
2015-01-01T15:33:21.000Z
2022-03-31T02:40:34.000Z
systests/uncategorized/src/test/java/org/apache/cxf/systest/clustering/LoadDistributorSequentialStrategy.java
tottislove/cxf
837401d8b08449ea34304df68600514d1132c499
[ "Apache-2.0" ]
399
2015-01-07T19:59:38.000Z
2022-03-30T21:56:27.000Z
systests/uncategorized/src/test/java/org/apache/cxf/systest/clustering/LoadDistributorSequentialStrategy.java
tottislove/cxf
837401d8b08449ea34304df68600514d1132c499
[ "Apache-2.0" ]
1,581
2015-01-01T02:22:05.000Z
2022-03-31T13:29:27.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.cxf.systest.clustering; import java.util.List; import org.apache.cxf.clustering.SequentialStrategy; import org.apache.cxf.endpoint.Endpoint; import org.apache.cxf.message.Exchange; public class LoadDistributorSequentialStrategy extends SequentialStrategy { @Override public List<Endpoint> getAlternateEndpoints(Exchange exchange) { // Get the list of endpoints, including the current one. // This part is required for most FailoverStrategys that provide alternate // target endpoints for the LoadDistributorTargetSelector. List<Endpoint> alternateEndpoints = getEndpoints(exchange, true); // Put the original endpoint at the head of the list // This is only required if the client wants to always try one endpoint first, // which is not typically desired for a load distributed configuration // (but is required by one of the unit tests) Endpoint endpoint = exchange.getEndpoint(); String defaultAddress = endpoint.getEndpointInfo().getAddress(); for (Endpoint alternate : alternateEndpoints) { if (defaultAddress.equals(alternate.getEndpointInfo().getAddress())) { alternateEndpoints.remove(alternate); alternateEndpoints.add(0, alternate); break; } } return alternateEndpoints; } }
40.036364
86
0.717984
da5729a1621e7c3b81fe877233470050a98a9688
1,224
sql
SQL
membership.sql
filipe-martins/carametade.tk
837192880f34d205ba0489b7d7758eb138d21b0a
[ "MIT" ]
null
null
null
membership.sql
filipe-martins/carametade.tk
837192880f34d205ba0489b7d7758eb138d21b0a
[ "MIT" ]
null
null
null
membership.sql
filipe-martins/carametade.tk
837192880f34d205ba0489b7d7758eb138d21b0a
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Feb 27, 2017 at 04:46 PM -- Server version: 10.1.16-MariaDB -- PHP Version: 5.6.24 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `membership` -- -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE DATABASE membership; USE membership; CREATE TABLE `users` ( `id` int(11) NOT NULL, `username` varchar(20) NOT NULL, `email` varchar(40) NOT NULL, `password` varchar(128) NOT NULL, `is_activated` tinyint(1) NOT NULL, `reset_code` varchar(16) DEFAULT NULL, `fpassword_key` varchar(128) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
27.2
67
0.687092
a9982a08407202101f91cacae662660f77baeb60
16,384
html
HTML
docs/spring-i18n-support-starter/jacoco-aggregate/spring-i18n-support/com.namics.oss.spring.support.i18n.service/MessageManagementServiceImpl.java.html
merkle-open/spring-i18n-support
4edf347fe6563c6bfc892394a8121aa5ac373e9e
[ "MIT" ]
2
2018-01-05T16:55:17.000Z
2018-02-24T03:49:49.000Z
docs/spring-i18n-support-starter/jacoco-aggregate/spring-i18n-support/com.namics.oss.spring.support.i18n.service/MessageManagementServiceImpl.java.html
merkle-open/spring-i18n-support
4edf347fe6563c6bfc892394a8121aa5ac373e9e
[ "MIT" ]
1
2022-02-19T19:06:18.000Z
2022-02-19T19:06:18.000Z
docs/spring-i18n-support-starter/jacoco-aggregate/spring-i18n-support/com.namics.oss.spring.support.i18n.service/MessageManagementServiceImpl.java.html
namics/spring-i18n-support
4edf347fe6563c6bfc892394a8121aa5ac373e9e
[ "MIT" ]
1
2022-02-19T18:07:28.000Z
2022-02-19T18:07:28.000Z
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml" lang="en"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><link rel="stylesheet" href="../../jacoco-resources/report.css" type="text/css"/><link rel="shortcut icon" href="../../jacoco-resources/report.gif" type="image/gif"/><title>MessageManagementServiceImpl.java</title><link rel="stylesheet" href="../../jacoco-resources/prettify.css" type="text/css"/><script type="text/javascript" src="../../jacoco-resources/prettify.js"></script></head><body onload="window['PR_TAB_WIDTH']=4;prettyPrint()"><div class="breadcrumb" id="breadcrumb"><span class="info"><a href="../../jacoco-sessions.html" class="el_session">Sessions</a></span><a href="../../index.html" class="el_report">spring-i18n-support-starter</a> &gt; <a href="../index.html" class="el_bundle">spring-i18n-support</a> &gt; <a href="index.source.html" class="el_package">com.namics.oss.spring.support.i18n.service</a> &gt; <span class="el_source">MessageManagementServiceImpl.java</span></div><h1>MessageManagementServiceImpl.java</h1><pre class="source lang-java linenums">/* * Copyright 2000-2010 namics ag. All rights reserved. */ package com.namics.oss.spring.support.i18n.service; import com.namics.oss.spring.support.i18n.dao.MessageSourceManagementDao; import com.namics.oss.spring.support.i18n.dao.jpa.model.MessageResource; import com.namics.oss.spring.support.i18n.excel.Excel; import com.namics.oss.spring.support.i18n.excel.ExcelReader; import com.namics.oss.spring.support.i18n.excel.ExcelWriter; import com.namics.oss.spring.support.i18n.exception.I18nException; import com.namics.oss.spring.support.i18n.model.MessageResourceEntry; import com.namics.oss.spring.support.i18n.text.TextWriter; import com.namics.oss.spring.support.i18n.util.LocaleComparator; import com.namics.oss.spring.support.i18n.util.MessageResourceEntryComparator; import org.apache.commons.lang.LocaleUtils; import org.springframework.util.Assert; import javax.annotation.PostConstruct; import javax.management.MXBean; import java.io.BufferedOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.*; import java.util.Map.Entry; /** * MessageManagementServiceImpl. * * @author aschaefer, namics ag * @since Namics commons i18n 1.0 - Oct 19, 2010 */ @MXBean <span class="fc" id="L35">public class MessageManagementServiceImpl implements MessageManagementService {</span> private MessageSourceManagementDao messageSourceDao; <span class="fc" id="L39"> private Comparator&lt;MessageResourceEntry&gt; messageResourceEntryComparator = new MessageResourceEntryComparator();</span> <span class="fc" id="L41"> private Comparator&lt;Locale&gt; localeComparator = new LocaleComparator();</span> private ExcelWriter excelWriter; private ExcelReader excelReader; private TextWriter textWriter; @PostConstruct public void init() { <span class="fc" id="L51"> Assert.notNull(this.messageSourceDao, &quot;messageSourceDao must be configured!&quot;);</span> <span class="fc" id="L52"> }</span> /** * {@inheritDoc} * * @see MessageManagementService#getMessage(java.lang.String, java.util.Locale) */ @Override public String getMessage(String codeId, Locale locale) throws I18nException { <span class="fc" id="L62"> List&lt;MessageResource&gt; messages = this.messageSourceDao.findByCodeAndLang(codeId, locale.toString());</span> <span class="pc bpc" id="L63" title="1 of 4 branches missed."> if (messages != null &amp;&amp; messages.size() &gt; 0) {</span> <span class="fc" id="L64"> return messages.get(0).getMessage();</span> } <span class="fc" id="L66"> return null;</span> } /** * {@inheritDoc} * * @see MessageManagementService#getAllMessages() */ @Override public List&lt;MessageResourceEntry&gt; getAllMessages() throws I18nException { <span class="fc" id="L76"> List&lt;MessageResourceEntry&gt; result = convertMessageMapToResourceEntries(this.messageSourceDao.findAll());</span> <span class="fc" id="L77"> Collections.sort(result, this.messageResourceEntryComparator);</span> <span class="fc" id="L78"> return result;</span> } /** * {@inheritDoc} * * @see MessageManagementService#getAllMessagesGrouped() */ @Override public Map&lt;String, List&lt;MessageResourceEntry&gt;&gt; getAllMessagesGrouped() throws I18nException { <span class="fc" id="L90"> List&lt;MessageResourceEntry&gt; data = getAllMessages();</span> <span class="fc" id="L91"> Map&lt;String, List&lt;MessageResourceEntry&gt;&gt; result = new HashMap&lt;&gt;(data.size());</span> <span class="fc bfc" id="L92" title="All 2 branches covered."> for (MessageResourceEntry entry : data) {</span> <span class="fc bfc" id="L93" title="All 2 branches covered."> String type = entry.getType() != null ? entry.getType() : &quot;DEFAULT&quot;;</span> <span class="fc bfc" id="L94" title="All 2 branches covered."> if (!result.containsKey(type)) {</span> <span class="fc" id="L95"> result.put(type, new ArrayList&lt;MessageResourceEntry&gt;());</span> } <span class="fc" id="L97"> result.get(type).add(entry);</span> <span class="fc" id="L98"> }</span> <span class="fc" id="L99"> return result;</span> } /** * {@inheritDoc} * * @see MessageManagementService#getMessage(java.lang.String) */ @Override public MessageResourceEntry getMessage(String codeId) throws I18nException { <span class="fc" id="L109"> List&lt;MessageResourceEntry&gt; messages = getAllMessages();</span> <span class="fc bfc" id="L110" title="All 2 branches covered."> for (MessageResourceEntry entry : messages) {</span> <span class="fc bfc" id="L111" title="All 2 branches covered."> if (entry.getCodeId().equals(codeId)) {</span> <span class="fc" id="L112"> return entry;</span> } <span class="fc" id="L114"> }</span> <span class="fc" id="L115"> return null;</span> } /** * {@inheritDoc} * * @see MessageManagementService#putMessage(java.lang.String, java.util.Locale, * java.lang.String) */ @Override public void putMessage(String codeId, Locale locale, String message, String type) throws I18nException { <span class="fc" id="L129"> Assert.hasLength(codeId);</span> <span class="fc" id="L130"> Assert.notNull(locale);</span> <span class="fc" id="L131"> LocaleUtils.toLocale(locale.toString()); // this validates the locale</span> <span class="fc" id="L132"> Assert.hasLength(message);</span> <span class="fc" id="L133"> MessageResource persisted = this.messageSourceDao.findTopByCodeAndLang(codeId, locale.toString());</span> <span class="fc bfc" id="L134" title="All 2 branches covered."> if (persisted != null) {</span> //update case <span class="fc" id="L136"> persisted.message(message).type(type);</span> } else { //insert case <span class="fc" id="L139"> persisted = new MessageResource()</span> <span class="fc" id="L140"> .code(codeId)</span> <span class="fc" id="L141"> .lang(locale.toString())</span> <span class="fc" id="L142"> .message(message)</span> <span class="fc" id="L143"> .type(type);</span> <span class="fc bfc" id="L144" title="All 2 branches covered."> persisted.id((type == null ? &quot;&quot; : type) + codeId + locale.toString());</span> } <span class="fc" id="L146"> this.messageSourceDao.save(persisted);</span> <span class="fc" id="L147"> }</span> /** * {@inheritDoc} * * @see MessageManagementService#putMessage(java.lang.String, java.util.Locale, * java.lang.String) */ @Override public void putMessage(String codeId, Locale locale, String message) throws I18nException { <span class="fc" id="L159"> putMessage(codeId, locale, message, null);</span> <span class="fc" id="L160"> }</span> /** * {@inheritDoc} * * @see MessageManagementService#exportToExcel2007(java.io.OutputStream) */ @Override public void exportToExcel2007(OutputStream output) throws I18nException { <span class="fc" id="L169"> Assert.notNull(output);</span> <span class="fc" id="L170"> Assert.notNull(this.excelWriter, &quot;you have to configure an excelWriter to use this operation.&quot;);</span> <span class="fc" id="L171"> Map&lt;String, List&lt;MessageResourceEntry&gt;&gt; exportable = getAllMessagesGrouped();</span> <span class="fc" id="L172"> this.excelWriter.createExcel(exportable, output, Excel.FORMAT_EXCEL_2007);</span> <span class="fc" id="L173"> }</span> /** * Be careful: Do not use a BufferedOutputStream for this implementation. {@inheritDoc} * * @see MessageManagementService#exportToExcel97(java.io.OutputStream) */ @Override public void exportToExcel97(OutputStream output) throws I18nException { <span class="fc" id="L182"> Assert.notNull(output);</span> <span class="fc" id="L183"> Assert.notNull(this.excelWriter, &quot;you have to configure an excelWriter to use this operation.&quot;);</span> <span class="pc bpc" id="L184" title="1 of 2 branches missed."> Assert.isTrue(!(output instanceof BufferedOutputStream));</span> <span class="fc" id="L185"> Map&lt;String, List&lt;MessageResourceEntry&gt;&gt; exportable = getAllMessagesGrouped();</span> <span class="fc" id="L186"> this.excelWriter.createExcel(exportable, output, Excel.FORMAT_EXCEL_97);</span> <span class="fc" id="L187"> }</span> @Override public void exportToText(OutputStream output) throws I18nException { <span class="fc" id="L191"> Assert.notNull(output);</span> <span class="fc" id="L192"> Assert.notNull(this.textWriter, &quot;you have to configure a textWriter to use this operation.&quot;);</span> <span class="fc" id="L193"> Map&lt;String, List&lt;MessageResourceEntry&gt;&gt; exportable = getAllMessagesGrouped();</span> <span class="fc" id="L194"> this.textWriter.createOutput(exportable, output);</span> <span class="fc" id="L195"> }</span> /** * {@inheritDoc} * * @see MessageManagementService#importFromExcel(java.io.InputStream) */ @Override public void importFromExcel(InputStream input) throws I18nException { <span class="fc" id="L204"> Assert.notNull(input);</span> <span class="fc" id="L205"> Assert.notNull(this.excelReader, &quot;you have to configure an excelReader to use this operation.&quot;);</span> <span class="fc" id="L206"> List&lt;MessageResourceEntry&gt; data = this.excelReader.processExcel(input);</span> <span class="fc bfc" id="L207" title="All 2 branches covered."> for (MessageResourceEntry entry : data) {</span> <span class="fc" id="L208"> String codeId = entry.getCodeId();</span> <span class="fc bfc" id="L209" title="All 2 branches covered."> for (Entry&lt;Locale, String&gt; langVal : entry.getNameMappings().entrySet()) {</span> <span class="fc" id="L210"> putMessage(codeId, langVal.getKey(), langVal.getValue(), entry.getType());</span> <span class="fc" id="L211"> }</span> <span class="fc" id="L212"> }</span> <span class="fc" id="L213"> }</span> /** * {@inheritDoc} * * @see MessageManagementService#getAvailableLanguages() */ @Override public List&lt;Locale&gt; getAvailableLanguages() throws I18nException { <span class="fc" id="L222"> List&lt;Locale&gt; locales = convertStringLangsToLocale(this.messageSourceDao.findDistinctLang());</span> <span class="fc" id="L223"> Collections.sort(locales, this.localeComparator);</span> <span class="fc" id="L224"> return locales;</span> } /** * {@inheritDoc} * * @see MessageManagementService#deleteMessage(java.lang.String) */ @Override public void deleteMessage(String codeId) throws I18nException { <span class="fc" id="L235"> Long rowsAffected = this.messageSourceDao.deleteByCode(codeId);</span> <span class="pc bpc" id="L236" title="2 of 4 branches missed."> if (rowsAffected == null || rowsAffected &lt; 1) {</span> <span class="nc" id="L237"> throw new I18nException(&quot;no message deleted with this code&quot;);</span> } <span class="fc" id="L239"> }</span> /** * {@inheritDoc} * * @see MessageManagementService#deleteMessage(java.lang.String) */ @Override public void deleteMessageForLanguage(String codeId, Locale locale) throws I18nException { <span class="nc" id="L248"> Long rowsAffected = this.messageSourceDao.deleteByCodeAndLang(codeId, locale.toString());</span> <span class="nc bnc" id="L249" title="All 4 branches missed."> if (rowsAffected == null || rowsAffected &lt; 0) {</span> <span class="nc" id="L250"> throw new I18nException(&quot;error on deleting message with code &quot; + codeId);</span> } <span class="nc" id="L252"> }</span> private List&lt;Locale&gt; convertStringLangsToLocale(List&lt;String&gt; languages) { <span class="fc" id="L255"> List&lt;Locale&gt; locales = new ArrayList&lt;&gt;(languages.size());</span> <span class="fc bfc" id="L256" title="All 2 branches covered."> for (String lang : languages) {</span> <span class="fc" id="L257"> locales.add(LocaleUtils.toLocale(lang));</span> <span class="fc" id="L258"> }</span> <span class="fc" id="L259"> return locales;</span> } private List&lt;MessageResourceEntry&gt; convertMessageMapToResourceEntries(List&lt;MessageResource&gt; input) { <span class="fc" id="L263"> Map&lt;String, MessageResourceEntry&gt; entries = new HashMap&lt;&gt;(input.size());</span> <span class="fc bfc" id="L264" title="All 2 branches covered."> for (MessageResource entry : input) {</span> <span class="fc bfc" id="L265" title="All 2 branches covered."> if (entries.containsKey(entry.getCode())) {</span> <span class="fc" id="L266"> entries.get(entry.getCode()).addLang(LocaleUtils.toLocale(entry.getLang()), entry.getMessage());</span> } else { <span class="fc" id="L268"> MessageResourceEntry data = new MessageResourceEntry();</span> <span class="fc" id="L269"> data.setCodeId(entry.getCode());</span> <span class="fc" id="L270"> data.addLang(LocaleUtils.toLocale(entry.getLang()), entry.getMessage());</span> <span class="fc" id="L271"> data.setType(entry.getType());</span> <span class="fc" id="L272"> entries.put(entry.getCode(), data);</span> } <span class="fc" id="L274"> }</span> <span class="fc" id="L275"> List&lt;MessageResourceEntry&gt; result = new ArrayList&lt;&gt;(entries.size());</span> <span class="fc" id="L276"> result.addAll(entries.values());</span> <span class="fc" id="L277"> return result;</span> } // CHECKSTYLE:OFF /** * Setter for messageSourceDao. @param messageSourceDao the messageSourceDao to set */ public void setMessageSourceDao(MessageSourceManagementDao messageSourceDao) { <span class="fc" id="L286"> this.messageSourceDao = messageSourceDao;</span> <span class="fc" id="L287"> }</span> /** * Setter for excelWriter. @param excelWriter the excelWriter to set */ public void setExcelWriter(ExcelWriter excelWriter) { <span class="fc" id="L293"> this.excelWriter = excelWriter;</span> <span class="fc" id="L294"> }</span> /** * Setter for excelReader. @param excelReader the excelReader to set */ public void setExcelReader(ExcelReader excelReader) { <span class="fc" id="L300"> this.excelReader = excelReader;</span> <span class="fc" id="L301"> }</span> /** * Setter for messageResourceEntryComparator. @param messageResourceEntryComparator the * messageResourceEntryComparator to set */ public void setMessageResourceEntryComparator(Comparator&lt;MessageResourceEntry&gt; messageResourceEntryComparator) { <span class="nc" id="L308"> this.messageResourceEntryComparator = messageResourceEntryComparator;</span> <span class="nc" id="L309"> }</span> /** * Setter for localeComparator. @param localeComparator the localeComparator to set */ public void setLocaleComparator(Comparator&lt;Locale&gt; localeComparator) { <span class="nc" id="L315"> this.localeComparator = localeComparator;</span> <span class="nc" id="L316"> }</span> /** * Setter for textWriter. @param textWriter the textWriter to set */ public void setTextWriter(TextWriter textWriter) { <span class="fc" id="L322"> this.textWriter = textWriter;</span> <span class="fc" id="L323"> }</span> // CHECKSTYLE:ON } </pre><div class="footer"><span class="right">Created with <a href="http://www.jacoco.org/jacoco">JaCoCo</a> 0.8.0.201801022044</span></div></body></html>
50.103976
1,251
0.709534
40f940c7a9d3b27016e59fda31f94432d4ed715b
1,535
py
Python
seg/2021Tianchi_RS/code/count_classes.py
HkkSimple/exp
14d708e5f581ccd5875d1773ae08d280bd8a0978
[ "Apache-2.0" ]
null
null
null
seg/2021Tianchi_RS/code/count_classes.py
HkkSimple/exp
14d708e5f581ccd5875d1773ae08d280bd8a0978
[ "Apache-2.0" ]
null
null
null
seg/2021Tianchi_RS/code/count_classes.py
HkkSimple/exp
14d708e5f581ccd5875d1773ae08d280bd8a0978
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Tue Jan 19 20:22:41 2021 @author: DELL """ import gdal import numpy as np import matplotlib.pyplot as plt import glob # 初始化每个类的数目 Cultivatedland_num = 0 Woodland_num = 0 Grass_num = 0 Road_num = 0 UrbanConstructionLand_num = 0 RuralConstructionLand_num = 0 IndustrialLand_num = 0 Structure_num = 0 Water_num = 0 NakedLand_num = 0 label_paths = glob.glob(r'E:\WangZhenQing\TianChi\tcdata\suichang_round1_train_210120\*.png') for label_path in label_paths: label = gdal.Open(label_path).ReadAsArray(0, 0, 256, 256) Cultivatedland_num += np.sum(label == 1) Woodland_num += np.sum(label == 2) Grass_num += np.sum(label == 3) Road_num += np.sum(label == 4) UrbanConstructionLand_num += np.sum(label == 5) RuralConstructionLand_num += np.sum(label == 6) IndustrialLand_num += np.sum(label == 7) Structure_num += np.sum(label == 8) Water_num += np.sum(label == 9) NakedLand_num += np.sum(label == 10) # 这两行代码解决 plt 中文显示的问题 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False classes = ('耕地', '林地', '草地', '道路', '城镇建设用地', '农村建设用地', '工业用地', '构筑物', '水域', '裸地') numbers = [Cultivatedland_num, Woodland_num, Grass_num, Road_num, UrbanConstructionLand_num, RuralConstructionLand_num, IndustrialLand_num, Structure_num, Water_num, NakedLand_num] plt.barh(classes, numbers) plt.title('地物要素类别像素数目') plt.savefig("地物要素类别像素数目图3.png", dpi = 300, bbox_inches="tight") plt.show()
30.098039
181
0.685342
682d34fd54c2e9b4bd5d4da3cfa24600810ad173
28,491
html
HTML
kampungSubWeb/index.html
priliviarf/kampungpreneur
dfdea4b8fda35973f0232b096c1f67f92a8869f3
[ "MIT" ]
null
null
null
kampungSubWeb/index.html
priliviarf/kampungpreneur
dfdea4b8fda35973f0232b096c1f67f92a8869f3
[ "MIT" ]
null
null
null
kampungSubWeb/index.html
priliviarf/kampungpreneur
dfdea4b8fda35973f0232b096c1f67f92a8869f3
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="id"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="keyword" content="kampungpreneur, ugm, enterpreneur"> <meta name="author" content="KampungPreneur IT Support Team"> <meta name="robots" content="index,follow"> <title>KampungPreneur</title> <!-- Shortcut icon --> <link rel="shortcut icon" type="x-icon" href="../assets/img/icon.png"> <!-- CSS HERE --> <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="../assets/css/loader.css"> <link rel="stylesheet" type="text/css" href="../assets/css/animate.css"> <link rel="stylesheet" type="text/css" href="../assets/css/normalize.css"> <link rel="stylesheet" type="text/css" href="../assets/css/kampungpreneur-style.css"> <link rel="stylesheet" type="text/css" href="../assets/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="../assets/css/owl.carousel.css"> <link rel="stylesheet" type="text/css" href="../assets/css/owl.theme.default.css"> <link rel="stylesheet" type="text/css" href="../assets/css/lightcase.css"> <!-- JAVASCRIPT HERE --> <script type="text/javascript" src="../assets/js/jquery.js"></script> <script type="text/javascript" src="../assets/js/bootstrap.min.js"></script> <script type="text/javascript" src="../assets/js/owl.carousel.js"></script> <script type="text/javascript" src="../assets/js/lightcase.js"></script> <script type="text/javascript" src="../assets/js/main.js"></script> </head> <body> <!-- Navbar section *this --> <section> <nav id="navbar" class="navbar navbar-dafult navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#Navbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"> <img src="../assets/img/logo.png"> </a> </div> <div class="collapse navbar-collapse" id="Navbar"> <ul class="nav navbar-nav navbar-right"> <li><a href="#header">BERANDA</a></li> <li><a href="#about">TENTANG KAMI</a></li> <li><a href="#news">BERITA</a></li> <li><a href="#store">USAHA KAMI</a></li> <li><a href="#gallery">GALLERY FOTO</a></li> <li><a href="../index.html">KAMPUNGPRENEUR</a></li> <li><a href="../register.html"><i class="fa fa-user fa-lg"></i> DAFTAR</a></li> <li><a href="../signin.html"><i class="fa fa-sign-in fa-lg"></i> MASUK</a></li> </ul> </div> </div> </nav> </section> <!-- Header *this --> <section id="header"> <div class="headerCover headerCover-2"> <figure> <img src="../assets/img/bg-header-news.png" style="background-image: url(../assets/img/wallpaper.jpg);"> <div class="overlay"></div> </figure> <div class="container containerCenter wh alignCenter"> <div class="col-md-8 col-sm-12 col-xs-12 beCenter"> <h1 class="h1-mainTitle">NAMA KAMPUNG</h1> <hr class="hrTitle"> <span> <p class="normal mg-b-20"> Lorem ipsum dolor sit amet, eos at nobis expetendis, nec cu wisi summo fastidii. Cu dicit habemus has, duo id suas autem nominati, sit id homero essent eleifend. </p> </span> </div> </div> </div> </section> <!-- About *this --> <section id="about" class="aboutSubWeb"> <div class="container-fluid areaContainer"> <h2 class="h2-title">TENTANG KAMI</h2> <hr class="hrTitle"> <section class="row"> <div class="col-md-5"> <figure> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/wallpaper3.jpg');"> </figure> </div> <div class="col-md-7"> <section class="aboutSide"> <h3 class="bl openSansBold">NAMA KAMPUNG</h3> <article class="mg-b-30"> <p> Lorem ipsum dolor sit amet, quas integre sit no, mei velit virtute oportere cu. Aeque adipisci instructior sit ne, equidem imperdiet ullamcorper cum no. Cu est integre democritum, mediocrem democritum ullamcorper no sit. Minim latine vix ut. </p> <p> Vix eu etiam mediocrem. Qui debet essent omnium ut. Ne qui recusabo temporibus, in eum singulis posidonium. Nec reque saepe ea, esse veniam definitionem est ei. </p> <p> Aliquam principes deterruisset cum et, vel an eius equidem. Id quando legimus inermis eum, cibo consul democritum cum te, cu cum suas laudem graeci. Bonorum gloriatur signiferumque an pro. Justo corpora suscipit quo et, vim te noluisse praesent scriptorem, pro ea incorrupte intellegam mediocritatem. Hinc laoreet mediocrem te nec, petentium iracundia ut cum. Fabulas ornatus iudicabit an pri, qui at decore legimus voluptatibus. Ei semper adipisci constituto eum, ad reque dicam nec. </p> </article> <table class="table table-hover"> <tbody> <tr> <td width="5%"><i class="fa fa-black-tie"></i></td> <td width="20%">Penanggung Jawab </td> <td>Lorem ipsum dolor</td> </tr> <tr> <td width="5%"><i class="fa fa-map-marker"></i></td> <td width="20%">Alamat </td> <td>Vix eu etiam mediocrem. Qui debet essent omnium ut. Ne qui recusabo temporibus</td> </tr> <tr> <td width="5%"><i class="fa fa-phone"></i></td> <td width="20%">Nomor Telepon</td> <td>+62 <span>888 8888 8888</span></td> </tr> </tbody> </table> </section> </div> </section> </div> </section> <!-- News --> <section id="news"> <div class="container-fluid areaContainer"> <h2 class="h2-title">BERITA</h2> <hr class="hrTitle"> <section class="row"> <div class="col-md-offset-3 col-md-6 col-sm-offset-2 col-sm-8"> <p class="alignCenter small"> Quod fierent torquatos no sit. Mundi blandit suscipiantur per an, et duis atqui rationibus quo. Oblique labores vix at, cu modus veritus ius. In dicant legendos complectitur duo. Labitur legimus ex mea, graecis intellegat pri ex. </p> </div> </section> <section class="row pd-lr-30"> <div class="col-md-offset-0 col-md-6 col-sm-offset-1 col-sm-10"> <a href="#"> <section class="post mg-bt-20"> <section class="row"> <div class="col-md-6 col-sm-6"> <figure> <img src="../assets/img/bg-news.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> <p class="slideInSection"><i class="fa fa-eye"></i> 22 Pembaca</p> </figure> </div> <div class="col-md-6 col-sm-6"> <article> <div class="category cat-bl"> <span>Category1</span> </div> <h4 class="h4-spec big linkHover">Lorem ipsum dolor sit amet</h4> <p class="date mg-b-10"><i class="fa fa-clock-o"></i> 23 March 2017</p> <p class="normal sourceSansRegular black"> Delenit fierent honestatis has et, sit an clita verear, ex philosophia consequuntur cum. Commodo probatus cu usu. Sit discere nermis facilisi ea, sea ad ... </p> </article> </div> </section> </section> </a> </div> <div class="col-md-offset-0 col-md-6 col-sm-offset-1 col-sm-10"> <a href="#"> <section class="post mg-bt-20"> <section class="row"> <div class="col-md-6 col-sm-6"> <figure> <img src="../assets/img/bg-news.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> <p class="slideInSection"><i class="fa fa-eye"></i> 22 Pembaca</p> </figure> </div> <div class="col-md-6 col-sm-6"> <article class="pd-bt-15 pd-lr-10"> <div class="category cat-black"> <span>Category2</span> </div> <h4 class="h4-spec big linkHover">Lorem ipsum dolor sit amet</h4> <p class="date mg-b-10"><i class="fa fa-clock-o"></i> 23 March 2017</p> <p class="normal sourceSansRegular black"> Delenit fierent honestatis has et, sit an clita verear, ex philosophia consequuntur cum. Commodo probatus cu usu. Sit discere nermis facilisi ea, sea ad ... </p> </article> </div> </section> </section> </a> </div> </section> <section class="row pd-lr-30"> <div class="col-md-offset-0 col-md-6 col-sm-offset-1 col-sm-10"> <a href="#"> <section class="post mg-bt-20"> <section class="row"> <div class="col-md-6 col-sm-6"> <figure> <img src="../assets/img/bg-news.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> <p class="slideInSection"><i class="fa fa-eye"></i> 22 Pembaca</p> </figure> </div> <div class="col-md-6 col-sm-6"> <article class="pd-bt-15 pd-lr-10"> <div class="category cat-or"> <span>Category3</span> </div> <h4 class="h4-spec big linkHover">Lorem ipsum dolor sit amet</h4> <p class="date mg-b-10"><i class="fa fa-clock-o"></i> 23 March 2017</p> <p class="normal sourceSansRegular black"> Delenit fierent honestatis has et, sit an clita verear, ex philosophia consequuntur cum. Commodo probatus cu usu. Sit discere nermis facilisi ea, sea ad ... </p> </article> </div> </section> </section> </a> </div> <div class="col-md-offset-0 col-md-6 col-sm-offset-1 col-sm-10"> <a href="#"> <section class="post mg-bt-20"> <section class="row"> <div class="col-md-6 col-sm-6"> <figure> <img src="../assets/img/bg-news.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> <p class="slideInSection"><i class="fa fa-eye"></i> 22 Pembaca</p> </figure> </div> <div class="col-md-6 col-sm-6"> <article class="pd-bt-15 pd-lr-10"> <div class="category cat-gr"> <span>Category4</span> </div> <h4 class="h4-spec big linkHover">Lorem ipsum dolor sit amet</h4> <p class="date mg-b-10"><i class="fa fa-clock-o"></i> 23 March 2017</p> <p class="normal sourceSansRegular black"> Delenit fierent honestatis has et, sit an clita verear, ex philosophia consequuntur cum. Commodo probatus cu usu. Sit discere nermis facilisi ea, sea ad ... </p> </article> </div> </section> </section> </a> </div> </section> <section class="row mg-bt-20"> <div class="alignCenter mg-b-20"> <a href="./news.html" class="btn2"> <i class="fa fa-spinner fa-spin fa-fw"></i> <span>BERITA SELENGKAPNYA</span> </a> </div> </section> </div> </section> <!-- Store --> <section id="store"> <div class="container-fluid areaContainer"> <h2 class="h2-title">USAHA KAMI</h2> <hr class="hrTitle"> <section class="row"> <div class="col-md-offset-3 col-md-6 col-sm-offset-2 col-sm-8"> <p class="alignCenter small"> Quod fierent torquatos no sit. Mundi blandit suscipiantur per an, et duis atqui rationibus quo. Oblique labores vix at, cu modus veritus ius. In dicant legendos complectitur duo. Labitur legimus ex mea, graecis intellegat pri ex. </p> </div> </section> <section class="row mg-t-30"> <div class="owl-carousel owl-theme carousel-2"> <div class="item"> <div class="items"> <section class="storeItem"> <div class="overlay"></div> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="detailItem containerCenter"> <p class="openSansSemiBold big">Product Name</p> <p>Product tag</p> <p class="openSansSemiBold lightor big">Rp 20.000</p> </div> <div class="itemAction"> <section class="row"> <!-- <div class="col-md-6 col-sm-6 col-xs-6 buy"> <a href="#"> <i class="fa fa-shopping-cart pd-r-10"></i> Beli </a> </div> --> <div class="col-md-8 col-md-offset-2 alignCenter detail"> <a href="#"> <i class="fa fa-info-circle pd-r-10"></i> Detail </a> </div> </section> </div> </section> </div> </div> <div class="item"> <div class="items"> <section class="storeItem"> <div class="overlay"></div> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery2.jpg');"> <div class="detailItem containerCenter"> <p class="openSansSemiBold big">Product Name</p> <p>Product tag</p> <p class="openSansSemiBold lightor big">Rp 20.000</p> </div> <div class="itemAction"> <section class="row"> <!-- <div class="col-md-6 col-sm-6 col-xs-6 buy"> <a href="#"> <i class="fa fa-shopping-cart pd-r-10"></i> Beli </a> </div> --> <div class="col-md-8 col-md-offset-2 alignCenter detail"> <a href="#"> <i class="fa fa-info-circle pd-r-10"></i> Detail </a> </div> </section> </div> </section> </div> </div> <div class="item"> <div class="items"> <section class="storeItem"> <div class="overlay"></div> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery3.jpg');"> <div class="detailItem containerCenter"> <p class="openSansSemiBold big">Product Name</p> <p>Product tag</p> <p class="openSansSemiBold lightor big">Rp 20.000</p> </div> <div class="itemAction"> <section class="row"> <!-- <div class="col-md-6 col-sm-6 col-xs-6 buy"> <a href="#"> <i class="fa fa-shopping-cart pd-r-10"></i> Beli </a> </div> --> <div class="col-md-8 col-md-offset-2 alignCenter detail"> <a href="#"> <i class="fa fa-info-circle pd-r-10"></i> Detail </a> </div> </section> </div> </section> </div> </div> <div class="item"> <div class="items"> <section class="storeItem"> <div class="overlay"></div> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/wallpaper.jpg');"> <div class="detailItem containerCenter"> <p class="openSansSemiBold big">Product Name</p> <p>Product tag</p> <p class="openSansSemiBold lightor big">Rp 20.000</p> </div> <div class="itemAction"> <section class="row"> <!-- <div class="col-md-6 col-sm-6 col-xs-6 buy"> <a href="#"> <i class="fa fa-shopping-cart pd-r-10"></i> Beli </a> </div> --> <div class="col-md-8 col-md-offset-2 alignCenter detail"> <a href="#"> <i class="fa fa-info-circle pd-r-10"></i> Detail </a> </div> </section> </div> </section> </div> </div> <div class="item"> <div class="items"> <section class="storeItem"> <div class="overlay"></div> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="detailItem containerCenter"> <p class="openSansSemiBold big">Product Name</p> <p>Product tag</p> <p class="openSansSemiBold lightor big">Rp 20.000</p> </div> <div class="itemAction"> <section class="row"> <!-- <div class="col-md-6 col-sm-6 col-xs-6 buy"> <a href="#"> <i class="fa fa-shopping-cart pd-r-10"></i> Beli </a> </div> --> <div class="col-md-8 col-md-offset-2 alignCenter detail"> <a href="#"> <i class="fa fa-info-circle pd-r-10"></i> Detail </a> </div> </section> </div> </section> </div> </div> <div class="item"> <div class="items"> <section class="storeItem"> <div class="overlay"></div> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery3.jpg');"> <div class="detailItem containerCenter"> <p class="openSansSemiBold big">Product Name</p> <p>Product tag</p> <p class="openSansSemiBold lightor big">Rp 20.000</p> </div> <div class="itemAction"> <section class="row"> <!-- <div class="col-md-6 buy"> <a href="#"> <i class="fa fa-shopping-cart pd-r-10"></i> Beli </a> </div> --> <div class="col-md-8 col-md-offset-2 alignCenter <a href="#"> <i class="fa fa-info-circle pd-r-10"></i> Detail </a> </div> </section> </div> </section> </div> </div> <div class="item"> <div class="items"> <section class="storeItem"> <div class="overlay"></div> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery2.jpg');"> <div class="detailItem containerCenter"> <p class="openSansSemiBold big">Product Name</p> <p>Product tag</p> <p class="openSansSemiBold lightor big">Rp 20.000</p> </div> <div class="itemAction"> <section class="row"> <!-- <div class="col-md-6 buy"> <a href="#"> <i class="fa fa-shopping-cart pd-r-10"></i> Beli </a> </div> --> <div class="col-md-8 col-md-offset-2 alignCenter <a href="#"> <i class="fa fa-info-circle pd-r-10"></i> Detail </a> </div> </section> </div> </section> </div> </div> <div class="item"> <div class="items"> <section class="storeItem"> <div class="overlay"></div> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="detailItem containerCenter"> <p class="openSansSemiBold big">Product Name</p> <p>Product tag</p> <p class="openSansSemiBold lightor big">Rp 20.000</p> </div> <div class="itemAction"> <section class="row"> <!-- <div class="col-md-6 buy"> <a href="#"> <i class="fa fa-shopping-cart pd-r-10"></i> Beli </a> </div> --> <div class="col-md-8 col-md-offset-2 alignCenter <a href="#"> <i class="fa fa-info-circle pd-r-10"></i> Detail </a> </div> </section> </div> </section> </div> </div> </div> </section> <section class="row mg-bt-20"> <div class="alignCenter mg-b-20"> <a href="./store.html" class="btn2"> <i class="fa fa-spinner fa-spin fa-fw"></i> <span>LIHAT SELENGKAPNYA</span> </a> </div> </section> </div> </section> <!-- Gallery *this --> <section id="gallery"> <div class="container-fluid areaContainer"> <h2 class="h2-title">GALLERY FOTO</h2> <hr class="hrTitle"> <section class="row pd-20"> <div class="col-md-3 col-sm-6"> <section class="galSec"> <a href="../assets/img/gallery1.jpg" data-rel="lightcase"> <figure> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> </figure> <i class="fa fa-search-plus wh fa-2x containerCenter"></i> </a> </section> </div> <div class="col-md-3 col-sm-6"> <section class="galSec"> <a href="../assets/img/gallery1.jpg" data-rel="lightcase"> <figure> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> </figure> <i class="fa fa-search-plus wh fa-2x containerCenter"></i> </a> </section> </div> <div class="col-md-3 col-sm-6"> <section class="galSec"> <a href="../assets/img/gallery1.jpg" data-rel="lightcase"> <figure> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> </figure> <i class="fa fa-search-plus wh fa-2x containerCenter"></i> </a> </section> </div> <div class="col-md-3 col-sm-6"> <section class="galSec"> <a href="../assets/img/gallery1.jpg" data-rel="lightcase"> <figure> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> </figure> <i class="fa fa-search-plus wh fa-2x containerCenter"></i> </a> </section> </div> <div class="col-md-3 col-sm-6"> <section class="galSec"> <a href="../assets/img/gallery1.jpg" data-rel="lightcase"> <figure> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> </figure> <i class="fa fa-search-plus wh fa-2x containerCenter"></i> </a> </section> </div> <div class="col-md-3 col-sm-6"> <section class="galSec"> <a href="../assets/img/gallery1.jpg" data-rel="lightcase"> <figure> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> </figure> <i class="fa fa-search-plus wh fa-2x containerCenter"></i> </a> </section> </div> <div class="col-md-3 col-sm-6"> <section class="galSec"> <a href="../assets/img/gallery1.jpg" data-rel="lightcase"> <figure> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> </figure> <i class="fa fa-search-plus wh fa-2x containerCenter"></i> </a> </section> </div> <div class="col-md-3 col-sm-6"> <section class="galSec"> <a href="../assets/img/gallery1.jpg" data-rel="lightcase"> <figure> <img src="../assets/img/bg.png" style="background-image: url('../assets/img/gallery1.jpg');"> <div class="overlay"></div> </figure> <i class="fa fa-search-plus wh fa-2x containerCenter"></i> </a> </section> </div> </section> <section class="row mg-bt-20"> <div class="alignCenter mg-b-20"> <a href="./gallery.html" class="btn2"> <i class="visible fa fa-spinner fa-spin fa-fw"></i> <span>LIHAT SELENGKAPNYA</span> </a> </div> </section> </div> </section> <!-- /Gallery --> <!-- Footer *this --> <footer> <div class="container-fluid pd-30"> <section class="row"> <div class="col-md-3 col-sm-3"> <section class="pd-bt-20"> <figure> <img src="../assets/img/logo.png"> </figure> <p class="small openSansRegular mg-t-30"> Quod fierent torquatos no sit. Mundi blandit suscipiantur per an, et duis atqui rationibus quo. Oblique labores vix at, cu modus veritus ius. In dicant legendos complectitur duo. Labitur legimus ex mea, graecis intellegat pri ex. </p> </section> </div> <div class="col-md-3 col-sm-3"> <section class="pd-20"> <h4 class="h4-spec mg-b-30">Kiriman Terbaru</h4> <section class="row pd-bt-10"> <a href="#"> <div class="col-md-4"> <figure> <img src="../assets/img/bg-news.png" style="background-image: url('../assets/img/wallpaper1.jpeg');"> </figure> </div> <div class="col-md-8 footerTitle"> <h5 class="linkHover normal openSansSemiBold noMag">Lorem ipsum dolor sit amet</h5> <p class="date mg-t-5 gray"><i class="fa fa-clock-o"></i> 23 March 2017</p> </div> </a> </section> <section class="row pd-bt-10"> <a href="#"> <div class="col-md-4"> <figure> <img src="../assets/img/bg-news.png" style="background-image: url('../assets/img/wallpaper1.jpeg');"> </figure> </div> <div class="col-md-8 footerTitle"> <h5 class="linkHover normal openSansSemiBold noMag">Lorem ipsum dolor sit amet</h5> <p class="date mg-t-5 gray"><i class="fa fa-clock-o"></i> 23 March 2017</p> </div> </a> </section> <section class="row pd-bt-10"> <a href="#"> <div class="col-md-4"> <figure> <img src="../assets/img/bg-news.png" style="background-image: url('../assets/img/wallpaper1.jpeg');"> </figure> </div> <div class="col-md-8 footerTitle"> <h5 class="linkHover normal openSansSemiBold noMag">Lorem ipsum dolor sit amet</h5> <p class="date mg-t-5 gray"><i class="fa fa-clock-o"></i> 23 March 2017</p> </div> </a> </section> </section> </div> <div class="col-md-2 col-sm-3"> <section class="pd-20"> <h4 class="h4-spec mg-b-30">Tautan Lain</h4> <ul class="noPad"> <li><a href="#">KAMPUNGPRENEUR</a></li> <li><a href="#">PENDAMPINGAN</a></li> <li><a href="#">BANTUAN MODAL</a></li> <li><a href="#">PEMASARAN</a></li> </ul> </section> </div> <div class="floatRight col-md-4 col-sm-3"> <section class="pd-20"> <h4 class="h4-spec mg-b-30">Hubungi Nama Kampung</h4> <section class="row pd-bt-10"> <div class="col-md-1 col-sm-1 col-xs-1"> <i class="fa-lg fa fa-map-marker"></i> </div> <div class="col-md-8 col-sm-11 col-xs-11"> <p class="openSansRegular small"> Qui debet essent omnium ut. Ne qui recusabo temporibus, in eum singulis posidonium. </p> </div> </section> <section class="row pd-bt-10"> <div class="col-md-1 col-sm-1 col-xs-1"> <i class="fa-lg fa fa-phone"></i> </div> <div class="col-md-8 col-sm-11 col-xs-11"> <p class="openSansRegular small"> +62 888 8888 8888 </p> </div> </section> <section class="row pd-bt-10"> <div class="col-md-1 col-sm-1 col-xs-1"> <i class="fa-lg fa fa-envelope"></i> </div> <div class="col-md-8 col-sm-11 col-xs-11"> <p class="openSansRegular small"> namakampung@mail.com </p> </div> </section> </section> </div> </section> </div> </footer> <!-- Copyright --> <section id="copyright"> <div class="container-fluid pd-30"> <section class="row"> <div class="floatRight col-md-6 col-sm-6 col-xs-12 socialMedia alignRight"> <ul class="noPad"> <li><a class="fb" href="#"><i class="fa fa-facebook-official"></i></a></li> <li><a class="tw" href="#"><i class="fa fa-twitter"></i></a></li> <li><a class="ig" href="#"><i class="fa fa-instagram"></i></a></li> <li><a class="wA" href="#"><i class="fa fa-whatsapp"></i></a></li> </ul> </div> <div class="floatRight col-md-6 col-sm-6 col-xs-12"> <p class="noMag openSansRegular">Made with love in Yogyakarta</p> <p class="noMag openSansRegular pd-t-5">By KampungPreneur IT Support Team</p> </div> </section> </div> </section> <!-- SOME JAVASCRIPT HERE --> <script type="text/javascript"> $(document).ready(function(){ // new WOW().init(); // to ease when click '#' url $(document).on('click', 'a', function(event){ if($.attr(this, 'href').charAt(0)=='#'){ event.preventDefault(); $('html, body').animate({ scrollTop: $( $.attr(this, 'href') ).offset().top }, 1000); } }); }); </script> </body> </html>
37.001299
491
0.550244
978d7bd1bc96791f69e65186f8f1ece43db046b4
203
lua
Lua
MMOCoreORB/bin/scripts/object/custom_content/tangible/quest/mysess_blossom.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/bin/scripts/object/custom_content/tangible/quest/mysess_blossom.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/bin/scripts/object/custom_content/tangible/quest/mysess_blossom.lua
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
object_tangible_quest_mysess_blossom = object_tangible_quest_shared_mysess_blossom:new { } ObjectTemplates:addTemplate(object_tangible_quest_mysess_blossom, "object/tangible/quest/mysess_blossom.iff")
33.833333
109
0.8867
96adb0742019612d35df87e5badfa4477a281ac0
6,815
cpp
C++
threepp/controls/Orbit.cpp
melMass/three.cpp
5a328b40036e359598baec8b3fcddae4f33e410a
[ "MIT" ]
1
2020-06-11T19:03:58.000Z
2020-06-11T19:03:58.000Z
threepp/controls/Orbit.cpp
melMass/three.cpp
5a328b40036e359598baec8b3fcddae4f33e410a
[ "MIT" ]
null
null
null
threepp/controls/Orbit.cpp
melMass/three.cpp
5a328b40036e359598baec8b3fcddae4f33e410a
[ "MIT" ]
null
null
null
// // Created by byter on 12/24/17. // #include "Orbit.h" #include <threepp/math/Math.h> #include <threepp/camera/PerspectiveCamera.h> #include <threepp/camera/OrthographicCamera.h> namespace three { namespace control { using namespace std; using namespace math; bool Orbit::update() { _offset = _camera->position() - target; // rotate offset to "y-axis-is-up" space _offset.apply(_quat); // angle from z-axis around y-axis _spherical.setFromVector3(_offset); if (autoRotate && _state == State::NONE) { rotateLeft(getAutoRotationAngle()); } _spherical.theta() += _sphericalDelta.theta(); _spherical.phi() += _sphericalDelta.phi(); // restrict theta to be between desired limits _spherical.theta() = std::max(minAzimuthAngle, std::min(maxAzimuthAngle, _spherical.theta())); // restrict phi to be between desired limits _spherical.phi() = std::max(minPolarAngle, std::min(maxPolarAngle, _spherical.phi())); _spherical.makeSafe(); _spherical.radius() *= scale; // restrict radius to be between desired limits _spherical.radius() = std::max(minDistance, std::min(maxDistance, _spherical.radius())); // move target to panned location target += _panOffset; _offset = math::Vector3::fromSpherical(_spherical); // rotate offset back to "camera-up-vector-is-up" space _offset.apply(_quatInverse); _camera->position() = target + _offset; _camera->lookAt(target); if (enableDamping) { _sphericalDelta.theta() *= (1 - dampingFactor); _sphericalDelta.phi() *= (1 - dampingFactor); } else { _sphericalDelta.set(0, 0, 0); } scale = 1; _panOffset.set(0, 0, 0); // update condition is: // min(camera displacement, camera rotation in radians)^2 > EPS // using small-angle approximation cos(x/2) = 1 - x^2 / 8 if (_zoomChanged || lastPosition.distanceToSquared(_camera->position()) > EPS || 8 * (1 - lastQuaternion.dot(_camera->quaternion())) > EPS) { onChanged.emitSignal(_state); lastPosition = _camera->position(); lastQuaternion = _camera->quaternion(); _zoomChanged = false; return true; } return false; } void Orbit::_pan(float deltaX, float deltaY) { if(PerspectiveCamera *pcamera = _camera->typer) { // perspective math::Vector3 offset = _camera->position() - target; float targetDistance = offset.length(); // half of the fov is center to top of screen targetDistance *= tan((pcamera->fov() / 2.0f) * M_PI / 180.0f); // we actually don't use screenWidth, since perspective camera is fixed to screen height if (deltaX != 0) panLeft(2.0f * deltaX * targetDistance / clientHeight(), pcamera->matrix()); if (deltaY != 0) panUp(2.0f * deltaY * targetDistance / clientHeight(), pcamera->matrix()); } else if(OrthographicCamera *ocamera = _camera->typer) { // orthographic if (deltaX != 0) panLeft(deltaX * (ocamera->right() - ocamera->left()) / ocamera->zoom() / clientWidth(), ocamera->matrix()); if (deltaY != 0) panUp(deltaY * (ocamera->top() - ocamera->bottom()) / ocamera->zoom() / clientHeight(), ocamera->matrix()); } else { // camera neither orthographic nor perspective enablePan = false; } } void Orbit::_dollyIn(float dollyScale) { if(PerspectiveCamera *pcamera = _camera->typer) { scale /= dollyScale; update(); } else if(OrthographicCamera *ocamera = _camera->typer) { ocamera->setZoom(std::max(minZoom, std::min(maxZoom, ocamera->zoom() * dollyScale))); ocamera->updateProjectionMatrix(); _zoomChanged = true; } else { // camera neither orthographic nor perspective enableZoom = false; } } void Orbit::_dollyOut(float dollyScale) { if(PerspectiveCamera *pcamera = _camera->typer) { scale *= dollyScale; update(); } else if(OrthographicCamera *ocamera = _camera->typer) { ocamera->setZoom(std::max(minZoom, std::min(maxZoom, ocamera->zoom() / dollyScale))); ocamera->updateProjectionMatrix(); _zoomChanged = true; } else { // camera neither orthographic nor perspective enableZoom = false; } } void Orbit::startRotate(unsigned x, unsigned y) { _rotateStart.set(x, y); _state = State::ROTATE; } void Orbit::startZoom(unsigned x, unsigned y) { _dollyStart.set(x, y); _state = State::DOLLY; } void Orbit::startPan(unsigned x, unsigned y) { _panStart.set(x, y); _state = State::PAN; } bool Orbit::resetState() { if (_state != State::NONE) { _state = State::NONE; return true; } return false; } bool Orbit::handleMove(unsigned x, unsigned y) { switch (_state) { case State::ROTATE: doRotate(x, y); return true; case State::DOLLY: doDolly(x, y); return true; case State::PAN: doPan(x, y); return true; default: return false; } } bool Orbit::handleDelta(int delta) { if ( delta < 0 ) { _dollyOut(getZoomScale()); return true; } else if ( delta > 0 ) { _dollyIn(getZoomScale()); return true; } return false; } void Orbit::doRotate(float x, float y) { _rotateEnd.set(x, y); _rotateDelta = _rotateEnd - _rotateStart; // rotating across whole screen goes 360 degrees around rotateLeft(2.0f * (float)M_PI * _rotateDelta.x() / clientWidth() * rotateSpeed); // rotating up and down along whole screen attempts to go 360, but limited to 180 rotateUp(2.0f * (float)M_PI * _rotateDelta.y() / clientHeight() * rotateSpeed); _rotateStart = _rotateEnd; update(); } void Orbit::doDolly(unsigned x, unsigned y) { _dollyEnd.set(x, y); _dollyDelta = _dollyEnd - _dollyStart; if (_dollyDelta.y() > 0) { _dollyIn(getZoomScale()); } else if (_dollyDelta.y() < 0) { _dollyOut(getZoomScale()); } _dollyStart = _dollyEnd; update(); } void Orbit::doPan(unsigned x, unsigned y) { _panEnd.set(x, y); _panDelta = _panEnd - _panStart; _pan(_panDelta.x(), _panDelta.y()); _panStart = _panEnd; update(); } void Orbit::rotate(float deltaX, float deltaY) { doRotate(_rotateStart.x() + deltaX, _rotateStart.y() + deltaY); } void Orbit::pan(float deltaX, float deltaY) { _pan(deltaX, deltaY); update(); } float Orbit::getDistance() const { return _camera ? _camera->position().distanceTo(target) : 0.0f; } void Orbit::set(float polar, float azimuth) { //initialize spherical as in update() _offset = _camera->position() - target; _offset.apply(_quat); _spherical.setFromVector3(_offset); //set the new angles _spherical.phi() = polar; _spherical.theta() = azimuth; _spherical.makeSafe(); _offset = math::Vector3::fromSpherical(_spherical); //rotate offset back to "camera-up-vector-is-up" space _offset.apply(_quatInverse); _camera->position() = target + _offset; _camera->lookAt(target); } } }
21.842949
114
0.662069
2f09050d499d8eb4df2f94048b0b44a79bf11ad5
3,892
java
Java
pushy/src/main/java/sa/com/stcpay/blink/pushy/server/MockApnsServer.java
Chatatata/pushy
11c0d36b9c6e4ca8e7cc3548e24792c0a893cbed
[ "MIT" ]
1
2021-01-04T11:06:26.000Z
2021-01-04T11:06:26.000Z
pushy/src/main/java/sa/com/stcpay/blink/pushy/server/MockApnsServer.java
Chatatata/pushy
11c0d36b9c6e4ca8e7cc3548e24792c0a893cbed
[ "MIT" ]
null
null
null
pushy/src/main/java/sa/com/stcpay/blink/pushy/server/MockApnsServer.java
Chatatata/pushy
11c0d36b9c6e4ca8e7cc3548e24792c0a893cbed
[ "MIT" ]
1
2019-01-13T19:18:43.000Z
2019-01-13T19:18:43.000Z
/* * Copyright (c) 2013-2017 Turo * * 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. */ package sa.com.stcpay.blink.pushy.server; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; import io.netty.handler.codec.http2.Http2Settings; import io.netty.handler.ssl.SslContext; import javax.net.ssl.SSLSession; /** * <p>A mock APNs server is an HTTP/2 server that can be configured to respond to APNs push notifications with a variety * of behaviors. Mock servers are primarily useful for integration tests and benchmarks; users do <strong>not</strong> * need to interact with mock servers as part of normal client operation.</p> * * <p>Callers construct mock APNs servers with the {@link MockApnsServerBuilder} class, and provide a * {@link PushNotificationHandlerFactory} at construction time. The factory constructs {@link PushNotificationHandler} * instances that control how the server responds to push notifications. Pushy comes with a * {@link ValidatingPushNotificationHandlerFactory} that constructs handlers that emulate the behavior of a real APNs * server (but do not actually deliver push notifications to destination devices) and an * {@link AcceptAllPushNotificationHandlerFactory} that constructs handlers that unconditionally accept push * notifications. Additionally, callers may specify a {@link MockApnsServerListener} that will be notified when * notifications are accepted or rejected by the server.</p> * * @author <a href="https://github.com/jchambers">Jon Chambers</a> * * @since 0.8 */ public class MockApnsServer extends BaseHttp2Server { private final PushNotificationHandlerFactory handlerFactory; private final MockApnsServerListener listener; private final int maxConcurrentStreams; MockApnsServer(final SslContext sslContext, final EventLoopGroup eventLoopGroup, final PushNotificationHandlerFactory handlerFactory, final MockApnsServerListener listener, final int maxConcurrentStreams) { super(sslContext, eventLoopGroup); this.handlerFactory = handlerFactory; this.listener = listener; this.maxConcurrentStreams = maxConcurrentStreams; } @Override protected void addHandlersToPipeline(final SSLSession sslSession, final ChannelPipeline pipeline) throws Exception { final PushNotificationHandler pushNotificationHandler = this.handlerFactory.buildHandler(sslSession); final MockApnsServerHandler serverHandler = new MockApnsServerHandler.MockApnsServerHandlerBuilder() .pushNotificationHandler(pushNotificationHandler) .initialSettings(Http2Settings.defaultSettings().maxConcurrentStreams(this.maxConcurrentStreams)) .listener(this.listener) .build(); pipeline.addLast(serverHandler); } }
47.463415
120
0.764388
250b1655d2010eacae427b8336e75841be49cac0
6,266
asm
Assembly
Appl/Art/Decks/GeoDeck/LMFlowers.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
504
2018-11-18T03:35:53.000Z
2022-03-29T01:02:51.000Z
Appl/Art/Decks/GeoDeck/LMFlowers.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
96
2018-11-19T21:06:50.000Z
2022-03-06T10:26:48.000Z
Appl/Art/Decks/GeoDeck/LMFlowers.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
73
2018-11-19T20:46:53.000Z
2022-03-29T00:59:26.000Z
LMFlowers label byte word C_BLACK Bitmap <71,100,0,BMF_MONO> db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 db 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c db 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04 db 0x8f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0 db 0x95, 0x55, 0x55, 0x79, 0x10, 0x0c, 0x35, 0x55, 0x50 db 0x9a, 0xaa, 0xab, 0xcf, 0x3c, 0x18, 0x3a, 0xaa, 0xb0 db 0x95, 0x55, 0x56, 0x0c, 0x23, 0x10, 0x6d, 0x55, 0x50 db 0x9a, 0xab, 0xea, 0x06, 0x41, 0x9e, 0x46, 0xaa, 0xb0 db 0x95, 0xfd, 0x97, 0x1c, 0x41, 0xf3, 0xcf, 0x55, 0x50 db 0x9a, 0x98, 0x0f, 0x18, 0x43, 0x83, 0x08, 0xea, 0xb0 db 0x95, 0x88, 0x19, 0xe0, 0xe7, 0x81, 0x90, 0x75, 0x50 db 0x9b, 0x8f, 0x18, 0x80, 0xf6, 0xc7, 0x10, 0x6a, 0xb0 db 0x96, 0xc0, 0xd1, 0xc7, 0xdd, 0xc6, 0x10, 0xf5, 0x50 db 0x9a, 0x60, 0xe1, 0xbf, 0xae, 0xf8, 0x39, 0xaa, 0xb0 db 0x96, 0x18, 0x61, 0x55, 0x57, 0x60, 0x35, 0x55, 0x50 db 0x9b, 0x08, 0x43, 0xaa, 0xae, 0xb1, 0xe3, 0xaa, 0xb0 db 0x95, 0x88, 0x7b, 0x55, 0x55, 0x5f, 0x41, 0xd5, 0x50 db 0x9a, 0xd8, 0x62, 0xaa, 0xfe, 0xae, 0xa0, 0xaa, 0xb0 db 0x95, 0xfe, 0xe3, 0x7d, 0xc7, 0x55, 0x70, 0xdd, 0xd0 db 0x9b, 0xbd, 0x06, 0xe7, 0x8d, 0xaa, 0xbc, 0xb7, 0x70 db 0x97, 0x56, 0x0d, 0x84, 0x10, 0xd5, 0x57, 0x6c, 0xb0 db 0x9e, 0xd3, 0xfa, 0xc5, 0xf0, 0xaa, 0xaa, 0xd8, 0x10 db 0x94, 0x9d, 0xd5, 0x76, 0xc8, 0xd5, 0x55, 0xb0, 0x10 db 0x98, 0x37, 0x6a, 0xcc, 0x07, 0xea, 0xab, 0xa1, 0x90 db 0x9e, 0x2c, 0xb5, 0xc4, 0x0c, 0xd5, 0x55, 0xb2, 0x90 db 0x91, 0xd8, 0x1b, 0xc7, 0x8c, 0x6a, 0xaa, 0xae, 0x70 db 0x91, 0xb0, 0x15, 0x60, 0x68, 0xd5, 0x57, 0xf6, 0x50 db 0x93, 0xa1, 0x9b, 0x30, 0x70, 0xfe, 0xab, 0x0d, 0x90 db 0x91, 0xb2, 0x8d, 0x0c, 0x30, 0xe7, 0x56, 0x0c, 0x10 db 0x91, 0xae, 0xfe, 0x84, 0x21, 0x92, 0xac, 0x1a, 0x30 db 0x95, 0xff, 0x8f, 0xc4, 0x3d, 0xc3, 0x57, 0x91, 0xf0 db 0x93, 0xcf, 0x18, 0x6c, 0x31, 0xe1, 0xbc, 0xf3, 0xd0 db 0x95, 0x08, 0x20, 0x7f, 0x71, 0x7d, 0x60, 0xc2, 0x30 db 0x9f, 0x8b, 0xe0, 0x5e, 0x83, 0xab, 0xa0, 0x64, 0x10 db 0x9c, 0xcc, 0x41, 0xaf, 0x07, 0x7d, 0x71, 0xc4, 0x10 db 0x97, 0xf8, 0x43, 0x6b, 0xfd, 0x86, 0xb1, 0x84, 0x30 db 0x9b, 0x84, 0x4e, 0x4d, 0x57, 0x07, 0x5e, 0x0e, 0x70 db 0x95, 0x06, 0x7c, 0x1a, 0xaa, 0x0d, 0xb8, 0x0f, 0x50 db 0x92, 0x0d, 0xe7, 0x15, 0x57, 0xc8, 0xd4, 0x7d, 0xd0 db 0x95, 0xc8, 0x84, 0xfa, 0xbe, 0x79, 0xeb, 0xf8, 0x70 db 0x9e, 0x79, 0xe5, 0xcd, 0x61, 0x61, 0x1d, 0x50, 0x30 db 0x90, 0x61, 0x1f, 0x26, 0xc1, 0xb2, 0x0e, 0xac, 0x10 db 0x90, 0x32, 0x0d, 0x87, 0x83, 0x62, 0x0d, 0x57, 0x10 db 0x98, 0xe2, 0x0e, 0xc2, 0xf2, 0x22, 0x1e, 0xaa, 0xb0 db 0x98, 0xc2, 0x1d, 0x7b, 0x9e, 0x7f, 0x35, 0x55, 0x70 db 0x9f, 0x07, 0x3a, 0xac, 0x18, 0x46, 0xaa, 0xaa, 0xb0 db 0x9c, 0x06, 0xb5, 0x54, 0x0c, 0x83, 0x75, 0x55, 0x50 db 0x9e, 0x3c, 0x6a, 0xae, 0x38, 0x83, 0x3a, 0xaa, 0xb0 db 0x97, 0xf8, 0x35, 0x56, 0x30, 0x87, 0x15, 0x7d, 0x50 db 0x9b, 0xb0, 0x1a, 0xab, 0xc1, 0xce, 0x2b, 0xc2, 0xb0 db 0x95, 0x7e, 0x3d, 0x57, 0x01, 0xaf, 0xb7, 0x83, 0x50 db 0x9a, 0xef, 0xaa, 0xaa, 0x8f, 0x1a, 0xeb, 0x06, 0xb0 db 0x95, 0xd8, 0xed, 0x55, 0x7a, 0x7d, 0x57, 0xe4, 0x50 db 0x9a, 0xd0, 0xce, 0xaa, 0xbd, 0xb2, 0xaf, 0x3c, 0xf0 db 0x95, 0x59, 0x47, 0x55, 0x53, 0x01, 0xd8, 0x30, 0x90 db 0x9b, 0xd7, 0x3b, 0xaa, 0xb1, 0x03, 0x38, 0x19, 0x10 db 0x95, 0xf3, 0x27, 0x55, 0x71, 0xe3, 0x1c, 0x71, 0x10 db 0x9b, 0x92, 0xca, 0xaa, 0xd8, 0x1a, 0x3c, 0x61, 0x10 db 0x97, 0x38, 0x3f, 0x55, 0x4c, 0x1c, 0x3f, 0x83, 0xb0 db 0x9b, 0x3c, 0xf0, 0xaa, 0xc3, 0x0c, 0x2e, 0x03, 0xd0 db 0x96, 0x67, 0xe0, 0xd5, 0x61, 0x08, 0x77, 0x1f, 0x70 db 0x9b, 0x83, 0xc1, 0xaa, 0xb1, 0x0f, 0x6b, 0xfe, 0x30 db 0x97, 0x81, 0xf9, 0x15, 0x5b, 0x0c, 0x55, 0xd4, 0x10 db 0x98, 0x47, 0x0f, 0x3e, 0xbf, 0xdc, 0x6a, 0xae, 0x10 db 0x90, 0x6c, 0x0c, 0x23, 0x77, 0xa0, 0xd5, 0x57, 0x10 db 0x90, 0xdc, 0x06, 0x41, 0xca, 0xc1, 0xaa, 0xaa, 0xd0 db 0x9c, 0x8c, 0x1c, 0x41, 0x9b, 0x7f, 0x55, 0x55, 0x50 db 0x97, 0x9c, 0x18, 0x43, 0x12, 0xaa, 0xaa, 0xaa, 0xb0 db 0x96, 0x14, 0xe0, 0x67, 0x25, 0x55, 0x57, 0xf5, 0x50 db 0x93, 0x27, 0x00, 0x77, 0xc6, 0xab, 0xff, 0x1a, 0xb0 db 0x9e, 0x21, 0x03, 0xdd, 0x7d, 0x57, 0x9e, 0x35, 0x50 db 0x9c, 0x21, 0xff, 0x8e, 0xaa, 0xae, 0x10, 0x42, 0xb0 db 0x90, 0x73, 0x75, 0x07, 0x55, 0x57, 0x17, 0xc3, 0x50 db 0x90, 0x6a, 0xab, 0xc6, 0xaa, 0xab, 0x98, 0x83, 0xb0 db 0x93, 0xc7, 0x55, 0xe5, 0x55, 0x55, 0x90, 0x87, 0x50 db 0x9e, 0x83, 0xaa, 0xbe, 0xaa, 0xab, 0x98, 0x9d, 0xb0 db 0x98, 0x01, 0x55, 0x55, 0x55, 0x55, 0x8c, 0xfd, 0x50 db 0x90, 0x62, 0xaa, 0xaa, 0xaa, 0xaa, 0xc7, 0xcf, 0xb0 db 0x91, 0xfb, 0x55, 0x57, 0xf5, 0x55, 0x60, 0x09, 0xf0 db 0x93, 0x87, 0xaa, 0xed, 0x9a, 0xaa, 0xb0, 0x0b, 0x90 db 0x93, 0x06, 0xd5, 0x98, 0x0f, 0x55, 0x58, 0x1e, 0x50 db 0x93, 0xe4, 0x6b, 0x88, 0x19, 0xaa, 0xac, 0x3f, 0x10 db 0x9f, 0x3c, 0xf7, 0x8f, 0x18, 0xd5, 0x57, 0x75, 0x90 db 0x98, 0x30, 0x8e, 0xc0, 0xd1, 0xaa, 0xab, 0xea, 0xf0 db 0x98, 0x19, 0x06, 0x60, 0xe1, 0x5f, 0x55, 0x55, 0x50 db 0x9c, 0x71, 0x06, 0x18, 0x61, 0xb0, 0xaa, 0xaa, 0xb0 db 0x94, 0x61, 0x0f, 0x08, 0x43, 0x60, 0xd5, 0x55, 0x50 db 0x9b, 0x83, 0x99, 0x88, 0x7a, 0xc1, 0xaa, 0xaa, 0xb0 db 0x96, 0x03, 0x50, 0xd8, 0x63, 0x79, 0x15, 0x55, 0x50 db 0x9b, 0x1e, 0x30, 0xfe, 0xe3, 0xcf, 0x3e, 0xaa, 0xb0 db 0x95, 0xfc, 0x19, 0xbd, 0x06, 0x0c, 0x23, 0x55, 0x50 db 0x9a, 0xea, 0x0b, 0x5e, 0x0e, 0x06, 0x41, 0xaa, 0xb0 db 0x95, 0x57, 0x0e, 0xd7, 0xff, 0x1c, 0x41, 0xd5, 0x50 db 0x9a, 0xab, 0xd4, 0x9a, 0xab, 0x18, 0x43, 0xaa, 0xb0 db 0x95, 0x55, 0x78, 0x35, 0x55, 0xe0, 0xe7, 0x55, 0x50 db 0x9a, 0xaa, 0xae, 0x2a, 0xab, 0x80, 0xd6, 0xaa, 0xb0 db 0x8f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0 db 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04 db 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
30.715686
53
0.614267
405af23f9cc29dce0e43af7bb24f0b3558fb20dc
4,022
py
Python
main/migrations/0005_auto_20181126_1117.py
czbiohub/crispycrunch
78a640b376ea878d2994d3759849ec8398e4d3f2
[ "MIT" ]
4
2018-12-21T04:49:40.000Z
2021-10-05T07:11:50.000Z
main/migrations/0005_auto_20181126_1117.py
czbiohub/crispycrunch
78a640b376ea878d2994d3759849ec8398e4d3f2
[ "MIT" ]
null
null
null
main/migrations/0005_auto_20181126_1117.py
czbiohub/crispycrunch
78a640b376ea878d2994d3759849ec8398e4d3f2
[ "MIT" ]
null
null
null
# Generated by Django 2.1.1 on 2018-11-26 19:17 import django.contrib.postgres.fields import django.contrib.postgres.fields.jsonb import django.core.validators from django.db import migrations, models import functools import main.models import utils.validators class Migration(migrations.Migration): dependencies = [ ('main', '0004_auto_20181115_1644'), ] operations = [ migrations.AddField( model_name='guidedesign', name='hdr_homology_arm_length', field=models.IntegerField(default=55, help_text='Length of each homolgous sequence that flank the tag sequence', validators=[django.core.validators.MinValueValidator(15), django.core.validators.MaxValueValidator(1000)], verbose_name='Homology arm length'), ), migrations.AlterField( model_name='experiment', name='is_hdr', field=models.BooleanField(default=True, help_text='Will guides be used with HDR (Homology Directed Repair)?', verbose_name='HDR experiment?'), ), migrations.AlterField( model_name='guidedesign', name='hdr_start_codon_tag_seq', field=models.CharField(blank=True, default='ACCGAGCTCAACTTCAAGGAGTGGCAAAAGGCCTTTACCGATATGATGGGTGGCGGATTGGAAGTTTTGTTTCAAGGTCCAGGAAGTGGT', help_text='Sequence of tag to insert just after start codon', max_length=65536, null=True, validators=[utils.validators.validate_seq, django.core.validators.MinLengthValidator(3), django.core.validators.MaxLengthValidator(1000)], verbose_name='Tag sequence for start codon'), ), migrations.AlterField( model_name='guidedesign', name='hdr_stop_codon_tag_seq', field=models.CharField(blank=True, default='GGTGGCGGATTGGAAGTTTTGTTTCAAGGTCCAGGAAGTGGTACCGAGCTCAACTTCAAGGAGTGGCAAAAGGCCTTTACCGATATGATG', help_text='Sequence of tag to insert just before stop codon', max_length=65536, null=True, validators=[utils.validators.validate_seq, django.core.validators.MinLengthValidator(3), django.core.validators.MaxLengthValidator(1000)], verbose_name='Tag sequence for stop codon'), ), migrations.AlterField( model_name='guidedesign', name='hdr_tag', field=models.CharField(blank=True, choices=[('start_codon', 'Within 96 before or after start codon (N-terminus)'), ('stop_codon', 'Within 96 before or after stop codon (C-terminus)'), ('per_target', 'Within 96 before or after, terminus specified per target ("N" or "C")')], default=None, help_text='Where to insert the tag in each gene', max_length=40, null=True, verbose_name='HDR tag terminus'), ), migrations.AlterField( model_name='guidedesign', name='target_tags', field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, choices=[('start_codon', 'Within 96 before or after start codon (N-terminus)'), ('stop_codon', 'Within 96 before or after stop codon (C-terminus)'), ('per_target', 'Within 96 before or after, terminus specified per target ("N" or "C")')], max_length=40), blank=True, size=None, verbose_name='Target HDR tags'), ), migrations.AlterField( model_name='primerdesign', name='max_amplicon_length', field=models.IntegerField(default=400, help_text='Amplicon = primer product. Length after HDR insertion.', validators=[django.core.validators.MinValueValidator(200), django.core.validators.MaxValueValidator(400)], verbose_name='Maximum amplicon length'), ), migrations.AlterField( model_name='primerselection', name='selected_primers', field=django.contrib.postgres.fields.jsonb.JSONField(default=dict, help_text='Primers returned by Crispor, grouped by guide, forward primer then reverse primer', validators=[functools.partial(utils.validators.validate_num_wells, *(), **{'max': 1152}), main.models.PrimerSelection._validate_selected_primers]), ), ]
67.033333
424
0.712581
64d967288738dc84e31323b7c416a8ae3de92650
4,900
java
Java
src/main/java/com/chaingrok/libra4j/crypto/KeyPair.java
fossabot/libra4j
7157278529ce3038bf5ffbd79d68ef89283a363c
[ "Apache-2.0" ]
2
2019-12-24T04:21:46.000Z
2020-04-27T13:26:46.000Z
src/main/java/com/chaingrok/libra4j/crypto/KeyPair.java
fossabot/libra4j
7157278529ce3038bf5ffbd79d68ef89283a363c
[ "Apache-2.0" ]
1
2020-01-18T06:01:24.000Z
2020-01-18T06:01:24.000Z
src/main/java/com/chaingrok/libra4j/crypto/KeyPair.java
fossabot/libra4j
7157278529ce3038bf5ffbd79d68ef89283a363c
[ "Apache-2.0" ]
1
2020-01-18T05:57:52.000Z
2020-01-18T05:57:52.000Z
package com.chaingrok.libra4j.crypto; import java.security.KeyFactory; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; import org.bouncycastle.jcajce.provider.digest.SHA3; import com.chaingrok.lib.ChaingrokException; import com.chaingrok.lib.Utils; public class KeyPair { public static final String ED25519 = "Ed25519"; public static final int UNCOMPRESSED_KEY_LENGTH = 83; //in bytes public static final int PUBLIC_KEY_PREFIX_LENGTH = 12; //in bytes public static final int PUBLIC_KEY_STRIPPED_LENGTH = 32; //in bytes public static final int COMPRESSED_KEY_LENGTH = PUBLIC_KEY_PREFIX_LENGTH + PUBLIC_KEY_STRIPPED_LENGTH; static { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); //to automatically initialize for BountyCastle } private PrivateKey privateKey; private PublicKey publicKey; public KeyPair(PrivateKey privateKey,PublicKey publicKey) { this.privateKey = privateKey; this.publicKey = publicKey; } public PrivateKey getPrivateKey() { return privateKey; } public PublicKey getPublicKey() { return publicKey; } public byte[] getLibraAddress() { byte[] result = null; if (this.publicKey != null) { result = KeyPair.toLibraAddressByteArray(getPublicKey()); } return result; } public String getAlgortihhm() { String result = null; if (publicKey != null) { result = publicKey.getAlgorithm(); } return result; } public static String PublicKeyHexToLibraAddress(String pkHex) { String result = null; PublicKey pk = publicKeyFromHexString(pkHex); result = toLibraAddress(pk); return result; } public static PublicKey publicKeyFromHexString(String publicKeyHexString) { return publicKeyFromByteArray(Utils.hexStringToByteArray(publicKeyHexString)); } public static PublicKey publicKeyFromByteArray(byte[] pkBytes) { PublicKey result = null; try { result = getKeyFactory().generatePublic(new X509EncodedKeySpec(pkBytes)); } catch (InvalidKeySpecException e) { throw new ChaingrokException(e); } return result; } public static byte[] stripPrefix(byte[] publicKeyUnstrippedBytes) { byte[] publicKeyStripped = new byte[PUBLIC_KEY_STRIPPED_LENGTH]; System.arraycopy(publicKeyUnstrippedBytes, PUBLIC_KEY_PREFIX_LENGTH, publicKeyStripped, 0, PUBLIC_KEY_STRIPPED_LENGTH); return publicKeyStripped; } public static String toLibraAddress(PublicKey publicKey) { String result = null; byte[] bytes = toLibraAddressByteArray(publicKey); result = Utils.byteArrayToHexString(bytes); return result; } public static byte[] toLibraAddressByteArray(PublicKey publicKey) { byte[] result = null; SHA3.DigestSHA3 digestSHA3 = new SHA3.Digest256(); byte[] strippedPublicKey = stripPrefix(publicKey.getEncoded()); result = digestSHA3.digest(strippedPublicKey); return result; } public static PrivateKey privateKeyFromHexString(String privateKeyHexString) { PrivateKey result = null; byte[] privateKeyBytes = Utils.hexStringToByteArray(privateKeyHexString); try { result = getKeyFactory().generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes)); } catch (InvalidKeySpecException e) { throw new ChaingrokException(e); } return result; } public static KeyPair random() { // Fpr x509 encoding , see https://stackoverflow.com/questions/22008337/generating-keypair-using-bouncy-castle KeyPair result = null; KeyPairGenerator keyGen; try { keyGen = KeyPairGenerator.getInstance(ED25519); } catch (NoSuchAlgorithmException e) { throw new ChaingrokException(e); } java.security.KeyPair keyPair = keyGen.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); result = new KeyPair(privateKey,publicKey); return result; } public static KeyFactory getKeyFactory() { KeyFactory result = null; try { result = KeyFactory.getInstance(ED25519); } catch (NoSuchAlgorithmException e) { throw new ChaingrokException(e); } return result; } public static boolean validatePair(PrivateKey privateKey, PublicKey publicKey) { boolean result = false; byte[] content = "foo-bar".getBytes(); Signer signer = new Signer(ED25519,privateKey,publicKey); byte[] signature = signer.sign(content); result = signer.verify(signature, content); return result; } }
32.026144
128
0.719388
64ecc0adc55762c3edcc01b7323f326245c106f4
6,205
java
Java
src/main/java/org/atreus/impl/core/Environment.java
bemisguided/atreus
35c61a84d2cefed878924465710e947e2e371d5b
[ "MIT" ]
null
null
null
src/main/java/org/atreus/impl/core/Environment.java
bemisguided/atreus
35c61a84d2cefed878924465710e947e2e371d5b
[ "MIT" ]
null
null
null
src/main/java/org/atreus/impl/core/Environment.java
bemisguided/atreus
35c61a84d2cefed878924465710e947e2e371d5b
[ "MIT" ]
null
null
null
/** * The MIT License * * Copyright (c) 2014 Martin Crawford and contributors. * * 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. */ package org.atreus.impl.core; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; import com.datastax.driver.core.exceptions.DriverException; import org.atreus.core.AtreusClusterConnectivityException; import org.atreus.core.AtreusConfiguration; import org.atreus.core.ext.plugins.AtreusPlugin; import org.atreus.impl.core.mappings.MappingBuilder; import org.atreus.impl.core.proxies.collections.CollectionProxyManager; import org.atreus.impl.core.proxies.entities.EntityProxyManager; import org.atreus.impl.core.queries.QueryManager; import org.atreus.impl.types.TypeManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; /** * Atreus Environment. * * @author Martin Crawford */ public class Environment { // Constants ---------------------------------------------------------------------------------------------- Constants private static final transient Logger LOG = LoggerFactory.getLogger(Environment.class); // Instance Variables ---------------------------------------------------------------------------- Instance Variables private Cluster cassandraCluster; private Session cassandraSession; private ManagerImpl manager; private final AtreusConfiguration configuration; private final MetaManagerImpl metaManager; private final MappingBuilder mappingBuilder; private final QueryManager queryManager; private final EntityProxyManager entityProxyManager; private final CollectionProxyManager collectionProxyManager; private final TypeManager typeManager; private final List<AtreusPlugin> plugins = new ArrayList<>(); // Constructors ---------------------------------------------------------------------------------------- Constructors public Environment(AtreusConfiguration configuration) { this.configuration = configuration; this.metaManager = new MetaManagerImpl(this); this.queryManager = new QueryManager(this); this.typeManager = new TypeManager(this); this.mappingBuilder = new MappingBuilder(this); this.entityProxyManager = new EntityProxyManager(); this.collectionProxyManager = new CollectionProxyManager(); } // Public Methods ------------------------------------------------------------------------------------ Public Methods public void addPlugin(AtreusPlugin plugin) { plugins.add(plugin); } public void connect() { try { Cluster cluster = Cluster.builder() .addContactPoints(configuration.getHosts()) .withPort(configuration.getPort()) .build(); cluster.connect(); setCassandraCluster(cluster); setCassandraSession(cluster.newSession()); } catch (DriverException e) { throw new AtreusClusterConnectivityException(AtreusClusterConnectivityException.ERROR_CODE_CANNOT_CONNECT, e); } } public void init() { typeManagerInit(); pluginsInit(); pluginsPreMapping(); metaBuilderInit(); pluginsPostMapping(); } // Protected Methods ------------------------------------------------------------------------------ Protected Methods // Private Methods ---------------------------------------------------------------------------------- Private Methods private void metaBuilderInit() { mappingBuilder.scanPaths(configuration.getScanPaths()); mappingBuilder.build(); } private void pluginsInit() { for (AtreusPlugin plugin : plugins) { plugin.init(); } } private void pluginsPreMapping() { for (AtreusPlugin plugin : plugins) { plugin.preMapping(manager); } } private void pluginsPostMapping() { for (AtreusPlugin plugin : plugins) { plugin.postMapping(manager); } } private void typeManagerInit() { getTypeManager().scanPaths(getConfiguration().getScanPaths()); } // Getters & Setters ------------------------------------------------------------------------------ Getters & Setters public Cluster getCassandraCluster() { return cassandraCluster; } public void setCassandraCluster(Cluster cassandraCluster) { this.cassandraCluster = cassandraCluster; } public Session getCassandraSession() { return cassandraSession; } public void setCassandraSession(Session cassandraSession) { this.cassandraSession = cassandraSession; } public AtreusConfiguration getConfiguration() { return configuration; } public MetaManagerImpl getMetaManager() { return metaManager; } public MappingBuilder getMappingBuilder() { return mappingBuilder; } public QueryManager getQueryManager() { return queryManager; } public EntityProxyManager getEntityProxyManager() { return entityProxyManager; } public CollectionProxyManager getCollectionProxyManager() { return collectionProxyManager; } public TypeManager getTypeManager() { return typeManager; } public ManagerImpl getManager() { return manager; } public void setManager(ManagerImpl manager) { this.manager = manager; } }
31.984536
119
0.677357
59e4d4262b36f857922ab661f7172249dbba7181
157
swift
Swift
EnumASCIIControlCharacter.playground/Contents.swift
carlos-santiago-2017/PlaygroundsSwift412
0638445ac5e61e74f0b672d6a731dd878df0902d
[ "MIT" ]
null
null
null
EnumASCIIControlCharacter.playground/Contents.swift
carlos-santiago-2017/PlaygroundsSwift412
0638445ac5e61e74f0b672d6a731dd878df0902d
[ "MIT" ]
null
null
null
EnumASCIIControlCharacter.playground/Contents.swift
carlos-santiago-2017/PlaygroundsSwift412
0638445ac5e61e74f0b672d6a731dd878df0902d
[ "MIT" ]
null
null
null
enum ASCIIControlCharacter: Character { case tab = "\t" case lineFeed = "\n" case carriageReturn = "\r" } let ascii = ASCIIControlCharacter.tab
19.625
39
0.675159
504e12c2e0eee5a7ec7edac08eb31595c3ae3f71
201
swift
Swift
src/ios/ProcessRate.swift
ImpacGroup/cordova-plugin-ml-barcode-scanner
f179f02b3e1f38fbf7a8b4b6cf6fb1e3ba166245
[ "Apache-2.0" ]
null
null
null
src/ios/ProcessRate.swift
ImpacGroup/cordova-plugin-ml-barcode-scanner
f179f02b3e1f38fbf7a8b4b6cf6fb1e3ba166245
[ "Apache-2.0" ]
null
null
null
src/ios/ProcessRate.swift
ImpacGroup/cordova-plugin-ml-barcode-scanner
f179f02b3e1f38fbf7a8b4b6cf6fb1e3ba166245
[ "Apache-2.0" ]
1
2022-01-16T18:14:49.000Z
2022-01-16T18:14:49.000Z
// // ProcessRate.swift // MLBarcodeScanner // // Created by Felix Nievelstein on 25.11.21. // import Foundation enum ProcessRate: Int { case SLOW = 10 case MEDIUM = 4 case FAST = 0 }
13.4
45
0.641791
499691aab46166dff6d44bdd70d219ea1525dc2a
5,536
dart
Dart
lib/presentation/friends/search_users_page.dart
jfrnd/smart_dish
88a7415684a011c837238e92434033913ee1a3fe
[ "CC-BY-3.0" ]
null
null
null
lib/presentation/friends/search_users_page.dart
jfrnd/smart_dish
88a7415684a011c837238e92434033913ee1a3fe
[ "CC-BY-3.0" ]
null
null
null
lib/presentation/friends/search_users_page.dart
jfrnd/smart_dish
88a7415684a011c837238e92434033913ee1a3fe
[ "CC-BY-3.0" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:smart_dish/application/search_user/search_user_cubit.dart'; import 'package:smart_dish/di/injection.dart'; import 'package:smart_dish/domain/core/failure.dart'; import 'package:smart_dish/domain/user/user_extended_data.dart'; import 'package:smart_dish/presentation/friends/widgets/buttons.dart'; import 'package:smart_dish/presentation/friends/widgets/request_item.dart'; import 'package:smart_dish/presentation/widgets/oval_image.dart'; import 'package:smart_dish/utils/platform.dart'; import '../hybrid_scaffold.dart'; class SearchUsersPage extends StatelessWidget { const SearchUsersPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final controller = TextEditingController(); return BlocProvider( create: (context) => getIt<SearchUserCubit>(), child: Builder(builder: (context) { return HybridScaffold( hideNavBarInMobile: true, appBar: AppBar( title: const Text("Search"), ), body: SingleChildScrollView( physics: const BouncingScrollPhysics(), child: SizedBox( width: deviceIsDesktop ? orientationThreshold : null, child: Column( mainAxisSize: MainAxisSize.min, children: [ SearchBar(controller), const Divider(), const ResultList(), ], ), ), ), ); }), ); } } class ResultList extends StatelessWidget { const ResultList({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return BlocBuilder<SearchUserCubit, SearchUserState>( builder: (context, state) { return state.map( initial: (_) => const SizedBox(), isLoading: (_) => const Center( child: Padding( padding: EdgeInsets.all(32.0), child: CircularProgressIndicator(), ), ), loadingFailed: (state) => ListTile( contentPadding: const EdgeInsets.all(8), leading: const Icon(Icons.error), title: Text(state.failure.toMessage())), loadingSuccessful: (state) { if (state.users.isEmpty) { return const ListTile( contentPadding: EdgeInsets.all(8), leading: Icon(Icons.error), title: Text("Nothing found.")); } else { return ListView.builder( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), itemCount: state.users.length, itemBuilder: (context, index) { final user = state.users[index]; if (user.isFriend || user.isSignedInUser) { return ListTile( leading: OvalImage(user.imageUrl), title: Text(user.userName), subtitle: user.isFriend ? const Text("You are friends.") : const Text("This is you.")); } else if (user.hasOpenFriendRequest && !user.isSignedInUser) { return RequestItem(user.friendRequest!); } else { return ListTile( leading: OvalImage(user.imageUrl), title: Text(user.userName), subtitle: Builder( builder: (context) { if (user.isSendingFriendRequest) { return const Text("is sending..."); } else { return user.sendingRequestFailureOrSuccess?.fold( (failure) => Text(failure.toMessage()), (unit) => const Text("Request sent successfully."), ) ?? const Text("Send request."); } }, ), trailing: CreateFriendRequestButton(user), ); } }, ); } }, ); }, ); } } class SearchBar extends StatelessWidget { const SearchBar( this.controller, { Key? key, }) : super(key: key); final TextEditingController controller; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: TextField( controller: controller, onSubmitted: (_) => context.read<SearchUserCubit>().onSearchClicked(controller.text), decoration: InputDecoration( hintText: "type user name", prefixIcon: IconButton( icon: const Icon(Icons.search), onPressed: () => context .read<SearchUserCubit>() .onSearchClicked(controller.text), ), suffixIcon: IconButton( icon: const Icon(Icons.clear), onPressed: () => controller.clear(), ), border: const OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(16)), ), ), ), ); } }
34.385093
79
0.517341
2c6975900317b6ebaf4b8b2d63a76ac4301b0678
1,265
lua
Lua
modules/luci-base/luasrc/tools/apnsetting.lua
AklllXCY/bywl
80f4253d76cea6ce691cd161ac8841abb742d1fa
[ "Apache-2.0" ]
null
null
null
modules/luci-base/luasrc/tools/apnsetting.lua
AklllXCY/bywl
80f4253d76cea6ce691cd161ac8841abb742d1fa
[ "Apache-2.0" ]
null
null
null
modules/luci-base/luasrc/tools/apnsetting.lua
AklllXCY/bywl
80f4253d76cea6ce691cd161ac8841abb742d1fa
[ "Apache-2.0" ]
null
null
null
module("luci.tools.apnsetting", package.seeall) local type = luci.sys.exec("uci get tastek.apn.apn_type") if(#type == 0) then type = '' end local id= luci.sys.exec("uci get tastek.apn.apn_id") if(#id == 0) then id = '' end local name = luci.sys.exec("uci get tastek.apn.apn_name") if(#name == 0) then name = '' end local account= luci.sys.exec("uci get tastek.apn.apn_account") if(#account == 0) then account = '' end local password = luci.sys.exec("uci get tastek.apn.apn_password") if(#password == 0) then password = '' end local auth = luci.sys.exec("uci get tastek.apn.apn_auth") if(#auth == 0) then auth = '' end data = string.format("at+qicsgp=%d,%d,%s,%s,%s,%d\r\n",id,type,tostring(name),tostring(account),tostring(password),auth) function deal() luci.sys.exec("stty -F /dev/ttyUSB2 raw speed 9600 -echo min 0 time 1") wserial=io.open("/dev/ttyUSB2","w") rserial=io.open("/dev/ttyUSB2","r") wserial:flush() rserial:read(1024) wserial:write(data) wserial:flush() copschaine=rserial:read(1024) if(string.find(copschaine, "ok") ~= nil) then luci.sys.exec("uci set tastek.control.qos_en1=666") else luci.sys.exec("uci set tastek.control.qos_en1=333") end io.close(wserial) io.close(rserial) end
28.75
121
0.671146
fb4ade42d021a9245fcf34e241f52802aa7cc8f4
4,051
h
C
TaskLayer/XLSearchTask/XLSearchTask.h
allenmcasey/HPCMetaMorpheus
578d880a9ab6780752c762f324f0bc1ec95c8b8c
[ "MIT" ]
2
2020-09-10T19:14:20.000Z
2021-09-11T16:36:56.000Z
TaskLayer/XLSearchTask/XLSearchTask.h
allenmcasey/HPCMetaMorpheus
578d880a9ab6780752c762f324f0bc1ec95c8b8c
[ "MIT" ]
null
null
null
TaskLayer/XLSearchTask/XLSearchTask.h
allenmcasey/HPCMetaMorpheus
578d880a9ab6780752c762f324f0bc1ec95c8b8c
[ "MIT" ]
3
2020-09-11T01:19:47.000Z
2021-09-02T02:05:01.000Z
#pragma once #include "../MetaMorpheusTask.h" #include <string> #include <unordered_set> #include <vector> #include <cmath> #include <limits> #include <iostream> #include <fstream> #include "stringhelper.h" #include "stringbuilder.h" #include "tangible_filesystem.h" #include "XLSearchParameters.h" #include "../DbForTask.h" #include "../MyTaskResults.h" #include "../FileSpecificParameters.h" #include "../../EngineLayer/MetaMorpheusEngine.h" using namespace EngineLayer; #include "../../EngineLayer/CrosslinkSearch/CrosslinkSearchEngine.h" using namespace EngineLayer::CrosslinkSearch; #include "../../EngineLayer/Indexing/IndexingEngine.h" using namespace EngineLayer::Indexing; #include "../../EngineLayer/FdrAnalysis/FdrAnalysisEngine.h" using namespace EngineLayer::FdrAnalysis; #include "MassSpectrometry/MassSpectrometry.h" using namespace MassSpectrometry; #include "Proteomics/Proteomics.h" using namespace Proteomics; using namespace Proteomics::ProteolyticDigestion; using namespace Proteomics::Fragmentation; #include "MzLibUtil.h" using namespace MzLibUtil; namespace TaskLayer { class XLSearchTask : public MetaMorpheusTask { private: TaskLayer::XlSearchParameters *privateXlSearchParameters=nullptr; // need access to proteinList for reconstruction of CrosslinkSpectralMatches in the MPI // version, hence they are stored as part of the class now, not just internally in the // RunSpecific() method std::vector<Protein*> proteinList; public: XLSearchTask(); XLSearchTask(std::string tomlFile ); ~XLSearchTask() { delete privateXlSearchParameters; } TaskLayer::XlSearchParameters *getXlSearchParameters() const; void setXlSearchParameters(TaskLayer::XlSearchParameters *value); void writeTomlConfig(std::string &filename, std::ofstream &tomlFd ); std::vector<Protein*> getProteinList () const; protected: MyTaskResults *RunSpecific(const std::string &OutputFolder, std::vector<DbForTask*> &dbFilenameList, std::vector<std::string> &currentRawFileList, const std::string &taskId, std::vector<FileSpecificParameters*> &fileSettingsList) override; //Calculate the FDR of single peptide FP/TP private: void SingleFDRAnalysis(std::vector<CrosslinkSpectralMatch*> &items, std::vector<std::string> &taskIds); //Calculate the FDR of crosslinked peptide FP/TP void DoCrosslinkFdrAnalysis(std::vector<CrosslinkSpectralMatch*> &csms); //Generate user defined crosslinker public: static Crosslinker *GenerateUserDefinedCrosslinker(TaskLayer::XlSearchParameters *xlSearchParameters); void WritePsmCrossToTsv(std::vector<CrosslinkSpectralMatch*> &items, const std::string &filePath, int writeType); void WriteCrosslinkToTxtForPercolator(std::vector<CrosslinkSpectralMatch*> &items, const std::string &outputFolder, const std::string &fileName, Crosslinker *crosslinker, std::vector<std::string> &nestedIds); void WritePepXML_xl(std::vector<CrosslinkSpectralMatch*> &items, std::vector<Protein*> &proteinList, const std::string &databasePath, std::vector<Modification*> &variableModifications, std::vector<Modification*> &fixedModifications, std::vector<std::string> &localizeableModificationTypes, const std::string &outputFolder, const std::string &fileName, std::vector<std::string> &nestedIds); }; }
39.330097
121
0.634905
2a466999b78e7fa08ac8315cf361b1d1154a49a1
2,092
java
Java
subprojects/core/src/main/java/org/gradle/api/internal/changedetection/state/IndexedNormalizedFileSnapshot.java
dewens12/gradle
ae36415a36bcf8f5075aceb397e8ba85f66ba1ba
[ "Apache-2.0" ]
1
2018-01-15T08:12:13.000Z
2018-01-15T08:12:13.000Z
subprojects/core/src/main/java/org/gradle/api/internal/changedetection/state/IndexedNormalizedFileSnapshot.java
dewens12/gradle
ae36415a36bcf8f5075aceb397e8ba85f66ba1ba
[ "Apache-2.0" ]
2
2020-07-17T08:52:17.000Z
2021-05-09T06:16:13.000Z
subprojects/core/src/main/java/org/gradle/api/internal/changedetection/state/IndexedNormalizedFileSnapshot.java
dewens12/gradle
ae36415a36bcf8f5075aceb397e8ba85f66ba1ba
[ "Apache-2.0" ]
1
2018-01-15T08:12:29.000Z
2018-01-15T08:12:29.000Z
/* * Copyright 2016 the original author or authors. * * 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 org.gradle.api.internal.changedetection.state; public class IndexedNormalizedFileSnapshot extends AbstractNormalizedFileSnapshot { private final String absolutePath; private final int index; public IndexedNormalizedFileSnapshot(String absolutePath, int index, FileContentSnapshot snapshot) { super(snapshot); this.absolutePath = absolutePath; this.index = index; } @Override public String getNormalizedPath() { return absolutePath.substring(index); } public String getAbsolutePath() { return absolutePath; } public int getIndex() { return index; } @Override protected boolean hasSameNormalizedPathAs(AbstractNormalizedFileSnapshot other) { if (other instanceof IndexedNormalizedFileSnapshot) { IndexedNormalizedFileSnapshot that = (IndexedNormalizedFileSnapshot) other; int myLength = absolutePath.length() - index; int otherLength = that.absolutePath.length() - that.index; if (myLength != otherLength) { return false; } return absolutePath.regionMatches(index, that.absolutePath, that.index, myLength); } return false; } @Override protected int hashNormalizedPath() { int h = 0; for (int i = index; i < absolutePath.length(); i++) { h = 31 * h + absolutePath.charAt(i); } return h; } }
32.184615
104
0.671606
1fbade4caa62962a3944dc95801be44df9e87997
13,677
html
HTML
index.html
double947/double947.github.io
5e615114c038f34b3a0c1281fcb21263be94dde5
[ "BSD-2-Clause" ]
33
2021-01-27T14:40:16.000Z
2022-03-14T04:53:04.000Z
index.html
wangenze267/Personal-page
f7201b2b7b2f1973b325ca4e452fd800ec4123f3
[ "BSD-2-Clause" ]
null
null
null
index.html
wangenze267/Personal-page
f7201b2b7b2f1973b325ca4e452fd800ec4123f3
[ "BSD-2-Clause" ]
7
2021-06-21T01:42:46.000Z
2021-12-18T04:12:51.000Z
<!DOCTYPE html> <html> <head> <title>Untitled</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="assets/css/main.css" /> <noscript ><link rel="stylesheet" href="assets/css/noscript.css" /></noscript> <script src="js/vue.min.js" language="JavaScript"></script> <script src="js/jquery-3.4.1.min.js"></script> <script src="js/html2canvas.min.js" async="async"></script> <style> img { border-radius: 10px; } </style> </head> <body class="is-preload"> <!-- Loader --> <link rel="stylesheet" href="assets/css/loader.css" /> <div class="loader"> <div class="container"> <h1>🍊</h1> <p>摇匀</p> <p>再喝</p> </div> </div> <!-- Wrapper --> <div id="wrapper"> <!-- Main --> <section id="main"> <!-- Screenshot Button --> <span style=" display: flex; position: fixed; top: 2em; right: 2em; opacity: 0.65; font-size: 0.8em; " v-show="backButton" ><button class="button small" @click="screenShot" id="screenshot"> 保存网页截图 </button></span > <!-- Welcome Message and Contacts --> <header v-show="Contacts"> <span class="avatar" ><img src="images/avatar.jpg" alt="" style="width: 122px; height: 122px" /></span> <h1>Untitled</h1> <transition-group name="fade"> <div v-show="defaults" key="text"> <p>Lorem</p> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore facere accusamus quae nesciunt at fuga dicta vitae quidem reiciendis. Quos blanditiis corporis vel iusto reprehenderit ratione distinctio fugiat quae sed. </p> <button class="button small fit" @click="showAbout" v-bind:disabled="onTransition==1" > Click! </button> </div> <div v-for="item in contacts" v-if="item.show" key="item.name" v-html="item.content" ></div> <button class="button small" key="button" @click="hideContact(true)" style="opacity: 0.55" v-show="backButton" > 返回 </button> </transition-group> </header> <hr /> <footer v-show="Contacts"> <ul class="icons"> <li v-for="item in contacts"> <a @click="showContact(item.name)" :class="item.icon" >{{item.desc}}</a > </li> </ul> </footer> <!-- Page container --> <header v-show="info"> <transition-group name="fade"> <h1 key="title">{{ title }}</h1> <p key="text" v-for="text in texts">{{ text }}</p> <div v-html="html" key="html"></div> <img v-bind:src="img" key="img" style="width: 95%; height: auto" v-for="img in imgs" /> <div key="buttons"> <button class="button small" v-bind:disabled="(nowPage < startPage || onTransition==1)" @click="navigate(-1)" > 上一页 </button> <button class="button small" v-bind:disabled="(nowPage >= endPage - 2 || onTransition==1)" @click="navigate(1)" > 下一页 </button> </div> <hr key="br" /> <button @click="returnToContact" key="button" class="button fit" v-bind:disabled="onTransition==1" > 返回 </button> </transition-group> </header> </section> <!-- Footer --> <footer id="footer"></footer> </div> <!-- Scripts --> <script> if ("addEventListener" in window) { window.addEventListener("load", function () { document.body.className = document.body.className.replace( /\bis-preload\b/, "" ); }); document.body.className += navigator.userAgent.match(/(MSIE|rv:11\.0)/) ? " is-ie" : ""; } </script> <!-- Vuejs --> <script language="javascript"> var mainsec = new Vue({ el: "#main", data: { title: "", // The title of one page html: "", // HTML text of one page texts: [], // Pure texts of one page imgs: [], // Image url of a page's images startPage: 1, // First page of the website endPage: 3, // The last page of the website defaults: 1, // Show welcome message Contacts: 1, // Detect if to show contacts info: 0, // If to show designed pages deg: 0, // Main section rotate deg backButton: false, /* Change things below this line */ //Contact info /** * 有关下方icon的优化 * 因下方icon可以挂上用户自己的站点,所以做了如下修改 * jump为true,会直接跳转链接,链接为用户自定义的content字段 * jump为false,则是与原来一样。 */ contacts: [ { name: "Wechat", icon: "icon brands fa-weixin", desc: "微信", content: "<img src='images/demoQR.png' class='qr' />", show: false, jump: false, }, { name: "QQ", icon: "icon brands fa-qq", desc: "QQ", content: "<img src='images/demoQR.png' class='qr' /><h2>QQ:XXXXXX</h2>", show: false, jump: false, }, { name: "Github", icon: "icon brands fa-github", desc: "Github", content: "https://github.com/Jiaocz/Personal-page", show: false, jump: true, }, ], //Pages content page: [ { title: "Page 1", texts: [ "Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore facere accusamus quae nesciunt at fuga dicta vitae quidem reiciendis. Quos blanditiis corporis vel iusto reprehenderit ratione distinctio fugiat quae sed.", ], html: "", imgs: ["images/bg.jpg"], }, { title: "Page 2", texts: ["Some text", "And some text"], html: "<h2>HTML Support</h2>", imgs: [""], }, { title: "Page 3", texts: ["Multi images"], imgs: ["images/bg.jpg", "images/demoQR.png"], html: "", }, { title: "Page 4", texts: ["Another Demo"], html: '<a onclick="todonate()" style="color:#fff; background-color:#f0a1a8; border-radius: 0.3em; padding: 0.2em; cursor: pointer;"><<u>Donate!</u>></a><br /><p style="color:#ccc; font-size:0.7em;">Last updated: Apr. 14, 2021<p>', imgs: [""], }, { title: "Eastern egg page!", texts: ["Can only access with ?page=#"], html: "<a href='https://github.com/Jiaocz/Personal-page' target='_blank'>Origin project</a>", }, ], /* Change ends here */ nowPage: 0, // Pointer to current page onTransition: 0, //If the transition animation is on }, methods: { showContact: function (name) { let num = 0; for (let i = 0; i < this.contacts.length; i++) { if (this.contacts[i].name == name) { num = i; break; } } if (this.contacts[num].jump == true) { window.open(this.contacts[num].content); return; } this.hideContact(false); this.defaults = 0; clearTimeout(this.timer); this.timer = setTimeout(() => { this.contacts[num].show = true; this.backButton = true; }, 500); }, hideContact: function (neededDefault = true) { for (i = 0; i < this.contacts.length; i++) { this.contacts[i].show = false; } clearTimeout(this.timer); if (neededDefault == true) { this.backButton = false; this.timer = setTimeout(() => { this.defaults = 1; }, 500); } }, showAbout: function () { this.rotateCard(-360, 1, "Y"); var that = this; setTimeout(function () { that.info = 1; that.Contacts = 0; }, 400); }, returnToContact: function () { this.rotateCard(360, 1, "Y"); var that = this; setTimeout(function () { that.info = 0; that.Contacts = 1; }, 400); }, rotateCard: function (deg, time, axis) { this.onTransition = 1; this.deg += deg; var ele = document.getElementById("main"); ele.style.transition = "transform " + time + "s 0s"; ele.style.transform = "rotate" + axis + "(" + this.deg + "deg)"; var that = this; setTimeout(function () { that.onTransition = 0; }, time * 1000); }, loadPage: function () { this.title = this.page[this.nowPage].title; this.texts = this.page[this.nowPage].texts; this.html = this.page[this.nowPage].html; this.imgs = this.page[this.nowPage].imgs; }, navigate: function (m) { if (m == 1) { this.nowPage++; this.rotateCard(-360, 1, "Y"); setTimeout("mainsec.loadPage()", 400); } if (m == -1) { this.nowPage--; this.rotateCard(+360, 1, "Y"); setTimeout("mainsec.loadPage()", 400); } }, screenShot: function () { var button = document.getElementById("screenshot"); button.disabled = true; button.innerHTML = "截图中…"; html2canvas(document.body).then((canvas) => { var w = window.open(); w.document.title = "保存截图"; var i = w.document.createElement("img"); w.document.body.appendChild(i); i.src = canvas.toDataURL("image/jpg"); w.alert("长按图片或直接保存图片即可"); button.innerHTML = "保存网页截图"; button.disabled = false; }); }, }, mounted: function () { this.loadPage(); this.startPage = 1; this.endPage = this.page.length; }, }); </script> <style> .fade-enter-active, .fade-leave-active { transition: all 0.5s; } .fade-enter, .fade-leave-to { opacity: 0; transform: scale(0%, 0%); } .qr { text-align: center; width: 80%; height: 80%; } </style> <script> let FirstTriggered = true; function loaded() { timeout = FirstTriggered ? 1200 : 0; var page = getQueryVariable("page"); if (page >= mainsec.startPage && page <= mainsec.endPage && page) { var m = mainsec; mainsec.nowPage = page - 1; setTimeout(function () { m.rotateCard(-360, 1, "Y"); setTimeout(function () { m.loadPage(); m.info = 1; m.Contacts = 0; }, 400); }, timeout); } if (FirstTriggered) { $("body").on("dblclick", "img", function () { window.open(this.src); }); } if ( getQueryVariable("showContacts") || getQueryVariable("showcontacts") ) { var url; var browser = navigator.userAgent.toLowerCase(); if (mainsec.info == 1) { mainsec.returnToContact(); } if (browser.match(/MicroMessenger/i) == "micromessenger") { //微信浏览器 url = "https://u.wechat.com/EO3JtzoXctOZXiAG8tvYHuI"; setTimeout(function () { mainsec.showContact("Wechat"); }, 1500); } else if ( browser.indexOf(" qq") != -1 && browser.indexOf("mqqbrowser") != -1 ) { //qq内置浏览器 url = "https://qm.qq.com/cgi-bin/qm/qr?k=OZm0covTGqrELIwI0XKV6LxlKsCcLIsm"; setTimeout(function () { mainsec.showContact("QQ"); }, 1500); } } FirstTriggered = false; } </script> <script src="js/common.js"></script> </body> </html>
31.297483
244
0.441106
b91512397e187c7533aee9ff694a2272c856f04c
1,429
h
C
src/math/Line.h
KeinR/Danzun
413beccb3e6d2fc1b7fa1c50e387057404e07d88
[ "MIT" ]
null
null
null
src/math/Line.h
KeinR/Danzun
413beccb3e6d2fc1b7fa1c50e387057404e07d88
[ "MIT" ]
null
null
null
src/math/Line.h
KeinR/Danzun
413beccb3e6d2fc1b7fa1c50e387057404e07d88
[ "MIT" ]
null
null
null
#ifndef DANZUN_LINE_H_INCLUDED #define DANZUN_LINE_H_INCLUDED namespace dan { class Circle; } namespace dan { /** * A simple linear equation * Not worth documenting extensively * */ template<typename T> class LineTpl { /// y = mx + b // Is NAN if line is vertical T m; /// y = mx + b // Is NAN if line is vertical T b; T domainMin; T domainMax; T rangeMin; T rangeMax; public: LineTpl(); LineTpl(T x0, T y0, T x1, T y1); void setM(T m); void setB(T b); void setDomainMin(T x); void setDomainMax(T x); void setRangeMin(T y); void setRangeMax(T y); T getM() const; T getB() const; T getDomainMin() const; T getDomainMax() const; T getRangeMin() const; T getRangeMax() const; void setPoints(T x0, T y0, T x1, T y1); bool inDomain(T x) const; bool inRange(T y) const; /// Vertical line: x = domainMin & x = domainMax bool isVertical() const; /** * Tests if the line crosses the circle * \oaran c The circle * \return true if yes * */ bool intersects(const Circle &c) const; /** * y = mx + b * */ T solveForY(T x) const; }; typedef LineTpl<float> Line; } #endif
21.014706
56
0.509447
85c706e6872e10e13168d7b62cfc40c951cdbbe7
2,249
h
C
GeneratedModels/MSGraphDeviceEnrollmentFailureReason.h
phil1995/msgraph-sdk-objc-models
383c764009fcaf29dfdc07e7feaa59ab67b42876
[ "MIT" ]
11
2019-02-13T08:21:45.000Z
2021-11-14T15:45:25.000Z
GeneratedModels/MSGraphDeviceEnrollmentFailureReason.h
phil1995/msgraph-sdk-objc-models
383c764009fcaf29dfdc07e7feaa59ab67b42876
[ "MIT" ]
40
2019-09-10T23:25:31.000Z
2021-09-17T19:50:38.000Z
GeneratedModels/MSGraphDeviceEnrollmentFailureReason.h
phil1995/msgraph-sdk-objc-models
383c764009fcaf29dfdc07e7feaa59ab67b42876
[ "MIT" ]
7
2019-02-13T08:21:46.000Z
2021-10-10T09:41:03.000Z
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. #include <Foundation/Foundation.h> typedef NS_ENUM(NSInteger, MSGraphDeviceEnrollmentFailureReasonValue){ MSGraphDeviceEnrollmentFailureReasonUnknown = 0, MSGraphDeviceEnrollmentFailureReasonAuthentication = 1, MSGraphDeviceEnrollmentFailureReasonAuthorization = 2, MSGraphDeviceEnrollmentFailureReasonAccountValidation = 3, MSGraphDeviceEnrollmentFailureReasonUserValidation = 4, MSGraphDeviceEnrollmentFailureReasonDeviceNotSupported = 5, MSGraphDeviceEnrollmentFailureReasonInMaintenance = 6, MSGraphDeviceEnrollmentFailureReasonBadRequest = 7, MSGraphDeviceEnrollmentFailureReasonFeatureNotSupported = 8, MSGraphDeviceEnrollmentFailureReasonEnrollmentRestrictionsEnforced = 9, MSGraphDeviceEnrollmentFailureReasonClientDisconnected = 10, MSGraphDeviceEnrollmentFailureReasonUserAbandonment = 11, MSGraphDeviceEnrollmentFailureReasonEndOfEnum }; @interface MSGraphDeviceEnrollmentFailureReason : NSObject +(MSGraphDeviceEnrollmentFailureReason*) unknown; +(MSGraphDeviceEnrollmentFailureReason*) authentication; +(MSGraphDeviceEnrollmentFailureReason*) authorization; +(MSGraphDeviceEnrollmentFailureReason*) accountValidation; +(MSGraphDeviceEnrollmentFailureReason*) userValidation; +(MSGraphDeviceEnrollmentFailureReason*) deviceNotSupported; +(MSGraphDeviceEnrollmentFailureReason*) inMaintenance; +(MSGraphDeviceEnrollmentFailureReason*) badRequest; +(MSGraphDeviceEnrollmentFailureReason*) featureNotSupported; +(MSGraphDeviceEnrollmentFailureReason*) enrollmentRestrictionsEnforced; +(MSGraphDeviceEnrollmentFailureReason*) clientDisconnected; +(MSGraphDeviceEnrollmentFailureReason*) userAbandonment; +(MSGraphDeviceEnrollmentFailureReason*) UnknownEnumValue; +(MSGraphDeviceEnrollmentFailureReason*) deviceEnrollmentFailureReasonWithEnumValue:(MSGraphDeviceEnrollmentFailureReasonValue)val; -(NSString*) ms_toString; @property (nonatomic, readonly) MSGraphDeviceEnrollmentFailureReasonValue enumValue; @end @interface NSString (MSGraphDeviceEnrollmentFailureReason) - (MSGraphDeviceEnrollmentFailureReason*) toMSGraphDeviceEnrollmentFailureReason; @end
41.648148
152
0.873722
20eab3883c8b24b8d76cc630bb62085965a93503
1,097
sql
SQL
scripts/schema/ccpv2/201-apb-87-system-enum_de2.sql
lbouma/Cyclopath
d09d927a1e6f9e07924007fd39e8e807cd9c0f8c
[ "Apache-2.0" ]
15
2015-05-06T05:11:48.000Z
2021-12-03T14:56:58.000Z
scripts/schema/ccpv2/201-apb-87-system-enum_de2.sql
landonb/Cyclopath
d09d927a1e6f9e07924007fd39e8e807cd9c0f8c
[ "Apache-2.0" ]
null
null
null
scripts/schema/ccpv2/201-apb-87-system-enum_de2.sql
landonb/Cyclopath
d09d927a1e6f9e07924007fd39e8e807cd9c0f8c
[ "Apache-2.0" ]
8
2015-05-06T05:11:36.000Z
2020-11-04T05:11:22.000Z
/* Copyright (c) 2006-2013 Regents of the University of Minnesota. For licensing terms, see the file LICENSE. */ /* Fix the last_modified triggers. */ BEGIN TRANSACTION; SET CONSTRAINTS ALL DEFERRED; \qecho \qecho Fix the last_modified triggers \qecho /* Run this script just once, for all instances of Cyclopath */ SET search_path TO public; /* ==================================================================== */ /* Step (1) -- Fix the last_modified triggers */ /* ==================================================================== */ CREATE TRIGGER enum_definition_i BEFORE INSERT ON enum_definition FOR EACH ROW EXECUTE PROCEDURE set_last_modified(); CREATE TRIGGER enum_definition_u BEFORE UPDATE ON enum_definition FOR EACH ROW EXECUTE PROCEDURE set_last_modified(); /* ==================================================================== */ /* Step (n) -- All done! */ /* ==================================================================== */ \qecho \qecho Done! \qecho COMMIT;
28.868421
74
0.489517
9eb40e758e9910baff2e55f452796a558d78caea
25,798
lua
Lua
lua/starfall/libs_sv/nextbot.lua
ANormalTwig/StarfallEx
9a2eb1c8a017c393d0bb5fe23e0bb4d1f6b16632
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
lua/starfall/libs_sv/nextbot.lua
ANormalTwig/StarfallEx
9a2eb1c8a017c393d0bb5fe23e0bb4d1f6b16632
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
lua/starfall/libs_sv/nextbot.lua
ANormalTwig/StarfallEx
9a2eb1c8a017c393d0bb5fe23e0bb4d1f6b16632
[ "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
local registerprivilege = SF.Permissions.registerPrivilege local checkluatype = SF.CheckLuaType --- NextBot type -- @name NextBot -- @class type -- @server -- @libtbl nb_methods -- @libtbl nb_meta SF.RegisterType("NextBot", false, true, debug.getregistry().NextBot, "Entity") --- Library for spawning NextBots. -- @name nextbot -- @server -- @class library -- @libtbl nextbot_library SF.RegisterLibrary("nextbot") registerprivilege("nextbot.create", "Create nextbot", "Allows the user to create nextbots.") registerprivilege("nextbot.setGotoPos", "Set nextbot goto pos", "Allows the user to set a vector pos for the nextbot to try and go to.", {entites = {}}) registerprivilege("nextbot.removeGotoPos", "Remove nextbot goto pos", "Allows the user to remove the goto pos from a nextbot.", {entites = {}}) registerprivilege("nextbot.playSequence", "Play nextbot sequence", "Allows the user to set an animation for the nextbot to play.", {entites = {}}) registerprivilege("nextbot.faceTowards", "Face nextbot towards", "Allows the user to make a nextbot face a position.", {entities = {}}) registerprivilege("nextbot.setRunAct", "Set nextbot run activity", "Allows the user to set nextbot's run animation.", {entities = {}}) registerprivilege("nextbot.setIdleAct", "Set nextbot idle activity", "Allows the user to set nextbot's idle animation.", {entities = {}}) registerprivilege("nextbot.setVelocity", "Set nextbot velocity", "Allows the user to set nextbot's velocity.", {entities = {}}) registerprivilege("nextbot.jump", "Nextbot jump", "Allows the user to force a nextbot to jump.", {entities = {}}) registerprivilege("nextbot.addDeathCallback", "Add nextbot death callback", "Allows the user to add a callback function to run when the nextbot dies.", {entities = {}}) registerprivilege("nextbot.removeDeathCallback", "Remove nextbot death callback", "Allows the user to remove a death callback function from the nextbot.", {entities = {}}) registerprivilege("nextbot.addInjuredCallback", "Add nextbot injured callback", "Allows the user to add a callback function to run when the nextbot is injured.", {entities = {}}) registerprivilege("nextbot.removeInjuredCallback", "Remove nextbot injured callback", "Allows the user to remove an on injured callback function from the nextbot.", {entities = {}}) registerprivilege("nextbot.addLandCallback", "Add nextbot land callback", "Allows the user to add a callback function to run when the nextbot lands on the ground.", {entities = {}}) registerprivilege("nextbot.removeLandCallback", "Remove nextbot land callback", "Allows the user to remove an on land callback function from the nextbot.", {entities = {}}) registerprivilege("nextbot.addLeaveGroundCallback", "Add nextbot jump callback", "Allows the user to add a callback function to run when the nextbot leaves the ground.", {entities = {}}) registerprivilege("nextbot.removeLeaveGroundCallback", "Remove nextbot jump callback", "Allows the user to remove an on jump callback function from the nextbot.", {entities = {}}) registerprivilege("nextbot.addContactCallback", "Add contact callback", "Allows the user to add a collision callback to the entity which is called every tick when touched.", {entities = {}, usergroups = {default = 1} } ) registerprivilege("nextbot.removeContactCallback", "Remove nextbot contact callback", "Allows the user to remove the on contact callback from the nextbot.", {entities = {}}) registerprivilege("nextbot.addIgniteCallback", "Add nextbot ignite callback", "Allows the user to add a callback function to run when the nextbot gets set on fire.", {entities = {}}) registerprivilege("nextbot.removeIgniteCallback", "Remove nextbot ignite callback", "Allows the user to remove an on ignite callback function from the nextbot.", {entities = {}}) registerprivilege("nextbot.addNavChangeCallback", "Add nextbot nav change callback", "Allows the user to add a callback function to run when the nextbot changes nav areas.", {entities = {}}) registerprivilege("nextbot.removeNavChangeCallback", "Remove nextbot nav change callback", "Allows the user to remove an on nav change callback function from the nextbot.", {entities = {}}) registerprivilege("nextbot.ragdollOnDeath", "Ragdoll nextbot on death", "Allows the user to set whether the nextbot will ragdoll on death.", {entities = {}}) registerprivilege("nextbot.setMoveSpeed", "Set nextbot movespeed", "Allows the user to set the nextbot's movespeed.", {entities = {}}) registerprivilege("nextbot.setAcceleration", "Set nextbot acceleration", "Allows the user to set the nextbot's acceleration value", {entities = {}}) registerprivilege("nextbot.setDeceleration", "Set nextbot deceleration", "Allows the user to set the nextbot's deceleration value", {entities = {}}) registerprivilege("nextbot.setMaxYawRate", "Set nextbot max yaw rate", "Allows the user to set nextbot's visual turning speed.", {entities = {}}) registerprivilege("nextbot.setGravity", "Set nextbot gravity", "Allows the user to set the nextbot's gravity", {entities = {}}) registerprivilege("nextbot.setDeathDropHeight", "Set nextbot death drop height", "Allows the user to set the height the nextbot is scared to fall from.", {entities = {}}) registerprivilege("nextbot.setJumpHeight", "Set nextbot jump height", "Allows the user to set the nextbot's jump height", {entities = {}}) registerprivilege("nextbot.setStepHeight", "Set nextbot step height", "Allows the user to set the nextbot's step height", {entities = {}}) registerprivilege("nextbot.jumpAcrossGap", "Nextbot jump across gap", "Allows the user to make a nextbot jump across a gap.", {entities = {}}) registerprivilege("nextbot.setClimbAllowed", "Nextbot allow climb", "Allows the user to set whether the nextbot can climb nav ladders.", {entities = {}}) registerprivilege("nextbot.setAvoidAllowed", "Nextbot allow avoid", "Allows the user to set whether the nextbot can try to avoid obstacles.", {entities = {}}) registerprivilege("nextbot.setJumpGapsAllowed", "Nextbot allow jump gaps", "Allows the user to set whether the nextbot can jump gaps.", {entities = {}}) local nbCount = SF.LimitObject("nextbots", "nextbots", 30, "The number of props allowed to spawn via Starfall") return function(instance) local checkpermission = instance.player ~= SF.Superuser and SF.Permissions.check or function() end local nextbots = {} local nextbot_library, nb_meta, nb_methods = instance.Libraries.nextbot, instance.Types.NextBot, instance.Types.NextBot.Methods local vec_meta, vwrap, vunwrap = instance.Types.Vector, instance.Types.Vector.Wrap, instance.Types.Vector.Unwrap local navarea_methods, navarea_meta, navwrap, navunwrap = instance.Types.NavArea.Methods, instance.Types.NavArea, instance.Types.NavArea.Wrap, instance.Types.NavArea.Unwrap local nbwrap, nbunwrap = instance.Types.NextBot.Wrap, instance.Types.NextBot.Unwrap local function nextbotOnDestroy(ent) local ply = instance.player nbCount:free(ply, 1) nextbots[ent] = nil end local function register(ent) ent:CallOnRemove("starfall_nextbot_delete", nextbotOnDestroy) nbCount:free(instance.player, -1) nextbots[ent] = true end instance:AddHook("deinitialize", function() for nextbot in pairs(nextbots) do nextbot:Remove() end end) function nb_meta:__tostring() return "NextBot" end --- Creates a customizable NextBot -- @server -- @param Vector spawnpos The position the nextbot will be spawned at. -- @param string? model The model the nextbot will use. If nil, uses Kleiner. -- @return NextBot The nextbot. function nextbot_library.create(pos, mdl) checkpermission(instance, nil, "nextbot.create") checkluatype(mdl, TYPE_STRING) local upos = vunwrap(pos) local ply = instance.player nbCount:checkuse(ply, 1) local nb = ents.Create("starfall_cnextbot") register(nb, instance) nb:SetPos(upos) nb:SetModel(mdl or "models/kleiner.mdl") nb.chip = instance.entity nb:Spawn() nextbots[nb] = true return nbwrap(nb) end --- Checks if a user can spawn anymore nextbots. -- @server -- @return boolean True if user can spawn nextbots, False if not. function nextbot_library.canSpawn() if not SF.Permissions.hasAccess(instance, nil, "nextbot.create") then return false end return nbCount:check(instance.player) > 0 end --- Makes the nextbot try to go to a specified position. -- @server -- @param Vector gotopos The position the nextbot will continuosly try to go to. function nb_methods:setGotoPos(pos) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setGotoPos") nb.goTo = vunwrap(pos) end --- Removes the "go to" position from the NextBot. -- @server function nb_methods:removeGotoPos() local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.removeGotoPos") nb.goTo = nil end --- Returns the Vector the nextbot is trying to go to, set by setGotoPos -- @server -- @return Vector? Where the nextbot is trying to go to if it exists, else returns nil. function nb_methods:getGotoPos() local nb = nbunwrap(self) if nb.goTo then return vwrap(nb.goTo) else return nil end end --- Makes the nextbot play a sequence. This takes priority over movement. Will go to set pos after animation plays. -- @server -- @param string seqtoplay The name of the sequence to play. function nb_methods:playSequence(seq) checkluatype(seq, TYPE_STRING) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.playSequence") nb.playSeq = seq end --- Makes the nextbot face towards a specified position. Has to be called continuously to be effective. -- @server -- @param Vector facepos Position to face towards. function nb_methods:faceTowards(pos) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.faceTowards") nb.loco:FaceTowards(vunwrap(pos)) end --- Sets the activity the nextbot uses for running. -- @server -- @param number runact The activity the nextbot will use. function nb_methods:setRunAct(act) checkluatype(act, TYPE_NUMBER) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setRunAct") nb.RUNACT = act end --- Gets the activity the nextbot uses for running. -- @server -- @return number The run activity. function nb_methods:getRunAct() local nb = nbunwrap(self) return nb.RUNACT end --- Sets the activity the nextbot uses for idling. -- @server -- @param number runact The activity the nextbot will use. function nb_methods:setIdleAct(act) checkluatype(act, TYPE_NUMBER) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setIdleAct") nb.IDLEACT = act end --- Gets the activity the nextbot uses for idling. -- @server -- @return number The idle activity. function nb_methods:getIdleAct() local nb = nbunwrap(self) return nb.IDLEACT end --- Sets the nextbot's velocity. Seems to work only when used if nextbot is in air after using nextbot:jump() -- @server -- @param Vector newvel Velocity. function nb_methods:setVelocity(vel) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setVelocity") nb.loco:SetVelocity(vunwrap(vel)) end --- Gets the nextbot's velocity as a vector. -- @server -- @return Vector NB's velocity. function nb_methods:getVelocity() local nb = nbunwrap(self) return vwrap(nb.loco:GetVelocity()) end --- Forces the nextbot to jump. Requires the model to have an ACT_JUMP for proper animation. -- @server function nb_methods:jump() local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.jump") nb.loco:Jump() end --- Adds a callback function that will be run when this nextbot dies. -- @server -- @param string callbackid The unique ID this callback will use. -- @param function callback The function to run when the NB dies. The arguments are: (The NextBot, Damage, Attacker, Inflictor, Damage Pos, Damage Force, Damage Type) function nb_methods:addDeathCallback(id, func) checkluatype(id, TYPE_STRING) checkluatype(func, TYPE_FUNCTION) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.addDeathCallback") nb.DeathCallbacks:add(id, func) end --- Removes a death callback function from the NextBot. -- @server -- @param string callbackid The unique ID of the callback to remove. function nb_methods:removeDeathCallback(id) checkluatype(id, TYPE_STRING) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.removeDeathCallback") nb.DeathCallbacks:remove(id) end --- Adds a callback function that will be run when this nextbot is injured. -- @server -- @param string callbackid The unique ID this callback will use. -- @param function callback The function to run when the NB gets injured. The arguments are: (The NextBot, Damage, Attacker, Inflictor, Damage Pos, Damage Force, Damage Type) function nb_methods:addInjuredCallback(id, func) checkluatype(id, TYPE_STRING) checkluatype(func, TYPE_FUNCTION) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.addInjuredCallback") nb.InjuredCallbacks:add(id, func) end --- Removes a injury callback function from the NextBot. -- @server -- @param string callbackid The unique ID of the callback to remove. function nb_methods:removeInjuredCallback(id) checkluatype(id, TYPE_STRING) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.removeInjuredCallback") nb.InjuredCallbacks:remove(id) end --- Adds a callback function that will be run when this nextbot lands on the ground. -- @server -- @param string callbackid The unique ID this callback will use. -- @param function callback The function to run when the NB lands on the ground. The arguments are: (The NextBot, The entity the NB landed on.) function nb_methods:addLandCallback(id, func) checkluatype(id, TYPE_STRING) checkluatype(func, TYPE_FUNCTION) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.addLandCallback") nb.LandCallbacks:add(id, func) end --- Removes a landing callback function from the NextBot. -- @server -- @param string callbackid The unique ID of the callback to remove. function nb_methods:removeLandCallback(id) checkluatype(id, TYPE_STRING) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.removeLandCallback") nb.LandCallbacks:remove(id) end --- Adds a callback function that will be run when this nextbot leaves the ground. -- @server -- @param string callbackid The unique ID this callback will use. -- @param function callback The function to run when the NB leaves the ground. The arguments are: (The NextBot, The entity the NB "jumped" from.) function nb_methods:addLeaveGroundCallback(id, func) checkluatype(id, TYPE_STRING) checkluatype(func, TYPE_FUNCTION) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.addLeaveGroundCallback") nb.JumpCallbacks:add(id, func) end --- Removes a landing callback function from the NextBot. -- @server -- @param string callbackid The unique ID of the callback to remove. function nb_methods:removeLeaveGroundCallback(id) checkluatype(id, TYPE_STRING) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.removeLeaveGroundCallback") nb.JumpCallbacks:remove(id) end --- Adds a callback function that will be run when this nextbot gets ignited. -- @server -- @param string callbackid The unique ID this callback will use. -- @param function callback The function to run when the NB gets ignited. The arguments are: (The NextBot) function nb_methods:addIgniteCallback(id, func) checkluatype(id, TYPE_STRING) checkluatype(func, TYPE_FUNCTION) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.addIgniteCallback") nb.IgniteCallbacks:add(id, func) end --- Removes a ignite callback function from the NextBot. -- @server -- @param string callbackid The unique ID of the callback to remove. function nb_methods:removeIgniteCallback(id) checkluatype(id, TYPE_STRING) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.removeIgniteCallback") nb.IgniteCallbacks:remove(id) end --- Adds a callback function that will be run when the nextbot enters a new nav area. -- @server -- @param string callbackid The unique ID this callback will use. -- @param function callback The function to run when the NB enters a new nav area. The arguments are: (The NextBot, Old Nav Area, New Nav Area) function nb_methods:addNavChangeCallback(id, func) checkluatype(id, TYPE_STRING) checkluatype(func, TYPE_FUNCTION) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.addNavChangeCallback") nb.NavChangeCallbacks:add(id, func) end --- Removes a nav area change callback function from the NextBot. -- @server -- @param string callbackid The unique ID of the callback to remove. function nb_methods:removeNavChangeCallback(id) checkluatype(id, TYPE_STRING) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.removeNavChangeCallback") nb.NavChangeCallbacks:remove(id) end --- Sets a callback function that will be run when this nextbot touches another entity. Only 1 per NB. Setting a new callback will replace the old one. -- @server -- @param string callbackid The unique ID this callback will use. -- @param function callback The function to run when the NB touches another entity. The arguments are: (The NextBot, The entity the NB touched.) function nb_methods:addContactCallback(id, func) checkluatype(id, TYPE_STRING) checkluatype(func, TYPE_FUNCTION) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.addContactCallback") nb.ContactCallbacks:add(id, func) end --- Removes the contact callback function from the NextBot if present. -- @server -- @param string callbackid The unique ID of the callback to remove. function nb_methods:removeContactCallback(id) checkluatype(id, TYPE_STRING) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.removeContactCallback") nb.ContactCallbacks:remove(id) end --- Enable or disable ragdolling on death for the NextBot. -- @server -- @param boolean ragdollondeath Whether the nextbot should ragdoll on death. function nb_methods:ragdollOnDeath(bool) checkluatype(bool, TYPE_BOOL) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.ragdollOnDeath") nb.RagdollOnDeath = bool end --- Sets the move speed of the NextBot. -- @server -- @param number newmovespeed NB's new move speed. Default is 200. function nb_methods:setMoveSpeed(val) checkluatype(val, TYPE_NUMBER) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setMoveSpeed") nb.MoveSpeed = val end --- Gets the move speed of the NextBot. -- @server -- @return number NB's move speed. function nb_methods:getMoveSpeed() local nb = nbunwrap(self) return nb.MoveSpeed end --- Sets the acceleration speed of the NextBot. -- @server -- @param number newaccel NB's new acceleration. Default is 400 function nb_methods:setAcceleration(val) checkluatype(val, TYPE_NUMBER) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setAcceleration") nb.loco:SetAcceleration(val) end --- Gets the acceleration speed of the NextBot. -- @server -- @return number NB's acceleration value. function nb_methods:getAcceleration() local nb = nbunwrap(self) return nb.loco:GetAcceleration() end --- Sets the deceleration speed of the NextBot. -- @server -- @param number newaccel NB's new deceleration. Default is 400 function nb_methods:setDeceleration(val) checkluatype(val, TYPE_NUMBER) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setDeceleration") nb.loco:SetDeceleration(val) end --- Gets the deceleration speed of the NextBot. -- @server -- @return number NB's deceleration value. function nb_methods:getDeceleration() local nb = nbunwrap(self) return nb.loco:GetDeceleration() end --- Gets the max rate at which the NextBot can visually rotate. -- @server -- @param number The NextBot's max yaw rate. function nb_methods:getMaxYawRate() local nb = nbunwrap(self) return nb.loco:GetMaxYawRate() end --- Sets the max rate at which the NextBot can visually rotate. This will not affect moving or pathing. -- @server -- @param number newmaxyawrate Desired new maximum yaw rate function nb_methods:setMaxYawRate(val) checkluatype(val, TYPE_NUMBER) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setMaxYawRate") nb.loco:SetMaxYawRate(val) end --- Gets the gravity of the NextBot. -- @server -- @return number The nextbot's current gravity value. function nb_methods:getGravity() local nb = nbunwrap(self) return nb.loco:GetGravity() end --- Sets the gravity of the NextBot. -- @server -- @param number newgravity NB's new gravity. Default is 1000 function nb_methods:setGravity(val) checkluatype(val, TYPE_NUMBER) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setGravity") nb.loco:SetGravity(val) end --- Sets the height the nextbot is scared to fall from. -- @server -- @param number newdeathdropheight New height nextbot is afraid of. Default is 200. function nb_methods:setDeathDropHeight(val) checkluatype(val, TYPE_NUMBER) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setDeathDropHeight") nb.loco:SetDeathDropHeight(val) end --- Gets the height the nextbot is scared to fall from. -- @server -- @return number Height nextbot is afraid of. function nb_methods:getDeathDropHeight() local nb = nbunwrap(self) return nb.loco:GetDeathDropHeight() end --- Sets the max height the bot can step up. -- @server -- @param number stepheight Height (default is 18) function nb_methods:setStepHeight(val) checkluatype(val, TYPE_NUMBER) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setStepHeight") nb.loco:SetStepHeight(val) end --- Gets the max height the bot can step up. -- @server -- @return number The max height the bot can step up. function nb_methods:getStepHeight() local nb = nbunwrap(self) return nb.loco:GetStepHeight() end --- Return unit vector in XY plane describing our direction of motion - even if we are currently not moving -- @server -- @return Vector A vector representing the X and Y movement. function nb_methods:getGroundMotionVector() local nb = nbunwrap(self) return vwrap(nb.loco:GetGroundMotionVector()) end --- Returns whether the nextbot this locomotion is attached to is on ground or not. -- @server -- @return boolean Whether the nextbot is on ground or not. function nb_methods:isOnGround() local nb = nbunwrap(self) return nb.loco:IsOnGround() end --- Returns whether this nextbot can reach and/or traverse/move in given NavArea. -- @server -- @param NavArea NavArea to check. -- @return boolean Whether this nextbot can traverse given NavArea. function nb_methods:isAreaTraversable(nav) local nb = nbunwrap(self) local unav = navunwrap(nav) return nb.loco:IsAreaTraversable(unav) end --- Sets whether the Nextbot is allowed try to to avoid obstacles or not. This is used during path generation. Works similarly to nb_allow_avoiding convar. By default bots are allowed to try to avoid obstacles. -- @server -- @param boolean avoidallowed Whether this bot should be allowed to try to avoid obstacles. function nb_methods:setAvoidAllowed(val) checkluatype(val, TYPE_BOOL) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setAvoidAllowed") nb.loco:SetAvoidAllowed(val) end --- Returns whether the Nextbot is allowed to avoid obstacles or not. -- @server -- @return boolean Whether this bot is allowed to try to avoid obstacles. function nb_methods:getAvoidAllowed() local nb = nbunwrap(self) return nb.loco:GetAvoidAllowed() end --- Sets whether the Nextbot is allowed to climb or not. This is used during path generation. Works similarly to nb_allow_climbing convar. By default bots are allowed to climb. -- @server -- @param boolean climballowed Whether this bot should be allowed to climb. function nb_methods:setClimbAllowed(val) checkluatype(val, TYPE_BOOL) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setClimbAllowed") nb.loco:SetClimbAllowed(val) end --- Returns whether the Nextbot is allowed to climb or not. -- @server -- @return boolean Whether this bot is allowed to climb. function nb_methods:getClimbAllowed() local nb = nbunwrap(self) return nb.loco:GetClimbAllowed() end --- Sets whether the Nextbot is allowed to jump gaps or not. This is used during path generation. Works similarly to nb_allow_gap_jumping convar. By default bots are allowed to jump gaps. -- @server -- @param boolean jumpgapsallowed Whether this bot should be allowed to jump gaps. function nb_methods:setJumpGapsAllowed(val) checkluatype(val, TYPE_BOOL) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setJumpGapsAllowed") nb.loco:SetJumpGapsAllowed(val) end --- Returns whether the Nextbot is allowed to jump gaps or not. -- @server -- @return boolean Whether this bot is allowed to jump gaps. function nb_methods:getJumpGapsAllowed() local nb = nbunwrap(self) return nb.loco:GetJumpGapsAllowed() end --- Sets the height of the bot's jump -- @server -- @param number jumpheight Height (default is 58) function nb_methods:setJumpHeight(val) checkluatype(val, TYPE_NUMBER) local nb = nbunwrap(self) checkpermission(instance, nb, "nextbot.setJumpHeight") nb.loco:SetJumpHeight(val) end --- Gets the height of the bot's jump -- @server -- @return number Jump height function nb_methods:getJumpHeight() local nb = nbunwrap(self) return nb.loco:GetJumpHeight() end --- Makes the bot jump across a gap. The bot must be on ground (Entity:isOnGround). Its model must have the ACT_JUMP activity for proper animation. -- @server -- @param Vector landGoal The goal the nextbot should aim for. -- @param Vector landForward Presumably the direction vector the entity should be aiming in when landing. function nb_methods:jumpAcrossGap(landGoal, landForward) local nb = nbunwrap(self) local v1, v2 = vunwrap(landGoal), vunwrap(landForward) checkpermission(instance, nb, "nextbot.jumpAcrossGap") nb.loco:JumpAcrossGap(v1, v2) end end
40.884311
220
0.768354
67ae87e2aa09419b7ad909517120912152dd355c
618
sql
SQL
load_data_files_from_website/load_current_indi_table.sql
ltscomputingllc/faersdbstats
088525aaa1e69f7dcc577c1c467270e601ca5910
[ "Apache-2.0" ]
32
2016-05-11T19:59:19.000Z
2021-12-29T06:40:05.000Z
load_data_files_from_website/load_current_indi_table.sql
ltscomputingllc/faersdbstats
088525aaa1e69f7dcc577c1c467270e601ca5910
[ "Apache-2.0" ]
12
2017-01-13T22:08:50.000Z
2022-01-13T15:10:38.000Z
load_data_files_from_website/load_current_indi_table.sql
ltscomputingllc/faersdbstats
088525aaa1e69f7dcc577c1c467270e601ca5910
[ "Apache-2.0" ]
21
2016-06-05T01:30:45.000Z
2022-01-04T07:57:37.000Z
--###################################################### --# Create indi staging tables DDL and --# Load current FAERS data files into the indi table --# --# LTS Computing LLC --###################################################### set search_path = faers; drop table if exists indi ; create table indi ( primaryid varchar, caseid varchar, indi_drug_seq varchar, indi_pt varchar, filename varchar ); truncate indi; COPY indi FROM '/home/ubuntu/inbound_data/faers/ascii/all_indi_data_with_filename.txt' WITH DELIMITER E'$' CSV HEADER QUOTE E'\b' ; select filename, count(*) from indi group by filename order by 1;
25.75
131
0.621359
db2ea51c78ea7e7d6a0288ab367c45a55cfd7c27
2,451
dart
Dart
lib/const/page_str_const.dart
aykutbilici/Flutter
8a2c0478bbdc76bf9a4a4d79723a9db7bbc1ce72
[ "Apache-2.0" ]
2,852
2018-12-24T18:02:15.000Z
2021-02-11T03:04:37.000Z
lib/const/page_str_const.dart
elileo1/flutter-ui-nice
dd4accc8319c318bdeee3df7a359a4f8db72700d
[ "Apache-2.0" ]
10
2018-12-30T08:03:49.000Z
2020-08-08T04:27:19.000Z
lib/const/page_str_const.dart
elileo1/flutter-ui-nice
dd4accc8319c318bdeee3df7a359a4f8db72700d
[ "Apache-2.0" ]
482
2018-12-24T18:04:05.000Z
2021-01-30T00:45:35.000Z
/// /// Created by NieBin on 2018/12/24 /// Github: https://github.com/nb312 /// Email: niebin312@gmail.com /// /// const SIGN_UP_PAGES = [ "Sign up page 01", "Sign up page 02", "Sign up page 03", "Sign up page 04", "Sign up page 05", "Sign up page 06", "Sign up page 07", "Sign up page 08", "Sign up page 09", "Sign up page 10", "Sign up page 11", /// fixme you could add by your group one name fit one page. ]; const WALK_THROUGH_PAGES = [ "Walk through page 01", "Walk through page 02", "Walk through page 03", "Walk through page 04", "Walk through page 05", "Walk through page 06", /// fixme you could add by your group one name fit one page. ]; const NAVIGATION_PAGES = [ "Navigation page 01", "Navigation page 02", "Navigation page 03", "Navigation page 04", "Navigation page 05", /// fixme you could add by your group one name fit one page. ]; const PROFILE_PAGES = [ "Profile page 01", "Profile page 02", "Profile page 03", /// fixme you could add by your group one name fit one page. ]; const FEED_PAGES = [ "Feed page 01", "Feed page 02", "Feed page 03", "Feed page 04", "Feed page 05", "Feed page 06", "Feed page 07", "Feed page 08", "Feed page 09", "Feed page 10", "Feed page 11", "Feed page 12", "Feed page 13", /// fixme you could add by your group one name fit one page. ]; const CHAT_PAGES = [ "Chat page 01", "Chat page 02", "Chat page 03", /// fixme you could add by your group one name fit one page. ]; const SHOPPING_PAGES = [ "Shopping page 01", "Shopping page 02", "Shopping page 03", "Shopping page 04", "Shopping page 05", "Shopping page 06", "Shopping page 07", "Shopping page 08", "Shopping page 09", "Shopping page 10", "Shopping page 11", "Shopping page 12", "Shopping page 13", "Shopping page 14", "Shopping page 15", "Shopping page 16", "Shopping page 17", "Shopping page 18", "Shopping page 19", /// fixme you could add by your group one name fit one page. ]; const STATISTIC_PAGES = [ "Statistic page 01", "Statistic page 02", "Statistic page 03", /// fixme you could add by your group one name fit one page. ]; const MEDIA_PAGES = [ "Media page 01", "Media page 02", "Media page 03", /// fixme you could add by your group one name fit one page. ]; const CAMERA_PAGES = [ "Camera page 01", /// fixme you could add by your group one name fit one page. ];
21.313043
62
0.637699
8143f5a815d219762069048b1a41aa3fe5dc496d
3,088
swift
Swift
TSWeChat/Helpers/NSDate+Extension.swift
Charleo85/WuChat
9cb1826ed3863be8e719213e4a64570d48f2d0b6
[ "MIT" ]
1
2021-01-08T14:30:57.000Z
2021-01-08T14:30:57.000Z
TSWeChat/Helpers/NSDate+Extension.swift
Charleo85/WuChat
9cb1826ed3863be8e719213e4a64570d48f2d0b6
[ "MIT" ]
null
null
null
TSWeChat/Helpers/NSDate+Extension.swift
Charleo85/WuChat
9cb1826ed3863be8e719213e4a64570d48f2d0b6
[ "MIT" ]
null
null
null
// // NSDate+Extension.swift // TSWeChat // // Created by Hilen on 2/22/16. // Copyright © 2016 Hilen. All rights reserved. // import Foundation extension NSDate { class var milliseconds: NSTimeInterval { get { return NSDate().timeIntervalSince1970 * 1000 } } func week() -> String { let myWeekday = NSCalendar.currentCalendar().components([NSCalendarUnit.Weekday], fromDate: self).weekday switch myWeekday { case 0: return "周日" case 1: return "周一" case 2: return "周二" case 3: return "周三" case 4: return "周四" case 5: return "周五" case 6: return "周六" default: break } return "未取到数据" } class func messageAgoSinceDate(date: NSDate) -> String { return self.timeAgoSinceDate(date, numericDates: false) } class func timeAgoSinceDate(date: NSDate, numericDates: Bool) -> String { let calendar = NSCalendar.currentCalendar() let now = NSDate() let earliest = now.earlierDate(date) let latest = (earliest == now) ? date : now let components:NSDateComponents = calendar.components([ NSCalendarUnit.Minute, NSCalendarUnit.Hour, NSCalendarUnit.Day, NSCalendarUnit.WeekOfYear, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Second ], fromDate: earliest, toDate: latest, options: NSCalendarOptions()) if (components.year >= 2) { return "\(components.year) 年前" } else if (components.year >= 1){ if (numericDates){ return "1 年前" } else { return "去年" } } else if (components.month >= 2) { return "\(components.month) 月前" } else if (components.month >= 1){ if (numericDates){ return "1 个月前" } else { return "上个月" } } else if (components.weekOfYear >= 2) { return "\(components.weekOfYear) 周前" } else if (components.weekOfYear >= 1){ if (numericDates){ return "1 周前" } else { return "上一周" } } else if (components.day >= 2) { return "\(components.day) 天前" } else if (components.day >= 1){ if (numericDates){ return "1 天前" } else { return "昨天" } } else if (components.hour >= 2) { return "\(components.hour) 小时前" } else if (components.hour >= 1){ return "1 小时前" } else if (components.minute >= 2) { return "\(components.minute) 分钟前" } else if (components.minute >= 1){ return "1 分钟前" } else if (components.second >= 3) { return "\(components.second) 秒前" } else { return "刚刚" } } }
29.409524
113
0.496762
9679850c32afbde1103431ce0c4a21f317d9deb3
214
php
PHP
app/Wppps_comment.php
Thyrosis/blog-core
663158d361f8f6f010a6040882ab96ac18b38127
[ "MIT" ]
null
null
null
app/Wppps_comment.php
Thyrosis/blog-core
663158d361f8f6f010a6040882ab96ac18b38127
[ "MIT" ]
9
2018-10-10T09:20:02.000Z
2022-02-26T09:43:55.000Z
app/Wppps_comment.php
Thyrosis/blog-core
663158d361f8f6f010a6040882ab96ac18b38127
[ "MIT" ]
null
null
null
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Wppps_comment extends Model { public function wppost() { return $this->belongsTo(Wppps_post::class, 'comment_post_ID'); } }
15.285714
70
0.691589
41daef4008d453adfa3c98d4365c74e98b0ff793
343
h
C
SurviosPrototype/Source/SurviosPrototype/PlayerPaddleAI.h
Ganemo/Prototype
787aecf231fd6790a0c0e114c69775e1297737e3
[ "Apache-2.0" ]
null
null
null
SurviosPrototype/Source/SurviosPrototype/PlayerPaddleAI.h
Ganemo/Prototype
787aecf231fd6790a0c0e114c69775e1297737e3
[ "Apache-2.0" ]
null
null
null
SurviosPrototype/Source/SurviosPrototype/PlayerPaddleAI.h
Ganemo/Prototype
787aecf231fd6790a0c0e114c69775e1297737e3
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "PlayerPaddle.h" #include "PlayerPaddleAI.generated.h" /** * */ UCLASS() class SURVIOSPROTOTYPE_API APlayerPaddleAI : public APlayerPaddle { GENERATED_BODY() public: void Tick(float DeltaTime) override; };
16.333333
78
0.752187
e6668d114d8bed4211b10d586fa74b8bc98b21ec
421
go
Go
solid/chat.go
maragudk/gomponents-heroicons
71ff79ee2426199a4203a8421dd44699404a2e7b
[ "MIT" ]
3
2021-06-28T15:59:33.000Z
2021-08-05T14:55:23.000Z
solid/chat.go
maragudk/gomponents-heroicons
71ff79ee2426199a4203a8421dd44699404a2e7b
[ "MIT" ]
null
null
null
solid/chat.go
maragudk/gomponents-heroicons
71ff79ee2426199a4203a8421dd44699404a2e7b
[ "MIT" ]
null
null
null
package solid import ( g "github.com/maragudk/gomponents" h "github.com/maragudk/gomponents-heroicons" ) func Chat(children ...g.Node) g.Node { return h.Solid(g.Group(children), g.Raw(`<path fill-rule="evenodd" d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7zM7 9H5v2h2V9zm8 0h-2v2h2V9zM9 9h2v2H9V9z" clip-rule="evenodd"/>`)) }
32.384615
234
0.712589
1c4b36f01ae6d41c24da48412f0f05225971bade
1,458
swift
Swift
AC Widget/Components/ButtonStyles/PrimaryButtonStyle.swift
iAugux/AppStore-Connect-Widget
38439fd9f110b6df1515ee0080efb584598b9779
[ "MIT" ]
null
null
null
AC Widget/Components/ButtonStyles/PrimaryButtonStyle.swift
iAugux/AppStore-Connect-Widget
38439fd9f110b6df1515ee0080efb584598b9779
[ "MIT" ]
null
null
null
AC Widget/Components/ButtonStyles/PrimaryButtonStyle.swift
iAugux/AppStore-Connect-Widget
38439fd9f110b6df1515ee0080efb584598b9779
[ "MIT" ]
null
null
null
// // PrimaryButtonStyle.swift // AC Widget by NO-COMMENT // import SwiftUI public struct PrimaryButtonStyle: ButtonStyle { private var color: Color = .accentColor private var foregroundColor: Color = .white private var scheme: ColorScheme = .light public init(color: Color = .accentColor, foregroundColor: Color = .white, scheme: ColorScheme = .light ) { self.color = color self.foregroundColor = foregroundColor self.scheme = scheme } public func makeBody(configuration: Configuration) -> some View { configuration.label .font(.system(size: 20)) .foregroundColor(scheme == .dark ? color : foregroundColor) .frame(minWidth: 0, maxWidth: .infinity, idealHeight: 10, maxHeight: 10, alignment: .center) .padding(18) .background(color.opacity(scheme == .dark ? 0.15 : 1)) .cornerRadius(10) .opacity(configuration.isPressed ? 0.8 : 1) } } struct PrimaryButtonStyle_Previews: PreviewProvider { static var previews: some View { Group { Button("Button", action: {}) .buttonStyle(PrimaryButtonStyle(scheme: .light)) .padding() Button("Button", action: {}) .buttonStyle(PrimaryButtonStyle(scheme: .dark)) .padding() .preferredColorScheme(.dark) } } }
30.375
104
0.588477
10255a96dc95b80a31b3ea7fa47327bfc02ccf62
2,324
dart
Dart
lib/models/response_data.dart
lukaskurz/http_interceptor
65648bf68f0a5102adb85f7f4d65f8ebb09eaded
[ "MIT" ]
76
2019-05-29T02:00:17.000Z
2022-03-10T06:28:12.000Z
lib/models/response_data.dart
lukaskurz/http_interceptor
65648bf68f0a5102adb85f7f4d65f8ebb09eaded
[ "MIT" ]
73
2019-07-06T16:36:13.000Z
2022-03-21T12:07:27.000Z
lib/models/response_data.dart
lukaskurz/http_interceptor
65648bf68f0a5102adb85f7f4d65f8ebb09eaded
[ "MIT" ]
42
2019-09-17T22:25:39.000Z
2022-03-24T02:52:26.000Z
import 'dart:typed_data'; import 'package:http/http.dart'; import 'package:http_interceptor/http/http.dart'; import 'package:http_interceptor/models/request_data.dart'; /// A class that mimics HTTP Response in order to intercept it's data. class ResponseData { /// The bytes comprising the body of this response. Uint8List bodyBytes; /// The HTTP status code for this response. int statusCode; Map<String, String>? headers; /// The body of the response as a string. String? body; /// The size of the response body, in bytes. /// /// If the size of the request is not known in advance, this is `null`. int? contentLength; bool? isRedirect; /// Whether the server requested that a persistent connection be maintained. bool? persistentConnection; /// The (frozen) request that triggered this response. RequestData? request; /// Creates a new response data with body bytes. ResponseData( this.bodyBytes, this.statusCode, { this.headers, this.body, this.contentLength, this.isRedirect, this.persistentConnection, this.request, }); /// Method of the request that triggered this response. Method? get method => request?.method; /// URL as String of the request that triggered this response. String? get url => request?.url; /// Creates a new response data from an HTTP response. factory ResponseData.fromHttpResponse(Response response) { return ResponseData( response.bodyBytes, response.statusCode, headers: response.headers, body: response.body, contentLength: response.contentLength, isRedirect: response.isRedirect, persistentConnection: response.persistentConnection, request: (response.request != null) ? RequestData.fromHttpRequest(response.request!) : null, ); } /// Converts this response data to an HTTP response. Response toHttpResponse() { return Response.bytes( bodyBytes, statusCode, headers: headers!, persistentConnection: persistentConnection!, isRedirect: isRedirect!, request: request?.toHttpRequest(), ); } /// Convenient toString implementation for logging. @override String toString() { return 'ResponseData { $method, $url, $headers, $statusCode, $body, $request }'; } }
27.341176
84
0.693201
96e73b97b66e1312664334e72c9e17816dea16b8
16,267
cpp
C++
camera_calibration_ws/monodepth-FPN/catkin_ws/src/ddd_plane_extr/src/ddd_plane_extra_save.cpp
tamaslevente/trai
4bf68463b941f305d9b25a9374b6c2a2d51a8046
[ "MIT" ]
null
null
null
camera_calibration_ws/monodepth-FPN/catkin_ws/src/ddd_plane_extr/src/ddd_plane_extra_save.cpp
tamaslevente/trai
4bf68463b941f305d9b25a9374b6c2a2d51a8046
[ "MIT" ]
null
null
null
camera_calibration_ws/monodepth-FPN/catkin_ws/src/ddd_plane_extr/src/ddd_plane_extra_save.cpp
tamaslevente/trai
4bf68463b941f305d9b25a9374b6c2a2d51a8046
[ "MIT" ]
null
null
null
// #include <boost/filesystem.hpp> #include <ros/ros.h> #include <dynamic_reconfigure/server.h> #include <visualization_msgs/Marker.h> // Include opencv2 #include <opencv2/core.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> // #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <image_transport/image_transport.h> #include <sensor_msgs/PointCloud.h> #include <pcl/point_types.h> #include <pcl_ros/point_cloud.h> #include <pcl_ros/publisher.h> #include <pcl/ModelCoefficients.h> #include <pcl_msgs/ModelCoefficients.h> #include <pcl/sample_consensus/method_types.h> #include <pcl/sample_consensus/model_types.h> #include <pcl/segmentation/sac_segmentation.h> #include <pcl/filters/extract_indices.h> #include <pcl/common/eigen.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/range_image/range_image_planar.h> #include <pcl/io/pcd_io.h> #include <pcl/filters/voxel_grid.h> #include <pcl/filters/extract_indices.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/filters/statistical_outlier_removal.h> #include <pcl/sample_consensus/sac_model_perpendicular_plane.h> #include <pcl/filters/project_inliers.h> #include <pcl/segmentation/extract_clusters.h> #include <pcl/common/common.h> #include <pcl/common/centroid.h> #include <pcl/common/pca.h> #include <pcl/features/fpfh.h> #include <pcl/features/normal_3d.h> #include <geometry_msgs/PointStamped.h> #include <pcl/filters/crop_hull.h> #include <pcl/surface/concave_hull.h> #include <pcl/surface/convex_hull.h> #include <iostream> #include <experimental/filesystem> #include <iterator> #include <vector> #include <algorithm> #include <math.h> #include <regex> using namespace cv; using namespace std; using namespace pcl_msgs; // namespace fs = boost::filesystem; namespace fs = std::experimental::filesystem; class Planes2Depth { public: // typedef pcl::PointXYZRGB Point; typedef pcl::PointXYZI Point; typedef pcl::PointCloud<Point> PointCloud; /* * constructor * setup which topics are passed out (advertise) and to which topics are listend (subscribe) */ Planes2Depth() : it_(nh_) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>); // "~" means, that the node hand is opened within the private namespace (to get the "own" paraemters) ros::NodeHandle private_nh("~"); // ######################################## // This should be used without a subscriber // ######################################## string saveDirOrig = "/home/marian/calibration_ws/monodepth-FPN/MonoDepth-FPN-PyTorch/dataset/training_data/training_data/curvature_grad/verify_network/orig_planes.PCD.train/"; // BEWARE of that last / !!! You don't want to forget that, trust me! string saveDirPred = "/home/marian/calibration_ws/monodepth-FPN/MonoDepth-FPN-PyTorch/dataset/training_data/training_data/curvature_grad/verify_network/pred_planes.PCD.train/"; // BEWARE of that last / !!! You don't want to forget that, trust me! long int lenOrig = saveDirOrig.length(); char saveDirOrigArr[lenOrig + 1]; long int lenPred = saveDirPred.length(); char saveDirPredArr[lenPred + 1]; strcpy(saveDirOrigArr, saveDirOrig.c_str()); strcpy(saveDirPredArr, saveDirPred.c_str()); if (private_nh.getParam("pcd_folder", _param)) { ROS_INFO("Got param: %s", _param.c_str()); int i = 0; fs::path p(_param.c_str()); typedef vector<fs::path> vec; // store paths, vec v; // so we can sort them later copy(fs::directory_iterator(p), fs::directory_iterator(), back_inserter(v)); sort(v.begin(), v.end()); for (vec::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it) { cout << "pcd_file:" << *it << '\n'; if (pcl::io::loadPCDFile<pcl::PointXYZ>(*it, *cloud) == -1) //* load the file { PCL_ERROR("Couldn't read file %s \n", it); } // cout << entry.path() << '\n'; std::cout << "Loaded " << cloud->width * cloud->height << " data points" << std::endl; string saveDirOrig(saveDirOrigArr); char numberDirOrigArr[6]; sprintf(numberDirOrigArr, "%05d", i); string origFilename = saveDirOrig + numberDirOrigArr; string saveDirPred(saveDirPredArr); char numberDirPredArr[6]; sprintf(numberDirPredArr, "%05d", i); string predFilename = saveDirPred + numberDirPredArr; pcl::PointCloud<pcl::PointXYZ>::Ptr resulted_plane; resulted_plane = getGTPlanes(cloud, origFilename, predFilename); // ############################################ // for loading the prediction cloud as well string pcd_file = *it; string temp_pred_pcd_file = regex_replace(pcd_file,regex("orig.PCD.train"),"pred.PCD.train"); string pred_pcd_file = regex_replace(temp_pred_pcd_file,regex("_orig.pcd"),"_pred.pcd"); cout << "pcd_file:" << pred_pcd_file << '\n'; if (pcl::io::loadPCDFile<pcl::PointXYZ>(pred_pcd_file, *cloud) == -1) //* load the file { PCL_ERROR("Couldn't read file %s \n", it); } pcl::PointCloud<pcl::PointXYZ>::Ptr pred_resulted_plane; pred_resulted_plane = getGTPlanes(cloud, predFilename, origFilename); if(!resulted_plane->empty() && !pred_resulted_plane->empty()){ // save the orig plane to a lonely file char number[6]; sprintf(number, "%01d", i); string pcd_version = "_orig"; pcl::io::savePCDFileASCII(origFilename + pcd_version +".pcd", *resulted_plane); std::cerr << "Saved " << resulted_plane->size() << " data points to" << origFilename << std::endl; char pred_number[6]; sprintf(pred_number, "%01d", i); pcd_version = "_pred"; pcl::io::savePCDFileASCII(predFilename + pcd_version +".pcd", *pred_resulted_plane); std::cerr << "Saved " << pred_resulted_plane->size() << " data points to" << predFilename << std::endl; i++; } } } else { ROS_ERROR("Failed to get param 'pcd_folder' "); } } ~Planes2Depth() {} pcl::PointCloud<pcl::PointXYZ>::Ptr getGTPlanes(pcl::PointCloud<pcl::PointXYZ>::Ptr inputCloud, string pcd_file_name, string no_filter_file_name) { // string only_points_path = "my_full_custom_pcdmultiP1.pcd"; // Set variables for the current data set, // because these are different depending on the camera range // ################################## // // multiP_pico_2m_50.bag // ################################## // _distanceThreshold = 0.0000175; // _okDistanceThreshold = 0.005; _clusterTolerance = 0.000006; _minClusterSize = 12000; _maxClusterSize = 250000; _maxIterations = 100; _remained_pointcloud = 0.2; // _alpha = 0.01; pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1(new pcl::PointCloud<pcl::PointXYZ>); pcl::copyPointCloud(*inputCloud, *cloud1); std::cerr << "#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#-#" << std::endl; std::cerr << "Point cloud sizeeeeeeeeeeeeeeeee: " << cloud1->size() << std::endl; // cleaning the point cloud of NaNs in order to further apply the Euclidean cluster extraction boost::shared_ptr<std::vector<int>> indices(new std::vector<int>); pcl::removeNaNFromPointCloud(*cloud1, *indices); pcl::ExtractIndices<pcl::PointXYZ> extract; extract.setInputCloud(cloud1); extract.setIndices(indices); extract.setNegative(false); extract.filter(*cloud1); // /////////////////////////////////////////////////////////////////////////////////////////// // Preparing the plane extraction pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients); pcl::PointIndices::Ptr inliers(new pcl::PointIndices); // Create the segmentation object pcl::SACSegmentation<pcl::PointXYZ> seg; // Optional seg.setOptimizeCoefficients(true); // Mandatory seg.setModelType(pcl::SACMODEL_PERPENDICULAR_PLANE); seg.setMethodType(pcl::SAC_RANSAC); seg.setMaxIterations(_maxIterations); seg.setDistanceThreshold(_distanceThreshold); //because we want a specific plane (X-Z Plane) (In camera coordinates the ground plane is perpendicular to the y axis) Eigen::Vector3f axis = Eigen::Vector3f(0.0, 1.0, 0.0); //y axis seg.setAxis(axis); int angle = 23; seg.setEpsAngle(angle * (M_PI / 180.0f)); // plane can be within 10.0 degrees of X-Z plane pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_rest(new pcl::PointCloud<pcl::PointXYZ>()); int i = 0, nr_points = (int)cloud1->size(); ////////////////// ????????????????????????? std::cerr << "Point cloud size: " << nr_points << std::endl; // While nr_points% of the original cloud is still there while (cloud1->size() > _remained_pointcloud * nr_points) { // Extract inliers pcl::ExtractIndices<pcl::PointXYZ> plane_extracter; pcl::PointCloud<pcl::PointXYZ>::Ptr plane_only(new pcl::PointCloud<pcl::PointXYZ>()); // Extracting the plane using RANSAC seg.setInputCloud(cloud1); seg.segment(*inliers, *coefficients); std::vector<int> ransac_plane_indices; ransac_plane_indices = inliers->indices; if (inliers->indices.size() == 0) { PCL_ERROR("Could not estimate a planar model for the given dataset.\n"); } plane_extracter.setInputCloud(cloud1); plane_extracter.setIndices(inliers); plane_extracter.setNegative(false); // Get the points associated with the planar surface plane_extracter.filter(*plane_only); std::cerr << "PointCloud representing the planar component: " << plane_only->width * plane_only->height << " data points." << std::endl; // //////////////////////////////////////////////////////////////////////// // Extracting indices of detected clusters for identifying the only plane pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>); tree->setInputCloud(plane_only); std::vector<pcl::PointIndices> cluster_indices; pcl::EuclideanClusterExtraction<pcl::PointXYZ> ec; ec.setClusterTolerance(_clusterTolerance); // in meters ec.setMinClusterSize(_minClusterSize); ec.setMaxClusterSize(_maxClusterSize); ec.setSearchMethod(tree); ec.setInputCloud(plane_only); std::vector<int> POIIndices; ec.extract(cluster_indices); // here should not be more than a single cluster extracted per plane int j = 0; for (std::vector<pcl::PointIndices>::const_iterator it = cluster_indices.begin(); it != cluster_indices.end(); ++it) { pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_cluster(new pcl::PointCloud<pcl::PointXYZ>); for (const auto &idx : it->indices) { cloud_cluster->push_back((*plane_only)[idx]); //* POIIndices.push_back(ransac_plane_indices[idx]); } cloud_cluster->width = cloud_cluster->size(); cloud_cluster->height = 1; cloud_cluster->is_dense = true; std::cout << "PointCloud representing the Cluster: " << cloud_cluster->size() << " data points." << std::endl; j++; } i++; // POI and scraps pcl::PointCloud<pcl::PointXYZ>::Ptr scraps_cloud(new pcl::PointCloud<pcl::PointXYZ>); // now we need to extract the prior detected plane pcl::PointIndices::Ptr clusterInliersIndices(new pcl::PointIndices); clusterInliersIndices->indices = POIIndices; // Extract Inliers from the input cloud pcl::ExtractIndices<pcl::PointXYZ> cluster_extracter; cluster_extracter.setInputCloud(cloud1); cluster_extracter.setIndices(clusterInliersIndices); cluster_extracter.setNegative(false); // Keep only the inliers (i.e. the plane) cluster_extracter.filter(*plane_only); cluster_extracter.setNegative(true); // Remove the inliers (i.e. remove only the plane and keep the rest) cluster_extracter.filter(*scraps_cloud); // ////////////////////////////////////////////////////////////////////////// // Statistical outlier remover for a plane pcl::PointCloud<pcl::PointXYZ>::Ptr plane_filtered (new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr empty_cloud (new pcl::PointCloud<pcl::PointXYZ>); std::cerr << "Cloud before filtering: " << std::endl; std::cerr << *plane_only << std::endl; if (plane_only->size() > 0){ // pcl::io::savePCDFileASCII(pcd_file_name+ "_just_plane.pcd", *plane_only); // std::cerr << "Saved " << plane_filtered->size() << " data points to just_plane" << std::endl; // Create the filtering object pcl::StatisticalOutlierRemoval<pcl::PointXYZ> sor; sor.setInputCloud (plane_only); sor.setMeanK (50); sor.setStddevMulThresh (2); sor.filter (*plane_filtered); std::cerr << "Cloud after filtering: " << std::endl; std::cerr << *plane_filtered << std::endl; return plane_filtered; // sor.setNegative (true); // sor.filter (*plane_filtered); // pcl::io::savePCDFileASCII(pcd_file_name+ number + pcd_version + "_nofilter.pcd", *plane_filtered); // std::cerr << "Saved " << plane_filtered->size() << " data points to" << pcd_file_name << std::endl; // ////////////////////////////////////////////////////// // adding the scraps to the original point cloud cloud1->points = scraps_cloud->points; } return empty_cloud; // one iteration is more than enough break; } } private: ros::NodeHandle nh_; image_transport::ImageTransport it_; ros::Subscriber sub_; // Pico parameters OK!!!!!!!!!!!!!! double K[9] = {460.585, 0.0, 334.081, 0.0, 460.268, 169.808, 0.0, 0.0, 1.0}; double centerX_ = K[2]; double centerY_ = K[5]; double focalX_ = K[0]; double focalY_ = K[4]; // int height_ = 480; int height_ = 360; // only for pico (I guess it has its name for a reason! XD) int width_ = 640; int pixel_pos_x, pixel_pos_y; float z, u, v; Mat cv_image; std::vector<Point2d> imagePoints; float _distanceThreshold; float _okDistanceThreshold; float _clusterTolerance; float _planesDelay; int _minClusterSize; int _maxClusterSize; float _remained_pointcloud; int _maxIterations; float _alpha; string _param; }; int main(int argc, char **argv) { ros::init(argc, argv, "ddd_plane_extr"); Planes2Depth c2d; return 0; }
40.974811
254
0.579025
e3bfb8c96153a31fdc05e8db4a98bce181a16b68
196
asm
Assembly
arch/x86/kernel/interrupt.asm
31core/illumi
344fa945df9031aadda6775121e8fb641b45e844
[ "MIT" ]
1
2021-05-10T10:52:06.000Z
2021-05-10T10:52:06.000Z
arch/x86/kernel/interrupt.asm
31core/illumi
344fa945df9031aadda6775121e8fb641b45e844
[ "MIT" ]
null
null
null
arch/x86/kernel/interrupt.asm
31core/illumi
344fa945df9031aadda6775121e8fb641b45e844
[ "MIT" ]
null
null
null
global asm_interrupt20h, asm_interrupt21h extern interrupt20h, interrupt21h asm_interrupt20h: pushad call interrupt20h popad iretd asm_interrupt21h: pushad call interrupt21h popad iretd
13.066667
41
0.836735
8008827d6edf46ad24dedbd45905a8b8de2c5807
305
java
Java
source/devhelper/src/main/java/com/github/jerryxia/devhelper/event/NopValueWrapperEventProducer.java
JerryXia/BizHttpRequestTest
c1212f01d5298e9b1cc782a7a9dcd7b45c33eab7
[ "MIT" ]
11
2018-06-26T03:07:01.000Z
2021-01-12T09:20:35.000Z
source/devhelper/src/main/java/com/github/jerryxia/devhelper/event/NopValueWrapperEventProducer.java
JerryXia/BizHttpRequestTest
c1212f01d5298e9b1cc782a7a9dcd7b45c33eab7
[ "MIT" ]
5
2021-01-20T23:38:50.000Z
2022-03-31T19:52:12.000Z
source/devhelper/src/main/java/com/github/jerryxia/devhelper/event/NopValueWrapperEventProducer.java
JerryXia/BizHttpRequestTest
c1212f01d5298e9b1cc782a7a9dcd7b45c33eab7
[ "MIT" ]
null
null
null
/** * */ package com.github.jerryxia.devhelper.event; public class NopValueWrapperEventProducer implements ValueWrapperEventProducer { @Override public void publish(Object record) { // ignore } @Override public void tryPublish(Object record) { // ignore } }
16.052632
80
0.659016
24d298342d35d20c7a485cd93c59b169574c703e
4,355
dart
Dart
gssuite/lib/Components/Classroom/UserClassrooms/Attendance/Attendance.dart
GS-Suite/flutter-front
0bd105489cf17b1ddc4cd89d19e94725f28ea970
[ "MIT" ]
null
null
null
gssuite/lib/Components/Classroom/UserClassrooms/Attendance/Attendance.dart
GS-Suite/flutter-front
0bd105489cf17b1ddc4cd89d19e94725f28ea970
[ "MIT" ]
null
null
null
gssuite/lib/Components/Classroom/UserClassrooms/Attendance/Attendance.dart
GS-Suite/flutter-front
0bd105489cf17b1ddc4cd89d19e94725f28ea970
[ "MIT" ]
1
2021-10-04T03:08:28.000Z
2021-10-04T03:08:28.000Z
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; import '../../../../apis/api.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'dart:async'; import './ViewAttendance.dart'; import './takeAttendance.dart'; class Attendance extends StatefulWidget { final classId; final initialTab; Attendance({this.classId, this.initialTab}); @override _AttendanceState createState() => _AttendanceState(); } class _AttendanceState extends State<Attendance> with TickerProviderStateMixin { var _attendanceToken; bool shouldButtonEnabled = true; TabController _tabController; @override void initState() { // TODO: implement initState super.initState(); _tabController = new TabController(length: 2, vsync: this); } @override Widget build(BuildContext context) { return Scaffold( bottomNavigationBar: Container( color: Colors.white, child: Container( color: Colors.white, child: TabBar( controller: _tabController, indicatorColor: Colors.teal[400], labelColor: Colors.teal[400], unselectedLabelColor: Colors.black54, tabs: <Widget>[ Tab( icon: Icon(Icons.list), child: Text('Take Attendance'), ), Tab( icon: Icon(Icons.playlist_play_outlined), child: Text('Attendance Logs'), ), ]), ), ), body: TabBarView( children: <Widget>[ TakeAttendance( classId: this.widget.classId, ), ViewAttendance( classId: this.widget.classId, ) ], controller: _tabController, ), ); } _disabledButton() { shouldButtonEnabled = false; Timer(Duration(seconds: 30), () => shouldButtonEnabled = true); } generateAttendanceToken() async { { print('take attendance'); SharedPreferences prefs = await SharedPreferences.getInstance(); Map<String, String> _headers = {'token': prefs.getString('token')}; print('headers:'); print(_headers); print(this.widget.classId); var _body = json.encode({ 'classroom_uid': this.widget.classId.toString(), 'timeout_minutes': 30, }); var response = await http.post(takeAttendance, body: _body, headers: _headers); print(response.body.toString()); var res = json.decode(response.body.toString()); if (res['success'] == true) { print(res); setState(() { this._attendanceToken = res['data']['attendance_token']; }); prefs.setString('token', res['token'].toString()); } else { print('Response didn\'t fetch'); print(res); } } } stopTakingAttendance() async { print('stop attendance'); SharedPreferences prefs = await SharedPreferences.getInstance(); print(_attendanceToken); Map<String, String> _headers = {'token': prefs.getString('token')}; print('headers:'); print(_headers); print(this.widget.classId); var _body = json.encode({ 'classroom_uid': this.widget.classId.toString(), 'attendance_token': _attendanceToken }); var response = await http.post(stopAttendance, body: _body, headers: _headers); var res = json.decode(response.body.toString()); if (res['success'] == true) { print(res); setState(() { this._attendanceToken = null; }); Fluttertoast.showToast( msg: res['message'], toastLength: Toast.LENGTH_LONG, gravity: ToastGravity.SNACKBAR, backgroundColor: Colors.grey[200], textColor: Colors.black38, fontSize: 16.0); prefs.setString('token', res['token'].toString()); } else { print('Response didn\'t fetch'); print(res); Fluttertoast.showToast( msg: 'Error', toastLength: Toast.LENGTH_LONG, gravity: ToastGravity.SNACKBAR, backgroundColor: Colors.grey[200], textColor: Colors.black38, fontSize: 16.0); } } }
29.425676
80
0.598852
91f631104c020e4ef65c136150a0bad1462d7caf
594
asm
Assembly
oeis/277/A277108.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/277/A277108.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/277/A277108.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A277108: a(n) = 4n*(n+5). ; Submitted by Christian Krause ; 24,56,96,144,200,264,336,416,504,600,704,816,936,1064,1200,1344,1496,1656,1824,2000,2184,2376,2576,2784,3000,3224,3456,3696,3944,4200,4464,4736,5016,5304,5600,5904,6216,6536,6864,7200,7544,7896,8256,8624,9000,9384,9776,10176,10584,11000,11424,11856,12296,12744,13200,13664,14136,14616,15104,15600,16104,16616,17136,17664,18200,18744,19296,19856,20424,21000,21584,22176,22776,23384,24000,24624,25256,25896,26544,27200,27864,28536,29216,29904,30600,31304,32016,32736,33464,34200,34944,35696,36456 add $0,4 bin $0,2 sub $0,3 mul $0,8
66
496
0.776094
e74d6b5cb6b33de03174b3f76422db075a9fcbe3
117,301
js
JavaScript
broadlink-webhooks.js
RandomApplications/broadlink-webhooks
f60efb62f25c894f92077e8bff437802471f7a54
[ "MIT" ]
4
2020-08-10T20:33:49.000Z
2022-01-29T20:28:13.000Z
broadlink-webhooks.js
RandomApplications/broadlink-webhooks
f60efb62f25c894f92077e8bff437802471f7a54
[ "MIT" ]
null
null
null
broadlink-webhooks.js
RandomApplications/broadlink-webhooks
f60efb62f25c894f92077e8bff437802471f7a54
[ "MIT" ]
null
null
null
#!/usr/bin/env node 'use strict'; const {Builder, By, Key, until} = require('selenium-webdriver'); // https://www.npmjs.com/package/selenium-webdriver const prompts = require('prompts'); // https://www.npmjs.com/package/prompts const sanitizeFilename = require('sanitize-filename'); // https://www.npmjs.com/package/sanitize-filename // The following requirements are included in selenium-webdriver: const seleniumFirefoxOptions = require('selenium-webdriver/firefox').Options; const seleniumChromeOptions = require('selenium-webdriver/chrome').Options; // The following requirements are included in Node.js: const homeDir = require('os').homedir(); const pathJoin = require('path').join; const {existsSync, readFileSync, writeFileSync, mkdirSync} = require('fs'); const {exec, execSync, spawnSync} = require('child_process'); // Adjustable Settings (but should not need to be adjusted unless something isn't working properly): const debugLogging = false; const defaultBrowserWindowSize = {width: 690, height: 1000}; // Only used for Firefox and Chrome when not Headless. const maxTaskAttempts = 3; // Number of times tasks will be attempted if they fail, such as logging in, retrieving Webhooks key, retrieving devices and scenes, and setting up an Applet, etc. const longWaitForElementTime = 10000; // Generally used when waiting for an element which only gets one chance to show up. const shortWaitForElementTime = 100; // Generally used when waiting for an element inside a loop with which is given many chances to show up. const waitForNextPageSleepInLoopTime = 100; // The next two variables help prevent getting caught in a infinite loop if the page doesn't get updated properly. const maxButtonClicksCount = 100; const maxIterationsOnPageAfterButtonNoLongerExists = 100; // INTERNAL SETTINGS - DO NOT EDIT: // Values for tasks: const taskCreateApplets = 'Create Webhooks Applets'; const taskArchiveAppletsNotInBroadLink = 'Archive Webhooks Applets Not in BroadLink'; const taskArchiveApplets = 'Archive Webhooks Applets'; const taskOutputSummary = 'Output Summary'; const taskGenerateHomebridgeIFTTTconfig = 'Generate homebridge-ifttt Configuration'; const taskGenerateHomebridgeHTTPconfig = 'Generate homebridge-http-switch Configuration'; const taskGenerateJSON = 'Generate JSON Details'; const taskOpenEditAppletURLs = 'Open Edit Applet URLs'; const taskOpenGitHubPage = 'Open "broadlink-webhooks" on GitHub'; // Values for BroadLink/Applet group choices: const groupDevicesAndScenes = 'Devices and Scenes'; const groupDevicesOnly = 'Devices Only'; const groupScenesOnly = 'Scenes Only'; // Values for multiple option questions: const optionChange = 'change'; const optionQuit = 'quit'; let webDriver = null; let browserToAutomate = null; (async function broadlink_webhooks() { console.info('\nbroadlink-webhooks: Create and Manage IFTTT Webhooks Applets for BroadLink'); try { let versionFromPackageJson = JSON.parse(readFileSync(`${__dirname}/package.json`)).version; if (versionFromPackageJson) { console.info(`Version ${versionFromPackageJson}\n`); } else { throw 'NO VERSION KEY'; } } catch (retrieveVersionErrr) { console.info(''); // Just for a line break if version retrieval fails. } let userQuit = false; try { let lastIFTTTusernameUsed = null; let lastIFTTTpasswordUsed = null; let lastBrowserToAutomate = null; while (!userQuit) { let browserPromptChoices = [ {title: 'Firefox (Hidden Window / Headless)', value: 'firefox-headless'}, {title: 'Firefox (Visible Window)', value: 'firefox'}, {title: '–', value: 'browserSpacer1', disabled: true}, {title: 'Chrome (Hidden Window / Headless)', value: 'chrome-headless'}, {title: 'Chrome (Visible Window)', value: 'chrome'}, {title: '–', value: 'browserSpacer2', disabled: true}, {title: 'Quit', value: optionQuit} ]; let initialBrowserChoiceSelection = 0; if (browserToAutomate) { for (let thisBrowserChoiceIndex = 0; thisBrowserChoiceIndex < browserPromptChoices.length; thisBrowserChoiceIndex ++) { let thisBrowserChoice = browserPromptChoices[thisBrowserChoiceIndex]; if (browserToAutomate == thisBrowserChoice.value) { initialBrowserChoiceSelection = thisBrowserChoiceIndex; break; } } } let optionsPrompts = [ { type: 'select', name: 'browserSelection', message: 'Choose a Web Browser to Automate (Using Selenium WebDriver):', choices: browserPromptChoices, initial: initialBrowserChoiceSelection }, { type: prev => ((prev == optionQuit) ? null : 'select'), name: 'taskSelection', message: 'Choose a Task:', choices: [ {title: 'Create Webhooks Applets', description: 'No duplicates will be created for identical Webhooks Applets already created by "broadlink-webhooks".', value: taskCreateApplets}, {title: 'Archive Webhooks Applets for Renamed or Deleted Devices/Scenes in BroadLink', description: 'For renamed devices/scenes, you can re-run the "Create Webhooks Applets" task after this task is finished.', value: taskArchiveAppletsNotInBroadLink}, {title: 'Archive All Webhooks Applets Created by "broadlink-webhooks"', description: 'If you ever want the Webhooks Applets back after removing them, you can re-run the "Create Webhooks Applets" task at any time.', value: taskArchiveApplets}, {title: '–', value: 'taskSpacer1', disabled: true}, {title: 'Output Summary of Webhooks Applets Created by "broadlink-webhooks" and Devices/Scenes in BroadLink', value: taskOutputSummary}, {title: 'Generate "homebridge-ifttt" Configuration for Webhooks Applets Created by "broadlink-webhooks"', description: 'Useful only if you use Homebridge. Visit homebridge.io to learn more.', value: taskGenerateHomebridgeIFTTTconfig}, {title: 'Generate "homebridge-http-switch" Configuration for Webhooks Applets Created by "broadlink-webhooks"', description: 'Useful only if you use Homebridge and want more customization options than homebridge-ifttt. Visit homebridge.io to learn more.', value: taskGenerateHomebridgeHTTPconfig}, {title: 'Generate JSON Details of Webhooks Applets Created by "broadlink-webhooks"', description: 'Useful for your own custom scripts.', value: taskGenerateJSON}, {title: 'Open All IFTTT Edit URLs for Webhooks Applets Created by "broadlink-webhooks"', description: 'Edit Applet URLs will open in your default web browser. You should be logged in to IFTTT in your default web browser before running this task.', value: taskOpenEditAppletURLs}, {title: taskOpenGitHubPage, description: 'To learn more, ask questions, make suggestions, and report issues.', value: taskOpenGitHubPage}, {title: '–', value: 'taskSpacer2', disabled: true}, {title: 'Change Web Browser Selection', value: optionChange}, {title: 'Quit', value: optionQuit} ] }, { type: prev => (((prev == taskOpenGitHubPage) || (prev == optionChange) || (prev == optionQuit)) ? null : 'select'), name: 'groupSelection', message: prev => `Which BroadLink group would you like to ${ ((prev == taskCreateApplets) ? 'create Webhooks Applets for' : ((prev == taskArchiveAppletsNotInBroadLink) ? 'archive Webhooks Applets for which have been renamed or deleted in BroadLink' : ((prev == taskArchiveApplets) ? 'archive all Webhooks Applets for' : ((prev == taskOutputSummary) ? 'output summary for' : ((prev == taskGenerateHomebridgeIFTTTconfig) ? 'generate "homebridge-ifttt" configuration for' : ((prev == taskGenerateHomebridgeHTTPconfig) ? 'generate "homebridge-http-switch" configuration for' : ((prev == taskGenerateJSON) ? 'generate JSON details for' : ((prev == taskOpenEditAppletURLs) ? 'open IFTTT edit Applet URLs for' : 'DO UNKNOWN TASK TO') ) ) ) ) ) ) ) }?`, choices: [ {title: 'Both Devices & Scenes', value: groupDevicesAndScenes}, {title: 'Only Devices', value: groupDevicesOnly}, {title: 'Only Scenes', value: groupScenesOnly}, {title: '–', value: 'groupSpacer1', disabled: true}, {title: 'Change Web Browser and Task Selection', value: optionChange}, {title: 'Quit', value: optionQuit} ] } ]; let optionsPromptsResponse = await prompts(optionsPrompts); let optionsPromptsResponseValues = Object.values(optionsPromptsResponse); if (optionsPromptsResponseValues.includes(optionQuit)) { throw 'USER QUIT'; } else if (optionsPromptsResponseValues.includes(optionChange)) { console.log(''); // Just for a line break before re-displaying options prompt. continue; } else if (optionsPromptsResponseValues.includes(taskOpenGitHubPage)) { let gitHubRepoURL = 'https://github.com/RandomApplications/broadlink-webhooks'; try { exec(`${((process.platform == 'darwin') ? 'open' : ((process.platform == 'win32') ? 'start' : 'xdg-open'))} ${gitHubRepoURL}`); console.info(`\n\n${taskOpenGitHubPage}: ${gitHubRepoURL}\n\n`); } catch (openGitHubRepoURLerror) { console.error(`\n\nERROR OPENING "${gitHubRepoURL}": ${openGitHubRepoURLerror}\n\n`); } continue; } else if (optionsPromptsResponseValues.length < optionsPrompts.length) { throw 'CANCELED OPTIONS SELECTION'; } browserToAutomate = optionsPromptsResponse.browserSelection; if (lastBrowserToAutomate != browserToAutomate) { if (webDriver) { try { await webDriver.quit(); } catch (quitWebDriverError) { // Ignore any error quitting WebDriver. } } lastBrowserToAutomate = browserToAutomate; } let needNewWebDriver = true; let iftttLogInURL = 'https://ifttt.com/login?wp_=1'; try { await webDriver.getCurrentUrl(); // If getCurrentUrl() fails, then WebDriver was not built yet, was quit(), or the window was probably closed, so we'll make a new one and log in. needNewWebDriver = false; await webDriver.get(iftttLogInURL); try { await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox). if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation'); } catch (acceptLeavePageAlertError) { // Ignore any error if there is no Leave Page confirmation. } if ((await webDriver.getCurrentUrl()) == iftttLogInURL) throw 'NEED TO RE-LOG IN'; } catch (checkForLogInError) { let logInMethodPromptResponse = await prompts([ { type: 'select', name: 'logInMethod', message: 'Choose Log In Method:', choices: [ {title: 'Log In via Command Line', description: 'Only regular IFTTT accounts are supported when logging in via command line.', value: 'logInViaCLI'}, {title: 'Log In Manually via Web Browser', description: 'To log in to IFTTT with a linked Apple, Google, or Facebook account, you must choose this option.', value: 'logInManuallyViaWebBrowser'}, {title: '–', value: 'logInMethodSpacer1', disabled: true}, {title: 'Change Web Browser and Task Selection', value: optionChange}, {title: 'Quit', value: optionQuit} ], initial: ((lastIFTTTusernameUsed == 'loggedInManuallyViaWebBrowser') ? 1 : 0) } ]); let logInMethodPromptResponseValues = Object.values(logInMethodPromptResponse); if (logInMethodPromptResponseValues.length < 1) { throw 'CANCELED IFTTT LOG IN'; } else if (logInMethodPromptResponseValues.includes(optionChange)) { console.log(''); // Just for a line break before re-displaying options prompt. continue; } else if (logInMethodPromptResponseValues.includes(optionQuit)) { throw 'USER QUIT'; } let logInViaCLI = (logInMethodPromptResponse.logInMethod == 'logInViaCLI'); if (!logInViaCLI && (browserToAutomate.endsWith('-headless'))) { console.info('\nLOGGING IN MANUALLY VIA WEB BROWSER IS ONLY SUPPORTED WHEN AUTOMATING FIREFOX OR CHROME WITH A VISIBLE WINDOW\n'); let changeBrowserPromptResponse = await prompts([ { type: 'select', name: 'newBrowserSelection', message: 'Change Web Browser to Automate (to Log In Manually via Web Browser):', choices: [ {title: 'Firefox (Visible Window)', value: 'firefox'}, {title: 'Chrome (Visible Window)', value: 'chrome'}, {title: '–', value: 'changeBrowserSpacer1', disabled: true}, {title: 'Log In via Command Line Instead', description: 'Only regular IFTTT accounts are supported when logging in via command line.', value: 'logInViaCLI'}, {title: '–', value: 'changeBrowserSpacer2', disabled: true}, {title: 'Quit', value: optionQuit} ], initial: ((browserToAutomate == 'chrome-headless') ? 1 : 0) } ]); let changeBrowserPromptResponseValues = Object.values(changeBrowserPromptResponse); if (changeBrowserPromptResponseValues.length < 1) { throw 'CANCELED IFTTT LOG IN'; } else if (changeBrowserPromptResponseValues.includes(optionQuit)) { throw 'USER QUIT'; } logInViaCLI = (changeBrowserPromptResponse.newBrowserSelection == 'logInViaCLI'); if (!logInViaCLI) { browserToAutomate = changeBrowserPromptResponse.newBrowserSelection; lastBrowserToAutomate = browserToAutomate; needNewWebDriver = true; } } let logInPrompts = [ { type: 'text', name: 'iftttUsername', message: 'IFTTT Username:', initial: ((lastIFTTTusernameUsed != 'loggedInManuallyViaWebBrowser') ? lastIFTTTusernameUsed : null), validate: iftttUsername => ((iftttUsername == '') ? 'IFTTT Username Required' : true) }, { type: 'password', name: 'iftttPassword', message: 'IFTTT Password:', initial: prev => ((prev == lastIFTTTusernameUsed) ? lastIFTTTpasswordUsed : null), validate: iftttPassword => ((iftttPassword == '') ? 'IFTTT Password Required' : ((iftttPassword.length < 6) ? 'IFTTT Password Too Short' : true)) } ]; let logInPromptsResponse = null; if (logInViaCLI) { console.log(''); // Just for a line break before log in prompts. logInPromptsResponse = await prompts(logInPrompts); if (Object.keys(logInPromptsResponse).length < 2) throw 'CANCELED IFTTT LOG IN'; } if (needNewWebDriver) { if (webDriver) { try { await webDriver.quit(); } catch (quitWebDriverError) { // Ignore any error quitting WebDriver. } } let browserToAutomateParts = browserToAutomate.split('-'); let actualBrowserToAutomate = browserToAutomateParts[0]; let browserShouldBeHeadless = ((browserToAutomateParts.length > 1) && (browserToAutomateParts[1] == 'headless')); if ((process.platform == 'darwin') && ((actualBrowserToAutomate == 'firefox') || (actualBrowserToAutomate == 'chrome'))) { // Make sure WebDriver executable isn't quarantined on Mac (which could result in "cannot be opened because the developer cannot be verified" error). let webDriverExecutablePath = `/usr/local/bin/${(actualBrowserToAutomate == 'firefox') ? 'gecko' : actualBrowserToAutomate}driver`; try { if (existsSync(webDriverExecutablePath)) { if (spawnSync('xattr', [webDriverExecutablePath]).stdout.toString().includes('com.apple.quarantine')) { if (debugLogging) console.debug(`DEBUG - "${webDriverExecutablePath}" IS QUARANTINED - ATTEMPTING TO REMOVE QUARANTINE XATTR`); execSync(`xattr -d com.apple.quarantine ${webDriverExecutablePath}`); if (debugLogging) { if (spawnSync('xattr', [webDriverExecutablePath]).stdout.toString().includes('com.apple.quarantine')) { console.warn(`DEBUG WARNING - "${webDriverExecutablePath}" IS STILL QUARANTINED`); } else { console.debug(`DEBUG - "${webDriverExecutablePath}" IS NO LONGER QUARANTINED`); } } } else if (debugLogging) { console.debug(`DEBUG - "${webDriverExecutablePath}" IS NOT QUARANTINED`); } } } catch (webDriverQuarantineError) { if (debugLogging) console.error(`DEBUG ERROR - FAILED TO CHECK OR REMOVE "${webDriverExecutablePath}" QUARANTINE - ${webDriverQuarantineError}`); } } webDriver = await new Builder().forBrowser(actualBrowserToAutomate).setFirefoxOptions( (browserShouldBeHeadless ? new seleniumFirefoxOptions().headless().windowSize(defaultBrowserWindowSize) : new seleniumFirefoxOptions().windowSize(defaultBrowserWindowSize)) ).setChromeOptions( (browserShouldBeHeadless ? new seleniumChromeOptions().headless().windowSize(defaultBrowserWindowSize) : new seleniumChromeOptions().windowSize(defaultBrowserWindowSize) ).excludeSwitches('enable-logging') // Disable excessive logging with Chrome on Windows. ).build(); } if (logInViaCLI) { for (let logInAttemptCount = 1; logInAttemptCount <= maxTaskAttempts; logInAttemptCount ++) { try { await webDriver.get(iftttLogInURL); try { await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox). if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation'); } catch (acceptLeavePageAlertError) { // Ignore any error if there is no Leave Page confirmation. } await check_for_server_error_page(); try { await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Log in"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. await webDriver.wait( until.elementLocated(By.id('user_username')), shortWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Entering IFTTT Username'); await thisElement.clear(); await thisElement.sendKeys(logInPromptsResponse.iftttUsername); }); await webDriver.wait( until.elementLocated(By.id('user_password')), shortWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Entering IFTTT Password'); await thisElement.clear(); await thisElement.sendKeys(logInPromptsResponse.iftttPassword); }); } catch (fillLogInPageError) { // Allow login page to error in case the user already logged in and submitted in the web browser. } let currentURL = await webDriver.getCurrentUrl(); // IFTTT will first redirect to "https://ifttt.com/session" and then finally to "https://ifttt.com/home" after successfully logging in. while (currentURL != 'https://ifttt.com/home') { if (currentURL == iftttLogInURL) { try { await webDriver.wait( until.elementLocated(By.xpath('//input[@value="Log in" or @value="Signing in..."]')), shortWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Clicking Log In Button'); try { await thisElement.click(); } catch (innerClickLogInButtonError) { // Ignore likely stale element error and keep looping. } }); } catch (outerClickLogInButtonError) { // Ignore likely error from element not existing and keep looping. } } else if (currentURL.startsWith('https://ifttt.com/login?email=')) { throw 'INCORRECT IFTTT USERNAME OR PASSWORD'; } else if (currentURL == 'https://ifttt.com/session') { try { await webDriver.wait( until.elementLocated(By.id('user_tfa_code')), shortWaitForElementTime // Don't wait long for TFA input since it may not exist and we want to keep looping if not. ).then(async thisElement => { if (await thisElement.getAttribute('value') == '') { // Make sure we don't prompt again before the page has reloaded. console.log(''); // Just for a line break before two-step code prompt. let twoStepPromptResponse = await prompts({ type: 'text', name: 'iftttTwoStepVerificationCode', message: 'IFTTT Two-Step Verification Code:' }); // Allow Two-Step Verification Code prompt to be clicked through without entering a code in case the code was already entered and submitted in the web browser. if ((Object.keys(twoStepPromptResponse).length == 1) && (twoStepPromptResponse.iftttTwoStepVerificationCode != '')) { if (debugLogging) console.debug('DEBUG - Entering IFTTT Two-Step Verification Code'); await thisElement.clear(); await thisElement.sendKeys(twoStepPromptResponse.iftttTwoStepVerificationCode); } } }); await webDriver.wait( until.elementLocated(By.xpath('//input[@value="Log in" or @value="Signing in..."]')), shortWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Clicking Two-Step Log In Button'); try { await thisElement.click(); } catch (innerIftttTwoStepVerificationError) { // Ignore likely stale element error and keep looping. } }); } catch (outerIftttTwoStepVerificationError) { // Ignore likely error from element not existing and keep looping. } } currentURL = await webDriver.getCurrentUrl(); await webDriver.sleep(waitForNextPageSleepInLoopTime); } break; } catch (logInError) { console.error(`\nERROR: ${logInError}`); if (debugLogging) { try { console.debug(`URL=${await webDriver.getCurrentUrl()}`); } catch (getCurrentURLerror) { console.debug('FAILED TO GET CURRENT URL'); } } console.error(`\n\nERROR LOGGING IN TO IFTTT - ATTEMPT ${logInAttemptCount} OF ${maxTaskAttempts}\n\n`); if (logInAttemptCount == maxTaskAttempts) { throw logInError; } else { if (logInError.toString().includes('INCORRECT IFTTT USERNAME OR PASSWORD')) { logInPrompts[0].initial = logInPromptsResponse.iftttUsername; logInPromptsResponse = await prompts(logInPrompts); if (Object.keys(logInPromptsResponse).length < 2) throw 'CANCELED IFTTT LOG IN'; } } } } lastIFTTTusernameUsed = logInPromptsResponse.iftttUsername; lastIFTTTpasswordUsed = logInPromptsResponse.iftttPassword; } else { for ( ; ; ) { try { await webDriver.get(iftttLogInURL); try { await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox). if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation'); } catch (acceptLeavePageAlertError) { // Ignore any error if there is no Leave Page confirmation. } let currentURL = await webDriver.getCurrentUrl(); if (currentURL == 'https://ifttt.com/home') { lastIFTTTusernameUsed = 'loggedInManuallyViaWebBrowser'; lastIFTTTpasswordUsed = null; break; } else { throw 'NEED TO LOG IN'; } } catch (checkForLogInError) { console.log(''); // Just for a line break before confirm log in prompt. let confirmLoggedInManuallyViaWebBrowserPromptResponse = await prompts({ type: 'toggle', name: 'confirmLogIn', message: 'Confirm After Logging In Manually via Web Browser:', initial: true, active: 'Confirm Log In', inactive: 'Quit' }); if ((Object.keys(confirmLoggedInManuallyViaWebBrowserPromptResponse).length == 0) || (confirmLoggedInManuallyViaWebBrowserPromptResponse.confirmLogIn == false)) { throw 'USER QUIT'; } } } } } let startTime = new Date(); console.info(`\nSTARTED "${optionsPromptsResponse.taskSelection}" TASK WITH "${optionsPromptsResponse.groupSelection}" ON ${startTime.toLocaleString().replace(', ', ' AT ')}`); let iftttWebhooksKey = 'DID_NOT_RETRIEVE_IFTTT_WEBHOOKS_KEY'; if ((optionsPromptsResponse.taskSelection == taskCreateApplets) || (optionsPromptsResponse.taskSelection == taskGenerateHomebridgeIFTTTconfig) || (optionsPromptsResponse.taskSelection == taskGenerateHomebridgeHTTPconfig) || (optionsPromptsResponse.taskSelection == taskGenerateJSON)) { for (let retrieveWebhooksKeyAttemptCount = 1; retrieveWebhooksKeyAttemptCount <= maxTaskAttempts; retrieveWebhooksKeyAttemptCount ++) { try { await webDriver.get('https://ifttt.com/maker_webhooks/settings'); try { await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox). if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation'); } catch (acceptLeavePageAlertError) { // Ignore any error if there is no Leave Page confirmation. } await check_for_server_error_page(); if ((await webDriver.getCurrentUrl()) == 'https://ifttt.com/maker_webhooks') { // If we got redirected, make sure that the Webhooks Service is connected. try { await webDriver.wait(until.elementLocated(By.xpath('//a[contains(@href,"/maker_webhooks/redirect_to_connect")]')), shortWaitForElementTime); throw '"Webhooks" SERVICE NOT CONNECTED IN IFTTT'; } catch (webhooksServiceConnectionError) { if (webhooksServiceConnectionError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT')) { throw webhooksServiceConnectionError; } // Otherwise, ignore likely error from element not existing. Which means that the Webhooks Service is connected like we want. } } await webDriver.wait( until.elementLocated(By.xpath('//span[starts-with(text(),"https://maker.ifttt.com/use/")]')), longWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Retrieving IFTTT Webhooks Key'); iftttWebhooksKey = (await thisElement.getText()).replace('https://maker.ifttt.com/use/', ''); }); break; } catch (retrieveWebhooksKeyError) { if (retrieveWebhooksKeyError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT')) { throw retrieveWebhooksKeyError; // Don't keep trying if service isn't connected. } console.error(`\nERROR: ${retrieveWebhooksKeyError}`); if (debugLogging) { try { console.debug(`URL=${await webDriver.getCurrentUrl()}`); } catch (getCurrentURLerror) { console.debug('FAILED TO GET CURRENT URL'); } } console.error(`\n\nERROR RETRIEVING WEBHOOKS KEY - ATTEMPT ${retrieveWebhooksKeyAttemptCount} OF ${maxTaskAttempts}\n\n`); if (retrieveWebhooksKeyAttemptCount == maxTaskAttempts) { throw retrieveWebhooksKeyError; } } } console.info(`\nIFTTT Webhooks Key: ${iftttWebhooksKey}`); } let existingWebhooksBroadLinkAppletIDsAndNames = {}; let allowedWebhooksBroadLinkAppletNamePrefixes = []; if ((optionsPromptsResponse.groupSelection == groupDevicesAndScenes) || (optionsPromptsResponse.groupSelection == groupDevicesOnly)) { allowedWebhooksBroadLinkAppletNamePrefixes = ['Webhooks Event: BroadLink-On', 'Webhooks Event: BroadLink-Off']; } if ((optionsPromptsResponse.groupSelection == groupDevicesAndScenes) || (optionsPromptsResponse.groupSelection == groupScenesOnly)) { allowedWebhooksBroadLinkAppletNamePrefixes.push('Webhooks Event: BroadLink-Scene'); } for (let retrieveExistingWebhooksBroadLinkAppletIDsAndNamesAttemptCount = 1; retrieveExistingWebhooksBroadLinkAppletIDsAndNamesAttemptCount <= maxTaskAttempts; retrieveExistingWebhooksBroadLinkAppletIDsAndNamesAttemptCount ++) { try { let totalBroadLinkAppletsDetected = 0; let existingWebhooksBroadLinkOnAppletsCount = 0; let existingWebhooksBroadLinkOffAppletsCount = 0; let existingWebhooksBroadLinkSceneAppletsCount = 0; existingWebhooksBroadLinkAppletIDsAndNames = {}; await webDriver.get('https://ifttt.com/broadlink'); try { await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox). if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation'); } catch (acceptLeavePageAlertError) { // Ignore any error if there is no Leave Page confirmation. } await check_for_server_error_page(); // First, wait a long time for community Applets to exist within the "discover_services" section, which will always exist. await webDriver.wait(until.elementsLocated(By.xpath('//section[@class="discover_services"]/ul[@class="web-applet-cards"]/li[contains(@class,"my-web-applet-card")]')), longWaitForElementTime); try { // Then, wait a short time for the "My Applets" button to exist and click it to switch to the "My Applets" section. // If no personal Applets exist, this link will not exist and we want to fail quickly in this case (which is why we wait a short time). // Clicking this will set the URL to "https://ifttt.com/broadlink/my_applets" but annoyingly that URL cannot be visited directly (it 404s). await webDriver.wait( until.elementLocated(By.xpath('//div[contains(@class,"discover_service_view")]/span[text()="My Applets"]')), shortWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Clicking My Applets Button'); await thisElement.click(); }); // Finally, wait a long time for personal Applets to exist within the "my_services" section (even though they should already be loaded from the first page load) which was revealed by switching to the "My Applets" section. await webDriver.wait(until.elementsLocated(By.xpath('//section[@class="my_services"]/ul[@class="web-applet-cards"]/li[contains(@class,"my-web-applet-card")]')), longWaitForElementTime); // Next, once we know the page is fully loaded, wait a short time to get the "my_services" Applet titles (so that it will fail quickly if none exist, even though we should have already failed since the "My Applets" button wouldn't exist). await webDriver.wait( until.elementsLocated(By.xpath('//section[@class="my_services"]/ul[@class="web-applet-cards"]/li[contains(@class,"my-web-applet-card")]/a[contains(@class,"applet-card-body")]')), shortWaitForElementTime ).then(async theseElements => { totalBroadLinkAppletsDetected = theseElements.length; if (debugLogging) console.debug(`DEBUG - Detected ${totalBroadLinkAppletsDetected} Total BroadLink Applets - Filtering to Only Webhooks Applets for BroadLink`); for (let thisElementIndex = 0; thisElementIndex < theseElements.length; thisElementIndex ++) { try { let thisAppletWorksWithPermissionsElement = await theseElements[thisElementIndex].findElement(By.xpath('.//div[@class="meta"]/div[@class="works-with"]/ul[@class="permissions"]')); let thisAppletTriggerServiceName = await thisAppletWorksWithPermissionsElement.findElement(By.xpath('.//li[1]/img')).getAttribute('title'); if (thisAppletTriggerServiceName == 'Webhooks') { let thisAppletActionServiceName = await thisAppletWorksWithPermissionsElement.findElement(By.xpath('.//li[2]/img')).getAttribute('title'); if (thisAppletActionServiceName == 'BroadLink') { // Since we're on https://ifttt.com/broadlink and the Trigger Service is Webhooks this is an unnecessary check, but better safe than sorry. let thisBroadLinkAppletName = await theseElements[thisElementIndex].findElement(By.xpath('.//div[contains(@class,"content")]/span[contains(@class,"title")]/span/div/div')).getText(); // "title" class had a space after it at the time of writing, which I don't trust to stay forever, so using contains instead of checking if equals "title ". if (debugLogging) console.debug(`DEBUG - Found Webhooks/BroadLink Applet: ${thisBroadLinkAppletName}`); let thisBroadLinkAppletNameParts = thisBroadLinkAppletName.split('+'); let thisBroadLinkAppletNamePrefixPart = thisBroadLinkAppletNameParts[0]; if ((thisBroadLinkAppletNameParts.length == 2) && allowedWebhooksBroadLinkAppletNamePrefixes.includes(thisBroadLinkAppletNamePrefixPart) && !/\s/g.test(thisBroadLinkAppletNameParts[1])) { let thisAppletURL = await theseElements[thisElementIndex].getAttribute('href'); if (thisAppletURL.includes('/applets/')) { if (thisBroadLinkAppletNamePrefixPart.endsWith('-On')) { existingWebhooksBroadLinkOnAppletsCount ++; } else if (thisBroadLinkAppletNamePrefixPart.endsWith('-Off')) { existingWebhooksBroadLinkOffAppletsCount ++; } else if (thisBroadLinkAppletNamePrefixPart.endsWith('-Scene')) { existingWebhooksBroadLinkSceneAppletsCount ++; } existingWebhooksBroadLinkAppletIDsAndNames[thisAppletURL.split('/applets/')[1].split('-webhooks-event-broadlink-')[0]] = thisBroadLinkAppletName; } } } } } catch (getAppletInfoError) { if (debugLogging) console.debug(`DEBUG ERROR - FAILED TO GET APPLET INFO: ${getAppletInfoError}`); } } }); } catch (getExistingBroadLinkAppletsError) { if (debugLogging) console.debug(`DEBUG ERROR - FAILED TO GET ANY EXISTING APPLETS: ${getExistingBroadLinkAppletsError}`); } if (totalBroadLinkAppletsDetected == 0) { // If we didn't detect any Applets, make sure that the BroadLink Service is connected. try { await webDriver.wait(until.elementLocated(By.xpath('//a[contains(@href,"/broadlink/redirect_to_connect")]')), shortWaitForElementTime); throw '"BroadLink" SERVICE NOT CONNECTED IN IFTTT'; } catch (broadLinkServiceConnectionError) { if (broadLinkServiceConnectionError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT')) { throw broadLinkServiceConnectionError; } // Otherwise, ignore likely error from element not existing. Which means that the BroadLink Service is connected like we want. } } let existingWebhooksBroadLinkTotalAppletsCount = Object.keys(existingWebhooksBroadLinkAppletIDsAndNames).length; let existingWebhooksBroadLinkOnAndOffAndSceneAppletsCount = (existingWebhooksBroadLinkOnAppletsCount + existingWebhooksBroadLinkOffAppletsCount + existingWebhooksBroadLinkSceneAppletsCount); console.info(`\n${existingWebhooksBroadLinkTotalAppletsCount} Existing Webhooks Applet${((existingWebhooksBroadLinkTotalAppletsCount == 1) ? '' : 's')} for BroadLink Detected${(((optionsPromptsResponse.groupSelection != groupDevicesAndScenes) || (existingWebhooksBroadLinkOnAndOffAndSceneAppletsCount > 0)) ? `:\n\t${((optionsPromptsResponse.groupSelection == groupScenesOnly) ? 'CHOSE NOT TO DETECT EXISTING WEBHOOKS APPLETS FOR DEVICES' : `${existingWebhooksBroadLinkOnAppletsCount} Turn Device On Applet${((existingWebhooksBroadLinkOnAppletsCount == 1) ? '' : 's')}\n\t${existingWebhooksBroadLinkOffAppletsCount} Turn Device Off Applet${((existingWebhooksBroadLinkOffAppletsCount == 1) ? '' : 's')}` )}\n\t${((optionsPromptsResponse.groupSelection == groupDevicesOnly) ? 'CHOSE NOT TO DETECT EXISTING WEBHOOKS APPLETS FOR SCENE' : `${existingWebhooksBroadLinkSceneAppletsCount} Scene Applet${((existingWebhooksBroadLinkSceneAppletsCount == 1) ? '' : 's')}` )}` : '' )}`); if (existingWebhooksBroadLinkTotalAppletsCount != existingWebhooksBroadLinkOnAndOffAndSceneAppletsCount) { console.warn(`WARNING: TOTAL EXISTING APPLETS COUNT (${existingWebhooksBroadLinkTotalAppletsCount}) != ON APPLETS + OFF APPLETS + SCENE APPLETS COUNT (${existingWebhooksBroadLinkOnAndOffAndSceneAppletsCount})`); } break; } catch (retrieveExistingWebhooksBroadLinkAppletIDsAndNamesError) { if (retrieveExistingWebhooksBroadLinkAppletIDsAndNamesError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT')) { throw retrieveExistingWebhooksBroadLinkAppletIDsAndNamesError; // Don't keep trying if service isn't connected. } console.error(`\nERROR: ${retrieveExistingWebhooksBroadLinkAppletIDsAndNamesError}`); if (debugLogging) { try { console.debug(`URL=${await webDriver.getCurrentUrl()}`); } catch (getCurrentURLerror) { console.debug('FAILED TO GET CURRENT URL'); } } console.error(`\n\nERROR RETRIEVING EXISTING WEBHOOKS APPLETS FOR BROADLINK - ATTEMPT ${retrieveExistingWebhooksBroadLinkAppletIDsAndNamesAttemptCount} OF ${maxTaskAttempts}\n\n`); if (retrieveExistingWebhooksBroadLinkAppletIDsAndNamesAttemptCount == maxTaskAttempts) { throw retrieveExistingWebhooksBroadLinkAppletIDsAndNamesError; } } } let existingWebhooksBroadLinkAppletNames = Object.values(existingWebhooksBroadLinkAppletIDsAndNames); // Get array of Applet names to be able to easily check if an Applet already exists. let currentBroadLinkDeviceNamesArray = []; let currentBroadLinkSceneNamesArray = []; if ((optionsPromptsResponse.taskSelection == taskCreateApplets) || (optionsPromptsResponse.taskSelection == taskArchiveAppletsNotInBroadLink) || (optionsPromptsResponse.taskSelection == taskOutputSummary)) { for (let retrieveDevicesAndScenesAttemptCount = 1; retrieveDevicesAndScenesAttemptCount <= maxTaskAttempts; retrieveDevicesAndScenesAttemptCount ++) { try { await setup_ifttt_webhooks_broadlink_applet('FakeEventName-ToRetrieveRealDeviceAndSceneNames', (optionsPromptsResponse.groupSelection == groupScenesOnly)); currentBroadLinkDeviceNamesArray = []; if (optionsPromptsResponse.groupSelection != groupScenesOnly) { await webDriver.wait(until.elementLocated(By.xpath('//select[@name="fields[deviceinfo]"]/option[text()!="Loading…"]')), longWaitForElementTime); // Wait for devices to be loaded. await webDriver.wait( until.elementsLocated(By.xpath('//select[@name="fields[deviceinfo]"]/option')), longWaitForElementTime // Now get all the devices. ).then(async theseElements => { if (debugLogging) console.debug('DEBUG - Retrieving BroadLink Device Names'); for (let thisElementIndex = 0; thisElementIndex < theseElements.length; thisElementIndex ++) { currentBroadLinkDeviceNamesArray.push(await theseElements[thisElementIndex].getText()); } }); if ((currentBroadLinkDeviceNamesArray.length == 1) && (currentBroadLinkDeviceNamesArray[0] == 'No options available')) currentBroadLinkDeviceNamesArray = []; if (currentBroadLinkDeviceNamesArray.length > 1) { currentBroadLinkDeviceNamesArray.sort(function(thisDeviceName, thatDeviceName) { return thisDeviceName.localeCompare(thatDeviceName); }); } console.info(`\n${currentBroadLinkDeviceNamesArray.length} BroadLink Device${((currentBroadLinkDeviceNamesArray.length == 1) ? '' : 's')} Detected`); if (optionsPromptsResponse.groupSelection != groupDevicesOnly) { // Do not keep clicking the "Back" button until the button no longer exists (like we do with other submits) so that we don't accidentally go back multiple pages. await webDriver.wait( until.elementLocated(By.xpath('//a[@title="Back"]')), longWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Clicking Back Button'); await thisElement.click(); }); await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Choose an action"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. await click_button_until_no_longer_exists(By.xpath('//a[@title="Choose action: Scene control"]')); await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Complete action fields" or text()="Connect service"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. try { await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Complete action fields"]')), shortWaitForElementTime); } catch (confirmServiceConnectionError) { throw '"BroadLink" SERVICE NOT CONNECTED IN IFTTT'; } } } else { console.info('\nCHOSE NOT TO DETECT DEVICES IN BROADLINK'); } currentBroadLinkSceneNamesArray = []; if (optionsPromptsResponse.groupSelection != groupDevicesOnly) { await webDriver.wait(until.elementLocated(By.xpath('//select[@name="fields[deviceinfo]"]/option[text()!="Loading…"]')), longWaitForElementTime); // Wait for scenes to be loaded. await webDriver.wait( until.elementsLocated(By.xpath('//select[@name="fields[deviceinfo]"]/option')), longWaitForElementTime // Now get all the scenes. ).then(async theseElements => { if (debugLogging) console.debug('DEBUG - Retrieving BroadLink Scene Names'); for (let thisElementIndex = 0; thisElementIndex < theseElements.length; thisElementIndex ++) { currentBroadLinkSceneNamesArray.push(await theseElements[thisElementIndex].getText()); } }); if ((currentBroadLinkSceneNamesArray.length == 1) && (currentBroadLinkSceneNamesArray[0] == 'No options available')) currentBroadLinkSceneNamesArray = []; if (currentBroadLinkSceneNamesArray.length > 1) { currentBroadLinkSceneNamesArray.sort(function(thisSceneName, thatSceneName) { return thisSceneName.localeCompare(thatSceneName); }); } console.info(`\n${currentBroadLinkSceneNamesArray.length} BroadLink Scene${((currentBroadLinkSceneNamesArray.length == 1) ? '' : 's')} Detected`); } else { console.info('\nCHOSE NOT TO DETECT SCENES IN BROADLINK'); } break; } catch (retrieveDevicesAndScenesError) { if (retrieveDevicesAndScenesError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT') || retrieveDevicesAndScenesError.toString().startsWith('MAXIMUM ALLOWED APPLETS CREATED')) { throw retrieveDevicesAndScenesError; // Don't keep trying if service isn't connected or maximum allowed Applets created (IFTTT Pro required). } console.error(`\nERROR: ${retrieveDevicesAndScenesError}`); if (debugLogging) { try { console.debug(`URL=${await webDriver.getCurrentUrl()}`); } catch (getCurrentURLerror) { console.debug('FAILED TO GET CURRENT URL'); } } console.error(`\n\nERROR RETRIEVING BROADLINK DEVICES AND SCENES - ATTEMPT ${retrieveDevicesAndScenesAttemptCount} OF ${maxTaskAttempts}\n\n`); if (retrieveDevicesAndScenesAttemptCount == maxTaskAttempts) { throw retrieveDevicesAndScenesError; } } } } if (optionsPromptsResponse.taskSelection == taskCreateApplets) { let currentBroadLinkDevicesAndScenesArrays = [currentBroadLinkDeviceNamesArray, currentBroadLinkSceneNamesArray]; for (let thisArrayIndex = 0; thisArrayIndex < currentBroadLinkDevicesAndScenesArrays.length; thisArrayIndex ++) { let thisDevicesOrScenesArray = currentBroadLinkDevicesAndScenesArrays[thisArrayIndex]; let isScene = (thisArrayIndex == 1); if (thisDevicesOrScenesArray.length > 0) console.info(`\n\nCreating Webhooks Applet${((thisDevicesOrScenesArray.length == 1) ? '' : 's')} for ${thisDevicesOrScenesArray.length} BroadLink ${isScene ? 'scene' : 'device'}${((thisDevicesOrScenesArray.length == 1) ? '' : 's')}...`); for (let thisDeviceOrSceneIndex = 0; thisDeviceOrSceneIndex < thisDevicesOrScenesArray.length; thisDeviceOrSceneIndex ++) { let thisDevicOrSceneName = thisDevicesOrScenesArray[thisDeviceOrSceneIndex]; let statesArray = (isScene ? ['Scene'] : ['On', 'Off']); for (let thisStateIndex = 0; thisStateIndex < statesArray.length; thisStateIndex ++) { let thisStateName = statesArray[thisStateIndex]; if (isScene) { console.info(`\nSCENE ${thisDeviceOrSceneIndex + 1} OF ${thisDevicesOrScenesArray.length}`); console.info(`\tScene Name: ${thisDevicOrSceneName}`); } else { console.info(`\nDEVICE ${thisDeviceOrSceneIndex + 1} OF ${thisDevicesOrScenesArray.length} - ${thisStateName} STATE`); console.info(`\tDevice Name: ${thisDevicOrSceneName}`); } let thisWebhooksEventName = `BroadLink-${thisStateName}+${thisDevicOrSceneName.replace(/\s/g, '_')}`; let correctOriginalAppletTitle = `If Maker Event "${thisWebhooksEventName}", then ${(isScene ? `the ${thisDevicOrSceneName} will turn on` : `turn ${thisStateName.toLowerCase()} ${thisDevicOrSceneName}`)}`; let desiredAppletTitle = `Webhooks Event: ${thisWebhooksEventName}`; if (existingWebhooksBroadLinkAppletNames.includes(desiredAppletTitle)) { console.info(`SKIPPING: WEBHOOKS APPLET WITH NAME "${desiredAppletTitle}" ALREADY EXISTS`); continue; } for (let appletSetupAttemptCount = 1; appletSetupAttemptCount <= maxTaskAttempts; appletSetupAttemptCount ++) { // If any error happen within the Applet setup phase, we can just start over and try again because the Applet has not been created yet. try { await setup_ifttt_webhooks_broadlink_applet(thisWebhooksEventName, isScene); await webDriver.wait( until.elementLocated(By.xpath(`//select[@name="fields[deviceinfo]"]/option[text()="${thisDevicOrSceneName}"]`)), longWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug(`DEBUG - Clicking ${isScene ? 'Scene' : 'Device'} Name Option`); await thisElement.click(); }); if (!isScene) { await webDriver.wait( until.elementLocated(By.xpath('//select[@name="fields[PowerControl_ChangePowerState_string]"]/option[2]')), longWaitForElementTime // Always wait for device states to get loaded. ).then(async thisElement => { if (thisStateName == 'Off') { // But we only need to click to set the state if we want to change it to "Off". if (debugLogging) console.debug('DEBUG - Clicking Device State Off Option'); await thisElement.click(); } }); } await click_button_until_no_longer_exists(By.xpath('//input[@value="Create action" or @value="Creating action..."]')); await webDriver.wait(until.elementLocated(By.xpath(`//span[text()="${isScene ? 'Scene control' : 'Turn device on or off'}"]`)), longWaitForElementTime); // Make sure correct page is loaded before continuing. await click_button_until_no_longer_exists(By.xpath('//button[text()="Continue"]')); await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Review and finish"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. let originalAppletTitle = 'FAILED_TO_RETRIEVE_ORIGINAL_APPLET_TITLE'; await webDriver.wait( until.elementLocated(By.xpath('//textarea[@name="description"]')), longWaitForElementTime ).then(async thisElement => { originalAppletTitle = await thisElement.getText(); if (originalAppletTitle != correctOriginalAppletTitle) { throw `ORIGINAL APPLET TITLE NOT CORRECT ("${originalAppletTitle}" != "${correctOriginalAppletTitle}")`; } await thisElement.clear(); await thisElement.sendKeys(Key.ENTER, Key.BACK_SPACE); // Send Enter and then Backspace keys be sure the contents get updated, because the character count doesn't always get updated when only using clear(). await thisElement.clear(); // clear() again after that to be sure the title field is empty. await thisElement.sendKeys(desiredAppletTitle); console.info(`\tOriginal Applet Title: ${originalAppletTitle}`); }); // Applets notifications are disabled by default now, but still check just in case. await webDriver.wait(until.elementLocated(By.xpath('//div[contains(@class,"preview__notification")]/div[@class="switch"]/div[@class="switch-ui disabled"]')), longWaitForElementTime); break; } catch (appletSetupError) { if (appletSetupError.toString().endsWith('SERVICE NOT CONNECTED IN IFTTT') || appletSetupError.toString().startsWith('MAXIMUM ALLOWED APPLETS CREATED')) { throw appletSetupError; // Don't keep trying if service isn't connected or maximum allowed Applets created (IFTTT Pro required). } console.error(`\nERROR: ${appletSetupError}`); if (debugLogging) { try { console.debug(`URL=${await webDriver.getCurrentUrl()}`); } catch (getCurrentURLerror) { console.debug('FAILED TO GET CURRENT URL'); } } console.error(`\n\nERROR SETTING UP WEBHOOKS APPLET FOR "${thisWebhooksEventName}" - ATTEMPT ${appletSetupAttemptCount} OF ${maxTaskAttempts}\n\n`); if (appletSetupAttemptCount == maxTaskAttempts) { throw appletSetupError; } } } for (let finishAppletAttemptCount = 1; finishAppletAttemptCount <= maxTaskAttempts; finishAppletAttemptCount ++) { // Do not keep clicking the "Finish" button until the correct URL is loaded (like we do with other submits) so that we don't accidentally create multiple instances of the same Applet. // But, do retry this part maxTaskAttempts times. If there is an issue the large delay between click attempts should help not make duplicates and only catch real issues. try { let currentURL = await webDriver.getCurrentUrl(); if (!currentURL.startsWith('https://ifttt.com/applets/')) { await webDriver.wait( until.elementLocated(By.xpath('//button[text()="Finish"]')), longWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Clicking Finish Applet Button'); await thisElement.click(); }); // But, do keep checking for the "Finish" buttons existance while waiting for the correct URL so we can exit this loop if it's been too long. let finishButtonExistsCount = 0; let finishButtonNoLongerExistsCount = 0; while (!currentURL.startsWith('https://ifttt.com/applets/')) { try { await webDriver.wait(until.elementLocated(By.xpath('//button[text()="Finish" or text()="Finishing..."]')), shortWaitForElementTime); finishButtonExistsCount ++; if (debugLogging) console.debug(`DEBUG - Finish Button Still Exists (${finishButtonExistsCount}) - URL=${currentURL}`); if (finishButtonExistsCount >= maxButtonClicksCount) { if (debugLogging) console.warn('DEBUG WARNING - FINISH BUTTON HAS EXISTED FOR TOO LONG WITHOUT URL GETTING UPDATED - EXITING STUCK LOOP'); break; } } catch (finishButtonExistsError) { finishButtonNoLongerExistsCount ++; if (debugLogging) console.debug(`DEBUG - FINISH BUTTON NO LONGER EXISTS (${finishButtonNoLongerExistsCount}) - URL=${currentURL}`); if (finishButtonNoLongerExistsCount >= maxIterationsOnPageAfterButtonNoLongerExists) { if (debugLogging) console.warn('DEBUG WARNING - FINISH BUTTON HAS NOT EXISTED FOR TOO LONG WITHOUT URL GETTING UPDATED - EXITING STUCK LOOP'); break; } } currentURL = await webDriver.getCurrentUrl(); await webDriver.sleep(waitForNextPageSleepInLoopTime); } } currentURL = await webDriver.getCurrentUrl(); if (currentURL.startsWith('https://ifttt.com/applets/')) { console.info(`\tEdit Applet URL: ${currentURL}/edit`); let finalAppletTitle = 'FAILED_TO_RETRIEVE_FINAL_APPLET_TITLE'; let failedToRetrieveFinalAppletTitleCount = 0; while (finalAppletTitle == 'FAILED_TO_RETRIEVE_FINAL_APPLET_TITLE') { try { await check_for_server_error_page(); } catch (serverError) { if (checkForServerError.toString().endsWith('NEED TO RELOAD PAGE')) { console.error(`\n\nERROR: ${checkForServerError}\n\n`); await webDriver.navigate().refresh(); } } try { await webDriver.wait( until.elementLocated(By.css('h1.connection-title')), ((failedToRetrieveFinalAppletTitleCount == 0) ? longWaitForElementTime : shortWaitForElementTime) ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Got Final Applet Title Element'); finalAppletTitle = await thisElement.getText(); }); } catch (retrieveFinalAppletTitleError) { failedToRetrieveFinalAppletTitleCount ++; // Retrieving Final Applet Title can timeout when the web browser window isn't visible, so alert the user. console.error(`ERROR RETRIEVING FINAL APPLET TITLE (${failedToRetrieveFinalAppletTitleCount}) - MAKE SURE WEB BROWSER WINDOW IS VISIBLE AND UNINTERRUPTED`); if (failedToRetrieveFinalAppletTitleCount >= maxIterationsOnPageAfterButtonNoLongerExists) { if (debugLogging) console.warn('DEBUG WARNING - FAILED TO RETRIEVE FINAL APPLET TITLE TOO MANY TIMES - EXITING STUCK LOOP'); break; } } } if (finalAppletTitle != desiredAppletTitle) { throw `FINAL APPLET TITLE NOT CORRECT ("${finalAppletTitle}" != "${desiredAppletTitle}")`; } console.info(`\tFinal Applet Title: ${finalAppletTitle}`); console.info(`\tTrigger Applet URL: https://maker.ifttt.com/trigger/${thisWebhooksEventName}/with/key/${iftttWebhooksKey}`); break; } else { throw `FINAL APPLET URL NOT CORRECT "${thisWebhooksEventName}" - URL=${currentURL}`; } } catch (finishAppletError) { console.error(`\nERROR: ${finishAppletError}`); if (debugLogging) { try { console.debug(`URL=${await webDriver.getCurrentUrl()}`); } catch (getCurrentURLerror) { console.debug('FAILED TO GET CURRENT URL'); } } console.error(`\n\nERROR FINISHING WEBHOOKS APPLET FOR "${thisWebhooksEventName}" - ATTEMPT ${finishAppletAttemptCount} OF ${maxTaskAttempts}\n\n`); if (finishAppletAttemptCount == maxTaskAttempts) { throw finishAppletError; } } } } } } } else if ((optionsPromptsResponse.taskSelection == taskArchiveApplets) || (optionsPromptsResponse.taskSelection == taskArchiveAppletsNotInBroadLink) || (optionsPromptsResponse.taskSelection == taskOpenEditAppletURLs)) { let thisAppletIndex = 0; for (let thisAppletID in existingWebhooksBroadLinkAppletIDsAndNames) { let thisAppletName = existingWebhooksBroadLinkAppletIDsAndNames[thisAppletID]; let isScene = thisAppletName.startsWith('Webhooks Event: BroadLink-Scene+'); if ((optionsPromptsResponse.groupSelection == groupDevicesAndScenes) || (isScene && (optionsPromptsResponse.groupSelection == groupScenesOnly)) || (!isScene && (optionsPromptsResponse.groupSelection == groupDevicesOnly))) { if (thisAppletIndex == 0) console.log('\n'); // Just for two line breaks before the first output for this task. thisAppletIndex ++; if (optionsPromptsResponse.taskSelection == taskOpenEditAppletURLs) { let thisEditAppletURL = `https://ifttt.com/applets/${thisAppletID}/edit`; try { exec(`${((process.platform == 'darwin') ? 'open' : ((process.platform == 'win32') ? 'start' : 'xdg-open'))} ${thisEditAppletURL}`); console.info(`${thisAppletIndex} - Opening Edit Webhooks Applet for ${isScene ? 'Scene' : 'Device'} URL: ${thisEditAppletURL} (${thisAppletName})`); } catch (openEditAppletURLerror) { console.error(`${thisAppletIndex} - ERROR OPENING EDIT WEBHOOKS APPLET FOR ${isScene ? 'SCENE' : 'DEVICE'} URL: ${thisEditAppletURL} (${thisAppletName})`); console.error(`ERROR: ${openEditAppletURLerror}\n`); } } else { if (optionsPromptsResponse.taskSelection == taskArchiveAppletsNotInBroadLink) { let thisDeviceOrSceneName = thisAppletName.split('+')[1].replace(/_/g, ' '); if ((!isScene && currentBroadLinkDeviceNamesArray.includes(thisDeviceOrSceneName)) || (isScene && currentBroadLinkSceneNamesArray.includes(thisDeviceOrSceneName))) { console.info(`${thisAppletIndex} - Not Archiving Webhooks Applet for ${isScene ? 'Scene' : 'Device'} - STILL EXISTS IN BROADLINK: ${thisDeviceOrSceneName} (${thisAppletName})`); continue; } } let thisAppletURL = `https://ifttt.com/applets/${thisAppletID}`; for (let archiveAppletAttemptCount = 1; archiveAppletAttemptCount <= maxTaskAttempts; archiveAppletAttemptCount ++) { try { await webDriver.get(thisAppletURL); try { await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox). if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation'); } catch (acceptLeavePageAlertError) { // Ignore any error if there is no Leave Page confirmation. } await check_for_server_error_page(); await webDriver.wait( until.elementLocated(By.xpath(`//h1[text()="${thisAppletName}"]|//h1[text()="Archive"]|//h1[contains(text(),"The requested page or file does not exist.")]`)), longWaitForElementTime ).then(async thisElement => { if ((await thisElement.getText()) == thisAppletName) { try { // Don't wait very long since H1 already exists and Archive button may not exist at all. // The Archive button should only not exist when visiting an Edit Applet URL which has already been archived. // But, that should not really be possible since this code is getting the Edit Applet URLs from what is currently in IFTTT. // This setup is left over from when this code got the Edit Applet URLs from a file, which weren't guaranteed to not already have been archived. // Kept this setup in place to be extra safe, since it could still happen if someone archives an Applet manually after this archive process was started. await webDriver.wait( until.elementLocated(By.linkText('Archive')), shortWaitForElementTime ).then(async thatElement => { await thatElement.click(); await webDriver.switchTo().alert().accept(); let currentURL = await webDriver.getCurrentUrl(); while ((currentURL != 'https://ifttt.com/home') && (currentURL != 'https://ifttt.com')) { // Could end up at either of these URLs after archiving an applet. currentURL = await webDriver.getCurrentUrl(); await webDriver.sleep(waitForNextPageSleepInLoopTime); } console.info(`${thisAppletIndex} - Archived Webhooks Applet for ${isScene ? 'Scene' : 'Device'}: ${thisAppletURL} (${thisAppletName})`); }); } catch (noArchiveButtonError) { console.info(`${thisAppletIndex} - Webhooks Applet for ${isScene ? 'Scene' : 'Device'} Already Archived - NO ARCHIVE BUTTON: ${thisAppletURL} (${thisAppletName})`); } } else { console.info(`${thisAppletIndex} - Webhooks Applet for ${isScene ? 'Scene' : 'Device'} Already Archived - DOES NOT EXIST: ${thisAppletURL} (${thisAppletName})`); } }); break; } catch (archiveAppletError) { console.error(`${thisAppletIndex} - ERROR ARCHIVING WEBHOOKS APPLET FOR ${isScene ? 'SCENE' : 'DEVICE'}: ${thisAppletURL} (${thisAppletName})`); console.error(`\nERROR: ${archiveAppletError}`); if (debugLogging) { try { console.debug(`URL=${await webDriver.getCurrentUrl()}`); } catch (getCurrentURLerror) { console.debug('FAILED TO GET CURRENT URL'); } } console.error(`\n\nERROR ARCHIVING WEBHOOKS APPLET - ATTEMPT ${archiveAppletAttemptCount} OF ${maxTaskAttempts}\n\n`); if (archiveAppletAttemptCount == maxTaskAttempts) { throw archiveAppletError; } } } } } } } else if (optionsPromptsResponse.taskSelection == taskGenerateHomebridgeIFTTTconfig) { let homebridgeIftttConfigPlatformDict = { platform: 'IFTTT', name: 'IFTTT', makerkey: iftttWebhooksKey, accessories: [] }; let homebridgeIftttConfigAccessoriesArray = []; for (let thisAppletNameIndex = 0; thisAppletNameIndex < existingWebhooksBroadLinkAppletNames.length; thisAppletNameIndex ++) { let thisAppletName = existingWebhooksBroadLinkAppletNames[thisAppletNameIndex]; let isScene = thisAppletName.startsWith('Webhooks Event: BroadLink-Scene+'); if ((optionsPromptsResponse.groupSelection == groupDevicesAndScenes) || (isScene && (optionsPromptsResponse.groupSelection == groupScenesOnly)) || (!isScene && (optionsPromptsResponse.groupSelection == groupDevicesOnly))) { let thisWebhooksEventName = thisAppletName.split('Webhooks Event: ')[1]; let thisWebhooksEventNameParts = thisWebhooksEventName.split('+'); let thisDeviceOrSceneName = (isScene ? 'Scene - ' : '') + thisWebhooksEventNameParts[1].replace(/_/g, ' '); let thisWebhooksEventState = thisWebhooksEventNameParts[0].split('-')[1]; let thisTriggerKey = `trigger${(isScene ? '' : thisWebhooksEventState)}`; let addedThisWebhooksEventNameToExistingAccessory = false; for (let thisAccessoryIndex = (homebridgeIftttConfigAccessoriesArray.length - 1); thisAccessoryIndex >= 0; thisAccessoryIndex --) { if (homebridgeIftttConfigAccessoriesArray[thisAccessoryIndex].name == thisDeviceOrSceneName) { homebridgeIftttConfigAccessoriesArray[thisAccessoryIndex].buttons[0][thisTriggerKey] = thisWebhooksEventName; addedThisWebhooksEventNameToExistingAccessory = true; break; } } if (!addedThisWebhooksEventNameToExistingAccessory) { homebridgeIftttConfigAccessoriesArray.push({ name: thisDeviceOrSceneName, buttons: [{ [thisTriggerKey]: thisWebhooksEventName }] }); } } } if (homebridgeIftttConfigAccessoriesArray.length > 0) { homebridgeIftttConfigAccessoriesArray.sort(function(thisAccessory, thatAccessory) { // Sort by names alphabetically with Scenes always on the bottom. Is there a nicer way to correcty sort Scenes onto the bottom? let thisAccessoryNameToSort = thisAccessory.name; if (thisAccessoryNameToSort.startsWith('Scene - ')) thisAccessoryNameToSort = `zzzzzzzzzz${thisAccessoryNameToSort}`; let thatAccessoryNameToSort = thatAccessory.name; if (thatAccessoryNameToSort.startsWith('Scene - ')) thatAccessoryNameToSort = `zzzzzzzzzz${thatAccessoryNameToSort}`; return thisAccessoryNameToSort.localeCompare(thatAccessoryNameToSort); }); homebridgeIftttConfigPlatformDict.accessories = homebridgeIftttConfigAccessoriesArray; } let homebridgeIftttConfigPlatformString = JSON.stringify(homebridgeIftttConfigPlatformDict, null, 4); console.log(`\n\n${homebridgeIftttConfigPlatformString}\n\n`); let saveFilePromptResponse = await prompts({ type: 'toggle', name: 'saveFile', message: 'Would you like to save the configuration displayed above onto your Desktop?', initial: false, active: 'Save File to Desktop', inactive: "Don't Save File" }); if ((Object.keys(saveFilePromptResponse).length == 1) && (saveFilePromptResponse.saveFile == true)) { let desktopPath = pathJoin(homeDir, 'Desktop'); if ((process.platform == 'win32') && !existsSync(desktopPath)) { desktopPath = pathJoin(homeDir, 'OneDrive', 'Desktop'); } let saveFileDate = new Date(); let saveFilePath = pathJoin(desktopPath, sanitizeFilename(`broadlink-webhooks Configuration for homebridge-ifttt (${optionsPromptsResponse.groupSelection}) ${sanitizeFilename(saveFileDate.toLocaleDateString('en-CA'), {replacement: '-'})} at ${sanitizeFilename(saveFileDate.toLocaleTimeString('en-US'), {replacement: '.'})}.json`)); try { writeFileSync(saveFilePath, homebridgeIftttConfigPlatformString); console.info(`\nhomebridge-ifttt Configuration File Saved: ${saveFilePath}`); } catch (writeFileError) { console.error(`\nERROR SAVING HOMEBRIDGE-IFTTT CONFIGURATION FILE: ${saveFilePath}\n\nINSTEAD, YOU CAN COPY-AND-PASTE THE CONFIGURATION DISPLAYED ABOVE\n\n${writeFileError}`); } } else { console.info(`\nCHOSE NOT TO SAVE HOMEBRIDGE-IFTTT CONFIGURATION FILE\nBut, you can still copy-and-paste the configuration displayed above.`); } } else if (optionsPromptsResponse.taskSelection == taskGenerateHomebridgeHTTPconfig) { let homebridgeHttpConfigAccessoriesArray = []; for (let thisAppletNameIndex = 0; thisAppletNameIndex < existingWebhooksBroadLinkAppletNames.length; thisAppletNameIndex ++) { let thisAppletName = existingWebhooksBroadLinkAppletNames[thisAppletNameIndex]; let isScene = thisAppletName.startsWith('Webhooks Event: BroadLink-Scene+'); if ((optionsPromptsResponse.groupSelection == groupDevicesAndScenes) || (isScene && (optionsPromptsResponse.groupSelection == groupScenesOnly)) || (!isScene && (optionsPromptsResponse.groupSelection == groupDevicesOnly))) { let thisWebhooksEventName = thisAppletName.split('Webhooks Event: ')[1]; let thisWebhooksEventNameParts = thisWebhooksEventName.split('+'); let thisDeviceOrSceneName = (isScene ? 'Scene - ' : '') + thisWebhooksEventNameParts[1].replace(/_/g, ' '); let thisWebhooksEventState = thisWebhooksEventNameParts[0].split('-')[1]; let thisStateKey = `${(isScene ? 'on' : thisWebhooksEventState.toLowerCase())}Url`; let addedThisWebhooksEventNameToExistingAccessory = false; for (let thisAccessoryIndex = (homebridgeHttpConfigAccessoriesArray.length - 1); thisAccessoryIndex >= 0; thisAccessoryIndex --) { if (homebridgeHttpConfigAccessoriesArray[thisAccessoryIndex].name == thisDeviceOrSceneName) { homebridgeHttpConfigAccessoriesArray[thisAccessoryIndex][thisStateKey] = `https://maker.ifttt.com/trigger/${thisWebhooksEventName}/with/key/${iftttWebhooksKey}`; addedThisWebhooksEventNameToExistingAccessory = true; break; } } if (!addedThisWebhooksEventNameToExistingAccessory) { homebridgeHttpConfigAccessoriesArray.push({ accessory: 'HTTP-SWITCH', name: thisDeviceOrSceneName, switchType: (isScene ? 'stateless' : 'toggle'), [thisStateKey]: `https://maker.ifttt.com/trigger/${thisWebhooksEventName}/with/key/${iftttWebhooksKey}` }); } } } if (homebridgeHttpConfigAccessoriesArray.length > 0) { homebridgeHttpConfigAccessoriesArray.sort(function(thisAccessory, thatAccessory) { // Sort by names alphabetically with Scenes always on the bottom. Is there a nicer way to correcty sort Scenes onto the bottom? let thisAccessoryNameToSort = thisAccessory.name; if (thisAccessoryNameToSort.startsWith('Scene - ')) thisAccessoryNameToSort = `zzzzzzzzzz${thisAccessoryNameToSort}`; let thatAccessoryNameToSort = thatAccessory.name; if (thatAccessoryNameToSort.startsWith('Scene - ')) thatAccessoryNameToSort = `zzzzzzzzzz${thatAccessoryNameToSort}`; return thisAccessoryNameToSort.localeCompare(thatAccessoryNameToSort); }); } let homebridgeHttpConfigAccessoriesString = JSON.stringify(homebridgeHttpConfigAccessoriesArray, null, 4); console.log(`\n\n${homebridgeHttpConfigAccessoriesString}\n\n`); let saveFilePromptResponse = await prompts({ type: 'toggle', name: 'saveFile', message: 'Would you like to save the configuration displayed above onto your Desktop?', initial: false, active: 'Save File to Desktop', inactive: "Don't Save File" }); if ((Object.keys(saveFilePromptResponse).length == 1) && (saveFilePromptResponse.saveFile == true)) { let desktopPath = pathJoin(homeDir, 'Desktop'); if ((process.platform == 'win32') && !existsSync(desktopPath)) { desktopPath = pathJoin(homeDir, 'OneDrive', 'Desktop'); } let saveFileDate = new Date(); let saveFilePath = pathJoin(desktopPath, sanitizeFilename(`broadlink-webhooks Configuration for homebridge-http-switch (${optionsPromptsResponse.groupSelection}) ${sanitizeFilename(saveFileDate.toLocaleDateString('en-CA'), {replacement: '-'})} at ${sanitizeFilename(saveFileDate.toLocaleTimeString('en-US'), {replacement: '.'})}.json`)); try { writeFileSync(saveFilePath, homebridgeHttpConfigAccessoriesString); console.info(`\nhomebridge-http-switch Configuration File Saved: ${saveFilePath}`); } catch (writeFileError) { console.error(`\nERROR SAVING HOMEBRIDGE-HTTP-SWITCH CONFIGURATION FILE: ${saveFilePath}\n\nINSTEAD, YOU CAN COPY-AND-PASTE THE CONFIGURATION DISPLAYED ABOVE\n\n${writeFileError}`); } } else { console.info(`\nCHOSE NOT TO SAVE HOMEBRIDGE-HTTP-SWITCH CONFIGURATION FILE\nBut, you can still copy-and-paste the configuration displayed above.`); } } else if (optionsPromptsResponse.taskSelection == taskGenerateJSON) { let jsonDetails = {}; if ((optionsPromptsResponse.groupSelection == groupDevicesAndScenes) || (optionsPromptsResponse.groupSelection == groupDevicesOnly)) { jsonDetails.webhooksBroadLinkOnApplets = []; jsonDetails.webhooksBroadLinkOffApplets = []; } if ((optionsPromptsResponse.groupSelection == groupDevicesAndScenes) || (optionsPromptsResponse.groupSelection == groupScenesOnly)) { jsonDetails.webhooksBroadLinkSceneApplets = []; } for (let thisAppletID in existingWebhooksBroadLinkAppletIDsAndNames) { let thisAppletName = existingWebhooksBroadLinkAppletIDsAndNames[thisAppletID]; let isScene = thisAppletName.startsWith('Webhooks Event: BroadLink-Scene+'); if ((optionsPromptsResponse.groupSelection == groupDevicesAndScenes) || (isScene && (optionsPromptsResponse.groupSelection == groupScenesOnly)) || (!isScene && (optionsPromptsResponse.groupSelection == groupDevicesOnly))) { let thisWebhooksEventName = thisAppletName.split('Webhooks Event: ')[1]; let thisAppletDetails = { name: thisAppletName.split('+')[1].replace(/_/g, ' '), appletID: thisAppletID, appletTitle: thisAppletName, webhooksEventName: thisWebhooksEventName, triggerAppletURL: `https://maker.ifttt.com/trigger/${thisWebhooksEventName}/with/key/${iftttWebhooksKey}`, editAppletURL: `https://ifttt.com/applets/${thisAppletID}/edit` }; if (isScene) { jsonDetails.webhooksBroadLinkSceneApplets.push(thisAppletDetails); } else { if (thisWebhooksEventName.startsWith('BroadLink-On+')) { jsonDetails.webhooksBroadLinkOnApplets.push(thisAppletDetails); } else { jsonDetails.webhooksBroadLinkOffApplets.push(thisAppletDetails); } } } } for (let thisAppletGroup in jsonDetails) { jsonDetails[thisAppletGroup].sort(function(thisAppletDetails, thatAppletDetails) { return thisAppletDetails.name.localeCompare(thatAppletDetails.name); }); } let jsonDetailsString = JSON.stringify(jsonDetails, null, 4); console.log(`\n\n${jsonDetailsString}\n\n`); let saveFilePromptResponse = await prompts({ type: 'toggle', name: 'saveFile', message: 'Would you like to save the JSON displayed above onto your Desktop?', initial: false, active: 'Save File to Desktop', inactive: "Don't Save File" }); if ((Object.keys(saveFilePromptResponse).length == 1) && (saveFilePromptResponse.saveFile == true)) { let desktopPath = pathJoin(homeDir, 'Desktop'); if ((process.platform == 'win32') && !existsSync(desktopPath)) { desktopPath = pathJoin(homeDir, 'OneDrive', 'Desktop'); } let saveFileDate = new Date(); let saveFilePath = pathJoin(desktopPath, sanitizeFilename(`broadlink-webhooks JSON Details (${optionsPromptsResponse.groupSelection}) ${sanitizeFilename(saveFileDate.toLocaleDateString('en-CA'), {replacement: '-'})} at ${sanitizeFilename(saveFileDate.toLocaleTimeString('en-US'), {replacement: '.'})}.json`)); try { writeFileSync(saveFilePath, jsonDetailsString); console.info(`\nJSON Details File Saved: ${saveFilePath}`); } catch (writeFileError) { console.error(`\nERROR SAVING JSON DETAILS FILE: ${saveFilePath}\n\nINSTEAD, YOU CAN COPY-AND-PASTE THE JSON DISPLAYED ABOVE\n\n${writeFileError}`) } } else { console.info(`\nCHOSE NOT TO SAVE JSON DETAILS FILE\nBut, you can still copy-and-paste the JSON displayed above.`); } } let endTime = new Date(); let runTimeMilliseconds = (endTime - startTime); let runTimeMinutes = Math.floor(runTimeMilliseconds / 60000); let runTimeSeconds = ((runTimeMilliseconds % 60000) / 1000).toFixed(0); if (runTimeSeconds == 60) { runTimeMinutes ++; runTimeSeconds = 0; } let runTimeDurationString = ''; if (runTimeMinutes > 0) runTimeDurationString += `${runTimeMinutes} MINUTE${(runTimeMinutes == 1) ? '' : 'S'}`; if (runTimeSeconds > 0) { if (runTimeDurationString != '') runTimeDurationString += ' '; runTimeDurationString += `${runTimeSeconds} SECOND${(runTimeSeconds == 1) ? '' : 'S'}`; } if (runTimeDurationString != '') runTimeDurationString = ` IN ${runTimeDurationString}`; console.info(`\n\nFINISHED "${optionsPromptsResponse.taskSelection}" TASK WITH "${optionsPromptsResponse.groupSelection}"${runTimeDurationString} ON ${endTime.toLocaleString().replace(', ', ' AT ')}\n\n`); try { if (!browserToAutomate.endsWith('-headless') && ((await webDriver.getCurrentUrl()) != 'https://ifttt.com/broadlink')) { await webDriver.get('https://ifttt.com/broadlink'); try { await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox). if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation'); } catch (acceptLeavePageAlertError) { // Ignore any error if there is no Leave Page confirmation. } await check_for_server_error_page(); await webDriver.wait(until.elementsLocated(By.xpath('//section[@class="discover_services"]/ul[@class="web-applet-cards"]/li[contains(@class,"my-web-applet-card")]')), longWaitForElementTime); await webDriver.wait( until.elementLocated(By.xpath('//div[contains(@class,"discover_service_view")]/span[text()="My Applets"]')), shortWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Clicking My Applets Button'); await thisElement.click(); }); } } catch (resetToBroadLinkAppletsPageError) { // Ignore any error from trying to load BroadLink Applets } } } catch (runtimeError) { if (runtimeError.toString() == 'USER QUIT') { userQuit = true; console.log(''); // Just for a line break before the next Terminal prompt. } else if (runtimeError.toString().includes('geckodriver executable could not be found') || runtimeError.toString().includes('ChromeDriver could not be found')) { let errorIsForFirefox = runtimeError.toString().includes('geckodriver'); let webDriverDownloadURL = (errorIsForFirefox ? 'https://github.com/mozilla/geckodriver/releases/' : 'https://chromedriver.chromium.org/downloads'); let webDriverExecutableName = (errorIsForFirefox ? 'geckodriver' : 'chromedriver') + ((process.platform == 'win32') ? '.exe' : ''); let webDriverName = `${errorIsForFirefox ? 'Firefox' : 'Chrome'} WebDriver executable (${webDriverExecutableName})`; let installFolderPaths = ((process.platform == 'darwin') ? ['/usr/local/bin/'] : ((process.platform == 'win32') ? ['C:\\Windows\\', 'C:\\Windows\\System32\\'] : [`${homeDir}/.local/bin/`, '/usr/local/bin/', '/usr/bin/'] ) ); console.error(`\n\nERROR: ${errorIsForFirefox ? 'FIREFOX' : 'CHROME'} WEBDRIVER AUTOMATION IS NOT ENABLED\n\nYou can download the ${webDriverName} from "${webDriverDownloadURL}".\n\nOnce you have downloaded the ${webDriverName}, install it by moving the "${webDriverExecutableName}" file into the "${installFolderPaths.join('" or "')}" folder.\n\nAfter the ${webDriverName} is installed, you can re-launch "broadlink-webhooks" to automate ${errorIsForFirefox ? 'Firefox' : 'Chrome'}.\n\n`); let openWebDriverDownloadPagePromptResponse = await prompts({ type: 'toggle', name: 'openLink', message: `Would you like to open "${webDriverDownloadURL}" in your default web browser?`, initial: true, active: 'Yes', inactive: 'No' }); let choseToOpenLink = ((Object.keys(openWebDriverDownloadPagePromptResponse).length == 1) && (openWebDriverDownloadPagePromptResponse.openLink == true)); if (choseToOpenLink) { try { exec(`${((process.platform == 'darwin') ? 'open' : ((process.platform == 'win32') ? 'start' : 'xdg-open'))} ${webDriverDownloadURL}`); } catch (openWebDriverDownloadURLerror) { console.error(`ERROR OPENING "${webDriverDownloadURL}": ${openWebDriverDownloadURLerror}`); } } let openFolderPromptChoices = ["Don't Open a Folder"]; for (let thisInstallFolderIndex = 0; thisInstallFolderIndex < installFolderPaths.length; thisInstallFolderIndex ++) { let thisInstallFolderPath = installFolderPaths[thisInstallFolderIndex]; openFolderPromptChoices.push({title: `Open "${thisInstallFolderPath}"`, value: thisInstallFolderPath}); } if (openFolderPromptChoices.length > 1) { console.log(''); // Just for a line break before the open folder prompt. let openFolderPromptResponse = await prompts({ type: 'select', name: 'openFolder', message: `Would you like to open ${((openFolderPromptChoices.length > 2) ? 'an' : 'the')} "${webDriverExecutableName}" install location folder${((process.platform == 'darwin') ? ' in Finder' : ((process.platform == 'win32') ? ' in File Explorer' : ''))}?`, choices: openFolderPromptChoices, initial: (choseToOpenLink ? 1 : 0) // Only default to opening a folder if the user chose to open the download URL. }); if (Object.keys(openFolderPromptResponse).length == 1) { try { if (!existsSync(openFolderPromptResponse.openFolder)) { // Should only possibly happen for `${homeDir}/.local/bin/` on Linux. mkdirSync(openFolderPromptResponse.openFolder, {recursive: true}); } } catch (makeFolderError) { // Ignore any error making a folder. } try { exec(`${((process.platform == 'darwin') ? 'open' : ((process.platform == 'win32') ? 'start' : 'xdg-open'))} ${openFolderPromptResponse.openFolder}`); } catch (openFolderError) { console.error(`ERROR OPENING "${openFolderPromptResponse.openFolder}": ${openFolderError}`); } } } console.log(''); // Just for a line break before the next Terminal prompt. } else { console.error(`\nERROR: ${runtimeError}`); console.error('\n\nRUNTIME ERROR OCCURRED - RE-LAUNCH BROADLINK-WEBHOOKS TO TRY AGAIN\n\n'); } } finally { if (webDriver && (userQuit || browserToAutomate.endsWith('-headless') || !debugLogging)) { // Keep web browser window open if errored with debugLogging enabled and was not headless. try { await webDriver.quit(); } catch (quitWebDriverError) { // Ignore any error quitting WebDriver. } } } })(); async function setup_ifttt_webhooks_broadlink_applet(thisWebhooksEventName, isScene) { await webDriver.get('https://ifttt.com/create'); try { await webDriver.switchTo().alert().accept(); // There could be a Leave Page confirmation that needs to be accepted on Chrome (but it doesn't hurt to also check on Firefox). if (debugLogging) console.debug('DEBUG - Accepted Leave Page Confirmation'); } catch (acceptLeavePageAlertError) { // Ignore any error if there is no Leave Page confirmation. } await check_for_server_error_page(); await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Create your own"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. // Make sure maximum number of allowed Applets haven't been created before continuing. await webDriver.wait( until.elementLocated(By.xpath('//button[text()="Add"]')), longWaitForElementTime ).then(async thisElement => { if (await thisElement.getCssValue('display') == 'none') { // IFTTT Pro required if "Add" button is hidden. throw 'MAXIMUM ALLOWED APPLETS CREATED\n\nPLEASE NOTE: IFTTT PRO REQUIRED TO DETECT BROADLINK DEVICES OR SCENES AND TO CREATE ANYMORE APPLETS'; } }); await click_button_until_no_longer_exists(By.xpath('//button[text()="Add"]')); await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Choose a service"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. await webDriver.wait( until.elementLocated(By.id('search')), longWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Entering "Webhooks" into Search Trigger Services Field'); await thisElement.clear(); await thisElement.sendKeys('Webhooks'); }); await click_button_until_no_longer_exists(By.xpath('//a[@title="Choose service Webhooks"]')); await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Choose a trigger"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. await click_button_until_no_longer_exists(By.xpath('//a[@title="Choose trigger: Receive a web request"]')); await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Complete trigger fields" or text()="Connect service"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. try { await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Complete trigger fields"]')), shortWaitForElementTime); } catch (confirmServiceConnectionError) { throw '"Webhooks" SERVICE NOT CONNECTED IN IFTTT'; } await webDriver.wait( until.elementLocated(By.xpath('//textarea[@name="fields[event]"]')), longWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug(`DEBUG - Entering "${thisWebhooksEventName}" into Webhooks Event Name Field`); await thisElement.clear(); await thisElement.sendKeys(thisWebhooksEventName); if (!thisWebhooksEventName.startsWith('FakeEventName')) { console.info(`\tWebhooks Event Name: ${thisWebhooksEventName}`); } }); await click_button_until_no_longer_exists(By.xpath('//input[@value="Create trigger" or @value="Creating trigger..."]')); await webDriver.wait(until.elementLocated(By.xpath('//span[text()="Receive a web request"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. await click_button_until_no_longer_exists(By.xpath('//section[contains(@class,"then-that")]/button[text()="Add"]')); await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Choose a service"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. await webDriver.wait( until.elementLocated(By.id('search')), longWaitForElementTime ).then(async thisElement => { if (debugLogging) console.debug('DEBUG - Entering "BroadLink" into Search Action Services Field'); await thisElement.clear(); await thisElement.sendKeys('BroadLink'); }); await click_button_until_no_longer_exists(By.xpath('//a[@title="Choose service BroadLink"]')); await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Choose an action"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. await click_button_until_no_longer_exists(By.xpath(`//a[@title="Choose action: ${(isScene ? 'Scene control' : 'Turn device on or off')}"]`)); await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Complete action fields" or text()="Connect service"]')), longWaitForElementTime); // Make sure correct page is loaded before continuing. try { await webDriver.wait(until.elementLocated(By.xpath('//h1[text()="Complete action fields"]')), shortWaitForElementTime); } catch (confirmServiceConnectionError) { throw '"BroadLink" SERVICE NOT CONNECTED IN IFTTT'; } } async function click_button_until_no_longer_exists(buttonLocatedBy) { let buttonClickCount = 0; if (debugLogging) console.debug(`\nDEBUG - Begin Clicking Button: ${buttonLocatedBy}`); while (buttonClickCount < maxButtonClicksCount) { try { await webDriver.wait( until.elementLocated(buttonLocatedBy), shortWaitForElementTime ).then(async thisElement => { if (debugLogging) { let thisElementText = await thisElement.getText(); console.debug(`DEBUG - Clicking Button: ${buttonLocatedBy} - [text="${thisElementText.split('\n')[(thisElementText.startsWith('✚\n') ? 1 : 0)]}", value="${await thisElement.getAttribute('value')}"] (${buttonClickCount + 1})`); } try { await thisElement.click(); buttonClickCount ++; } catch (innerClickButtonError) { if (innerClickButtonError.name == 'ElementNotInteractableError') buttonClickCount ++; // Still increment click count if button is disabled to not infinite loop. // Otherwise, ignore likely stale element error and keep looping. } }); } catch (outerClickButtonError) { if (debugLogging) console.debug('DEBUG - BUTTON NO LONGER EXISTS - EXITING LOOP'); break; } await webDriver.sleep(waitForNextPageSleepInLoopTime); } if (debugLogging) { console.debug(`DEBUG - Done Clicking Button ${buttonClickCount} Times: ${buttonLocatedBy}\n`); } } async function check_for_server_error_page() { try { // Occasionally, IFTTT will hit a 502 error. So try to detect any server error quick to retry more quickly (instead of waiting a long time for an element to not exist). await webDriver.wait(until.elementLocated(By.xpath('//center[starts-with(text(),"nginx/")]')), shortWaitForElementTime); if (debugLogging) console.warn('DEBUG WARNING - "nginx/" FOUND ON LIKELY SERVER ERROR PAGE'); let serverErrorTitle = 'Unknown Server Error'; try { await webDriver.wait( until.elementLocated(By.css('h1')), shortWaitForElementTime ).then(async thisElement => { try { serverErrorTitle = await thisElement.getText(); } catch (innerGetH1error) { // Ignore possible stale element error. } }); } catch (outerGetH1error) { // Ignore possible error from element not existing. } throw `HIT "${serverErrorTitle}" - NEED TO RELOAD PAGE`; } catch (checkForServerError) { if (checkForServerError.toString().endsWith('NEED TO RELOAD PAGE')) { throw checkForServerError; } } }
68.198256
502
0.520499
9a6655c1bfba2830732afbdaa933f6d5d9b0e599
1,437
swift
Swift
Unrepeatable/Unrepeatable/Feature/Login/LoginViewController.swift
inahuelzapata/Unrepeatable
29e8e6854f9069384bde9fc2c6912c0903ba6d05
[ "MIT" ]
null
null
null
Unrepeatable/Unrepeatable/Feature/Login/LoginViewController.swift
inahuelzapata/Unrepeatable
29e8e6854f9069384bde9fc2c6912c0903ba6d05
[ "MIT" ]
null
null
null
Unrepeatable/Unrepeatable/Feature/Login/LoginViewController.swift
inahuelzapata/Unrepeatable
29e8e6854f9069384bde9fc2c6912c0903ba6d05
[ "MIT" ]
null
null
null
// // LoginViewController.swift // Unrepeatable // // Created by Nahuel Zapata on 5/29/19. // Copyright © 2019 @iNahuelZapata. All rights reserved. // import Foundation import ReactiveCocoa import ReactiveSwift import UIKit class LoginViewController: UIViewController { @IBOutlet private weak var emailTextField: UITextField! @IBOutlet private weak var passwordTextField: UITextField! let provider: LoginProvidable = LoginProvider(requestBuilder: currentReactive.requestBuilder, requestProvider: currentReactive.requestProvider) override func viewDidLoad() { super.viewDidLoad() logIn() } func logIn() { do { try provider.execute(loginRequest: LoginRequest(email: "Inahuelzapata@gmail.com", password: "skere")) .on(starting: { [weak self] in self?.view.backgroundColor = .blue }, failed: { [weak self] error in print(error) self?.view.backgroundColor = .red }, value: { [weak self] response in self?.view.backgroundColor = .green print(response) }).start() } catch { // error handling print(error) self.view.backgroundColor = .red } } }
30.574468
99
0.556019
c3a7fd9844fcdb94b8e8666add4128d6658407c4
351
go
Go
pkg/clig/cmd/.snapshots/TestInit-skip_viper--home-go-src-go.example.com-foobar-pkg-foobar-context.go
izumin5210/clig
f97e90b6bad78a1e4c9b824c8f68dd871e11d6dc
[ "MIT" ]
8
2018-12-15T10:32:09.000Z
2021-05-12T16:28:28.000Z
pkg/clig/cmd/.snapshots/TestInit-skip_viper--home-go-src-go.example.com-foobar-pkg-foobar-context.go
izumin5210/clig
f97e90b6bad78a1e4c9b824c8f68dd871e11d6dc
[ "MIT" ]
null
null
null
pkg/clig/cmd/.snapshots/TestInit-skip_viper--home-go-src-go.example.com-foobar-pkg-foobar-context.go
izumin5210/clig
f97e90b6bad78a1e4c9b824c8f68dd871e11d6dc
[ "MIT" ]
1
2018-12-26T02:55:15.000Z
2018-12-26T02:55:15.000Z
package foobar import ( "github.com/izumin5210/clig/pkg/clib" "github.com/pkg/errors" "github.com/spf13/afero" "go.uber.org/zap" "k8s.io/utils/exec" ) type Ctx struct { WorkingDir clib.Path IO *clib.IO FS afero.Fs Exec exec.Interface Build clib.Build Config *Config } func (c *Ctx) Init() error { return nil }
13.5
38
0.652422
804fd19c863caa9a32c259a83bbd38baa16db219
34,057
java
Java
calcite-adapter/src/main/java/software/amazon/documentdb/jdbc/metadata/DocumentDbTableSchemaGeneratorHelper.java
alinaliBQ/amazon-documentdb-jdbc-driver
992fe4a93431e507e955db73f627b07063273866
[ "ECL-2.0", "Apache-2.0" ]
5
2021-11-03T23:34:56.000Z
2022-03-27T18:49:30.000Z
calcite-adapter/src/main/java/software/amazon/documentdb/jdbc/metadata/DocumentDbTableSchemaGeneratorHelper.java
alinaliBQ/amazon-documentdb-jdbc-driver
992fe4a93431e507e955db73f627b07063273866
[ "ECL-2.0", "Apache-2.0" ]
134
2021-10-29T18:53:53.000Z
2022-03-31T18:23:20.000Z
calcite-adapter/src/main/java/software/amazon/documentdb/jdbc/metadata/DocumentDbTableSchemaGeneratorHelper.java
alinaliBQ/amazon-documentdb-jdbc-driver
992fe4a93431e507e955db73f627b07063273866
[ "ECL-2.0", "Apache-2.0" ]
6
2021-12-13T01:03:42.000Z
2022-01-27T01:38:14.000Z
/* * Copyright <2021> Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file 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 software.amazon.documentdb.jdbc.metadata; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import org.bson.BsonType; import software.amazon.documentdb.jdbc.common.utilities.JdbcType; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.apache.calcite.sql.parser.SqlParser.DEFAULT_IDENTIFIER_MAX_LENGTH; public class DocumentDbTableSchemaGeneratorHelper { static final String EMPTY_STRING = ""; static final int KEY_COLUMN_NONE = 0; private static final String PATH_SEPARATOR = "."; private static final String ID_FIELD_NAME = "_id"; private static final int ID_PRIMARY_KEY_COLUMN = 1; /** * The map of data type promotions. * * @see <a href="https://github.com/aws/amazon-documentdb-jdbc-driver#data-type-conflict-promotion"> * Map Relational Schemas to DocumentDB - Scalar-Scalar Conflicts</a> */ private static final ImmutableMap<Entry<JdbcType, BsonType>, JdbcType> PROMOTION_MAP = new ImmutableMap.Builder<Entry<JdbcType, BsonType>, JdbcType>() .put(new SimpleEntry<>(JdbcType.NULL, BsonType.BOOLEAN), JdbcType.BOOLEAN) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.BINARY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.DATE_TIME), JdbcType.TIMESTAMP) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.DECIMAL128), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.DOUBLE), JdbcType.DOUBLE) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.INT32), JdbcType.INTEGER) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.INT64), JdbcType.BIGINT) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.MAX_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.MIN_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.NULL), JdbcType.NULL) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.OBJECT_ID), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.STRING), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.ARRAY), JdbcType.ARRAY) .put(new SimpleEntry<>(JdbcType.NULL, BsonType.DOCUMENT), JdbcType.JAVA_OBJECT) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.BOOLEAN), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.BINARY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.DATE_TIME), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.DECIMAL128), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.DOUBLE), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.INT32), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.INT64), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.MAX_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.MIN_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.NULL), JdbcType.ARRAY) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.OBJECT_ID), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.STRING), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.ARRAY), JdbcType.ARRAY) .put(new SimpleEntry<>(JdbcType.ARRAY, BsonType.DOCUMENT), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.BOOLEAN), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.BINARY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.DATE_TIME), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.DECIMAL128), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.DOUBLE), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.INT32), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.INT64), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.MAX_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.MIN_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.NULL), JdbcType.JAVA_OBJECT) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.OBJECT_ID), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.STRING), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.ARRAY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.JAVA_OBJECT, BsonType.DOCUMENT), JdbcType.JAVA_OBJECT) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.BOOLEAN), JdbcType.BOOLEAN) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.BINARY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.DATE_TIME), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.DECIMAL128), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.DOUBLE), JdbcType.DOUBLE) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.INT32), JdbcType.INTEGER) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.INT64), JdbcType.BIGINT) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.MAX_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.MIN_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.NULL), JdbcType.BOOLEAN) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.OBJECT_ID), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.STRING), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.ARRAY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BOOLEAN, BsonType.DOCUMENT), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.BOOLEAN), JdbcType.BIGINT) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.BINARY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.DATE_TIME), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.DECIMAL128), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.DOUBLE), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.INT32), JdbcType.BIGINT) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.INT64), JdbcType.BIGINT) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.MAX_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.MIN_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.NULL), JdbcType.BIGINT) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.OBJECT_ID), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.STRING), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.ARRAY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.BIGINT, BsonType.DOCUMENT), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.BOOLEAN), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.BINARY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.DATE_TIME), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.DECIMAL128), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.DOUBLE), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.INT32), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.INT64), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.MAX_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.MIN_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.NULL), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.OBJECT_ID), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.STRING), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.ARRAY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DECIMAL, BsonType.DOCUMENT), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.BOOLEAN), JdbcType.DOUBLE) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.BINARY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.DATE_TIME), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.DECIMAL128), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.DOUBLE), JdbcType.DOUBLE) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.INT32), JdbcType.DOUBLE) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.INT64), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.MAX_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.MIN_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.NULL), JdbcType.DOUBLE) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.OBJECT_ID), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.STRING), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.ARRAY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.DOUBLE, BsonType.DOCUMENT), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.BOOLEAN), JdbcType.INTEGER) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.BINARY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.DATE_TIME), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.DECIMAL128), JdbcType.DECIMAL) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.DOUBLE), JdbcType.DOUBLE) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.INT32), JdbcType.INTEGER) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.INT64), JdbcType.BIGINT) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.MAX_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.MIN_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.NULL), JdbcType.INTEGER) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.OBJECT_ID), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.STRING), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.ARRAY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.INTEGER, BsonType.DOCUMENT), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.BOOLEAN), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.BINARY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.DATE_TIME), JdbcType.TIMESTAMP) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.DECIMAL128), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.DOUBLE), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.INT32), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.INT64), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.MAX_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.MIN_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.NULL), JdbcType.TIMESTAMP) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.OBJECT_ID), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.STRING), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.ARRAY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.TIMESTAMP, BsonType.DOCUMENT), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.BOOLEAN), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.BINARY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.DATE_TIME), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.DECIMAL128), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.DOUBLE), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.INT32), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.INT64), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.MAX_KEY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.MIN_KEY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.NULL), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.OBJECT_ID), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.STRING), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.ARRAY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARBINARY, BsonType.DOCUMENT), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.BOOLEAN), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.BINARY), JdbcType.VARBINARY) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.DATE_TIME), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.DECIMAL128), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.DOUBLE), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.INT32), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.INT64), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.MAX_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.MIN_KEY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.NULL), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.OBJECT_ID), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.STRING), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.ARRAY), JdbcType.VARCHAR) .put(new SimpleEntry<>(JdbcType.VARCHAR, BsonType.DOCUMENT), JdbcType.VARCHAR) .build(); /** * Combines two paths to form a new path. * * @param path the root/parent path. * @param fieldName the field name to append to the path. * @return a new path with the fieldName append to the root path separated by a period. */ public static String combinePath(final String path, final String fieldName) { final boolean isPathEmpty = Strings.isNullOrEmpty(path); final boolean isFieldNameEmpty = Strings.isNullOrEmpty(fieldName); final String pathSeparator = !isPathEmpty && !isFieldNameEmpty ? PATH_SEPARATOR : EMPTY_STRING; final String newPath = !isPathEmpty ? path : EMPTY_STRING; final String newFieldName = !isFieldNameEmpty ? fieldName : EMPTY_STRING; return String.format("%s%s%s", newPath, pathSeparator, newFieldName); } /** * Gets the promoted SQL data type from previous SQL data type and the current BSON data type. * * @param bsonType the current BSON data type. * @param prevSqlType the previous SQL data type. * @return returns the promoted SQL data type. */ @VisibleForTesting static JdbcType getPromotedSqlType(final BsonType bsonType, final JdbcType prevSqlType) { final Entry<JdbcType, BsonType> key = new SimpleEntry<>(prevSqlType, bsonType); return PROMOTION_MAP.getOrDefault(key, JdbcType.VARCHAR); } /** * Gets whether the field is the "_id" field. * * @param fieldName the name of the field. * @return returns {@code true} if the field name if "_id", {@code false} otherwise. */ static boolean isIdField(final String fieldName) { return ID_FIELD_NAME.equals(fieldName); } /** * Handles a complex to scalar conflict by removing the previous table map and clearing existing * column map. * * @param tableMap the table map. * @param path the path to the table. * @param columnMap the column map. */ static void handleComplexScalarConflict( final Map<String, DocumentDbSchemaTable> tableMap, final String path, final Map<String, DocumentDbSchemaColumn> columnMap) { tableMap.remove(path); columnMap.clear(); } /** * Detects and handles the case were a conflict occurs at a lower lever in the array. * It removes the index column for the higher level array index. * It ensures the SQL type is set to VARCHAR. * * @param columnMap the column map to modify. * @param level the current array level. * @param sqlType the previous SQL type. * @return if a conflict is detected, returns VARCHAR, otherwise, the original SQL type. */ static JdbcType handleArrayLevelConflict( final Map<String, DocumentDbSchemaColumn> columnMap, final int level, final JdbcType sqlType) { JdbcType newSqlType = sqlType; // Remove previously detect index columns at higher index level, // if we now have scalars at a lower index level. final Map<String, DocumentDbSchemaColumn> origColumns = new LinkedHashMap<>(columnMap); for (Entry<String, DocumentDbSchemaColumn> entry : origColumns.entrySet()) { final DocumentDbMetadataColumn column = (DocumentDbMetadataColumn) entry.getValue(); if (column.getArrayIndexLevel() != null && column.getArrayIndexLevel() > level) { columnMap.remove(entry.getKey()); // We're collapsing an array level, so revert to VARCHAR/VARBINARY this and for the higher // level array components. newSqlType = getPromotedSqlType(BsonType.STRING, newSqlType); } } return newSqlType; } /** * Gets the primary key column number depending on whether we are whether it is the primary key. * * @param isPrimaryKey an indicator of whether we are dealing with the primary key. * @return the value {@link #ID_PRIMARY_KEY_COLUMN} if the primary key, other it * returns {@link #KEY_COLUMN_NONE}. */ static int getPrimaryKeyColumn(final boolean isPrimaryKey) { // If primary key, then first column, zero indicates not part of primary key. return isPrimaryKey ? ID_PRIMARY_KEY_COLUMN : KEY_COLUMN_NONE; } /** * Gets the field name, depending on whether it is the primary key. * * @param path the path the field belongs to. * @param fieldName the name of the field in the path. * @param isPrimaryKey an indicator of whether this is the primary key. * @param columnNameMap a map of unique column names. * @return a column name for the field. */ static String getFieldNameIfIsPrimaryKey( final String path, final String fieldName, final boolean isPrimaryKey, final Map<String, String> columnNameMap) { return isPrimaryKey // For the primary key, qualify it with the parent name. ? toName(combinePath(getParentName(path), fieldName), columnNameMap) : fieldName; } /** * Gets the virtual table name, depending on whether this is the primary key. * * @param fieldPath the path the field belongs to. * @param nextSqlType the next SQL type. * @param isPrimaryKey an indicator of whether this is the primary key. * @param collectionName a map of unique column names. * @param tableNameMap a map of unique table names. * @return the name of the virtual table if not a primary key (base table) and type is not * ARRAY or JAVA_OBJECT. Otherwise, null. */ static String getVirtualTableNameIfIsPrimaryKey( final String fieldPath, final JdbcType nextSqlType, final boolean isPrimaryKey, final String collectionName, final Map<String, String> tableNameMap) { return !isPrimaryKey && (nextSqlType == JdbcType.ARRAY || nextSqlType == JdbcType.JAVA_OBJECT) ? toName(combinePath(collectionName, fieldPath), tableNameMap) : null; } /** * Gets the SQL type, depending on whether this is the primary key. * * @param bsonType the underlying source data type. * @param prevSqlType the previous SQL type detected. * @param isPrimaryKey an indicator of whether this is the primary key. * @return the SQL type to use. */ static JdbcType getSqlTypeIfIsPrimaryKey( final BsonType bsonType, final JdbcType prevSqlType, final boolean isPrimaryKey) { return isPrimaryKey && bsonType == BsonType.DOCUMENT ? JdbcType.VARCHAR : getPromotedSqlType(bsonType, prevSqlType); } /** * Gets the previous SQL data type. * * @param prevMetadataColumn the column to get the SQL type for. Can be null. * @return the previous SQL data type if the column is not null, {@link JdbcType#NULL}, * otherwise. */ static JdbcType getPrevSqlTypeOrDefault( final DocumentDbMetadataColumn prevMetadataColumn) { return prevMetadataColumn != null ? prevMetadataColumn.getSqlType() : JdbcType.NULL; } /** * Gets whether the given SQL type is a complex type (ARRAY or JAVA_OBJECT). * * @param sqlType the SQL type to tests. * @return {@code true} if a complex type, {@code false}, otherwise. */ static boolean isComplexType(final JdbcType sqlType) { return sqlType == JdbcType.JAVA_OBJECT || sqlType == JdbcType.ARRAY; } /** * Adds to the list of primary keys, if is a primary key. * * @param foreignKeys the list of foreign keys. * @param isPrimaryKey an indicator of whether this is a primary key. * @param metadataColumn the column to add. */ static void addToForeignKeysIfIsPrimary( final List<DocumentDbMetadataColumn> foreignKeys, final boolean isPrimaryKey, final DocumentDbMetadataColumn metadataColumn) { // Add the key to the foreign keys for child tables. if (isPrimaryKey) { foreignKeys.add(metadataColumn); } } /** * Gets the previous index for this column. * * @param prevMetadataColumn the previous column to use. Can be null. * @param defaultValue the default index value to use if the column is null. * @return the index of the column, if not null. Otherwise, the default value. */ static int getPrevIndexOrDefault(final DocumentDbMetadataColumn prevMetadataColumn, final int defaultValue) { return prevMetadataColumn != null ? prevMetadataColumn.getIndex() : defaultValue; } /** * Checks and ensures consistency of SQL type between the primary key of the base table and any * generated virtual tables. * * @param tableMap the map of tables. * @param path the path of the collection. * @param columnMap the column map of the base table. * @param columnNameMap the map of unique column names. */ static void checkVirtualTablePrimaryKeys( final Map<String, DocumentDbSchemaTable> tableMap, final String path, final LinkedHashMap<String, DocumentDbSchemaColumn> columnMap, final Map<String, String> columnNameMap) { final String primaryKeyColumnName = toName(combinePath(path, ID_FIELD_NAME), columnNameMap); final DocumentDbMetadataColumn primaryKeyColumn = (DocumentDbMetadataColumn) columnMap .get(primaryKeyColumnName); for (DocumentDbSchemaTable table : tableMap.values()) { final DocumentDbMetadataColumn column = (DocumentDbMetadataColumn) table .getColumnMap().get(primaryKeyColumnName); if (column != null && !column.getSqlType().equals(primaryKeyColumn.getSqlType())) { column.setSqlType(primaryKeyColumn.getSqlType()); } } } /** * Converts the path to name swapping the period character for an underscore character. Unique * names of maximum length {@link org.apache.calcite.sql.parser.SqlParser#DEFAULT_IDENTIFIER_MAX_LENGTH} * are maintained in the uniqueNameMap parameter. * * @param path the path to convert. * @param uniqueNameMap the map of unique names. * @return a string the period character swapped for an underscore character, of correct maximum * length and unique within the map of given paths */ @VisibleForTesting static String toName(final String path, final Map<String, String> uniqueNameMap) { return toName(path, uniqueNameMap, DEFAULT_IDENTIFIER_MAX_LENGTH); } /** * Converts the path to name swapping the period character for an underscore character. Unique * names of maximum length given in identifierMaxLength parameter. are maintained in the * uniqueNameMap parameter. * * @param path the path to convert. * @param uniqueNameMap the map of unique names. * @param identifierMaxLength the maximum length of identifier name. * @return a string the period character swapped for an underscore character, of correct maximum * length and unique within the map of given paths */ @VisibleForTesting static String toName( final String path, final Map<String, String> uniqueNameMap, final int identifierMaxLength) { final String fullPathName = path.replaceAll("\\.", "_"); // If already mapped, return the mapped value. if (uniqueNameMap.containsKey(path)) { return uniqueNameMap.get(path); } // If not greater the maximum allowed length, return value. if (path.length() <= identifierMaxLength) { return fullPathName; } // Shorten the name and ensure uniqueness. final StringBuilder shortenedName = new StringBuilder(fullPathName); final List<MatchResult> matches = getSeparatorMatches(path); if (matches.isEmpty()) { // Only "base table" shortenBaseName( path, uniqueNameMap, identifierMaxLength, shortenedName); } else if (matches.get(0).start() < identifierMaxLength) { // Base table shorter than max length - combine with trailing path. shortenWithBaseNameLessThanMaxLength( path, uniqueNameMap, identifierMaxLength, shortenedName, matches); } else { // Base table too long. Combine on trailing path. shortenWithBaseNameLongerThanMaxLength( path, uniqueNameMap, identifierMaxLength, shortenedName, matches); } return shortenedName.toString(); } private static void shortenWithBaseNameLongerThanMaxLength( final String path, final Map<String, String> uniqueNameMap, final int identifierMaxLength, final StringBuilder shortenedName, final List<MatchResult> matches) { int lastMatchIndex = 0; for (int matchIndex = matches.size() - 1; matchIndex > 0; matchIndex--) { if ((path.length() - matches.get(matchIndex).start()) >= identifierMaxLength) { break; } lastMatchIndex = matchIndex; } if (lastMatchIndex > 0) { shortenedName.delete(0, matches.get(lastMatchIndex).start()); } else { shortenedName.delete(0, shortenedName.length() - identifierMaxLength); } ensureUniqueName(uniqueNameMap, shortenedName, path); } private static void shortenWithBaseNameLessThanMaxLength( final String path, final Map<String, String> uniqueNameMap, final int identifierMaxLength, final StringBuilder shortenedName, final List<MatchResult> matches) { int lastMatchIndex = 0; for (int matchIndex = matches.size() - 1; matchIndex > 0; matchIndex--) { if ((path.length() - matches.get(matchIndex).start()) + matches.get(0).start() >= identifierMaxLength) { break; } lastMatchIndex = matchIndex; } final int deleteChars; if (lastMatchIndex > 0) { deleteChars = matches.get(lastMatchIndex).start() - matches.get(0).start(); } else { deleteChars = path.length() - identifierMaxLength; } shortenedName.delete(matches.get(0).start(), matches.get(0).start() + deleteChars); ensureUniqueName(uniqueNameMap, shortenedName, path); } private static void shortenBaseName( final String path, final Map<String, String> uniqueNameMap, final int identifierMaxLength, final StringBuilder shortenedName) { shortenedName.delete(identifierMaxLength, shortenedName.length()); ensureUniqueName(uniqueNameMap, shortenedName, path); } private static void ensureUniqueName( final Map<String, String> uniqueNameMap, final StringBuilder shortenedName, final String path) { int counter = 0; final StringBuilder tempName = new StringBuilder(shortenedName); while (uniqueNameMap.values().stream().anyMatch(s -> tempName.toString().equals(s))) { counter++; final String counterString = String.valueOf(counter); tempName.setLength(0); tempName.append( shortenedName.substring(0, shortenedName.length() - counterString.length())) .append(counterString); } shortenedName.setLength(0); shortenedName.append(tempName); uniqueNameMap.put(path, shortenedName.toString()); } private static List<MatchResult> getSeparatorMatches(final String path) { final List<MatchResult> matches = new ArrayList<>(); final Pattern separatorPattern = Pattern.compile("\\."); final Matcher separatorMatcher = separatorPattern.matcher(path); separatorMatcher.reset(); while (separatorMatcher.find()) { matches.add(separatorMatcher.toMatchResult()); } return matches; } /** * Gets the parent name (last node) in the path. * * @param path the path to read. * @return the last node in the path. */ private static String getParentName(final String path) { return path.substring(path.lastIndexOf('.') + 1); } }
55.648693
108
0.639986
6ef0559dbf333b3ba18393c90eb58a3d6731cca8
303
asm
Assembly
sw/552tests/inst_tests/sle_1.asm
JPShen-UWM/ThreadKraken
849c510531f28e36d3469535737b2120bd774935
[ "MIT" ]
1
2022-02-15T16:03:25.000Z
2022-02-15T16:03:25.000Z
sw/552tests/inst_tests/sle_1.asm
JPShen-UWM/ThreadKraken
849c510531f28e36d3469535737b2120bd774935
[ "MIT" ]
null
null
null
sw/552tests/inst_tests/sle_1.asm
JPShen-UWM/ThreadKraken
849c510531f28e36d3469535737b2120bd774935
[ "MIT" ]
null
null
null
// Original test: ./kohlmann/hw4/problem6/sle_0.asm // Author: kohlmann // Test source code follows // SLE Test 0 - Verify that SLE correctly compares positive numbers. lbi r1, 0x10 // r1 = 16'd16 lbi r2, 0x18 // r2 = 16'd24 sle r3, r1, r2 // r3 should equal 1 sle r3, r2, r1 // r3 should equal 0 halt
27.545455
68
0.689769
0c808cb709ff18e791fad72250ff77bac76e87d8
1,032
html
HTML
manuscript/page-952/body.html
marvindanig/the-romance-of-lust
d7bc9078b6fb129e8d3623b5e9e27c6d967a39f4
[ "BlueOak-1.0.0", "MIT" ]
null
null
null
manuscript/page-952/body.html
marvindanig/the-romance-of-lust
d7bc9078b6fb129e8d3623b5e9e27c6d967a39f4
[ "BlueOak-1.0.0", "MIT" ]
2
2020-09-05T01:47:33.000Z
2021-05-07T16:08:34.000Z
manuscript/page-952/body.html
marvindanig/the-romance-of-lust
d7bc9078b6fb129e8d3623b5e9e27c6d967a39f4
[ "BlueOak-1.0.0", "MIT" ]
null
null
null
<div class="leaf flex"><div class="inner justify"><p class="no-indent ">able to be much more tranquil all the afternoon.</p><p>The Dale and Ellen came to dinner; I slipt into their room when all were dressing for dinner, and had a delicious rack-off in both their lecherous and longing cunts. Uncle had equally enjoyed the tight favourite arsehole of Harry Dale, he having conducted him to the well-known summer house for that purpose as soon as we arrived.</p><p>We could all thus peaceably enjoy the good things set before us, and during our wine after dinner exchange accounts of all events that had passed since last we met, and they were varied, for Mr. Nixon’s death and legacies to my sisters and myself were subjects of congratulation, while the death of my mother was, on the contrary, one of condolence and sympathy.</p><p class=" stretch-last-line">By ten o’clock we all broke up, but with the whispered request to all to repair to aunt’s bedroom half an hour after the household had retired. We were all</p></div> </div>
1,032
1,032
0.775194
2f2b43622cdd13a475dddd20b8c4b2d42e404ea8
725
java
Java
src/main/java/de/embl/cba/mobie/display/AbstractSourceDisplay.java
imagejan/mobie-viewer-fiji
8515016820176f4c2ae08b902265f7028abe5dc9
[ "MIT" ]
null
null
null
src/main/java/de/embl/cba/mobie/display/AbstractSourceDisplay.java
imagejan/mobie-viewer-fiji
8515016820176f4c2ae08b902265f7028abe5dc9
[ "MIT" ]
null
null
null
src/main/java/de/embl/cba/mobie/display/AbstractSourceDisplay.java
imagejan/mobie-viewer-fiji
8515016820176f4c2ae08b902265f7028abe5dc9
[ "MIT" ]
null
null
null
package de.embl.cba.mobie.display; import bdv.viewer.SourceAndConverter; import de.embl.cba.mobie.transform.SourceTransformer; import de.embl.cba.mobie.bdv.view.SliceViewer; import java.util.List; public abstract class AbstractSourceDisplay implements SourceDisplay { // Serialization protected String name; protected double opacity = 1.0; protected boolean visible = true; public String getName() { return name; } public double getOpacity() { return opacity; } public boolean isVisible() { return visible; } // Runtime public transient List< SourceAndConverter< ? > > sourceAndConverters; public transient List< SourceTransformer > sourceTransformers; public transient SliceViewer sliceViewer; }
21.323529
70
0.775172
acb8ba9e7e23463839d56dd025e892e338de8928
1,762
cpp
C++
Algorithms/AlgorithmAndDatastructure/Graph/SymbolDigraph.cpp
balusi/AlgorithmsAndDataStructure
73bb73cabb4e58e8da21795f8cc13c59074b8e98
[ "Apache-2.0" ]
48
2017-08-28T11:44:06.000Z
2021-12-31T09:18:09.000Z
Algorithms/AlgorithmAndDatastructure/Graph/SymbolDigraph.cpp
Enber/AlgorithmsAndDataStructure
ac7d0c5d07c4f3d695d00728453c6859adaf27f1
[ "Apache-2.0" ]
null
null
null
Algorithms/AlgorithmAndDatastructure/Graph/SymbolDigraph.cpp
Enber/AlgorithmsAndDataStructure
ac7d0c5d07c4f3d695d00728453c6859adaf27f1
[ "Apache-2.0" ]
26
2018-03-28T03:11:11.000Z
2021-07-29T12:45:58.000Z
// // Created by windyear_office on 18-1-31. // #include <fstream> #include "SymbolDigraph.h" #include <boost/algorithm/string.hpp> #include <iostream> SymbolDigraph::SymbolDigraph(string filename, char* sp) { ifstream input(filename); if(input){ string s; vector<string> ss; //以sp为分隔符读取字符串内容到s中 while(getline(input, s)) { //map的插入方法,要熟悉 boost::algorithm::split(ss, s, boost::algorithm::is_any_of(sp)); for(auto v: ss) { if (!index_table.count(v)) { index_table.insert(pair<string, int>(v, index_table.size())); } } } } input.close(); //第二次遍历构造图 g = new Digraph(index_table.size()); //重新分配大小 index.resize(index_table.size()); //遍历map map<string, int>::iterator it; for(it = index_table.begin(); it != index_table.end(); it++){ index[it->second] = it->first; } input.open(filename); if(input){ string s; vector<string> ss; while(getline(input, s)) { //map的插入方法,要熟悉 boost::algorithm::split(ss, s, boost::algorithm::is_any_of(sp)); int v = index_table[ss[0]]; for(int i = 1; i < ss.size(); i++) { g->AddEdge(v, index_table[ss[i]]); } } } input.close(); cout << "The size of the Digraph is: " << index_table.size() << endl; } SymbolDigraph::~SymbolDigraph() { delete g; } bool SymbolDigraph::Contains(string s) { return index_table.count(s); } Digraph SymbolDigraph::G() { return *g; } int SymbolDigraph::Index(string s) { return index_table[s]; } string SymbolDigraph::Name(int index_) { return index[index_]; }
23.493333
81
0.555619
1622d419175ebcdf4491dd4526cadae6b5b2d79b
987
ts
TypeScript
services/renderer-ts/src/rehype-github-icon.ts
mkizka/Hatena-Intern-2020
9c758dc1436da3b3eccc4646b12e19be28e7c298
[ "MIT" ]
null
null
null
services/renderer-ts/src/rehype-github-icon.ts
mkizka/Hatena-Intern-2020
9c758dc1436da3b3eccc4646b12e19be28e7c298
[ "MIT" ]
null
null
null
services/renderer-ts/src/rehype-github-icon.ts
mkizka/Hatena-Intern-2020
9c758dc1436da3b3eccc4646b12e19be28e7c298
[ "MIT" ]
null
null
null
import { Transformer, Attacher } from "unified"; import visit from "unist-util-visit"; type HTMLNode = { type: string; tagName?: string; value: string; children: HTMLNode[]; properties?: { [key: string]: any }; }; const githubIcon: Attacher = () => { const transformer: Transformer = (tree, _) => { visit<HTMLNode>(tree, "element", (node) => { node.children = node.children.map((child) => { if (child.type !== "text") return child; const matched = child.value.match(/\[([\w-]+)\.icon\]/); if (matched) { return { type: "element", tagName: "img", value: "", children: [], properties: { src: `https://github.com/${matched[1]}.png`, alt: matched[1], style: "height: 1.5rem", }, }; } else { return child; } }); }); }; return transformer; }; export default githubIcon;
24.675
64
0.497467
312fea5270085e9a95d4648d0b5ee1812a1d8be8
322
dart
Dart
example/lib/config/router.dart
flutter-jp/flutter_ui
53d9283439186ec4226ff6375ccb772a8cb437cb
[ "MIT" ]
20
2019-10-29T02:39:43.000Z
2022-03-02T08:22:50.000Z
example/lib/config/router.dart
flutter-jp/flutter_ui
53d9283439186ec4226ff6375ccb772a8cb437cb
[ "MIT" ]
1
2019-11-22T07:21:46.000Z
2019-11-22T07:21:46.000Z
example/lib/config/router.dart
flutter-jp/flutter_ui
53d9283439186ec4226ff6375ccb772a8cb437cb
[ "MIT" ]
5
2019-11-01T11:13:56.000Z
2020-10-07T23:51:07.000Z
class Router { static final String toast = 'toast'; static final String actionSheet = 'actionSheet'; static final String button = 'button'; static final String language = 'language'; static final String checkList = 'checkList'; static final String badge = 'badge'; static final String browser = 'browser'; }
32.2
50
0.720497
dd7250e57d0a6ae8a5034e5809983c9f4f4f64dd
218
go
Go
vfs/vfsflags/vfsflags_non_unix.go
database64128/rclone
b55575e6225f7b297ea7636272705855aae5486f
[ "MIT" ]
18,121
2019-07-28T19:57:56.000Z
2022-03-31T21:53:48.000Z
vfs/vfsflags/vfsflags_non_unix.go
database64128/rclone
b55575e6225f7b297ea7636272705855aae5486f
[ "MIT" ]
3,298
2019-07-28T17:25:45.000Z
2022-03-31T21:18:53.000Z
vfs/vfsflags/vfsflags_non_unix.go
database64128/rclone
b55575e6225f7b297ea7636272705855aae5486f
[ "MIT" ]
2,024
2019-07-28T20:50:40.000Z
2022-03-31T10:19:12.000Z
//go:build !linux && !darwin && !freebsd // +build !linux,!darwin,!freebsd package vfsflags import ( "github.com/spf13/pflag" ) // add any extra platform specific flags func platformFlags(flags *pflag.FlagSet) { }
16.769231
42
0.706422
aef5f622cf34bbb41abb5e6ff68b4eecb65a465f
29,070
dart
Dart
BlossomApp/lib/pages/maps_page.dart
aditisandhu/blossom
c5fba13ddec881d50855057bcbfd450426f14a8b
[ "MIT" ]
null
null
null
BlossomApp/lib/pages/maps_page.dart
aditisandhu/blossom
c5fba13ddec881d50855057bcbfd450426f14a8b
[ "MIT" ]
null
null
null
BlossomApp/lib/pages/maps_page.dart
aditisandhu/blossom
c5fba13ddec881d50855057bcbfd450426f14a8b
[ "MIT" ]
1
2022-03-29T16:58:43.000Z
2022-03-29T16:58:43.000Z
import 'dart:async'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:geolocator/geolocator.dart'; import 'package:sliding_up_panel/sliding_up_panel.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:flutter_polyline_points/flutter_polyline_points.dart'; import '../helpers/location_service.dart'; import '../helpers/new_menstrual_icons_icons.dart'; import '../secret.dart'; class MapSample extends StatefulWidget { const MapSample({Key? key}) : super(key: key); @override State<MapSample> createState() => MapSampleState(); } class MapSampleState extends State<MapSample> { Completer<GoogleMapController> _controller = Completer(); late GoogleMapController newGoogleMapController; GlobalKey<ScaffoldState> scaffoldkey = GlobalKey<ScaffoldState>(); late Position currentPosition; var geoLocator = Geolocator(); dynamic pharmacies; Set<Marker> markers = Set(); Set<Polyline> polylines = {}; List<LatLng> polylineCoordinates = []; PolylinePoints polylinePoints = PolylinePoints(); String googleAPIKey = GoogleAPIKey; // ignore: prefer_const_declarations static final CameraPosition _kGooglePlex = const CameraPosition( target: LatLng(37.42796133580664, -122.085749655962), zoom: 14.4746, ); TextEditingController _searchController = TextEditingController(); bool flag = false; bool pageRequestedFlag = false; dynamic pageRequestedResults; dynamic pageRequestedAllResults; late BitmapDescriptor originMarker; late BitmapDescriptor destinationMarker; @override void initState() { super.initState(); setCustomMarker(); } void setCustomMarker() async { originMarker = await BitmapDescriptor.fromAssetImage(const ImageConfiguration(), 'assets/origin.png'); destinationMarker = await BitmapDescriptor.fromAssetImage(const ImageConfiguration(), 'assets/destination.png'); } void locatePosition() async { Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high); currentPosition = position; LatLng latLangPosition = LatLng(position.latitude, position.longitude); CameraPosition cameraPosition = CameraPosition(target: latLangPosition, zoom: 14); newGoogleMapController.animateCamera(CameraUpdate.newCameraPosition(cameraPosition)); setState(() async { pharmacies = await LocationService().getPlace('pharmacy', position.latitude, position.longitude); flag = true; }); } void setMarker(dynamic result) { setState(() { for (var i = 0; i < result.length; i++) { markers.add(Marker( //add first marker markerId: MarkerId('Location' + i.toString()), position: LatLng(result[i]['geometry']['location']['lat'], result[i]['geometry']['location']['lng']), //position of marker infoWindow: InfoWindow( //popup info title: result[i]['name'], ), icon: destinationMarker, //Icon for Marker )); } }); } void setRouteMarkers(origin, destination) { setState(() { markers.add(Marker( //add first marker markerId: const MarkerId('Origin'), position: LatLng(origin.latitude, origin.longitude), //position of marker icon: originMarker, //Icon for Marker )); markers.add(Marker( //add first marker markerId: const MarkerId('Destination'), position: LatLng(destination.latitude, destination.longitude), //position of marker icon: destinationMarker, //Icon for Marker )); }); } setPolylines(origin, destination) async { var result = await polylinePoints.getRouteBetweenCoordinates( googleAPIKey, PointLatLng(origin.latitude, origin.longitude), PointLatLng(destination.latitude, destination.longitude)); if (result.points.isNotEmpty) { result.points.forEach((PointLatLng point) { polylineCoordinates.add(LatLng(point.latitude, point.longitude)); }); } setState(() { Polyline polyline = Polyline( polylineId: const PolylineId("poly"), color: const Color.fromARGB(255, 238, 170, 168), points: polylineCoordinates); polylines.add(polyline); }); } String getDistance(double lat2, double lon2) { var R = 6371; // Radius of the earth in km var dLat = (lat2-currentPosition.latitude) * pi/180; var dLon = (lon2-currentPosition.longitude) * pi/180; var a = sin(dLat/2) * sin(dLat/2) + cos((currentPosition.latitude) * pi/180) * cos((lat2) * pi/180) * sin(dLon/2) * sin(dLon/2); var c = 2 * atan2(sqrt(a), sqrt(1-a)); var d = R * c; // Distance in km d = double.parse((d).toStringAsFixed(2)); return d.toString() + ' km'; } void search(String textToSearch) async { Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high); var result = await LocationService().getPlace(textToSearch, position.latitude, position.longitude); markers = Set(); polylines = {}; polylineCoordinates = []; setMarker(result); } @override Widget build(BuildContext context) { // ignore: unnecessary_new return new Scaffold( body: SlidingUpPanel( minHeight: 80, maxHeight: MediaQuery.of(context).size.height*0.8, borderRadius: const BorderRadius.vertical(top: Radius.circular(18)), parallaxEnabled: true, parallaxOffset: 0.5, body: GoogleMap( mapType: MapType.normal, initialCameraPosition: _kGooglePlex, myLocationButtonEnabled: false, myLocationEnabled: true, zoomGesturesEnabled: true, zoomControlsEnabled: true, markers: markers, polylines: polylines, onMapCreated: (GoogleMapController controller) { controller.setMapStyle(Utils.mapStyle); _controller.complete(controller); newGoogleMapController = controller; locatePosition(); }, ), panelBuilder: (controller) => PanelWidget(controller), ), floatingActionButton: FloatingActionButton.extended( onPressed: locatePosition, label: const Text('My Location'), icon: const Icon(Icons.location_history), ), floatingActionButtonLocation: FloatingActionButtonLocation.miniCenterTop, ); } Widget PanelWidget(ScrollController controller) { return Container( decoration: const BoxDecoration( color: Color.fromARGB(255, 242, 242, 242), borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20)) ), child: ListView( padding: EdgeInsets.zero, controller: controller, children: <Widget>[ const SizedBox(height: 15,), buildDragHandle(), if (pageRequestedFlag) ...[ const SizedBox(height: 5,), pageWidget(pageRequestedResults, pageRequestedAllResults) ] else ...[ slidingPanelHome(), ], const SizedBox(height: 24,), ], ), ); } Widget buildDragHandle() => Center( child: Container( width: 30, height: 5, decoration: BoxDecoration( color: Colors.grey[300], borderRadius: BorderRadius.circular(12) ), ) ); Widget slidingPanelHome() => Container( padding: const EdgeInsets.symmetric(horizontal: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row(children: [ IconButton( onPressed: () => search(_searchController.text), icon: const Icon(Icons.search),), Expanded(child: TextFormField( controller: _searchController, textCapitalization: TextCapitalization.words, decoration: const InputDecoration(hintText: 'Search Maps'), onChanged: (value) { // print(value); }, )), InkWell(child: Container( decoration: BoxDecoration( color: const Color.fromARGB(255, 2, 42, 59), borderRadius: BorderRadius.circular(12) ), width: 89, height: 38, padding: const EdgeInsets.all(10), child: const Text('Clear Map', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13, color: Color.fromARGB(255, 255, 255, 255)))), onTap: () { setState(() { markers = Set(); polylines = {}; }); }, )],), const SizedBox(height: 20,), Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( decoration: const BoxDecoration( color: Color.fromARGB(255, 2, 42, 59), shape: BoxShape.circle ), child: IconButton(onPressed: () => search("sanitary pads"), icon: const Icon(NewMenstrualIcons.pad, color: Color.fromARGB(255, 255, 255, 255),), iconSize: 40,) ), Container( decoration: const BoxDecoration( color: Color.fromARGB(255, 2, 42, 59), shape: BoxShape.circle ), child: IconButton(onPressed: () => search("tampon"), icon: const Icon(NewMenstrualIcons.tampon, color: Color.fromARGB(255, 255, 255, 255),), iconSize: 40,) ), Container( decoration: const BoxDecoration( color: Color.fromARGB(255, 2, 42, 59), shape: BoxShape.circle ), child: IconButton(onPressed: () => search("contraception"), icon: const Icon(NewMenstrualIcons.birthcontrol, color: Color.fromARGB(255, 255, 255, 255),), iconSize: 40,) ), Container( decoration: const BoxDecoration( color: Color.fromARGB(255, 2, 42, 59), shape: BoxShape.circle ), child: IconButton(onPressed: () => search("pharmacy"), icon: const Icon(NewMenstrualIcons.stethoscope, color: Color.fromARGB(255, 255, 255, 255),), iconSize: 40,) ), Container( decoration: const BoxDecoration( color: Color.fromARGB(255, 2, 42, 59), shape: BoxShape.circle ), child: IconButton(onPressed: () => search("doctor"), icon: const Icon(NewMenstrualIcons.family, color: Color.fromARGB(255, 255, 255, 255),), iconSize: 40,) ), ],), const SizedBox(height: 20,), const Text(' Near Me', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 25, color: Color.fromARGB(255, 2, 42, 59))), const SizedBox(height: 10,), if (flag) ...[ Column( children: [ for (var i = 0; i < 5; i++) nearBy(i), ], ), ], ], ), ); Widget nearBy(i) => Container( width: double.infinity, margin: const EdgeInsets.all(10), decoration: BoxDecoration( color: const Color.fromARGB(255, 237, 211, 210), border: Border.all( color: const Color.fromARGB(255, 237, 211, 210), ), borderRadius: const BorderRadius.all(Radius.circular(20)) ), child: Padding(padding: const EdgeInsets.all(15), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(pharmacies[i]['name'], style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 20, color: Color.fromARGB(255, 2, 42, 59))), const SizedBox(height: 15,), Text(pharmacies[i]['formatted_address'], style: const TextStyle(fontSize: 15, color: Color.fromARGB(255, 2, 42, 59))), Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Distance: ' + getDistance(pharmacies[i]['geometry']['location']['lat'], pharmacies[i]['geometry']['location']['lng']) + ' • Rating: ' + pharmacies[i]['rating'].toString(), style: const TextStyle(fontSize: 15, color: Color.fromARGB(255, 2, 42, 59))), IconButton(onPressed: () => pageRequested(pharmacies[i], pharmacies), icon: const Icon(Icons.arrow_forward, size: 25,)) ],) ]), ), ); pageRequested(results, allResults) { // print(results); // print(results.keys.toList()..sort()); setState(() { pageRequestedFlag = true; pageRequestedResults = results; pageRequestedAllResults = allResults; }); } homeRequested() { setState(() { pageRequestedFlag = false; }); } var defaultHours = [ "Monday: 9:00 AM - 10:00 PM", "Tuesday: 9:00 AM - 10:00 PM", "Wednesday: 9:00 AM - 10:00 PM", "Thursday: 9:00 AM - 10:00 PM", "Friday: 9:00 AM - 10:00 PM", "Saturday: 9:00 AM - 10:00 PM", "Sunday: 9:00 AM - 10:00 PM", ]; Widget pageWidget(results, allResults) => Container( padding: const EdgeInsets.symmetric(horizontal: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row(children: [ IconButton(onPressed: () => homeRequested(), icon: const Icon(Icons.arrow_back, size: 25,)), Flexible( child: Text(results['name'], maxLines: 2, style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 25, color: Color.fromARGB(255, 2, 42, 59))), ) ],), const SizedBox(height: 10,), Text(' Sanitary Products • ' + getDistance(results['geometry']['location']['lat'], results['geometry']['location']['lng']) + ' • ' + results['rating'].toString() + ' ☆ • ' + getStars(results), style: const TextStyle(fontSize: 15, color: Color.fromARGB(255, 2, 42, 59))), InkWell( child: Container( width: double.infinity, margin: const EdgeInsets.all(10), alignment: Alignment.center, decoration: BoxDecoration( color: const Color.fromARGB(255, 2, 42, 59), borderRadius: BorderRadius.circular(12) ), child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: const [ SizedBox(height: 10,), Text('Directions', style: TextStyle(fontSize: 18, color: Color.fromARGB(255, 255, 255, 255))), SizedBox(height: 10,), ]), ), onTap: () { print('can you see me'); markers = Set(); polylines = {}; polylineCoordinates = []; setRouteMarkers( LatLng(currentPosition.latitude, currentPosition.longitude), LatLng(results['geometry']['location']['lat'], results['geometry']['location']['lng'])); setPolylines( LatLng(currentPosition.latitude, currentPosition.longitude), LatLng(results['geometry']['location']['lat'], results['geometry']['location']['lng']));} ), Row(mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: 100, margin: const EdgeInsets.all(5), alignment: Alignment.center, decoration: BoxDecoration( color: const Color.fromARGB(255, 240, 229, 229), borderRadius: BorderRadius.circular(12) ), child: InkWell(child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: const [ SizedBox(height: 10,), Icon(Icons.phone), SizedBox(height: 10,), Text('Call', style: TextStyle(fontSize: 18, color: Colors.black)), SizedBox(height: 10,), ]), onTap: () async { var number = results['formatted_phone_number']; launch('tel://$number'); }) ), Container( width: 100, margin: const EdgeInsets.all(5), alignment: Alignment.center, decoration: BoxDecoration( color: const Color.fromARGB(255, 240, 229, 229), borderRadius: BorderRadius.circular(12) ), child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: const [ SizedBox(height: 10,), Icon(Icons.bookmark), SizedBox(height: 10,), Text('Bookmark', style: TextStyle(fontSize: 18, color: Colors.black)), SizedBox(height: 10,), ]) ), Container( width: 100, margin: const EdgeInsets.all(5), alignment: Alignment.center, decoration: BoxDecoration( color: const Color.fromARGB(255, 240, 229, 229), borderRadius: BorderRadius.circular(12) ), child: InkWell(child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: const [ SizedBox(height: 10,), Icon(Icons.language), SizedBox(height: 10,), Text('More', style: TextStyle(fontSize: 18, color: Colors.black)), SizedBox(height: 10,), ]), onTap: () async { var website = results['website']; launch(website); }) ) ],), const SizedBox(height: 10,), const Text(' Hours', style: TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.bold)), const SizedBox(height: 5,), if (results.containsKey('opening_hours') && results['opening_hours'].containsKey('weekday_text')) ...[ for (var i = 0; i < results['opening_hours']['weekday_text'].length; i++) Text(' ' + results['opening_hours']['weekday_text'][i], style: const TextStyle(fontSize: 16, color: Colors.black)), ] else ...[ for (var i = 0; i < defaultHours.length; i++) Text(' ' + defaultHours[i], style: const TextStyle(fontSize: 16, color: Colors.black)), ], const SizedBox(height: 15,), const Text(' Address', style: TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.bold)), const SizedBox(height: 5,), Padding(padding: const EdgeInsets.only(left:13), child: Text(results['formatted_address'], style: const TextStyle(fontSize: 16, color: Colors.black)),), const SizedBox(height: 15,), const Text(' Useful to Know', style: TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.bold)), Padding(padding: const EdgeInsets.only(left:13), child: Column(children: [ for (var i in ['Sanitary Pads', 'Tampons', 'Pregnancy Test', 'Condoms']) Row(children: [const Icon(Icons.check), Text(' ' + i, style: const TextStyle(fontSize: 16, color: Colors.black))]), Row(children: const [ Icon(Icons.close), Text(' Available Medical Professionals', style: TextStyle(fontSize: 16, color: Colors.black)), ],), ],) ), const SizedBox(height: 15,), const Text(' Similar Locations', style: TextStyle(fontSize: 18, color: Colors.black, fontWeight: FontWeight.bold)), Padding(padding: const EdgeInsets.only(left:13, right: 13), child: SingleChildScrollView(scrollDirection: Axis.horizontal, child: Row(children: [ for (var i=0; i<5; i++) if (allResults[i]!=results) ...[ Padding(padding: const EdgeInsets.only(right: 13), child: InkWell(child: Container( width: 200, height: 130, margin: const EdgeInsets.only(top: 5), alignment: Alignment.center, decoration: BoxDecoration( color: const Color.fromARGB(255, 240, 229, 229), borderRadius: BorderRadius.circular(12) ), child: Column(crossAxisAlignment: CrossAxisAlignment.center, children: [ const SizedBox(height: 10,), Padding(padding: const EdgeInsets.only(left: 5, right: 5) ,child: Text(allResults[i]['name'], textAlign: TextAlign.center, style: const TextStyle(fontSize: 18, color: Colors.black))), const SizedBox(height: 10,), Text(getDistance(allResults[i]['geometry']['location']['lat'], allResults[i]['geometry']['location']['lng']) + ' • Rating: ' + allResults[i]['rating'].toString(), style: const TextStyle(fontSize: 15, color: Color.fromARGB(255, 2, 42, 59))), const SizedBox(height: 10,), ]), ), onTap: () => pageRequested(allResults[i], allResults)),) ] ],) )) ]) ); String getStars(results) { var level = results['price_level']; if (results.containsKey('price_level')) { if (level == 0) { return '\$'; } else { return '\$'*level; } } return '\$'; } } class Utils { static String mapStyle = ''' [ { "featureType": "all", "elementType": "all", "stylers": [ { "visibility": "on" } ] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [ { "color": "#444444" } ] }, { "featureType": "administrative.province", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative.locality", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative.neighborhood", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative.land_parcel", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "administrative.land_parcel", "elementType": "labels.text", "stylers": [ { "visibility": "off" } ] }, { "featureType": "landscape", "elementType": "all", "stylers": [ { "color": "#f2f2f2" } ] }, { "featureType": "landscape.man_made", "elementType": "all", "stylers": [ { "visibility": "simplified" } ] }, { "featureType": "poi", "elementType": "all", "stylers": [ { "visibility": "off" }, { "color": "#cee9de" }, { "saturation": "2" }, { "weight": "0.80" } ] }, { "featureType": "poi.attraction", "elementType": "geometry.fill", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.park", "elementType": "all", "stylers": [ { "visibility": "on" } ] }, { "featureType": "road", "elementType": "all", "stylers": [ { "saturation": -100 }, { "lightness": 45 } ] }, { "featureType": "road.highway", "elementType": "all", "stylers": [ { "visibility": "simplified" } ] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [ { "visibility": "on" }, { "color": "#f5d6d6" } ] }, { "featureType": "road.highway", "elementType": "labels.text", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road.highway", "elementType": "labels.icon", "stylers": [ { "hue": "#ff0000" }, { "visibility": "on" } ] }, { "featureType": "road.highway.controlled_access", "elementType": "labels.text", "stylers": [ { "visibility": "simplified" } ] }, { "featureType": "road.highway.controlled_access", "elementType": "labels.icon", "stylers": [ { "visibility": "on" }, { "hue": "#0064ff" }, { "gamma": "1.44" }, { "lightness": "-3" }, { "weight": "1.69" } ] }, { "featureType": "road.arterial", "elementType": "all", "stylers": [ { "visibility": "on" } ] }, { "featureType": "road.arterial", "elementType": "labels.text", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road.arterial", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road.local", "elementType": "all", "stylers": [ { "visibility": "on" } ] }, { "featureType": "road.local", "elementType": "labels.text", "stylers": [ { "visibility": "simplified" }, { "weight": "0.31" }, { "gamma": "1.43" }, { "lightness": "-5" }, { "saturation": "-22" } ] }, { "featureType": "transit", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "transit.line", "elementType": "all", "stylers": [ { "visibility": "on" }, { "hue": "#ff0000" } ] }, { "featureType": "transit.station.airport", "elementType": "all", "stylers": [ { "visibility": "simplified" }, { "hue": "#ff0045" } ] }, { "featureType": "transit.station.bus", "elementType": "all", "stylers": [ { "visibility": "on" }, { "hue": "#00d1ff" } ] }, { "featureType": "transit.station.bus", "elementType": "labels.text", "stylers": [ { "visibility": "simplified" } ] }, { "featureType": "transit.station.rail", "elementType": "all", "stylers": [ { "visibility": "simplified" }, { "hue": "#00cbff" } ] }, { "featureType": "transit.station.rail", "elementType": "labels.text", "stylers": [ { "visibility": "simplified" } ] }, { "featureType": "water", "elementType": "all", "stylers": [ { "color": "#46bcec" }, { "visibility": "on" } ] }, { "featureType": "water", "elementType": "geometry.fill", "stylers": [ { "weight": "1.61" }, { "color": "#cde2e5" }, { "visibility": "on" } ] } ] '''; }
30.696938
267
0.512659
163cb83ccaca5a0d861b6aed8bfd378ff33660ca
8,331
ts
TypeScript
src/tasks/javascript.ts
cyrale/gulpfile.js
bef23945b959632f96689bf09d6e0486b6a0df82
[ "MIT" ]
3
2017-11-27T09:18:55.000Z
2020-03-10T15:18:36.000Z
src/tasks/javascript.ts
cyrale/gulpfile.js
bef23945b959632f96689bf09d6e0486b6a0df82
[ "MIT" ]
39
2017-05-16T13:21:23.000Z
2021-07-19T18:17:28.000Z
src/tasks/javascript.ts
cyrale/gulpfile.js
bef23945b959632f96689bf09d6e0486b6a0df82
[ "MIT" ]
3
2019-08-14T12:04:00.000Z
2020-03-07T09:54:19.000Z
import { CLIEngine, Linter } from "eslint"; import log from "fancy-log"; import babel from "gulp-babel"; import clone from "gulp-clone"; import concat from "gulp-concat"; import esLint from "gulp-eslint"; import order from "gulp-order"; import rename from "gulp-rename"; import sourcemaps from "gulp-sourcemaps"; import terser from "gulp-terser"; import merge from "lodash/merge"; import omit from "lodash/omit"; import mergeStream from "merge-stream"; import path from "path"; import Config from "../libs/config"; import { Options as TaskOptions, TaskCallback } from "./task"; import TaskExtended from "./task-extended"; import sourcemapExtractor from "../gulp-plugins/sourcemap-extractor"; type ESLintFile = unknown[]; export interface ESLintErrors extends ESLintFile { errorCount: number; warningCount: number; } /** * Concatenate Javascript files into one file. This file could be babelified. */ export default class Javascript extends TaskExtended { /** * Global task name. * @type {string} * @readonly */ public static readonly taskName: string = "javascript"; /** * Level to order task in execution pipeline. * @type {number} * @readonly */ public static readonly taskOrder: number = 50; /** * Default settings for babel. * * @type {{[name: string]: any}} * @protected * @readonly */ protected static readonly _babelDefaultSettings: { [name: string]: unknown; } = { presets: ["@babel/preset-env"], }; /** * Task constructor. * * @param {TaskOptions} options */ constructor(options: TaskOptions) { super(options); // This task sync browser with filter. this._browserSyncSettings = { match: "**/*.js" }; this._minifySuffix = ".min"; this._hideGzippedSize = false; this._settings.settings = this._settings.settings || {}; // Babel configuration. if (typeof this._settings.settings.babel !== "undefined") { if (typeof this._settings.settings.babel === "object") { this._settings.settings.babel = merge( (this.constructor as any)._babelDefaultSettings, // eslint-disable-line @typescript-eslint/no-explicit-any this._settings.settings.babel ); this._settings.settings.babel = omit(this._settings.settings.babel, ["_flags"]); } else if (typeof this._settings.settings.babel === "string") { this._settings.settings.babel = { configFile: this._settings.settings.babel, }; } } // ESLint configuration. if (typeof this._settings.settings.eslint !== "undefined") { if (typeof this._settings.settings.eslint === "object") { if (!this._settings.settings.eslint.cwd) { this._settings.settings.eslint.cwd = this._settings.cwd; } } else if (typeof this._settings.settings.eslint === "string") { this._settings.settings.eslint = { configFile: this._settings.settings.eslint, cwd: this._settings.cwd, }; } } } /** * Display error from Babel, Uglify or other modules used by this task. * * @param {Record<string, unknown>} error * @protected */ protected _displayError(error: Record<string, unknown>): void { const config: Config = Config.getInstance(); const cliEngine: CLIEngine = new CLIEngine({}); const formatter: CLIEngine.Formatter = cliEngine.getFormatter("stylish"); const relativeFile: string = path.relative(this._settings.cwd, (error.fileName as string) || ""); let formattedMessage: CLIEngine.LintResult[] = []; if (error.cause) { const cause: Record<string, string | number> = error.cause as Record<string, string | number>; // Message send by gulp-babel formattedMessage = [ { errorCount: 1, filePath: relativeFile, fixableErrorCount: 0, fixableWarningCount: 0, messages: [ { column: cause.col as number, line: cause.line as number, message: cause.message as string, nodeType: "", ruleId: null, severity: 2 as Linter.Severity, source: null, }, ], usedDeprecatedRules: [], warningCount: 0, }, ]; // Particular exit due to the comportment of gulp-babel. if (config.isLintRun() || config.isBuildRun()) { log.error(formatter(formattedMessage)); process.exit(1); } } else if (error.message && error.loc) { const location: Record<string, number> = error.loc as Record<string, number>; // Message send by gulp-terser or other formattedMessage = [ { errorCount: 1, filePath: relativeFile, fixableErrorCount: 0, fixableWarningCount: 0, messages: [ { column: location.column, line: location.line, message: (error.message as string).replace(error.fileName as string, relativeFile), nodeType: "", ruleId: null, severity: 2 as Linter.Severity, source: null, }, ], usedDeprecatedRules: [], warningCount: 0, }, ]; log.error(formatter(formattedMessage)); } } /** * Flag current task with error to avoid build execution. * * @param {ESLintErrors} filesWithErrors * @param {TaskCallback} done * @protected */ protected _esLintResults(filesWithErrors: ESLintErrors, done?: TaskCallback): void { const config: Config = Config.getInstance(); this._lintError = filesWithErrors.errorCount > 0; if (this._lintError && config.isLintRun()) { for (const error of filesWithErrors) { TaskExtended.taskErrors.push({ taskName: this._taskName("lint"), error, done, }); } } } /** * Method to add specific steps for the build. * * @param {NodeJS.ReadableStream} stream * @return {NodeJS.ReadableStream} * @protected */ protected _hookBuildBefore(stream: NodeJS.ReadableStream): NodeJS.ReadableStream { stream = stream.pipe(order(this._settings.src)); if (this._settings.sourcemaps) { stream = stream.pipe(sourcemaps.init()); } if (this._settings.settings.babel !== false) { stream = stream.pipe(babel(this._settings.settings.babel)); } stream = stream.pipe(concat(this._settings.filename)); stream = this._minifyFiles(stream); if (this._settings.sourcemaps) { stream = stream.pipe(sourcemaps.write(this._settings.sourcemapFiles)); } return stream; } /** * Method to add specific steps for the lint. * * @param {NodeJS.ReadWriteStream} stream * @param {TaskCallback} done * @return {NodeJS.ReadWriteStream} * @protected */ protected _hookLint(stream: NodeJS.ReadWriteStream, done?: TaskCallback): NodeJS.ReadWriteStream { return stream .pipe(esLint(this._settings.settings.eslint)) .pipe(esLint.format()) .pipe( esLint.results((filesWithErrors: ESLintErrors): void => { this._esLintResults(filesWithErrors, done); }) ); } /** * Add minification to the stream to generate 2 files: normal and minified. * * @param {NodeJS.ReadableStream} stream * @returns {NodeJS.ReadableStream} * @protected */ protected _minifyFiles(stream: NodeJS.ReadableStream): NodeJS.ReadableStream { const streamMin: NodeJS.ReadableStream = stream .pipe(clone()) .pipe(terser({ output: { comments: false } })) .pipe(rename({ suffix: this._minifySuffix })); return mergeStream(stream, streamMin); } /** * Add sourcemap and minification to the stream. * * @param {NodeJS.ReadableStream} stream * @returns {NodeJS.ReadableStream} * @protected */ protected _sourceMapsAndMinification(stream: NodeJS.ReadableStream): NodeJS.ReadableStream { if (this._settings.sourcemaps) { stream = stream.pipe(sourcemapExtractor()).pipe(sourcemaps.init()); } stream = this._minifyFiles(stream); if (this._settings.sourcemaps) { stream = stream.pipe(sourcemaps.write(this._settings.sourcemapFiles)); } return stream; } }
28.927083
116
0.627896
5f555458fcd02ce3ed97e0d5b5b7c7bb6cf1b8e2
878
asm
Assembly
src/test/ref/fillscreen-2.asm
jbrandwood/kickc
d4b68806f84f8650d51b0e3ef254e40f38b0ffad
[ "MIT" ]
2
2022-03-01T02:21:14.000Z
2022-03-01T04:33:35.000Z
src/test/ref/fillscreen-2.asm
jbrandwood/kickc
d4b68806f84f8650d51b0e3ef254e40f38b0ffad
[ "MIT" ]
null
null
null
src/test/ref/fillscreen-2.asm
jbrandwood/kickc
d4b68806f84f8650d51b0e3ef254e40f38b0ffad
[ "MIT" ]
null
null
null
// Fill screen using an word-based index // Commodore 64 PRG executable file .file [name="fillscreen-2.prg", type="prg", segments="Program"] .segmentdef Program [segments="Basic, Code, Data"] .segmentdef Basic [start=$0801] .segmentdef Code [start=$80d] .segmentdef Data [startAfter="Code"] .segment Basic :BasicUpstart(main) .label SCREEN = $400 .segment Code main: { .label i = 2 .label __1 = 4 lda #<0 sta.z i sta.z i+1 __b1: // for(unsigned int i=0;i<1000; i++) lda.z i+1 cmp #>$3e8 bcc __b2 bne !+ lda.z i cmp #<$3e8 bcc __b2 !: // } rts __b2: // SCREEN[i] = ' ' lda.z i clc adc #<SCREEN sta.z __1 lda.z i+1 adc #>SCREEN sta.z __1+1 lda #' ' ldy #0 sta (__1),y // for(unsigned int i=0;i<1000; i++) inc.z i bne !+ inc.z i+1 !: jmp __b1 }
17.918367
63
0.55467
605673a28ca244ab2992ca939e5fa6bf0eb06caa
14,138
sql
SQL
sql/_14_mysql_compatibility_2/_02_datetime_functions/cases/_010_dayofweek.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
null
null
null
sql/_14_mysql_compatibility_2/_02_datetime_functions/cases/_010_dayofweek.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
null
null
null
sql/_14_mysql_compatibility_2/_02_datetime_functions/cases/_010_dayofweek.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
null
null
null
--+ holdcas on; set system parameters 'return_null_on_function_errors = yes'; select date_format('2000-01-02', '%w=>%W'), dayofweek('2000-01-02'); select date_format('2000-01-03', '%w=>%W'), dayofweek('2000-01-03'); select date_format('2000-01-04', '%w=>%W'), dayofweek('2000-01-04'); select date_format('2000-01-05', '%w=>%W'), dayofweek('2000-01-05'); select date_format('2000-01-06', '%w=>%W'), dayofweek('2000-01-06'); select date_format('2000-01-07', '%w=>%W'), dayofweek('2000-01-07'); select date_format('2000-01-08', '%w=>%W'), dayofweek('2000-01-08'); select date_format('01/01/2010', '%W'), dayofweek('01/01/2010'); select dayofweek(str_to_date('12/25/1999', '%m/%d/%Y')); select dayofweek('2010-01-01 12:20:00'); create table dayofweek_tests(char_col char(32), varchar_col varchar(32), string_col string, bit_col bit(16), integer_col integer, smallint_col smallint, bigint_col bigint, float_col float, double_col double, numeric_col numeric(10,2), monetary_col monetary, date_col DATETIME, time_col TIME, timestamp_col timestamp, datetime_col datetime, set_col set(varchar(32), integer) ); insert into dayofweek_tests values('2010-01-02','asdf','05/04/2010 12:23:15.123',NULL,12000,6,1111111111,12.25,111.11111111,11.12,1234,'2010-01-02','12:10:09',timestamp('2008-10-11 10:49:51'),'1983-01-02 17:28:31',{'golf', 'handicap', 10}),('2010-01-02','1971-12-22 00:14:11','10/04/2010 12:23:15.123',NULL,12000,2,1111111111,12.25,111.11111111,11.12,1234,'2010-01-02','12:10:09',timestamp('2008-10-11 10:49:51'),'1983-01-02 17:28:31',{'golf', 'handicap', 10}); select char_col, dayofweek(char_col) from dayofweek_tests order by smallint_col; select varchar_col, dayofweek(varchar_col) from dayofweek_tests order by smallint_col; select string_col, dayofweek(string_col) from dayofweek_tests order by smallint_col; select bit_col, dayofweek(bit_col) from dayofweek_tests order by smallint_col; select integer_col, dayofweek(integer_col) from dayofweek_tests order by smallint_col; select smallint_col, dayofweek(smallint_col) from dayofweek_tests order by smallint_col; select bigint_col, dayofweek(bigint_col) from dayofweek_tests order by smallint_col; --select float_col, dayofweek(float_col) from dayofweek_tests order by smallint_col; select float_col, if(dayofweek(float_col)=dayofweek(concat(year(sysdate),'-12-25')),'ok','nok') from dayofweek_tests order by smallint_col; select double_col, dayofweek(double_col) from dayofweek_tests order by smallint_col; --select numeric_col, dayofweek(numeric_col) from dayofweek_tests order by smallint_col; select numeric_col, if(dayofweek(numeric_col)=dayofweek(concat(year(sysdate),'-11-12')),'ok','nok') from dayofweek_tests order by smallint_col; select monetary_col, dayofweek(monetary_col) from dayofweek_tests order by smallint_col; select date_col, dayofweek(date_col) from dayofweek_tests order by smallint_col; select time_col, dayofweek(time_col) from dayofweek_tests order by smallint_col; select timestamp_col, dayofweek(timestamp_col) from dayofweek_tests order by smallint_col; select datetime_col, dayofweek(datetime_col) from dayofweek_tests order by smallint_col; select set_col, dayofweek(set_col) from dayofweek_tests order by smallint_col; select * from dayofweek_tests where smallint_col = dayofweek('2010-01-02')-1 order by smallint_col; select * from dayofweek_tests where smallint_col < dayofweek(varchar_col) order by smallint_col; drop table dayofweek_tests; create table t (col varchar(255)) partition by list (dayofweek(col)) (PARTITION P0 VALUES IN (2010, 2011)); drop table t; create table dayofweek_tests as select dayofweek('2010-01-02'); SELECT * FROM db_attribute where class_name='dayofweek_tests'; select * from dayofweek_tests; drop table dayofweek_tests; create view dayofweek_view(v) as select dayofweek('2010-01-02') from db_root; select * from dayofweek_view; drop dayofweek_view; $varchar, $2009-01-01 20:18:32 select dayofweek(?) as rez; $date, $1985-01-02 select dayofweek(?) as rez; $datetime, $01/02/1985 12:13:15 select dayofweek(?) as rez; $time, $12:23:15 select dayofweek(?) as rez; $date, $1985-04-05 select 1 as rez from db_root where dayofweek(?) = 6; $datetime, $01/03/1985 19:45:00 select 1 as rez from db_root where dayofweek(?) = 2; -- test for valid date time format select dayofweek(datetime'2003-08-23 01:02:03.1234'), if (dayofweek(datetime'2010-08-23 01:02:03.1234') = 2, 'ok', 'nok'); select dayofweek(timestamp'2010-08-23 01:02:03'), if (dayofweek(timestamp'2010-08-23 01:02:03') = 2, 'ok', 'nok'); select dayofweek(date'2010-08-23'), if (dayofweek(date'2010-08-23') = 2, 'ok', 'nok'); -- test for valid date, time string format select dayofweek('2010-08-23 01:02:03.1234'), if (dayofweek('2010-08-23 01:02:03.1234') = 2, 'ok', 'nok'); select dayofweek('2010-08-23 01:02:03'), if (dayofweek('2010-08-23 01:02:03') = 2, 'ok', 'nok'); select dayofweek('2010-08-23'), if (dayofweek('2010-08-23') = 2, 'ok', 'nok'); -- test for valid current_* select if (dayofweek(current_datetime)= CAST(date_format(current_datetime,'%w') AS INTEGER)+1, 'ok', 'nok'); select if (dayofweek(current_timestamp)= CAST(date_format(current_timestamp,'%w') AS INTEGER)+1, 'ok', 'nok'); select if (dayofweek(current_date)= CAST(date_format(current_date,'%w') AS INTEGER)+1, 'ok', 'nok'); -- test for normal case select dayofweek('2010-08-01'), if (dayofweek('2010-08-01') = 1, 'ok', 'nok'); select dayofweek('2010-08-02'), if (dayofweek('2010-08-02') = 2, 'ok', 'nok'); select dayofweek('2010-08-03'), if (dayofweek('2010-08-03') = 3, 'ok', 'nok'); select dayofweek('2010-08-04'), if (dayofweek('2010-08-04') = 4, 'ok', 'nok'); select dayofweek('2010-08-05'), if (dayofweek('2010-08-05') = 5, 'ok', 'nok'); select dayofweek('2010-08-06'), if (dayofweek('2010-08-06') = 6, 'ok', 'nok'); select dayofweek('2010-08-07'), if (dayofweek('2010-08-07') = 7, 'ok', 'nok'); select dayofweek('2000-08-01'), if (dayofweek('2000-08-01') = 3, 'ok', 'nok'); select dayofweek('2000-08-02'), if (dayofweek('2000-08-02') = 4, 'ok', 'nok'); select dayofweek('2000-08-03'), if (dayofweek('2000-08-03') = 5, 'ok', 'nok'); select dayofweek('2000-08-04'), if (dayofweek('2000-08-04') = 6, 'ok', 'nok'); select dayofweek('2000-08-05'), if (dayofweek('2000-08-05') = 7, 'ok', 'nok'); select dayofweek('2000-08-06'), if (dayofweek('2000-08-06') = 1, 'ok', 'nok'); select dayofweek('2000-08-07'), if (dayofweek('2000-08-07') = 2, 'ok', 'nok'); -- test for special case select dayofweek('2000-08-06'), if (dayofweek('2000-08-06') = 1, 'ok', 'nok'); select dayofweek(date'2000-08-06' - 1), if (dayofweek(date'2000-08-06' - 1) = 7, 'ok', 'nok'); select dayofweek('2000-08-05'), if (dayofweek('2000-08-05') = 7, 'ok', 'nok'); select dayofweek(date'2000-08-05' + 1), if (dayofweek(date'2000-08-05' + 1) = 1, 'ok', 'nok'); -- check if ER_DATE_CONVERSION is occured. select dayofweek('2000-01-00 01:02:03'); select dayofweek('2000-12-32 01:02:03'); select dayofweek('1999-2-29 01:02:03'); select dayofweek('01:02:03'); set system parameters 'return_null_on_function_errors = no'; select date_format('2000-01-02', '%w=>%W'), dayofweek('2000-01-02'); select date_format('2000-01-03', '%w=>%W'), dayofweek('2000-01-03'); select date_format('2000-01-04', '%w=>%W'), dayofweek('2000-01-04'); select date_format('2000-01-05', '%w=>%W'), dayofweek('2000-01-05'); select date_format('2000-01-06', '%w=>%W'), dayofweek('2000-01-06'); select date_format('2000-01-07', '%w=>%W'), dayofweek('2000-01-07'); select date_format('2000-01-08', '%w=>%W'), dayofweek('2000-01-08'); select date_format('01/01/2010', '%W'), dayofweek('01/01/2010'); select dayofweek(str_to_date('12/25/1999', '%m/%d/%Y')); select dayofweek('2010-01-01 12:20:00'); create table dayofweek_tests(char_col char(32), varchar_col varchar(32), string_col string, bit_col bit(16), integer_col integer, smallint_col smallint, bigint_col bigint, float_col float, double_col double, numeric_col numeric(10,2), monetary_col monetary, date_col DATETIME, time_col TIME, timestamp_col timestamp, datetime_col datetime, set_col set(varchar(32), integer) ); insert into dayofweek_tests values('2010-01-02','asdf','05/04/2010 12:23:15.123',NULL,12000,6,1111111111,12.25,111.11111111,11.12,1234,'2010-01-02','12:10:09',timestamp('2008-10-11 10:49:51'),'1983-01-02 17:28:31',{'golf', 'handicap', 10}),('2010-01-02','1971-12-22 00:14:11','10/04/2010 12:23:15.123',NULL,12000,2,1111111111,12.25,111.11111111,11.12,1234,'2010-01-02','12:10:09',timestamp('2008-10-11 10:49:51'),'1983-01-02 17:28:31',{'golf', 'handicap', 10}); select char_col, dayofweek(char_col) from dayofweek_tests order by smallint_col; select varchar_col, dayofweek(varchar_col) from dayofweek_tests order by smallint_col; select string_col, dayofweek(string_col) from dayofweek_tests order by smallint_col; select bit_col, dayofweek(bit_col) from dayofweek_tests order by smallint_col; select integer_col, dayofweek(integer_col) from dayofweek_tests order by smallint_col; select smallint_col, dayofweek(smallint_col) from dayofweek_tests order by smallint_col; select bigint_col, dayofweek(bigint_col) from dayofweek_tests order by smallint_col; --select float_col, dayofweek(float_col) from dayofweek_tests order by smallint_col; select float_col, if(dayofweek(float_col)=dayofweek(concat(year(sysdate),'-12-25')),'ok','nok') from dayofweek_tests order by smallint_col; select double_col, dayofweek(double_col) from dayofweek_tests order by smallint_col; --select numeric_col, dayofweek(numeric_col) from dayofweek_tests order by smallint_col; select numeric_col, if(dayofweek(numeric_col)=dayofweek(concat(year(sysdate),'-11-12')),'ok','nok') from dayofweek_tests order by smallint_col; select monetary_col, dayofweek(monetary_col) from dayofweek_tests order by smallint_col; select date_col, dayofweek(date_col) from dayofweek_tests order by smallint_col; select time_col, dayofweek(time_col) from dayofweek_tests order by smallint_col; select timestamp_col, dayofweek(timestamp_col) from dayofweek_tests order by smallint_col; select datetime_col, dayofweek(datetime_col) from dayofweek_tests order by smallint_col; select set_col, dayofweek(set_col) from dayofweek_tests order by smallint_col; select * from dayofweek_tests where smallint_col = dayofweek('2010-01-02')-1 order by smallint_col; select * from dayofweek_tests where smallint_col < dayofweek(varchar_col) order by smallint_col; drop table dayofweek_tests; create table t (col varchar(255)) partition by list (dayofweek(col)) (PARTITION P0 VALUES IN (2010, 2011)); drop table t; create table dayofweek_tests as select dayofweek('2010-01-02'); SELECT * FROM db_attribute where class_name='dayofweek_tests'; select * from dayofweek_tests; drop table dayofweek_tests; create view dayofweek_view(v) as select dayofweek('2010-01-02') from db_root; select * from dayofweek_view; drop dayofweek_view; $varchar, $2009-01-01 20:18:32 select dayofweek(?) as rez; $date, $1985-01-02 select dayofweek(?) as rez; $datetime, $01/02/1985 12:13:15 select dayofweek(?) as rez; $time, $12:23:15 select dayofweek(?) as rez; $date, $1985-04-05 select 1 as rez from db_root where dayofweek(?) = 6; $datetime, $01/03/1985 19:45:00 select 1 as rez from db_root where dayofweek(?) = 2; -- test for valid date time format select dayofweek(datetime'2003-08-23 01:02:03.1234'), if (dayofweek(datetime'2010-08-23 01:02:03.1234') = 2, 'ok', 'nok'); select dayofweek(timestamp'2010-08-23 01:02:03'), if (dayofweek(timestamp'2010-08-23 01:02:03') = 2, 'ok', 'nok'); select dayofweek(date'2010-08-23'), if (dayofweek(date'2010-08-23') = 2, 'ok', 'nok'); -- test for valid date, time string format select dayofweek('2010-08-23 01:02:03.1234'), if (dayofweek('2010-08-23 01:02:03.1234') = 2, 'ok', 'nok'); select dayofweek('2010-08-23 01:02:03'), if (dayofweek('2010-08-23 01:02:03') = 2, 'ok', 'nok'); select dayofweek('2010-08-23'), if (dayofweek('2010-08-23') = 2, 'ok', 'nok'); -- test for valid current_* select if (dayofweek(current_datetime)= CAST(date_format(current_datetime,'%w') AS INTEGER)+1, 'ok', 'nok'); select if (dayofweek(current_timestamp)= CAST(date_format(current_timestamp,'%w') AS INTEGER)+1, 'ok', 'nok'); select if (dayofweek(current_date)= CAST(date_format(current_date,'%w') AS INTEGER)+1, 'ok', 'nok'); -- test for normal case select dayofweek('2010-08-01'), if (dayofweek('2010-08-01') = 1, 'ok', 'nok'); select dayofweek('2010-08-02'), if (dayofweek('2010-08-02') = 2, 'ok', 'nok'); select dayofweek('2010-08-03'), if (dayofweek('2010-08-03') = 3, 'ok', 'nok'); select dayofweek('2010-08-04'), if (dayofweek('2010-08-04') = 4, 'ok', 'nok'); select dayofweek('2010-08-05'), if (dayofweek('2010-08-05') = 5, 'ok', 'nok'); select dayofweek('2010-08-06'), if (dayofweek('2010-08-06') = 6, 'ok', 'nok'); select dayofweek('2010-08-07'), if (dayofweek('2010-08-07') = 7, 'ok', 'nok'); select dayofweek('2000-08-01'), if (dayofweek('2000-08-01') = 3, 'ok', 'nok'); select dayofweek('2000-08-02'), if (dayofweek('2000-08-02') = 4, 'ok', 'nok'); select dayofweek('2000-08-03'), if (dayofweek('2000-08-03') = 5, 'ok', 'nok'); select dayofweek('2000-08-04'), if (dayofweek('2000-08-04') = 6, 'ok', 'nok'); select dayofweek('2000-08-05'), if (dayofweek('2000-08-05') = 7, 'ok', 'nok'); select dayofweek('2000-08-06'), if (dayofweek('2000-08-06') = 1, 'ok', 'nok'); select dayofweek('2000-08-07'), if (dayofweek('2000-08-07') = 2, 'ok', 'nok'); -- test for special case select dayofweek('2000-08-06'), if (dayofweek('2000-08-06') = 1, 'ok', 'nok'); select dayofweek(date'2000-08-06' - 1), if (dayofweek(date'2000-08-06' - 1) = 7, 'ok', 'nok'); select dayofweek('2000-08-05'), if (dayofweek('2000-08-05') = 7, 'ok', 'nok'); select dayofweek(date'2000-08-05' + 1), if (dayofweek(date'2000-08-05' + 1) = 1, 'ok', 'nok'); -- check if ER_DATE_CONVERSION is occured. select dayofweek('2000-01-00 01:02:03'); select dayofweek('2000-12-32 01:02:03'); select dayofweek('1999-2-29 01:02:03'); select dayofweek('01:02:03'); commit; --+ holdcas off;
45.902597
220
0.712972
819d512f3085a96b2688fc92b74acdcb6077991f
1,705
ps1
PowerShell
src/Tests/Elastic.Installer.Integration.Tests/Tests/SilentInstall-DifferentLocations/SilentInstall-DifferentLocations.Tests.ps1
mgreau/windows-installers
46b9d1e0ef64ae7fd4c51dfb270cd158fe81377f
[ "Apache-2.0" ]
116
2016-12-18T12:18:10.000Z
2022-03-16T02:31:46.000Z
src/Tests/Elastic.Installer.Integration.Tests/Tests/SilentInstall-DifferentLocations/SilentInstall-DifferentLocations.Tests.ps1
mgreau/windows-installers
46b9d1e0ef64ae7fd4c51dfb270cd158fe81377f
[ "Apache-2.0" ]
380
2017-01-05T09:29:18.000Z
2022-03-31T07:44:53.000Z
src/Tests/Elastic.Installer.Integration.Tests/Tests/SilentInstall-DifferentLocations/SilentInstall-DifferentLocations.Tests.ps1
mgreau/windows-installers
46b9d1e0ef64ae7fd4c51dfb270cd158fe81377f
[ "Apache-2.0" ]
44
2016-12-17T00:51:33.000Z
2021-11-10T02:11:06.000Z
$currentDir = Split-Path -parent $MyInvocation.MyCommand.Path Set-Location $currentDir # mapped sync folder for common scripts . $currentDir\..\common\Utils.ps1 . $currentDir\..\common\CommonTests.ps1 . $currentDir\..\common\Artifact.ps1 Get-Version Get-PreviousVersions $InstallDir = "C:\temp dir\Elasticsearch\$($($Global:Version).FullVersion)\" $DataDir = "C:\foo\data" $ConfigDir = "C:\bar\config" $LogsDir = "C:\baz\logs" Describe "Silent Install with different install locations $(($Global:Version).Description)" { $InstallLocations = "INSTALLDIR=$InstallDir","DATADIRECTORY=$DataDir","CONFIGDIRECTORY=$ConfigDir","LOGSDIRECTORY=$LogsDir" Invoke-SilentInstall -ExeArgs $InstallLocations Context-ElasticsearchService Context-PingNode Context-EsHomeEnvironmentVariable -Expected $InstallDir Context-EsConfigEnvironmentVariable -Expected @{ Path = $ConfigDir } Context-PluginsInstalled Context-MsiRegistered Context-ServiceRunningUnderAccount -Expected "LocalSystem" Context-EmptyEventLog Context-ClusterNameAndNodeName Context-ElasticsearchConfiguration -Expected @{ Data = $DataDir Logs = $LogsDir } Context-JvmOptions Copy-ElasticsearchLogToOut -Path "$LogsDir\elasticsearch.log" } Describe "Silent Uninstall with different install locations $(($Global:Version).Description)" { Invoke-SilentUninstall Context-NodeNotRunning Context-EsConfigEnvironmentVariableNull Context-EsHomeEnvironmentVariableNull Context-MsiNotRegistered Context-ElasticsearchServiceNotInstalled Context-EmptyInstallDirectory -Path $InstallDir Context-DataDirectories -Path @($ConfigDir, $DataDir, $LogsDir) -DeleteAfter }
24.357143
127
0.769501
b68fef7f168005bd874e12abf6628a3c81f99803
975
podspec
Ruby
Tiled.podspec
M0rph3v5/Tiled.iOS
55553ff8a2b2a7a85d702648e179062c4e6605d4
[ "MIT" ]
null
null
null
Tiled.podspec
M0rph3v5/Tiled.iOS
55553ff8a2b2a7a85d702648e179062c4e6605d4
[ "MIT" ]
null
null
null
Tiled.podspec
M0rph3v5/Tiled.iOS
55553ff8a2b2a7a85d702648e179062c4e6605d4
[ "MIT" ]
null
null
null
Pod::Spec.new do |s| s.name = "Tiled" s.version = "0.1.0" s.license = "MIT" s.summary = "A CATiledLayer implementation to easily view high resolution (tiled) images in a zooming UIScrollView." s.description = <<-DESC Everyone who has ever dealt with CATiledLayer knows it can take some time to wrap your head around it, this pod simplifies this by having a drop in TilingScrollView which you populate through the datasource to view your tiled content. As simple as that. DESC s.authors = { "Benjamin de Jager" => "me@m0rph3v5.com" } s.social_media_url = "https://twitter.com/m0rph3v5" s.homepage = "https://github.com/m0rph3v5/Tiled" s.ios.deployment_target = '8.0' s.source = { :git => "https://github.com/m0rph3v5/Tiled.git", :tag => s.version } s.requires_arc = true s.default_subspec = "Core" s.subspec "Core" do |ss| ss.source_files = "src/Tiled" end end
34.821429
234
0.649231
4a32e6178358602ee2227e35a402276e5c71c58e
1,410
js
JavaScript
dist-fontawesome/fontawesome/solid/stopwatch-20-solid.js
maciejg-git/vue-bootstrap-icons
bc60cf77193e15cc72ec7eb7f9949ed8b552e7ec
[ "MIT", "CC-BY-4.0", "MIT-0" ]
null
null
null
dist-fontawesome/fontawesome/solid/stopwatch-20-solid.js
maciejg-git/vue-bootstrap-icons
bc60cf77193e15cc72ec7eb7f9949ed8b552e7ec
[ "MIT", "CC-BY-4.0", "MIT-0" ]
null
null
null
dist-fontawesome/fontawesome/solid/stopwatch-20-solid.js
maciejg-git/vue-bootstrap-icons
bc60cf77193e15cc72ec7eb7f9949ed8b552e7ec
[ "MIT", "CC-BY-4.0", "MIT-0" ]
null
null
null
import { h } from 'vue' export default { name: "Stopwatch20", vendor: "Fa", type: "Solid", tags: ["stopwatch","20"], render() { return h( "svg", {"xmlns":"http://www.w3.org/2000/svg","viewBox":"0 0 448 512","class":"v-icon","fill":"currentColor","data-name":"fa-stopwatch-20","innerHTML":"<path d='M398.5,190.91l.59-.61,26.59-26.58a16,16,0,0,0,0-22.63L403,118.41a16,16,0,0,0-22.63,0l-24.68,24.68A206.68,206.68,0,0,0,256,98.5V64h32a16,16,0,0,0,16-16V16A16,16,0,0,0,288,0H160a16.05,16.05,0,0,0-16,16V48a16.05,16.05,0,0,0,16,16h32V98.5A207.92,207.92,0,0,0,16.09,297.57C12.64,411.5,106.76,510.22,220.72,512,337.13,513.77,432,420,432,304A206,206,0,0,0,398.5,190.91ZM204.37,377.55a8.2,8.2,0,0,1,8.32,8.07v22.31a8.2,8.2,0,0,1-8.32,8.07H121.52a16.46,16.46,0,0,1-16.61-17.62c2.78-35.22,14.67-57.41,38.45-91.37,20.42-29.19,27.1-37.32,27.1-62.34,0-16.92-1.79-24.27-12.21-24.27-9.39,0-12.69,7.4-12.69,22.68v5.23a8.2,8.2,0,0,1-8.33,8.07h-24.9a8.2,8.2,0,0,1-8.33-8.07v-4.07c0-27.3,8.48-60.24,56.43-60.24,43,0,55.57,25.85,55.57,61,0,35.58-12.44,51.21-34.35,81.31-11.56,15-24.61,35.57-26.41,51.2ZM344,352.32c0,35.16-12.3,63.68-57.23,63.68C243.19,416,232,386.48,232,352.55V247.22c0-40.73,19.58-63.22,56.2-63.22C325,184,344,206.64,344,245.3ZM287.87,221.73c-9.41,0-13.23,7.5-13.23,20V357.68c0,13.11,3.59,20.59,13.23,20.59s13-8,13-21.27V241.06C300.89,229.79,297.88,221.73,287.87,221.73Z'/>"}, ) } }
108.461538
1,233
0.659574
3760b5d1c4e41cc9e697b75268e2ef373959773b
2,252
sql
SQL
antrian.sql
TasyaAuliaAdzany/RekayasaWeb
56316ada080f3604c3a2e368884e83503de3e792
[ "MIT" ]
null
null
null
antrian.sql
TasyaAuliaAdzany/RekayasaWeb
56316ada080f3604c3a2e368884e83503de3e792
[ "MIT" ]
null
null
null
antrian.sql
TasyaAuliaAdzany/RekayasaWeb
56316ada080f3604c3a2e368884e83503de3e792
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Waktu pembuatan: 28 Jun 2020 pada 13.21 -- Versi server: 10.4.13-MariaDB -- Versi PHP: 7.2.31 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `antrian` -- -- -------------------------------------------------------- -- -- Struktur dari tabel `tb_admin` -- CREATE TABLE `tb_admin` ( `id` int(11) NOT NULL, `email` varchar(150) NOT NULL, `password` varchar(150) NOT NULL, `nama` varchar(150) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `tb_admin` -- INSERT INTO `tb_admin` (`id`, `email`, `password`, `nama`) VALUES (1, 'zulfan@gmail.com', '12345', 'Admin Zulfan'), (2, 'khaidir@gmail.com', '12345', 'Admin Khaidir'); -- -------------------------------------------------------- -- -- Struktur dari tabel `user` -- CREATE TABLE `user` ( `id` int(50) NOT NULL, `nama` varchar(50) NOT NULL, `nik` int(50) NOT NULL, `alamat` varchar(100) NOT NULL, `tanggal` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data untuk tabel `user` -- INSERT INTO `user` (`id`, `nama`, `nik`, `alamat`, `tanggal`) VALUES (29, 'Adit Asyidiq', 2147483647, 'Ambon, Maluku', '2020-06-25'); -- -- Indexes for dumped tables -- -- -- Indeks untuk tabel `tb_admin` -- ALTER TABLE `tb_admin` ADD PRIMARY KEY (`id`); -- -- Indeks untuk tabel `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT untuk tabel yang dibuang -- -- -- AUTO_INCREMENT untuk tabel `tb_admin` -- ALTER TABLE `tb_admin` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT untuk tabel `user` -- ALTER TABLE `user` MODIFY `id` int(50) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=48; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
22.078431
68
0.648313
a51887a2321afa616bb803c664bcefe90702a814
131
sql
SQL
mssql/02.CRUD/P11.FindAllEmployeesWithASalaryMoreThan50000.sql
vassdeniss/software-university-courses
02314a2c6bb48f46ed497c4007519ba1f702fc4f
[ "MIT" ]
7
2022-01-13T17:00:09.000Z
2022-03-13T16:35:35.000Z
mssql/02.CRUD/P11.FindAllEmployeesWithASalaryMoreThan50000.sql
vassdeniss/software-university-courses
02314a2c6bb48f46ed497c4007519ba1f702fc4f
[ "MIT" ]
1
2022-02-24T19:02:03.000Z
2022-02-24T19:02:03.000Z
mssql/02.CRUD/P11.FindAllEmployeesWithASalaryMoreThan50000.sql
vassdeniss/software-university-courses
02314a2c6bb48f46ed497c4007519ba1f702fc4f
[ "MIT" ]
1
2022-03-13T17:02:52.000Z
2022-03-13T17:02:52.000Z
GO USE [SoftUni] GO SELECT [FirstName] , [LastName] , [Salary] FROM [Employees] WHERE [Salary] > 50000 ORDER BY [Salary] DESC
10.076923
22
0.679389
1c3ada11f511e1e301aac9363fd21d78e63a833b
2,076
ps1
PowerShell
Public/ConvertTo-JavaProperty.ps1
Akaizoku/PSTK
d4c57eb6d9d418c362335354e88c4c23311b3553
[ "MIT" ]
3
2021-01-01T22:22:59.000Z
2022-02-14T06:32:38.000Z
Public/ConvertTo-JavaProperty.ps1
Akaizoku/PSTK
d4c57eb6d9d418c362335354e88c4c23311b3553
[ "MIT" ]
null
null
null
Public/ConvertTo-JavaProperty.ps1
Akaizoku/PSTK
d4c57eb6d9d418c362335354e88c4c23311b3553
[ "MIT" ]
null
null
null
function ConvertTo-JavaProperty { <# .SYNOPSIS Convert to Java property .DESCRIPTION Format property key-value pair as Java property .PARAMETER Property The property parameter corresponds to the property key-value pair to format. .PARAMETER Prefix The optional prefix parameter corresponds to the prefix of the expected Java property. The default value is "D". .INPUTS System.Collections.Specialized.OrderedDictionary. You can pipe the property key-value pair to ConvertTo-JavaProperty. .OUTPUTS System.String. ConvertTo-JavaProperty returns the formatted Java property. .NOTES File name: ConvertTo-JavaProperty.ps1 Author: Florian Carrier Creation date: 2019-10-15 Last modified: 2020-01-16 #> [CmdletBinding ()] Param( [Parameter ( Position = 1, Mandatory = $true, HelpMessage = "Property key-value pair", ValueFromPipeline = $true )] [ValidateNotNullOrEmpty()] [Alias ("Properties")] [System.Collections.Specialized.OrderedDictionary] $Property, [Parameter ( Position = 2, Mandatory = $false, HelpMessage = "Java property prefix" )] [String] $Prefix = "D" ) Begin { # Get global preference variables Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState } Process { if ($Property.Count -gt 0) { $JavaString = New-Object -TypeName "System.String" -ArgumentList "" # Loop through properties (if multiple have been provided) foreach ($SingleProperty in $Property.GetEnumerator()) { # Add space between consecutive properties if ($JavaString) { $JavaString += " " } # Format property $JavaString += "-" + $Prefix + '"' + $SingleProperty.Name + '"' + "=" + '"' + $SingleProperty.Value + '"' } # Return Java property string return $JavaString } else { # If property is invalid return $null } } }
29.239437
121
0.629576
5e0c09dfc74dbfc07866faf2dd78c27811d6597d
3,665
kt
Kotlin
viewpager2/viewpager2/src/androidTest/java/androidx/viewpager2/widget/PageTransformerItemAnimatorTest.kt
semoro/androidx
9edfb9c95d72d2a93f4c13b9634b5dd821aaf193
[ "Apache-2.0" ]
7
2020-07-23T18:52:59.000Z
2020-07-23T20:31:41.000Z
viewpager2/viewpager2/src/androidTest/java/androidx/viewpager2/widget/PageTransformerItemAnimatorTest.kt
semoro/androidx
9edfb9c95d72d2a93f4c13b9634b5dd821aaf193
[ "Apache-2.0" ]
2
2020-07-23T19:17:07.000Z
2020-07-23T19:43:42.000Z
viewpager2/viewpager2/src/androidTest/java/androidx/viewpager2/widget/PageTransformerItemAnimatorTest.kt
semoro/androidx
9edfb9c95d72d2a93f4c13b9634b5dd821aaf193
[ "Apache-2.0" ]
5
2020-07-23T18:45:08.000Z
2020-07-23T18:56:15.000Z
/* * Copyright 2019 The Android Open Source Project * * 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 androidx.viewpager2.widget import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.ItemAnimator import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.LargeTest import androidx.viewpager2.widget.ViewPager2.ORIENTATION_HORIZONTAL import androidx.viewpager2.widget.ViewPager2.PageTransformer import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.not import org.hamcrest.CoreMatchers.notNullValue import org.hamcrest.CoreMatchers.nullValue import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.junit.runner.RunWith /** * Tests that setting a transformer disables data-set change animations, and that those are restored * when a transformer is removed. */ @RunWith(AndroidJUnit4::class) @LargeTest class PageTransformerItemAnimatorTest : BaseTest() { @Test fun test() { setUpTest(ORIENTATION_HORIZONTAL).apply { setAdapterSync(viewAdapterProviderValueId.provider(stringSequence(5))) assertBasicState(0) val rv = viewPager.getChildAt(0) as RecyclerView val animatorDefault = rv.itemAnimator as ItemAnimator val animatorCustom = object : DefaultItemAnimator() {} as ItemAnimator assertThat(animatorDefault, notNullValue()) assertThat(animatorDefault, not(equalTo(animatorCustom))) val transformer1 = PageTransformer { _, _ -> } val transformer2 = PageTransformer { _, _ -> } val transformer3 = PageTransformer { _, _ -> } runOnUiThreadSync { assertThat(rv.itemAnimator, equalTo(animatorDefault)) viewPager.setPageTransformer(MarginPageTransformer(50)) assertThat(rv.itemAnimator, nullValue()) viewPager.setPageTransformer(transformer1) assertThat(rv.itemAnimator, nullValue()) viewPager.setPageTransformer(null) assertThat(rv.itemAnimator, equalTo(animatorDefault)) rv.itemAnimator = animatorCustom viewPager.setPageTransformer(transformer2) assertThat(rv.itemAnimator, nullValue()) viewPager.setPageTransformer(MarginPageTransformer(100)) assertThat(rv.itemAnimator, nullValue()) viewPager.setPageTransformer(CompositePageTransformer()) assertThat(rv.itemAnimator, nullValue()) viewPager.setPageTransformer(null) assertThat(rv.itemAnimator, equalTo(animatorCustom)) viewPager.setPageTransformer(transformer3) assertThat(rv.itemAnimator, nullValue()) viewPager.setPageTransformer(null) assertThat(rv.itemAnimator, equalTo(animatorCustom)) viewPager.setPageTransformer(null) assertThat(rv.itemAnimator, equalTo(animatorCustom)) } } } }
38.989362
100
0.699864
c270a09b326fb3d4766dd13a36fb4e41e2299c69
510
go
Go
app/index.go
mohae/kraul
bdb1de1a4ef0f18cbbb93940c36d0968e43fabac
[ "MIT" ]
1
2017-12-02T15:01:12.000Z
2017-12-02T15:01:12.000Z
app/index.go
mohae/kraul
bdb1de1a4ef0f18cbbb93940c36d0968e43fabac
[ "MIT" ]
null
null
null
app/index.go
mohae/kraul
bdb1de1a4ef0f18cbbb93940c36d0968e43fabac
[ "MIT" ]
null
null
null
package app import ( "fmt" "github.com/mohae/contour" "github.com/mohae/geomi" ) // Index indexes the site at the starturl. URLs not in the startUrl domain // are not crawled func Index(startUrl string) (string, error) { spider, err := geomi.NewSpider(startUrl) if err != nil { fmt.Printf("Could not create spider: %q", err) return "", err } fetchDelay := contour.GetInt("wait") if fetchDelay > 0 { spider.SetFetchInterval(int64(fetchDelay)) } msg, err := spider.Crawl(4) return msg, err }
20.4
74
0.690196
1f0a01f5ad90a34ba45101bb92a5b0f66854d6cd
13,090
cpp
C++
torch/csrc/autograd/python_variable.cpp
UmaTaru/run
be29e4d41a4de3dee27cd6796801bfe51382d294
[ "MIT" ]
null
null
null
torch/csrc/autograd/python_variable.cpp
UmaTaru/run
be29e4d41a4de3dee27cd6796801bfe51382d294
[ "MIT" ]
null
null
null
torch/csrc/autograd/python_variable.cpp
UmaTaru/run
be29e4d41a4de3dee27cd6796801bfe51382d294
[ "MIT" ]
null
null
null
#include "torch/csrc/autograd/python_variable.h" #include <structmember.h> #include "THP.h" #include "torch/csrc/DynamicTypes.h" #include "torch/csrc/Types.h" #include "torch/csrc/autograd/python_cpp_function.h" #include "torch/csrc/autograd/python_hook.h" #include "torch/csrc/cuda/AutoGPU.h" #include "torch/csrc/utils/auto_gil.h" #include "torch/csrc/Exceptions.h" #include <THPP/tensors/THTensor.hpp> using namespace torch::autograd; PyObject *THPVariableClass = NULL; static PyObject* THPVariable_NewWithVar(PyTypeObject* type, std::shared_ptr<Variable> var) { PyObject* obj = type->tp_alloc(type, 0); if (obj) { auto v = (THPVariable*) obj; new (&v->cdata) std::shared_ptr<Variable>(std::move(var)); } return obj; } PyObject * THPVariable_Wrap(const std::shared_ptr<Variable>& var) { if (!var) { Py_RETURN_NONE; } else if (var->pyobj) { Py_INCREF(var->pyobj); } else { var->pyobj = THPVariable_NewWithVar((PyTypeObject *)THPVariableClass, var); THPVariable* py_var = (THPVariable*)var->pyobj; py_var->data = torch::createPyObject(*var->data); } return var->pyobj; } // This function DOES NOT steal a reference to data and grad_fn PyObject * THPVariable_New(PyObject *data, PyObject *_grad_fn) { THPUtils_assert(THPModule_isTensor(data), "data must be a Tensor"); THPUtils_assert(THPFunction_Check(_grad_fn), "grad_fn must be a Function"); THPFunction *grad_fn = (THPFunction*)_grad_fn; auto v = std::make_shared<Variable>(torch::createTensor(data), grad_fn->cdata.is_executable, false); PyObject* obj = THPVariable_NewWithVar((PyTypeObject*)THPVariableClass, v); if (obj) { v->pyobj = obj; v->grad_fn = THPFunction_asFunction((THPFunction*)grad_fn); ((THPVariable*)obj)->data = data; Py_INCREF(data); } return obj; } // This function DOES NOT steal a reference to data PyObject * THPVariable_NewVolatile(PyObject *data) { auto v = std::make_shared<Variable>(torch::createTensor(data), false, true); PyObject* obj = THPVariable_NewWithVar((PyTypeObject*)THPVariableClass, v); if (obj) { v->pyobj = obj; ((THPVariable*)obj)->data = data; Py_INCREF(data); } return obj; } // This function DOES NOT steal a reference to data PyObject * THPVariable_NewLeaf(PyObject *data) { auto v = std::make_shared<Variable>(torch::createTensor(data), false, false); PyObject* obj = THPVariable_NewWithVar((PyTypeObject*)THPVariableClass, v); if (obj) { v->pyobj = obj; ((THPVariable*)obj)->data = data; Py_INCREF(data); } return obj; } static int THPVariable_traverse(THPVariable *self, visitproc visit, void *arg) { Py_VISIT(self->data); Py_VISIT(self->backward_hooks); if (self->cdata) { if (auto fn = dynamic_cast<PyFunction*>(self->cdata->grad_fn.get())) { Py_VISIT(fn->obj); } for (auto& hook : self->cdata->hooks) { if (auto pyhook = dynamic_cast<PyFunctionPreHook*>(hook.get())) { Py_VISIT(pyhook->dict); } } } return 0; } static int THPVariable_clear(THPVariable *self) { Py_CLEAR(self->data); Py_CLEAR(self->backward_hooks); if (self->cdata) { if (auto grad_acc = self->cdata->grad_accumulator.lock()) { grad_acc->pre_hooks.clear(); } self->cdata->pyobj = nullptr; } self->cdata.reset(); return 0; } static void THPVariable_dealloc(THPVariable* self) { PyObject_GC_UnTrack(self); THPVariable_clear(self); self->cdata.~shared_ptr<Variable>(); Py_TYPE(self)->tp_free((PyObject*)self); } PyObject *THPVariable_pynew(PyTypeObject *type, PyObject *args, PyObject *kwds) { THPObjectPtr _data; PyObject *data = NULL; PyObject *grad_fn = NULL; char is_volatile = 0; char requires_grad = 0; const char *accepted_args[] = {"data", "requires_grad", "volatile", "_grad_fn", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ObbO", (char**)accepted_args, &data, &requires_grad, &is_volatile, &grad_fn)) return NULL; if (grad_fn == Py_None) grad_fn = NULL; if (data == NULL || data == Py_None) { // For legacy serialization code, create an empty tensor temporarily. thpp::THTensor<float> tensor; _data = torch::createPyObject(tensor); data = _data.get(); } THPUtils_assert(!(is_volatile && requires_grad), "Variable can't be volatile and require_grad at the same time!"); THPUtils_assert(!grad_fn || THPFunction_Check(grad_fn), "Variable _grad_fn has to be a Function object or None, but got %s", THPUtils_typename(grad_fn)); THPUtils_assert(THPModule_isTensor(data), "Variable data has to " "be a tensor, but got %s", THPUtils_typename(data)); std::shared_ptr<Variable> var; if (grad_fn) { var = std::make_shared<Variable>(torch::createTensor(data), THPFunction_asFunction((THPFunction*)grad_fn)); } else { var = std::make_shared<Variable>(torch::createTensor(data), requires_grad, is_volatile); } PyObject* self = THPVariable_NewWithVar(type, var); if (self) { var->pyobj = self; ((THPVariable*)self)->cdata = var; ((THPVariable*)self)->data = data; Py_INCREF(data); } return self; } int THPVariable_pyinit(PyObject *self, PyObject *args, PyObject *kwds) { // Ensures that calls to Variable() and subclasses contain data argument. // The 'data' argument is optional in __new__ to handle legacy serialized // Variables. PyObject *data; PyObject *grad_fn = NULL; char is_volatile = 0; char requires_grad = 0; const char *accepted_args[] = {"data", "requires_grad", "volatile", "_grad_fn", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ObbO", (char**)accepted_args, &data, &requires_grad, &is_volatile, &grad_fn)) return -1; return 0; } typedef PyObject *(*getter)(PyObject *, void *); typedef int (*setter)(PyObject *, PyObject *, void *); PyObject *THPVariable_get_version(THPVariable *self) { auto& var = *self->cdata; return PyInt_FromLong(**var.version_counter); } PyObject *THPVariable_get_grad_fn(THPVariable *self) { auto& var = *self->cdata; if (!var.grad_fn) { Py_RETURN_NONE; } return functionToPyObject(var.grad_fn); } int THPVariable_set_grad_fn(THPVariable *self, PyObject *obj) { THPUtils_assertRet(-1, obj == Py_None, "_grad_fn can be only set to None"); self->cdata->grad_fn = nullptr; return 0; } PyObject *THPVariable_is_leaf(THPVariable *self) { return PyBool_FromLong(!self->cdata->grad_fn); } PyObject * THPVariable_get_data(THPVariable *self) { if (!self->data) { self->data = torch::createPyObject(*self->cdata->data); } Py_INCREF(self->data); return self->data; } int THPVariable_set_data(THPVariable *self, PyObject *data) { THPUtils_assertRet(-1, THPModule_isTensor(data), "Variable data has to " "be a tensor, but got %s", THPUtils_typename(data)); Py_INCREF(data); Py_XDECREF(self->data); self->data = data; auto& var = *self->cdata; auto tensor = torch::createTensor(data); var.data.swap(tensor); return 0; } PyObject *THPVariable_get_raw_grad(THPVariable *self) { auto& var = *self->cdata; if (!var.grad) { Py_RETURN_NONE; } return THPVariable_Wrap(var.grad); } int THPVariable_set_raw_grad(THPVariable *self, PyObject *data) { auto& var = *self->cdata; if (data == Py_None) { var.grad.reset(); return 0; } THPUtils_assertRet(-1, THPVariable_Check(data), "expected Variable or None (got %s)", THPUtils_typename(data)); var.grad = ((THPVariable*)data)->cdata; return 0; } PyObject *THPVariable_get_grad(THPVariable *self) { auto& var = *self->cdata; if (!var.grad) { Py_RETURN_NONE; } return THPVariable_Wrap(var.grad); } PyObject *THPVariable_get_volatile(THPVariable *self) { auto& var = *self->cdata; return PyBool_FromLong(var.is_volatile); } int THPVariable_set_volatile(THPVariable *self, PyObject *obj) { THPUtils_assertRet(-1, PyBool_Check(obj), "volatile must be a bool"); THPUtils_assertRet(-1, !self->cdata->grad_fn, "volatile can only be set on leaf variables"); auto& var = *self->cdata; var.is_volatile = (obj == Py_True); return 0; } PyObject *THPVariable_get_output_nr(THPVariable *self) { auto& var = *self->cdata; return PyInt_FromLong(var.output_nr); } PyObject *THPVariable_get_requires_grad(THPVariable *self) { auto& var = *self->cdata; return PyBool_FromLong(var.requires_grad); } int THPVariable_set_requires_grad(THPVariable *self, PyObject *obj) { THPUtils_assertRet(-1, PyBool_Check(obj), "requires_grad must be a bool"); auto& var = *self->cdata; if (var.grad_fn) { const char *hint = ""; if (obj == Py_False) { hint = " If you want to use a computed variable in a subgraph " "that doesn't require differentiation use " "var_no_grad = var.detach()."; } THPUtils_setError("you can only change requires_grad flags of leaf variables.%s", hint); return -1; } var.requires_grad = obj == Py_True; auto grad_accumulator = var.grad_accumulator.lock(); if (grad_accumulator) { grad_accumulator->is_executable = var.requires_grad; } return 0; } PyObject *THPVariable_get_backwards_hooks(THPVariable *self) { if (self->backward_hooks) { Py_INCREF(self->backward_hooks); return self->backward_hooks; } Py_RETURN_NONE; } int THPVariable_set_backwards_hooks(THPVariable *self, PyObject *obj) { if (obj == Py_None) { obj = nullptr; } Py_XINCREF(obj); Py_XDECREF(self->backward_hooks); self->backward_hooks = obj; self->cdata->hooks.clear(); if (obj) { self->cdata->hooks.emplace_back(new PyFunctionPreHook(obj, 0)); } return 0; } static struct PyGetSetDef THPVariable_properties[] = { {"_version", (getter)THPVariable_get_version, NULL, NULL, NULL}, {"grad_fn", (getter)THPVariable_get_grad_fn, NULL, NULL, NULL}, {"_grad_fn", (getter)THPVariable_get_grad_fn, (setter)THPVariable_set_grad_fn, NULL, NULL}, {"is_leaf", (getter)THPVariable_is_leaf, NULL, NULL, NULL}, {"data", (getter)THPVariable_get_data, (setter)THPVariable_set_data, NULL, NULL}, {"_grad", (getter)THPVariable_get_raw_grad, (setter)THPVariable_set_raw_grad, NULL, NULL}, {"grad", (getter)THPVariable_get_grad, NULL, NULL, NULL}, {"volatile", (getter)THPVariable_get_volatile, (setter)THPVariable_set_volatile, NULL, NULL}, {"output_nr", (getter)THPVariable_get_output_nr, NULL, NULL, NULL}, {"requires_grad", (getter)THPVariable_get_requires_grad, (setter)THPVariable_set_requires_grad, NULL, NULL}, {"_backward_hooks", (getter)THPVariable_get_backwards_hooks, (setter)THPVariable_set_backwards_hooks, NULL, NULL}, {NULL} }; PyTypeObject THPVariableType = { PyVarObject_HEAD_INIT(NULL, 0) "torch._C._VariableBase", /* tp_name */ sizeof(THPVariable), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)THPVariable_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ NULL, /* tp_doc */ (traverseproc)THPVariable_traverse, /* tp_traverse */ (inquiry)THPVariable_clear, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, /* tp_members */ THPVariable_properties, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ THPVariable_pyinit, /* tp_init */ 0, /* tp_alloc */ THPVariable_pynew /* tp_new */ }; bool THPVariable_initModule(PyObject *module) { if (PyType_Ready(&THPVariableType) < 0) return false; Py_INCREF(&THPVariableType); PyModule_AddObject(module, "_VariableBase", (PyObject *)&THPVariableType); return true; }
31.694915
116
0.633079
054242955206ead560ad326fb37dc71c1ff853f4
245
rb
Ruby
lib/binance/authentication.rb
cyril/binance-connector-ruby
1d8ebeea2bed2c6540c5344edfe69d1ce01a073c
[ "MIT" ]
11
2021-11-26T19:21:45.000Z
2022-03-09T06:00:10.000Z
lib/binance/authentication.rb
tochki/binance-connector-ruby
855b7a1cf0873adb3c74074d69423f1f58525740
[ "MIT" ]
4
2021-11-19T12:35:21.000Z
2022-03-14T15:02:04.000Z
lib/binance/authentication.rb
tochki/binance-connector-ruby
855b7a1cf0873adb3c74074d69423f1f58525740
[ "MIT" ]
4
2022-01-20T12:05:23.000Z
2022-03-29T02:13:57.000Z
# frozen_string_literal: true module Binance # Authentication response to API key and signature class Authentication attr_accessor :key, :secret def initialize(key, secret) @key = key @secret = secret end end end
17.5
52
0.693878
5c8e8eb80363f2cf5013cf8f7c67273f0c0545e2
610
css
CSS
website/static/css/custom.css
disneystreaming/automated-cloud-advisor
eeb5d0547d06cd5c094a2314816bcff9479f79ef
[ "Apache-2.0" ]
97
2020-09-13T19:42:21.000Z
2022-03-20T04:56:06.000Z
website/static/css/custom.css
disneystreaming/automated-cloud-advisor
eeb5d0547d06cd5c094a2314816bcff9479f79ef
[ "Apache-2.0" ]
103
2020-09-13T18:02:55.000Z
2020-10-06T05:00:28.000Z
website/static/css/custom.css
disneystreaming/automated-cloud-advisor
eeb5d0547d06cd5c094a2314816bcff9479f79ef
[ "Apache-2.0" ]
9
2020-09-15T04:02:30.000Z
2022-03-02T15:49:29.000Z
@media only screen and (min-device-width: 360px) and (max-device-width: 736px) { /* overwrite */ } @media only screen and (min-width: 1024px) { /* overwrite */ } @media only screen and (max-width: 1023px) { /* overwrite */ } @media only screen and (min-width: 1400px) { /* overwrite */ } @media only screen and (min-width: 1500px) { /* overwrite */ } .imageAlignTop .blockImage { margin-bottom: 20px; max-width: 350px; } .homeContainer .homeWrapper { padding: 1em 5px; } .nav-footer { padding-bottom: 1.5em; padding-top: 1.5em; } .nav-footer .fbOpenSource { margin: 0 auto; }
18.484848
80
0.644262
e05f74d86bf907d56fe3658595e4485051bf10b8
3,354
lua
Lua
test/lua/unit/tokenizer.lua
AndreKR/rspamd
cdb9a9ad60ee2d1494ca3e0236d3debd7aca919e
[ "ECL-2.0" ]
null
null
null
test/lua/unit/tokenizer.lua
AndreKR/rspamd
cdb9a9ad60ee2d1494ca3e0236d3debd7aca919e
[ "ECL-2.0" ]
null
null
null
test/lua/unit/tokenizer.lua
AndreKR/rspamd
cdb9a9ad60ee2d1494ca3e0236d3debd7aca919e
[ "ECL-2.0" ]
null
null
null
context("Text tokenization test", function() local util = require "rspamd_util" local logger = require "rspamd_logger" test("Tokenize simple text", function() local cases = { {"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mattis, nibh", {"Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "Integer", "mattis", "nibh" } }, {"Հետաքրքրվողների համար ոտորև ներկայացված", {"Հետաքրքրվողների", "համար", "ոտորև", "ներկայացված"} }, {"", {}}, {",,,,,", {}}, {"word,,,,,word ", {"word", "word"}}, {"word", {"word"}}, {",,,,word,,,", {"word"}} } for _,c in ipairs(cases) do local w = util.tokenize_text(c[1]) if #c[2] == 0 then assert_equal(#w, 0, "must not have tokens " .. c[1]) else assert_not_nil(w, "must tokenize " .. c[1]) for i,wrd in ipairs(w) do assert_equal(wrd, c[2][i]) end end end end) test("Tokenize simple text (legacy)", function() local cases = { -- First token is bad {"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer mattis, nibh", {"orem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "Integer", "mattis", "nibh" } }, -- Unicode is broken --{"Հետաքրքրվողների համար ոտորև ներկայացված", -- {"Հետաքրքրվողների", "համար", "ոտորև", "ներկայացված"} --}, {"", {}}, {",,,,,", {}}, {"word,,,,,word ", {"ord", "word"}}, {"word", {"ord"}}, {",,,,word,,,", {"word"}} } for _,c in ipairs(cases) do local w = util.tokenize_text(c[1], {}, true) if #c[2] == 0 then assert_equal(#w, 0, "must not have tokens " .. c[1]) else assert_not_nil(w, "must tokenize " .. c[1]) for i,wrd in ipairs(w) do assert_equal(wrd, c[2][i]) end end end end) test("Tokenize with exceptions", function() local cases = { {"word https://example.com/path word", {{5, 24}}, {"word", "!!EX!!", "word"} }, {"համար https://example.com/path համար", {{11, 24}}, {"համար", "!!EX!!", "համար"} }, {"word https://example.com/path https://example.com/path word", {{5, 24}, {30, 24}}, {"word", "!!EX!!", "!!EX!!", "word"} }, {"word https://example.com/path https://example.com/path", {{5, 24}, {30, 24}}, {"word", "!!EX!!", "!!EX!!"} }, {"https://example.com/path https://example.com/path word", {{0, 24}, {25, 24}}, {"!!EX!!", "!!EX!!", "word"} }, {"https://example.com/path https://example.com/path", {{0, 24}, {25, 24}}, {"!!EX!!", "!!EX!!"} }, {",,,,https://example.com/path https://example.com/path ", {{4, 24}, {29, 24}}, {"!!EX!!", "!!EX!!"} }, } for _,c in ipairs(cases) do local w = util.tokenize_text(c[1], c[2]) if #c[3] == 0 then assert_equal(#w, 0, "must not have tokens " .. c[1]) else assert_not_nil(w, "must tokenize " .. c[1]) for i,wrd in ipairs(w) do assert_equal(wrd, c[3][i]) end end end end) end)
30.216216
87
0.473763
74aaeb6391e631ae8008e126465eb21830b5cf64
18,355
js
JavaScript
DateRangePicker.js
kizen/date-range-picker
8f494d4957d6e6e521ab0cdf03fda6a90370c976
[ "MIT" ]
null
null
null
DateRangePicker.js
kizen/date-range-picker
8f494d4957d6e6e521ab0cdf03fda6a90370c976
[ "MIT" ]
3
2020-04-06T18:09:19.000Z
2021-05-10T21:56:12.000Z
DateRangePicker.js
kizen/date-range-picker
8f494d4957d6e6e521ab0cdf03fda6a90370c976
[ "MIT" ]
null
null
null
import "./style.css"; import "./stylemods.css"; /* eslint-disable no-else-return */ /* eslint-disable no-unused-expressions */ /* eslint-disable react/sort-comp */ /* eslint-disable react/destructuring-assignment */ /* eslint-disable lines-between-class-members */ /* eslint-disable react/require-default-props */ /* eslint-disable react/static-property-placement */ import * as React from "react"; import PropTypes from "prop-types"; import classNames from "classnames"; import compose from "recompose/compose"; import _ from "lodash"; import { format, addDays, subDays, isBefore, isAfter, isSameDay, isSameMonth, addMonths, startOfISOWeek, endOfISOWeek, startOfWeek, endOfWeek, startOfMonth, endOfMonth, startOfYear, setYear, compareAsc } from "date-fns"; import IntlProvider, { defaultLocale } from "./IntlProvider"; import DatePicker from "./DatePicker"; import { defaultProps, prefix, createChainedFunction, withPickerMethods, setTimingMargin, TYPE } from "./utils"; import { PickerToggle, MenuWrapper, PickerToggleTrigger, getToggleWrapperClassName } from "./Picker"; import { PLACEMENT } from "./constants"; import QuickSelection from "./QuickSelection"; import range from "./range"; class DateRangePicker extends React.Component { static propTypes = { appearance: PropTypes.oneOf(["default", "subtle"]), value: PropTypes.arrayOf(PropTypes.instanceOf(Date)), defaultValue: PropTypes.arrayOf(PropTypes.instanceOf(Date)), defaultCalendarValue: PropTypes.arrayOf(PropTypes.instanceOf(Date)), defaultRange: PropTypes.arrayOf(PropTypes.instanceOf(Date)), format: PropTypes.string, disabled: PropTypes.bool, locale: PropTypes.object, hoverRange: PropTypes.oneOfType([ PropTypes.oneOf(["week", "month"]), PropTypes.func ]), isoWeek: PropTypes.bool, oneTap: PropTypes.bool, limitEndYear: PropTypes.number, className: PropTypes.string, menuClassName: PropTypes.string, classPrefix: PropTypes.string, container: PropTypes.oneOfType([PropTypes.node, PropTypes.func]), containerPadding: PropTypes.number, block: PropTypes.bool, toggleComponentClass: PropTypes.elementType, style: PropTypes.object, open: PropTypes.bool, defaultOpen: PropTypes.bool, placement: PropTypes.oneOf(PLACEMENT), preventOverflow: PropTypes.bool, showWeekNumbers: PropTypes.bool, onChange: PropTypes.func, onOk: PropTypes.func, disabledDate: PropTypes.func, onSelect: PropTypes.func, onOpen: PropTypes.func, onClose: PropTypes.func, onHide: PropTypes.func, onEnter: PropTypes.func, onEntering: PropTypes.func, onEntered: PropTypes.func, onExit: PropTypes.func, onExiting: PropTypes.func, onExited: PropTypes.func }; static defaultProps = { appearance: "default", placement: "bottomStart", limitEndYear: 1000, format: "MM/dd/yy", locale: defaultLocale, ranges: [ range.today, range.yesterday, range.thisMonth, range.last7Days, range.last30Days, range.thisYear, range.allTime, range.today ] }; static getDerivedStateFromProps(nextProps, prevState) { const { value } = nextProps; if (typeof value === "undefined") { return null; } if ( (value[0] && !isSameDay(value[0], prevState.value[0])) || (value[1] && !isSameDay(value[1], prevState.value[1])) ) { return { value, selectValue: value, calendarDate: this.getCalendarDate(value) }; } return null; } constructor(props) { super(props); const { defaultValue, value, defaultCalendarValue, defaultRange, ranges } = props; const defaultRangeIndex = ranges.findIndex(element => { return element.default; }); const defaultRangeValue = !!defaultRange ? defaultRange : defaultRangeIndex !== -1 ? ranges[defaultRangeIndex].value : null; const activeValue = value || defaultValue || defaultRangeValue || []; const calendarDate = this.getCalendarDate(value || defaultCalendarValue); this.state = { value: activeValue, selectValue: activeValue, doneSelected: true, calendarDate, hoverValue: [], currentHoverDate: null, selectedIndex: defaultRangeIndex !== -1 ? defaultRangeIndex : null, tempSelectedIndex: null }; // for test this.menuContainerRef = React.createRef(); this.triggerRef = React.createRef(); } getCalendarDate = (value = [], nextSelectedIndex = null) => { if (value[0] && value[1]) { if (this.isAllTime(nextSelectedIndex)) { console.log("IsAllTime"); return [value[1], addMonths(value[1], 1)]; } const sameMonth = isSameMonth(value[0], value[1]); return [value[0], sameMonth ? addMonths(value[1], 1) : value[1]]; } return [new Date(), addMonths(new Date(), 1)]; }; isAllTime = (nextSelectedIndex = null) => { const { selectedIndex } = this.state; const { ranges } = this.props; const allTimeRangeIndex = ranges.findIndex(element => { return element.isAllTime; }); return nextSelectedIndex !== null ? nextSelectedIndex === allTimeRangeIndex : selectedIndex === allTimeRangeIndex; }; getValue = () => { const { value } = this.props; if (typeof value !== "undefined") { return value; } return this.state.value || []; }; getDateString() { const { format: formatType, ranges } = this.props; const nextValue = this.getValue(); const selectedIndex = this.state.selectedIndex; const startDate = nextValue && nextValue[0]; const endDate = nextValue && nextValue[1]; if (startDate && endDate) { const displayValue = [startDate, endDate].sort(compareAsc); let matchingRange = null; if (selectedIndex) { matchingRange = ranges[selectedIndex]; } else { matchingRange = ranges.find(element => { return ( isSameDay(element.value[0], displayValue[0]) && isSameDay(element.value[1], displayValue[1]) ); }); } if (matchingRange && matchingRange.customPlaceholderLabel) { return matchingRange.customPlaceholderLabel; } return `${format(displayValue[0], formatType)} - ${format( displayValue[1], formatType )}`; } return ""; } // hover range presets getWeekHoverRange = date => { const { isoWeek } = this.props; if (isoWeek) { // set to the first day of this week according to ISO 8601, 12:00 am return [startOfISOWeek(date), endOfISOWeek(date)]; } return [startOfWeek(date), endOfWeek(date)]; }; getMonthHoverRange = date => [startOfMonth(date), endOfMonth(date)]; getHoverRange(date) { const { hoverRange } = this.props; if (!hoverRange) { return []; } let hoverRangeFunc = hoverRange; if (hoverRange === "week") { hoverRangeFunc = this.getWeekHoverRange; } if (hoverRangeFunc === "month") { hoverRangeFunc = this.getMonthHoverRange; } if (typeof hoverRangeFunc !== "function") { return []; } const hoverValues = hoverRangeFunc(date); const isHoverRangeValid = hoverValues instanceof Array && hoverValues.length === 2; if (!isHoverRangeValid) { return []; } if (isAfter(hoverValues[0], hoverValues[1])) { hoverValues.reverse(); } return hoverValues; } handleChangeCalendarDate = (index, date) => { const { calendarDate } = this.state; calendarDate[index] = date; this.setState({ calendarDate }); }; handleCloseDropdown = () => { if (this.triggerRef.current) { this.triggerRef.current.hide(); } }; handleOpenDropdown = () => { if (this.triggerRef.current) { this.triggerRef.current.show(); } }; handleClear = (value, closeOverlay, event) => { this.updateValue(event, value, closeOverlay, true); }; handleQuickSelection = (value, selectedIndex) => { this.setState({ selectValue: value, value: value, selectedIndex: selectedIndex, tempSelectedIndex: null }); this.handleCloseDropdown(); this.props.onOk && this.props.onOk(value, event); }; updateValue(event, nextSelectValue, closeOverlay = true) { const { value, selectValue } = this.state; const { onChange, ranges } = this.props; let nextValue = !_.isUndefined(nextSelectValue) ? nextSelectValue : selectValue; //Odd case where you can only select 1 value and right click out of selection to hit apply if (nextValue && nextValue[1] === undefined) { nextValue[1] = nextValue[0]; } //Remove any extra dates caused by not selecting if (nextValue.length > 2) { nextValue = nextValue.slice(0, 2); } if (isAfter(nextValue[0], nextValue[1])) { nextValue.reverse(); } setTimingMargin(nextValue[1], "right"); //Find if the selected values are in our ranges const rangeExistsIndex = ranges.findIndex(element => { const dates = element.value; return ( isSameDay(dates[0], nextValue[0]) && isSameDay(dates[1], nextValue[1]) ); }); this.setState({ selectValue: nextValue || [], value: nextValue, selectedIndex: rangeExistsIndex !== -1 ? rangeExistsIndex : null, tempSelectedIndex: null }); if ( onChange && (!isSameDay(nextValue[0], value[0]) || !isSameDay(nextValue[1], value[1])) ) { onChange(nextValue, event); } // `closeOverlay` default value is `true` if (closeOverlay !== false) { this.handleCloseDropdown(); } } handleOK = event => { this.updateValue(event); this.props.onOk && this.props.onOk(this.state.selectValue, event); }; handleChangeSelectValue = (date, event) => { //do some checking somewhere in here if it matches with a quick select option? const { selectValue, doneSelected, selectedIndex } = this.state; const { onSelect, oneTap, ranges } = this.props; let nextValue = []; let nextHoverValue = this.getHoverRange(date); if (doneSelected) { if (nextHoverValue.length) { nextValue = [nextHoverValue[0], nextHoverValue[1], date]; nextHoverValue = [nextHoverValue[0], nextHoverValue[1], date]; } else { nextValue = [date, undefined, date]; } } else { if (nextHoverValue.length) { nextValue = [selectValue[0], selectValue[1]]; } else { nextValue = [selectValue[0], date]; } if (isAfter(nextValue[0], nextValue[1])) { nextValue.reverse(); } nextValue[0] = setTimingMargin(nextValue[0]); nextValue[1] = setTimingMargin(nextValue[1], "right"); //Find if the selected values are in our ranges const rangeExistsIndex = ranges.findIndex(element => { const dates = element.value; return ( isSameDay(dates[0], nextValue[0]) && isSameDay(dates[1], nextValue[1]) ); }); this.setState({ selectedIndex, tempSelectedIndex: rangeExistsIndex, calendarDate: this.getCalendarDate(nextValue, rangeExistsIndex) }); } const nextState = { doneSelected: !doneSelected, selectValue: nextValue, hoverValue: nextHoverValue }; event.persist(); this.setState(nextState, () => { // 如果是单击模式,并且是第一次点选,再触发一次点击 if (oneTap && !this.state.doneSelected) { this.handleChangeSelectValue(date, event); } // 如果是单击模式,并且是第二次点选,更新值,并关闭面板 if (oneTap && this.state.doneSelected) { this.updateValue(event); } onSelect && onSelect(date, event); }); }; handleMouseMoveSelectValue = date => { const { doneSelected, selectValue, hoverValue, currentHoverDate } = this.state; const { hoverRange } = this.props; if (currentHoverDate && isSameDay(date, currentHoverDate)) { return; } const nextHoverValue = this.getHoverRange(date); if (doneSelected && !_.isUndefined(hoverRange)) { this.setState({ currentHoverDate: date, hoverValue: nextHoverValue }); return; } else if (doneSelected) { return; } let nextValue = selectValue; if (!nextHoverValue.length) { nextValue[1] = date; } else if (hoverValue) { nextValue = [ isBefore(nextHoverValue[0], hoverValue[0]) ? nextHoverValue[0] : hoverValue[0], isAfter(nextHoverValue[1], hoverValue[1]) ? nextHoverValue[1] : hoverValue[1], nextValue[2] ]; } // If `nextValue[0]` is greater than `nextValue[1]` then reverse order if (isAfter(nextValue[0], nextValue[1])) { nextValue.reverse(); } this.setState({ currentHoverDate: date, selectValue: nextValue }); }; handleEnter = () => { const value = this.getValue(); this.setState({ selectValue: value, calendarDate: this.getCalendarDate(value), active: true }); }; handleEntered = () => { this.props.onOpen && this.props.onOpen(); }; handleExit = () => { this.setState({ active: false, doneSelected: true, tempSelectedIndex: null }); this.props.onClose && this.props.onClose(); }; disabledByBetween(start, end, type) { const { disabledDate } = this.props; const { selectValue, doneSelected } = this.state; const selectStartDate = selectValue[0]; const selectEndDate = selectValue[1]; const nextSelectValue = [selectStartDate, selectEndDate]; // If the date is between the start and the end // the button is disabled while (isBefore(start, end) || isSameDay(start, end)) { if ( disabledDate && disabledDate(start, nextSelectValue, doneSelected, type) ) { return true; } start = addDays(start, 1); } return false; } disabledOkButton = () => { const { selectValue, doneSelected } = this.state; if (!selectValue[0] || !selectValue[1] || !doneSelected) { return true; } return this.disabledByBetween( selectValue[0], selectValue[1], TYPE.TOOLBAR_BUTTON_OK ); }; disabledShortcutButton = (value = []) => { if (!value[0] || !value[1]) { return true; } return this.disabledByBetween(value[0], value[1], TYPE.TOOLBAR_SHORTCUT); }; handleDisabledDate = (date, values, type) => { const { disabledDate } = this.props; const { doneSelected } = this.state; if (disabledDate) { return disabledDate(date, values, doneSelected, type); } return false; }; addPrefix = name => prefix(this.props.classPrefix)(name); renderDropdownMenu() { const { menuClassName, ranges, isoWeek, limitEndYear, showWeekNumbers } = this.props; const { calendarDate, selectValue, hoverValue, doneSelected } = this.state; const classes = classNames(this.addPrefix("daterange-menu"), menuClassName); const pickerProps = { isoWeek, doneSelected, hoverValue, calendarDate, limitEndYear, showWeekNumbers, value: selectValue, disabledDate: this.handleDisabledDate, onSelect: this.handleChangeSelectValue, onMouseMove: this.handleMouseMoveSelectValue, onChangeCalendarDate: this.handleChangeCalendarDate }; return ( <MenuWrapper className={classes} ref={this.menuContainerRef}> <div className={this.addPrefix("daterange-panel")}> <div className={classNames( this.addPrefix("daterange-content"), "kizen-daterange-content" )} > <div className="kizen-quick-selection-container"> <div className="kizen-quick-selection-header"> Quick Selection </div> <QuickSelection ranges={ranges} selectValue={selectValue} disabledShortcutButton={this.disabledShortcutButton} onShortcut={this.handleQuickSelection} selectedIndex={this.state.selectedIndex} tempSelectedIndex={this.state.tempSelectedIndex} /> </div> <div className={this.addPrefix("daterange-calendar-group")}> <DatePicker index={0} {...pickerProps} /> <DatePicker index={1} {...pickerProps} /> </div> </div> <div className="kizen-daterangepicker-toolbar"> <button className="applyButton" type="button" onClick={this.handleOK} > Apply </button> </div> </div> </MenuWrapper> ); } render() { const { disabled, locale, toggleComponentClass, style, onEntered, onEnter, onExited, dropdownTrigger } = this.props; const value = this.getValue(); const hasValue = value && value.length > 1; const classes = getToggleWrapperClassName( "daterange", this.addPrefix, this.props, hasValue ); return ( <IntlProvider locale={locale}> <div className={classes} style={style}> <PickerToggleTrigger pickerProps={this.props} ref={this.triggerRef} onEnter={createChainedFunction(this.handleEnter, onEnter)} onEntered={createChainedFunction(this.handleEntered, onEntered)} onExit={createChainedFunction(this.handleExit, onExited)} speaker={this.renderDropdownMenu()} > <PickerToggle componentClass={toggleComponentClass} hasValue={hasValue} active={this.state.active} > {this.getDateString()} </PickerToggle> </PickerToggleTrigger> </div> </IntlProvider> ); } } const enhance = compose( defaultProps({ classPrefix: "picker" }), withPickerMethods() ); export default enhance(DateRangePicker);
26.410072
94
0.614928
dc181897c8f549f91dbcbb8991534b44fd744bca
9,839
py
Python
lib/copy.py
KaueGuimaraes/Translator-train
72d6b901b3a15aa48b8dc4f2e2af011ec6944979
[ "MIT" ]
null
null
null
lib/copy.py
KaueGuimaraes/Translator-train
72d6b901b3a15aa48b8dc4f2e2af011ec6944979
[ "MIT" ]
null
null
null
lib/copy.py
KaueGuimaraes/Translator-train
72d6b901b3a15aa48b8dc4f2e2af011ec6944979
[ "MIT" ]
null
null
null
LISTA = [['add', ['adicionar'], 'added', 'added'], ['arise', ['erguer', 'levantar'], 'arose', 'arisen'], ['awake', ['acordar', 'despertar'], 'awoke', 'awoken'], ['answer', ['responder'], 'answered', 'answered'], ['ask', ['perguntar'], 'asked', 'asked'], ['be', ['ser', 'estar'], 'was-were', 'been'], ['bear', ['suportar', 'aguentar'], 'bore', 'borne'], ['beat', ['bater', 'espancar', 'superar', 'vibrar', 'palpitar'], 'beat', 'beaten'], ['become', ['tornar-se'], 'became', 'become'], ['begin', ['comecar', 'iniciar'], 'began', 'begun'], ['bend', ['curvar', 'entortar'], 'bent', 'bent'], ['bet', ['apostar'], 'bet', 'bet'], ['bite', ['morder', 'engolir-a-isca'], 'bit', 'bitten'], ['bring', ['trazer', 'servir'], 'brought', 'brought'], ['bleed', ['sangrar'], 'bled', 'bled'], ['blow', ['soprar', 'assobiar'], 'blew', 'blown'], ['break', ['quebrar', 'romper'], 'broke', 'broken'], ['build', ['construir', 'fabricar'], 'built', 'built'], ['burn', ['queimar', 'incendiar'], 'burnt', 'burnt'], ['buy', ['comprar'], 'bought', 'bought'], ['call', ['chamar', 'ligar'], 'called', 'called'], ['can', ['poder'], 'could', ''], ['cast', ['arremessar', 'jogar'], 'cast', 'cast'], ['carry', ['carregar'], 'carried', 'carried'], ['catch', ['pegar', 'adquirir'], 'caught', 'caught'], ['change', ['mudar'], 'changed', 'changed'], ['choose', ['escolher', 'selecionar'], 'chose', 'chosen'], ['close', ['fechar'], 'closed', 'closed'], # ['come', ['vir'], 'came', 'come'], ['cost', ['custar'], 'cost', 'cost'], ['cover', ['cobrir'], 'covered', 'covered'], ['cry', ['chorar'], 'cried', 'cried'], ['cut', ['cortar'], 'cut', 'cut'], ['deal', ['distribuir', 'negociar'], 'dealt', 'dealt'], ['dig', ['cavar', 'escavar'], 'dug', 'dug'], ['do', ['fazer'], 'did', 'done'], ['draw', ['desenhar', 'extrair'], 'drew', 'drawn'], ['drink', ['beber'], 'drank', 'drunk'], ['drive', ['dirigir'], 'drove', 'driven'], ['dry', ['secar'], 'dried', 'dried'], ['eat', ['comer'], 'ate', 'eaten'], ['end', ['acabar'], 'ended', 'ended'], ['explain', ['explicar'], 'explained', 'explained'], ['fall', ['cair', 'diminuir', 'decrescer'], 'fell', 'fallen'], ['feel', ['sentir', 'notar'], 'felt', 'felt'], ['fight', ['lutar', 'brigar'], 'fought', 'fought'], ['fill', ['encher', 'preencher'], 'filled', 'filled'], ['find', ['encontrar', 'achar'], 'found', 'found'], ['fly', ['voar'], 'flew', 'flown'], ['follow', ['seguir'], 'followed', 'followed'], ['forbid', ['proibir'], 'forbade', 'forbidden'], ['forget', ['esquecer-se'], 'forgot', 'forgotten'], ['forgive', ['perdoar'], 'forgave', 'forgiven'], ['forsake', ['abandonar', 'deserdar'], 'forsook', 'forsaken'], ['freeze', ['congelar'], 'froze', 'frozen'], ['get', ['pegar', 'obter', 'conseguir'], 'got', 'got'], ['give', ['dar'], 'gave', 'given'], ['go', ['ir'], 'went', 'gone'], ['feed', ['alimentar', 'nutrir'], 'fed', 'fed'], # ['grow', ['crescer', 'florescer'], 'grew', 'grown'], ['hang', ['pendurar', 'suspender'], 'hung', 'hung'], ['happen', ['acontecer'], 'happened', 'happened'], ['have', ['ter'], 'had', 'had'], ['hear', ['ouvir', 'escutar'], 'heard', 'heard'], ['help', ['ajudar'], 'helped', 'helped'], ['hide', ['esconder-se', 'ocultar'], 'hid', 'hidden'], ['hit', ['bater', 'chocar-se'], 'hit', 'hit'], ['hold', ['segurar', 'agarrar'], 'held', 'held'], ['hurt', ['machucar'], 'hurt', 'hurt'], ['keep', ['manter', 'preservar'], 'kept', 'kept'], ['kneel', ['ajoelhar-se'], 'knelt', 'knelt'], ['knit', ['tricotar'], 'knit', 'knit'], ['know', ['saber', 'conhecer'], 'knew', 'known'], ['lay', ['por', 'colocar', 'deitar'], 'laid', 'laid'], ['lead', ['conduzir', 'liderar'], 'led', 'led'], ['leap', ['saltar', 'pular'], 'leapt', 'leapt'], ['learn', ['aprender'], 'learnt', 'learnt'], ['leave', ['deixar', 'partir'], 'left', 'left'], ['lend', ['emprestar'], 'lent', 'lent'], ['let', ['deixar', 'permitir'], 'let', 'let'], ['lie', ['deitar'], 'lay', 'lain'], ['light', ['acender', 'iluminar'], 'lit', 'lit'], ['like', ['gostar'], 'liked', 'liked'], ['listen', ['escutar'], 'listened', 'listened'], ['live', ['viver'], 'lived', 'lived'], ['look', ['olhar'], 'looked', 'looked'], ['lose', ['perder'], 'lost', 'lost'], ['love', ['amar'], 'loved', 'loved'], ['make', ['fazer', 'produzir'], 'made', 'made'], # ['may', ['poder'], 'might', ''], ['mean', ['significar'], 'meant', 'meant'], ['meet', ['encontrar', 'reunir'], 'met', 'met'], ['move', ['mover'], 'moved', 'moved'], ['need', ['precisar'], 'needed', 'needed'], ['open', ['abrir'], 'opened', 'opened'], ['pay', ['pagar'], 'paid', 'paid'], ['plan', ['planejar'], 'planned', 'planned'], ['play', ['jogar', 'tocar', 'brincar'], 'played', 'played'], ['pull', ['puxar'], 'pulled', 'pulled'], ['put', ['colocar'], 'put', 'put'], ['quit', ['desistir', 'abandonar'], 'quit', 'quit'], ['read', ['ler'], 'read', 'read'], ['remember', ['lembrar'], 'remembered', 'remembered'], ['ride', ['cavalgar', 'andar-de-bike', 'andar-de-carro'], 'rode', 'ridden'], ['ring', ['soar', 'tocar-campainha'], 'rang', 'rung'], ['rise', ['erguer-se', 'levantar-se'], 'rose', 'risen'], ['run', ['correr'], 'ran', 'run'], ['saw', ['serrar'], 'sawed', 'sawn'], ['say', ['dizer'], 'said', 'said'], ['see', ['ver'], 'saw', 'seen'], ['seem', ['parecer'], 'seemed', 'seemed'], ['seek', ['procurar', 'pedir', 'almejar'], 'sought', 'sought'], ['sell', ['vender'], 'sold', 'sold'], ['set', ['por', 'ajustar'], 'set', 'set'], ['sew', ['costurar'], 'sewed', 'sewn'], ['shake', ['sacudir', 'agitar', 'apertar-a-mao'], 'shook', 'shaken'], ['shave', ['barbear'], 'shaved', 'shaved'], ['shine', ['brilhar'], 'shone', 'shone'], ['shoot', ['atirar', 'ferir-com-tiro'], 'shot', 'shot'], # ['show', ['mostrar', 'atirar'], 'showed', 'show'], ['shred', ['picar', 'retalhar', 'rasgar', 'cortar-em-pedacos'], 'shred', 'shred'], ['shrink', ['contrair', 'encolher'], 'shrank', 'shrunk'], ['shut', ['tampar', 'cerrar', 'fechar'], 'shut', 'shut'], ['sing', ['cantar'], 'sang', 'sung'], ['sink', ['afundar'], 'sank', 'sunk'], ['sit', ['sentar-se'], 'sat', 'sat'], ['slay', ['matar', 'assassinar', 'arruinar', 'destruir'], 'slew', 'slain'], ['sleep', ['dormir'], 'slept', 'slept'], ['slide', ['deslizar', 'escorregar'], 'slid', 'slid'], ['smell', ['cheirar'], 'smelt', 'smelt'], ['sow', ['semear'], 'sowed', 'sown'], ['speak', ['falar', '(mododefalar)'], 'spoke', 'spoken'], ['spell', ['soletrar'], 'spelt', 'spelt'], ['spend', ['gastar-dinheiro', 'gastar-tempo'], 'spent', 'spent'], ['spill', ['derramar'], 'spilt', 'spilt'], ['spin', ['girar'], 'spun', 'spun'], ['spoil', ['estragar', 'destruir', 'mimar'], 'spoilt', 'spoilt'], ['spread', ['espalhar', 'estender'], 'spread', 'spread'], ['spring', ['saltar', 'lancar-se'], 'sprang', 'sprung'], ['stand', ['por-se-de-pe'], 'stood', 'stood'], ['start', ['comecar'], 'started', 'started'], ['stay', ['ficar'], 'stayed', 'stayed'], ['steal', ['roubar'], 'stole', 'stolen'], ['stick', ['fincar', 'cravar'], 'stuck', 'stuck'], ['sting', ['picar', 'ferroar'], 'stung', 'stung'], ['stink', ['enjoar', 'feder'], 'stank', 'stunk'], ['stop', ['parar'], 'stopped', 'stopped'], ['strick', ['bater', 'golpear'], 'struck', 'struck'], # ['string', ['amarrar', 'pendurar', 'enfiar'], 'strung', 'strung'], ['strive', ['aspirar', 'tentar', 'esforcar'], 'strove', 'striven'], ['study', ['estudar'], 'studied', 'studied'], ['swear', ['jurar'], 'swore', 'sworn'], ['sweat', ['suar'], 'sweat', 'sweat'], ['sweep', ['varrer'], 'swept', 'swept'], ['swell', ['inchar', 'crescer', 'encher-pneus'], 'swelled', 'swollen'], ['swin', ['nadar'], 'swan', 'swun'], ['swing', ['balancar'], 'swang', 'swung'], ['take', ['pegar', 'levar', 'tomar'], 'toke', 'taken'], ['talk', ['conversar'], 'talked', 'talked'], ['teach', ['ensinar'], 'taught', 'taught'], ['tear', ['lacrimejar'], 'tore', 'torn'], ['tell', ['contar'], 'told', 'told'], ['think', ['achar', 'pensar'], 'thought', 'thought'], ['thrive', ['ter-sucesso'], 'throve', 'thriven'], ['throw', ['lancar', 'atirar'], 'threw', 'thrown'], ['thrust', ['empurrar'], 'thrust', 'thrust'], ['travel', ['viajar'], 'traveled', 'traveled'], ['try', ['tentar'], 'tried', 'tried'], ['turn', ['girar'], 'turned', 'turned'], ['understand', ['entender', 'compreender'], 'understood', 'understood'], ['use', ['usar'], 'used', 'used'], ['wait', ['esperar'], 'waited', 'waited'], ['wake', ['acordar'], 'woke', 'woken'], ['walk', ['andar', 'caminhar'], 'walked', 'walked'], ['want', ['querer'], 'wanted', 'wanted'], ['watch', ['assistir'], 'watched', 'watched'], ['wear', ['vestir', 'usar', 'trajar'], 'wore', 'worn'], ['weave', ['lancar', 'tecer'], 'wove', 'woven'], # ['win', ['ganhar', 'vencer'], 'won', 'won'], ['wind', ['girar', 'enrolar-se'], 'wound', 'wound'], ['work', ['trabalhar'], 'worked', 'worked'], ['write', ['ecrever'], 'wrote', 'written'], ['wring', ['torcer'], 'wrung', 'wrung'],] # PASTE YOUR LIST HERE # 0 = palavra 1 = traduções 2 = passado 3 = particípio def get(): return LISTA
83.381356
148
0.477792
e756234afd639ae525203c20c8eedec68d3989ca
47,834
js
JavaScript
etc/withnode/learn.js
taroyanaka/JavaScript
637fa6c546a94aa1fac22a89cf48382251c13a88
[ "MIT" ]
null
null
null
etc/withnode/learn.js
taroyanaka/JavaScript
637fa6c546a94aa1fac22a89cf48382251c13a88
[ "MIT" ]
21
2020-07-16T16:11:48.000Z
2022-01-08T15:06:12.000Z
etc/withnode/learn.js
taroyanaka/javascript
c100e5ac18dc93d03b8130051fdf6283baecbe28
[ "MIT" ]
null
null
null
const R = require('ramda'); const RA = require('ramda-adjunct'); const R_ = require('ramda-extension'); // // const _ = require('underscore'); // function showAZ() { // console.log("a: "); // console.dir(a); // console.log("b: "); // console.dir(b); // console.log("c: "); // console.dir(c); // console.log("d: "); // console.dir(d); // console.log("e: "); // console.dir(e); // console.log("f: "); // console.dir(f); // console.log("g: "); // console.dir(g); // console.log("h: "); // console.dir(h); // console.log("i: "); // console.dir(i); // console.log("j: "); // console.dir(j); // console.log("k: "); // console.dir(k); // console.log("l: "); // console.dir(l); // console.log("m: "); // console.dir(m); // console.log("n: "); // console.dir(n); // console.log("o: "); // console.dir(o); // console.log("p: "); // console.dir(p); // console.log("q: "); // console.dir(q); // console.log("r: "); // console.dir(r); // console.log("s: "); // console.dir(s); // console.log("t: "); // console.dir(t); // console.log("u: "); // console.dir(u); // console.log("v: "); // console.dir(v); // console.log("w: "); // console.dir(w); // console.log("x: "); // console.dir(x); // console.log("y: "); // console.dir(y); // console.log("z: "); // console.dir(z); // } // // let chars = "abc"; // // const toUpperCaseFirstChar = str => { // // let remainChars = ""; // // for (let i = 1; i < str.length; i++) { // // // remainChars = remainChars += str[i]; // // remainChars += str[i]; // // } // // return str[0].toUpperCase() + remainChars // // } // // console.log(toUpperCaseFirstChar(chars)); // => "Abc" // // var 123; // // console.log(foo); // // const sample = () => { // // 100; // // console.log(foo); // // } // // sample(); // // let bar = 456; // // const sample2 = () => { // // console.log(bar); // // bar = 789; // // } // // sample2(); // // console.log(bar); // let a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z; // // ramda.js samples // a = R.sortBy(R.prop(1))([ // [10, 1], // [5, 2], // [2.5, 3], // ]); // b = R.pipe(R.sortBy(R.prop(1)), R.reverse)([ // [10, 1], // [5, 2], // [2.5, 3] // ]); // c = R.sortBy(R.prop(1))([ // [10, 1], // [5, 2], // [2.5, 3] // ]); // d = R.sortBy(R.prop('name'))([{ // name: "Taro", // age: 28 // }, { // name: "Blue", // age: 30 // }, { // name: "Aka", // age: 24 // }]); // // e = R.sortBy(R.prop('age'))([{ // e = R.pipe(R.sortBy(R.prop('age'), R.__), R.reverse)([{ // name: "Taro", // age: 28 // }, { // name: "Blue", // age: 30 // }, { // name: "Aka", // age: 24 // }]); // var albums = [{ // title: "Sabbath Bloody Sabbath", // genre: "Metal" // }, // { // title: "Scientist", // genre: "Dub" // }, // { // title: "Undertow", // genre: "Metal" // } // ]; // var dub = { // title: "Scientist", // genre: "Dub" // } // f = R.groupBy(R.prop('genre'))(albums); // g = R.countBy(R.prop('genre'))(albums); // var nums = [ // [1, 2], // [3, 4], // [5, 6] // ]; // h = R.reduce(R.concat, [], [ // [1, 2], // [3, 4], // [5, 6] // ]); // i = R.pluck(0)([ // [1, 2], // [3, 4] // ]); // j = R.pluck('title')(albums); // k = R.keys(dub); // l = R.values(dub); // m = R.map([ // ['name', 'number'], // ['Taro', 32] // ]); // n = R.invert({ // first: 'alice', // second: 'jake', // third: 'alice', // }); // const pred = R.where({ // a: R.equals('foo'), // b: R.complement(R.equals('bar')), // x: R.gt(R.__, 10), // y: R.lt(R.__, 20) // }); // o = pred({ // a: 'foo', // b: 'xxx', // x: 11, // y: 19 // }); // //=> true; // //pred({a: 'xxx', b: 'xxx', x: 11, y: 19});//=> false; // //pred({a: 'foo', b: 'bar', x: 11, y: 19});//=> false; // //pred({a: 'foo', b: 'xxx', x: 10, y: 19});//=> false; // //pred({a: 'foo', b: 'xxx', x: 11, y: 20});//=> false; // //R.zipObj() // //R.reduce(R.concat, [], [[1, 2], [3, 4], [5, 6]]); // let obj = { // first: 'alice', // second: 'jake', // third: 'alice', // } // p = R.keys(R.invert(obj)) // q = R.omit(['a', 'c'], { // a: 1, // b: 2, // c: 3 // }); // //R.invertObj([1,2]) // const isNotNil = R.complement(R.isNil); // r = R.isNil(null); // //=> true; // s = isNotNil(null); // //=> false; // t = R.where({ // a: R.equals('foo'), // b: R.complement(R.equals('bar')), // x: R.gt(R.__, 10), // y: R.lt(R.__, 20) // }, R.__)({ // a: 'foo', // b: 'xxx', // x: 11, // y: 19 // }) // const log = R.bind(console.log, console); // // R.pipe(R.assoc('a', 2), R.tap(log), R.assoc('a', 3))({ // // a: 1 // // }); // u = R.assoc('a', 3, { // a: 1, // b: 2 // }); // //=> {a: 3, b: 2} // v = R.pick(['a', 'b', 'e', 'f'], { // a: 1, // b: 2, // c: 3, // d: 4 // }); // //=> {"a": 1, "b": 2}; // w = R.pluck('a', { // a: 1, // b: 2, // c: 3, // d: 4 // }); // //=> {"a": 1, "b": 2}; // x = R.pluck('val', { // a: { // val: 3 // }, // b: { // val: 5 // } // }); // y = R.pluck('name', [{ // name: 'fred', // age: 29 // }, { // name: 'wilma', // age: 27 // }]); // // alias R.pluck('',[]) is R.map(R.prop())([]) // z = R.map(R.prop('name'))([{ // name: 'fred', // age: 29, // sex: 'male', // }, { // name: 'wilma', // age: 27, // sex: 'female', // }]); // foo = R.map(((x) => x * 2))([1, 2]); // foo = R.map(R.pick(['a', 'b', 'e']))([{ // a: 1, // b: 2, // c: 3, // d: 4 // }, { // a: 3, // b: 4, // c: 5, // d: 6 // }]) // foo; // // map with reduce and map and map // // ary = [ // // ["foo", 1, ["bar", 2, 3]], // // ["foo2", 10, ["bar2", 20, 30]], // // ] // // let mapWithReduce = ary.map(V => { // // let V2 = V[2].reduce((all, one) => { // // return all + " and " + one.toString(); // // }) // // return `${V[0]} and ${V[1].toString()}, ${V2}` // // }) // // console.log(mapWithReduce); // // ary = [ // // ["foo", 1, [ // // [2, 3], // // [4, 5], // // [6, 7] // // ]], // // ["foo2", 10, [ // // [2, 3], // // [4, 5], // // [6, 7] // // ]], // // ] // // let mapWithMap = ary.map(V => { // // let V2 = V[2].map(V2 => { // // return V2[0] + V2[1] // // }) // // return `${V[0]} and ${V[1].toString()}, ${V2.join("-").toString()}` // // }) // // console.log(mapWithMap); // // "map with reduce and map and map".split(" ").map(V => { // // let chars = V.split() // // let head = chars.splice(0, 1)[0] // // // head = head.toUpperCase(); // // h = head.toUpperCase(); // // chars.splice(0, 0, h); // // return chars.join(",") // // }) //.join(); // // console.log(foo); // // console.log([1, 2, 3].concat([4, 5, 6])); // => [ 1, 2, 3, 4, 5, 6 ] // // ary1 = [1, 2, 3, 4, 5, 6]; // // ary1.splice(ary1.length, 0, ["foo", "bar"]); // // console.log(ary1); // => [ 1, 2, 3, 4, 5, 6, [ 'foo', 'bar' ] ] // // ary1.splice(-1, 1); // // console.log(ary1); // // ary1 = [1, 2, 3, 4, 5, 6, ["foo", "bar"]]; // // ary2 = [] // // while (ary1.length !== 0) { // // ary2.splice(ary2.length, 0, ary1.splice(0, 2)) // // } // // console.log(ary1); // // console.log(ary2); // // ary1 = [1, 2, 3, 4, 5, 6, ["foo", "bar"]].reverse(); // // ary2 = [] // // while (ary1.length !== 0) { // // ary2.splice(ary2.length, 0, ary1.splice(0, 2)) // // } // // console.log(ary1); // // console.log(ary2); // => [ [ [ 'foo', 'bar' ], 6 ], [ 5, 4 ], [ 3, 2 ], [ 1 ] ] // // ary1 = [1, 2, 3, 4, 5, 6, ["foo", "bar"]].reverse(); // // ary2 = [] // // while (ary1.length !== 0) { // // ary2.splice(0, 0, ary1.splice(0, 2)) // // } // // console.log(ary1); // // console.log(ary2); // => [ [ 1 ], [ 3, 2 ], [ 5, 4 ], [ [ 'foo', 'bar' ], 6 ] ] // // console.log(ary2); // => [ [ 1 ], [ 3, 2 ], [ 5, 4 ], [ [ 'foo', 'bar' ], 6 ] ] // // console.log(require('ramda').flatten(ary2)); // // flat and fullflat a.k.a flatten function // // reference from https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#reduce_%E3%81%A8_concat // // unFlattenAry = [1, 2, [3, 4, [5, 6]]]; // // const flat = (array) => { // // return array.reduce((acc, val) => acc.concat(val), []) // // }; // // console.log(flat(unFlattenAry)); // => [ 1, 2, 3, 4, [ 5, 6 ] ] // // const fullFlat = ary => { // // while (ary.some(V => Array.isArray(V))) { // // ary = flat(ary) // // } // // return ary; // // } // // console.log(fullFlat(unFlattenAry)); // => [ 1, 2, 3, 4, 5, 6 ] // // console.log([1, 2, ["foo", "bar"], 3].some(V => Array.isArray(V))); // // console.log([1, 2, ["foo", "bar"], 3].some(V => Array.isArray(V))); // // Map does not replace filter // // console.log([1, 2, 3].filter(V => V == 2)); // => [ 2 ] // // console.log([1, 2, 3].map(V => { // // if (V == 2) { // // return V // // } // // })); // => [ undefined, 2, undefined ] // // use map dont use forEach // // longer // // ary1 = [ // // [1, 2], // // [3, 4], // // [5, 6] // // ] // // ary2 = [] // // ary1.forEach(V => { // // ary2.splice(ary2.length, 0, [V[0], V[1] * 2]) // // }) // // console.log(ary2) // => [ [ 1, 4 ], [ 3, 8 ], [ 5, 12 ] ] // // // shorter // // ary1 = [ // // [1, 2], // // [3, 4], // // [5, 6] // // ] // // ary2 = ary1.map(V => { // // return [V[0], V[1] * 2] // // }); // // console.log(ary2) // => [ [ 1, 4 ], [ 3, 8 ], [ 5, 12 ] ] // // // forEach is same with map in console.log // // ary1 = [ // // [1, 2], // // [3, 4], // // [5, 6] // // ] // // ary1.forEach(V => { // // console.log(V); // => [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ] // // }) // // ary1.map(V => { // // console.log(V); // => [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ] // // }) // // console.log("------"); // // // forEach is not same with map in return // // ary1 = [ // // [1, 2], // // [3, 4], // // [5, 6] // // ] // // ary2 = ary1.forEach(V => { // // return V // // }) // // console.log(ary2); // => undefined // // ary2 = ary1.map(V => { // // return V // // }) // // console.log(ary2); // => [ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ] // // console.log([1, 2, 3].map(V => { if (V == 2) { V } }) // // https://qiita.com/jkr_2255/items/62b3ee3361315d55078a // // const testFunc = async () => { // // for(let item of arr) await sleptLog(item); // // console.log('done!') // // }; // // const testFunc = async () => { // // await Promise.all(arr.map(async item => await sleptLog(item))) // // console.log('done!') // // }; // // const fetch = require("node-fetch"); // // const simpleCrawler = (url = "https://www.yahoo.co.jp/") => { // // let target = []; // // fetch(url) // // .then(res => res.text()) // // .then(text => new DOMParser().parseFromString(text, "text/html")) // // .then(doc => { // // doc.querySelectorAll('a') // // .forEach(aElm => { target.push([aElm.innerText, aElm.href]) }) // // }); // // return target // // } // // simpleCrawler(); // // const request = require('request'); // // //const HTMLParser = require('fast-html-parser'); // // const HTMLParser = require('htmlparser2'); // // request('https://www.yahoo.co.jp/', (error, response, body) => { 'body:', // // HTMLParser.parse(body) // // .querySelectorAll('a') // // // .forEach(aElm => { console.log(aElm.textContent) }) // // }); // // [1, 2, 3].forEach(v => { console.log(v) }); // // const request = require('request'); let []; // // const HTMLParser = require('fast-html-parser'); // // request('https://www.yahoo.co.jp/', (error, response, body) => { // // 'body:', // // HTMLParser.parse(body) // // .querySelectorAll('a') // // }); // // Array.from(foo).forEach(v => { console.log(v) }); // // // const bar = Array.from(foo); // // // bar.forEach(v => { console.log(v) }); // // const request = require('request'); // // const HTMLParser = require('fast-html-parser'); // // const req = (url = 'https://www.yahoo.co.jp/') => { // // return new Promise((resolve, reject) => { // // request(url, (error, response, body) => { // // resolve(body); // // }); // // }); // // } // // function foo(bar) { // // bar += 1 // // return bar // // } // // function hoge("bar") { // // return foo // // } // // // VS codeのAdd jsdoc commentsというpluginでJSDocを生成 // // // const namedArgumentFunc = ... =>{...} の形式で関数定義するとAdd jsdoc comments不可(対応してほしい...) // // /** // // * @param {string} {foo='bar' random.number // // * @param {string} baz=200 random.word // // * @param {boolean} qux=false}={} random.boolean // // * @returns {string} `a=${foo}, b=${baz}, c=${qux}` // // * @example // // namedArgumentFunc({ // // qux: false, // // foo: 'content.html', // // }) // // * // returns {string} 'a=content.html, b=200, c=false' // // */ // // function namedArgumentFunc({ // // 'bar', // // baz = 200, // // qux = false // // } = {}) { // // return `a=${foo}, b=${baz}, c=${qux}`; // // } // // require("assert").equal( // // namedArgumentFunc({ // // qux: false, // // foo: 'content.html', // // }), 'a=content.html, b=200, c=false' // // ) // // for (let i = 0; i <= 100; i++) { // // arg0 = require("faker").random.number(); // // arg1 = require('faker').random.word(); // // arg2 = require('faker').random.boolean(); // // res = `a=${arg0}, b=${arg1}, c=${arg2}` // // require('assert').equal( // // namedArgumentFunc({ // // foo: arg0, // // baz: arg1, // // qux: arg2, // // }), // // res, // // console.log("ok!") // // ) // // } // // require("assert").equal( // // namedArgumentFunc({ // // qux: false, // // foo: 'content.html', // // }), 'a=content.html, b=200, c=false' // // ) // // const (bar) => { // // return "bar" // // } // // require('assert').equal( // // foo("bar"), // // "bar", // // console.log(`test is clear`) // // ) // // const assert = require('assert').strict; // // assert.ok(true); // // console.log(require("ramda").add(2, 3)); // // // const assert = require('assert'); // // require('assert').ok(/^hello/.test('hello world!')); // // var http = require('http'), // // vm = require('vm'), // // concat = require('concat-stream'); // this is just a helper to receive the // // // http payload in a single callback // // // see https://www.npmjs.com/package/concat-stream // // http.get({ // // host: "https://rawgit.com", // // port: 80, // // path: '/Marak/faker.js/master/examples/browser/js/faker.js' // // }, // // function (res) { // // res.setEncoding('utf8'); // // res.pipe(concat({ // // encoding: 'string' // // }, function (remoteSrc) { // // vm.runInThisContext(remoteSrc, 'remote_modules/faker.js'); // // })); // // }); // // email regexp https://qiita.com/sakuro/items/1eaa307609ceaaf51123 // // node.js assert http://sucrose.hatenablog.com/entry/20120304/p1 // // faker.js https://github.com/Marak/faker.js/tree/master/build/build // // require('assert').ok( // // // check true // // /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/ // // .test( // // require("faker").internet.email() // // ), // // console.log(`test is clear`) // // ); // // [1, 2, 3].forEach(currentItem => { // // console.log(currentItem); // // }); // // console.log() // // var regex1 = RegExp('foo*'); // // var regex2 = RegExp('foo*', 'g'); // // var str1 = 'table football'; // // console.log(/^hello/.test('hello world!')) // // // expected output: true // // namedArgumentFunc({ // // qux: false, // // foo: 'content.html', // // // 引数の順序関係無し&必要な引数だけを指定できる // // }); // // // 関数定義引数末尾に={}を付けたので引数無しで関数を実行できる // // // namedArgumentFunc(); // // /** // // * // // * // // * @param {*} [{ // // * 'bar', // // * baz = 200, // // * qux = false // // * }={}] // // * @returns // // */ // // function namedArgumentFunc2({ // // 'bar', // // baz = 200, // // qux = false // // } = {}) { // // return `a=${foo}, b=${baz}, c=${qux}`; // // } // // function showPanel( // // path = 'content.html', // // height = 200, // // modeless = false // // ) { // // console.log(`a=${path}`, `b=${height}`, `c=${modeless}`); // // } // // showPanel( // // modeless: false, // // //全ての引数を指定しないとerrorになる // // path: 'content.html', // // ); // // req('https://qiita.com/murase/items/908cf31b6776448a5b1d') // // .then(body => ( // // HTMLParser.parse(body) // // .querySelectorAll('a') // // .forEach(element => { // // console.log(element.rawAttrs) // // }) // // )); // // const crawler = async () => { // // return new Promise(resolve => { // // let target = []; // // resolve(target); // // }) // // // return target; // // } // // crawler().then(res => (console.log(res))); // // const request = require('request'); // // const HTMLParser = require('fast-html-parser'); // // var ary = []; // // const httpRequest = (url = 'https://www.yahoo.co.jp/') => { // // return new Promise((resolve, reject) => { // // let proxyUrl = process.env.PROXYURL // // let proxiedRequest = request.defaults({ 'proxy': proxyUrl }); // // // request(url, (error, response, body) => { // // proxiedRequest.get(url, (error, response, body) => { // // resolve(body); // // }); // // }); // // } // // httpRequest('https://gihyo.jp/') // // .then(body => { // // HTMLParser.parse(body) // // .querySelectorAll('a') // // .forEach(element => { // // // console.log(element.rawAttrs) // // ary.push(element.rawAttrs) // // }) // // // return ary; // // }) // // .then(result => { // // console.log(ary) // // }); // // // package.json // // // { // // // "dependencies": { // // // "request": "^2.88.0", // // // "fast-html-parser": "^1.0.1" // // // } // // // } // // /** // // * Responds to any HTTP request. // // * // // * @param {!express:Request} req HTTP request context. // // * @param {!express:Response} res HTTP response context. // // */ // // // using proxy, using environment variable "PROXYURL" // // // reference with https://stackoverflow.com/a/23856484/9740478 // // const request = require('request'); // // const HTMLParser = require('fast-html-parser'); // // exports.nodeSimpleCrawlerFromJP = (req, res) => { // // const httpRequest = (url = 'https://www.yahoo.co.jp/') => { // // return new Promise((resolve, reject) => { // // let proxyUrl = process.env.PROXYURL // // let proxiedRequest = request.defaults({ 'proxy': proxyUrl }); // // // request(url, (error, response, body) => { // // proxiedRequest.get(url, (error, response, body) => { // // resolve(body); // // }); // // }); // // } // // var ary = []; // // httpRequest('https://gihyo.jp/') // // .then(body => { // // HTMLParser.parse(body) // // .querySelectorAll('a') // // .forEach(element => { // // ary.push(element.rawAttrs) // // }) // // }) // // .then(result => { // // res.status(200).send(ary); // // }); // // }; // // function parseXML(response) { // // return response.text().then((stringContainingXMLSource) => { // // const parser = new DOMParser(); // // return parser.parseFromString(stringContainingXMLSource, "text/xml"); // // }); // // } // // let new XMLHttpRequest(); // // foo.open('GET', 'https://ja.wikipedia.org/w/api.php?format=xml&action=query&prop=links&titles=%E3%82%A8%E3%83%9E%E3%83%BB%E3%83%AF%E3%83%88%E3%82%BD%E3%83%B3') // // foo.send(null) // // let bar = foo.responseXML // // bar.querySelectorAll('*') // // // => NodeList(16)[api, continue, query, pages, page, links, pl, pl, pl, pl, pl, pl, pl, pl, pl, pl] // // const csvStr = '1,2,3\n3,4,5\n7,8,9' // // const value = ["https://www.xvideos.com/video25717629/best-2017-01/0/aya_kawasaki", "https://www.xvideos.com/video25718969/best-2017-01/0/asian_schoolgirl", "https://www.xvideos.com/video26134121/best-2017-01/0/loped_mature_asian"].toString(); // // const csv = require("csvtojson") // // csv({ // // noheader: true, // // output: "csv" // // }) // // .fromString(value) // // .then((jsonObj) => { // // console.log(jsonObj) // => [["1","2","3"], ["4","5","6"], ["7","8","9"]] // // }) // // for (let num of range(1, 3)) { // // Array.from( // // document.querySelectorAll(`#container > section.boxTagList.data-tag.clearFix > ul > li:nth-child(${num}) > dl > dt > a > span,#container > section.boxTagList.data-tag.clearFix > ul > li:nth-child(${num}) > dl > dd.txtNumber`)) // // .forEach(v => { // // ary.push([v.textContent.replace(/,/, "").replace(/ 投稿/, "").split('\n')]) // // }) // // } // // node wc.js|cat|sort|uniq|sort -n // // const jsdom = require("jsdom"); // // const { JSDOM } = jsdom; // // JSDOM.fromURL(`https://www.aozora.gr.jp/cards/001850/files/57353_57270.html`).then(dom => { // // return dom.window.document.querySelectorAll('body > div.main_text')[0].textContent.split(''); // // }).then(myCurrentArray => { // // let counts = {}; // // for (let i = 0; i < myCurrentArray.length; i++) { // // let key = myCurrentArray[i]; // // counts[key] = (counts[key]) ? counts[key] + 1 : 1; // // } // // return counts // // }).then( counts =>{ // // for(let key in counts) { // // console.log(counts[key]+" "+key); // // } // // }).catch( error => { // // console.log(error); // // }); // // let globalTunnel = require('global-tunnel-ng'); // // globalTunnel.initialize({ // // host: '*************.com', // // port: ****, // // proxyAuth: 'id:pas' // // }); // //requestをrequire // //ヘッダーを定義 // //オプションを定義 // // var options = { // // // url: `https://www.aozora.gr.jp/cards/001850/files/57353_57270.html` // headers: headers, // // url: `https://www.yahoo.co.jp/` // headers: headers, // // // json: true, // // // form: { "hoge": "fuga" } // // } // // npm config set https - proxy http://id:pass@host:port // // //リクエスト送信 // // // const bar = options => { // // const new Promise(resolve =>{ // // request({ url: `https://www.yahoo.co.jp/` }, function (error, response, body) { // // resolve(body); // // // reject(error); // // }) // // }) // // let new Promise(function (resolve, reject) { // // resolve('foo'); // // }); // // const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); // // const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); // // bar.then(body => { console.log(body) }); // // foo.then(body => { // // JSDOM.fromURL(`https://www.aozora.gr.jp/cards/001850/files/57353_57270.html`).then(dom => { // // console.log( // // dom.window.document.querySelector(`body > div.main_text`).textContent // // ) // // // return dom; // // // console.log(dom.window.document.querySelectorAll('#topicsfb > div.topicsindex > ul.emphasis > li:nth-child(1) > a').textContent); // // // console.log(dom.window.document.querySelectorAll('body')[0].textContent ); // // // console.log(dom.window.document.querySelectorAll('*')); // // }) // // .then(myCurrentArray => { // // let counts = {}; // // for (let i = 0; i < myCurrentArray.length; i++) { // // let key = myCurrentArray[i]; // // counts[key] = (counts[key]) ? counts[key] + 1 : 1; // // } // // return counts // // }).then( counts =>{ // // for(let key in counts) { // // console.log(counts[key]+" "+key); // // } // // }).catch( error => { // // console.log(error); // // }); // // var request = require('request'); // // const { JSDOM } = require('jsdom') // // const jsdom = require("jsdom"); // // const resourceLoader = new jsdom.ResourceLoader({ // // proxy: "id:pass@host:port" // // }); // // JSDOM.fromURL(`https://www.aozora.gr.jp/cards/001850/files/57353_57270.html`, { resources: resourceLoader }).then(dom => { // // console.log( // // dom.window.document.querySelector(`body > div.main_text`).textContent // // ) // // // return dom; // // // console.log(dom.window.document.querySelectorAll('#topicsfb > div.topicsindex > ul.emphasis > li:nth-child(1) > a').textContent); // // // console.log(dom.window.document.querySelectorAll('body')[0].textContent ); // // // console.log(dom.window.document.querySelectorAll('*')); // // }) // // request({ url: `https://www.yahoo.co.jp/` }, function (error, response, body) { // // console.log(body) // // // resolve(body); // // // reject(error); // // }) // // const dom = new JSDOM(``, { resources: resourceLoader }); // // _.all(list, [iterator], [context]) // // _.every のエイリアス。 list のすべての値が iterator 関数の真偽テストで true を返した場合に true を返す。 iterator が渡されない場合は要素の値自体で真偽 を 判 定 す る。(JavaScript は false、 undefined、 null、 NaN、 0、 - 0、 '' // // の 場 合 に false と判定し、 その他はすべて true と判定する。) // // _.any(list, [iterator], [context]) // // _.some のエイリアス。 list のいずれかの値が iterator 関数の真偽テストで true を返した場合に true を返す。 iterator が渡されない場合は要素の値自体で真偽 を判定する(JavaScript は false、 undefined、 null、 NaN、 0、 - 0、 空の文字列('') の場合に false と判定し、 その他はすべて true と判定する。) // // _.bind(function, object, [ * arguments]) // // function を object にバインドした関数を返す。 返された関数は、 どのコン // // 説明付きの Underscore のソースコードは、 http: //underscorejs.org/docs/underscore.html で参照でき ます(説明は英語)。 // // テクストで呼ばれても this の値として object を参照した状態で実行する。 // // _.bindAll(object, * methodNames) // // methodNames で指定されたメソッドを、 常に object にバインドし、 どこで実行し てもそれを this として実行するようにする。 // // _.chain(obj) // // _.chain(obj).sortBy(...).first().value() のようにチェーン記法で連続処理を行 う。 チェーン内のそれぞれの関数は obj を処理した結果をラッパーオブジェク トに格納して、 チェーン上の次のメソッドに渡す。 チェーン内のメソッドには ラッパーオブジェクトが渡され、 メソッドの 1 つ目のパラメータ(list、 array、 object) は省略される。 push や reverse など、 ネイティブ Array のプロトタイプ メソッドもチェーン可能。 最後に value() をチェーンすることで、 ラッパーオブ ジェクトから obj の処理結果を抽出して返す。 // // _.clone(object) // // オブジェクト object を「 浅くコピー」 したものを返す。 入れ子になっているオ ブジェクトや配列は参照がコピーされ、 それらの実体は複製されない。 // // _.compose( * functions) // // functions に渡された複数の関数を合成して返す。 右側の関数から順に処理を行 い、 次の関数は右側の関数の戻り値を引数として実行する。 // // _.contains(list, value) // // value が list 内に存在する場合に true を返す。 list が配列の場合は、 内部的に indexOf で処理する。 // // _.countBy(list, iterator, [context]) // // iterator 関数の戻り値をキーとして list の要素をカウントし、 それぞれの要素 とその出現回数をキー値として格納したオブジェクトを返す。 元の list は変更 されない。 // // _.defaults(object, * defaults) // // defaults オブジェクトに定義されているプロパティが object に存在しない場合、 もしくは値が undefined の場合、 defaults で与えられたプロパティを挿入する。 // // _.each(list, iterator, [context]) // // list を走査して、 それぞれの要素を iterator 関数に与えて実行する。 context を // // 渡している場合には iterator は context にバインドされる。 list が配列の場合、 iterator には要素、 インデックス、 配列の 3 つの引数が渡される。 list がオブ ジェクトの場合には、 値、 キー、 オブジェクトの 3 つが渡される。 // // _.every(list, [iterator], [context]) // // list のすべての値が iterator の真偽テストで true を返した場合に true を返す。 iterator が渡されない場合は要素の値自体で真偽を判定する。(JavaScript は false、 undefined、 null、 NaN、 0、 - 0、 '' // // の場合に false と判定し、 その他はすべ て true と判定する。) // // _.extend(destination, * sources) // // sources に渡されたオブジェクトのプロパティを destination オブジェクトに追加 する。 その際、 destination オブジェクト自身が変更対象となり、 キーが重複す る場合は新しい値で上書きされる。 sources に渡した順番に上書きするため、 最 後に渡されたオブジェクトが優先される。 // // _.filter(list, iterator, [context]) // // list の要素をそれぞれ iterator 関数に渡して実行し、 true が返されるすべての 要素を配列に格納して返す。 true が返される要素がない場合は空の配列を返す。 // // _.find(list, iterator, [context]) // // list の要素をそれぞれ iterator 関数に渡して実行し、 true が返される最初の要 素を返す。 true が返される要素がない場合は undefined を返す。 // // _.findWhere(list, properties) // // list のそれぞれの値を走査して、 properties に渡されたオブジェクトのすべての プロパティのキーと値の両方を持っている最初のオブジェクトを返す。 // // _.first(array, [n]) // // 配列 array の最初の要素を返します。 数値 n を指定すると、 最初の n 個の要素を 返す。 // // _.flatten(array, [shallow]) // // 配列 array にネストされている配列があれば、 ネストを解いて平坦な新しい配列 に変換して返す。 shallow に true を渡すと、 1 レベルだけ平坦にする。 // // _.groupBy(list, iterator, [context]) // // iterator 関数の戻り値をキーとして、 list 内の対応する要素の配列をそのフィー // // _.has(object, key) // // object に key というキーが存在する場合に true を返す(プロトタイプで定義 されているキーには false を返す)。 object.hasOwnProperty(key) と同じだが、 hasOwnProperty 関数への安全な参照を使うことによって、 object から参照する hasOwnProperty メソッドがオーバーライドされても問題なく動作させるようにし ている。 // // _.identity(value) // // value をそのまま返す。 // // _.invert(object) // // object のプロパティのキーと値が入れ替えられたオブジェクトを返す。 元の object は変更されない。 格納されている値は一意で、 文字列に変換できるもので ある必要がある。 // // _.isArguments(object) // // object が引数オブジェクト(arguments) の場合に true を返し、 それ以外の場 合に false を返す。 // // _.isArray(object) // // object が配列である場合に true を返し、 それ以外の場合に false を返す。 // // _.isBoolean(object) // // object が true もしくは false である場合に true を返し、 それ以外の場合に false を返す。 // // _.isDate(object) // // object が Date オブジェクトである場合に true を返し、 それ以外の場合に false を返す。 // // _.isEmpty(object) // // object に何も格納されていない場合に true を返し、 何かが格納されている場合 は false を返す。 // // _.isEqual(object, other) // // object と other の 2 つのオブジェクトの深い比較を行う。 // // _.isFinite(object) // // object が有限数である場合に true を返し、 それ以外の場合に false を返す。 // // _.isFunction(object) // // object が関数である場合に true を返し、 それ以外の場合に false を返す。 // // _.isNaN(object) // // object が NaN の場合に true を返し、 それ以外の場合に false を返す。 object が undefined の場合、 JavaScript ネイティブの isNaN 関数は true を返すが、 この関 数は false を返す。 // // _.isNull(object) // // object が null の場合に true を返し、 それ以外の場合に false を返す。 // // _.isNumber(object) // // object が数値型(NaN を含む) の場合に true を返し、 それ以外の場合に false を 返す。 // // _.isObject(value) // // value が object 型である場合に true を返し、 それ以外の場合に false を返す。 // // _.isRegExp(object) // // object が RegExp オブジェクトである場合に true を返し、 それ以外の場合に false を返す。 // // _.isString(object) // // object が文字列型である場合に true を返し、 それ以外の場合に false を返す。 // // _.isUndefined(value) // // value が undefined である場合に true を返し、 それ以外の場合に false を返す。 // // _.keys(object) // // object 自身が持つすべてのプロパティ名を配列に格納して返します。 // // _.last(array, [n]) // // 配列 array の最後の要素を返す。 数値 n を渡した場合は、 最後の n 個の要素を配 列に格納して返す。 文字列でも動作する。 要素を持たない配列や、 配列・ 文字列 以外が array に渡された場合は undefined を返す。 // // _.map(list, iterator, [context]) // // list に格納されているそれぞれの要素を iterator 関数に渡して実行した結果を 格納した新たな配列を生成する。 list がオブジェクト型であっても、 戻り値は配 列となる。 JavaScript ネイティブの map 関数が存在する場合はネイティブ関数が 優先される。 // // _.max(list, [iterator], [context]) // // list 内で一番大きな値を返す。 iterator 関数が引数に渡されている場合は、 各要 素においてこの関数が返す値により値の順序付けが行われる。 // // _.object(list, [values])[key, value] のような配列が格納された入れ子配列をlistに渡すか、 もしくは キーの配列を list に、 値の配列を values に渡すことによって、 それらをオブ ジェクトに変換する。 // // _.omit(object, * keys) // // keys に与えられたプロパティを object から除去して新しいオブジェクトに格納 して返す。 // // _.pairs(object) // // objectの各プロパティを[key, value] の配列に変換し、 それらを格納した配列を 返す。 // // _.partial(function, [ * arguments])[ * arguments] に与えられた任意の数の引数を // // function に部分適用する。 // // _.pick(object, * keys) // // keys に与えられたプロパティを object から抽出して新しいオブジェクトに格納 して返す。 // // _.pluck(list, propertyName) // // _.map の一番一般的とおもわれるユースケースを実現するための便利関数。 オブ ジェクトの配列 list から、 propertyName のキーを持った値を抽出して、 配列に格 納して返す。 // // _.range([start], stop, [step]) // // 連続した数値を格納した配列を生成する。 start から stop までの間、 数値 step ごとの連続した数値を配列に格納して返す。 start と step が省略された場合はそ // // れぞれが 0 と 1 とみなされ、 stop の個数分の自然数を格納した配列を返す。 // // _.reduce(list, iterator, [memo], [context]) // // list に格納されているそれぞれの要素を左から順番に iterator 関数に渡して実 行し、 その結果を結合することで単一の値まで「 煮詰める」。 memo(累積変数) は最終的に返す値の初期状態で、 省略された場合は list の最初の値が初期状態 となる。 list が配列の場合、 memo と配列の要素が iterator に引数として渡され る。 list がオブジェクトの場合の引数は memo、 値、 キーの順となる。 // // _.reduceRight(list, iterator, memo, [context]) _.reduce と同様の動作を右側から実行する。 // // _.reject(list, iterator, [context]) // // _.filter と逆の動作を行う。 つまり、 list の要素をそれぞれ iterator 関数に渡 して実行し、 true が返されないすべての要素を配列に格納して返す。 true が返さ れない要素がない場合は空の配列を返す。 // // _.rest(array, [index]) // // _.rest(array, [index\]) 配列 array から最初の要素を取り除いた配列を返す。 index を指定した場合は index とそれ以降の要素を含んだ配列を返す。 // // _.size(list) // // list の要素の数を返す。 list が配列の場合は length、 オブジェクトの場合はキー の数を返す。 // // _.some(list, [iterator], [context]) // // list のいずれかの値が iterator の真偽テストで true を返した場合に true を返 す。 iterator が渡されない場合は要素の値自体で真偽を判定する(JavaScript は false、 undefined、 null、 NaN、 0、 - 0、 '' // // の場合に false と判定し、 その他はすべ て true と判定する。) // // _.sortBy(list, iterator, [context]) // // list の要素を iterator 関数の結果によってソートした結果のリストを返す。 元 の list は変更されない。 // // _.tap(object, interceptor) // // object をターゲットオブジェクトとして interceptor 関数を呼び出し、 そして、 object をそのまま返す。 このメソッドの主な利用方法は _.chain によるメソッド // // _.take(array, [n]) // // _.first のエイリアス。 配列 array の最初の要素を返す。 数値 n を指定すると、 最初の n 個の要素を返す。 // // _.times(n, iterator, [context]) // // iterator に渡された関数を n 回実行する。 それぞれの iterator 関数の実行時には インデックス番号が引数として渡される。 実行結果が配列に格納されて返される。 // // _.toArray(list) // // イテレート可能なデータ型 list を Array 型に変換する。 arguments オブジェクト を Array 型に変換する際に便利。 list がオブジェクトの場合は、 それぞれの値が 配列の要素となる。 // // _.uniq(array, [isSorted], [iterator]) // // 配列 array から重複要素を取り除いた新しい配列を返す。 重複要素の判定は同値 演算子( === ) で行われる。 配列がすでにソートされていることが判明している 場合は、 isSorted に true を渡すことで、 動作の早いアルゴリズムを使用できる。 iterator に関数を渡しておくと、 これを使って _.map であらかじめ処理を行っ てから重複要素を取り除く。 isSorted の位置に関数が渡された場合は、 それが iterator として認識される。 // // _.values(object) // // object のすべてのプロパティの値だけを配列に格納して返す。 // // _.where(list, properties) // // list のそれぞれの値を走査して、 properties に渡されたオブジェクトのすべての プロパティのキーと値の両方を持っているオブジェクトをすべて抽出し、 その配 列を返す。 // // _.without(array, [ * values]) // // array から values に渡された値を除いた新たな配列を生成して返す。 // // _.zip( * arrays) // // 渡されたそれぞれの配列の同じインデックスにある要素を新たな配列の要素 としてまとめて、 それぞれの配列を要素に持った配列を返す。 _.zip([1, 2, 3\], ['a', 'b', 'c'\]) の実行結果は[[1, 'a'\], [2, 'b'\], [3, 'c'\]\] となる。 let A, B, C; //, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, S, T, U, V, W, X, Y, Z; // // A = R.pipe( // // R.all(R.match(/(\d)./g), )([3, 3, 3, 3]); // // B = R.any(R.equals(2))([1, 2]); const addXY = ary => { let [x, y] = ary; return x + y } const show = arg => console.log(`show: ${arg}`); const add2 = (a, b) => a + b; const mergeTwo = (a, b) => [].concat(a, b); const toArray = a => [].concat(a); const tripleAdd = (x, y, z) => x + y + z; const tripleMultiply = (x, y, z) => x * y * z; const doubleAdd = R.unary(tripleAdd); // console.log(R.map(R.product(R.__))([ // [1, 2], // [3, 4] // ])) A = R.pipe( R.take(50), R.reject(((n) => n % 2 === 1)), // except odd R.filter(((n) => n % 3 === 0)), // only 3 multiples R.toPairs(), R.sortBy(R.prop(0)), R.reverse(), R.pluck(1), // R.pluck('', []) is alias R.map(R.prop())([]) R.zip((R.times(R.identity, 10))), R.map(addXY), R.groupBy(num => { return num < 10 ? 'A' : num < 20 ? 'B' : num < 30 ? 'C' : num < 40 ? 'D' : 'E'; }), R.omit(['D', 'F']), R.toPairs(), R.sort(R.descend(R.prop(0))), //Z→A 10→1 is descend R.sort(R.ascend(R.prop(0))), //A→Z 1→10 is ascend R.flatten(), R.filter(R.is(Number)), R.length(), R.range(1), R.without([3, 4, 5, 6]), R.zipObj(['a', 'b', 'c']), R.invertObj(), R.invertObj(), R.values(), R.map((N => (N - 0))), R.insertAll(0, ['y', 'z']), R.partition(R.is(String)), R.transpose(), R.tail(), R.fromPairs(), R.merge({ x: 0 }), R.pick(['z']), R.values(), R.insertAll(0, R.repeat(2, 3)), // R.reduce(R.add, 0), R.insertAll(-1, [7, 8, 9, 10]), R.uniq(), R.adjust(0, R.toString), R.addIndex(R.map)((val, idx) => idx + '-' + val), // ['f', 'o', 'o', 'b', 'a', 'r']); R.concat([1, 2, 3]), R.insert(3, 100), R.prepend(10), R.append('foo'), R.update(-1, 'bar'), R.update(0, 20), R.set(R.lensIndex(-1), 'baz'), R.over(R.lensIndex(-1), R.toUpper), R.filter(R.is(Number)), R.scan(R.multiply, 10), R.remove(3, 3), R.init(), R.nth(-1), toArray, R.flip(mergeTwo)(10), // R.apply(Math.max), // R.toString(), // R.splitEvery(1), // R.map((STR => (STR - 0))), // R.converge(tripleAdd, [R.sum, R.sum, R.sum]), // R.useWith(Math.pow, [R.dec, R.inc])(3), // 2^7 => 128 // R.converge(R.add, [R.add(2), R.add(2)]), // 130+130 => 260 // R.insert(0, R.__, [1, 2, 3]), // R.apply(R.juxt([Math.max, Math.min])), // R.insertAll(-1, [100]), // R.tap(show), // R.max(), // R.into([]), // R.insertAll(0, [1, 2, 3], [R.__]), // R.toPairs(), // R.concat([1, 2]), // R.none(R.is(String)), // R.map(R.toString), // R.addIndex(R.map((val, idx) => idx + '-' + val)), )(R.times(R.identity, 100)); // const double = R.partial(add2, [2, 3, 10]); // B = double(); //=> 4 // var sm = require('sequencematcher'); // var array1 = [1, 2, 3]; // var array2 = [1, 0]; // var similarity = sm.sequenceMatcher(array1, array2); // console.log(similarity); // let array_3 = []; // sequenceMatcher = function (array_1, array_2) { // if (!isArray(array_1) || !isArray(array_2)) { // return -1; // } // var total_length = array_1.length + array_2.length; // if (!total_length) { // return -1; // } // var matched_times = 0; // for (var i in array_1) { // for (var j in array_2) { // if (array_1[i] === array_2[j]) { // matched_times++; // array_3 = R.insert(-1, array_1[i], array_3); // break; // } else { // array_3 = R.insert(-1, 0, array_3); // break; // } // } // } // return matched_times / (total_length / 2); // } // function isArray(o) { // return Object.prototype.toString.call(o) === '[object Array]'; // } // var array1 = [1, 2, 3]; // var array2 = [1, 10, 3]; // // var similarity = sm.sequenceMatcher(array1, array2); // var similarity = sequenceMatcher(array1, array2); // console.log(similarity); // console.log(array_3); // R.insert(-1, 'x', [1, 2, 3, 4]); var array1 = [1, 2, 3, 4]; var array2 = [1, 2, 3, 4]; const foo = a => a[0] === a[1] ? a[0] : 0 const matcher = (array_1, array_2) => { return R.pipe(R.zip, R.map(foo))(array_1, array_2); } const unMatchedTimes = (array_1, array_2) => { return R.countBy(Math.abs)(matcher(array1, array2))["0"] } // matcher(array1, array2) // unMatchedTimes(array1, array2) const similarity = (array_1, array_2) => { let total_length = array_1.length + array_2.length; // return total_length / 2 * (unMatchedTimes(array_1, array_2) / 10) // return total_length / 2 * (2 / 10) // return unMatchedTimes(array_1, array_2) return matcher(array_1, array_2) } console.log(similarity(array1, array2)); // const NJTEXTARRAY = [ // // "◆罪罰◆\nザイバツ・シャドーギルド討つべし!チャンピオンREDで連載中!ニンジャスレイヤーコミカライズ第2幕!\n◆影業◆\n刮目せよ!キョート・ヘル・オン・アースの幕開けを!1巻&2巻、2019年1月18日決断的同時発売!\n\nhttps://www.amazon.co.jp/dp/4253239161/ \n\nhttps://www.amazon.co.jp/dp/425323917X/ \n\n◆ニンジャ、殺すべし!◆", // "カシウスは腕を引き抜き、返り血を浴びカラテを啜る!彼はただ、ネオワラキアのため!ワラキアの民を守るため!そして己の主君のために!「殿!お急ぎください!長くはもちません!」地下へ殺到してくる論理十字軍ニンジャたちを睨みながら、カシウスは祈った!この声よ、ブラド・ニンジャに届けと!28", // "「イヤーッ!」「アバーッ!?」カシウスのボトルネックカットチョップ!「イヤーッ!」「アバババーーーーッ!」サマーソルトキック!「イイイヤアアアアーーーーッ!」「アババババーーーーーッ!」さらに隻腕のインペイラー・ツキが、オムラ主任の心臓に決まった!「ヤッタ!」ミカエルが叫ぶ! 27", // "BRATATATATATATATATA!怒りの一斉射撃により、反重力キャリアーの装甲が破壊されてゆく!「ヤバイよ、ジェイク!」「マザーファッカー!」だが「イヤーッ!」ここでカシウスがオムラに飛びかかった!己をここまで導いた勇敢なエメツ鉱夫たちを援護すべく、カシウスは死に物狂いでカラテを振るう! 26", // "KLICK!KLICK!KLICK!「何じゃ、もうタマ切れか!?」「ジェイク!もっと動かないと、撃たれるって!」ミカエルが叫ぶ!「お、おのれ!カタナ社めがーッ!裏切りましたね!」コマンド・グンバイを掲げ、オムラ主任が唸った!「ウケテミロ!」「「「オムラウケテミロ!」」」 25", // "「おう!今まで好き勝手やりおってオムラのクソどもが!見ておれ!」クリキが腕捲りし、グレネードランチャー射撃ボタンを押す!シュゴウン!「「「アイエエエエエ!」」」KRA-TOOOM!押す!「「「アイエエエエエ!」」」KRA-TOOOM!押す!KRA-TOOOM!「「「アイエーエエエエエ!」」」「イェー!」24", // "「イェー!こいつは実に気持ちがいいね。爺さんも一発カマしてみるか!?」UNIX椅子にふんぞり返り、LAN直結しながら操縦を行うのは、ラッキー・ジェイク!横にはクリキとミカエル!彼らはカシウスと結託してカタナ社の反重力キャリアーを盗み、この地下電源ユニットを叩く作戦を立てたのである! 23", // "KRA-TOOOOOM!着弾、爆発!明らかな論理十字軍軍事協定違反!「「「グワーーーッ!?」」」パワード鎧を着たオムラマンが腕を回しながら吹っ飛ぶ!果たして何故カタナ・オブ・リバプール社はこのような行動に出たのか!?その理由は、操縦席の中にある! 22", // "だがカタナ社の反重力キャリアーは聞く耳持たぬ!『庶子!』自動翻訳された威嚇的電子音声とともに、オムラ陣営に対してグレネード弾を発射した!シュゴウン!「「「アイエエエエエ!?」」」不意を打たれ困惑するオムラ・アシガル!「か、回避しなさいーッ!」主任の命令も、間に合わぬ! 21", // "「カタナ社の援護などいらない!とっととリバプールに戻って、シケたメシでも食っていなさい!」オムラ主任が叫ぶ!これは実際ギリギリの警告行動!論理十字軍を形成している間は、カタナ社に対して威嚇射撃などを行うだけでも論理聖教会からクレームを入れられてしまうのである! 20", // "「アイエッ!?カタナ社!?」「カタナ社が何故ここに!?」「止まりなさい!ここは我々オムラの担当エリアです!」アシガルに制圧射撃を続けさせながら、オムラ主任たちが叫ぶ!平時、カタナ・オブ・リバプール社とは敵対関係なれど、今は同じ論理十字軍の友軍! 19", // "ギャリギャリギャリギャリ!地上部との連結路から猛烈な騒音!(カシウス=サンが危ない!急いで!急いで!)(ファッキンバスタード!道が狭すぎるんだよ!)乱暴な運転で車体のあちこちを壁や天井にぶつけ、火花を散らしながら、カタナ社製のハコブ級反重力キャリアーが乱入してきたのである! 18", // "「「「イチ!ニ!サン!シー!」」」次のロケット弾斉射でカシウスにとどめを刺すべく、オムラマンたちは秒読み体制に入った!この無慈悲なるサンダンウチが行われれば、カシウスは物陰から炙り出され、蜂の巣となってしまう!……だが、その時! 17", // // "\4/1(月)まで!『JUDGE EYES:死神の遺言』が30%オフ!/\n\nPlayStation StoreでのDL購入限定で『ジャッジアイズ』が30%オフに!\n完全犯罪の謎を暴け。想像を超えた真実が、あなたを待つ。\n#judge", // "「オムラ!」「「「ダカラ!」」」「オムラ!」「「「イチバン!」」」「ウケテ・ミロ・ヨロシク!」「「「ウケテ・ミロ!」」」続々駆けつけるオムラ兵!BRATATATATATA!そして火力!火力!火力あるのみ!制圧射撃でカシウスを追い込みながら、たちまち完璧な対ニンジャフォーメーションを形成! 16", // "BRATATATATATA!BRATATATATATA!「「「敵襲!敵襲ーーーーッ!」」」オムラマンたちは電子法螺貝を吹き鳴らす!その間、オムラの制圧射撃は片時も止まない!飛び出せば、さしものカシウスもたちまち銃弾の雨を全身に浴びて死ぬであろう! 15", // "「ネオワアラキアのニンジャを確認!社敵ーーッ!」「「「殲滅!」」」オムラ兵の待機部隊が駆けつけ、カシウスに対してマシンガン斉射を行う! BRATATATATATATA!「イヤーッ!」カシウスは咄嗟の横っ飛びで回避!BRATATATATATATATA!だが制圧射撃で物陰に追い詰められ、身動き不能の状態となる! 14", // "「殿!今援護いたします!イヤーッ!」満身創痍のカシウスは発電ユニットに接近!太い電源ケーブルを脇に抱えこむと、膂力を振り絞り、一本一本強引に引き抜く!「イヤーッ!」接続部からバチバチと火花が散り、カシウスの体を焼く!「イヤーッ!」防護服も纏わぬ無謀!「イヤーッ!」狂気の沙汰! 13", // "「イヤーッ!」「グワーッ!」「イヤーッ!」「グワーッ!」「イヤーッ!」「グワーッ!」プロイェスティの地下エメツ採掘場、発電ユニット周辺の闇からスーツを纏った黒人の吸血鬼ニンジャが飛び出し、鮮やかな空中3連続回し蹴りでオムラ・アシガルの首を跳ねた!カシウスである! 12", // "________ 11", // "『カ、カタナ社の製品に落ち度はありません。地下のオムラ・エンパイアからIRC入電です!エメツ採掘場の発電ユニットが、吸血鬼ニンジャに奇襲されております……!』『コーッ!シュコーッ!何だと……!?』 10", // "無論、この異常に気づいたのは、彼ら2人だけではない。『コーッ!シュコーッ!何が起こっている!まさか、この程度でデミ太陽球がオーバーヒートを起こしたとでも!?』ウリエルがIRCで問う。『アイエエエエ!ち、違います!』即座に、シスターオイラン技師たちが状況を把握し、返した。 9", // // "\900社以上導入/\n\nレンジで約1~4分。\n\n働き方改革でビジネスマンの健康を\n最大限バックアップ!!\n\nまずは無料試食から!♪", // "ZZZZZT!突如、デミ太陽球がノイズ明滅。電脳都市の漏電ネオン看板めいて、バチバチと火花を散らしたのだ。異常事態である。サツバツナイトとブラド・ニンジャは目を見合わせ、頷いた。「……あるいは、予期せぬ蛮勇であろう」とブラド・ニンジャは笑った。 8", // "だが二者はゼンを高め、決して揺るがず、また取り乱しもしなかった。フーリンカザンがために。「ならば、そこに一瞬の翳りをもたらすものとは、人の恐怖、盲目の怒り、奢り、欲望、慢心、ウカツ、あるいは……」サツバツナイトが言いかけた、その時である。 7", // "「いかにも、人の手による人工物だ。余が心酔したIRC端末と同じく……」ブラド・ニンジャがゼンモンドーめいて返す。その間にも、2人のリアルニンジャを守る蝙蝠のドームは、銃弾や光を浴びせられて次々に燃え落ち、消えてゆく。このままでは、ジリー・プアー(訳注:徐々に不利)。 6", // "「……フーリンカザンの教えによれば、満ち続ける潮はなく、また引き続ける潮もない。翳らぬ太陽はなく、また翳らぬ月もない」フジキドはチャドー呼吸の間に、ユカノの教えを反芻した。「一瞬でもあのデミ太陽が翳れば、勝機はあろう。しかしあれは自然物ではない。雲に覆い隠せるものではない……」5", // "血を吸い終えたブラドは、口元を拭うと、失った片腕を蝙蝠の群れでかろうじて再生。サツバツナイトに問うた。「……どう打って出る。座して死を待つとは言うまいな」チャドー呼吸によるゼンが血中カラテを介して染み渡ったのか、ブラドは苛烈なる怒りを克服し、幾許かの冷静さを取り戻していた。 4", // "血液量にして400ml弱。だが重要なのは血そのものではない。血中カラテを吸い上げられているのだ。脆弱の精神の持ち主であれば、即座に気絶、ないしはパニックに陥っていたであろう。両者ともに強大なるリアルニンジャであるからこそ、こうして冷静に自制心を保てているのだ。3", // "牙はつぷりと静脈に穴を穿ち、湯気が上がるほど熱いカラテの血潮がサツバツナイトの内側から湧き出て、ブラドの口内に広がった。彼はゴクリ、ゴクリと喉を鳴らし、リアルニンジャの血中カラテを吸い上げていった。血を抜かれてゆく感覚に、さしものサツバツナイトも顔を歪め、チャドー呼吸を深めた。2" // ]; // /** // * // * // * @param {*} [{ // * targetChar = '!', // * textArray = ['foo!bar!', 'baz!'], // * }={}] // * @returns {number} '3' // */ // // const countAnyChar = ({ // // targetChar = '!', // // textArray = ['foo!bar!', 'baz!'], // // } = {}) => { // // const countAnyChar = ({ // // targetChar = '!' // // } = {}) => // // ({ // // textArray = ['foo!bar!', 'baz!'], // // } = {}) => { // const countAnyChar = targetChar => textArray => { // return R.pipe( // R.map(R.match( // new RegExp(targetChar, 'g') // )), // R.flatten(), // R.length(), // )(textArray) // } // // const zip = xs => ys => // // (xs.length < ys.length) ? xs.map((e, i) => [e, ys[i]]) : // // ys.map((e, i) => [xs[i], e]); // // console.log( // // countAnyChar({ // // targetChar: '!', // // textArray: NJTEXTARRAY // // }) // // ); // => 160 // // let countAnyCharParamObj = { // // targetChar: '!', // // textArray: NJTEXTARRAY // // } // let foo = // R.pipe( // R.toPairs, // R.flatten, // countAnyChar('!'), // // (() => { // // textArray: R.__ // // }), // // countAnyChar({ // // targetChar: '!' // // }), // )( // // { // // a: 'foo!bar!', // // b: 'foo!bar!' // // } // NJTEXTARRAY // ) // console.log( // // countAnyChar('!')(['foo!bar!', 'baz!']) // foo // => 4 // ); // // C = R.map(R.split('。'))(B); // // // C = R.converge(tripleAdd, [R.sum, R.sum, R.sum])([1, 2, 3]); // // // D = R.useWith(tripleAdd, [R.sum, R.sum, R.sum])([1, 2, 3]); // // C = R.lift((a, b, c) => a + b + c) // // ([100, 200], [10, 20], [1, 2]); // // D = RA.list('a', 'b', 'c'); // // E = R_.xPairs(1, [2, 3]); // [[1, 2], [1, 3]] // // F = R_.between(1, 5, 5); // // let multiplyXY = (x, y) => x * y; // // _.all(list, [iterator], [context]) // // _.any(list, [iterator], [context]) // // _.bind(function, object, [ * arguments]) // // _.bindAll(object, * methodNames) // // _.chain(obj) // // _.clone(object) // // _.compose( * functions) // // _.contains(list, value) // // _.countBy(list, iterator, [context]) // // _.defaults(object, * defaults) // // _.each(list, iterator, [context]) // // _.every(list, [iterator], [context]) // // _.extend(destination, * sources) // // _.filter(list, iterator, [context]) // // _.find(list, iterator, [context]) // // _.findWhere(list, properties) // // _.first(array, [n]) // // _.flatten(array, [shallow]) // // _.groupBy(list, iterator, [context]) // // _.has(object, key) // // _.identity(value) // // _.invert(object) // // _.keys(object) // // _.last(array, [n]) // // _.map(list, iterator, [context]) // // _.max(list, [iterator], [context]) // // _.object(list, [values]) // // _.omit(object, * keys) // // _.pairs(object) // // _.partial(function, [ * arguments]) // // _.pick(object, * keys) // // _.pluck(list, propertyName) // // _.range([start], stop, [step]) // // _.reduce(list, iterator, [memo], [context]) // // _.reduceRight(list, iterator, memo, [context]) // // _.reject(list, iterator, [context]) // // _.rest(array, [index]) // // _.size(list) // // _.some(list, [iterator], [context]) // // _.sortBy(list, iterator, [context]) // // _.tap(object, interceptor) // // _.take(array, [n]) // // _.times(n, iterator, [context]) // // _.toArray(list) // // _.uniq(array, [isSorted], [iterator]) // // _.values(object) // // _.where(list, properties) // // _.without(array, [ * values]) // // _.zip( * arrays) // // _.isArguments(object) // // _.isArray(object) // // _.isBoolean(object) // // _.isDate(object) // // _.isEmpty(object) // // _.isEqual(object, other) // // _.isFinite(object) // // _.isFunction(object) // // _.isNaN(object) // // _.isNull(object) // // _.isNumber(object) // // _.isObject(value) // // _.isRegExp(object) // // _.isString(object) // // _.isUndefined(value) // console.dir(A); // console.dir(B); // console.dir(C); // console.dir(D); // console.dir(E); // console.dir(F); // console.dir(G); // console.dir(H); // console.dir(I); // console.dir(J); // console.dir(K); // console.dir(L); // console.dir(M); // console.dir(N); // console.dir(O); // console.dir(P); // console.dir(Q); // console.dir(R); // console.dir(S); // console.dir(T); // console.dir(U); // console.dir(V); // console.dir(W); // console.dir(X); // console.dir(Y); // console.dir(Z);
29.256269
334
0.538529
54fae28f486c0b42386775ffed11e9f103688cfa
1,468
lua
Lua
src/TrackBuilder/Segment/MeshDataBuilder.lua
Twin1Twin2/track-builder
30922900e51700f619820d521dfa0fed5c3d3cc6
[ "MIT" ]
2
2021-01-05T08:41:47.000Z
2021-02-20T01:39:17.000Z
src/TrackBuilder/Segment/MeshDataBuilder.lua
Twin1Twin2/track-builder
30922900e51700f619820d521dfa0fed5c3d3cc6
[ "MIT" ]
null
null
null
src/TrackBuilder/Segment/MeshDataBuilder.lua
Twin1Twin2/track-builder
30922900e51700f619820d521dfa0fed5c3d3cc6
[ "MIT" ]
null
null
null
--- MeshDataBuilder --- Builder Pattern constructor for a MeshData local MeshData = require(script.Parent.MeshData) local root = script.Parent.Parent local Builder = require(root.Builder) local util = root.Util local t = require(util.t) local MeshDataBuilder = { ClassName = "MeshDataBuilder"; } MeshDataBuilder.__index = MeshDataBuilder setmetatable(MeshDataBuilder, Builder) function MeshDataBuilder.new() local self = setmetatable(Builder.new(), MeshDataBuilder) self.Mesh = nil self.MeshType = nil self.Offset = Vector3.new(0, 0, 0) self.Scale = Vector3.new(1, 1, 1) return self end -- makes sure everything is setup properly -- runs an "any" check on the following properties local BuilderCheck = Builder.Check({ "Mesh" }) function MeshDataBuilder:Build() assert(BuilderCheck(self)) return MeshData.fromData({ Mesh = self.Mesh, MeshType = self.MeshType, Offset = self.Offset, Scale = self.Scale, }) end function MeshDataBuilder:WithMesh(meshName) assert(MeshData.IsMeshClassName(meshName)) self.Mesh = meshName return self end function MeshDataBuilder:WithMeshType(meshType) assert(t.optional(MeshData.IsMeshType)(meshType)) self.MeshType = meshType return self end function MeshDataBuilder:WithOffset(offset) assert(t.Vector3(offset)) self.Offset = offset return self end function MeshDataBuilder:WithScale(scale) assert(t.Vector3(scale)) self.Scale = scale return self end return MeshDataBuilder
16.311111
58
0.756812
4a5c639acac8de61316d509e98e172116dc964c4
969
html
HTML
manuscript/page-735/body.html
marvindanig/the-last-of-the-mohicans
f1eb0c6fca3e07715c5b444d29a143ab21f60e76
[ "CECILL-B" ]
null
null
null
manuscript/page-735/body.html
marvindanig/the-last-of-the-mohicans
f1eb0c6fca3e07715c5b444d29a143ab21f60e76
[ "CECILL-B" ]
null
null
null
manuscript/page-735/body.html
marvindanig/the-last-of-the-mohicans
f1eb0c6fca3e07715c5b444d29a143ab21f60e76
[ "CECILL-B" ]
null
null
null
<div class="leaf flex"><div class="inner justify"><p>The merriment of Hawkeye was not easily appeased. Without ceremony, and with a rough hand, he twirled the supple Gamut around on his heel, and more than once affirmed that the Hurons had done themselves great credit in the fashion of his costume. Then, seizing the hand of the other, he squeezed it with a grip that brought tears into the eyes of the placid David, and wished him joy of his new condition.</p><p>&ldquo;You were about opening your throat-practisings among the beavers, were ye?&rdquo; he said. &ldquo;The cunning devils know half the trade already, for they beat the time with their tails, as you heard just now; and in good time it was, too, or 'killdeer' might have sounded the first note among them. I have known greater fools, who could read and write, than an experienced old beaver; but as for squalling, the animals are born dumb! What think you of such a song as this?&rdquo;</p></div> </div>
969
969
0.770898
15915ba8ac3b46ff79fb893ee9157db261fdba9c
431
asm
Assembly
programs/oeis/227/A227209.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
programs/oeis/227/A227209.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
programs/oeis/227/A227209.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
; A227209: Expansion of 1/((1-x)^2*(1-2x)*(1-4x)). ; 1,8,43,198,849,3516,14311,57746,231997,930024,3724179,14904894,59635945,238576532,954371647,3817617642,15270732693,61083455040,244334868715,977341571990,3909370482241,15637490317548 mov $2,2 mov $3,$0 lpb $0 sub $0,1 add $2,1 mul $2,2 lpe mov $1,3 sub $3,$2 mov $4,$2 pow $2,2 add $4,$2 add $4,3 div $4,3 add $3,$4 sub $3,3 add $4,$3 add $1,$4 sub $1,4 div $1,3 add $1,1
17.24
183
0.672854
292fc0cc76abee01a8b2295bf382e92ec19c530e
3,983
py
Python
orchestra/contrib/plans/migrations/0001_squashed_0003_auto_20210422_1108.py
RubenPX/django-orchestra
5ab4779e1ae12ec99569d682601b7810587ed381
[ "Unlicense" ]
null
null
null
orchestra/contrib/plans/migrations/0001_squashed_0003_auto_20210422_1108.py
RubenPX/django-orchestra
5ab4779e1ae12ec99569d682601b7810587ed381
[ "Unlicense" ]
4
2021-01-30T14:26:46.000Z
2022-03-18T16:28:39.000Z
orchestra/contrib/plans/migrations/0001_squashed_0003_auto_20210422_1108.py
RubenPX/django-orchestra
5ab4779e1ae12ec99569d682601b7810587ed381
[ "Unlicense" ]
3
2022-02-06T04:35:59.000Z
2022-03-17T00:40:17.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2021-04-22 11:09 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion import orchestra.core.validators class Migration(migrations.Migration): replaces = [('plans', '0001_initial'), ('plans', '0002_auto_20160114_1713'), ('plans', '0003_auto_20210422_1108')] initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('services', '0001_initial'), ] operations = [ migrations.CreateModel( name='ContractedPlan', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='plans', to=settings.AUTH_USER_MODEL, verbose_name='account')), ], options={ 'verbose_name_plural': 'plans', }, ), migrations.CreateModel( name='Plan', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=32, unique=True, validators=[orchestra.core.validators.validate_name], verbose_name='name')), ('verbose_name', models.CharField(blank=True, max_length=128, verbose_name='verbose_name')), ('is_active', models.BooleanField(default=True, help_text='Designates whether this account should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')), ('is_default', models.BooleanField(default=False, help_text='Designates whether this plan is used by default or not.', verbose_name='default')), ('is_combinable', models.BooleanField(default=True, help_text='Designates whether this plan can be combined with other plans or not.', verbose_name='combinable')), ('allow_multiple', models.BooleanField(default=False, help_text='Designates whether this plan allow for multiple contractions.', verbose_name='allow multiple')), ], ), migrations.CreateModel( name='Rate', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('quantity', models.PositiveIntegerField(blank=True, help_text='See rate algorihm help text.', null=True, verbose_name='quantity')), ('price', models.DecimalField(decimal_places=2, max_digits=12, verbose_name='price')), ('plan', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rates', to='plans.Plan', verbose_name='plan')), ('service', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='rates', to='services.Service', verbose_name='service')), ], ), migrations.AddField( model_name='contractedplan', name='plan', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='contracts', to='plans.Plan', verbose_name='plan'), ), migrations.AlterUniqueTogether( name='rate', unique_together=set([('service', 'plan', 'quantity')]), ), migrations.AlterField( model_name='rate', name='plan', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rates', to='plans.Plan', verbose_name='plan'), ), migrations.AlterField( model_name='rate', name='plan', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='rates', to='plans.Plan', verbose_name='plan'), ), ]
53.106667
206
0.642983
6a78fb1e4d19207baf690d1491b5e312fa00a73d
764
asm
Assembly
Modul 3/latih11.asm
hyuwah/fu-praktikum-smd
a06fe109a42aa96e75f9a425a0905d6bfbfdfc7e
[ "MIT" ]
null
null
null
Modul 3/latih11.asm
hyuwah/fu-praktikum-smd
a06fe109a42aa96e75f9a425a0905d6bfbfdfc7e
[ "MIT" ]
null
null
null
Modul 3/latih11.asm
hyuwah/fu-praktikum-smd
a06fe109a42aa96e75f9a425a0905d6bfbfdfc7e
[ "MIT" ]
null
null
null
;-------------------------------------------------------------------- ; Praktikum SMD 2015 ; M.Wahyudin (140310120031) ; ; Name : LATIH11.ASM ; Desc : Membaca penekanan keypad 4x3 ; Input : Keypad di P3 ; Output: LED di P1 ; 4-display segmen di P2 ;-------------------------------------------------------------------- mulai: mov P3, #127 mov A, P3 mov 30h, A mov P1, A lcall konversi mov P2, A jmp mulai konversi: mov R0, #255 putar: inc R0 cjne R0, #12, lanjut ret lanjut: mov A, R0 add A, #5 movc A, @A+pc cjne A, 30h, putar mov A, R0 ret tabel: db 3Dh, 76h, 75h, 73h, 63h, 6Dh, 6Bh, 5Eh, 5Dh, 5Bh, 3Eh, 3Bh end
20.105263
69
0.420157
ada17ee5ebbe2c58242a5f31124198c9288976f8
167
swift
Swift
Marshroute/Sources/Routers/Routers/DetailRouterTransitionable.swift
turlodales/Marshroute
db71dc8323006a57ccc283f689af43a7128bec65
[ "MIT" ]
235
2016-05-31T06:05:53.000Z
2022-02-21T13:57:53.000Z
Marshroute/Sources/Routers/Routers/DetailRouterTransitionable.swift
turlodales/Marshroute
db71dc8323006a57ccc283f689af43a7128bec65
[ "MIT" ]
11
2017-02-05T16:31:39.000Z
2022-03-01T19:09:37.000Z
Marshroute/Sources/Routers/Routers/DetailRouterTransitionable.swift
turlodales/Marshroute
db71dc8323006a57ccc283f689af43a7128bec65
[ "MIT" ]
46
2016-06-06T03:00:03.000Z
2022-03-15T16:43:16.000Z
public protocol DetailRouterTransitionable: class { /// ссылка на обработчика переходов var detailTransitionsHandlerBox: RouterTransitionsHandlerBox { get } }
33.4
72
0.796407
78f419117c2fbb2c806772d8048262c1ef07dee9
1,869
dart
Dart
test/theme/bloc/theme_state_test.dart
lgjenero/puzzle_challenge
f7adce99490fa39ce1e9f870177f8284a3e248e2
[ "MIT" ]
null
null
null
test/theme/bloc/theme_state_test.dart
lgjenero/puzzle_challenge
f7adce99490fa39ce1e9f870177f8284a3e248e2
[ "MIT" ]
null
null
null
test/theme/bloc/theme_state_test.dart
lgjenero/puzzle_challenge
f7adce99490fa39ce1e9f870177f8284a3e248e2
[ "MIT" ]
null
null
null
// ignore_for_file: prefer_const_constructors import 'package:flutter_test/flutter_test.dart'; import 'package:very_good_slide_puzzle/dungeon/dungeon.dart'; import 'package:very_good_slide_puzzle/house/house_theme.dart'; import 'package:very_good_slide_puzzle/platform/platform_theme.dart'; import 'package:very_good_slide_puzzle/theme/theme.dart'; import '../../helpers/helpers.dart'; void main() { group('ThemeState', () { test('supports value comparisons', () { final themes = [MockPuzzleTheme(), MockPuzzleTheme()]; expect( ThemeState( themes: themes, theme: themes[0], ), equals( ThemeState( themes: themes, theme: themes[0], ), ), ); }); test('default theme is SimpleTheme', () { expect( ThemeState(themes: const [HouseTheme()]).theme, equals(HouseTheme()), ); }); group('copyWith', () { test('updates themes', () { final themesA = [HouseTheme(), DungeonTheme()]; final themesB = [HouseTheme(), PlatformTheme()]; expect( ThemeState( themes: themesA, theme: HouseTheme(), ).copyWith(themes: themesB), equals( ThemeState( themes: themesB, theme: HouseTheme(), ), ), ); }); test('updates theme', () { final themes = [HouseTheme(), DungeonTheme()]; final themeA = HouseTheme(); final themeB = DungeonTheme(); expect( ThemeState( themes: themes, theme: themeA, ).copyWith(theme: themeB), equals( ThemeState( themes: themes, theme: themeB, ), ), ); }); }); }); }
24.592105
69
0.524345
378333cdd7971c58ab29b4cc689a87a87c731944
2,126
kt
Kotlin
src/bluetooth/BluetoothDiffieHellmanHandshakeService.kt
Penguin-Dream-Team/PenguBank-Desktop
79d85a99ca99529116e8ca5e7f20571b8b6b3f43
[ "MIT" ]
null
null
null
src/bluetooth/BluetoothDiffieHellmanHandshakeService.kt
Penguin-Dream-Team/PenguBank-Desktop
79d85a99ca99529116e8ca5e7f20571b8b6b3f43
[ "MIT" ]
null
null
null
src/bluetooth/BluetoothDiffieHellmanHandshakeService.kt
Penguin-Dream-Team/PenguBank-Desktop
79d85a99ca99529116e8ca5e7f20571b8b6b3f43
[ "MIT" ]
null
null
null
package bluetooth import bluetooth.models.messages.DiffieHellmanInitRequestMessage import bluetooth.models.messages.DiffieHellmanInitResponseMessage import controllers.BluetoothConnectionController import exceptions.BluetoothMessageSignatureFailedException import security.SignatureConnectionHandler import utils.DiffieHellmanUtils import java.io.DataInputStream import java.io.DataOutputStream import javax.crypto.SecretKey class BluetoothDiffieHellmanHandshakeService( securityConnection: SignatureConnectionHandler, bluetoothConnectionController: BluetoothConnectionController, inputStream: DataInputStream, outputStream: DataOutputStream ) : BluetoothService(securityConnection, inputStream, outputStream) { init { val (keyAgreement, keyPair) = DiffieHellmanUtils.init() var signatureFailed = false lateinit var secretKey: SecretKey do { try { // send diffie hellman public a val myPublicY = DiffieHellmanUtils.retrieveYFromPublicKey(keyPair) sendMessage(DiffieHellmanInitRequestMessage(myPublicY)) // receive diffie hellman public b val response = receiveMessage<DiffieHellmanInitResponseMessage>() val otherPublicKey = DiffieHellmanUtils.parsePublicKeyFromY(keyPair, response.publicY) // generate key secretKey = DiffieHellmanUtils.generateSecretKey(keyAgreement, otherPublicKey) } catch (e: BluetoothMessageSignatureFailedException) { // Do nothing, continue loop e.printStackTrace() signatureFailed = true } } while (signatureFailed) bluetoothConnectionController.connected = true // start secured communication protocol with newly generated shared secret key BluetoothCommunicationService( secretKey, securityConnection, bluetoothConnectionController, inputStream, outputStream ) bluetoothConnectionController.connected = false } }
36.655172
102
0.708373
80220c757fc906866a2e617f444c0dd7ead3d2aa
875
java
Java
apps/endringsmelding-frontend/src/main/java/no/nav/testnav/apps/endringsmeldingfrontend/config/SecurityConfig.java
navikt/testnorge
8400ad28d37ec5dee87a4fe76e233632d2cfdbd1
[ "MIT" ]
3
2020-06-30T18:14:44.000Z
2022-03-07T10:10:48.000Z
apps/endringsmelding-frontend/src/main/java/no/nav/testnav/apps/endringsmeldingfrontend/config/SecurityConfig.java
navikt/testnorge
8400ad28d37ec5dee87a4fe76e233632d2cfdbd1
[ "MIT" ]
1,546
2020-05-25T14:39:45.000Z
2022-03-31T13:41:00.000Z
apps/endringsmelding-frontend/src/main/java/no/nav/testnav/apps/endringsmeldingfrontend/config/SecurityConfig.java
navikt/testnorge
8400ad28d37ec5dee87a4fe76e233632d2cfdbd1
[ "MIT" ]
1
2021-11-03T16:02:17.000Z
2021-11-03T16:02:17.000Z
package no.nav.testnav.apps.endringsmeldingfrontend.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.web.server.SecurityWebFilterChain; @Configuration @EnableWebFluxSecurity public class SecurityConfig { @Bean public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { return http.csrf() .disable() .authorizeExchange() .pathMatchers("/internal/isReady", "/internal/isAlive").permitAll() .anyExchange().authenticated() .and().oauth2Login() .and().build(); } }
36.458333
89
0.722286
59b5e9ab376657d5a8acf81c3505fca9e2443aff
2,163
hpp
C++
src/network/Network.hpp
IPetr0v/compromutator
6e1c34b5238a78f7f2f1628504103edfcb145523
[ "Apache-2.0" ]
null
null
null
src/network/Network.hpp
IPetr0v/compromutator
6e1c34b5238a78f7f2f1628504103edfcb145523
[ "Apache-2.0" ]
null
null
null
src/network/Network.hpp
IPetr0v/compromutator
6e1c34b5238a78f7f2f1628504103edfcb145523
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Rule.hpp" #include "Switch.hpp" #include "../openflow/Action.hpp" #include "../Types.hpp" #include <map> #include <memory> #include <vector> struct Link { PortPtr src_port; PortPtr dst_port; static Link inverse(Link link) {return {link.dst_port, link.src_port};} }; class Network { public: Network(); ~Network(); // Switch management SwitchPtr getSwitch(SwitchId id) const; SwitchPtr addSwitch(const SwitchInfo& info); void deleteSwitch(SwitchId id); TablePtr getTable(SwitchId switch_id, TableId table_id) const; PortPtr getPort(TopoId topo_id) const; // Rule management RulePtr rule(RuleId id) const; RulePtr rule(SwitchId switch_id, TableId table_id, Priority priority, const Match& match); RulePtr addRule(SwitchId switch_id, TableId table_id, Priority priority, Cookie cookie, Match&& match, ActionsBase&& actions_base); void deleteRule(RuleId id); std::list<RulePtr> matchingRules(SwitchId switch_id, TableId table_id, const Match& match); PortPtr adjacentPort(PortPtr port) const; std::pair<Link, bool> link(TopoId src_topo_id, TopoId dst_topo_id); std::pair<Link, bool> addLink(TopoId src_topo_id, TopoId dst_topo_id); std::pair<Link, bool> deleteLink(TopoId src_topo_id, TopoId dst_topo_id); RulePtr dropRule() const {return drop_rule_;} RulePtr controllerRule() const {return controller_rule_;} bool empty() const { return switch_map_.empty();} size_t size() const {return switch_map_.size();} // TODO: use RuleRange std::vector<RulePtr> rules(); private: std::map<SwitchId, SwitchPtr> switch_map_; // Topology keeps links as pairs {src_topo_id, dst_port_ptr} std::map<TopoId, PortPtr> topology_; // Special rules RulePtr drop_rule_; RulePtr controller_rule_; std::pair<bool, Actions> get_actions(SwitchPtr sw, ActionsBase&& actions_base) const; void add_rule_to_topology(RulePtr rule); void delete_rule_from_topology(RulePtr rule); };
29.630137
77
0.675913
50ed2e256e896c9de0d9b4745cf3d9f3fee683f2
6,626
lua
Lua
receive_fields.lua
pandorabox-io/fancy_vend
0bed2e5bd98fb74705802ba21f5cd067604f473c
[ "MIT" ]
null
null
null
receive_fields.lua
pandorabox-io/fancy_vend
0bed2e5bd98fb74705802ba21f5cd067604f473c
[ "MIT" ]
4
2019-11-11T07:20:33.000Z
2022-02-06T04:06:08.000Z
receive_fields.lua
pandorabox-io/fancy_vend
0bed2e5bd98fb74705802ba21f5cd067604f473c
[ "MIT" ]
1
2019-11-10T17:56:03.000Z
2019-11-10T17:56:03.000Z
local has_digilines = minetest.get_modpath("digilines") local function get_max_lots(pos, player) local max = 0 while fancy_vend.run_inv_checks(pos, player, max).overall do max = max + 1 end return math.max(0, max -1) end minetest.register_on_player_receive_fields(function(player, formname, fields) local name = formname:split(":")[1] if name ~= "fancy_vend" then return end local formtype = formname:split(":")[2] formtype = formtype:split(";")[1] local pos = minetest.string_to_pos(formname:split(";")[2]) if not pos then return end local node = minetest.get_node(pos) if not fancy_vend.is_vendor(node.name) then return end local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local player_inv = player:get_inventory() local settings = fancy_vend.get_vendor_settings(pos) -- Handle settings changes if fancy_vend.can_modify_vendor(pos, player) then for i in pairs(fields) do if fancy_vend.stb(fields[i]) ~= settings[i] then settings[i] = fancy_vend.stb(fields[i]) end end -- Check number-only fields contain only numbers if not tonumber(settings.input_item_qty) then settings.input_item_qty = 1 else settings.input_item_qty = math.floor(math.abs(tonumber(settings.input_item_qty))) end if not tonumber(settings.output_item_qty) then settings.output_item_qty = 1 else settings.output_item_qty = math.floor(math.abs(tonumber(settings.output_item_qty))) end -- Check item quantities aren't too high (which could lead to additional -- processing for no reason), if so, set it to the maximum the player inventory can handle if ItemStack(settings.output_item):get_stack_max() * player_inv:get_size("main") < settings.output_item_qty then settings.output_item_qty = ItemStack(settings.output_item):get_stack_max() * player_inv:get_size("main") end if ItemStack(settings.input_item):get_stack_max() * player_inv:get_size("main") < settings.input_item_qty then settings.input_item_qty = ItemStack(settings.input_item):get_stack_max() * player_inv:get_size("main") end -- Admin vendor priv check if not minetest.check_player_privs(meta:get_string("owner"), {admin_vendor = true}) and fields.admin_vendor == "true" then settings.admin_vendor = false end fancy_vend.set_vendor_settings(pos, settings) fancy_vend.refresh_vendor(pos) end if fields.quit then if fancy_vend.can_access_vendor_inv(player, pos) and settings.auto_sort then fancy_vend.sort_inventory(inv) end return true end if fields.sort and fancy_vend.can_access_vendor_inv(player, pos) then fancy_vend.sort_inventory(inv) end if fields.buy then local lots = math.floor(tonumber(fields.lot_count) or 1) -- prevent negative numbers lots = math.max(lots, 1) local success, message = fancy_vend.make_purchase(pos, player, lots) if success then -- Add to vendor logs local logs = minetest.deserialize(meta:get_string("log")) for i in pairs(logs) do if i >= fancy_vend.max_logs then table.remove(logs, 1) end end table.insert(logs, "Player "..player:get_player_name().." purchased "..lots.." lots from this vendor.") meta:set_string("log", minetest.serialize(logs)) -- Send digiline message if applicable if has_digilines then local msg = { buyer = player:get_player_name(), lots = lots, settings = settings, } fancy_vend.send_message(pos, settings.digiline_channel, msg) end end -- Set message and refresh vendor if message then meta:set_string("message", message) end fancy_vend.refresh_vendor(pos) elseif fields.lot_fill then minetest.show_formspec( player:get_player_name(), "fancy_vend:buyer;"..minetest.pos_to_string(pos), fancy_vend.get_vendor_buyer_fs(pos, player, get_max_lots(pos, player)) ) return true end if fancy_vend.can_access_vendor_inv(player, pos) then if fields.inv_tovendor then minetest.log("action", player:get_player_name().. " moves inventory contents to vendor at ".. minetest.pos_to_string(pos) ) fancy_vend.move_inv(player_inv, inv, nil) fancy_vend.refresh_vendor(pos) elseif fields.inv_output_tovendor then minetest.log("action", player:get_player_name().. " moves output items in inventory to vendor at ".. minetest.pos_to_string(pos) ) fancy_vend.move_inv(player_inv, inv, settings.output_item) fancy_vend.refresh_vendor(pos) elseif fields.inv_fromvendor then minetest.log("action", player:get_player_name().. " moves inventory contents from vendor at ".. minetest.pos_to_string(pos) ) fancy_vend.move_inv(inv, player_inv, nil) fancy_vend.refresh_vendor(pos) elseif fields.inv_input_fromvendor then minetest.log("action", player:get_player_name().. " moves input items from vendor at ".. minetest.pos_to_string(pos) ) fancy_vend.move_inv(inv, player_inv, settings.input_item) fancy_vend.refresh_vendor(pos) end end -- Handle page changes if fields.button_log then minetest.show_formspec( player:get_player_name(), "fancy_vend:log;"..minetest.pos_to_string(pos), fancy_vend.get_vendor_log_fs(pos) ) return elseif fields.button_settings then minetest.show_formspec( player:get_player_name(), "fancy_vend:settings;"..minetest.pos_to_string(pos), fancy_vend.get_vendor_settings_fs(pos) ) return elseif fields.button_inv then minetest.show_formspec( player:get_player_name(), "fancy_vend:default;"..minetest.pos_to_string(pos), fancy_vend.get_vendor_default_fs(pos, player) ) return elseif fields.button_buy then minetest.show_formspec( player:get_player_name(), "fancy_vend:buyer;"..minetest.pos_to_string(pos), fancy_vend.get_vendor_buyer_fs(pos, player, (tonumber(fields.lot_count) or 1)) ) return end -- Update formspec if formtype == "log" then minetest.show_formspec( player:get_player_name(), "fancy_vend:log;"..minetest.pos_to_string(pos), fancy_vend.get_vendor_log_fs(pos, player) ) elseif formtype == "settings" then minetest.show_formspec( player:get_player_name(), "fancy_vend:settings;"..minetest.pos_to_string(pos), fancy_vend.get_vendor_settings_fs(pos, player) ) elseif formtype == "default" then minetest.show_formspec( player:get_player_name(), "fancy_vend:default;"..minetest.pos_to_string(pos), fancy_vend.get_vendor_default_fs(pos, player) ) elseif formtype == "buyer" then minetest.show_formspec( player:get_player_name(), "fancy_vend:buyer;"..minetest.pos_to_string(pos), fancy_vend.get_vendor_buyer_fs(pos, player, (tonumber(fields.lot_count) or 1)) ) end end)
31.552381
114
0.742982