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
a6fd78ef85cfd051fd217ae3de7d09ca0a33be99
1,324
rb
Ruby
test/reynard/schema_test.rb
Manfred/Reynard
85f8610fd91e13b0200569d43ca40238db148a8d
[ "MIT" ]
1
2021-10-06T20:22:15.000Z
2021-10-06T20:22:15.000Z
test/reynard/schema_test.rb
Manfred/Reynard
85f8610fd91e13b0200569d43ca40238db148a8d
[ "MIT" ]
10
2021-11-04T10:03:02.000Z
2022-02-23T11:20:40.000Z
test/reynard/schema_test.rb
Manfred/Reynard
85f8610fd91e13b0200569d43ca40238db148a8d
[ "MIT" ]
1
2021-10-14T13:38:36.000Z
2021-10-14T13:38:36.000Z
# frozen_string_literal: true require_relative '../test_helper' class Reynard class SchemaTest < Reynard::Test def setup @node = %w[ paths /books/{id} get responses 200 content application/json schema ] @schema = Schema.new( node: @node, object_type: 'object', item_schema_name: nil ) end test 'returns its node' do assert_equal @node, @schema.node end test 'returns its object type' do assert_equal 'object', @schema.object_type end test 'does not return an item schema name' do assert_nil @schema.item_schema_name end end class CollectionSchemaTest < Reynard::Test def setup @node = %w[ paths /books get responses 200 content application/json schema ] @schema = Schema.new( node: @node, object_type: 'array', item_schema_name: 'Book' ) end test 'returns its node' do assert_equal @node, @schema.node end test 'returns its object type' do assert_equal 'array', @schema.object_type end test 'returns its item schema name' do assert_equal 'Book', @schema.item_schema_name end end end
18.914286
51
0.573263
9044d5d321a3de506ddb75b31186c0e454e20ac0
1,066
h
C
Engine/Source/Runtime/Engine/Public/CustomPhysXPayload.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/Engine/Public/CustomPhysXPayload.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/Engine/Public/CustomPhysXPayload.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "EngineDefines.h" #include "Components/PrimitiveComponent.h" #if WITH_PHYSX namespace physx { class PxRigidActor; } struct FCustomPhysXSyncActors { virtual ~FCustomPhysXSyncActors() {} /** Update any UE4 data as needed given the actors that moved as a result of the simulation*/ virtual void SyncToActors_AssumesLocked(int32 SceneType, const TArray<physx::PxRigidActor*>& RigidActors) = 0; private: friend class FPhysScene; TArray<physx::PxRigidActor*> Actors; }; struct FBodyInstance; struct FCustomPhysXPayload { FCustomPhysXPayload(FCustomPhysXSyncActors* InCustomSyncActors) : CustomSyncActors(InCustomSyncActors) { } virtual ~FCustomPhysXPayload(){} virtual TWeakObjectPtr<UPrimitiveComponent> GetOwningComponent() const = 0; virtual int32 GetItemIndex() const = 0; virtual FName GetBoneName() const = 0; virtual FBodyInstance* GetBodyInstance() const = 0; FCustomPhysXSyncActors* CustomSyncActors; }; #endif // WITH_PHYSICS
23.173913
111
0.781426
2ca87bae7f11b13142de7d3ee4935ff338a1a172
10,072
cpp
C++
Examples/PatternedSubstrate/PatternedSubstrate.cpp
YourKarma42/ViennaLS
aae39a860e1fb6edc2d3568ab09110f7e81572b1
[ "MIT" ]
6
2019-11-18T16:05:12.000Z
2021-06-16T16:11:41.000Z
Examples/PatternedSubstrate/PatternedSubstrate.cpp
YourKarma42/ViennaLS
aae39a860e1fb6edc2d3568ab09110f7e81572b1
[ "MIT" ]
26
2019-10-17T14:59:31.000Z
2022-02-07T17:06:30.000Z
Examples/PatternedSubstrate/PatternedSubstrate.cpp
YourKarma42/ViennaLS
aae39a860e1fb6edc2d3568ab09110f7e81572b1
[ "MIT" ]
7
2020-03-13T07:17:07.000Z
2022-03-29T07:58:37.000Z
#include <iostream> #include <random> #include <lsAdvect.hpp> #include <lsBooleanOperation.hpp> #include <lsConvexHull.hpp> #include <lsDomain.hpp> #include <lsExpand.hpp> #include <lsMakeGeometry.hpp> #include <lsPrune.hpp> #include <lsSmartPointer.hpp> #include <lsToDiskMesh.hpp> #include <lsToMesh.hpp> #include <lsToSurfaceMesh.hpp> #include <lsToVoxelMesh.hpp> #include <lsVTKWriter.hpp> /** 3D Example showing how to use the library for topography simulation. A hexagonal pattern of rounded cones is formed. These cones are then used as masks for etching. A uniform layer is then deposited on top creating voids in the structure. \example PatternedSubstrate.cpp */ // implement velocity field describing a directional etch class directionalEtch : public lsVelocityField<double> { public: double getScalarVelocity(const std::array<double, 3> & /*coordinate*/, int material, const std::array<double, 3> &normalVector, unsigned long /*pointId*/) { // etch directionally if (material > 0) { return (normalVector[2] > 0.) ? -normalVector[2] : 0; } else { return 0; } } std::array<double, 3> getVectorVelocity(const std::array<double, 3> & /*coordinate*/, int /*material*/, const std::array<double, 3> & /*normalVector*/, unsigned long /*pointId*/) { return std::array<double, 3>({}); } }; // implement velocity field describing an isotropic deposition class isotropicDepo : public lsVelocityField<double> { public: double getScalarVelocity(const std::array<double, 3> & /*coordinate*/, int /*material*/, const std::array<double, 3> & /*normalVector*/, unsigned long /*pointId*/) { // deposit isotropically everywhere return 1; } std::array<double, 3> getVectorVelocity(const std::array<double, 3> & /*coordinate*/, int /*material*/, const std::array<double, 3> & /*normalVector*/, unsigned long /*pointId*/) { return std::array<double, 3>({}); } }; // create a rounded cone as the primitive pattern. // Define a pointcloud and create a hull mesh using lsConvexHull. void makeRoundCone(lsSmartPointer<lsMesh<>> mesh, hrleVectorType<double, 3> center, double radius, double height) { // cone is just a circle with a point above the center auto cloud = lsSmartPointer<lsPointCloud<double, 3>>::New(); // frist inside top point { hrleVectorType<double, 3> topPoint = center; topPoint[2] += height; cloud->insertNextPoint(topPoint); } // now create all points of the base unsigned numberOfBasePoints = 40; unsigned numberOfEdgePoints = 7; for (unsigned i = 0; i < numberOfBasePoints; ++i) { double angle = double(i) / double(numberOfBasePoints) * 2. * 3.141592; for (unsigned j = 1; j <= numberOfEdgePoints; ++j) { double distance = double(j) / double(numberOfEdgePoints) * radius; double pointHeight = std::sqrt(double(numberOfEdgePoints - j) / double(numberOfEdgePoints)) * height; double x = center[0] + distance * cos(angle); double y = center[1] + distance * sin(angle); cloud->insertNextPoint( hrleVectorType<double, 3>(x, y, center[2] + pointHeight)); } } lsConvexHull<double, 3>(mesh, cloud).apply(); } int main() { constexpr int D = 3; omp_set_num_threads(6); // scale in micrometers double coneDistance = 3.5; double xExtent = 21; double yConeDelta = std::sqrt(3) * coneDistance / 2; double yExtent = 6 * yConeDelta; double gridDelta = 0.15; double bounds[2 * D] = {-xExtent / 2., xExtent / 2., -yExtent / 2., yExtent / 2., -5, 5}; lsDomain<double, D>::BoundaryType boundaryCons[D]; boundaryCons[0] = lsDomain<double, D>::BoundaryType::PERIODIC_BOUNDARY; boundaryCons[1] = lsDomain<double, D>::BoundaryType::PERIODIC_BOUNDARY; boundaryCons[2] = lsDomain<double, D>::BoundaryType::INFINITE_BOUNDARY; auto substrate = lsSmartPointer<lsDomain<double, D>>::New(bounds, boundaryCons, gridDelta); { double origin[3] = {0., 0., 0.001}; double planeNormal[3] = {0., 0., 1.}; auto plane = lsSmartPointer<lsPlane<double, D>>::New(origin, planeNormal); lsMakeGeometry<double, D>(substrate, plane).apply(); } // copy the structure to add the pattern on top auto pattern = lsSmartPointer<lsDomain<double, D>>::New(bounds, boundaryCons, gridDelta); pattern->setLevelSetWidth(2); // Create varying cones and put them in hexagonal pattern --------- { std::cout << "Creating pattern..." << std::endl; // need to place cone one grid delta below surface to avoid rounding hrleVectorType<double, D> coneCenter(-xExtent / 2.0 + coneDistance / 2.0, -3 * yConeDelta, -gridDelta); double coneRadius = 1.4; double coneHeight = 1.5; // adjust since cone is slightly below the surface { double gradient = coneHeight / coneRadius; coneRadius += gridDelta / gradient; coneHeight += gridDelta * gradient; } // random radius cones double variation = 0.1; std::mt19937 gen(532132432); std::uniform_real_distribution<> dis(1 - variation, 1 + variation); // for each row for (unsigned j = 0; j < 6; ++j) { // for each cone in a row for (unsigned i = 0; i < 6; ++i) { // make ls from cone mesh and add to substrate auto cone = lsSmartPointer<lsDomain<double, D>>::New( bounds, boundaryCons, gridDelta); // create cone auto coneMesh = lsSmartPointer<lsMesh<>>::New(); makeRoundCone(coneMesh, coneCenter, coneRadius * dis(gen), coneHeight * dis(gen)); lsFromSurfaceMesh<double, D>(cone, coneMesh, false).apply(); lsBooleanOperation<double, D> boolOp(pattern, cone, lsBooleanOperationEnum::UNION); boolOp.apply(); // now shift mesh for next bool coneCenter[0] += coneDistance; } coneCenter[0] = -xExtent / 2. + ((j % 2) ? coneDistance / 2.0 : 0); coneCenter[1] += yConeDelta; } } lsBooleanOperation<double, D>(substrate, pattern, lsBooleanOperationEnum::UNION) .apply(); // Etch the substrate under the pattern --------------------------- unsigned numberOfEtchSteps = 30; std::cout << "Advecting" << std::endl; lsAdvect<double, D> advectionKernel; advectionKernel.insertNextLevelSet(pattern); advectionKernel.insertNextLevelSet(substrate); { auto velocities = lsSmartPointer<directionalEtch>::New(); advectionKernel.setVelocityField(velocities); // Now advect the level set, outputting every // advection step. Save the physical time that // passed during the advection. double passedTime = 0.; for (unsigned i = 0; i < numberOfEtchSteps; ++i) { std::cout << "\rEtch step " + std::to_string(i) + " / " << numberOfEtchSteps << std::flush; auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, "substrate-" + std::to_string(i) + ".vtp") .apply(); advectionKernel.apply(); passedTime += advectionKernel.getAdvectedTime(); } std::cout << std::endl; { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, "substrate-" + std::to_string(numberOfEtchSteps) + ".vtp") .apply(); } std::cout << "Time passed during directional etch: " << passedTime << std::endl; } // make disk mesh and output { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToDiskMesh<double, 3>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, lsFileFormatEnum::VTP, "diskMesh.vtp").apply(); } // Deposit new layer ---------------------------------------------- // new level set for new layer auto fillLayer = lsSmartPointer<lsDomain<double, D>>::New(substrate); { auto velocities = lsSmartPointer<isotropicDepo>::New(); advectionKernel.setVelocityField(velocities); advectionKernel.insertNextLevelSet(fillLayer); // stop advection in voids, which will form advectionKernel.setIgnoreVoids(true); double passedTime = 0.; unsigned numberOfDepoSteps = 30; for (unsigned i = 0; i < numberOfDepoSteps; ++i) { std::cout << "\rDepo step " + std::to_string(i) + " / " << numberOfDepoSteps << std::flush; auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(fillLayer, mesh).apply(); lsVTKWriter<double>(mesh, "fillLayer-" + std::to_string(numberOfEtchSteps + 1 + i) + ".vtp") .apply(); advectionKernel.apply(); passedTime += advectionKernel.getAdvectedTime(); } std::cout << std::endl; { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(fillLayer, mesh).apply(); lsVTKWriter<double>( mesh, "fillLayer-" + std::to_string(numberOfEtchSteps + numberOfDepoSteps) + ".vtp") .apply(); } std::cout << "Time passed during isotropic deposition: " << passedTime << std::endl; } // now output the final level sets { auto mesh = lsSmartPointer<lsMesh<>>::New(); lsToSurfaceMesh<double, D>(substrate, mesh).apply(); lsVTKWriter<double>(mesh, "final-substrate.vtp").apply(); lsToSurfaceMesh<double, D>(fillLayer, mesh).apply(); lsVTKWriter<double>(mesh, "final-fillLayer.vtp").apply(); } return 0; }
34.611684
80
0.606732
774f0b311da0ca34695c8823addac69b060109bf
105
sql
SQL
database/sqlserver/monit-queries/checkLocksOnDatabase.sql
hpettenuci/operation
5a079adcf375145f782587a9f0a03cf860841d44
[ "Apache-2.0" ]
2
2021-01-05T18:26:42.000Z
2021-09-17T13:00:26.000Z
database/sqlserver/monit-queries/checkLocksOnDatabase.sql
hpettenuci/operation
5a079adcf375145f782587a9f0a03cf860841d44
[ "Apache-2.0" ]
null
null
null
database/sqlserver/monit-queries/checkLocksOnDatabase.sql
hpettenuci/operation
5a079adcf375145f782587a9f0a03cf860841d44
[ "Apache-2.0" ]
null
null
null
select * from Resultado_WhoisActive where blocking_session_id is not null order by [dd hh:mm:ss.mss] desc
105
105
0.819048
c98113439e3d09bb13ad30ba63c45a699182381b
977
tsx
TypeScript
AppZ.tsx
sizplay/react_native_gangnam
4ebbe1501988babe71ccad96f83dd3c79f06ce2d
[ "MIT" ]
null
null
null
AppZ.tsx
sizplay/react_native_gangnam
4ebbe1501988babe71ccad96f83dd3c79f06ce2d
[ "MIT" ]
2
2021-05-08T09:43:24.000Z
2021-05-10T18:04:01.000Z
AppZ.tsx
sizplay/react_native_gangnam
4ebbe1501988babe71ccad96f83dd3c79f06ce2d
[ "MIT" ]
7
2019-09-23T22:46:14.000Z
2019-11-04T04:08:56.000Z
import React, {Component} from 'react'; import {StyleSheet, Text, View} from 'react-native'; import UserInfoList from './components/UserInfoList'; interface IProps { } const App: React.FC<IProps> = () => { return ( <View style={styles.container}> <View style={styles.header}> <Text style={styles.title}>♘ User Info List..</Text> </View> <View style={styles.main}> <UserInfoList /> </View> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#262926', alignItems: 'flex-start' }, header: { marginTop: 80, backgroundColor: 'black', width: '100%' }, title: { fontSize: 40, color: 'white', marginLeft: 20 }, main: { width: '100%', marginTop: 20, marginHorizontal: 'auto', display: 'flex', alignItems: 'center' } }); export default App;
20.354167
60
0.539406
4110ca6a2febec27287936c69460d4d301075175
11,435
rs
Rust
test-utils/src/mocks.rs
Aloxaf/jsonrpsee
1730368adaf22200c52da011b9db11b4397948c4
[ "MIT" ]
null
null
null
test-utils/src/mocks.rs
Aloxaf/jsonrpsee
1730368adaf22200c52da011b9db11b4397948c4
[ "MIT" ]
null
null
null
test-utils/src/mocks.rs
Aloxaf/jsonrpsee
1730368adaf22200c52da011b9db11b4397948c4
[ "MIT" ]
1
2022-03-13T15:28:02.000Z
2022-03-13T15:28:02.000Z
// Copyright 2019-2021 Parity Technologies (UK) Ltd. // // 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. use std::io; use std::net::SocketAddr; use std::time::Duration; use futures_channel::mpsc::{self, Receiver, Sender}; use futures_channel::oneshot; use futures_util::future::FutureExt; use futures_util::io::{BufReader, BufWriter}; use futures_util::sink::SinkExt; use futures_util::stream::{self, StreamExt}; use futures_util::{pin_mut, select}; use serde::{Deserialize, Serialize}; use soketto::handshake::{self, http::is_upgrade_request, server::Response, Error as SokettoError, Server}; use tokio::net::TcpStream; use tokio_util::compat::{Compat, TokioAsyncReadCompatExt}; pub use hyper::{Body, HeaderMap, StatusCode, Uri}; type Error = Box<dyn std::error::Error>; pub struct TestContext; impl TestContext { pub fn ok(&self) -> Result<(), anyhow::Error> { Ok(()) } pub fn err(&self) -> Result<(), anyhow::Error> { Err(anyhow::anyhow!("RPC context failed")) } } /// Request Id #[derive(Debug, PartialEq, Clone, Hash, Eq, Deserialize, Serialize)] #[serde(deny_unknown_fields)] #[serde(untagged)] pub enum Id { /// No id (notification) Null, /// Numeric id Num(u64), /// String id Str(String), } #[derive(Debug)] pub struct HttpResponse { pub status: StatusCode, pub header: HeaderMap, pub body: String, } /// WebSocket client to construct with arbitrary payload to construct bad payloads. pub struct WebSocketTestClient { tx: soketto::Sender<BufReader<BufWriter<Compat<TcpStream>>>>, rx: soketto::Receiver<BufReader<BufWriter<Compat<TcpStream>>>>, } impl std::fmt::Debug for WebSocketTestClient { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "WebSocketTestClient") } } #[derive(Debug)] pub enum WebSocketTestError { Redirect, RejectedWithStatusCode(u16), Soketto(SokettoError), } impl From<io::Error> for WebSocketTestError { fn from(err: io::Error) -> Self { WebSocketTestError::Soketto(SokettoError::Io(err)) } } impl WebSocketTestClient { pub async fn new(url: SocketAddr) -> Result<Self, WebSocketTestError> { let socket = TcpStream::connect(url).await?; let mut client = handshake::Client::new(BufReader::new(BufWriter::new(socket.compat())), "test-client", "/"); match client.handshake().await { Ok(handshake::ServerResponse::Accepted { .. }) => { let (tx, rx) = client.into_builder().finish(); Ok(Self { tx, rx }) } Ok(handshake::ServerResponse::Redirect { .. }) => Err(WebSocketTestError::Redirect), Ok(handshake::ServerResponse::Rejected { status_code }) => { Err(WebSocketTestError::RejectedWithStatusCode(status_code)) } Err(err) => Err(WebSocketTestError::Soketto(err)), } } pub async fn send_request_text(&mut self, msg: impl AsRef<str>) -> Result<String, Error> { self.tx.send_text(msg).await?; self.tx.flush().await?; let mut data = Vec::new(); self.rx.receive_data(&mut data).await?; String::from_utf8(data).map_err(Into::into) } pub async fn send_request_binary(&mut self, msg: &[u8]) -> Result<String, Error> { self.tx.send_binary(msg).await?; self.tx.flush().await?; let mut data = Vec::new(); self.rx.receive_data(&mut data).await?; String::from_utf8(data).map_err(Into::into) } pub async fn close(&mut self) -> Result<(), Error> { self.tx.close().await.map_err(Into::into) } } #[derive(Debug, Clone)] pub enum ServerMode { // Send out a hardcoded response on every connection. Response(String), // Send out a subscription ID on a request and continuously send out data on the subscription. Subscription { subscription_id: String, subscription_response: String }, // Send out a notification after timeout Notification(String), } /// JSONRPC v2 dummy WebSocket server that sends a hardcoded response. pub struct WebSocketTestServer { local_addr: SocketAddr, exit: Sender<()>, } impl WebSocketTestServer { // Spawns a dummy `JSONRPC v2` WebSocket server that sends out a pre-configured `hardcoded response` for every // connection. pub async fn with_hardcoded_response(sockaddr: SocketAddr, response: String) -> Self { let listener = tokio::net::TcpListener::bind(sockaddr).await.unwrap(); let local_addr = listener.local_addr().unwrap(); let (tx, rx) = mpsc::channel::<()>(4); tokio::spawn(server_backend(listener, rx, ServerMode::Response(response))); Self { local_addr, exit: tx } } // Spawns a dummy `JSONRPC v2` WebSocket server that sends out a pre-configured `hardcoded notification` for every // connection. pub async fn with_hardcoded_notification(sockaddr: SocketAddr, notification: String) -> Self { let (tx, rx) = mpsc::channel::<()>(1); let (addr_tx, addr_rx) = oneshot::channel(); std::thread::spawn(move || { let rt = tokio::runtime::Runtime::new().unwrap(); let listener = rt.block_on(tokio::net::TcpListener::bind(sockaddr)).unwrap(); let local_addr = listener.local_addr().unwrap(); addr_tx.send(local_addr).unwrap(); rt.block_on(server_backend(listener, rx, ServerMode::Notification(notification))); }); let local_addr = addr_rx.await.unwrap(); Self { local_addr, exit: tx } } // Spawns a dummy `JSONRPC v2` WebSocket server that sends out a pre-configured subscription ID and subscription // response. // // NOTE: ignores the actual subscription and unsubscription method. pub async fn with_hardcoded_subscription( sockaddr: SocketAddr, subscription_id: String, subscription_response: String, ) -> Self { let listener = tokio::net::TcpListener::bind(sockaddr).await.unwrap(); let local_addr = listener.local_addr().unwrap(); let (tx, rx) = mpsc::channel::<()>(4); tokio::spawn(server_backend(listener, rx, ServerMode::Subscription { subscription_id, subscription_response })); Self { local_addr, exit: tx } } pub fn local_addr(&self) -> SocketAddr { self.local_addr } pub async fn close(&mut self) { self.exit.send(()).await.unwrap(); } } async fn server_backend(listener: tokio::net::TcpListener, mut exit: Receiver<()>, mode: ServerMode) { let mut connections = Vec::new(); loop { let conn_fut = listener.accept().fuse(); let exit_fut = exit.next(); pin_mut!(exit_fut, conn_fut); select! { _ = exit_fut => break, conn = conn_fut => { if let Ok((stream, _)) = conn { let (tx, rx) = mpsc::channel::<()>(4); let handle = tokio::spawn(connection_task(stream, mode.clone(), rx)); connections.push((handle, tx)); } } } } // close connections for (handle, mut exit) in connections { // If the actual connection was never established i.e., returned early // It will most likely be caught on the client-side but just to be explicit. exit.send(()).await.expect("WebSocket connection was never established"); handle.await.unwrap(); } } async fn connection_task(socket: tokio::net::TcpStream, mode: ServerMode, mut exit: Receiver<()>) { let mut server = Server::new(socket.compat()); let key = match server.receive_request().await { Ok(req) => req.key(), Err(_) => return, }; let accept = server.send_response(&Response::Accept { key, protocol: None }).await; if accept.is_err() { return; } let (mut sender, receiver) = server.into_builder().finish(); let ws_stream = stream::unfold(receiver, move |mut receiver| async { let mut buf = Vec::new(); let ret = match receiver.receive_data(&mut buf).await { Ok(_) => Ok(buf), Err(err) => Err(err), }; Some((ret, receiver)) }); pin_mut!(ws_stream); loop { let next_ws = ws_stream.next().fuse(); let next_exit = exit.next().fuse(); let time_out = tokio::time::sleep(Duration::from_millis(200)).fuse(); pin_mut!(time_out, next_exit, next_ws); select! { _ = time_out => { match &mode { ServerMode::Subscription { subscription_response, .. } => { if let Err(e) = sender.send_text(&subscription_response).await { tracing::warn!("send response to subscription: {:?}", e); } }, ServerMode::Notification(n) => { if let Err(e) = sender.send_text(&n).await { tracing::warn!("send notification: {:?}", e); } }, _ => {} } } ws = next_ws => { // Got a request on the connection but don't care about the contents. // Just send out the pre-configured hardcoded responses. if let Some(Ok(_)) = ws { match &mode { ServerMode::Response(r) => { if let Err(e) = sender.send_text(&r).await { tracing::warn!("send response to request error: {:?}", e); } }, ServerMode::Subscription { subscription_id, .. } => { if let Err(e) = sender.send_text(&subscription_id).await { tracing::warn!("send subscription id error: {:?}", e); } }, _ => {} } } } _ = next_exit => break, } } } // Run a WebSocket server running on localhost that redirects requests for testing. // Requests to any url except for `/myblock/two` will redirect one or two times (HTTP 301) and eventually end up in `/myblock/two`. pub fn ws_server_with_redirect(other_server: String) -> String { let addr = ([127, 0, 0, 1], 0).into(); let service = hyper::service::make_service_fn(move |_| { let other_server = other_server.clone(); async move { Ok::<_, hyper::Error>(hyper::service::service_fn(move |req| { let other_server = other_server.clone(); async move { handler(req, other_server).await } })) } }); let server = hyper::Server::bind(&addr).serve(service); let addr = server.local_addr(); tokio::spawn(async move { server.await }); format!("ws://{}", addr) } /// Handle incoming HTTP Requests. async fn handler( req: hyper::Request<Body>, other_server: String, ) -> Result<hyper::Response<Body>, soketto::BoxedError> { if is_upgrade_request(&req) { tracing::debug!("{:?}", req); match req.uri().path() { "/myblock/two" => { let response = hyper::Response::builder() .status(301) .header("Location", other_server) .body(Body::empty()) .unwrap(); Ok(response) } "/myblock/one" => { let response = hyper::Response::builder().status(301).header("Location", "two").body(Body::empty()).unwrap(); Ok(response) } _ => { let response = hyper::Response::builder() .status(301) .header("Location", "/myblock/one") .body(Body::empty()) .unwrap(); Ok(response) } } } else { panic!("expect upgrade to WS"); } }
30.656836
131
0.676519
434d406a39adbf5674440a53800932db93b7cdef
297
ts
TypeScript
docs/showcase/list_view/dist/components/breadcrumbs/breadcrumbs.component.d.ts
AlastairMcKee/UX-Aspects-IE-Bug
a370da878ffb619a0b729fce5a86ca5918500519
[ "Apache-2.0" ]
null
null
null
docs/showcase/list_view/dist/components/breadcrumbs/breadcrumbs.component.d.ts
AlastairMcKee/UX-Aspects-IE-Bug
a370da878ffb619a0b729fce5a86ca5918500519
[ "Apache-2.0" ]
null
null
null
docs/showcase/list_view/dist/components/breadcrumbs/breadcrumbs.component.d.ts
AlastairMcKee/UX-Aspects-IE-Bug
a370da878ffb619a0b729fce5a86ca5918500519
[ "Apache-2.0" ]
null
null
null
export declare class BreadcrumbsComponent { crumbs: Breadcrumb[]; clickCrumb(event: MouseEvent, crumb: Breadcrumb): void; } export interface Breadcrumb { title: string; routerLink?: string; fragment?: string; queryParams?: any; onClick?: (event: MouseEvent) => void; }
24.75
59
0.686869
e7dc6d751c68e29d5f12376fc079f810e0daedb4
3,898
rs
Rust
oni_trace/src/local.rs
oniproject/tto
4336c525ac39b1706e7ded9b28e4c5d55929268f
[ "Apache-2.0", "MIT" ]
2
2019-11-30T22:52:28.000Z
2019-12-04T21:29:43.000Z
oni_trace/src/local.rs
oniproject/tto
4336c525ac39b1706e7ded9b28e4c5d55929268f
[ "Apache-2.0", "MIT" ]
null
null
null
oni_trace/src/local.rs
oniproject/tto
4336c525ac39b1706e7ded9b28e4c5d55929268f
[ "Apache-2.0", "MIT" ]
null
null
null
use std::{cell::RefCell, borrow::Cow, sync::mpsc::Sender}; use log::{Record, Level}; use crate::{ colors, trace::{ Event, Args, Base, Async, Flow, Instant, }, }; thread_local!(pub static LOCAL: RefCell<Option<Local>> = RefCell::new(None)); pub struct Local { tid: usize, pid: usize, tx: Sender<Event>, } impl Local { pub fn new(tid: usize, pid: usize, tx: Sender<Event>) -> Self { Self { tid, pid, tx } } pub fn instant_thread(&self, ts: u64, name: &'static str, cat: &'static str, args: Args) { self.instant(Instant::Thread, ts, name.into(), Some(cat.into()), args, None); } pub fn instant( &self, kind: Instant, ts: u64, name: Cow<'static, str>, cat: Option<Cow<'static, str>>, args: Args, cname: Option<&'static str>, ) { self.tx.send(Event::Instant { ts: ts / 1000, s: match kind { Instant::Thread => "t", Instant::Process => "p", Instant::Global => "g", }, base: Base { name, cat, pid: self.pid, tid: self.tid, args, cname, }, }).ok(); } pub fn flow_event( &self, kind: Flow, ts: u64, id: usize, name: Cow<'static, str>, cat: Option<Cow<'static, str>>, args: Args, cname: Option<&'static str>, ) { let ts = ts / 1000; let base = Base { name, cat, args, cname, pid: self.pid, tid: self.tid, }; self.tx.send(match kind { Flow::Start => Event::FlowStart { base, id, ts }, Flow::Step => Event::FlowStep { base, id, ts }, Flow::End => Event::FlowEnd { base, id, ts }, }).ok(); } pub fn async_event( &self, kind: Async, ts: u64, id: usize, name: Cow<'static, str>, cat: Option<Cow<'static, str>>, scope: Option<Cow<'static, str>>, args: Args, cname: Option<&'static str>, ) { let ts = ts / 1000; let base = Base { name, cat, args, cname, pid: self.pid, tid: self.tid, }; self.tx.send(match kind { Async::Start => Event::AsyncStart { base, id, ts, scope }, Async::Instant => Event::AsyncInstant { base, id, ts, scope }, Async::End => Event::AsyncEnd { base, id, ts, scope }, }).ok(); } pub fn complete( &self, start: u64, end: u64, name: Cow<'static, str>, cat: Option<Cow<'static, str>>, args: Args, ) { self.tx.send(Event::Complete { ts: start / 1000, dur: (end - start) / 1000, base: Base { name, cat, args, pid: self.pid, tid: self.tid, cname: None, }, }).ok(); } pub fn log(&self, ts: u64, record: &Record) { let name = format!("{}", record.args()); let (cname, cat) = match record.level() { Level::Error => (colors::PEACH, "Error"), Level::Warn => (colors::TANGERINE, "Warn"), Level::Info => (colors::GREEN, "Info"), Level::Debug => (colors::BLUE, "Debug"), Level::Trace => (colors::GREY, "Trace"), }; self.instant(Instant::Thread, ts, name.into(), Some(cat.into()), Args::Log { target: record.target().into(), module_path: record.module_path().map(|m| m.into()), file: record.file().map(|m| m.into()), line: record.line(), }, Some(cname)); } }
26.882759
94
0.446126
078097c56a8dd53deedb932ae23c162bcf7a85df
6,110
css
CSS
html/stylesheets/softcover.css
gitter-badger/PadrinoBook
5a286382ac7672fcf2419751ae092de9c6abf709
[ "MIT" ]
null
null
null
html/stylesheets/softcover.css
gitter-badger/PadrinoBook
5a286382ac7672fcf2419751ae092de9c6abf709
[ "MIT" ]
null
null
null
html/stylesheets/softcover.css
gitter-badger/PadrinoBook
5a286382ac7672fcf2419751ae092de9c6abf709
[ "MIT" ]
null
null
null
/* This file is auto-generated. Do not edit. */ body #book { width: 41em; font-size: 18px; font-family: Georgia, serif; line-height: 1.5; margin-left: 5em; color: #070707; margin-bottom: 20em; } #book h1 { font-size: 230%; border-top: 2px solid #333; padding-top: 1em; } #book h2 { font-size: 180%; margin-top: 1.5em; } #book h3 { margin-top: 1.5em; } #book h4 { margin-top: 2em; } #book img.tex { vertical-align: -6px; } /* Title and subtitle */ #book .title { text-align: center; font-size: 250%; } #book .subtitle { border-top: none; padding-top: 0; margin: 0; text-align: center; font-size: 140%; } #book .author { margin-top: 1em; text-align: center; } #book .date { margin-top: 1em; text-align: center; } #book a { color: #002f72; text-decoration: underline; } #book a.tex { text-decoration: none; } #book code { font-size: 95%; color: darkgreen; font-weight: bold; } #book .number { margin-right: 1em; } #book h1 span.number { display: block; margin-bottom: 0.5em; font-size: 80%; } #book span.number { font-weight: bold; } #book .label { font-weight: bold; margin-right: 0.5em; } #book .header { font-weight: bold; margin-right: 0.5em; } #book .caption .header { font-weight: normal; } #book .code { margin-top: 0.2em; width: 100%; white-space: pre; font-family: "Courier New", Courier, monospace; border: 1px solid #999; background: #eee; margin-bottom: 1em; } #book .codelisting { width: 100%; border: 1px solid #999; background: #eee; margin-bottom: 1em; margin-top: 1em; } #book .codelisting .code { border: 0; margin-bottom: 0; } #book .codelisting .heading { width: 100%; background: #ccc; line-height: 1.2; padding-top: 0.1em; padding-bottom: 0.3em; } #book .codelisting .heading .number { margin-right: 0.3em; margin-left: 0.3em; } #book .codelisting .heading span.filepath { display: block; margin-left: 0.4em; margin-top: 0.2em; margin-bottom: 0.1em; padding-top: 10px; font-style: italic; } #book .codelisting span.break { margin-top: -0.4em; } #book .code .highlight .lineno { color: #666; font-weight: normal; } #book .filepath { font-family: Courier, monospace; font-size: 80%; } #book .inline_verbatim { font-family: Courier, monospace; } #book a.ref { color: #002f72; } #book .graphics.image { text-align: center; } #book .graphics.image img { margin-top: 2em; } #book .graphics.image.box img { border: 1px solid #666; } #book .table { text-align: center; margin-top: 2em; } #book table.tabular { margin-left: auto; margin-right: auto; } #book .center { text-align: center; } #book .displaymath { text-align: center; margin-top: 1em; margin-bottom: 1em; } #book .caption { font-size: 0.85em; font-style: italic; text-align: center; margin-bottom: 3em; margin-top: 1em; } #book .equation { margin-top: 2em; margin-bottom: 2em; } #book .equation_number { float: right; } #book table.tabular { border-collapse: collapse; } #book .tabular th { padding: 0.5em; } #book .tabular th.align_left { text-align: left; } #book .tabular th.align_center { text-align: center; } #book .tabular th.align_right { text-align: right; } #book .tabular th.left_border { border-left: 1px solid black; } #book .tabular th.right_border { border-right: 1px solid black; } #book .tabular td { padding: 0.5em; } #book .tabular td.align_left { text-align: left; } #book .tabular td.align_center { text-align: center; } #book .tabular td.align_right { text-align: right; } #book .tabular td.left_border { border-left: 1px solid black; } #book .tabular td.right_border { border-right: 1px solid black; } #book .tabular tr.top_border { border-top: 1px solid black; } #book .tabular tr.bottom_border { border-bottom: 1px solid black; } #book .tabular tr.top_border { border-top: 1px solid black; } #book .footnotes { border-top: 1px solid black; margin-top: 5em; font-size: 90%; } #book sup.footnote { font-size: 90%; margin-right: 2px; line-height: 0; } #book sup.footnote.intersentence { margin-right: 0px; } #book sup.footnote a:visited { color: #002f72; } #book ol.footnotes a.arrow { text-decoration: none; } #book ol.footnotes.nonumbers li { list-style-type: none; } #book .footnotes .header { padding-top: 1em; padding-bottom: 0.5em; margin-left: 0.5em; font-size: 120%; font-weight: bold; } #book a.arrow { text-decoration: none; } #book a:visited.arrow { color: #002f72; } #book a.section { color: #070707; text-decoration: none; } #book a.heading { color: #000; text-decoration: none; } #book a:hover.heading { text-decoration: underline; } #book .aside { border: 1px solid #999; padding: 0.5em; background: #eee; width: 100%; } #book .aside .heading { font-weight: bold; } #book .highlight { width: 100%; padding-right: 0.5px; } #book .highlight .go { color: darkgreen; } #book pre { line-height: 1.2em; font-family: monospace; } #book .highlight pre { margin: 10px 0 10px 10px; font-size: 85%; font-weight: bold; } #book #table_of_contents { margin-top: -1em; margin-bottom: 3em; margin-left: -1.8em; } #book #table_of_contents ul { list-style-type: none; list-style-position: outside; padding-left: 0; line-height: 1.2em; } #book #table_of_contents li.chapter { font-weight: bold; padding-top: 1.2em; } #book #table_of_contents ul li { padding-left: 3.6em; } #book #table_of_contents a { color: #002f72; } #book .navigation { font-size: 90%; padding-bottom: 2em; } #book .navigation .prev_page { float: left; } #book .navigation .next_page { float: right; } #book a span.undefined_ref { color: red; } #book .tt { font-family: Courier, monospace; } #book .sc { font-variant: small-caps; } #book .texhtml { line-height: 0.5; } #book span.break { display: block; } #book h1 span.break { display: block; margin-top: 0.5em; } #book span.intersentencespace { margin-right: 0.2em; }
13.886364
49
0.645663
2c46cdf7f5b38363cbdbbb70c6b32b5f4594169b
1,748
py
Python
setup.py
kseniyapotter/django-datawatch
b42648219940b85ecb5d7fd6f4d84686ecd272e7
[ "MIT" ]
null
null
null
setup.py
kseniyapotter/django-datawatch
b42648219940b85ecb5d7fd6f4d84686ecd272e7
[ "MIT" ]
null
null
null
setup.py
kseniyapotter/django-datawatch
b42648219940b85ecb5d7fd6f4d84686ecd272e7
[ "MIT" ]
null
null
null
# -*- coding: UTF-8 -*- from os.path import join, dirname from setuptools import setup, find_packages def long_description(): """Return long description from README.rst if it's present because it doesn't get installed.""" try: return open(join(dirname(__file__), 'README.md')).read() except IOError: return '' setup( name='django-datawatch', packages=find_packages(exclude=['example*']), version='1.0.3', description='Django Datawatch runs automated data checks in your Django installation', author='Jens Nistler <opensource@jensnistler.de>, Bogdan Radko <bogdan.radko@regiohelden.de>', author_email='opensource@regiohelden.de', long_description=long_description(), long_description_content_type='text/markdown', install_requires=[ 'celery>=3.1.25', 'Django>=1.11.20', 'django-bootstrap3>=11.0.0', 'django-extensions>=2.1.5', 'django-model-utils>=3.1.2', 'python-dateutil>=2.8.0', ], license='MIT', url='https://github.com/RegioHelden/django-datawatch', download_url='', keywords=['django', 'monitoring', 'datawatch', 'check', 'checks'], include_package_data=True, classifiers=[ "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Development Status :: 4 - Beta", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: System :: Monitoring", ] )
34.27451
98
0.633867
582aa032694b4a9d95e3c107e6e7349caeea229d
969
css
CSS
assets/backend/css/jquery.tagsinput.css
rizkydrma/mykosan
e70220d537fc5052651a6abd6b545cb97b73304a
[ "MIT" ]
null
null
null
assets/backend/css/jquery.tagsinput.css
rizkydrma/mykosan
e70220d537fc5052651a6abd6b545cb97b73304a
[ "MIT" ]
null
null
null
assets/backend/css/jquery.tagsinput.css
rizkydrma/mykosan
e70220d537fc5052651a6abd6b545cb97b73304a
[ "MIT" ]
null
null
null
div.tagsinput { border: 1px solid #CCC; background: #FFF; padding: 5px; width: 300px; height: 100px; overflow-y: auto; } div.tagsinput span.tag { border: 1px solid #215c84; -moz-border-radius: 2px; -webkit-border-radius: 2px; display: block; float: left; padding: 5px; text-decoration: none; background: #215c84; color: #ffffff; margin-right: 5px; margin-bottom: 5px; font-family: helvetica; font-size: 13px; } div.tagsinput span.tag a { font-weight: bold; color: #ffffff; text-decoration: none; font-size: 11px; } div.tagsinput input { width: 80px; margin: 0px; font-family: helvetica; font-size: 13px; border: 1px solid transparent; padding: 5px; background: transparent; color: #000; outline: 0px; margin-right: 5px; margin-bottom: 5px; } div.tagsinput div { display: block; float: left; } .tags_clear { clear: both; width: 100%; height: 0px; } .not_valid { background: #FBD8DB !important; color: #90111A !important; }
15.629032
32
0.691434
38abc3ec2f2b1cd6d2ee6bcc7dd2307ca93ff499
659
php
PHP
core/reordermedia.php
DiemenDesign/AuroraCMS
cfbde949d6fdc14de027504b17ac8f079de1b29b
[ "MIT" ]
15
2020-03-31T17:10:30.000Z
2022-02-12T07:20:10.000Z
core/reordermedia.php
DiemenDesign/AuroraCMS
cfbde949d6fdc14de027504b17ac8f079de1b29b
[ "MIT" ]
7
2021-06-26T08:19:17.000Z
2021-07-01T13:42:26.000Z
core/reordermedia.php
DiemenDesign/AuroraCMS
cfbde949d6fdc14de027504b17ac8f079de1b29b
[ "MIT" ]
1
2021-06-29T07:11:46.000Z
2021-06-29T07:11:46.000Z
<?php /** * AuroraCMS - Copyright (C) Diemen Design 2019 * * @category Administration - Core - Reorder Media Items * @package core/reordermedia.php * @author Dennis Suitters <dennis@diemen.design> * @copyright 2014-2019 Diemen Design * @license http://opensource.org/licenses/MIT MIT License * @version 0.1.3 * @link https://github.com/DiemenDesign/AuroraCMS * @notes This PHP Script is designed to be executed using PHP 7+ */ require'db.php'; $i=0; foreach($_POST['mi'] as$id){ $s=$db->prepare("UPDATE `".$prefix."media` SET `ord`=:ord WHERE `id`=:id"); $s->execute([ ':ord'=>$i, ':id'=>$id ]); $i++; }
27.458333
77
0.623672
eb8cc1e5d9fbe5541a992f30ed303f8b49104adc
3,091
css
CSS
build/static/css/main.e6de4366.chunk.css
javeedshareef/Naukri_portal
ae8a9043f05f6f5f23f4670b48e75130227e87ae
[ "MIT" ]
null
null
null
build/static/css/main.e6de4366.chunk.css
javeedshareef/Naukri_portal
ae8a9043f05f6f5f23f4670b48e75130227e87ae
[ "MIT" ]
null
null
null
build/static/css/main.e6de4366.chunk.css
javeedshareef/Naukri_portal
ae8a9043f05f6f5f23f4670b48e75130227e87ae
[ "MIT" ]
null
null
null
body{margin:0;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Oxygen,Ubuntu,Cantarell,Fira Sans,Droid Sans,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}code{font-family:source-code-pro,Menlo,Monaco,Consolas,Courier New,monospace}.nav-list{margin-left:20%;font-size:14px}.nav-item{padding-left:20px}.post:hover{background-color:#263bd6}.jobseeker:hover{background-color:#666}.dropdown-item:hover{background-color:#263bd6!important}.bgcolor{background:#f0f0f0}.h5-heading{font-size:20px;color:#555;font-weight:700;margin-bottom:15px;font-family:Roboto,sans-serif;text-align:center}.fb-icon{color:#3b5998;font-size:40px}.plus-icon{color:#dd4b39;font-size:40px}.twitter-icon{color:#00aced;font-size:40px}.h5-headings{font-size:20px;color:#555;font-weight:700;margin-bottom:15px;text-align:left}.login-btn{width:100%;background:#263bd6!important;color:#fff;border-radius:0;padding:10px;font-size:16px;font-weight:700;text-transform:uppercase}.user-icon{margin-top:2rem;margin-left:2rem;color:grey}.user-heading{margin-top:1.9rem;text-align:center;margin-right:10px;color:grey}.link-tab{color:#263bd6!important}@media (min-width:1024px) and (max-width:1440px){.testing{justify-content:center}}@media (min-width:1441px) and (max-width:2560px){.testing{justify-content:center}}@media (min-width:376px) and (max-width:2560px){.user{justify-content:center}}@media (min-width:375px) and (max-width:2560px){.user-heading{padding-left:.5rem}}.login-img{background-image:url(/assets/images/login.jpg);background-size:cover}.login-h1{font-size:40px;font-weight:700;font-family:Roboto,sans-serif;margin:unset}.job-name a,.login-h1{color:#fff}.job-name span{color:#263bd6}@media (max-width:576px){.login-h1{text-align:center;font-family:Roboto,sans-serif;font-size:35px;font-weight:600}.testing{margin-top:65px}.testingtwo{margin-top:10px;text-align:center}.bground{padding-bottom:3.5rem}}@media (min-width:577px) and (max-width:768px){.login-h1{padding-top:2.5rem;padding-bottom:4rem;text-align:center}.testingtwo{text-align:center;padding-top:60px}}@media (min-width:769px) and (max-width:1024px){.login-h1{padding-top:70px;padding-bottom:4rem}.testingtwo{text-align:right;padding-top:90px}}@media (min-width:1025px) and (max-width:1440px){.login-h1{padding-top:80px;padding-bottom:5rem}.testingtwo{text-align:right;padding-top:95px}}.headers-tab span{color:#292929;font-size:19px;margin-bottom:10px}.headers-tab h2{color:#292929;font-size:40px;font-weight:800;letter-spacing:1px;margin:0}.contact-box{border:1px solid grey;width:400px}.fullname{padding:15px 10px}.email-tab,.fullname{width:100%;color:#8c8c8c;border:1px solid #ddd}.email-tab{padding:20px}.submit-tab{background-color:#263bd6;border:0;color:#fff;font-size:16px;font-weight:600;padding:18px 40px;margin-top:30px;float:right}.information{color:#000;display:table;font-size:16px;font-weight:700;margin-bottom:5px;text-transform:uppercase}.fa-home{color:#00f}.para-tab{color:#333;font-size:14px;font-family:Open Sans,sans-serif} /*# sourceMappingURL=main.e6de4366.chunk.css.map */
1,545.5
3,039
0.796182
4425f4dc41e0ad6e9cb9ab451b3554bb34e8c03c
37,055
py
Python
io_scene_halo/file_tag/file_scenario/h2/format.py
Project-Cartographer/Halo-Jointed-Model-Blender-Toolset
8261bcc377ede0856079a4d5cc782790693c7d78
[ "MIT" ]
1
2019-12-29T20:28:59.000Z
2019-12-29T20:28:59.000Z
io_scene_halo/file_tag/file_scenario/h2/format.py
General-101/H2V-Blender-JMSv2-Exporter
8261bcc377ede0856079a4d5cc782790693c7d78
[ "MIT" ]
4
2020-08-25T02:17:12.000Z
2020-09-01T19:58:04.000Z
io_scene_halo/file_tag/file_scenario/h2/format.py
General-101/H2V-Blender-JMSv2-Exporter
8261bcc377ede0856079a4d5cc782790693c7d78
[ "MIT" ]
null
null
null
# ##### BEGIN MIT LICENSE BLOCK ##### # # MIT License # # Copyright (c) 2022 Steven Garcia # # 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. # # ##### END MIT LICENSE BLOCK ##### from mathutils import Vector, Euler SALT_SIZE = 32 class ScenarioAsset(): def __init__(self): self.header = None self.scenario_body_header = None self.scenario_body = None self.skies_header = None self.skies = None self.object_name_header = None self.object_names = None self.scenery_header = None self.scenery = None self.scenery_palette_header = None self.scenery_palette = None self.bipeds_header = None self.bipeds = None self.biped_palette_header = None self.biped_palette = None self.vehicles_header = None self.vehicles = None self.vehicle_palette_header = None self.vehicle_palette = None self.equipment_header = None self.equipment = None self.equipment_palette_header = None self.equipment_palette = None self.weapon_header = None self.weapons = None self.weapon_palette_header = None self.weapon_palette = None self.device_machine_header = None self.device_machines = None self.device_machine_palette_header = None self.device_machine_palette = None self.light_volume_header = None self.light_volumes = None self.light_volume_palette_header = None self.light_volume_palette = None self.player_starting_profile_header = None self.player_starting_profiles = None self.player_starting_location_header = None self.player_starting_locations = None self.trigger_volumes_header = None self.trigger_volumes = None self.decals_header = None self.decals = None self.decal_palette_header = None self.decal_palette = None self.style_palette_header = None self.style_palette = None self.squad_groups_header = None self.squad_groups = None self.squads_header = None self.squads = None self.zones_header = None self.zones = None self.character_palette_header = None self.character_palette = None self.scripting_data_header = None self.scripting_data = None self.cutscene_flags_header = None self.cutscene_flags = None self.cutscene_camera_points_header = None self.cutscene_camera_points = None self.orders_header = None self.orders = None self.triggers_header = None self.triggers = None class ScenarioBody: def __init__(self, unused_tag_ref=None, skies_tag_block=None, scenario_type=0, scenario_flags=0, child_scenarios_tag_block=None, local_north=0.0, predicted_resources_tag_block=None, functions_tag_block=None, editor_scenario_data=0, comments_tag_block=None, environment_objects_tag_block=None, object_names_tag_block=None, scenery_tag_block=None, scenery_palette_tag_block=None, bipeds_tag_block=None, biped_palette_tag_block=None, vehicles_tag_block=None, vehicle_palette_tag_block=None, equipment_tag_block=None, equipment_palette_tag_block=None, weapons_tag_block=None, weapon_palette_tag_block=None, device_groups_tag_block=None, machines_tag_block=None, machine_palette_tag_block=None, controls_tag_block=None, control_palette_tag_block=None, light_fixtures_tag_block=None, light_fixtures_palette_tag_block=None, sound_scenery_tag_block=None, sound_scenery_palette_tag_block=None, light_volumes_tag_block=None, light_volume_palette_tag_block=None, player_starting_profile_tag_block=None, player_starting_locations_tag_block=None, trigger_volumes_tag_block=None, recorded_animations_tag_block=None, netgame_flags_tag_block=None, netgame_equipment_tag_block=None, starting_equipment_tag_block=None, bsp_switch_trigger_volumes_tag_block=None, decals_tag_block=None, decal_palette_tag_block=None, detail_object_collection_palette_tag_block=None, style_palette_tag_block=None, squad_groups_tag_block=None, squads_tag_block=None, zones_tag_block=None, mission_scenes_tag_block=None, character_palette_tag_block=None, ai_pathfinding_data_tag_block=None, ai_animation_references_tag_block=None, ai_script_references_tag_block=None, ai_recording_references_tag_block=None, ai_conversations_tag_block=None, script_syntax_data_tag_data=None, script_string_data_tag_data=None, scripts_tag_block=None, globals_tag_block=None, references_tag_block=None, source_files_tag_block=None, scripting_data_tag_block=None, cutscene_flags_tag_block=None, cutscene_camera_points_tag_block=None, cutscene_titles_tag_block=None, custom_object_names_tag_ref=None, chapter_title_text_tag_ref=None, hud_messages_tag_ref=None, structure_bsps_tag_block=None, scenario_resources_tag_block=None, old_structure_physics_tag_block=None, hs_unit_seats_tag_block=None, scenario_kill_triggers_tag_block=None, hs_syntax_datums_tag_block=None, orders_tag_block=None, triggers_tag_block=None, background_sound_palette_tag_block=None, sound_environment_palette_tag_block=None, weather_palette_tag_block=None, unused_0_tag_block=None, unused_1_tag_block=None, unused_2_tag_block=None, unused_3_tag_block=None, scavenger_hunt_objects_tag_block=None, scenario_cluster_data_tag_block=None, salt_array=None, spawn_data_tag_block=None, sound_effect_collection_tag_ref=None, crates_tag_block=None, crate_palette_tag_block=None, global_lighting_tag_ref=None, atmospheric_fog_palette_tag_block=None, planar_fog_palette_tag_block=None, flocks_tag_block=None, subtitles_tag_ref=None, decorators_tag_block=None, creatures_tag_block=None, creature_palette_tag_block=None, decorator_palette_tag_block=None, bsp_transition_volumes_tag_block=None, structure_bsp_lighting_tag_block=None, editor_folders_tag_block=None, level_data_tag_block=None, game_engine_strings_tag_ref=None, mission_dialogue_tag_block=None, objectives_tag_ref=None, interpolators_tag_block=None, shared_references_tag_block=None, screen_effect_references_tag_block=None, simulation_definition_table_tag_block=None): self.unused_tag_ref = unused_tag_ref self.skies_tag_block = skies_tag_block self.scenario_type = scenario_type self.scenario_flags = scenario_flags self.child_scenarios_tag_block = child_scenarios_tag_block self.local_north = local_north self.predicted_resources_tag_block = predicted_resources_tag_block self.functions_tag_block = functions_tag_block self.editor_scenario_data = editor_scenario_data self.comments_tag_block = comments_tag_block self.environment_objects_tag_block = environment_objects_tag_block self.object_names_tag_block = object_names_tag_block self.scenery_tag_block = scenery_tag_block self.scenery_palette_tag_block = scenery_palette_tag_block self.bipeds_tag_block = bipeds_tag_block self.biped_palette_tag_block = biped_palette_tag_block self.vehicles_tag_block = vehicles_tag_block self.vehicle_palette_tag_block = vehicle_palette_tag_block self.equipment_tag_block = equipment_tag_block self.equipment_palette_tag_block = equipment_palette_tag_block self.weapons_tag_block = weapons_tag_block self.weapon_palette_tag_block = weapon_palette_tag_block self.device_groups_tag_block = device_groups_tag_block self.machines_tag_block = machines_tag_block self.machine_palette_tag_block = machine_palette_tag_block self.controls_tag_block = controls_tag_block self.control_palette_tag_block = control_palette_tag_block self.light_fixtures_tag_block = light_fixtures_tag_block self.light_fixtures_palette_tag_block = light_fixtures_palette_tag_block self.sound_scenery_tag_block = sound_scenery_tag_block self.sound_scenery_palette_tag_block = sound_scenery_palette_tag_block self.light_volumes_tag_block = light_volumes_tag_block self.light_volume_palette_tag_block = light_volume_palette_tag_block self.player_starting_profile_tag_block = player_starting_profile_tag_block self.player_starting_locations_tag_block = player_starting_locations_tag_block self.trigger_volumes_tag_block = trigger_volumes_tag_block self.recorded_animations_tag_block = recorded_animations_tag_block self.netgame_flags_tag_block = netgame_flags_tag_block self.netgame_equipment_tag_block = netgame_equipment_tag_block self.starting_equipment_tag_block = starting_equipment_tag_block self.bsp_switch_trigger_volumes_tag_block = bsp_switch_trigger_volumes_tag_block self.decals_tag_block = decals_tag_block self.decal_palette_tag_block = decal_palette_tag_block self.detail_object_collection_palette_tag_block = detail_object_collection_palette_tag_block self.style_palette_tag_block = style_palette_tag_block self.squad_groups_tag_block = squad_groups_tag_block self.squads_tag_block = squads_tag_block self.zones_tag_block = zones_tag_block self.mission_scenes_tag_block = mission_scenes_tag_block self.character_palette_tag_block = character_palette_tag_block self.ai_pathfinding_data_tag_block = ai_pathfinding_data_tag_block self.ai_animation_references_tag_block = ai_animation_references_tag_block self.ai_script_references_tag_block = ai_script_references_tag_block self.ai_recording_references_tag_block = ai_recording_references_tag_block self.ai_conversations_tag_block = ai_conversations_tag_block self.script_syntax_data_tag_data = script_syntax_data_tag_data self.script_string_data_tag_data = script_string_data_tag_data self.scripts_tag_block = scripts_tag_block self.globals_tag_block = globals_tag_block self.references_tag_block = references_tag_block self.source_files_tag_block = source_files_tag_block self.scripting_data_tag_block = scripting_data_tag_block self.cutscene_flags_tag_block = cutscene_flags_tag_block self.cutscene_camera_points_tag_block = cutscene_camera_points_tag_block self.cutscene_titles_tag_block = cutscene_titles_tag_block self.custom_object_names_tag_ref = custom_object_names_tag_ref self.chapter_title_text_tag_ref = chapter_title_text_tag_ref self.hud_messages_tag_ref = hud_messages_tag_ref self.structure_bsps_tag_block = structure_bsps_tag_block self.scenario_resources_tag_block = scenario_resources_tag_block self.old_structure_physics_tag_block = old_structure_physics_tag_block self.hs_unit_seats_tag_block = hs_unit_seats_tag_block self.scenario_kill_triggers_tag_block = scenario_kill_triggers_tag_block self.hs_syntax_datums_tag_block = hs_syntax_datums_tag_block self.orders_tag_block = orders_tag_block self.triggers_tag_block = triggers_tag_block self.background_sound_palette_tag_block = background_sound_palette_tag_block self.sound_environment_palette_tag_block = sound_environment_palette_tag_block self.weather_palette_tag_block = weather_palette_tag_block self.unused_0_tag_block = unused_0_tag_block self.unused_1_tag_block = unused_1_tag_block self.unused_2_tag_block = unused_2_tag_block self.unused_3_tag_block = unused_3_tag_block self.scavenger_hunt_objects_tag_block = scavenger_hunt_objects_tag_block self.scenario_cluster_data_tag_block = scenario_cluster_data_tag_block self.salt_array = salt_array self.spawn_data_tag_block = spawn_data_tag_block self.sound_effect_collection_tag_ref = sound_effect_collection_tag_ref self.crates_tag_block = crates_tag_block self.crate_palette_tag_block = crate_palette_tag_block self.global_lighting_tag_ref = global_lighting_tag_ref self.atmospheric_fog_palette_tag_block = atmospheric_fog_palette_tag_block self.planar_fog_palette_tag_block = planar_fog_palette_tag_block self.flocks_tag_block = flocks_tag_block self.subtitles_tag_ref = subtitles_tag_ref self.decorators_tag_block = decorators_tag_block self.creatures_tag_block = creatures_tag_block self.creature_palette_tag_block = creature_palette_tag_block self.decorator_palette_tag_block = decorator_palette_tag_block self.bsp_transition_volumes_tag_block = bsp_transition_volumes_tag_block self.structure_bsp_lighting_tag_block = structure_bsp_lighting_tag_block self.editor_folders_tag_block = editor_folders_tag_block self.level_data_tag_block = level_data_tag_block self.game_engine_strings_tag_ref = game_engine_strings_tag_ref self.mission_dialogue_tag_block = mission_dialogue_tag_block self.objectives_tag_ref = objectives_tag_ref self.interpolators_tag_block = interpolators_tag_block self.shared_references_tag_block = shared_references_tag_block self.screen_effect_references_tag_block = screen_effect_references_tag_block self.simulation_definition_table_tag_block = simulation_definition_table_tag_block class ObjectName: def __init__(self, name="", object_type=0, placement_index=0): self.name = name self.object_type = object_type self.placement_index = placement_index class Object: def __init__(self, palette_index=0, name_index=0, placement_flags=0, position=Vector(), rotation=Euler(), scale=0.0, transform_flags=0, manual_bsp_flags=0, unique_id=0, origin_bsp_index=0, object_type=0, source=0, bsp_policy=0, editor_folder_index=0): self.palette_index = palette_index self.name_index = name_index self.placement_flags = placement_flags self.position = position self.rotation = rotation self.scale = scale self.transform_flags = transform_flags self.manual_bsp_flags = manual_bsp_flags self.unique_id = unique_id self.origin_bsp_index = origin_bsp_index self.object_type = object_type self.source = source self.bsp_policy = bsp_policy self.editor_folder_index = editor_folder_index class Scenery(Object): def __init__(self, sobj_header=None, obj0_header=None, sper_header=None, sct3_header=None, variant_name_length=0, variant_name="", active_change_colors=0, primary_color_BGRA=(0.0, 0.0, 0.0, 1.0), secondary_color_BGRA=(0.0, 0.0, 0.0, 1.0), tertiary_color_BGRA=(0.0, 0.0, 0.0, 1.0), quaternary_color_BGRA=(0.0, 0.0, 0.0, 1.0), pathfinding_policy=0, lightmap_policy=0, pathfinding_references_header=None, pathfinding_references=None, valid_multiplayer_games=0): super().__init__() self.sobj_header = sobj_header self.obj0_header = obj0_header self.sper_header = sper_header self.sct3_header = sct3_header self.variant_name_length = variant_name_length self.variant_name = variant_name self.active_change_colors = active_change_colors self.primary_color_BGRA = primary_color_BGRA self.secondary_color_BGRA = secondary_color_BGRA self.tertiary_color_BGRA = tertiary_color_BGRA self.quaternary_color_BGRA = quaternary_color_BGRA self.pathfinding_policy = pathfinding_policy self.lightmap_policy = lightmap_policy self.pathfinding_references_header = pathfinding_references_header self.pathfinding_references = pathfinding_references self.valid_multiplayer_games = valid_multiplayer_games class Unit(Object): def __init__(self, sobj_header=None, obj0_header=None, sper_header=None, sunt_header=None,variant_name_length=0, variant_name="", active_change_colors=0, primary_color_BGRA=(0.0, 0.0, 0.0, 1.0), secondary_color_BGRA=(0.0, 0.0, 0.0, 1.0), tertiary_color_BGRA=(0.0, 0.0, 0.0, 1.0), quaternary_color_BGRA=(0.0, 0.0, 0.0, 1.0), body_vitality=0.0, flags=0): super().__init__() self.sobj_header = sobj_header self.obj0_header = obj0_header self.sper_header = sper_header self.sunt_header = sunt_header self.variant_name_length = variant_name_length self.variant_name = variant_name self.active_change_colors = active_change_colors self.primary_color_BGRA = primary_color_BGRA self.secondary_color_BGRA = secondary_color_BGRA self.tertiary_color_BGRA = tertiary_color_BGRA self.quaternary_color_BGRA = quaternary_color_BGRA self.body_vitality = body_vitality self.flags = flags class Equipment(Object): def __init__(self, sobj_header=None, obj0_header=None, seqt_header=None, flags=0): super().__init__() self.sobj_header = sobj_header self.obj0_header = obj0_header self.seqt_header = seqt_header self.flags = flags class Weapon(Object): def __init__(self, sobj_header=None, obj0_header=None, sper_header=None, swpt_header=None, variant_name_length=0, variant_name="", active_change_colors=0, primary_color_BGRA=(0.0, 0.0, 0.0, 1.0), secondary_color_BGRA=(0.0, 0.0, 0.0, 1.0), tertiary_color_BGRA=(0.0, 0.0, 0.0, 1.0), quaternary_color_BGRA=(0.0, 0.0, 0.0, 1.0), rounds_left=0, rounds_loaded=0, flags=0): super().__init__() self.sobj_header = sobj_header self.obj0_header = obj0_header self.sper_header = sper_header self.swpt_header = swpt_header self.variant_name_length = variant_name_length self.variant_name = variant_name self.active_change_colors = active_change_colors self.primary_color_BGRA = primary_color_BGRA self.secondary_color_BGRA = secondary_color_BGRA self.tertiary_color_BGRA = tertiary_color_BGRA self.quaternary_color_BGRA = quaternary_color_BGRA self.rounds_left = rounds_left self.rounds_loaded = rounds_loaded self.flags = flags class DeviceMachine(Object): def __init__(self, sobj_header=None, obj0_header=None, sdvt_header=None, smht_header=None, power_group_index=0, position_group_index=0, flags_0=0, flags_1=0, pathfinding_references_header=None, pathfinding_references=None): super().__init__() self.sobj_header = sobj_header self.obj0_header = obj0_header self.sdvt_header = sdvt_header self.smht_header = smht_header self.power_group_index = power_group_index self.position_group_index = position_group_index self.flags_0 = flags_0 self.flags_1 = flags_1 self.pathfinding_references_header = pathfinding_references_header self.pathfinding_references = pathfinding_references class LightVolume(Object): def __init__(self, sobj_header=None, obj0_header=None, sdvt_header=None, slit_header=None, power_group_index=0, position_group_index=0, flags_0=0, shape_type=0, flags_1=0, lightmap_type=0, lightmap_flags=0, lightmap_half_life=0.0, lightmap_light_scale=0.0, target_point=Vector(), width=0.0, height_scale=0.0, field_of_view=0.0, falloff_distance=0.0, cutoff_distance=0.0): super().__init__() self.sobj_header = sobj_header self.obj0_header = obj0_header self.sdvt_header = sdvt_header self.slit_header = slit_header self.power_group_index = power_group_index self.position_group_index = position_group_index self.flags_0 = flags_0 self.shape_type = shape_type self.flags_1 = flags_1 self.lightmap_type = lightmap_type self.lightmap_flags = lightmap_flags self.lightmap_half_life = lightmap_half_life self.lightmap_light_scale = lightmap_light_scale self.target_point = target_point self.width = width self.height_scale = height_scale self.field_of_view = field_of_view self.falloff_distance = falloff_distance self.cutoff_distance = cutoff_distance class PlayerStartingProfile(): def __init__(self, name="", starting_health_damage=0.0, starting_shield_damage=0.0, primary_weapon_tag_ref=None, primary_rounds_loaded=0, primary_rounds_total=0, secondary_weapon_tag_ref=None, secondary_rounds_loaded=0, secondary_rounds_total=0, starting_fragmentation_grenades_count=0, starting_plasma_grenade_count=0, starting_custom_2_grenade_count=0, starting_custom_3_grenade_count=0): super().__init__() self.name = name self.starting_health_damage = starting_health_damage self.starting_shield_damage = starting_shield_damage self.primary_weapon_tag_ref = primary_weapon_tag_ref self.primary_rounds_loaded = primary_rounds_loaded self.primary_rounds_total = primary_rounds_total self.secondary_weapon_tag_ref = secondary_weapon_tag_ref self.secondary_rounds_loaded = secondary_rounds_loaded self.secondary_rounds_total = secondary_rounds_total self.starting_fragmentation_grenades_count = starting_fragmentation_grenades_count self.starting_plasma_grenade_count = starting_plasma_grenade_count self.starting_custom_2_grenade_count = starting_custom_2_grenade_count self.starting_custom_3_grenade_count = starting_custom_3_grenade_count class PlayerStartingLocation(): def __init__(self, position=Vector(), facing=0.0, team_designator=0, bsp_index=0, type_0=0, type_1=0, type_2=0, type_3=0, spawn_type_0=0, spawn_type_1=0, spawn_type_2=0, spawn_type_3=0, unk_0="", unk_0_length=0, unk_1="", unk_1_length=0, campaign_player_type=0): super().__init__() self.position = position self.facing = facing self.team_designator = team_designator self.bsp_index = bsp_index self.type_0 = type_0 self.type_1 = type_1 self.type_2 = type_2 self.type_3 = type_3 self.spawn_type_0 = spawn_type_0 self.spawn_type_1 = spawn_type_1 self.spawn_type_2 = spawn_type_2 self.spawn_type_3 = spawn_type_3 self.unk_0 = unk_0 self.unk_0_length = unk_0_length self.unk_1 = unk_1 self.unk_1_length = unk_1_length self.campaign_player_type = campaign_player_type class TriggerVolume(): def __init__(self, name="", name_length=0, object_name_index=0, node_name="", node_name_length=0, forward=Vector(), up=Vector(), position=Vector(), extents=Vector(), kill_trigger_volume_index=0): self.name = name self.name_length = name_length self.object_name_index = object_name_index self.node_name = node_name self.node_name_length = node_name_length self.forward = forward self.up = up self.position = position self.extents = extents self.kill_trigger_volume_index = kill_trigger_volume_index class Decal(): def __init__(self, palette_index=0, yaw=0, pitch=0, position=Vector()): self.palette_index = palette_index self.yaw = yaw self.pitch = pitch self.position = position class SquadGroups(): def __init__(self, name="", parent_index=0, initial_order_index=0): self.name = name self.parent_index = parent_index self.initial_order_index = initial_order_index class Squad(): def __init__(self, name="", flags=0, team=0, parent_squad_group_index=0, squad_delay_time=0.0, normal_difficulty_count=0, insane_difficulty_count=0, major_upgrade=0, vehicle_type_index=0, character_type_index=0, initial_zone_index=0, initial_weapon_index=0, initial_secondary_weapon_index=0, grenade_type=0, initial_order_index=0, vehicle_variant_length=0, starting_locations_tag_block=None, placement_script="", starting_locations_header=None, starting_locations=None): self.name = name self.flags = flags self.team = team self.parent_squad_group_index = parent_squad_group_index self.squad_delay_time = squad_delay_time self.normal_difficulty_count = normal_difficulty_count self.insane_difficulty_count = insane_difficulty_count self.major_upgrade = major_upgrade self.vehicle_type_index = vehicle_type_index self.character_type_index = character_type_index self.initial_zone_index = initial_zone_index self.initial_weapon_index = initial_weapon_index self.initial_secondary_weapon_index = initial_secondary_weapon_index self.grenade_type = grenade_type self.initial_order_index = initial_order_index self.vehicle_variant_length = vehicle_variant_length self.starting_locations_tag_block = starting_locations_tag_block self.placement_script = placement_script self.starting_locations_header = starting_locations_header self.starting_locations = starting_locations class StartingLocation(): def __init__(self, name="", name_length=0, position=Vector(), reference_frame=0, facing_y=0.0, facing_p=0.0, flags=0, character_type_index=0, initial_weapon_index=0, initial_secondary_weapon_index=0, vehicle_type_index=0, seat_type=0, grenade_type=0, swarm_count=0, actor_variant_name_length=0, vehicle_variant_name_length=0, initial_movement_distance=0, emitter_vehicle_index=0, initial_movement_mode=0, placement_script=""): self.name = name self.name_length = name_length self.position = position self.reference_frame = reference_frame self.facing_y = facing_y self.facing_p = facing_p self.flags = flags self.character_type_index = character_type_index self.initial_weapon_index = initial_weapon_index self.initial_secondary_weapon_index = initial_secondary_weapon_index self.vehicle_type_index = vehicle_type_index self.seat_type = seat_type self.grenade_type = grenade_type self.swarm_count = swarm_count self.actor_variant_name_length = actor_variant_name_length self.vehicle_variant_name_length = vehicle_variant_name_length self.initial_movement_distance = initial_movement_distance self.emitter_vehicle_index = emitter_vehicle_index self.initial_movement_mode = initial_movement_mode self.placement_script = placement_script class Zone(): def __init__(self, name="", flags=0, manual_bsp_index=0, firing_positions_tag_block=None, areas_tag_block=None, firing_positions_header=None, areas_header=None, firing_positions=None, areas=None): self.name = name self.flags = flags self.manual_bsp_index = manual_bsp_index self.firing_positions_tag_block = firing_positions_tag_block self.areas_tag_block = areas_tag_block self.firing_positions_header = firing_positions_header self.areas_header = areas_header self.firing_positions = firing_positions self.areas = areas class FiringPosition(): def __init__(self, position=Vector(), reference_frame=0, flags=0, area_index=0, cluster_index=0, normal_y=0.0, normal_p=0.0): self.position = position self.reference_frame = reference_frame self.flags = flags self.area_index = area_index self.cluster_index = cluster_index self.normal_y = normal_y self.normal_p = normal_p class Area(): def __init__(self, name="", flags=0, runtime_starting_index=0, runtime_count=0, manual_reference_frame=0, flight_hints_tag_block=None, flight_hints_header=None, flight_hints=None): self.name = name self.flags = flags self.runtime_starting_index = runtime_starting_index self.runtime_count = runtime_count self.manual_reference_frame = manual_reference_frame self.flight_hints_tag_block = flight_hints_tag_block self.flight_hints_header = flight_hints_header self.flight_hints = flight_hints class ScriptingData(): def __init__(self, point_sets_tag_block=None, point_sets_header=None, point_sets=None): self.point_sets_tag_block = point_sets_tag_block self.point_sets_header = point_sets_header self.point_sets = point_sets class PointSet(): def __init__(self, name="", points_tag_block=None, bsp_index=0, manual_reference_frame=0, flags=0, points_header=None, points=None): self.name = name self.points_tag_block = points_tag_block self.bsp_index = bsp_index self.manual_reference_frame = manual_reference_frame self.flags = flags self.points_header = points_header self.points = points class Point(): def __init__(self, name="", position=Vector(), reference_frame=0, surface_index=0, facing_direction_y=0.0, facing_direction_p=0.0): self.name = name self.position = position self.reference_frame = reference_frame self.surface_index = surface_index self.facing_direction_y = facing_direction_y self.facing_direction_p = facing_direction_p class CutsceneFlags(): def __init__(self, name="", position=Vector(), facing_y=0.0, facing_p=0.0): self.name = name self.position = position self.facing_y = facing_y self.facing_p = facing_p class CutsceneCameraPoints(): def __init__(self, flags=0, camera_type=0, name="", position=Vector(), orientation=Vector()): self.flags = flags self.camera_type = camera_type self.name = name self.position = position self.orientation = orientation class Order(): def __init__(self, name="", style_index=0, flags=0, force_combat_status=0, entry_script="", follow_squad=0, follow_radius=0.0, primary_area_set_tag_block=None, secondary_area_set_tag_block=None, secondary_set_trigger_tag_block=None, special_movement_tag_block=None, order_endings_tag_block=None, primary_area_set_header=None, secondary_area_set_header=None, secondary_set_trigger_header=None, special_movement_header=None, order_endings_header=None, primary_area_set=None, secondary_area_set=None, secondary_set_trigger=None, special_movement=None, order_endings=None): self.name = name self.style_index = style_index self.flags = flags self.force_combat_status = force_combat_status self.entry_script = entry_script self.follow_squad = follow_squad self.follow_radius = follow_radius self.primary_area_set_tag_block = primary_area_set_tag_block self.secondary_area_set_tag_block = secondary_area_set_tag_block self.secondary_set_trigger_tag_block = secondary_set_trigger_tag_block self.special_movement_tag_block = special_movement_tag_block self.order_endings_tag_block = order_endings_tag_block self.primary_area_set_header = primary_area_set_header self.secondary_area_set_header = secondary_area_set_header self.secondary_set_trigger_header = secondary_set_trigger_header self.special_movement_header = special_movement_header self.order_endings_header = order_endings_header self.primary_area_set = primary_area_set self.secondary_area_set = secondary_area_set self.secondary_set_trigger = secondary_set_trigger self.special_movement = special_movement self.order_endings = order_endings class PrimaryAreaSet(): def __init__(self, area_type=0, zone_index=0, area_index=0): self.area_type = area_type self.zone_index = zone_index self.area_index = area_index class OrderEnding(): def __init__(self, next_order_index=0, combination_rule=0, delay_time=0.0, dialogue_type=0, triggers_tag_block=None, triggers_header=None, triggers=None): self.next_order_index = next_order_index self.combination_rule = combination_rule self.delay_time = delay_time self.dialogue_type = dialogue_type self.triggers_tag_block = triggers_tag_block self.triggers_header = triggers_header self.triggers = triggers class Trigger(): def __init__(self, trigger_flags=0, trigger_index=0): self.trigger_flags = trigger_flags self.trigger_index = trigger_index class AITrigger(): def __init__(self, name="", trigger_flags=0, combination_rule=0, conditions_tag_block=None, conditions_header=None, conditions=None): self.name = name self.trigger_flags = trigger_flags self.combination_rule = combination_rule self.conditions_tag_block = conditions_tag_block self.conditions_header = conditions_header self.conditions = conditions class Condition(): def __init__(self, rule_type=0, squad_index=0, squad_group_index=0, a=0, x=0.0, trigger_volume_index=0, exit_condition_script="", exit_condition_script_index=0, flags=0): self.rule_type = rule_type self.squad_index = squad_index self.squad_group_index = squad_group_index self.a = a self.x = x self.trigger_volume_index = trigger_volume_index self.exit_condition_script = exit_condition_script self.exit_condition_script_index = exit_condition_script_index self.flags = flags
58.446372
183
0.700661
6434991b0677679508d730176e20970d8dd0cbe3
23,643
py
Python
turing_bot.py
wyldbrian/turing
51f4e5b942da2820f3f893a1e6700ce1eaee7f12
[ "MIT" ]
1
2017-11-01T16:08:12.000Z
2017-11-01T16:08:12.000Z
turing_bot.py
wyldbrian/turing
51f4e5b942da2820f3f893a1e6700ce1eaee7f12
[ "MIT" ]
2
2018-05-06T20:18:04.000Z
2019-07-26T18:00:05.000Z
turing_bot.py
wyldbrian/turing
51f4e5b942da2820f3f893a1e6700ce1eaee7f12
[ "MIT" ]
null
null
null
#!/bin/python # +-----------------------------------------------------------------------+ # | File Name: turing_bot.py | # +-----------------------------------------------------------------------+ # | Description: Turing watches an IRC channel and responds to prompts | # +-----------------------------------------------------------------------+ # | Usage: Use ++ or -- to hand out or take away karma (e.g. wyldbrian++) | # | Use !rank to check an items karma rank (e.g. !rank wyldbrian) | # | Use !top to see the top 5 items by karma | # | Use !bottom to see the bottom 5 items by karma | # | Use !weather City,State to check weather | # | Use !astronomy to check moon info and sunset/sunrise times | # | Use !$stock to check current quote for a stock (e.g. !$AMD) | # +-----------------------------------------------------------------------+ # | Authors: wyldbrian | # +-----------------------------------------------------------------------+ # | Date: 2019-07-22 | # +-----------------------------------------------------------------------+ # | Version: 1.7.4 | # +-----------------------------------------------------------------------+ #################################################### # Import necessary modules # #################################################### import re import ssl import sys import json import socket import requests import logging import threading from time import sleep from datetime import datetime, time from ConfigParser import ConfigParser #################################################### # Setup config parser # #################################################### config = ConfigParser() config.read('turing.cfg') #################################################### # Set logging parameters # #################################################### try: logfile = config.get('IRC', 'log') except BaseException: logfile = '/var/log/turing.log' loglevel = logging.INFO logformat = '%(asctime)s - %(levelname)s - %(message)s' logging.basicConfig(filename=logfile, format=logformat, level=loglevel) #################################################### # Set IRC connection values # #################################################### try: tls = config.getboolean('IRC', 'tls') port = config.getint('IRC', 'port') quake = config.getboolean('Features', 'quake') server = config.get('IRC', 'host') strava = config.getboolean('Features', 'strava') channel = config.get('IRC', 'channel') botnick = config.get('IRC', 'nick') passreq = config.getboolean('IRC', 'passreq') oxford_id = config.get('API Keys', 'oxford_id') oxford_key = config.get('API Keys', 'oxford_key') mag_thresh = config.getint('Earthquake', 'mag_thresh') weather_key = config.get('API Keys', 'weather_key') if strava: strava_key = config.get('API Keys', 'strava_key') if passreq: password = config.get('IRC', 'password') except BaseException: message = "Exiting: unable to get config values" logging.critical(message) sys.exit() #################################################### # Global IRC message function # #################################################### def chat(msg): irc.send('PRIVMSG ' + channel + ' :' + msg + '\r\n') #################################################### # Create karma save/load process # #################################################### karma_val = [] karma_num = [] def karmaload(): global karma_val global karma_num load_val = open("karma_val.json") load_num = open("karma_num.json") karma_val = json.loads(load_val.read()) karma_num = json.loads(load_num.read()) load_val.close() load_num.close() def karmasave(): threading.Timer(30, karmasave).start() global karma_val global karma_num save_val = file("karma_val.json", "w") save_num = file("karma_num.json", "w") save_val.write(json.dumps(karma_val)) save_num.write(json.dumps(karma_num)) save_val.close() save_num.close() try: karmaload() except BaseException: logging.critical('Karmaload failed, exiting') sys.exit() else: karmasave() #################################################### # Create earthquake save/load process # #################################################### quake_id = [] def quakeload(): global quake_id load_quakes = open("quake_id.json") quake_id = json.loads(load_quakes.read()) load_quakes.close() def quakesave(): global quake_id save_quakes = file("quake_id.json", "w") save_quakes.write(json.dumps(quake_id)) save_quakes.close() try: quakeload() except ValueError: logging.critical('Quakeload discovered no values, moving on.') except BaseException: logging.critical('Quakeload failed, moving on.') #################################################### # Create strava save/load process # #################################################### strava_id = [] def stravaload(): global strava_id load_strava = open("strava_id.json") strava_id = json.loads(load_strava.read()) load_strava.close() def stravasave(): threading.Timer(30, stravasave).start() global strava_id save_strava = file("strava_id.json", "w") save_strava.write(json.dumps(strava_id)) save_strava.close() try: stravaload() except BaseException: logging.critical('Stravaload failed, exiting') sys.exit() else: stravasave() #################################################### # Build karma functions for IRC # #################################################### def karmaup(): try: karma_up = (text.split("++")[0]).split(":")[2].rsplit(None, 1)[-1].lower() except IndexError: message = "What would you like to give Karma to? (e.g. Karmabot++)" chat(message) return if karma_up in karma_val: idx = karma_val.index(karma_up) num = karma_num[idx] karma_num[idx] = int(num) + 1 user = (text.split(":")[1]).split("!")[0] logmsg = user + " gave karma to " + karma_up + " (++)" logging.info(logmsg) elif karma_up not in karma_val: karma_val.append(karma_up) karma_num.append(1) user = (text.split(":")[1]).split("!")[0] logmsg = user + " gave karma to " + karma_up + " (++)" logging.info(logmsg) def karmadown(): try: karma_down = (text.split("--")[0]).split(":")[2].rsplit(None, 1)[-1].lower() except IndexError: message = "What would you like to take Karma away from? (e.g. Karmabot--)" chat(message) return if karma_down in karma_val: idx = karma_val.index(karma_down) num = karma_num[idx] karma_num[idx] = int(num) - 1 user = (text.split(":")[1]).split("!")[0] logmsg = user + " took karma away from " + karma_down + " (--)" logging.info(logmsg) elif karma_down not in karma_val: karma_val.append(karma_down) karma_num.append(-1) user = (text.split(":")[1]).split("!")[0] logmsg = user + " took karma away from " + karma_down + " (--)" logging.info(logmsg) def karmarank(): try: rank = (text.split(':!rank')[1]).strip().lower() except IndexError: message = "What would you like to check the rank of? (e.g. !rank Karmabot)" chat(message) return if rank in karma_val: idx = karma_val.index(rank) num = karma_num[idx] message = (rank + " has " + str(num) + " points of karma!") chat(message) elif rank not in karma_val: message = (rank + " doesn't have any karma yet!") chat(message) def topkarma(): top_results = sorted(zip(karma_num, karma_val), reverse=True)[:5] irc.send('PRIVMSG ' + channel + ' :' + "## TOP 5 KARMA RECIPIENTS ##" + '\r\n') for (x, y) in top_results: message = (y + ": " + str(x)) chat(message) def bottomkarma(): top_results = sorted(zip(karma_num, karma_val), reverse=False)[:5] irc.send('PRIVMSG ' + channel + ' :' + "## BOTTOM 5 KARMA RECIPIENTS ##" + '\r\n') for (x, y) in top_results: message = (y + ": " + str(x)) chat(message) #################################################### # Build weather function for IRC # #################################################### def weathercheck(): zipcode = (text.split("!weather")[1]).strip() try: url = 'https://api.openweathermap.org/data/2.5/weather?zip=%s&units=imperial&appid=%s' % (zipcode, weather_key) req = requests.get(url) except (socket.timeout, requests.RequestException): message = "Weather API timed out, please try again in a few seconds." chat(message) logging.warning(message) return weather_output = req.text weather_dict = json.loads(weather_output) try: location = weather_dict['name'] tempf = int(weather_dict['main']['temp']) tempc = int((tempf - 32)*.5556) humidity = weather_dict['main']['humidity'] condition = weather_dict['weather'][0]['description'] except KeyError: if "requests limitation" in weather_output: message = ("Weather API rate limit reached, please try again in a few seconds.") chat(message) logging.warning(message) return elif "city not found" in weather_output: message = ("No weather results found for ZIP code %s") % zipcode chat(message) logging.warning(message) return elif "Nothing to geocode" in weather_output: message = "What ZIP code (US only) would you like to check the weather of? (e.g. !weather 12345)" chat(message) return else: message = ("Unknown API error occured, please try again later") chat(message) logging.warning(message) return message = "The weather in %s is currently showing %s with a temperature of %sF (%sC) and %s%% humidity" % (location, condition, tempf, tempc, humidity) chat(message) #################################################### # Build function for astronomy checks # #################################################### def astronomycheck(): try: url = 'http://api.wunderground.com/api/%s//astronomy/q/OR/Bend.json' % weather_key req = requests.get(url) except (socket.timeout, requests.RequestException): message = "Caught timeout/url exception when hitting Weather Underground API" logging.critical(message) return astronomy_output = req.text astronomy_dict = json.loads(astronomy_output) try: age = astronomy_dict['moon_phase']['ageOfMoon'] phase = astronomy_dict['moon_phase']['phaseofMoon'] illum = astronomy_dict['moon_phase']['percentIlluminated'] sunrise = str(astronomy_dict['moon_phase']['sunrise']['hour']) + ":" + str(astronomy_dict['moon_phase']['sunrise']['minute']) sunset = str(astronomy_dict['moon_phase']['sunset']['hour']) + ":" + str(astronomy_dict['moon_phase']['sunset']['minute']) except KeyError: if "keynotfound" in astronomy_output or "missingkey" in astronomy_output: message = ("Weather API rate limit reached, please try again in a few seconds.") chat(message) logging.warning(message) return else: message = ("Unknown API error occured, please try again later") chat(message) logging.warning(message) return first_message = "Today the moon is %s days old, %s illuminated, and in its %s phase." % (age, illum + "%", phase) second_message = "Today the sun rises at %s and sets at %s." % (sunrise, sunset) irc.send('PRIVMSG ' + channel + ' :' + first_message + '\r\n') irc.send('PRIVMSG ' + channel + ' :' + second_message + '\r\n') #################################################### # Build function for earthquake checks # #################################################### def quakecheck(): threading.Timer(120, quakecheck).start() try: req = requests.get('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson') except (socket.timeout, requests.RequestException): message = "Caught timeout/url exception when contacting USGS API" logging.critical(message) return quake_output = req.text quake_dict = json.loads(quake_output) global quake_id for quake in quake_dict['features']: if quake['id'] not in quake_id: quake_id.append(quake['id']) quakesave() mag = quake['properties']['mag'] location = quake['properties']['place'] message = "%s magnitude earthquake detected %s" % (mag, location) try: if int(mag) >= mag_thresh: chat(message) logging.warning(message) except BaseException: message = "Caught exception trying to post quake info to IRC" logging.critical(message) return #################################################### # Build function for strava checks # #################################################### def stravacheck(): threading.Timer(120, stravacheck).start() try: url = 'https://www.strava.com/api/v3/activities/following' headers = {'Authorization': 'Bearer %s'} % strava_key req = requests.get(url, headers=headers) except (socket.timeout, requests.RequestException): message = "Caught timeout/url exception when contacting Strava API" logging.critical(message) return strava_output = req.text strava_dict = json.loads(strava_output) global strava_id for activity in strava_dict: if activity['id'] not in strava_id: strava_id.append(activity['id']) first = activity['athlete']['firstname'] last = activity['athlete']['lastname'] type = activity['type'] name = activity['name'] miles = round((activity['distance'] / 1609.344), 1) message = "%s %s just completed a %s mile %s - %s" % (first, last, miles, type, name) try: chat(message) except BaseException: message = "Caught exception trying to post strava info to IRC" logging.critical(message) return logging.info(message) #################################################### # Build function for dictionary checks # #################################################### def dictionarycheck(): try: word = (text.split("!define")[1]).strip() except IndexError: message = "What word would you like to lookup the definition for? (e.g. !define ace)" chat(message) return try: url = 'https://od-api.oxforddictionaries.com:443/api/v2/entries/en/%s' % word headers = { 'accept': 'application/json', 'app_id': oxford_id, 'app_key': oxford_key } req = requests.get(url, headers=headers) except socket.timeout: message = "Oxford API timed out, please try again in a few seconds." chat(message) logging.warning(message) return try: oxford_output = req.text.encode('ascii', 'ignore') oxford_dict = json.loads(oxford_output) except ValueError: message = "No results found for %s, please try a different word." % (word) chat(message) return try: type = oxford_dict['results'][0]['lexicalEntries'][0]['lexicalCategory']['id'][:1] definition = oxford_dict['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['definitions'][0] except KeyError: try: type = oxford_dict['results'][0]['lexicalEntries'][1]['lexicalCategory']['id'][:1] definition = oxford_dict['results'][0]['lexicalEntries'][1]['entries'][0]['senses'][0]['definitions'][0] except KeyError: message = "No results found for %s, please try a different word." % (word) chat(message) return except IndexError: message = "No results found for %s, please try a different word." % (word) chat(message) return message = "%s(%s) - %s" % (word.capitalize(), type.lower(), definition.capitalize()) chat(message) #################################################### # Build function for stock checks # #################################################### def marketopen(): day = datetime.today().weekday() now = datetime.utcnow().time() if day < 5 and now >= time(14, 30) and now <= time(21, 00): return True else: return False def stockcheck(): try: stock = text.split(':!$')[1].rstrip() except IndexError: message = "\x0304Please use correct format (e.g. !$AMD)\x03" chat(message) return try: url = 'https://finance.yahoo.com/quote/%s' % stock headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \ AppleWebKit/537.36 (KHTML, like Gecko) \ Chrome/70.0.3538.77 Safari/537.36' } req = requests.get(url, headers=headers) content = req.text.encode("utf-8") ticker = stock.upper() name = re.findall(r'<title>(.*?)\(%s\)' % ticker, content)[0].strip() if marketopen(): price = re.findall(r'data-reactid=.\d*.>([0-9,*]+\.\d\d)</span><span\sclass=.Trsdu', content)[0] change = re.findall(r'data-reactid=.\d\d.>([-+]\d*\.?\d*.\([-+]?.*?\(?)</span>', content)[0] status = "\x0303Market Open\x03" else: try: price = re.findall(r'data-reactid=.\d*.>([0-9,*]+\.\d*)</span><!--', content)[0] change = re.findall(r'data-reactid=.\d\d.>([-+]\d*\.?\d*.\([-+]?.*?\(?)</span>', content)[1] status = "\x0304Market Closed\x03" except IndexError: price = re.findall(r'data-reactid=.\d*.>([0-9,*]+\.\d\d)</span><span\sclass=.Trsdu', content)[0] change = re.findall(r'data-reactid=.\d\d.>([-+]\d*\.?\d*.\([-+]?.*?\(?)</span>', content)[0] status = "\x0304Market Closed\x03" if "+" in change: message = "%s | %s | %s | \x0303$%s\x03 | \x0303%s\x03" % (ticker, name, status, price, change) else: message = "%s | %s | %s | \x0304$%s\x03 | \x0304%s\x03" % (ticker, name, status, price, change) except socket.timeout: message = "\x0304Timeout occurred, please try again in a few seconds.\x03" except AttributeError: message = "\x0304No quote found, try the full ticker (e.g. !$NYSE:%s)\x03" % (stock.upper()) except BaseException: message = "\x0304Unknown error occured, please try again later\x03" irc.send('PRIVMSG ' + channel + ' :' + message.replace("\\x26", "&").replace("&amp;", "&") + '\r\n') #################################################### # Build IRC help function # #################################################### def help(): irc.send('PRIVMSG ' + channel + ' :' + " ##############################TURING USAGE##############################" + '\r\n') irc.send('PRIVMSG ' + channel + ' :' + " !weather = check weather for a specific ZIP code (e.g. !weather 12345)" + '\r\n') irc.send('PRIVMSG ' + channel + ' :' + " ++ or -- = give or take karma from whatever you want (e.g. Turing++)" + '\r\n') irc.send('PRIVMSG ' + channel + ' :' + " !rank = show the rank of a particular thing (e.g. !rank Turing)" + '\r\n') irc.send('PRIVMSG ' + channel + ' :' + " !define = lookup the definition of a word (e.g. !define chat)" + '\r\n') irc.send('PRIVMSG ' + channel + ' :' + " !astronomy = check moon information and sunset/sunrise times" + '\r\n') irc.send('PRIVMSG ' + channel + ' :' + " !top or !bottom = show the top or bottom 5 items by Karma" + '\r\n') irc.send('PRIVMSG ' + channel + ' :' + " !$stock = show the current quote for a stock (e.g. !$AMD)" + '\r\n') #################################################### # Build IRC connect function # #################################################### def connect(): global irc if tls: irc = ssl.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) else: irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) while True: try: irc.connect((server, port)) except socket.error: sleep(30) continue break if passreq: irc.send("PASS " + password + "\n") irc.send("NICK " + botnick + "\n") irc.send("USER " + botnick + " " + botnick + " " + botnick + " :Machines take me by surprise with great frequency.\n") irc.send("JOIN " + channel + "\n") else: irc.send("USER " + botnick + " " + botnick + " " + botnick + " :Machines take me by surprise with great frequency.\n") irc.send("NICK " + botnick + "\n") irc.send("JOIN " + channel + "\n") #################################################### # Watch IRC chat for key values and run functions # #################################################### connect() if quake: try: quakecheck() except BaseException: message = "Unable to start quakecheck, starting Turing without it." logging.critical(message) pass if strava: try: stravacheck() except BaseException: message = "Unable to start stravacheck, starting Turing without it" logging.critical(message) pass while True: text = irc.recv(1024) if text.find('PING') != -1: irc.send('PONG ' + text.split()[1] + '\r\n') elif text.find('++') != -1 and text.find(channel) != -1: karmaup() elif text.find('--') != -1 and text.find(channel) != -1: karmadown() elif text.find('!define') != -1 and text.find(channel) != -1: dictionarycheck() elif text.find('!rank') != -1 and text.find(channel) != -1: karmarank() elif text.find('!top') != -1 and text.find(channel) != -1: topkarma() elif text.find('!bottom') != -1 and text.find(channel) != -1: bottomkarma() elif text.find('!weather') != -1 and text.find(channel) != -1: weathercheck() elif text.find('!astronomy') != -1 and text.find(channel) != -1: astronomycheck() elif text.find('!$') != -1 and text.find(channel) != -1: stockcheck() elif text.find('!help') != -1 and text.find(channel) != -1: sleep(.5) help() elif len(text) == 0: while True: try: sleep(30) connect() except BaseException: continue break
37.8288
155
0.51271
cdee1cd0db195d886f8e1b3a5958cb46f97c2456
144
cs
C#
src/ExplorePackages.Logic/Protocol/Data/IAsOfData.cs
loic-sharma/ExplorePackages
3d60646aa60b118377bd3356f5802078beb09f5c
[ "MIT" ]
null
null
null
src/ExplorePackages.Logic/Protocol/Data/IAsOfData.cs
loic-sharma/ExplorePackages
3d60646aa60b118377bd3356f5802078beb09f5c
[ "MIT" ]
null
null
null
src/ExplorePackages.Logic/Protocol/Data/IAsOfData.cs
loic-sharma/ExplorePackages
3d60646aa60b118377bd3356f5802078beb09f5c
[ "MIT" ]
null
null
null
using System; namespace Knapcode.ExplorePackages { public interface IAsOfData { DateTimeOffset AsOfTimestamp { get; } } }
14.4
45
0.673611
f5f0888275222b51dd8b30eca58c9bf0e0c4c186
33
css
CSS
src/lib/src/component/number-control/number-control.component.css
BenjaminDobler/ng-schema-editor
e5e10502f354fbc6c9461e44280aacb9862cde2b
[ "MIT" ]
null
null
null
src/lib/src/component/number-control/number-control.component.css
BenjaminDobler/ng-schema-editor
e5e10502f354fbc6c9461e44280aacb9862cde2b
[ "MIT" ]
null
null
null
src/lib/src/component/number-control/number-control.component.css
BenjaminDobler/ng-schema-editor
e5e10502f354fbc6c9461e44280aacb9862cde2b
[ "MIT" ]
null
null
null
@import "../control.common.css";
16.5
32
0.666667
a15773364dbf741e8514afc2dfdd4055ccc69246
487
cpp
C++
src/Griddly/Core/Observers/NoneObserver.cpp
Thaigun/Griddly
de5972a608a2928172510a0ac81a977c48af6b1f
[ "MIT" ]
null
null
null
src/Griddly/Core/Observers/NoneObserver.cpp
Thaigun/Griddly
de5972a608a2928172510a0ac81a977c48af6b1f
[ "MIT" ]
null
null
null
src/Griddly/Core/Observers/NoneObserver.cpp
Thaigun/Griddly
de5972a608a2928172510a0ac81a977c48af6b1f
[ "MIT" ]
null
null
null
#include "NoneObserver.hpp" #include <memory> namespace griddly { NoneObserver::NoneObserver(std::shared_ptr<Grid> grid) : Observer(grid) { observationShape_ = {1,1,1}; observationStrides_ = {1,1,1}; emptyObs_ = std::shared_ptr<uint8_t>(new uint8_t[1]{}); //NOLINT } uint8_t& NoneObserver::update() { return *emptyObs_.get(); } void NoneObserver::resetShape() { } ObserverType NoneObserver::getObserverType() const { return ObserverType::NONE; } } // namespace griddly
19.48
73
0.712526
10b6afb6edbb5fd07f121dfd2ce590339f06ec4a
8,761
swift
Swift
PropertyExchange/YPProjectInverstmentTableViewCell.swift
forwk1990/PropertyExchange
bc24b0cf13c5978f7d17440fe1650e79c455c70c
[ "MIT" ]
null
null
null
PropertyExchange/YPProjectInverstmentTableViewCell.swift
forwk1990/PropertyExchange
bc24b0cf13c5978f7d17440fe1650e79c455c70c
[ "MIT" ]
null
null
null
PropertyExchange/YPProjectInverstmentTableViewCell.swift
forwk1990/PropertyExchange
bc24b0cf13c5978f7d17440fe1650e79c455c70c
[ "MIT" ]
null
null
null
// // YPProjectInverstmentTableViewCell.swift // PropertyExchange // // Created by itachi on 16/9/29. // Copyright © 2016年 com.itachi. All rights reserved. // import UIKit class YPProjectInverstmentTableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.createSubviews() self.createLayoutConstraints() } public class func cell(withTableView tableView:UITableView, forReuseIdentifier reuseIdentifier:String) -> UITableViewCell?{ var tableViewCell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) if(tableViewCell == nil){ tableViewCell = YPProjectInverstmentTableViewCell(style: UITableViewCellStyle.default,reuseIdentifier: reuseIdentifier) tableViewCell?.selectionStyle = UITableViewCellSelectionStyle.none } tableViewCell?.contentView.backgroundColor = UIColor.colorWithHex(hex: 0xFFFFFF) return tableViewCell } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private lazy var suggestImageView:UIImageView = { let _imageView = UIImageView() _imageView.image = UIImage(named:"荐") return _imageView }() private lazy var titleLabel:UILabel = { return self.createLabel(withFont:UIFont.systemFont(ofSize: 14), andColor:UIColor.colorWithHex(hex: 0x39404D)) }() private lazy var categoryTitleLabel:UILabel = { let _label = self.createLabel(withFont:UIFont.systemFont(ofSize: 12), andColor:UIColor.colorWithHex(hex: 0x999999)) _label.text = "借款" return _label }() private lazy var totalMoneyLabel:UILabel = { return self.createLabel(withFont:UIFont.systemFont(ofSize: 12), andColor:UIColor.colorWithHex(hex: 0x999999)) }() private lazy var rateLabel:UILabel = { return self.createLabel(withFont:UIFont.systemFont(ofSize: 14), andColor:UIColor.colorWithHex(hex: 0xCBA064)) }() private lazy var deadlineLabel:UILabel = { return self.createLabel(withFont:UIFont.systemFont(ofSize: 14), andColor:UIColor.colorWithHex(hex: 0xCBA064)) }() private lazy var rateFlagLabel:UILabel = { let _label = self.createLabel(withFont:UIFont.systemFont(ofSize: 12), andColor:UIColor.colorWithHex(hex: 0x999999)) _label.text = "年化利率" return _label }() private lazy var deadlineFlagLabel:UILabel = { let _label = self.createLabel(withFont:UIFont.systemFont(ofSize: 12), andColor:UIColor.colorWithHex(hex: 0x999999)) _label.text = "借款期限" return _label }() private lazy var typeCategoryLabel:UILabel = { let _label = self.createLabel(withFont:UIFont.systemFont(ofSize: 12), andColor:UIColor.colorWithHex(hex: 0x999999)) _label.text = "按月到期还款" return _label }() private lazy var remainFlagLabel:UILabel = { let _label = self.createLabel(withFont:UIFont.systemFont(ofSize: 12), andColor:UIColor.colorWithHex(hex: 0x999999)) _label.text = "剩余" return _label }() private lazy var remainLabel:UILabel = { return self.createLabel(withFont:UIFont.systemFont(ofSize: 12), andColor:UIColor.colorWithHex(hex: 0x999999)) }() private lazy var containerView:UIView = { let _view = UIView() return _view }() private lazy var circleProgress:CircleProgressBar = { let _circleProgress = CircleProgressBar() _circleProgress.backgroundColor = UIColor.white _circleProgress.startAngle = 90 _circleProgress.progressBarWidth = 2.0 _circleProgress.hintViewSpacing = 10 _circleProgress.hintTextColor = UIColor.colorWithHex(hex: 0xCBA064) _circleProgress.hintTextFont = UIFont.systemFont(ofSize: 12) _circleProgress.hintViewBackgroundColor = UIColor.white _circleProgress.progressBarTrackColor = UIColor.colorWithHex(hex: 0xF5F5F5) _circleProgress.progressBarProgressColor = UIColor.colorWithHex(hex: 0xCBA064) return _circleProgress }() public var model:YPProjectInverstmentCellModel?{ didSet{ guard let _model = self.model else { return } self.titleLabel.text = _model.title if(_model.isSuggest){ self.suggestImageView.snp.remakeConstraints { (make) in make.top.equalTo(self.containerView).offset(13) make.left.equalTo(self.containerView) make.width.height.equalTo(14) } self.titleLabel.snp.remakeConstraints({ (make) in make.top.equalTo(self.containerView) make.height.equalTo(40) make.left.equalTo(self.suggestImageView.snp.right).offset(5) }) }else{ self.suggestImageView.snp.remakeConstraints { (make) in make.top.equalTo(self.containerView).offset(13) make.left.equalTo(self.containerView) make.width.height.equalTo(0) } self.titleLabel.snp.remakeConstraints({ (make) in make.top.equalTo(self.containerView) make.height.equalTo(40) make.left.equalTo(self.containerView) }) } self.typeCategoryLabel.text = _model.payingWay self.totalMoneyLabel.text = "¥ \(String.decimalString(from: Float(_model.totalMoney)))" self.rateLabel.text = "\(_model.rate)%" self.deadlineLabel.text = _model.deadline self.remainLabel.text = "¥\(_model.remainMoney)" self.circleProgress.setProgress(CGFloat(_model.remainMoney / _model.totalMoney), animated: true) } } private func createSubviews(){ self.contentView.addSubview(self.containerView) self.containerView.addSubview(self.suggestImageView) self.containerView.addSubview(self.titleLabel) self.containerView.addSubview(self.categoryTitleLabel) self.containerView.addSubview(self.totalMoneyLabel) self.containerView.addSubview(self.rateLabel) self.containerView.addSubview(self.deadlineLabel) self.containerView.addSubview(self.rateFlagLabel) self.containerView.addSubview(self.deadlineFlagLabel) self.containerView.addSubview(self.typeCategoryLabel) self.containerView.addSubview(self.remainFlagLabel) self.containerView.addSubview(self.remainLabel) self.containerView.addSubview(self.circleProgress) } private func createLabel(withFont font:UIFont,andColor color:UIColor) -> UILabel{ let _categoryTitleLabel = UILabel() _categoryTitleLabel.textColor = color _categoryTitleLabel.font = font return _categoryTitleLabel } private func createLayoutConstraints(){ self.containerView.snp.makeConstraints { (make) in make.edges.equalTo(contentView).inset(UIEdgeInsetsMake(0, 18, 0, 18)) } self.titleLabel.snp.makeConstraints { (make) in make.top.equalTo(self.containerView) make.height.equalTo(40) } self.categoryTitleLabel.snp.makeConstraints { (make) in make.right.equalTo(self.containerView).offset(-100) make.top.equalTo(self.containerView) make.height.equalTo(40) } self.totalMoneyLabel.snp.makeConstraints { (make) in make.right.equalTo(self.containerView) make.top.equalTo(self.containerView) make.height.equalTo(40) } self.rateLabel.snp.makeConstraints { (make) in make.left.equalTo(self.containerView) make.top.equalTo(self.titleLabel.snp.bottom) make.height.equalTo(20) } self.deadlineLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self.containerView) make.top.equalTo(self.rateLabel) make.height.equalTo(20) } self.rateFlagLabel.snp.makeConstraints { (make) in make.height.equalTo(20) make.left.equalTo(self.containerView) make.top.equalTo(self.rateLabel.snp.bottom) } self.deadlineFlagLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self.containerView) make.top.equalTo(self.deadlineLabel.snp.bottom) make.height.equalTo(20) } self.circleProgress.snp.makeConstraints { (make) in make.height.equalTo(40) make.width.equalTo(40) make.right.equalTo(self.containerView) make.top.equalTo(self.totalMoneyLabel.snp.bottom) } self.typeCategoryLabel.snp.makeConstraints { (make) in make.left.equalTo(self.containerView) make.bottom.equalTo(self.containerView) make.height.equalTo(40) } self.remainFlagLabel.snp.makeConstraints { (make) in make.centerX.equalTo(self.categoryTitleLabel) make.bottom.equalTo(self.containerView) make.height.equalTo(40) } self.remainLabel.snp.makeConstraints { (make) in make.right.equalTo(self.containerView) make.bottom.equalTo(self.containerView) make.height.equalTo(40) } } }
35.326613
125
0.713275
8c12d2d883cef441217c2440618c4d677ac03a45
211
cs
C#
Assets/Scripts/Player.cs
alohaeee/ModernPingPong
5dbf7de90238c2685d845e8dc6fafad78e03ba8f
[ "MIT" ]
null
null
null
Assets/Scripts/Player.cs
alohaeee/ModernPingPong
5dbf7de90238c2685d845e8dc6fafad78e03ba8f
[ "MIT" ]
null
null
null
Assets/Scripts/Player.cs
alohaeee/ModernPingPong
5dbf7de90238c2685d845e8dc6fafad78e03ba8f
[ "MIT" ]
null
null
null
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class Player : MonoBehaviour { public TextMeshProUGUI scoreLabel; public TextMeshProUGUI nameLabel; }
19.181818
38
0.796209
981c1c830d533970769ae94088dbe1b624d50321
9,305
py
Python
model/tacotron.py
Numanor/tacotron2
73be3dc08ab5f461f1503715b1a2d443f80b00cc
[ "BSD-3-Clause" ]
null
null
null
model/tacotron.py
Numanor/tacotron2
73be3dc08ab5f461f1503715b1a2d443f80b00cc
[ "BSD-3-Clause" ]
null
null
null
model/tacotron.py
Numanor/tacotron2
73be3dc08ab5f461f1503715b1a2d443f80b00cc
[ "BSD-3-Clause" ]
null
null
null
from math import sqrt, ceil import random from typing import Dict from numpy import mod import torch from pytorch_lightning import LightningModule from .layers import AdversarialClassifier from utils.utils import get_mask_from_lengths from text import symbols from utils.plot import plot_alignment_to_numpy, plot_spectrogram_to_numpy, plot_gate_outputs_to_numpy from hifigan.vocoder import Vocoder class Tacotron2(LightningModule): def __init__(self, encoder: LightningModule, decoder: LightningModule, postnet: LightningModule, mask_padding: bool=True, n_mel_channels: int=80, n_frames_per_step: int=3, symbols_lang: str="en", symbols_embedding_dim: int=512, freeze_text: bool=False, load_pretrained_text: str=None, multi_speaker: bool=False, spker_embedding_dim: int=64, n_spker: int=1, speaker_loss_weight: float=0.02, speaker_classifier: AdversarialClassifier=None, vocoder: Vocoder=None): super(Tacotron2, self).__init__() self.save_hyperparameters() # init embedding table and text encoder if load_pretrained_text != None: _pretrained_taco = Tacotron2.load_from_checkpoint(load_pretrained_text, map_location="cpu") self.encoder = _pretrained_taco.encoder.to(self.device) self.embedding = _pretrained_taco.embedding.to(self.device) assert self.encoder.device == self.device == self.embedding.weight.device del encoder del _pretrained_taco else: n_symbols = len(symbols(symbols_lang)) self.embedding = torch.nn.Embedding( n_symbols, symbols_embedding_dim) std = sqrt(2.0 / (n_symbols + symbols_embedding_dim)) val = sqrt(3.0) * std # uniform bounds for std self.embedding.weight.data.uniform_(-val, val) self.encoder = encoder if freeze_text: self.embedding.weight.requires_grad = False self.encoder.freeze() if multi_speaker: self.speaker_embedding = torch.nn.Embedding( n_spker, spker_embedding_dim) std = sqrt(2.0 / (n_spker + spker_embedding_dim)) val = sqrt(3.0) * std # uniform bounds for std self.speaker_embedding.weight.data.uniform_(-val, val) self.speaker_classifier = speaker_classifier self.decoder = decoder self.postnet = postnet self.vocoder = vocoder if self.vocoder != None: for v in self.vocoder.generator.parameters(): v.requires_grad = False def parse_batch(self, batch): text_padded, input_lengths, mel_padded, gate_padded, output_lengths, spkerID = batch return ((text_padded, input_lengths, mel_padded, output_lengths, spkerID), (mel_padded, gate_padded, spkerID)) def parse_output(self, outputs: Dict, output_lengths=None): if self.hparams.mask_padding and output_lengths is not None: output_total_length = outputs["mel"].size(2) mask = ~get_mask_from_lengths(output_lengths, output_total_length) mask = mask.expand(self.hparams.n_mel_channels, mask.size(0), mask.size(1)) if mask.size(2)%self.hparams.n_frames_per_step != 0 : to_append = torch.ones( mask.size(0), mask.size(1), (self.hparams.n_frames_per_step-mask.size(2)%self.hparams.n_frames_per_step) ).bool() mask = torch.cat([mask, to_append], dim=-1) mask = mask.permute(1, 0, 2) outputs["mel_raw"].data.masked_fill_(mask, 0.0) outputs["mel"].data.masked_fill_(mask, 0.0) outputs["gate"].data.masked_fill_(mask[:, 0, :], 1e3) return outputs def compute_loss(self, model_output: Dict, targets: Dict): for t in targets.values(): if t != None: t.requires_grad = False mel_target, gate_target = targets["mel"], targets["gate"].view(-1, 1) mel_loss = torch.nn.MSELoss()(model_output["mel_raw"], mel_target) + \ torch.nn.MSELoss()(model_output["mel"], mel_target) gate_out = model_output["gate"].view(-1, 1) gate_loss = torch.nn.BCEWithLogitsLoss()(gate_out, gate_target) loss = {'mel_loss': mel_loss, 'gate_loss': gate_loss} if "speaker" in model_output: speaker_predict = model_output["speaker"].transpose(1, 2) # (B, T, n_speaker) -> (B, n_speaker, T) speaker_target = targets["speaker"].unsqueeze(1).repeat(1, speaker_predict.size(2)) # (B) -> (B, T) speaker_loss = torch.nn.CrossEntropyLoss()(speaker_predict, speaker_target) speaker_loss = speaker_loss * self.hparams.speaker_loss_weight loss['speaker_loss'] = speaker_loss loss['loss'] = sum(loss.values()) return loss def forward(self, inputs: Dict): inputs["text_len"], inputs["mel_len"] = inputs["text_len"].data, inputs["mel_len"].data embedded_inputs = self.embedding(inputs["text"]).transpose(1, 2) encoder_outputs = self.encoder(embedded_inputs, inputs["text_len"]) outputs = dict({}) if self.hparams.multi_speaker: if self.speaker_classifier != None: outputs["speaker"] = self.speaker_classifier(encoder_outputs) speaker_embedded = self.speaker_embedding(inputs["speaker"])[:, None] speaker_embedded = speaker_embedded.repeat(1, encoder_outputs.size(1), 1) encoder_outputs = torch.cat((encoder_outputs, speaker_embedded), dim=2) outputs["mel_raw"], outputs["gate"], outputs["align"] = self.decoder( encoder_outputs, inputs["mel"], memory_lengths=inputs["text_len"]) postnet_outputs = self.postnet(outputs["mel_raw"]) outputs["mel"] = outputs["mel_raw"] + postnet_outputs return self.parse_output(outputs, inputs["mel_len"]) def inference(self, inputs): embedded_inputs = self.embedding(inputs).transpose(1, 2) encoder_outputs = self.encoder.inference(embedded_inputs) mel_outputs, gate_outputs, alignments = self.decoder.inference( encoder_outputs) mel_outputs_postnet = self.postnet(mel_outputs) mel_outputs_postnet = mel_outputs + mel_outputs_postnet outputs = self.parse_output( [mel_outputs, mel_outputs_postnet, gate_outputs, alignments]) return outputs def mel2wav(self, mel) -> torch.Tensor: audio = self.vocoder.mel2wav(mel.T) return audio def log_loss(self, loss: Dict, prefix: str="training"): for k, v in loss.items(): self.log(f"{prefix}.{k}", v) def log_validation(self, reduced_loss: Dict, y: Dict, y_pred: Dict, iteration: int): self.log_loss(reduced_loss, "validation") # plot distribution of parameters for tag, value in self.named_parameters(): tag = tag.replace('.', '/') self.logger.experiment.add_histogram(tag, value, iteration) # random select a sample for logging idx = random.randint(0, y_pred["align"].size(0) - 1) input_len = y["text_len"][idx].data mel_len = y["mel_len"][idx].data # plot decoder (and reference) attention alignment decoder_steps = ceil(mel_len / self.hparams.n_frames_per_step) self.logger.experiment.add_image( "alignment", plot_alignment_to_numpy(y_pred["align"][idx, :decoder_steps, :input_len].data.cpu().numpy().T), iteration, dataformats='HWC') # plot gate target and predicted self.logger.experiment.add_image( "gate", plot_gate_outputs_to_numpy( y["gate"][idx].data.cpu().numpy(), torch.sigmoid(y_pred["gate"][idx]).data.cpu().numpy()), iteration, dataformats='HWC') # plot mel target and predicted mel_pred = y_pred["mel"][idx, :, :mel_len].data.cpu().numpy() mel_target = y["mel"][idx, :, :mel_len].data.cpu().numpy() self.logger.experiment.add_image( "mel_target", plot_spectrogram_to_numpy(mel_target), iteration, dataformats='HWC') self.logger.experiment.add_image( "mel_predicted", plot_spectrogram_to_numpy(mel_pred), iteration, dataformats='HWC') # synthesis audio from mel-spec audio_pred = self.mel2wav(mel_pred) audio_target = self.mel2wav(mel_target) self.logger.experiment.add_audio("audio_pred", audio_pred, iteration, self.vocoder.config.sampling_rate) self.logger.experiment.add_audio("audio_target", audio_target, iteration, self.vocoder.config.sampling_rate) def training_step(self, batch: Dict, batch_idx): y_pred = self(batch) loss = self.compute_loss(y_pred, batch) self.log_loss(loss) return loss['loss'] def validation_step(self, batch : Dict, batch_idx): y_pred = self(batch) loss = self.compute_loss(y_pred, batch) self.log_validation(loss, batch, y_pred, self.global_step) return loss['loss']
42.683486
153
0.637937
8e7c08d95473573b402a0b287c707555f09d00f2
635
js
JavaScript
lib/unset.js
WindomZ/gituser.js
610430112247c2409fead9426010973b65df0636
[ "MIT" ]
8
2017-04-29T14:12:02.000Z
2022-01-12T10:17:00.000Z
lib/unset.js
WindomZ/gituser.js
610430112247c2409fead9426010973b65df0636
[ "MIT" ]
36
2017-05-03T08:44:18.000Z
2021-05-08T15:08:10.000Z
lib/unset.js
WindomZ/gituser.js
610430112247c2409fead9426010973b65df0636
[ "MIT" ]
1
2020-09-09T23:05:34.000Z
2020-09-09T23:05:34.000Z
/** * Created by WindomZ on 17-5-2. */ 'use strict' const shell = require('shelljs') function * unset (options) { if (!shell.which('git')) { throw new ReferenceError('Sorry, this script requires git') } let cmd = 'git config --unset user.name' if (shell.exec(cmd).code !== 0) { throw new ReferenceError('Error: "' + cmd + '" commit failed') } cmd = 'git config --unset user.email' if (shell.exec(cmd).code !== 0) { throw new ReferenceError('Error: "' + cmd + '" commit failed') } return yield true } module.exports = (options) => new Promise(resolve => { resolve(unset(options).next().value) })
21.896552
66
0.620472
7f5c5e6c93c64afb4cf6d66dfb7aab5afa7e0d47
701
php
PHP
resources/views/admin/reservations-edit.blade.php
WiWaG/wowita
9555e3c64810cda5269b410062fceda2fa8cfe1a
[ "MIT" ]
3
2021-01-29T12:08:39.000Z
2021-02-27T14:55:25.000Z
resources/views/admin/reservations-edit.blade.php
WiWaG/wowita
9555e3c64810cda5269b410062fceda2fa8cfe1a
[ "MIT" ]
15
2021-02-01T12:31:34.000Z
2021-02-27T10:01:22.000Z
resources/views/admin/reservations-edit.blade.php
WiWaG/wowita
9555e3c64810cda5269b410062fceda2fa8cfe1a
[ "MIT" ]
3
2021-01-28T08:33:14.000Z
2021-02-27T14:55:05.000Z
@extends('layouts.dashboard') @section('content') <div class="container bg-yellow-300 p-2 lg:p-4"> <div class="rounded bg-white shadow-xl p-5 lg:p-20 mx-auto text-gray-800"> <form action=" {{ route('admin.reservations.update', ['reservation' => $reservation]) }} " method="POST"> @csrf @method('PUT') <h2>Reservering {{ $reservation->id }}</h2> <input type="date" name="start_date"> <input type="date" name="end_date"> <input class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" type="submit"> </form> </div> </div> @endsection
25.962963
152
0.594864
cf0c3c0b4b975ac969b3e322c08693e35e30ee16
17,262
php
PHP
modules/Property/Views/frontend/detail.blade.php
Robiul26/property_one
fd9612ad8b7136c4104dd8af28327ef814917b65
[ "MIT" ]
null
null
null
modules/Property/Views/frontend/detail.blade.php
Robiul26/property_one
fd9612ad8b7136c4104dd8af28327ef814917b65
[ "MIT" ]
null
null
null
modules/Property/Views/frontend/detail.blade.php
Robiul26/property_one
fd9612ad8b7136c4104dd8af28327ef814917b65
[ "MIT" ]
null
null
null
@extends('layouts.app') @section('head') @endsection @section('content') <section class="listing-title-area p-0"> @include('Property::frontend.layouts.details.gallery_property') </section> <!-- Agent Single Grid View --> <section class="our-agent-single bgc-f7 pb30-991"> <div class="container"> @include('Agencies::frontend.detail.search_mobile') <div class="row"> <div class="col-md-12 col-lg-8 mt50"> <div class="row"> <div class="col-lg-12"> <div class="listing_single_description2 mt30-767 mb30-767"> <div class="single_property_title"> <h2>{{ $translation->title ?? '' }}</h2> <p>{{ $translation->address }}</p> </div> <div class="single_property_social_share style2"> <div class="price"> <h2>{{ $row['display_price'] ? $row['display_price'] : '' }}</h2> </div> </div> </div> </div> <div class="col-lg-12"> <div class="listing_single_description style2"> <div class="lsd_list"> <ul class="mb0"> @if(!empty($row['Category'])) <?php $translationCategory = $row['Category']->translateOrOrigin(app()->getLocale()); ?> <li class="list-inline-item"><a href="#">{{ __($translationCategory->name) }}</a></li> @endif @if(!empty($row['bed'])) <li class="list-inline-item"><a href="#">{{ __("Beds") }}: {{ !empty($row['bed']) ? $row['bed'] : ''}}</a></li> @endif @if(!empty($row['bathroom'])) <li class="list-inline-item"><a href="#">{{ __("Baths") }}: {{ !empty($row['bathroom']) ? $row['bathroom'] : '' }}</a></li> @endif @if(!empty($row['square'])) <li class="list-inline-item"><a href="#">{{ __("Sq Ft") }}: {{ !empty($row['square']) ? $row['square'] : ''}}</a></li> @endif </ul> </div> @if(!empty($row['Description'])) <h4 class="mb30">{{ __("Description") }}</h4> <div class="collapse" id="collapseExample"> <div class="card card-body"> <p class="mt10 mb10">{!! clean($translation->content) !!}</p> </div> </div> <p class="overlay_close"> <a class="text-thm fz14" data-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false" aria-controls="collapseExample"> {{__('Show More')}} <span class="flaticon-download-1 fz12"></span> </a> </p> @endif </div> </div> <div class="col-lg-12"> <div class="additional_details"> <div class="row"> <div class="col-lg-12"> <h4 class="mb15">{{ __("Property Details") }}</h4> </div> <div class="col-md-6 col-lg-6 col-xl-4"> <dl class="inline"> <dt><p>{{ __("Property ID") }} :</p></dt> <dd><p>{{ $row->id ? $row->id : 0 }}</p></dd> <dt><p>{{ __("Price") }} :</p></dt> <dd><p>{{ $row->display_price ? $row->display_price : 0 }}</p></dd> <dt><p>{{ __("Property Size") }} :</p></dt> <dd><p>{!! !empty($row['square']) ? size_unit_format($row['square']) : 0 !!}</p></dd> <dt><p>{{ __("Year Built") }} :</p></dt> <dd><p>{{ $row->year_built ? $row->year_built : __('None') }}</p></dd> </dl> </div> <div class="col-md-6 col-lg-6 col-xl-4"> <dl class="inline"> <dt><p>{{ __("Bedrooms") }} :</p></dt> <dd><p>{{ $row->bed ? $row->bed : 0 }}</p></dd> <dt><p>{{ __("Bathrooms") }} :</p></dt> <dd><p>{{ $row->bathroom ? $row->bathroom : 0 }}</p></dd> <dt><p>{{ __("Garage") }} :</p></dt> <dd><p>{{ $row->garages ? $row->garages : 0 }}</p></dd> </dl> </div> <div class="col-md-6 col-lg-6 col-xl-4"> <dl class="inline"> <dt><p>{{ __("Property Type") }} :</p></dt> <dd><p>{{ $row->category ? $row->category->name : '' }}</p></dd> <dt><p>{{ __("Property Status") }} :</p></dt> <dd><p><span>{{$row->property_type == 1 ? __('For Buy') : __('For Rent')}}</span></p></dd> </dl> </div> </div> </div> </div> <div class="col-lg-12"> <div class="additional_details"> <div class="row"> <div class="col-lg-12"> <h4 class="mb15">{{__('Additional details')}}</h4> </div> <div class="col-md-6 col-lg-6"> <ul class="list-inline-item"> <li><p>{{ __('Deposit') }} :</p></li> <li><p>{{ __('Pool Size') }} :</p></li> <li><p>{{ __('Additional Rooms') }} :</p></li> </ul> <ul class="list-inline-item"> <li><p><span>{{ $row->deposit ? $row->deposit : 0 }}%</span></p></li> <li><p><span>{{ $row->pool_size ? size_unit_format($row->pool_size) : 0 }}</span></p></li> <li><p><span>{{ $row->additional_zoom ? $row->additional_zoom : 0 }}</span></p></li> </ul> </div> <div class="col-md-6 col-lg-6"> <ul class="list-inline-item"> <li><p>{{ __('Last remodel year') }} :</p></li> <li><p>{{ __('Amenities') }} :</p></li> <li><p>{{ __('Equipment') }} :</p></li> </ul> <ul class="list-inline-item"> <li><p><span>{{ $row->remodal_year ? $row->remodal_year : __('None') }}</span></p></li> <li><p><span>{{ $row->amenities ? $row->amenities : 0 }}</span></p></li> <li><p><span>{{ $row->equipment ? $row->equipment : 0 }}</span></p></li> </ul> </div> </div> </div> </div> @include('Property::frontend.layouts.details.property_feature') @if(!empty($row->location->name)) @php $location = $row->location->translateOrOrigin(app()->getLocale()) @endphp @endif <div class="col-lg-12"> <div class="application_statics mt30"> <h4 class="mb30">{{ __("Location") }} <small class="float-right">{{ !empty($location->name) ? $location->name : '' }}</small></h4> <div class="property_video p0"> <div class="thumb"> <div class="h400" id="map-canvas"></div> <div class="overlay_icon"> <a href="#"><img class="map_img_icon" src="{{asset('findhouse/images/header-logo.png')}}" alt="header-logo.png"></a> </div> </div> </div> </div> </div> @include('Property::frontend.layouts.details.property_video') <div class="col-lg-12"> @include('Agencies::frontend.detail.review', ['review_service_id' => $row['id'], 'review_service_type' => 'property']) </div> @include('Property::frontend.layouts.details.property-related') </div> </div> <div class="col-lg-4 col-xl-4 mt50"> <div class="sidebar_listing_list"> <div class="sidebar_advanced_search_widget"> <div class="sl_creator"> <h4 class="mb25">{{ __("Listed By") }}</h4> <div class="media"> <a href="{{route('agent.detail',['id'=>$row->user->id])}}" class="c-inherit"> @if($avatar_url = $row->user->getAvatarUrl()) <img class="mr-3" src="{{$avatar_url}}" alt="{{$row->user->getDisplayName()}}"> @else <span class="mr-3">{{ucfirst($row->user->getDisplayName()[0])}}</span> @endif </a> <div class="media-body"> <h5 class="mt-0 mb0"><a href="{{route('agent.detail',['id'=>$row->user->id])}}" class="c-inherit">{{ $row->user->getDisplayName() }}</a></h5> <p class="mb0">{{ !empty($row->user->phone) ? $row->user->phone : '' }}</p> <p class="mb0">{{ !empty($row->user->email) ? $row->user->email : '' }}</p> <a class="text-thm" href="{{route('agent.detail',['id'=>$row->user->id])}}">{{ __("View My Listing") }}</a> </div> </div> </div> <form action="{{ route('agent.contact') }}" method="POST" class="agent_contact_form"> @csrf <ul class="sasw_list mb0"> <li class="search_area"> <div class="form-group"> <input type="text" class="form-control" placeholder="{{ __('Your Name') }}" name="name"> </div> </li> <li class="search_area"> <div class="form-group"> <input type="number" class="form-control" placeholder="{{ __('Phone') }}" name="phone"> </div> </li> <li class="search_area"> <div class="form-group"> <input type="email" class="form-control" id="email" placeholder="{{ __('Email') }}" name="email"> </div> </li> <li class="search_area"> <div class="form-group"> <textarea id="form_message" name="message" class="form-control required" rows="5" placeholder="{{ __('Your Message') }}"></textarea> </div> </li> <li> <input type="hidden" name="vendor_id" value="{{ $row->user->id }}"> <input type="hidden" name="object_id" value="{{ $row->id }}"> <input type="hidden" name="object_model" value="property"> </li> <li> <div class="search_option_button"> <button type="submit" class="btn btn-block btn-thm">{{ __('Contact') }}</button> </div> </li> </ul> <div class="form-mess"></div> </form> </div> </div> @include('Property::frontend.layouts.search.form-search') @include('Property::frontend.sidebar.FeatureProperty') @include('Property::frontend.sidebar.categoryProperty') @include('Property::frontend.sidebar.recentViewdProperty') </div> </div> </div> </section> @endsection @section('footer') <link href="{{ asset('libs/fotorama/fotorama.css') }}" rel="stylesheet"> <script src="{{ asset('libs/fotorama/fotorama.js') }}"></script> {!! App\Helpers\MapEngine::scripts() !!} <script> jQuery(function ($) { new BravoMapEngine('map-canvas', { fitBounds: true, center: [{{$row->map_lat ?? "51.505"}}, {{$row->map_lng ?? "-0.09"}}], zoom:{{$row->map_zoom ?? "8"}}, ready: function (engineMap) { @if($row->map_lat && $row->map_lng) engineMap.addMarker([{{$row->map_lat}}, {{$row->map_lng}}], { icon_options: {} }); @endif engineMap.on('click', function (dataLatLng) { engineMap.clearMarkers(); engineMap.addMarker(dataLatLng, { icon_options: {} }); $("input[name=map_lat]").attr("value", dataLatLng[0]); $("input[name=map_lng]").attr("value", dataLatLng[1]); }); engineMap.on('zoom_changed', function (zoom) { $("input[name=map_zoom]").attr("value", zoom); }); engineMap.searchBox($('.bravo_searchbox'),function (dataLatLng) { engineMap.clearMarkers(); engineMap.addMarker(dataLatLng, { icon_options: {} }); $("input[name=map_lat]").attr("value", dataLatLng[0]); $("input[name=map_lng]").attr("value", dataLatLng[1]); }); } }); }) </script> @endsection
64.410448
181
0.325339
3905e9afd6f434ab51114bf636fddb5a5109cc12
1,986
py
Python
bravado_core/exception.py
terencehonles/bravado-core
382db874b7b838dcfd169b0ce490d6a447ad6ff2
[ "BSD-3-Clause" ]
122
2015-04-22T17:31:18.000Z
2021-11-08T10:29:57.000Z
bravado_core/exception.py
terencehonles/bravado-core
382db874b7b838dcfd169b0ce490d6a447ad6ff2
[ "BSD-3-Clause" ]
364
2015-04-10T22:19:23.000Z
2022-02-25T08:55:10.000Z
bravado_core/exception.py
terencehonles/bravado-core
382db874b7b838dcfd169b0ce490d6a447ad6ff2
[ "BSD-3-Clause" ]
118
2015-04-20T15:11:53.000Z
2021-12-09T10:03:34.000Z
# -*- coding: utf-8 -*- import sys import six import typing if getattr(typing, 'TYPE_CHECKING', False): from bravado_core._compat_typing import FuncType class SwaggerError(Exception): """Base exception class which all bravado-core specific exceptions inherit from. """ class SwaggerMappingError(SwaggerError): """Raised when an error is encountered during processing of a request or a response. """ class MatchingResponseNotFound(SwaggerMappingError): """Raised when an incoming or outgoing response cannot be matched to a documented response in the swagger spec. """ class SwaggerValidationError(SwaggerMappingError): """Raised when an error is encountered during validating user defined format values in a request or a response. """ class SwaggerSchemaError(SwaggerError): """Raised when an error is encountered during processing of a SwaggerSchema. """ class SwaggerSecurityValidationError(SwaggerValidationError): """Raised when an error is encountered during processing of security related Swagger definitions """ def wrap_exception(exception_class): # type: (typing.Type[BaseException]) -> typing.Callable[[FuncType], FuncType] """Helper decorator method to modify the raised exception class to `exception_class` but keeps the message and trace intact. :param exception_class: class to wrap raised exception with """ def generic_exception(method): # type: (FuncType) -> FuncType def wrapper(*args, **kwargs): # type: (typing.Any, typing.Any) -> typing.Any try: return method(*args, **kwargs) except Exception as e: six.reraise( exception_class, exception_class(str(e)), sys.exc_info()[2], ) return wrapper # type: ignore # ignoring type to avoiding typing.cast call return generic_exception
28.782609
84
0.67422
f3abc82a5600dd12b1da3b7b523bfe22a604854b
2,801
dart
Dart
lib/model/module_coverage.dart
sowderca/azure_devops_sdk
1ef1b3b5f72dca3d5075d211f97196caa99494ad
[ "MIT" ]
2
2019-10-07T12:30:29.000Z
2021-03-19T11:49:53.000Z
lib/model/module_coverage.dart
sowderca/azure_devops_sdk
1ef1b3b5f72dca3d5075d211f97196caa99494ad
[ "MIT" ]
null
null
null
lib/model/module_coverage.dart
sowderca/azure_devops_sdk
1ef1b3b5f72dca3d5075d211f97196caa99494ad
[ "MIT" ]
null
null
null
part of azure_devops_sdk.api; class ModuleCoverage { int blockCount = null; List<String> blockData = []; /* Code Coverage File Url */ String fileUrl = null; List<FunctionCoverage> functions = []; String name = null; String signature = null; int signatureAge = null; CoverageStatistics statistics = null; ModuleCoverage(); @override String toString() { return 'ModuleCoverage[blockCount=$blockCount, blockData=$blockData, fileUrl=$fileUrl, functions=$functions, name=$name, signature=$signature, signatureAge=$signatureAge, statistics=$statistics, ]'; } ModuleCoverage.fromJson(Map<String, dynamic> json) { if (json == null) return; if (json['blockCount'] == null) { blockCount = null; } else { blockCount = json['blockCount']; } if (json['blockData'] == null) { blockData = null; } else { blockData = (json['blockData'] as List).cast<String>(); } if (json['fileUrl'] == null) { fileUrl = null; } else { fileUrl = json['fileUrl']; } if (json['functions'] == null) { functions = null; } else { functions = FunctionCoverage.listFromJson(json['functions']); } if (json['name'] == null) { name = null; } else { name = json['name']; } if (json['signature'] == null) { signature = null; } else { signature = json['signature']; } if (json['signatureAge'] == null) { signatureAge = null; } else { signatureAge = json['signatureAge']; } if (json['statistics'] == null) { statistics = null; } else { statistics = CoverageStatistics.fromJson(json['statistics']); } } Map<String, dynamic> toJson() { Map <String, dynamic> json = {}; if (blockCount != null) json['blockCount'] = blockCount; if (blockData != null) json['blockData'] = blockData; if (fileUrl != null) json['fileUrl'] = fileUrl; if (functions != null) json['functions'] = functions; if (name != null) json['name'] = name; if (signature != null) json['signature'] = signature; if (signatureAge != null) json['signatureAge'] = signatureAge; if (statistics != null) json['statistics'] = statistics; return json; } static List<ModuleCoverage> listFromJson(List<dynamic> json) { return json == null ? List<ModuleCoverage>() : json.map((value) => ModuleCoverage.fromJson(value)).toList(); } static Map<String, ModuleCoverage> mapFromJson(Map<String, dynamic> json) { var map = Map<String, ModuleCoverage>(); if (json != null && json.isNotEmpty) { json.forEach((String key, dynamic value) => map[key] = ModuleCoverage.fromJson(value)); } return map; } }
26.67619
202
0.594788
2001e552c57a71b4955eee22b5ee4de2e09de43d
636
py
Python
DeepFilterNet/df/scripts/plot_spec.py
ishine/DeepFilterNet
797a02a20a10f4bc0c9af1c3bfa41bb0009342fc
[ "ECL-2.0", "Apache-2.0", "MIT" ]
null
null
null
DeepFilterNet/df/scripts/plot_spec.py
ishine/DeepFilterNet
797a02a20a10f4bc0c9af1c3bfa41bb0009342fc
[ "ECL-2.0", "Apache-2.0", "MIT" ]
5
2022-02-15T00:29:20.000Z
2022-03-18T13:07:57.000Z
DeepFilterNet/df/scripts/plot_spec.py
ishine/DeepFilterNet
797a02a20a10f4bc0c9af1c3bfa41bb0009342fc
[ "ECL-2.0", "Apache-2.0", "MIT" ]
null
null
null
import os import sys import torchaudio as ta from df.visualization import plt, spec_figure def main(path: str): audio, sr = ta.load(path) f = plt.figure(figsize=(10, 6)) f.set_tight_layout(True) spec_figure( audio, sr, colorbar=True, from_audio=True, figure=f, labels=True, colorbar_format="%+2.0f dB", cmap="inferno", n_fft=2048, hop=512, kHz=True, ) plt.savefig(os.path.splitext(path)[0] + ".pdf") if __name__ == "__main__": assert len(sys.argv) == 2 assert os.path.isfile(sys.argv[1]) main(sys.argv[1])
19.272727
51
0.577044
5aa9c29e2809d1d4bb473268b848463f2e16d122
2,260
dart
Dart
app_transito/lib/core/app_text_styles.dart
KoriCorporation/TrabalhoPraticoUNA-
ffcf955ebfd631b873761b48a66610c93babfc51
[ "MIT" ]
null
null
null
app_transito/lib/core/app_text_styles.dart
KoriCorporation/TrabalhoPraticoUNA-
ffcf955ebfd631b873761b48a66610c93babfc51
[ "MIT" ]
null
null
null
app_transito/lib/core/app_text_styles.dart
KoriCorporation/TrabalhoPraticoUNA-
ffcf955ebfd631b873761b48a66610c93babfc51
[ "MIT" ]
2
2021-04-15T14:02:09.000Z
2021-04-29T19:33:06.000Z
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'app_colors.dart'; class AppTextStyles { static final TextStyle titleBlue = GoogleFonts.roboto( color: AppColors.textBlue, fontSize: 56, fontWeight: FontWeight.w400, ); static final TextStyle titlerose = GoogleFonts.roboto( color: AppColors.titlerose, fontSize: 50, fontWeight: FontWeight.w400, ); static final TextStyle buttons = GoogleFonts.roboto( color: AppColors.titlerose, fontSize: 32, fontWeight: FontWeight.w400, ); static final TextStyle textPesquisa = GoogleFonts.roboto( color: AppColors.titlerose, fontSize: 22, fontWeight: FontWeight.w400, ); static final TextStyle titlePrimeiroSocorros = GoogleFonts.roboto( color: AppColors.textBlue, fontSize: 22, fontWeight: FontWeight.w700, ); static final TextStyle resultadoPositivo = GoogleFonts.roboto( color: AppColors.darkGreen, fontSize: 16, fontWeight: FontWeight.w700, ); static final TextStyle resultadoNegativo = GoogleFonts.roboto( color: AppColors.resultadoNegativo, fontSize: 16, fontWeight: FontWeight.w700, ); static final TextStyle body = GoogleFonts.notoSans( color: AppColors.grey, fontSize: 13, fontWeight: FontWeight.normal, ); static final TextStyle textPrimeirosSocorros = GoogleFonts.roboto( color: AppColors.textBlue, fontSize: 22, fontWeight: FontWeight.w400, ); static final TextStyle textSimuladotitle = GoogleFonts.roboto( color: AppColors.textBlue, fontSize: 18, fontWeight: FontWeight.w400, ); static final TextStyle textSimuladoquestao = GoogleFonts.roboto( color: AppColors.textBlue, fontSize: 16, fontWeight: FontWeight.w400, ); static final TextStyle textocategoria = GoogleFonts.roboto( color: AppColors.textBlue, fontSize: 30, fontWeight: FontWeight.w400, ); static final TextStyle titleSplash = GoogleFonts.roboto( color: AppColors.textBlueTitle, fontSize: 70, fontWeight: FontWeight.w400, ); static final TextStyle titleSplashSimulado = GoogleFonts.roboto( color: AppColors.textBlueTitle, fontSize: 75, fontWeight: FontWeight.w400, ); }
26.588235
68
0.722566
43ce301f66e34af8eb9f6f1b3f6806a5e6de208f
177
ts
TypeScript
web/src/utils/classNames.ts
Tocabi/clearcloud
972a796aec68755f66fdcf7cc39d5f77ca96f096
[ "MIT" ]
25
2021-07-24T07:06:42.000Z
2021-07-25T13:58:53.000Z
web/src/utils/classNames.ts
Tocabi/clearcloud
972a796aec68755f66fdcf7cc39d5f77ca96f096
[ "MIT" ]
62
2021-06-24T15:55:37.000Z
2021-07-24T16:06:34.000Z
web/src/utils/classNames.ts
keydrive/keydrive
972a796aec68755f66fdcf7cc39d5f77ca96f096
[ "MIT" ]
1
2021-07-24T15:43:52.000Z
2021-07-24T15:43:52.000Z
export type ClassName = string | undefined | false; export function classNames(...classList: ClassName[]): string { return classList.filter((c): boolean => !!c).join(' '); }
29.5
63
0.683616
85079edaf8e416ba217b2017ebe7c19ad6682234
1,019
cs
C#
NiftyPerforce/Commands/P4ShowItem.cs
ben-marsh/niftyplugins
191def49818942d8e41ca618716830d98949c02e
[ "MIT" ]
8
2016-01-05T10:44:57.000Z
2022-02-10T21:38:47.000Z
NiftyPerforce/Commands/P4ShowItem.cs
ben-marsh/niftyplugins
191def49818942d8e41ca618716830d98949c02e
[ "MIT" ]
null
null
null
NiftyPerforce/Commands/P4ShowItem.cs
ben-marsh/niftyplugins
191def49818942d8e41ca618716830d98949c02e
[ "MIT" ]
4
2015-10-11T16:31:31.000Z
2021-04-09T04:32:12.000Z
// Copyright (C) 2006-2010 Jim Tilander. See COPYING for and README for more details. using System; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio.CommandBars; namespace Aurora { namespace NiftyPerforce { class P4ShowItem : ItemCommandBase { public P4ShowItem(Plugin plugin) : base("ShowItem", plugin, "Shows the item in p4win", true, true) { } public override int IconIndex { get { return 8; } } public override bool RegisterGUI(Command vsCommand, CommandBar vsCommandbar, bool toolBarOnly) { if(toolBarOnly) { _RegisterGUIBar(vsCommand, vsCommandbar); } else { _RegisterGuiContext(vsCommand, "Project"); _RegisterGuiContext(vsCommand, "Item"); _RegisterGuiContext(vsCommand, "Easy MDI Document Window"); } return true; } public override void OnExecute(SelectedItem item, string fileName, OutputWindowPane pane) { P4Operations.P4WinShowFile(pane, fileName); } } } }
24.261905
98
0.675172
dfdd5a60160f8cea820b4dbd961e99ed4ac24a25
492
rb
Ruby
spec/spec_helper.rb
aptible/fridge
c40da8f5c89ac0f437624237f08f7e3b66ca0189
[ "MIT" ]
5
2015-04-27T22:43:23.000Z
2018-09-28T13:10:58.000Z
spec/spec_helper.rb
aptible/fridge
c40da8f5c89ac0f437624237f08f7e3b66ca0189
[ "MIT" ]
6
2015-04-01T15:00:23.000Z
2021-05-18T15:20:40.000Z
spec/spec_helper.rb
aptible/fridge
c40da8f5c89ac0f437624237f08f7e3b66ca0189
[ "MIT" ]
5
2016-02-24T14:48:20.000Z
2020-04-24T16:36:01.000Z
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'active_support/all' require 'action_controller' require 'action_dispatch' require 'action_view' require 'fridge' require 'fridge/rails_helpers' require 'rspec' require 'rspec/rails' # Load shared spec files Dir["#{File.dirname(__FILE__)}/shared/**/*.rb"].each do |file| require file end RSpec.configure do |config| config.before { Fridge.configuration.reset } end
21.391304
66
0.754065
a66c157b299632f2c4bee149596a4c8730812108
965
rb
Ruby
contracts/generators/secp256k1_sha3_sighash_all.rb
KellyShang/ckb-demo-ruby-sdk
449e291cf0460749c530b27a6fd218262de553a8
[ "MIT" ]
null
null
null
contracts/generators/secp256k1_sha3_sighash_all.rb
KellyShang/ckb-demo-ruby-sdk
449e291cf0460749c530b27a6fd218262de553a8
[ "MIT" ]
null
null
null
contracts/generators/secp256k1_sha3_sighash_all.rb
KellyShang/ckb-demo-ruby-sdk
449e291cf0460749c530b27a6fd218262de553a8
[ "MIT" ]
null
null
null
if ARGV.length < 1 raise "Not enough arguments!" end tx = CKB.load_tx sha3 = Sha3.new sha3.update(tx["version"].to_s) tx["deps"].each do |dep| sha3.update(dep["hash"]) sha3.update(dep["index"].to_s) end tx["inputs"].each do |input| sha3.update(input["hash"]) sha3.update(input["index"].to_s) sha3.update(input["unlock"]["version"].to_s) # First argument here is signature input["unlock"]["arguments"].drop(1).each do |argument| sha3.update(argument) end end tx["outputs"].each do |output| sha3.update(output["capacity"].to_s) sha3.update(output["lock"]) end hash = sha3.final def hex_to_bin(s) s.each_char.each_slice(2).map(&:join).map(&:hex).map(&:chr).join end def bin_to_hex(s) s.bytes.map { |b| b.to_s(16).rjust(2, "0") }.join end seckey = hex_to_bin(ARGV[0]) pubkey = Secp256k1.pubkey(seckey) CKB.debug "Pubkey: #{bin_to_hex(pubkey)}" signature = Secp256k1.sign(seckey, hash) CKB.debug "Signature: #{bin_to_hex(signature)}"
22.97619
66
0.688083
c6761e63ebd58102c6af6e3c3f9e9cce1afd4a2d
364
css
CSS
client/components/Header/Header.module.css
GTBitsOfGood/bgc-safety
1c7efc2149623cf62185a407f2b632d064da8264
[ "MIT" ]
7
2020-02-22T16:22:30.000Z
2021-07-29T16:22:41.000Z
client/components/Header/Header.module.css
GTBitsOfGood/bgc-safety
1c7efc2149623cf62185a407f2b632d064da8264
[ "MIT" ]
115
2020-02-10T22:41:31.000Z
2022-03-31T23:01:52.000Z
client/components/Header/Header.module.css
GTBitsOfGood/bgc-safety
1c7efc2149623cf62185a407f2b632d064da8264
[ "MIT" ]
null
null
null
.root { width: 100%; display: flex; flex-direction: row; justify-content: space-around; padding: 8px 4px; align-items: center; border-bottom: 1px solid rgba(128, 128, 128, 0.5); } .dropdown-menu select { display: none; } .printButton { background-color: #c4c4c4; border: none; padding: 16px 20px; text-align: center; font-size: 16px; }
16.545455
52
0.662088
502b070e8141cb579330440f5a9d8bdf9e2f9178
293
dart
Dart
app_client/lib/screens/index.dart
DonnC/food_app
e6100db9db185b95a5b39bed3e242ec2e27153b5
[ "MIT" ]
8
2021-02-06T21:19:02.000Z
2021-12-31T17:38:23.000Z
app_client/lib/screens/index.dart
wechulimaven/food_app
e6100db9db185b95a5b39bed3e242ec2e27153b5
[ "MIT" ]
null
null
null
app_client/lib/screens/index.dart
wechulimaven/food_app
e6100db9db185b95a5b39bed3e242ec2e27153b5
[ "MIT" ]
5
2021-02-06T21:19:35.000Z
2021-06-07T11:08:27.000Z
// export all screens files here export 'login_signup.dart'; export 'home_page.dart'; export 'start_page.dart'; export 'cart_page.dart'; export 'product_details.dart'; export 'favorites_page.dart'; export 'notification_page.dart'; export 'profile_page.dart'; export 'order_payment_page.dart';
26.636364
33
0.788396
e461328a5c25abd23385e8f01956ccb30851bd4e
5,814
rs
Rust
src/render.rs
Aofusa/gemspt-rs
58862f20eb29dbeb732a86edd347e8e5b26326eb
[ "Apache-2.0" ]
2
2018-02-25T11:31:58.000Z
2018-08-14T16:58:41.000Z
src/render.rs
Aofusa/gemspt-rs
58862f20eb29dbeb732a86edd347e8e5b26326eb
[ "Apache-2.0" ]
null
null
null
src/render.rs
Aofusa/gemspt-rs
58862f20eb29dbeb732a86edd347e8e5b26326eb
[ "Apache-2.0" ]
null
null
null
#![allow(dead_code, unused_variables)] use std; use std::sync::{Arc, Mutex}; use rayon::prelude::*; use radiance::radiance; use ppm::save_ppm_file; use random::Random; use vec::{Vec, Normalize, Cross}; use scene::Scene; use ray::Ray; macro_rules! clone_value { ($x:expr, $n:expr) => ({ let mut temp_vec = std::vec::Vec::new(); for _ in 0..$n { temp_vec.push($x); } temp_vec }) } pub fn render( scene: &Scene, filename: &str, width: i32, height: i32, num_sample_per_subpixel: i32, num_subpixel: i32, is_parallel: bool) { // カメラ位置。 let camera_position = Vec { x: 7.0, y: 3.0, z: 7.0 }; let camera_lookat = Vec { x: 0.0, y: 1.0, z: 0.0 }; let camera_dir = Vec::normalize(&camera_lookat - &camera_position); let camera_up = Vec { x: 0.0, y: 1.0, z: 0.0 }; // ワールド座標系でのイメージセンサーの大きさ。 let sensor_width = 30.0 * width as f64 / height as f64; // アスペクト比調整。 let sensor_height= 30.0; // イメージセンサーまでの距離。 let sensor_dist = 45.0; // イメージセンサーを張るベクトル。 let sensor_x_vec = Vec::normalize(Vec::cross(&camera_dir, &camera_up)) * &sensor_width; let sensor_y_vec = Vec::normalize(Vec::cross(&sensor_x_vec, &camera_dir)) * &sensor_height; let sensor_center = &camera_position + &camera_dir * &sensor_dist; let mut image = clone_value![Vec { x: 0.0, y: 0.0, z: 0.0 }, (width * height) as u64]; println!("{}x{} {} spp", width, height, num_sample_per_subpixel * (num_subpixel * num_subpixel)); // Rayonを使った並列処理 // 実装するために下の逐次処理版と一部ロジックが変わってしまった // 1. for 文から for_each メソッドへの変更 // 2. 1.に伴う 二重ループの除去 // 3. 1.に伴う image 配列へのアクセスロジックの変更 // 4. 進捗表示処理の追加と表示回数抑制のための if 文の追加 if is_parallel { let count = Arc::new(Mutex::new(0)); image.par_iter_mut().enumerate().for_each(|(i, pixel)| { // 進捗表示 { let mut count = count.lock().unwrap(); *count += 1; let count = *count; if count % width == 0 { eprint!("\rRendering (y= {}, {} %)\x1b[0K", count / width as i32, 100.0 * count as f64 / (width * height) as f64); } } let y = i as i32 / width; let x = i as i32 - y * width; let mut random = Random::new((y * width + x + 1) as u64); let image_index = height - y - 1; // num_subpixel x num_subpixel のスーパーサンプリング。 for sy in 0..num_subpixel { for sx in 0..num_subpixel { let mut accumulated_radiance = Vec { x: 0.0, y: 0.0, z: 0.0 }; // let accumulated_radiance: Vec; // 一つのサブピクセルあたりsamples回サンプリングする。 for _s in 0..num_sample_per_subpixel { let rate = 1.0 / num_subpixel as f64; let r1 = sx as f64 * rate + rate / 2.0; let r2 = sy as f64 * rate + rate / 2.0; // イメージセンサー上の位置。 let position_on_sensor = &sensor_center + &sensor_x_vec * ((r1 + x as f64) / width as f64 - 0.5) + &sensor_y_vec * ((r2 + image_index as f64) / height as f64 - 0.5); // レイを飛ばす方向。 let dir = Vec::normalize(&position_on_sensor - &camera_position); accumulated_radiance = accumulated_radiance + radiance(scene, &Ray::new(&camera_position, &dir), &mut random, &0) / num_sample_per_subpixel as f64 / (num_subpixel * num_subpixel) as f64; } *pixel = &*pixel + accumulated_radiance; } } }); eprintln!(""); } // 逐次処理 else { for y in 0..height { eprint!("\rRendering (y= {}, {} %)\x1b[0K", y, 100.0 * y as f64 / (height - 1) as f64); for x in 0..width { let mut random = Random::new((y * width + x + 1) as u64); let image_index = ((height - y - 1) * width + x) as usize; // num_subpixel x num_subpixel のスーパーサンプリング。 for sy in 0..num_subpixel { for sx in 0..num_subpixel { let mut accumulated_radiance = Vec { x: 0.0, y: 0.0, z: 0.0 }; // let accumulated_radiance: Vec; // 一つのサブピクセルあたりsamples回サンプリングする。 for _s in 0..num_sample_per_subpixel { let rate = 1.0 / num_subpixel as f64; let r1 = sx as f64 * rate + rate / 2.0; let r2 = sy as f64 * rate + rate / 2.0; // イメージセンサー上の位置。 let position_on_sensor = &sensor_center + &sensor_x_vec * ((r1 + x as f64) / width as f64 - 0.5) + &sensor_y_vec * ((r2 + y as f64) / height as f64 - 0.5); // レイを飛ばす方向。 let dir = Vec::normalize(&position_on_sensor - &camera_position); accumulated_radiance = accumulated_radiance + radiance(scene, &Ray::new(&camera_position, &dir), &mut random, &0) / num_sample_per_subpixel as f64 / (num_subpixel * num_subpixel) as f64; } image[image_index] = &image[image_index] + accumulated_radiance; } } } } eprintln!(""); } // 出力 save_ppm_file(filename, &image, width, height); }
41.234043
134
0.485208
050abd8582c9d281beef71b656b30969cd5cabfc
5,739
rs
Rust
molt/src/macros.rs
Twisol/molt
f7c601008a32b42934e790d132b6b2ac134e61da
[ "BSD-3-Clause" ]
52
2019-07-07T16:42:31.000Z
2022-02-10T03:24:47.000Z
molt/src/macros.rs
wduquette/gcl
f7c601008a32b42934e790d132b6b2ac134e61da
[ "BSD-3-Clause" ]
78
2019-01-21T17:00:34.000Z
2021-12-12T19:58:39.000Z
molt/src/macros.rs
wduquette/gcl
f7c601008a32b42934e790d132b6b2ac134e61da
[ "BSD-3-Clause" ]
9
2019-07-01T16:31:20.000Z
2021-09-06T08:12:49.000Z
//! Convenience Macros //! //! This module contains macros for use by command authors. /// Returns an `Ok` `MoltResult`. /// /// If called with no arguments, returns an empty value as the `Ok` result. /// If called with one argument, returns the argument as the `Ok` result, converting it /// to a value automatically. /// If called with two or more arguments, computes the `Ok` result using /// `format!()`; the first argument is naturally the format string. /// /// # Examples /// /// ``` /// use molt::*; /// /// // Return the empty result /// fn func1() -> MoltResult { /// // ... /// molt_ok!() /// } /// /// assert_eq!(func1(), Ok(Value::empty())); /// /// // Return an arbitrary value /// fn func2() -> MoltResult { /// // ... /// molt_ok!(17) /// } /// /// assert_eq!(func2(), Ok(17.into())); /// /// // Return a formatted value /// fn func3() -> MoltResult { /// // ... /// molt_ok!("The answer is {}", 17) /// } /// /// assert_eq!(func3(), Ok("The answer is 17".into())); /// ``` #[macro_export] macro_rules! molt_ok { () => ( Ok(Value::empty()) ); ($arg:expr) => ( Ok(Value::from($arg)) ); ($($arg:tt)*) => ( Ok(Value::from(format!($($arg)*))) ) } /// Returns an `Error` `MoltResult`. The error message is formatted /// as with `format!()`. /// /// If called with one argument, the single argument is used as the error message. /// If called with more than one argument, the first is a `format!()` format string, /// and the remainder are the values to format. /// /// This macro wraps the [`Exception::molt_err`](types/struct.Exception.html#method.molt_err) /// method. /// /// # Examples /// /// ``` /// use molt::*; /// /// // Return a simple error message /// fn err1() -> MoltResult { /// // ... /// molt_err!("error message") /// } /// /// let result = err1(); /// assert!(result.is_err()); /// /// let exception = result.err().unwrap(); /// assert!(exception.is_error()); /// assert_eq!(exception.value(), "error message".into()); /// /// // Return a formatted error /// fn err2() -> MoltResult { /// // ... /// molt_err!("invalid value: {}", 17) /// } /// /// let result = err2(); /// assert!(result.is_err()); /// /// let exception = result.err().unwrap(); /// assert!(exception.is_error()); /// assert_eq!(exception.value(), "invalid value: 17".into()); /// ``` #[macro_export] macro_rules! molt_err { ($arg:expr) => ( Err(Exception::molt_err(Value::from($arg))) ); ($($arg:tt)*) => ( Err(Exception::molt_err(Value::from(format!($($arg)*)))) ) } /// Returns an `Error` `MoltResult` with a specific error code. The error message is formatted /// as with `format!()`. /// /// The macro requires two or more arguments. The first argument is always the error code. /// If called with two arguments, the second is the error message. /// If called with more than two arguments, the second is a `format!()` format string and /// the remainder are the values to format. /// /// This macro wraps /// the [`Exception::molt_err2`](types/struct.Exception.html#method.molt_err2) /// method. /// /// # Examples /// /// ``` /// use molt::*; /// /// // Throw a simple error /// fn throw1() -> MoltResult { /// // ... /// molt_throw!("MYCODE", "error message") /// } /// /// let result = throw1(); /// assert!(result.is_err()); /// /// let exception = result.err().unwrap(); /// assert!(exception.is_error()); /// assert_eq!(exception.value(), "error message".into()); /// assert_eq!(exception.error_code(), "MYCODE".into()); /// /// // Return a formatted error /// fn throw2() -> MoltResult { /// // ... /// molt_throw!("MYCODE", "invalid value: {}", 17) /// } /// /// let result = throw2(); /// assert!(result.is_err()); /// /// let exception = result.err().unwrap(); /// assert!(exception.is_error()); /// assert_eq!(exception.value(), "invalid value: 17".into()); /// assert_eq!(exception.error_code(), "MYCODE".into()); /// ``` #[macro_export] macro_rules! molt_throw { ($code:expr, $msg:expr) => ( Err(Exception::molt_err2(Value::from($code), Value::from($msg))) ); ($code:expr, $($arg:tt)*) => ( Err(Exception::molt_err2(Value::from($code), Value::from(format!($($arg)*)))) ) } #[cfg(test)] mod tests { use crate::*; #[test] fn test_molt_ok() { let result: MoltResult = molt_ok!(); assert_eq!(Ok(Value::empty()), result); let result: MoltResult = molt_ok!(5); assert_eq!(Ok(Value::from(5)), result); let result: MoltResult = molt_ok!("Five"); assert_eq!(Ok(Value::from("Five")), result); let result: MoltResult = molt_ok!("The answer is {}.", 5); assert_eq!(Ok(Value::from("The answer is 5.")), result); } #[test] fn test_molt_err() { check_err(molt_err!("error message"), "error message"); check_err(molt_err!("error {}", 5), "error 5"); } #[test] fn test_molt_throw() { check_throw( molt_throw!("MYERR", "error message"), "MYERR", "error message", ); check_throw(molt_throw!("MYERR", "error {}", 5), "MYERR", "error 5"); } fn check_err(result: MoltResult, msg: &str) -> bool { match result { Err(exception) => exception.is_error() && exception.value() == msg.into(), _ => false, } } fn check_throw(result: MoltResult, code: &str, msg: &str) -> bool { match result { Err(exception) => { exception.is_error() && exception.value() == msg.into() && exception.error_code() == code.into() } _ => false, } } }
26.817757
95
0.556717
06c472dff48bfef9805779d58dd3ff284ecc38ff
6,659
py
Python
blockchain/main/api/views.py
alexporcar/ASCIIcoin
d9d0da1a6dbb8a19c3f0e2a5598c72b8910924f6
[ "MIT" ]
1
2021-08-01T17:16:26.000Z
2021-08-01T17:16:26.000Z
blockchain/main/api/views.py
alexporcar/ASCIIcoin
d9d0da1a6dbb8a19c3f0e2a5598c72b8910924f6
[ "MIT" ]
null
null
null
blockchain/main/api/views.py
alexporcar/ASCIIcoin
d9d0da1a6dbb8a19c3f0e2a5598c72b8910924f6
[ "MIT" ]
null
null
null
from django.db.models import F from django.http import HttpResponse from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from main.models import Transaction, Mempool, Block_header, Block_transaction, Node from main.api.serializers import TransactionSerializer, MempoolSerializer, Block_headerSerializer, NodeSerializer, ChainSerializer from datetime import datetime import requests @api_view(['GET', 'POST']) def nodes(request): if request.method == 'GET': nodes = Node.objects.all() serializer = NodeSerializer(nodes, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = NodeSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET', 'DELETE']) def node(request, ip_address): try: node = Node.objects.get(ip_address=ip_address) except: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = NodeSerializer(node) return Response(serializer.data) elif request.method == 'DELETE': node.delete() return Response(status=status.HTTP_204_NO_CONTENT) @api_view(['GET', 'POST']) def chain(request): if request.method == 'GET': blocks = Block_header.objects.all() serializer = Block_headerSerializer(blocks, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = ChainSerializer(data=request.data) if serializer.is_valid(): if len(Block_header.objects.filter(block_hash=request.data['block_hash'])) == 0: if serializer.create(request.data): # sharing the block with the rest of nodes for node in Node.objects.all(): try: url = f'http://{node.ip_address}:{node.port}/api/store_block/' data = { 'block_hash': request.data['block_hash'], 'height': int(request.data['height']), 'nonce': int(request.data['nonce']), 'timestamp': datetime.strptime(request.data['timestamp'], "%Y-%m-%d %H:%M:%S.%f"), 'previous_hash': request.data['previous_hash'], 'merkle_root': request.data['merkle_root'], 'transactions': request.data['transactions'], } r = requests.post(url, data=data, timeout=1) # we don't need to check the status code received except: pass # ignore the node return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['POST']) def store_block(request): if request.method == 'POST': serializer = ChainSerializer(data=request.data) if serializer.is_valid(): if len(Block_header.objects.filter(block_hash=request.data['block_hash'])) == 0: if serializer.create(request.data): return Response(serializer.data, status=status.HTTP_201_CREATED) else: return HttpResponse(status=418) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['POST']) def store_transaction(request): if request.method == 'POST': serializer = TransactionSerializer(data=request.data) if serializer.is_valid(): if len(Transaction.objects.filter(tx_hash=request.data['tx_hash'])) == 0: if serializer.create(request.data): return Response(serializer.data, status=status.HTTP_201_CREATED) else: return HttpResponse(status=418) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['GET']) def last_block(request): try: block = Block_header.objects.all().order_by('-height')[0] except: return Response(status=status.HTTP_404_NOT_FOUND) serializer = Block_headerSerializer(block) return Response(serializer.data) @api_view(['GET']) def block(request, block_hash): try: block = Block_header.objects.get(block_hash=block_hash) except: return Response(status=status.HTTP_404_NOT_FOUND) serializer = Block_headerSerializer(block) return Response(serializer.data) @api_view(['GET']) def tx(request, tx_hash): try: tx = Transaction.objects.get(tx_hash=tx_hash) except: return Response(status=status.HTTP_404_NOT_FOUND) serializer = TransactionSerializer(tx) return Response(serializer.data) @api_view(['GET']) def tx_block(request, block_hash): try: tx = Block_transaction.objects.filter(block_hash=block_hash).order_by('index').values('tx_hash', sender=F('tx_hash__sender'), receiver=F('tx_hash__receiver'), amount=F('tx_hash__amount'), fee=F('tx_hash__fee'), sender_public_key=F('tx_hash__sender_public_key'), timestamp=F('tx_hash__timestamp'), signature=F('tx_hash__signature')) except: return Response(status=status.HTTP_404_NOT_FOUND) serializer = TransactionSerializer(tx, many=True) return Response(serializer.data) @api_view(['GET']) def tx_address(request, address): tx = Transaction.objects.filter(sender=address) serializer = TransactionSerializer(tx, many=True) return Response(serializer.data) @api_view(['GET']) def mempool(request): Mempool.objects.check_mempool() tx = Mempool.objects.all().order_by('-fee', '-timestamp') serializer = MempoolSerializer(tx, many=True) return Response(serializer.data) @api_view(['POST']) def coinbase_tx(request): tx = Transaction.objects.create_coinbase_tx(request.data['address']) if tx == False: return Response('An error ocurred') serializer = TransactionSerializer(tx) return Response(serializer.data) @api_view(['POST']) def fee_tx(request): tx = Transaction.objects.create_fee_tx(request.data['address'], float(request.data['total_fee'])) if tx == False: return Response('An error ocurred') serializer = TransactionSerializer(tx) return Response(serializer.data)
40.852761
339
0.646343
0370ece77558b8cbeec3aae88f9374d885d54e7d
5,737
dart
Dart
lib/app/router/router_utils.dart
yichengzou/FlutterUnit
3dedd8587aff09bb81482195f96a356a41ce1b51
[ "MIT" ]
1
2020-12-05T07:20:14.000Z
2020-12-05T07:20:14.000Z
lib/app/router/router_utils.dart
Jiabaokang/FlutterUnit
2cc5dad887a1f4b0604e75aebde5534ff1124c01
[ "MIT" ]
null
null
null
lib/app/router/router_utils.dart
Jiabaokang/FlutterUnit
2cc5dad887a1f4b0604e75aebde5534ff1124c01
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; //缩放路由动画 class ScaleRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; ScaleRouter({required this.child, this.durationMs = 500,this.curve=Curves.fastOutSlowIn}) : super( pageBuilder: (context, animation, secondaryAnimation) => child, transitionDuration: Duration(milliseconds: durationMs), transitionsBuilder: (context, a1, a2, child) => ScaleTransition( scale: Tween(begin: 0.0, end: 1.0).animate( CurvedAnimation(parent: a1, curve: curve)), child: child, ), ); } //渐变透明路由动画 class FadeRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; FadeRouter({required this.child, this.durationMs = 500,this.curve=Curves.fastOutSlowIn}) : super( pageBuilder: (context, animation, secondaryAnimation) => child, transitionDuration: Duration(milliseconds: durationMs), transitionsBuilder: (context, a1, a2, child) => FadeTransition( opacity: Tween(begin: 0.1, end: 1.0).animate( CurvedAnimation(parent: a1, curve:curve,)), child: child, )); } //旋转路由动画 class RotateRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; RotateRouter({required this.child, this.durationMs = 500,this.curve=Curves.fastOutSlowIn}) : super( pageBuilder: (context, animation, secondaryAnimation) => child, transitionDuration: Duration(milliseconds: durationMs), transitionsBuilder: (context, a1, a2, child) => RotationTransition( turns: Tween(begin: 0.1, end: 1.0).animate( CurvedAnimation(parent: a1, curve:curve,)), child: child, )); } //右--->左 class Right2LeftRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; Right2LeftRouter({required this.child,this.durationMs=500,this.curve=Curves.fastOutSlowIn}) :super( transitionDuration:Duration(milliseconds: durationMs), pageBuilder:(ctx,a1,a2)=>child, transitionsBuilder:(ctx,a1,a2, child,) => SlideTransition( child: child, position: Tween<Offset>( begin: Offset(1.0, 0.0), end: Offset(0.0, 0.0),).animate( CurvedAnimation(parent: a1, curve: curve)), )); } //左--->右 class Left2RightRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; Left2RightRouter({required this.child,this.durationMs=500,this.curve=Curves.fastOutSlowIn}) :assert(true),super( transitionDuration:Duration(milliseconds: durationMs), pageBuilder:(ctx,a1,a2){return child;}, transitionsBuilder:(ctx,a1,a2,child,) { return SlideTransition( position: Tween<Offset>( begin: Offset(-1.0, 0.0), end: Offset(0.0, 0.0),).animate( CurvedAnimation(parent: a1, curve: curve)), child: child ); }); } //上--->下 class Top2BottomRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; Top2BottomRouter({required this.child,this.durationMs=500,this.curve=Curves.fastOutSlowIn}) :super( transitionDuration:Duration(milliseconds: durationMs), pageBuilder:(ctx,a1,a2){return child;}, transitionsBuilder:(ctx,a1,a2, child,) { return SlideTransition( position: Tween<Offset>( begin: Offset(0.0,-1.0), end: Offset(0.0, 0.0),).animate( CurvedAnimation(parent: a1, curve: curve)), child: child ); }); } //下--->上 class Bottom2TopRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; Bottom2TopRouter({required this.child,this.durationMs=500,this.curve=Curves.fastOutSlowIn}) :super( transitionDuration:Duration(milliseconds: durationMs), pageBuilder:(ctx,a1,a2)=> child, transitionsBuilder:(ctx,a1,a2, child,) { return SlideTransition( position: Tween<Offset>( begin: Offset(0.0, 1.0), end: Offset(0.0, 0.0),).animate( CurvedAnimation(parent: a1, curve: curve)), child: child ); }); } //缩放+透明+旋转路由动画 class ScaleFadeRotateRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; ScaleFadeRotateRouter({required this.child, this.durationMs = 1000,this.curve=Curves.fastOutSlowIn}) : super( transitionDuration: Duration(milliseconds: durationMs), pageBuilder: (ctx, a1, a2)=>child,//页面 transitionsBuilder: (ctx, a1, a2, Widget child,) => RotationTransition(//旋转动画 turns: Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation( parent: a1, curve: curve, )), child: ScaleTransition(//缩放动画 scale: Tween(begin: 0.0, end: 1.0).animate( CurvedAnimation(parent: a1, curve: curve)), child: FadeTransition(opacity://透明度动画 Tween(begin: 0.5, end: 1.0).animate(CurvedAnimation(parent: a1, curve: curve)), child: child,), ), )); } //无动画 class NoAnimRouter<T> extends PageRouteBuilder<T> { final Widget child; NoAnimRouter({required this.child}) : super( opaque: false, pageBuilder: (context, animation, secondaryAnimation) => child, transitionDuration: Duration(milliseconds: 0), transitionsBuilder: (context, animation, secondaryAnimation, child) => child); }
34.981707
111
0.638313
7569c7415aa46af724e3ee5c926e2efdecd7f299
1,733
css
CSS
public/assets/css/reports/expense_bill.css
lucasmb/consorcia-2
72c9dcde9b156553cd9f9ecddf04eb6734407be6
[ "MIT" ]
null
null
null
public/assets/css/reports/expense_bill.css
lucasmb/consorcia-2
72c9dcde9b156553cd9f9ecddf04eb6734407be6
[ "MIT" ]
null
null
null
public/assets/css/reports/expense_bill.css
lucasmb/consorcia-2
72c9dcde9b156553cd9f9ecddf04eb6734407be6
[ "MIT" ]
null
null
null
.page{ height: 670px; } .left_column{ font: 9pt 'trebuchet ms',arial,sans-serif; float: left; width: 48%; } .right_column{ font: 9pt 'trebuchet ms',arial,sans-serif; width:48%; padding-left: 5px; margin-left: 1%; float: left; } .original_left{ height: 335px; } .original_right{ height: 335px; } .duplicate_left{ height: 335px; } .duplicate_right{ height: 338px; } .title{ font: 9pt 'trebuchet ms',arial,sans-serif; text-align: center; width: 100%; border: solid 1px #000; } .title div{ display: inline-block; } .title_bill_type{ margin-bottom: 5px; } .title_bill_id{ margin-right: 12px; margin-bottom: 2px; margin-top: 4px; } .title_center{ margin-top: 4px; margin-left: 5%; width: 50%; } .title_right{ width: 44%; margin-right: 0; } .content{ margin: 5px 0 0 25px; } .table_properties{ border-spacing:0px; font: 8pt 'trebuchet ms',arial,sans-serif; margin: 0 0% 0% 0% ; width: 95%; } .import{ text-align: right; } .table_owner{ font: 8pt 'trebuchet ms',arial,sans-serif; margin: 0 1px 0 1px; width: 100%; } .table_properties th{ color: #FFF; background: #322A27 url(../../img/home/header_table.jpg); } hr { display: block; height: 1px; border: 0; border-top: 1px solid #322A27; margin: 0.5em 0; padding: 0; } .sign{ width: 30%; text-align: center; margin: 0.5% 0 0 50%; margin-top: 20px; border-top: 1px solid #322A27; font: 9pt 'trebuchet ms',arial,sans-serif; } .footer{ text-align: left; margin: 0% 0 0 0; font: 8pt 'trebuchet ms',arial,sans-serif; float: bottom; } #owner{ width: 285px; }
14.686441
61
0.599538
5b59bc065ddaf6b2f77e136fde93a5d7427f5956
538
sql
SQL
tests/queries/0_stateless/01455_optimize_trivial_insert_select.sql
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
15,577
2019-09-23T11:57:53.000Z
2022-03-31T18:21:48.000Z
tests/queries/0_stateless/01455_optimize_trivial_insert_select.sql
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
16,476
2019-09-23T11:47:00.000Z
2022-03-31T23:06:01.000Z
tests/queries/0_stateless/01455_optimize_trivial_insert_select.sql
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
3,633
2019-09-23T12:18:28.000Z
2022-03-31T15:55:48.000Z
SET max_insert_threads = 1, max_threads = 100, min_insert_block_size_rows = 1048576, max_block_size = 65536; DROP TABLE IF EXISTS t; CREATE TABLE t (x UInt64) ENGINE = StripeLog; -- For trivial INSERT SELECT, max_threads is lowered to max_insert_threads and max_block_size is changed to min_insert_block_size_rows. INSERT INTO t SELECT * FROM numbers_mt(1000000); SET max_threads = 1; -- If data was inserted by more threads, we will probably see data out of order. SELECT DISTINCT blockSize(), runningDifference(x) FROM t; DROP TABLE t;
53.8
135
0.791822
58bae816f9fecf67987dc408c2e074833999fcaf
18,899
css
CSS
css/first.css
dreamingodd/ykcoin.top
8d77aa4bac15d742ce0e3681abb337381f4d4cae
[ "MIT" ]
1
2020-09-26T03:22:27.000Z
2020-09-26T03:22:27.000Z
www/yimian.xyz/public_html/css/first.css
IoTcat/ushio-cn
8eaa890e0e5af3afe2db212becf6a61eb5ce84fa
[ "Apache-2.0" ]
3
2020-06-11T09:20:06.000Z
2020-06-11T09:30:51.000Z
www/yimian.xyz/public_html/css/first.css
IoTcat/ushio-cn
8eaa890e0e5af3afe2db212becf6a61eb5ce84fa
[ "Apache-2.0" ]
null
null
null
@charset "utf-8"; /* font */ @font-face { font-family: "Segoe UI Light"; src: url("../fonts/segoeuil.eot"); /* IE9 Compat Modes */ src:local("Segoe UI Light"), url("../fonts/segoeuil.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */ url("../fonts/segoeuil.woff") format("woff"), /* Modern Browsers */ url("../fonts/segoeuil.ttf") format("truetype"), /* Safari, Android, iOS */ url("../fonts/segoeuil.svg#LandyThanks") format("svg"); /* Legacy iOS */ font-weight:normal; font-style:normal; } /* reset */ * {padding:0;margin:0;-webkit-text-size-adjust:none;} img {border:0} select,input {font-family:"Microsoft YaHei", "微软雅黑", Tahoma, Verdana, Arial; font-size:12px;} ul,ol {display:block;list-style:none;} h1,h2,h3,h4,h5,h6 {display:block;} p {display:block;} a {text-decoration:none;} a:hover {text-decoration:none;} em {font-style:normal;} button {font-family:"Microsoft YaHei", "微软雅黑", Tahoma, Verdana, Arial; font-weight:normal;} :focus {outline: 0;} .clearfix {zoom:1} .clearfix:after { content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0; } .clear {clear:both;} /* header body {background:url("../images/common/bg.gif") repeat-x 0 100px;} header {width:100%; height:100px; background:url("../images/common/header_pc_bg.gif") repeat-x 0 0 #fff; box-shadow:0px 2px 4px #777; z-index:100;position:relative;} * */ #gnb_mobile {display:none;} #gnb_pc {display:block; width:960px; height:100px; margin:0 auto; } #gnb_pc h1 {float:left; text-indent:-9999px;width:123px; height:100px; background:url("../images/common/header_pc_logo.jpg") no-repeat 0 0; margin:0 33px 0 0;} #gnb_pc h1 a {width:123px;height:100px; display:block;} #gnb_pc ul {float:left; width:793px; height:100px; background:url("../images/common/header_pc_gnb.gif") no-repeat 0 0;} #gnb_pc ul li {float:left; text-align:left; margin:0 0 0 39px;height:100px; } #gnb_pc ul li a {display:block; line-height:100px; font-size:14px; color:#000;} #gnb_pc_submenu {display:block; position:absolute; top:100px; width:100%; height:59px; background:url("../images/common/header_gnb_submenu_bg.gif") repeat-x 0 0 #efefef;overflow:hidden; height:0px;box-shadow:0px 2px 4px #777;} #gnb_pc_submenu article {width:960px; height:59px; margin:0 auto;} #gnb_pc_submenu table {height:59px; border:0; border-collapse:collapse;} #gnb_pc_submenu table td {border-left: solid 1px #e0e0e0; border-right:solid 1px #e0e0e0;} #gnb_pc_submenu table td a {display:block; height:59px; padding:0px 27px; font-size:14px; color:#000; text-shadow:0px 2px 1px #fff; line-height:59px;} #gnb_pc_submenu table td a:hover {background:url("../images/common/header_gnb_submenu_item_bg") repeat-x 0 0 #ebebeb;} #gnb_pc_submenu1 {margin:0 0 0 150px;} #gnb_pc_submenu2 {margin:0 0 0 300px;} #gnb_pc_submenu3 {margin:0 0 0 300px;} #gnb_pc_submenu4 {margin:0 0 0 200px;} #gnb_pc_submenu5 {margin:0 0 0 550px;} #gnb_pc_submenu6 {margin:0 0 0 550px;} #gnb_pc_submenu7 {margin:0 0 0 380px;} #gnb_mobile_submenu {display:none;} /* footer */ footer {height:382px; width:100%; background:url("../images/common/footer_bg.gif") repeat-x 0 0 #fff; margin:0;} footer article {width:960px; height:100%; margin:0 auto; background:url("../images/common/footer_line.gif") repeat-x 0 0 #fff; overflow:hidden;} footer article dl {float:left; width:137px; display:block;} footer article dl dt {padding:11px 0 0 0; color:#666; font-size:14px;} footer article dl dt a {color:#666; font-size:14px; width: auto; height:auto; line-height:62px; text-align:left; margin:0; background:none;text-indent:8px;display:block;} footer article dl dd {display:block;} footer article dl dd li {line-height:25px;padding:0 0 0 8px; display:block;background:url("../images/common/footer_dot.gif") no-repeat 0px center;} footer article dl dd a {line-height:25px; font-size:12px; color:#b0b0b0;} footer article dl dd a:hover {color:#666;} footer p {clear:both; text-align:center; font-size:10px; color:#7a7a7a; margin:30px 0 0 0; line-height:20px;} footer ol {clear:both; display:block; margin:40px auto 20px auto; width:300px;} footer ol a {color:#000;} footer ol li#footer_weibo {height:22px; float:left; width:120px; background:url("../images/common/sina.png") no-repeat 0 0 #fff;padding:0 0 0 30px; line-height:22px; font-size:12px;} footer ol li#footer_wechat {height:22px; float:left; width:120px; background:url("../images/common/wechat.png") no-repeat 0 0 #fff;padding:0 0 0 30px; line-height:22px; font-size:12px;} /* animation */ @-webkit-keyframes kv_ani1 { 0% {-webkit-transform: translate(-300px,0px); opacity:0;} 100% {-webkit-transform: translate(0px,0px); opacity:1;} } @-webkit-keyframes kv_ani2 { 0% {-webkit-transform: translate(300px,0px);opacity:0;} 100% {-webkit-transform: translate(0px,0px); opacity:1;} } @-webkit-keyframes kv_ani3 { 0% { opacity:0;} 100% {opacity:1;} } @-ms-keyframes kv_ani1 { 0% {-ms-transform: translate(-300px,0px); opacity:0;} 100% {-ms-transform: translate(0px,0px); opacity:1;} } @-ms-keyframes kv_ani2 { 0% {-ms-transform: translate(300px,0px);opacity:0;} 100% {-ms-transform: translate(0px,0px); opacity:1;} } @-ms-keyframes kv_ani3 { 0% { opacity:0;} 100% {opacity:1;} } @keyframes kv_ani1 { 0% {transform: translate(-300px,0px); opacity:0;} 100% {transform: translate(0px,0px); opacity:1;} } @keyframes kv_ani2 { 0% {transform: translate(300px,0px);opacity:0;} 100% {transform: translate(0px,0px); opacity:1;} } @keyframes kv_ani3 { 0% { opacity:0;} 100% {opacity:1;} } @keyframes main_aniwheel { 0% {transform: rotate(0deg);} 100% {transform: rotate(360deg);} } @-ms-keyframes main_aniwheel { 0% {-ms-transform: rotate(0deg);} 100% {-ms-transform: rotate(360deg);} } @-webkit-keyframes main_aniwheel { 0% {-webkit-transform: rotate(0deg);} 100% {-webkit-transform: rotate(360deg);} } @keyframes main_anilogo { 0% {transform: scale(0.8);} 50% {transform: scale(1.0);} 100% {transform: scale(0.8);} } @-ms-keyframes main_anilogo { 0% {-ms-transform: scale(0.8);} 50% {-ms-transform: scale(1.0);} 100% {-ms-transform: scale(0.8);} } @-webkit-keyframes main_anilogo { 0% {-webkit-transform: scale(0.8);} 50% {-webkit-transform: scale(1.0);} 100% {-webkit-transform: scale(0.8);} } /* - mouse wheel - */ @keyframes mousewheel_ani { 0% {opacity:0;} 50% {opacity:1;} 100% {opacity:0;} } @-webkit-keyframes mousewheel_ani { 0% {opacity:0;} 50% {opacity:1;} 100% {opacity:0;} } @-ms-keyframes mousewheel_ani { 0% {opacity:0;} 50% {opacity:1;} 100% {opacity:0;} } /* main */ html,body {width:100%; overflow-x:hidden;} #main_content {width:960px;margin:0 auto; padding:0 0 100px 0;} .kv_index_main {width:100%; height:535px;background-size:auto 535px; -webkit-animation: kv_ani3 2s ease; -ms-animation: kv_ani3 2s ease; animation:kv_ani3 2s ease; overflow:hidden;} .kv_index_main strong {line-height:94px; font-weight:normal; width:100%; text-align:center; font-size:72px;padding:190px 0 0 0; color:#000; display:block; -webkit-animation: kv_ani1 2s ease; -ms-animation: kv_ani1 2s ease; animation:kv_ani1 2s ease;} .kv_index_main em {line-height:62px; font-weight:normal; width:100%; text-align:center; font-size:60px;color:#000; display:block; font-family: "Segoe UI Light"; -webkit-animation: kv_ani2 2s ease; -ms-animation: kv_ani2 2s ease; animation:kv_ani2 2s ease;} #kv_index_main1 { background:url("../images/main/kv_main1.jpg") no-repeat top center; } #kv_index_main2 { background:url("../images/main/kv_main2.jpg") no-repeat top center; } #kv_index_main3 { background:url("../images/main/kv_main3.jpg") no-repeat top center; } #kv_index_main4 { background:url("../images/main/kv_main4.jpg") no-repeat top center; } #kv_index_main5 { background:url("../images/main/kv_main5.jpg") no-repeat top center; } #kv_index_main6 { background:url("../images/main/kv_main6.jpg") no-repeat top center; } #kv_index_main7 { background:url("../images/main/kv_main7.jpg") no-repeat top center; } #kv_index_main8 { background:url("../images/main/kv_main8.jpg") no-repeat top center; } #kv_index_main9 { background:url("../images/main/kv_main9.jpg") no-repeat top center; } #kv_index_main2 strong {display:none;} #kv_index_main2 em {display:none;} #kv_index_main3 strong {display:none;} #kv_index_main3 em {display:none;} #main_icon {width:960px;} #main_icon li {float:left; width:320px; height:470px; overflow:hidden;} #main_icon li h2 {height:311px; font-size:30px; text-align:center; line-height:560px; font-weight:normal; text-indent:0;} #main_icon li h2 a {width:320px; height:311px; display:block;} #main_icon li p {display:block;font-size:14px; line-height:30px; color:#000; padding:0 16px 0 16px; text-indent:2em;} #main_icon_section1 {background:url("../images/main/main_icon1.gif") no-repeat top center;} #main_icon_section1 h2 a, #main_icon_section1 h2 a:hover {color:#784acb;} #main_icon_section2 {background:url("../images/main/main_icon2.gif") no-repeat top center;} #main_icon_section2 h2 a, #main_icon_section2 h2 a:hover {color:#00c3ce;} #main_icon_section3 {background:url("../images/main/main_icon3.gif") no-repeat top center;} #main_icon_section3 h2 a, #main_icon_section3 h2 a:hover {color:#00a8ce;} .main_desc {width:320px; float:left; height:369px;} .main_desc li {padding:0 16px 0 16px; margin:0 0 15px 0;} .main_desc li a {font-size:14px; line-height:25px; color:#666; } .main_desc li a:hover {color:#000;} #main_desc1 {list-style-image:url("../images/main/main_list_dot1.gif"); list-style-position:inside; list-style-type: square;} #main_desc2 {list-style-image:url("../images/main/main_list_dot2.gif"); list-style-position:inside; list-style-type: square;} #main_desc3 {list-style-image:url("../images/main/main_list_dot3.gif"); list-style-position:inside; list-style-type: square;} #main_case {clear:both; margin:50px 0 50px 0; background:none;} #main_case h2 {font-size:30px; line-height:60px; color:#666; font-weight:normal; text-align:center;} #main_case p {font-size:14px; color:#666; text-align:center; display:block; padding:0 0 30px 0; line-height:20px;} #main_case dl {width:311px; height:311px; float:left; overflow:hidden; position:relative; margin:0 12px 12px 0; box-shadow:0px 0px 6px #999; left:0;} #main_case dd img {width:311px; height:311px;position:relative;top:-30px;} #main_case dt {display:block; width:311px; height:60px; line-height:60px; text-align:center; position:absolute; left:0; bottom:0; background-color:#7f7f7f; color:#fff; font-size:18px;} #main_case dt a {color:#fff;} #main_case dl.last {margin-right:0 !important;} #main_case dl.last_mobile {margin-right:12px;} #main_case dl.hide {display:block;} #main_mousewheel {z-index:9999;position:absolute; left:50%; margin-left:-35px; bottom:60px; -webkit-animation: mousewheel_ani 2s linear infinite; -ms-animation: mousewheel_ani 2s linear infinite; animation:mousewheel_ani 2s linear infinite;} /* animation area - desktop version */ #main_sections {} #main_section1 {width:100%; height:786px; background:url("../images/main/section1_bg.gif") no-repeat center top; overflow:hidden;} #main_section2 {width:100%; height:567px; background:url("../images/main/section2_bg.png") no-repeat center top; overflow:hidden;transform-origin:0 0;-webkit-transform-origin:0 0;-ms-transform-origin:0 0;} #main_section3 {width:100%; height:769px; background:url("../images/main/section3_bg.jpg") no-repeat center top; margin:0px 0 0 0;} #main_section4 {width:100%; height:506px; background:url("../images/main/section4_bg.png") no-repeat center top; overflow:hidden;} #main_section5 {width:100%; height:1208px; background:url("../images/main/section5_bg.jpg") no-repeat center top; overflow:hidden;} #main_section6 {width:100%; height:500px; background:url("../images/main/section6_bg.jpg") no-repeat center top; overflow:hidden;} #main_section1 section {width:960px; margin:0 auto; height:100%;position:relative;} #main_section2 section {width:960px; margin:0 auto; height:100%;} #main_section3 section {width:960px; margin:0 auto; height:100%;position:relative;} #main_section4 section {width:960px; margin:0 auto; height:100%;} #main_section5 section {width:960px; margin:0 auto; height:100%;position:relative;} #main_section6 section {width:960px; margin:0 auto; height:100%;} /* section 1 */ #main_section1 div {width:960px; height:128px; padding:29px 0 0 0;z-index:9999;} #main_section1 div h2 {color:#000; font-weight:normal; font-size:50px; line-height:72px;text-align:right;} #main_section1 div h3 {color:#000; font-weight:normal; font-size:28px; line-height:36px;text-align:right; font-weight:normal;} #main_section1 div img {margin:0 0 0 21px;} #main_section1 h4 {font-size:30px;color:#000;} #main_section1 h4 span {font-size:16px; color:#000; display:block; line-height:25px;} #main_section1 p {font-size:14px; color:#000; line-height:24px; font-weight:bold;} #main_section1_control1 {position:absolute;top:133px;left:0;} #main_section1_control2 {position:absolute;top:189px;left:357px;text-align:left;} #main_section1_control3 {position:absolute;top:298px;left:357px;text-align:left;} #main_section1_control4 {position:absolute;top:387px;right:0;} #main_section1_control5 {position:absolute;top:441px;left:0;text-align:right; width:600px;} #main_section1_control6 {position:absolute;top:573px;left:0;text-align:right; width:600px;} /* section 2 */ #main_section2 p {padding:200px 70px 0 70px; color:#fff; font-size:48px; line-height:65px; text-align:center;} /* section 3 */ #main_section3 h3 {position:relative;padding:44px 0 0 0; font-size:30px; line-height:40px; text-align:center;font-weight:normal;z-index:150; color:#000; transform-origin:center center;-webkit-transform-origin:center center;-ms-transform-origin:center center;} #main_section3 div#main_section3_chart {width:960px; height:769px; overflow:hidden;position:absolute; top:0; left:0; z-index:100; background:url("../images/main/section3_chart.jpg") no-repeat top center;} #main_section3 div#main_section3_bar {position:absolute; bottom:300px; left: 158px; z-index:200; width:644px; } #main_section3_bar1 {width: 644px; height:70px; line-height:70px; overflow:hidden; background:url("../images/main/section3_bar1.png") no-repeat 0 0; z-index:200;} #main_section3_bar1 span {display:block; width:435px; height:70px; font-size:18px; color:#fff; text-align:center; float:left; margin:0 0 0 70px;} #main_section3_bar1 em {font-size:30px; display:block; width:69px; height:70px; float:left; color:#fff;} #main_section3_bar2 {width: 644px; height:70px; line-height:70px; overflow:hidden; background:url("../images/main/section3_bar2.png") no-repeat 0 0; z-index:200;} #main_section3_bar2 span {display:block; width:435px; height:70px; font-size:18px; color:#fff; text-align:center; float:right; margin:0 70px 0 0;} #main_section3_bar2 em {font-size:30px; display:block; width:69px; height:70px; float:right; color:#fff; } /* section 4 */ #main_section4 section {padding:90px 0 0 0; transform-origin:top center;-webkit-transform-origin:top center;-ms-transform-origin:top center;} #main_section4 section h3 {text-align:center; font-weight:normal; color:#fff; font-size:35px; line-height:85px;} #main_section4 section h4 {text-align:center; font-weight:normal;color:#fff; font-size:48px; line-height:65px;} /* section 5 */ #section5_logo1 {position:absolute;top:163px;left:490px; transform-origin:center center;-webkit-animation: main_anilogo 3s linear infinite; -ms-animation: main_anilogo 3s linear infinite; animation:main_anilogo 3s linear infinite;-webkit-transform-origin:center center;-ms-transform-origin:center center;} #section5_logo2 {position:absolute;top:338px;left:270px; transform-origin:center center;-webkit-animation: main_anilogo 3s linear infinite; -ms-animation: main_anilogo 3s linear infinite; animation:main_anilogo 3s linear infinite;-webkit-transform-origin:center center;-ms-transform-origin:center center;} #section5_wheel1 {position:absolute;top:501px;left:435px; width:162px; height:162px;-webkit-animation: main_aniwheel 5s linear infinite; -ms-animation: main_aniwheel 5s linear infinite; animation:main_aniwheel 5s linear infinite;} #section5_wheel2 {position:absolute;top:759px;left:439px; -webkit-animation: main_aniwheel 2s linear infinite; -ms-animation: main_aniwheel 2s linear infinite; animation:main_aniwheel 2s linear infinite;} #section5_wheel3 {position:absolute;top:830px;left:423px; -webkit-animation: main_aniwheel 2s linear infinite; -ms-animation: main_aniwheel 2s linear infinite; animation:main_aniwheel 2s linear infinite;} /* section 6 */ #main_section6 section {padding:156px 0 0 0; color:#fff; font-size:48px; line-height:65px; text-align:center;} #skrollr-body {height:100%; width:100%;} /* main key visual carousel */ /* --------------------------------------------- */ /* main carousel settings */ /* --------------------------------------------- */ .main_kv_container { /* defaults for responsive height container */ position: relative; width: 100%; height: 535px; overflow: visible; } #main_kv_slider { width: 100%; height: 535px; } #main_kv_slider .slider { width: 100%; height: 100%; } #main_kv_slider .slider .item { float: left; width: 100%; } #main_kv_slider .slider .item img { width: 100%; height: auto; } .main_kv_container .prev { position: absolute; top: 0; left: 0; width: 100px; height: 535px; z-index: 10; background:url("../images/main/main_slider_prev.png") no-repeat -15px center; } .main_kv_container .next { position: absolute; top: 0; right: 0; width: 100px; height: 535px; z-index: 10; background:url("../images/main/main_slider_next.png") no-repeat left center; } .main_kv_container .slideSelectors { position: absolute; bottom: 40px; left: 40%; width: 300px; //控制banner 滚动图片的宽度 margin-left:-30px; z-index: 1; height: 10px; } .main_kv_container .slideSelectors .item { float: left; width: 12px; height: 12px; border: 1px solid #bbb; background: #bbb; margin: 0 0 0 10px; border-radius:6px; opacity: 0.5; filter: alpha(opacity=50); } .main_kv_container .slideSelectors .selected { background: #fff; opacity: 1; filter: alpha(opacity=100); } /* --------------------------------------------- */ /* main carousel settings */ /* --------------------------------------------- */
37.873747
307
0.706175
6589014caaf719e51c04102abad9eab868cf587c
689
kt
Kotlin
app/src/main/java/win/ca/demo/myapplication/domain/usecase/base/BaseUseCase.kt
sud007/Note-Reader-Sample
2061d65f862511a73b3a2f7173ac7b12f53d2678
[ "Apache-2.0" ]
null
null
null
app/src/main/java/win/ca/demo/myapplication/domain/usecase/base/BaseUseCase.kt
sud007/Note-Reader-Sample
2061d65f862511a73b3a2f7173ac7b12f53d2678
[ "Apache-2.0" ]
null
null
null
app/src/main/java/win/ca/demo/myapplication/domain/usecase/base/BaseUseCase.kt
sud007/Note-Reader-Sample
2061d65f862511a73b3a2f7173ac7b12f53d2678
[ "Apache-2.0" ]
null
null
null
package win.ca.demo.myapplication.domain.usecase.base import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.async import kotlinx.coroutines.launch import win.ca.demo.myapplication.data.api.model.response.base.Failure import win.ca.demo.myapplication.data.arch.Either /** * Created by Sudhanshu Singh on 29/01/22. */ abstract class BaseUseCase<out T, in P> { abstract suspend fun callApi(request: P?): Either<Failure, T> open operator fun invoke( scope: CoroutineScope, request: P?, onResult: (Either<Failure, T>) -> Unit = {} ) { val job = scope.async { callApi(request) } scope.launch { onResult(job.await()) } } }
29.956522
69
0.698113
d4f9f8bfe4f1608fda2b39cf64891e97ccd3588b
13,095
ts
TypeScript
src/main/resources/static/typescript/path.ts
Poxterx/Dungeon-Crawler
102add7c69947378155d7a02996ad04906534517
[ "Apache-2.0" ]
2
2020-03-15T21:39:20.000Z
2021-08-28T11:55:54.000Z
src/main/resources/static/typescript/path.ts
Poxterx/Dungeon-Crawler
102add7c69947378155d7a02996ad04906534517
[ "Apache-2.0" ]
null
null
null
src/main/resources/static/typescript/path.ts
Poxterx/Dungeon-Crawler
102add7c69947378155d7a02996ad04906534517
[ "Apache-2.0" ]
3
2018-11-18T21:21:27.000Z
2021-08-28T11:55:56.000Z
class Path { /** * Entidad que está siguiendo esta ruta */ private entity :Entity; /** * Punto de destino, en píxeles, en el que concluye la ruta */ private destination :Phaser.Math.Vector2; /** * Lista de puntos, en píxeles, que componen la ruta */ private points :Vector2[]; /** * Ruta inteligente trazada desde la posición actual de una entidad hasta un punto dado * en la sala, esquivando todos los tiles sólidos, implementada con el algoritmo A* * @param entity La entidad que va a seguir esta ruta * @param destination El punto de destino al que debe dirigirse la entidad */ constructor(entity :Entity, destination :Vector2) { this.entity = entity; this.destination = new Phaser.Math.Vector2(destination); this.points = []; // Al crear a ruta, procedemos a construirla inmediatamente this.generatePoints(); } /** * Devuelve el siguiente punto en la ruta, o el último si no quedan más */ public next() { // Si queda más de un punto, sacamos el que estuviera al frente if(this.points.length > 1) { this.points.shift(); } // Y devolvemos el siguiente, que estará ahora al frente return this.points[0]; } /** * Indica si la ruta ha sido recorrida al completo, es decir, si mediante next() ya se * ha obtenido el último punto de la ruta, o si la ruta no tiene puntos en primer lugar * porque es imposible. */ public isDone() { return this.points.length <= 1; } /** * Indica si la ruta es imposible de recorrer. Esto puede pasar si el punto de destino * se encuentra dentro de un tile sólido o si está en una estancia a la que es imposible * acceder desde la posición en la que se encuentra la entidad. */ public isImpossible() { return this.points.length == 0; } /** * Dibuja una línea verde que representa la ruta, para hacerla visible. Esta función es sólo * para depuración y no se va a usar en la versión final. * @param graphics El objeto de gráficos de Phaser con el que se va a dibujar la ruta */ public draw(graphics :Phaser.GameObjects.Graphics) { // Si la entidad que tiene esta ruta está muerta no hay nada que dibujar if(this.entity.dead) { return; } // Ponemos la línea verde y con 3px de grosor graphics.lineStyle(3, 0x00FF00); // Si no hay nada que dibujar if(this.points.length == 0) { // Aquí no pintamos nada return; } // Comenzamos el trazado de la ruta graphics.beginPath(); // A partir de aquí, a todas las coordenadas se les resta la posición del propio objeto // de gráficos. Esto es porque queremos introducir las coordenadas de cada punto respecto // al origen del mundo, pero el objeto de gráficos no necesariamente tiene que estar // ahí. Por esa razón restamos su posición actual // Empezamos en la posición de la entidad graphics.moveTo( this.entity.sprite.body.center.x - graphics.x, this.entity.sprite.body.center.y - graphics.y); // Y ahora dibujamos una línea a cada punto de la ruta for(let point of this.points) { graphics.lineTo(point.x - graphics.x, point.y - graphics.y); } // Ya podemos emitir el trazado graphics.strokePath(); } /** * Genera los puntos que componen esta ruta siguiendo el algoritmo A* */ private generatePoints() { // Empezamos con un acceso más conveniente a la sala en la que se encuentra la entidad var room = this.entity.scene.room; // Obtenemos el tile en el que empezamos y el tile al que vamos var destTilePosition = pixelToTilePosition(this.destination); var startTilePosition = pixelToTilePosition({ x: this.entity.sprite.body.center.x, y: this.entity.sprite.body.center.y}); var destTile = room.getColliderTileAt(destTilePosition); var startTile = room.getColliderTileAt(startTilePosition); // Puede ser que el tile al que vamos sea sólido, en cuyo caso la ruta es imposible if(destTile.properties.Solid) { console.warn("Atención, Ruta Imposible: " + "%s ha intentado generar una ruta hacia el tile sólido situado en (%d, %d)", this.entity.name, destTilePosition.x, destTilePosition.y); // ¿Para qué perder el tiempo intentando crear la ruta si ya sabemos que es imposible? return; } // Todos los posibles tiles que vayamos a recorrer se guardan en este mapa, que le // asigna a cada tile un valor y referencias a sus tiles colindantes var astarmap = new Map<Phaser.Tilemaps.Tile, { /** * Distancia en tiles que se ha recorrido desde el tile inicial hasta este */ value :number, /** * Vecinos en vertical y horizontal de este tile que no son sólidos */ neighbours :Phaser.Tilemaps.Tile[] }>(); // También tenemos una cola donde añadiremos los tiles que hay que procesar. La // inicializamos con el tile inicial, que es por el que vamos a empezar. var tileQueue = [startTile]; // También es buena idea añadir el tile inicial al mapa para que se pueda empezar // el procesamiento sin problemas. astarmap.set(startTile, {value: 0, neighbours: []}); // Estaremos procesando tiles hasta que ya no queden más por procesar while(tileQueue.length > 0) { // Obtenemos los vecinos y los datos en el mapa del tile que estamos procesando // actualmente (el que está al frente de la cola) let neighbours = Path.getNeighbourTiles(room, tileQueue[0]); let currentTileData = astarmap.get(tileQueue[0]); for(let neighbour of neighbours) { // Si el vecino no es sólido ni está todavía en el mapa if(!astarmap.has(neighbour) && !neighbour.properties.Solid) { // Hay que añadirlo al mapa. Además, la relación de vecindad // es recíproca y hay que indicarlo también. astarmap.set(neighbour, { value: currentTileData.value + 1, neighbours: [tileQueue[0]] }); // El tile recién añadido al mapa no se ha procesado todavía. Lo // procesaremos más tarde en el bucle. tileQueue.push(neighbour); // El mapa también tiene que tener constancia de los vecinos de este tile. // La diferencia entre los vecinos obtenidos con Path.getNeighbourTiles() // y los que estamos añadiendo ahora es que ahora estamos distinguiendo // los que son sólidos de los que no. currentTileData.neighbours.push(neighbour); } } // ¿El tile que acabamos de procesar es el tile al que teníamos que llegar? if(tileQueue[0] == destTile) { // Si es así entonces esta etapa de la generación de la ruta ha terminado break; } else { // Si no, sacamos de la cola al tile que acabamos de procesar para que // pase el siguiente tileQueue.shift(); } } // A lo mejor hemos salido del bucle anterior por haber vaciado la cola y no por haber // encontrado el tile de destino. Esto se debe a que la estancia donde está la entidad // y la estancia donde está el tile de destino están completamente separadas y aisladas // por tiles sólidos. En este caso, la ruta también es imposible. if(tileQueue[0] != destTile) { console.warn("Atención, Ruta Imposible: " + "%s ha intentado generar una ruta hacia el tile (%d, %d) pero es inalcanzable " + "desde su posición actual", this.entity.name, destTilePosition.x, destTilePosition.y); // No podemos hacer nada más return; } // Ahora que ya está el mapa trazado, tenemos que hacer el recorrido inverso: Desde el // tile de destino hasta la posición inicial. Lo haremos utilizando los valores que // hemos asignado previamente en el mapa. Esta es la etapa que genera los puntos realmente. var currentTile = destTile; var lastTile = destTile; var lastTileAux = destTile; // Vamos a estar generando puntos hasta que hayamos vuelto a la posición original, // aunque haremos al menos una iteración para que, si no es una ruta imposible, // haya al menos un punto en la misma para evitar errores. while(currentTile != startTile || this.points.length == 0) { // Hay que añadir el punto de este tile. La lista de puntos está en píxeles, así // que hay que pasar el tile a píxeles antes de añadirlo. El punto de destino // está en píxeles también así que no hay que pasarlo a nada. let add :Vector2; if(currentTile == destTile) { add = this.destination; } else { add = tileToPixelPosition(currentTile); } // Metemos el nuevo punto al principio de la lista de puntos this.points.unshift(add); // Ahora vamos a consultar los datos de este tile para determinar cuál será el siguiente let currentTileData = astarmap.get(currentTile); for(let neighbour of currentTileData.neighbours) { let neighbourData = astarmap.get(neighbour); // Si el vecino que estamos mirando existe y su valor es menor que el tile actual, // es porque está más cerca del tile inicial que el actual if(neighbourData && neighbourData.value < currentTileData.value) { // Y si además es adyacente al tile que miramos en la iteración anterior... if(this.areDiagonallyAdjacent(lastTile, neighbour) && currentTile != destTile) { // ... entonces no necesitamos tener el tile actual en la lista de puntos // (salvo si es el tile de destino, por muy adyacente que sea) this.points.shift(); // Pasamos a este vecino para la siguiente iteración currentTile = neighbour; break; } else { // Ponemos a este vecino como posible tile de la siguiente iteración, // pero seguimos mirando por si hay otro vecino que sí es adyacente currentTile = neighbour; } } } // Pero hay que guardar el tile que miramos en la iteración anterior para futuras // referencias relacionadas con la adyacencia lastTile = lastTileAux; lastTileAux = currentTile; } } /** * Devuelve los tiles de Phaser en la capa de colisiones que son colindantes, * horizontal y verticalmente, al tile indicado * @param room La sala a la que pertenece el tile * @param tile El tile en cuestión */ private static getNeighbourTiles(room :Room, tile :Phaser.Tilemaps.Tile) { var ret :Phaser.Tilemaps.Tile[] = []; if(tile == null){ return []; } var possibleNeighbours = [ {x: tile.x, y: tile.y-1}, {x: tile.x, y: tile.y+1}, {x: tile.x-1, y: tile.y}, {x: tile.x+1, y: tile.y} ]; // Antes de consultar si hay una colisión en el tile, hay que comprobar que // esté dentro de la sala, para evitar problemas con funciones de Phaser for(let possibility of possibleNeighbours) { if(possibility.x >= 0 && possibility.x < room.size.x / TILE_SIZE && possibility.y >= 0 && possibility.y < room.size.y / TILE_SIZE) { ret.push(room.getColliderTileAt(possibility)); } } return ret; } /** * Indica si dos tiles dados son adyacentes diagonalmente * @param tile1 El primer tile a mirar * @param tile2 El segundo tile a mirar */ private areDiagonallyAdjacent(tile1 :Vector2, tile2 :Vector2) { // Dos tiles son diagonalmente adyacentes si están separados por una distancia de una // unidad en ambos ejes. Si la distancia en cualquiera de los ejes fuera 0 ya no sería // una adyacencia diagonal, y si la distancia fuera más de 1 ya no sería una adyacencia. return Math.abs(tile1.x - tile2.x) == 1 && Math.abs(tile1.y - tile2.y) == 1 } }
45.155172
100
0.598855
7f7270fee9ac592dc687fc6b63b2f0abc970b27f
910
php
PHP
app/Http/Controllers/UserFavoriteController.php
yuto0139/microposts
e072877a63c765afa46b69ff628f4c2ecf0cd67c
[ "MIT" ]
null
null
null
app/Http/Controllers/UserFavoriteController.php
yuto0139/microposts
e072877a63c765afa46b69ff628f4c2ecf0cd67c
[ "MIT" ]
1
2018-08-24T07:30:03.000Z
2018-08-24T07:30:04.000Z
app/Http/Controllers/UserFavoriteController.php
yuto0139/microposts
e072877a63c765afa46b69ff628f4c2ecf0cd67c
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; class UserFavoriteController extends Controller { public function store(Request $request, $micropost) { \Auth::user()->give_favorite($micropost); return redirect()->back(); } public function destroy($micropost) { \Auth::user()->cancel_favorite($micropost); return redirect()->back(); } public function index(Request $request, $id) { if (\Auth::check()) { $user = \Auth::user(); $microposts = $user->favorite_with()->orderBy('created_at', 'desc')->paginate(10); $data = [ 'user' => $user, 'microposts' => $microposts, ]; $data += $this->counts($user); return view('users.favorite_with', $data); } return view('welcome'); } }
23.947368
94
0.530769
748aae272aa297f4f520071d21b2673ea054fca5
434
css
CSS
lib/style/DefaultStyle.css
AlexScriba/Weaver
811cd5df6ca8ad71e4e92bbde953ae4303ae16e5
[ "MIT" ]
1
2022-01-22T12:08:02.000Z
2022-01-22T12:08:02.000Z
lib/style/DefaultStyle.css
AlexScriba/Weaver
811cd5df6ca8ad71e4e92bbde953ae4303ae16e5
[ "MIT" ]
null
null
null
lib/style/DefaultStyle.css
AlexScriba/Weaver
811cd5df6ca8ad71e4e92bbde953ae4303ae16e5
[ "MIT" ]
null
null
null
:root { padding: 0; margin: 0; display: flex; flex-direction: column; align-items: center; height: 100%; } body { padding: 0; margin: 0; height: 100%; width: 100%; display: flex; flex-direction: column; align-items: center; } div { padding: 0; margin: 0; } .row { display: flex; flex-direction: row; justify-content: space-evenly; } .column { display: flex; flex-direction: column; align-items: center; }
10.85
31
0.647465
135251379815a94578744f3b2f2e395e73df68c4
161
lua
Lua
2017/06/solution.lua
MechWipf/adventofcode
4645db2e883c4e256f58c1bd59536ebff70f99e2
[ "MIT" ]
null
null
null
2017/06/solution.lua
MechWipf/adventofcode
4645db2e883c4e256f58c1bd59536ebff70f99e2
[ "MIT" ]
null
null
null
2017/06/solution.lua
MechWipf/adventofcode
4645db2e883c4e256f58c1bd59536ebff70f99e2
[ "MIT" ]
null
null
null
package.path = [[X:\Notizen\OtherStuff\?.lua;]] .. package.path local utils = require "utils" print( (function () return table.unpack { 1, 2 }, 3 end)() );
32.2
64
0.627329
6b7dac3c39252a4f484a013f9b9dc7597554a542
30,490
swift
Swift
ActionsCatalog/ActionsCatalog/GameScene.swift
hotchner/2DGames
c23596d294d91211450b59205efd765137400447
[ "MIT" ]
null
null
null
ActionsCatalog/ActionsCatalog/GameScene.swift
hotchner/2DGames
c23596d294d91211450b59205efd765137400447
[ "MIT" ]
null
null
null
ActionsCatalog/ActionsCatalog/GameScene.swift
hotchner/2DGames
c23596d294d91211450b59205efd765137400447
[ "MIT" ]
null
null
null
/** * Copyright (c) 2017 Razeware LLC * * 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. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import SpriteKit class GameScene: SKScene { let playableRect: CGRect let cat:SKSpriteNode = SKSpriteNode(imageNamed: "cat") let dog:SKSpriteNode = SKSpriteNode(imageNamed: "dog") let turtle:SKSpriteNode = SKSpriteNode(imageNamed: "turtle") let label:SKLabelNode = SKLabelNode(fontNamed: "Verdana") override init(size: CGSize) { let maxAspectRatio:CGFloat = 16.0/9.0 // iPhone 5" let maxAspectRatioHeight = size.width / maxAspectRatio let playableMargin = (size.height-maxAspectRatioHeight)/2.0 playableRect = CGRect(x: 0, y: playableMargin, width: size.width, height: size.height-playableMargin*2) super.init(size: size) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMove(to view: SKView) { backgroundColor = SKColor.white cat.position = CGPoint(x: size.width * 1/6, y: size.height / 2) addChild(cat) dog.position = CGPoint(x: size.width * 3/6, y: size.height / 2) addChild(dog) turtle.position = CGPoint(x: size.width * 5/6, y: size.height / 2) addChild(turtle) label.text = "Test" label.fontSize = 40 label.fontColor = SKColor.black label.position = CGPoint(x: size.width / 2, y: playableRect.minY + playableRect.height * 1/6) addChild(label) } } class MoveScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // move(to:duration:) cat.run(SKAction.repeatForever( SKAction.sequence([ SKAction.move(to: CGPoint(x: playableRect.minX, y:playableRect.minY), duration:1.0), SKAction.move(to: cat.position, duration:1.0) ]) )) // moveBy(x:y:duration:) dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.moveBy(x: 0, y: playableRect.height * 1/6, duration: 1.0), SKAction.moveBy(x: 0, y: -playableRect.height * 1/6, duration: 1.0) ]) )) // moveTo(x:duration:) and moveTo(y:duration:) turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.group([ SKAction.moveTo(x: playableRect.maxX, duration: 1.0), SKAction.moveTo(y: playableRect.minY, duration: 1.0), ]), SKAction.group([ SKAction.moveTo(x: turtle.position.x, duration: 1.0), SKAction.moveTo(y: turtle.position.y, duration: 1.0), ]) ]) )) label.text = "Move Actions / Cross Fade" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.crossFade(withDuration: 1.0) let nextScene = RotateScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class RotateScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // rotate(byAngle:duration:) cat.run(SKAction.repeatForever( SKAction.rotate(byAngle: π*2, duration: 1.0) )) // rotate(toAngle:duration:) dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.rotate(toAngle: π/2, duration: 1.0), SKAction.rotate(toAngle: π, duration: 1.0), SKAction.rotate(toAngle: -π/2, duration: 1.0), SKAction.rotate(toAngle: π, duration: 1.0), ]) )) // rotate(toAngle:duration:shortestUnitArc:) turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.rotate(toAngle: π/2, duration: 1.0, shortestUnitArc:true), SKAction.rotate(toAngle: π, duration: 1.0, shortestUnitArc:true), SKAction.rotate(toAngle: -π/2, duration: 1.0, shortestUnitArc:true), SKAction.rotate(toAngle: π, duration: 1.0, shortestUnitArc:true), ]) )) label.text = "Rotate Actions / Fade" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.fade(withDuration: 1.0) let nextScene = ResizeScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class ResizeScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // resize(byWidth:height:duration:) cat.run(SKAction.repeatForever( SKAction.sequence([ SKAction.resize(byWidth: cat.size.width, height: -cat.size.height/2, duration: 1.0), SKAction.resize(byWidth: -cat.size.width, height: cat.size.height/2, duration: 1.0) ]) )) // resize(toWidth:height:duration:) dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.resize(toWidth: 10, height: 200, duration: 1.0), SKAction.resize(toWidth: dog.size.width, height: dog.size.height, duration: 1.0) ]) )) // resize(toWidth:duration:) and resize(toHeight:duration:) turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.group([ SKAction.resize(toWidth: turtle.size.width*2, duration: 1.0), SKAction.resize(toHeight: turtle.size.height/2, duration: 1.0) ]), SKAction.group([ SKAction.resize(toWidth: turtle.size.width, duration: 1.0), SKAction.resize(toHeight: turtle.size.height, duration: 1.0) ]) ]) )) label.text = "Resize Actions / Fade with Color" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.fade(with: SKColor.red, duration:1.0) let nextScene = ScaleScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class ScaleScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // scale(by:duration:) and scale(to:duration:) cat.run(SKAction.repeatForever( SKAction.sequence([ SKAction.scale(by: 2.0, duration: 0.5), SKAction.scale(by: 2.0, duration: 0.5), // now effectively at 4x SKAction.scale(to: 1.0, duration: 1.0), ]) )) // scaleX(by:y:duration:) and scaleX(to:y:duration:) dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.scaleX(by: 0.25, y:1.25, duration:0.5), SKAction.scaleX(by: 0.25, y:1.25, duration:0.5), // now effectively xScale 0.0625, yScale 1.565 SKAction.scaleX(to: 1.0, y:1.0, duration:1.0), ]) )) // scaleX(to:duration:) and scaleY(to:duration:) turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.group([ SKAction.scaleX(to: 3.0, duration:1.0), SKAction.scaleY(to: 0.5, duration:1.0) ]), SKAction.group([ SKAction.scaleX(to: 1.0, duration:1.0), SKAction.scaleY(to: 1.0, duration:1.0) ]) ]) )) label.text = "Scale Actions / Flip Horizontal" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.flipHorizontal(withDuration: 1.0) let nextScene = RepeatScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class RepeatScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // repeat(_:count:) cat.run(SKAction.repeat( SKAction.sequence([ SKAction.moveBy(x: 0, y: playableRect.height * 1/6, duration: 0.2), SKAction.moveBy(x: 0, y: -playableRect.height * 1/6, duration: 0.2) ]), count:2 )) dog.run(SKAction.repeat( SKAction.sequence([ SKAction.moveBy(x: 0, y: playableRect.height * 1/6, duration: 0.2), SKAction.moveBy(x: 0, y: -playableRect.height * 1/6, duration: 0.2) ]), count:4 )) // repeatForever(_:) turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.moveBy(x: 0, y: playableRect.height * 1/6, duration: 0.2), SKAction.moveBy(x: 0, y: -playableRect.height * 1/6, duration: 0.2) ]) )) label.text = "Repeat Actions / Flip Vertical" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.flipVertical(withDuration: 1.0) let nextScene = FadeScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class FadeScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // fadeOut(withDuration:) and fadeIn(withDuration:) cat.run(SKAction.repeatForever( SKAction.sequence([ SKAction.fadeOut(withDuration: 1.0), SKAction.fadeIn(withDuration: 1.0) ]) )) // fadeAlpha(by:duration:) dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.fadeAlpha(by: -0.75, duration: 1.0), SKAction.fadeAlpha(by: 0.75, duration: 1.0), ]) )) // fadeAlpha(to:duration:) turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.fadeAlpha(to: 0.25, duration: 1.0), SKAction.fadeAlpha(to: 1.0, duration: 1.0), ]) )) label.text = "Fade Actions / Reveal" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.reveal(with: .left, duration:1.0) let nextScene = TextureScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class TextureScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) let catTexture = SKTexture(imageNamed: "cat") let dogTexture = SKTexture(imageNamed: "dog") let turtleTexture = SKTexture(imageNamed: "turtle") // setTexture(_:) cat.run(SKAction.repeatForever( SKAction.sequence([ SKAction.setTexture(catTexture), SKAction.wait(forDuration: 0.25), SKAction.setTexture(dogTexture), SKAction.wait(forDuration: 0.25), SKAction.setTexture(turtleTexture), SKAction.wait(forDuration: 0.25) ]) )) // animate(with:timePerFrame:) let textures = [catTexture, dogTexture, turtleTexture] dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.animate(with: textures, timePerFrame: 0.25) ]) )) // animate(with:timePerFrame:resize:restore:) turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.animate(with: textures, timePerFrame: 0.25, resize: true, restore: true) ]) )) label.text = "Texture Actions / Move In" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.moveIn(with: .left, duration: 1.0) let nextScene = SoundRemoveScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class SoundRemoveScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // removeFromParent() cat.run(SKAction.sequence([ SKAction.wait(forDuration: 1.0), SKAction.removeFromParent() ])) // playSoundFileNamed(_:waitForCompletion:) dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.playSoundFileNamed("pew-pew-lei.caf", waitForCompletion: true), SKAction.moveBy(x: 0, y: playableRect.height * 1/6, duration: 1.0), SKAction.moveBy(x: 0, y: -playableRect.height * 1/6, duration: 1.0), SKAction.playSoundFileNamed("pew-pew-lei.caf", waitForCompletion: true), SKAction.rotate(byAngle: π*2, duration: 1.0) ]) )) // removeFromParent() turtle.run(SKAction.sequence([ SKAction.wait(forDuration: 1.0), SKAction.removeFromParent() ])) label.text = "Sound and Remove Actions / Push" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.push(with: .left, duration: 1.0) let nextScene = ColorizeScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class ColorizeScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) let dogTexture = SKTexture(imageNamed: "dog") cat.texture = dogTexture turtle.texture = dogTexture // colorize(with:colorBlendFactor:duration:) and colorize(withColorBlendFactor:duration:) cat.run(SKAction.repeatForever( SKAction.sequence([ SKAction.colorize(with: SKColor.red, colorBlendFactor: 1.0, duration: 1.0), SKAction.colorize(withColorBlendFactor: 0.0, duration: 1.0) ]) )) dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.colorize(with: SKColor.red, colorBlendFactor: 0.25, duration: 1.0), SKAction.colorize(withColorBlendFactor: 0.0, duration: 1.0) ]) )) turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.colorize(with: SKColor.red, colorBlendFactor: 1.0, duration: 1.0), SKAction.colorize(withColorBlendFactor: 0.0, duration: 1.0), SKAction.colorize(with: SKColor.green, colorBlendFactor: 1.0, duration: 1.0), SKAction.colorize(withColorBlendFactor: 0.0, duration: 1.0), SKAction.colorize(with: SKColor.blue, colorBlendFactor: 1.0, duration: 1.0), SKAction.colorize(withColorBlendFactor: 0.0, duration: 1.0), ]) )) label.text = "Colorize Actions / Doors Open" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.doorsOpenHorizontal(withDuration: 1.0) let nextScene = FollowScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class FollowScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // follow(_:duration:) cat.position = CGPoint.zero let screenBorders = CGPath(rect: playableRect, transform: nil) cat.run(SKAction.repeatForever( SKAction.sequence([ SKAction.follow(screenBorders, duration:10.0) ]) )) // follow(_:speed:) let stepAmt:CGFloat = 20 let steps:CGFloat = 5 let path = CGMutablePath() path.move(to: CGPoint(x: playableRect.minX, y: playableRect.minY)) for i in stride(from: 0, to: steps, by: 1.0) { path.addLine(to: CGPoint(x: i*stepAmt, y: (i+1)*stepAmt)) path.addLine(to: CGPoint(x: (i+1)*stepAmt, y: (i+1)*stepAmt)) } for i in stride(from: 0, to: steps, by: 1.0) { path.addLine(to: CGPoint(x: (steps-i)*stepAmt, y: (steps-i-1)*stepAmt)) path.addLine(to: CGPoint(x: (steps-i-1)*stepAmt, y: (steps-i-1)*stepAmt)) } dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.follow(path, speed: 50.0) ]) )) // follow(_:asOffset:orientToPath:duration:) let circle = CGPath(roundedRect: CGRect(x: playableRect.minX, y: playableRect.minY, width: 400, height: 400), cornerWidth: 200, cornerHeight: 200, transform: nil) turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.follow(circle, asOffset: false, orientToPath: false, duration: 5.0) ]) )) label.text = "Follow Actions / Doors Close" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.doorsCloseHorizontal(withDuration: 1.0) let nextScene = SpeedScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class SpeedScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // speed(to:duration:) cat.run(SKAction.repeatForever( SKAction.sequence([ SKAction.group([ SKAction.speed(to: 5.0, duration:1.0), SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 1.0), ]), SKAction.group([ SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 1.0), ]), SKAction.group([ SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 1.0), ]), SKAction.group([ SKAction.speed(to: 1.0, duration:1.0), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 1.0), ]), ]) )) dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 0.25), SKAction.speed(to: 0.5, duration:0.1), SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 0.25), SKAction.speed(to: 1.0, duration:1.0), ]) )) // speedBy(by:duration:) // TODO: BUG??? Getting unexpected behavior on this... turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 0.25), SKAction.speed(by: -0.5, duration:0.1), SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 0.25), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 0.25), SKAction.speed(by: 0.5, duration:1.0), ]) )) label.text = "Speed Actions / Doorway" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.doorway(withDuration: 1.0) let nextScene = WaitScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class WaitScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // wait(forDuration:) cat.run(SKAction.repeatForever( SKAction.sequence([ SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 1.0), SKAction.wait(forDuration: 1.0), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 1.0), ]) )) // wait(forDuration:withRange:) dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 1.0), SKAction.wait(forDuration: 1.0, withRange:1.0), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 1.0), ]) )) turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 1.0), SKAction.wait(forDuration: 2.0, withRange:2.0), SKAction.moveBy(x: 0, y: self.playableRect.height * -1/6, duration: 1.0), ]) )) label.text = "Wait Actions / CIFilter" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let filter = CIFilter(name: "CIDissolveTransition")! filter.setDefaults() let transition = SKTransition(ciFilter: filter, duration: 1.0) let nextScene = BlockScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class BlockScene : GameScene { func rotateCat() { cat.run(SKAction.rotate(byAngle: π*2, duration:1.0)) } override func didMove(to view: SKView) { super.didMove(to: view) // run(_:) cat.run(SKAction.repeatForever( SKAction.sequence([ SKAction.run() { [weak self] in self?.rotateCat() }, SKAction.wait(forDuration: 2.0) ]) )) dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.run() { [weak self] in self?.dog.run(SKAction.rotate(byAngle: π*2, duration:1.0)) }, SKAction.wait(forDuration: 2.0) ]) )) // run(_:queue:) let queue = DispatchQueue(label: "com.razeware.actionscatalog.bgqueue") var workDone = true turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.run({ [weak self] in guard let strongSelf = self else { return } if (workDone) { workDone = false strongSelf.turtle.run(SKAction.rotate(byAngle: π*2, duration:1.0)) strongSelf.turtle.run(SKAction.run({ sleep(1) workDone = true }, queue: queue)) } }, queue: queue), SKAction.wait(forDuration: 1.0) ]) )) label.text = "Block Actions" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.crossFade(withDuration: 1.0) let nextScene = ChildActionsScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class ChildActionsScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) cat.removeFromParent() cat.position = CGPoint(x: size.width * -1/3, y: 0) cat.name = "cat" dog.addChild(cat) turtle.removeFromParent() turtle.position = CGPoint(x: size.width * 1/3, y: 0) turtle.name = "turtle" dog.addChild(turtle) // children affected by action dog.run(SKAction.repeatForever( SKAction.rotate(byAngle: π*2, duration: 3.0) )) // run(_:onChildWithName:) dog.run(SKAction.run(SKAction.repeatForever( SKAction.rotate(byAngle: π*2, duration: 3.0) ), onChildWithName: "cat")) dog.run(SKAction.run(SKAction.repeatForever( SKAction.sequence([ SKAction.moveBy(x: -200, y:0, duration:1.0), SKAction.moveBy(x: 200, y:0, duration:1.0), ]) ), onChildWithName: "turtle")) label.text = "Child Actions" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.crossFade(withDuration: 1.0) let nextScene = CustomActionScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class CustomActionScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // "Blink" action /** Challenge 1 answers: 1) follow(_:duration:) 2) fadeAlpha(to:duration:) 3) Explanation follows: Custom actions allow you to easily make a node do something over time that there isn't already an action for. The ActionsCatalog demonstrates three kinds of custom actions: making a node blink, jump, or follow a sin wave. Custom actions give you a node to work with, and how much time has elapsed. Your job is to update something on the node, based on the percentage of how much time has elapsed vs. the passed in duration. As an example, here's an explanation of the blink action demo in ActionsCatalog: 1) Divide the duration by the number of blinks desired in that time period. Call that a "slice" of time. In each slice, the node should be visible for half the time, and invisible for the other half. That is what will make the node appear to blink. 2) The truncatingRemainder method returns the remainder of the first parameter (elapsedTime) after being divided by the second parameter (slice). So in this example, it gives you the amount of time that has elapsed in this "slice" calculated earlier. 3) The hidden property on a node controls whether it is rendered or not. If the remainder calculated above is in the second half of the slice, it should be hidden (invisible). Otherwise it will be visible. Hence, the blink effect! Note that you can also accomplish a blink effect with a combination of hide() and unhide() actions, as you see in HideScene. */ let blinkTimes = 6.0 let duration = 2.0 cat.run(SKAction.repeatForever( SKAction.customAction(withDuration: duration) { node, elapsedTime in let slice = duration / blinkTimes let remainder = Double(elapsedTime).truncatingRemainder(dividingBy: slice) node.isHidden = remainder > slice / 2 } )) // "Jump" action let dogStart = dog.position let jumpHeight = 100.0 let dogDuration = 2.0 dog.run(SKAction.repeatForever( SKAction.customAction(withDuration: duration) { node, elapsedTime in let fraction = Double(elapsedTime) / dogDuration let yOff = jumpHeight * 4 * fraction * (1 - fraction) node.position = CGPoint(x: node.position.x, y: dogStart.y + CGFloat(yOff)) } )) // "Sin wave" let turtleStart = turtle.position let amplitude = 25.0 let turtleDuration = 1.0 turtle.run(SKAction.repeatForever( SKAction.customAction(withDuration: duration) { node, elapsedTime in let fraction = Double(elapsedTime) / turtleDuration let yOff = sin(Double.pi * 2 * fraction) * amplitude node.position = CGPoint(x: node.position.x, y: turtleStart.y + CGFloat(yOff)) } )) label.text = "Custom Actions" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.crossFade(withDuration: 1.0) let nextScene = TimingScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class TimingScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // SKActionTimingMode.easeIn let catMoveUp = SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 1.0) catMoveUp.timingMode = .easeIn let catMoveDown = catMoveUp.reversed() cat.run(SKAction.repeatForever( SKAction.sequence([catMoveUp, catMoveDown]) )) // SKActionTimingMode.easeOut let dogMoveUp = SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 1.0) dogMoveUp.timingMode = .easeOut let dogMoveDown = catMoveUp.reversed() dog.run(SKAction.repeatForever( SKAction.sequence([dogMoveUp, dogMoveDown]) )) // SKActionTimingMode.easeInEaseOut let turtleMoveUp = SKAction.moveBy(x: 0, y: self.playableRect.height * 1/6, duration: 1.0) turtleMoveUp.timingMode = .easeInEaseOut let turtleMoveDown = catMoveUp.reversed() turtle.run(SKAction.repeatForever( SKAction.sequence([turtleMoveUp, turtleMoveDown]) )) label.text = "Timing Actions" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.crossFade(withDuration: 1.0) let nextScene = HideScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } } class HideScene : GameScene { override func didMove(to view: SKView) { super.didMove(to: view) // hide() and unhide() cat.run(SKAction.repeatForever( SKAction.sequence([ SKAction.hide(), SKAction.wait(forDuration: 1.0), SKAction.unhide(), SKAction.wait(forDuration: 1.0), ]) )) dog.run(SKAction.repeatForever( SKAction.sequence([ SKAction.hide(), SKAction.wait(forDuration: 0.5), SKAction.unhide(), SKAction.wait(forDuration: 0.5), ]) )) turtle.run(SKAction.repeatForever( SKAction.sequence([ SKAction.hide(), SKAction.wait(forDuration: 0.1), SKAction.unhide(), SKAction.wait(forDuration: 0.1), ]) )) label.text = "Hide Actions" } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let transition = SKTransition.crossFade(withDuration: 1.0) let nextScene = MoveScene(size: size) nextScene.scaleMode = scaleMode view?.presentScene(nextScene, transition: transition) } }
32.714592
254
0.648081
54cb80a017eacebb49f737fa7d592c2c9bc662c9
406
css
CSS
assets/css/leashless.css
greggoryhogan/leashless
683c858adb6cfe046625235f42cda01779361843
[ "MIT" ]
null
null
null
assets/css/leashless.css
greggoryhogan/leashless
683c858adb6cfe046625235f42cda01779361843
[ "MIT" ]
null
null
null
assets/css/leashless.css
greggoryhogan/leashless
683c858adb6cfe046625235f42cda01779361843
[ "MIT" ]
null
null
null
.gform_wrapper #gform_1 .gfield_chainedselect select{width:100% !important}.ui-autocomplete{max-height:250px;overflow-y:auto;overflow-x:hidden}.ui-autocomplete .ui-autocomplete-category{font-weight:bold;padding:.2em .4em;margin:.2em 0 .2em;line-height:1.5}#findapark{padding:1rem 2rem;width:100%}#findapark input[type="text"]{width:100%;padding:1rem;font-size:2rem;border-radius:5px;border:1px solid #ccc}
203
405
0.79803
da3e60500b06f63ba85e9d7fc28967a2a8692e6a
7,572
tsx
TypeScript
src/pages/spectrum_strip.tsx
Abhimanyu6676/www
01a7ad0a91fe28c33fdcacfc98308ddacdc332d7
[ "RSA-MD" ]
null
null
null
src/pages/spectrum_strip.tsx
Abhimanyu6676/www
01a7ad0a91fe28c33fdcacfc98308ddacdc332d7
[ "RSA-MD" ]
null
null
null
src/pages/spectrum_strip.tsx
Abhimanyu6676/www
01a7ad0a91fe28c33fdcacfc98308ddacdc332d7
[ "RSA-MD" ]
null
null
null
import { graphql, useStaticQuery } from "gatsby" import React from "react" import { Container } from "react-bootstrap" import Layout from "../components/common/layout" import Section1 from "../components/common/productSection" import Section2 from "../components/common/sectionType1" import Section3 from "../components/common/sectionType2" import SubscribeSection from "../components/common/subscribeSection" import BlogSection from "../components/common/latestBlogType1" export default () => { const data = useStaticQuery(graphql` query { thumbs: allFile(filter: {extension: {regex: "/(jpg)|(jpeg)|(png)/"}, dir: {eq: "C:/Users/admin/react/Website/web/src/images/Products/Strips/spectrum_strip/productPhotos"}}, sort: {fields: name}) { edges { node { id childImageSharp { fluid(maxWidth: 100) { ...GatsbyImageSharpFluid } } } } } pics: allFile(filter: {extension: {regex: "/(jpg)|(jpeg)|(png)/"}, dir: {eq: "C:/Users/admin/react/Website/web/src/images/Products/Strips/spectrum_strip/productPhotos"}}, sort: {fields: name}) { edges { node { id childImageSharp { fluid(maxWidth: 750) { ...GatsbyImageSharpFluid } } } } } section2Img_mobile: file(relativePath: {eq: "Products/Strips/spectrum_strip/spectrumStrip_section2_main-mobile.png"}) { childImageSharp { fluid(maxWidth: 700, quality: 100) { ...GatsbyImageSharpFluid } } } section2Img: file(relativePath: {eq: "Products/Strips/spectrum_strip/spectrumStrip_section2_main.png"}) { childImageSharp { fluid(maxWidth: 2000, quality: 100) { ...GatsbyImageSharpFluid } } } section3Img1: file(relativePath: { eq: "Products/Strips/spectrum_strip/section3_img1.png" }) { childImageSharp { fluid(maxWidth: 800) { ...GatsbyImageSharpFluid } } } section3Img2: file(relativePath: { eq: "Products/Strips/spectrum_strip/section3_img2.png" }) { childImageSharp { fluid(maxWidth: 800) { ...GatsbyImageSharpFluid } } } section3Img3: file(relativePath: { eq: "Products/Strips/spectrum_strip/section3_img3.png" }) { childImageSharp { fluid(maxWidth: 800) { ...GatsbyImageSharpFluid } } } section4Img_mobile: file(relativePath: {eq: "Products/Strips/spectrum_strip/spectrumStrip_section4_mainImg-mobile.png"}) { childImageSharp { fluid(maxWidth: 700, quality: 100) { ...GatsbyImageSharpFluid } } } section4Img: file(relativePath: {eq: "Products/Strips/spectrum_strip/spectrumStrip_section4_mainImg.png"}) { childImageSharp { fluid(maxWidth: 2000, quality: 100) { ...GatsbyImageSharpFluid } } } section5Img_mobile: file(relativePath: {eq: "Products/Strips/spectrum_strip/spectrumStrip_section5_mainImg-mobile.png"}) { childImageSharp { fluid(maxWidth: 700, quality: 100) { ...GatsbyImageSharpFluid } } } section5Img: file(relativePath: {eq: "Products/Strips/spectrum_strip/spectrumStrip_section5_mainImg.png"}) { childImageSharp { fluid(maxWidth: 2000, quality: 100) { ...GatsbyImageSharpFluid } } } } `) return ( <Layout> <Container /* Sec2: section1 container */> <Section1 price={1999} productName="HUElight Aroura" productExtension="5 mtr" offer="Buy 4 ang get Rs-250 off" description="HUElite smart strip are energy efficient solution used for wide variety of fixtures and architecture deign to to suite your space. Allows you to control your space from HUElite Smart Mobile app from anywhere in the world. Rich color contast and high brightness led offers you 16 million possiblities to decorate your home and space. Flowing Colors with syncronized group controll gives you immersive experiences." descArray={[ { desc: "Color", value: "Multicolor" }, { desc: "Power and Plug", value: "AC, 180-220V" }, { desc: "Wattage", value: "15 Watts" }, { desc: "Control Interfaces", value: "Mobile Application, Wi-Fi, Google Assistant, Amazon Alexa" }, { desc: "Warranty", value: "1 Year warranty, 14 Days Moneyback Guarantee" }, ]} varient={[{ varientName: "120 led" }, { varientName: "60 led" }]} buyLink="https://www.amazon.in/dp/B08V8JPHN4/ref=twister_B08V81M6J3?_encoding=UTF8&psc=1" data={data} /> </Container> <Section2 /* Sec2: section2 */ sources={[ data.section2Img_mobile.childImageSharp.fluid, { ...data.section2Img.childImageSharp.fluid, media: `(min-width: 576px)`, }, ]} heading1="Your Home," heading2="Your Rules." subText="Now choose your light to make your home cozy, green and awesome" /> <Section3 imgData={data.section3Img1} heading="Adding ambieance to life" subText="with 16 million possiblities, now switch your home ambieance in an instant. go calm to party in seconds" /> <Section3 reverse imgData={data.section3Img2} heading="Bias Lighting" subText="With the right backlighting on your TV, you can now reduce eye strain." /> <Section3 imgData={data.section3Img3} heading="Sleeping Tips" subText="Set your bedroom lights to deep red just before bed to produce more melatonin which helps you get better quality sleep." /> <div className="-mt-50--sm-dn-"></div> <Section2 /* Sec2: section2 */ position="right" sources={[ data.section4Img_mobile.childImageSharp.fluid, { ...data.section4Img.childImageSharp.fluid, media: `(min-width: 576px)`, }, ]} heading1="Your BattleStation is now upgraded for battle." /> <Section2 /* Sec2: section2 */ sources={[ data.section5Img_mobile.childImageSharp.fluid, { ...data.section5Img.childImageSharp.fluid, media: `(min-width: 576px)`, }, ]} heading1="Your Work From Home setup is ready." /> <BlogSection /> <SubscribeSection /> </Layout> ) }
40.063492
208
0.529715
714955d953127c9f5fb12109fdf6eada9be34a41
4,217
rs
Rust
src/auth.rs
flosse/spotify-oauth
914cc8a5e9293b2be726b90f606d2f9e6758e8ed
[ "MIT" ]
null
null
null
src/auth.rs
flosse/spotify-oauth
914cc8a5e9293b2be726b90f606d2f9e6758e8ed
[ "MIT" ]
null
null
null
src/auth.rs
flosse/spotify-oauth
914cc8a5e9293b2be726b90f606d2f9e6758e8ed
[ "MIT" ]
null
null
null
use crate::{generate_random_string, SpotifyResult, SpotifyScope, UrlError, SPOTIFY_AUTH_URL}; use snafu::ResultExt; use std::string::ToString; use url::Url; /// Spotify Authentication /// /// This struct follows the parameters given at [this](https://developer.spotify.com/documentation/general/guides/authorization-guide/ "Spotify Auth Documentation") link. /// ``` pub struct SpotifyAuth { /// The Spotify Application Client ID pub client_id: String, /// The Spotify Application Client Secret pub client_secret: String, /// Required by the Spotify API. pub response_type: String, /// The URI to redirect to after the user grants or denies permission. pub redirect_uri: Url, /// A random generated string that can be useful for correlating requests and responses. pub state: String, /// Vec of Spotify Scopes. pub scope: Vec<SpotifyScope>, /// Whether or not to force the user to approve the app again if they’ve already done so. pub show_dialog: bool, } /// Conversion and helper functions for SpotifyAuth. impl SpotifyAuth { /// Generate a new SpotifyAuth structure from values in memory. /// /// This function loads ``SPOTIFY_CLIENT_ID`` and ``SPOTIFY_REDIRECT_ID`` from values given in /// function parameters. /// /// This function also automatically generates a state value of length 20 using a random string generator. /// /// # Example /// /// ``` /// # use spotify_oauth::{SpotifyAuth, SpotifyScope}; /// // SpotifyAuth with the scope "Streaming". /// let auth = SpotifyAuth::new("00000000000".into(), "secret".into(), "code".into(), "http://localhost:8000/callback".into(), vec![SpotifyScope::Streaming], false); /// # assert_eq!(auth.scope_into_string(), "streaming"); /// ``` pub fn new( client_id: String, client_secret: String, response_type: String, redirect_uri: String, scope: Vec<SpotifyScope>, show_dialog: bool, ) -> Self { Self { client_id, client_secret, response_type, redirect_uri: Url::parse(&redirect_uri).context(UrlError).unwrap(), state: generate_random_string(20), scope, show_dialog, } } /// Concatenate the scope vector into a string needed for the authorization URL. /// /// # Example /// /// ``` /// # use spotify_oauth::{SpotifyAuth, SpotifyScope}; /// // Default SpotifyAuth with the scope "Streaming". /// let auth = SpotifyAuth::new("00000000000".into(), "secret".into(), "code".into(), "http://localhost:8000/callback".into(), vec![SpotifyScope::Streaming], false); /// # assert_eq!(auth.scope_into_string(), "streaming"); /// ``` pub fn scope_into_string(&self) -> String { self.scope .iter() .map(|x| x.clone().to_string()) .collect::<Vec<String>>() .join(" ") } /// Convert the SpotifyAuth struct into the authorization URL. /// /// More information on this URL can be found [here](https://developer.spotify.com/documentation/general/guides/authorization-guide/ "Spotify Auth Documentation"). /// /// # Example /// /// ``` /// # use spotify_oauth::{SpotifyAuth, SpotifyScope}; /// // Default SpotifyAuth with the scope "Streaming" converted into the authorization URL. /// let auth = SpotifyAuth::new("00000000000".into(), "secret".into(), "code".into(), "http://localhost:8000/callback".into(), vec![SpotifyScope::Streaming], false) /// .authorize_url().unwrap(); /// ``` pub fn authorize_url(&self) -> SpotifyResult<String> { let mut url = Url::parse(SPOTIFY_AUTH_URL).context(UrlError)?; url.query_pairs_mut() .append_pair("client_id", &self.client_id) .append_pair("response_type", &self.response_type) .append_pair("redirect_uri", self.redirect_uri.as_str()) .append_pair("state", &self.state) .append_pair("scope", &self.scope_into_string()) .append_pair("show_dialog", &self.show_dialog.to_string()); Ok(url.to_string()) } }
39.411215
170
0.631017
0302fe1a71acf309e102cacbe39d1e06fc755094
41
cpp
C++
GObj.cpp
sparrowflyy/GEngine
06834976289feec202245a7ec44a3c7e8687bb8e
[ "MIT" ]
null
null
null
GObj.cpp
sparrowflyy/GEngine
06834976289feec202245a7ec44a3c7e8687bb8e
[ "MIT" ]
null
null
null
GObj.cpp
sparrowflyy/GEngine
06834976289feec202245a7ec44a3c7e8687bb8e
[ "MIT" ]
null
null
null
#include "GObj.h" #include <iostream>
6.833333
19
0.658537
1a905afc96e78a1e69cec5e56dd4f2b982418ee1
4,707
py
Python
curio-0.8/tests/test_local.py
lleej/python
f4eff76819cec2c479ec19a4940141406079cb9a
[ "MIT" ]
1
2017-10-11T07:15:15.000Z
2017-10-11T07:15:15.000Z
curio-0.8/tests/test_local.py
lleej/python
f4eff76819cec2c479ec19a4940141406079cb9a
[ "MIT" ]
2
2018-02-01T02:54:17.000Z
2018-06-14T03:18:51.000Z
curio-0.8/tests/test_local.py
lleej/python
f4eff76819cec2c479ec19a4940141406079cb9a
[ "MIT" ]
null
null
null
# test_tls.py import pytest from curio import * from threading import Thread # Like run, but unwraps exceptions so pytest can see them properly. # Lets us use assert from inside async functions. def run_with_real_exceptions(*args, **kwargs): try: return run(*args, **kwargs) except TaskError as e: real = e.__cause__ # we can't avoid ending up with real.__context__ == e # and if e.__cause__ = real then we end up with a reference loop that # makes py.test blow up. So we have to None-out e.__cause__. (del is # illegal.) e.__cause__ = None raise real from None def test_smoketest(): local = Local() async def smoketest(): assert local.__dict__ == {} assert vars(local) == {} local.a = 1 assert local.a == 1 assert local.__dict__ == {"a": 1} assert vars(local) == {"a": 1} assert dir(local) == ['a'] del local.a with pytest.raises(AttributeError): local.a with pytest.raises(AttributeError): del local.a assert local.__dict__ == {} assert vars(local) == {} local.__dict__["b"] = 2 assert local.b == 2 run_with_real_exceptions(smoketest()) def test_isolation(): local = Local() event1 = Event() event2 = Event() async def check_isolated_1(): local.a = 1 await event1.set() await event2.wait() assert local.a == 1 async def check_isolated_2(): await event1.wait() # another task has done local.a = 1, but we shouldn't be able to see # it assert not hasattr(local, "a") # Just like our assignment shouldn't be visible to them local.a = 2 await event2.set() async def check_isolated(): for task in [await spawn(check_isolated_1), await spawn(check_isolated_2)]: await task.join() run_with_real_exceptions(check_isolated()) def test_inheritance(): local = Local() event1 = Event() event2 = Event() async def parent(): local.a = "both" assert local.a == "both" child_task = await spawn(child) # now let the child check that it got the value, and try to change it await event1.wait() # child modification shouldn't be visible here assert local.a == "both" # and now check that the child can't see our change local.a = "parent" await event2.set() await child_task.join() async def child(): assert local.a == "both" local.a = "child" assert local.a == "child" await event1.set() await event2.wait() assert local.a == "child" run_with_real_exceptions(parent()) def test_nested_curio(): # You should never do this. But that doesn't mean it should crash. # Well, actually it probably should crash. local = Local() async def inner(): assert not hasattr(local, "a") local.a = "inner" assert local.a == "inner" async def outer(): local.a = "outer" with pytest.raises(RuntimeError): run_with_real_exceptions(inner()) run_with_real_exceptions(outer()) def test_within_thread(): local = Local() async def parent(parent_data): async def child(data): local.data = data await sleep(0) assert local.parent == parent_data # inherited assert local.data == data local.parent = parent_data tasks = [] for data in range(8): tasks.append(await spawn(child, data)) for t in tasks: await t.join() exceptions = [] def run_capturing_exceptions(*args, **kwargs): try: run_with_real_exceptions(*args, **kwargs) except Exception as e: nonlocal exceptions exceptions.append(e) threads = [Thread(target=run_capturing_exceptions, args=(parent(data),)) for data in range(8)] for t in threads: t.start() for t in threads: t.join() if exceptions: raise exceptions.pop() def test_outside_context(kernel): # Test what happens if you access locals in environment where no task is running right now local = Local() t1 = None async def inner(): assert not hasattr(local, "a") local.a = "inner" assert local.a == "inner" await sleep(1) async def main(): nonlocal t1 t1 = await spawn(inner) await t1.join() kernel.run(main()) with pytest.raises(RuntimeError): local.a
26.005525
94
0.581474
742a44918b8132ebb0910d689a42aaa184db4a6c
4,314
css
CSS
src/style.css
brahimdidi/Leaderboard-setup-project
f39d8e46e91bcd30cbcf50f4fa92432ff6a36dde
[ "MIT" ]
null
null
null
src/style.css
brahimdidi/Leaderboard-setup-project
f39d8e46e91bcd30cbcf50f4fa92432ff6a36dde
[ "MIT" ]
null
null
null
src/style.css
brahimdidi/Leaderboard-setup-project
f39d8e46e91bcd30cbcf50f4fa92432ff6a36dde
[ "MIT" ]
null
null
null
* { margin: 0; padding: 0; box-sizing: border-box; list-style: none; text-transform: capitalize; } body { background: linear-gradient(to left, #333, #333 50%, #eee 75%, #333 75%); } #main { display: flex; margin: 0 auto; width: 91%; } .title { font-size: 390%; font-weight: bold; padding: 20px; display: flex; justify-content: center; margin-top: 2%; font-family: 'Calligraffitti', cursive; } .title, .add-your-score, .recent-scores { color: whitesmoke; } .container { width: 80vw; height: 70vh; max-height: 700px; display: flex; gap: 15%; } .list-container { width: 30%; height: auto; } .rs-list { margin-top: 20px; border: 2px solid whitesmoke; border-radius: 5px; transition: 0.9s ease-in; width: 75%; background: linear-gradient(to left, #333, #333 50%, #eee 75%, #333 75%); } .name-score { font-size: 24px; padding: 2px; display: flex; justify-content: space-between; align-items: center; color: rgb(17, 10, 10); font-weight: bold; } .name-score:nth-child(even) { background: unset; } .name-score:nth-child(odd) { background-color: unset; } .form { width: 35%; height: 40%; display: flex; flex-direction: column; gap: 5%; } input { width: 60%; height: 80px; border: 2px solid black; padding-inline-start: 3%; border-radius: 17px; background-color: black; font-weight: 300; font-size: 29px; color: white; } .submit { display: flex; width: 90px; margin-left: 40%; justify-content: center; cursor: pointer; padding: 20px; height: 35px; font-weight: bold; font-size: 20px; border: 2px solid black; align-items: center; } .footer { position: fixed; bottom: 0; left: 0; right: 0; height: 7%; width: 100%; background: linear-gradient(to left, #333, #333 50%, #eee 75%, #333 75%); } .refresh { display: flex; width: 25%; justify-content: center; cursor: pointer; padding: 3%; height: 35px; font-weight: bold; font-size: 1rem; border: 2px solid black; align-items: center; } .recent-scores { width: 80%; font-size: 2rem; font-weight: bold; font-family: 'Calligraffitti', cursive; } .name { color: whitesmoke; background-color: #333; } .score { color: red; background-color: #333; } .rs-div { display: flex; width: 80%; height: 49px; align-items: center; } .add-your-score { font-size: 40px; font-weight: bold; display: flex; font-family: 'Calligraffitti', cursive; } .bamo { display: flex; justify-content: center; align-items: center; font-size: 3rem; color: whitesmoke; font-weight: bold; } button { font-family: 'fantasy', cursive; border-radius: 10px; background-color: black; color: #eee; } button:hover { background-color: #eee; color: black; font-weight: bold; transition: 0.3s ease-in-out; } input::placeholder { color: #eee; font-weight: 300; font-size: 27px; } /* for mobile and tablet version */ @media screen and (max-width: 1200px) { .list-container, .form { width: 50%; } .refresh { width: 34%; } } @media screen and (max-width: 700px) { #main { flex-direction: column; width: 90%; } .title { font-size: 2.5rem; display: flex; justify-content: center; padding: 2%; } .container { flex-direction: column; width: 100%; gap: 3%; } .list-container { flex-direction: column; display: flex; width: 100%; } .rs-div, .rs-list, .form { width: 80%; margin: 0 auto; } .recent-scores, .add-your-score { font-size: 1.6rem; background-color: #333; } .form { gap: 4%; height: 20vh; } input { width: 100%; height: 40px; border-radius: 9px; } .submit { width: 50%; height: 12%; margin: 0 auto; padding: 3%; } .footer { display: none; } } @media screen and (max-height: 840px) { .title { margin-top: 1%; padding: 1%; font-size: 2.2rem; } .container { margin-top: 1%; } } @media screen and (min-width: 700px) { .rs-list { display: flex; width: 100%; max-height: 600px; flex-direction: column; flex-wrap: wrap; padding: 2%; } .container { width: 70%; } .list-container { width: 100%; } .form { gap: 10px; } }
14.428094
75
0.600139
2162e37b64510d6f7f04b7579773fad6f1a716cf
1,944
js
JavaScript
app/containers/Pages/Dashboard/Main/ControlUser/ControlUserModal.js
artur-master/ssilva-front-end
52329d4187afd56f5fb9cf1df04ab5a0df40f050
[ "MIT" ]
null
null
null
app/containers/Pages/Dashboard/Main/ControlUser/ControlUserModal.js
artur-master/ssilva-front-end
52329d4187afd56f5fb9cf1df04ab5a0df40f050
[ "MIT" ]
2
2020-06-28T00:18:21.000Z
2021-09-03T03:01:40.000Z
app/containers/Pages/Dashboard/Main/ControlUser/ControlUserModal.js
artur-master/ssilva-front-end
52329d4187afd56f5fb9cf1df04ab5a0df40f050
[ "MIT" ]
1
2022-02-02T20:26:50.000Z
2022-02-02T20:26:50.000Z
/** * * Restriction * */ import React from 'react'; import PropTypes from 'prop-types'; import { Modal, ModalBody, ModalFooter, ModalHeader } from 'components/Modal'; import Button from 'components/Button'; import Thead from 'components/Table/Thead'; import ControlUItem from './ControlUserItem'; export function ControlUserModal({ ControlUserItems, onHide, isOpen = false, query, onQuery }) { return ( <> <Modal isOpen={isOpen} size="xl" scrollable > <ModalHeader>Control de Usuarios</ModalHeader> <ModalBody className=""> <table className="table table-responsive-sm table-fixed table-sm m-0 border-bottom"> <Thead ths={[ { field: 'UserName', label: 'Nombre', sortable: true }, { field: 'Role', label: 'Rol', className: "pl-3", sortable: true }, { field: 'Pendientes', label: 'Pendientes', sortable: true }, { field: 'Dias', label: 'Días atraso', sortable: true }, { field: 'Average', label: 'Atraso promedio',sortable: true }, { field: '', label: '' }, ]} onQuery={onQuery} query={query} /> <tbody> {ControlUserItems && ( ControlUserItems.map((useraction, index) => ( <ControlUItem key={index} userAction={useraction} /> )) )} </tbody> </table> {/* <SyncMessage {...restSelector} /> */} </ModalBody> <ModalFooter> <Button color="white" onClick={onHide}> Volver </Button> </ModalFooter> </Modal> </> ); } ControlUserModal.propTypes = { ControlUserItems: PropTypes.oneOfType([PropTypes.bool, PropTypes.array]), onHide: PropTypes.func, isOpen: PropTypes.bool, }; export default ControlUserModal;
29.907692
96
0.545267
1a572274b15de5a4099b3e316811e7da64b6d960
1,600
py
Python
lab-04-3-file_input_linear_regression.py
KANG91/Deep_Learning
e3e9de769ab835215d0ebeee79ff869afbe64ebf
[ "MIT" ]
null
null
null
lab-04-3-file_input_linear_regression.py
KANG91/Deep_Learning
e3e9de769ab835215d0ebeee79ff869afbe64ebf
[ "MIT" ]
null
null
null
lab-04-3-file_input_linear_regression.py
KANG91/Deep_Learning
e3e9de769ab835215d0ebeee79ff869afbe64ebf
[ "MIT" ]
null
null
null
# Lab 4 Multi-variable linear regression import tensorflow as tf import numpy as np tf.set_random_seed(777) # for reproducibility xy = np.loadtxt('data-01-test-score.csv', delimiter=',', dtype=np.float32) x_data = xy[:, 0:-1] y_data = xy[:, [-1]] # Make sure the sape and data are OK print(x_data.shape, x_data, len(x_data)) print(y_data.shape, y_data) # placeholders for a tensor that will be always fed. X = tf.placeholder(tf.float32, shape=[None, 3]) Y = tf.placeholder(tf.float32, shape=[None, 1]) W = tf.Variable(tf.random_normal([3, 1]), name='weight') b = tf.Variable(tf.random_normal([1]), name='bias') # Hypothesis hypothesis = tf.matmul(X, W) + b # Simplified cost function cost = tf.reduce_mean(tf.square(hypothesis - Y)) # Minimize optimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5) train = optimizer.minimize(cost) # Launch the graph in a session. sess = tf.Session() # Initializes global variables in the graph. sess.run(tf.global_variables_initializer()) for step in range(2001): feed = {X: x_data, Y: y_data} sess.run(train, feed_dict=feed) if step % 10 == 0: print(step, "Cost: ", sess.run(cost, feed_dict=feed), "\nPrediction:\n", sess.run(hypothesis, feed_dict=feed)) # Ask my score score = np.array([[100, 70, 101]]) print("Your score will be ", sess.run(hypothesis, feed_dict={X: score})) score = np.array([[60, 70, 110], [90, 100, 80]]) print("Other scores will be ", sess.run(hypothesis, feed_dict={X: score})) ''' Your score will be [[ 181.73277283]] Other scores will be [[ 145.86265564] [ 187.23129272]] '''
28.571429
74
0.68875
0d48958671e3200354cab400ce1d8cd07a06be02
7,710
cs
C#
ctlTopMenuN.ascx.cs
richardreamz/rentaboat
210441dbe0ab1082ef6c3aae49264fb3da6d20a5
[ "Apache-2.0" ]
null
null
null
ctlTopMenuN.ascx.cs
richardreamz/rentaboat
210441dbe0ab1082ef6c3aae49264fb3da6d20a5
[ "Apache-2.0" ]
null
null
null
ctlTopMenuN.ascx.cs
richardreamz/rentaboat
210441dbe0ab1082ef6c3aae49264fb3da6d20a5
[ "Apache-2.0" ]
null
null
null
using Microsoft.VisualBasic; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls; using System.Text; public partial class ctlTopMenu : System.Web.UI.UserControl { [WebMethod] public static string ValidateLogin(string username, string password) { DataTable dt = Util.getDataSet("execute SP_BR_USER_LOGIN @p_vc_userName='" + username + "' , @p_vc_password='" + password + "'").Tables[0]; if (dt.Rows.Count > 0) return "Success"; else return "Failed"; } private void RegisterStartupScript(string url) { // String csname1 = "PopupScript"; String csname2 = "ButtonClickScript"; Type cstype = this.GetType(); StringBuilder cstext2 = new StringBuilder(); cstext2.Append("<script type=\"text/javascript\"> {"); cstext2.Append("window.location =" + url+ " } </"); cstext2.Append("script>"); Page.ClientScript.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false); } protected void btnSignIn_Click(object sender, EventArgs e) { DataTable dt = Util.getDataSet("execute SP_BR_USER_LOGIN @p_vc_userName='" + txtLoginName.Text.Trim() + "' , @p_vc_password='" + txtPassword.Text.Trim() + "'").Tables[0]; try { if (dt.Rows.Count > 0) { String currentPage = HttpContext.Current.Request.Url.AbsolutePath; String dotNET = Strings.Right(currentPage, 1); String dotNETdb = Strings.Right(Convert.ToString(dt.Rows[0]["vc_defaultHomePage"].ToString()), 1); if (dotNET == dotNETdb) { dotNET = ""; } Session.Add("userID", dt.Rows[0]["in_userID"].ToString()); Session.Add("userLevelID", dt.Rows[0]["in_userLevelID"].ToString()); Session.Add("MarinaID", dt.Rows[0]["in_MarinaID"].ToString()); Session.Add("BusinessName", dt.Rows[0]["vc_BusinessName"].ToString()); Session.Add("defaultPage", "admin/" + Convert.ToString(dt.Rows[0]["vc_defaultHomePage"].ToString()) + dotNET); Session.Add("userName", dt.Rows[0]["vc_username"].ToString()); lnkUsername.Text = Session["userName"].ToString() + "&nbsp;&nbsp;"; lblLoginLogout.Text = "Sign out"; if (dt.Rows[0]["in_userLevelID"].ToString() == "4") { Session["ClientID"] = Util.getClientIDFromUserID(dt.Rows[0]["in_userID"].ToString()); Response.Redirect("UpdateClientInfo.aspx", true); } // else // Response.Redirect(Convert.ToString(Session["defaultPage"])); else if (Session["userLevelID"].ToString() == "1") Response.Redirect("~/admin/facilities_list.aspx"); else if (Session["userLevelID"].ToString() == "2" || Session["userLevelID"].ToString() == "3") { // Session["marinaID"].ToString() if (IsProfileComplete()) { // Server.Transfer(ResolveUrl("~/admin/FacilityCalendarView.aspx")); Page.Response.Redirect( ResolveUrl("~/admin/FacilityCalendarView.aspx"), false); // Context.ApplicationInstance.CompleteRequest(); Response.End(); // Context.ApplicationInstance.CompleteRequest(); // RegisterStartupScript(ResolveUrl("~/admin/FacilityCalendarView.aspx")); return; } else { Response.Redirect("~/admin/Facilities_mant.aspx", false); // Context.ApplicationInstance.CompleteRequest(); // Response.End(); return; } } } } catch(Exception ex) { } } private bool IsProfileComplete() { bool complete = true; DataTable dtC = Util.getDataSet("execute usp_is_profile_complete @marinaID=" + Session["MarinaID"].ToString()).Tables[0]; if (dtC.Rows.Count == 0) complete = false; return complete; } protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["userID"] != null && Session["userID"].ToString() != "") { lblLoginLogout.Text = "Sign out"; if (Session["userName"] != null) lnkUsername.Text = Session["userName"].ToString() + "&nbsp;&nbsp;"; } else { lblLoginLogout.Text = "Sign in"; } string CtrlID = Request.Form["__EVENTTARGET"]; if (CtrlID != null && CtrlID.Contains("btnSignIn")) { if (lblLoginLogout.Text == "Sign in") btnSignIn_Click(this, null); else { //Sign out Session.Clear(); lblLoginLogout.Text = "Sign in"; Response.Redirect("index.aspx"); } } } //else //{ // if (Session["loginRequested"] != null) else { string CtrlID = Request.Form["__EVENTTARGET"]; if (CtrlID != null && CtrlID.Contains("btnSignIn")) { if (lblLoginLogout.Text == "Sign in") btnSignIn_Click(this, null); else { //Sign out Session.Clear(); lblLoginLogout.Text = "Sign in"; Response.Redirect("index.aspx"); } } } if (Session["userName"] !=null) { lnkUsername.Text = Session["userName"].ToString() + "&nbsp;&nbsp;"; lblLoginLogout.Text = "Sign out"; Session["loginRequested"] = null; } // } } public void checkLogin() { if (Session["userName"] != null) { lnkUsername.Text = Session["userName"].ToString() + "&nbsp;&nbsp;"; lblLoginLogout.Text = "Sign out"; Session["loginRequested"] = null; } // uplLogin.Update(); } protected void lnkUsername_Click(object sender, EventArgs e) { if (Session["userLevelID"].ToString() == "4") { Response.Redirect("~/UpdateClientInfo.aspx"); /// Response.Redirect("UpdateClientInfo.aspx"); } else if (Session["userLevelID"].ToString() == "1") Response.Redirect("~/admin/facilities_list.aspx"); else if (Session["userLevelID"].ToString() == "2" || Session["userLevelID"].ToString() == "3") { // Session["marinaID"].ToString() if (IsProfileComplete()) Response.Redirect("~/admin/FacilityCalendarView.aspx"); else Response.Redirect("~/admin/Facilities_mant.aspx"); } } }
27.833935
179
0.490791
dd79066518788e82799304761ae334e2e311bc22
4,318
java
Java
drools-ruleunit/src/main/java/org/drools/ruleunit/RuleUnitExecutor.java
targeter21/drools
83923adc5d2483303d0f402de3c20171abcdcc88
[ "Apache-2.0" ]
5
2016-07-31T17:00:18.000Z
2022-01-11T04:34:29.000Z
drools-ruleunit/src/main/java/org/drools/ruleunit/RuleUnitExecutor.java
targeter21/drools
83923adc5d2483303d0f402de3c20171abcdcc88
[ "Apache-2.0" ]
5
2017-11-08T14:08:38.000Z
2018-07-02T14:49:23.000Z
drools-ruleunit/src/main/java/org/drools/ruleunit/RuleUnitExecutor.java
targeter21/drools
83923adc5d2483303d0f402de3c20171abcdcc88
[ "Apache-2.0" ]
1
2019-10-18T09:35:54.000Z
2019-10-18T09:35:54.000Z
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.ruleunit; import org.kie.api.KieBase; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.KieSessionConfiguration; /** * RuleUnitExecutor allows to execute different {@link RuleUnit}s. */ public interface RuleUnitExecutor { /** * Bind this executor to a {@link KieBase} in order to execute the units defined in it. */ RuleUnitExecutor bind( KieBase kiebase ); /** * Returns the {@link KieSession} internally used by this executor. */ KieSession getKieSession(); /** * Runs a RuleUnit of the given class. */ int run( Class<? extends RuleUnit> ruleUnitClass ); /** * Runs a RuleUnit of the given class. */ int run( RuleUnit ruleUnit ); /** * Runs until halt a RuleUnit of the given class. */ void runUntilHalt( Class<? extends RuleUnit> ruleUnitClass ); /** * Runs until halt a RuleUnit of the given class. */ void runUntilHalt( RuleUnit ruleUnit ); /** * Requests the executor to stop running units. */ void halt(); /** * Creates a DataSource, optionally containing some items, and bind it this executor with the given name. * * @param name the name with which the newly created DataSource will be bound to this executor. * @param items the items contained in the DataSource. */ <T> DataSource<T> newDataSource( String name, T... items ); /** * Binds a variable to this executor with a given name. This named variable will be then injected into * {@link RuleUnit}s executed on this executor using a naming convention. * * @param name the name with which the value will be bound to this executor. * @param value the value to bind. */ RuleUnitExecutor bindVariable(String name, Object value); /** * Releases all the current executor resources, setting up the session for garbage collection. * This method <b>must</b> always be called after finishing using the executor, or the engine * will not free the memory used by the executor. */ void dispose(); static RuleUnitExecutor newRuleUnitExecutor( KieContainer kieContainer ) { return create( kieContainer.newKieSession() ); } static RuleUnitExecutor newRuleUnitExecutor(KieContainer kieContainer, KieSessionConfiguration conf) { return create( kieContainer.newKieSession( conf ) ); } static RuleUnitExecutor newRuleUnitExecutor(KieContainer kieContainer, String kSessionName) { return create( kieContainer.newKieSession( kSessionName ) ); } static RuleUnitExecutor newRuleUnitExecutor(KieContainer kieContainer, String kSessionName, KieSessionConfiguration conf) { return create( kieContainer.newKieSession( kSessionName, conf ) ); } /** * Creates a brand new RuleUnitExecutor */ static RuleUnitExecutor create() { try { return ( RuleUnitExecutor ) Class.forName( "org.drools.ruleunit.executor.RuleUnitExecutorSession" ).newInstance(); } catch (Exception e) { throw new RuntimeException("Unable to instance RuleUnitExecutor", e); } } /** * Creates a brand new RuleUnitExecutor */ static RuleUnitExecutor create(KieSession kieSession) { try { return ( RuleUnitExecutor ) Class.forName( "org.drools.ruleunit.executor.RuleUnitExecutorSession" ) .getConstructor( KieSession.class ).newInstance( kieSession ); } catch (Exception e) { throw new RuntimeException("Unable to instance RuleUnitExecutor", e); } } }
34
127
0.680871
1f38170082d41c496234138ae62d2150290fdf8d
2,809
cs
C#
Db/DbConnectionWrapper.cs
codeex/MmWizard
43c86cc8121c36900fdd3133b4ede16cee078b76
[ "Apache-2.0" ]
1
2018-12-13T08:38:30.000Z
2018-12-13T08:38:30.000Z
Db/DbConnectionWrapper.cs
codeex/MmWizard
43c86cc8121c36900fdd3133b4ede16cee078b76
[ "Apache-2.0" ]
1
2018-09-18T05:12:53.000Z
2018-09-18T05:12:53.000Z
Db/DbConnectionWrapper.cs
codeex/MmWizard
43c86cc8121c36900fdd3133b4ede16cee078b76
[ "Apache-2.0" ]
null
null
null
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace MmWizard.Db { public partial class DbConnectionWrapper :IDisposable { public DbConnectionWrapper(DbConnectionManager manager, DbConnection conn) { this._manager = manager; this._dbConn = conn; LastAccessed = DateTime.Now; InitThreadInfo(); } private DbConnectionManager _manager; private DbConnection _dbConn; private int _refCount = 0; public DbConnection Conn { get { this.MarkAccessed(); Trace.WriteLine($"db connection in {ThreadInfo.ThreadId}:{ThreadInfo.ThreadName},ref={RefCount}"); return _dbConn; } } /// <summary> /// 线程信息 /// </summary> public ThreadInfo ThreadInfo { get; private set; } private void InitThreadInfo() { this.ThreadInfo = new ThreadInfo { ThreadId = Thread.CurrentThread.ManagedThreadId, ThreadName = Thread.CurrentThread.Name }; } /// <summary> /// 引用计数 /// </summary> public int RefCount => _refCount; /// <summary> /// 修改最后访问时间 /// </summary> private void MarkAccessed() { LastAccessed = DateTime.Now; } public void MarkRefUsed() { MarkAccessed(); InitThreadInfo(); Interlocked.Increment(ref _refCount); } /// <summary> /// 空闲时间超过给定时间 /// </summary> /// <param name="timeout">秒</param> /// <returns>空闲</returns> public bool IdleTime(int timeout) { return (DateTime.Now - LastAccessed).TotalSeconds >= timeout; } /// <summary> /// 连接是否可用 /// </summary> /// <returns></returns> public bool CanUse() { return this._dbConn?.State.HasFlag(ConnectionState.Open) ?? false; } public DateTime LastAccessed { get; set; } public void Dispose() { Interlocked.Decrement(ref _refCount); this._manager?.ReleaseConn(this); if(this._manager == null) { try { this._dbConn?.Close(); } catch { } } } } /// <summary> /// 线程信息 /// </summary> public class ThreadInfo { public int ThreadId { get; set; } public string ThreadName { get; set; } } }
25.536364
114
0.509078
1a8192bd8c9dab60171b03fa4617f751ef122505
595
cs
C#
src/MariGlobals/Logger/Entities/MariEventLogMessage.cs
MariBotOfficial/MariGlobals
9b169f618aeb715d7d8cafaa899af1140adefa5e
[ "MIT" ]
null
null
null
src/MariGlobals/Logger/Entities/MariEventLogMessage.cs
MariBotOfficial/MariGlobals
9b169f618aeb715d7d8cafaa899af1140adefa5e
[ "MIT" ]
3
2020-10-11T19:35:12.000Z
2021-06-25T15:44:53.000Z
src/MariGlobals/Logger/Entities/MariEventLogMessage.cs
MariBotOfficial/MariGlobals
9b169f618aeb715d7d8cafaa899af1140adefa5e
[ "MIT" ]
1
2021-03-10T17:38:09.000Z
2021-03-10T17:38:09.000Z
using Microsoft.Extensions.Logging; using System; namespace MariGlobals.Logger.Entities { public readonly struct MariEventLogMessage { internal MariEventLogMessage(string message, string sectionName, LogLevel logLevel, Exception exception) { Message = message; SectionName = sectionName; LogLevel = logLevel; Exception = exception; } public string Message { get; } public string SectionName { get; } public LogLevel LogLevel { get; } public Exception Exception { get; } } }
24.791667
112
0.631933
f68cb6bbc5f036370324a7d621a4a7c4a6b1c613
856
dart
Dart
test/website_request_test.dart
ezmaxinc/eZmax-SDK-dart
5a02736620b669bc492c504be9dd3fc344a39505
[ "MIT" ]
null
null
null
test/website_request_test.dart
ezmaxinc/eZmax-SDK-dart
5a02736620b669bc492c504be9dd3fc344a39505
[ "MIT" ]
null
null
null
test/website_request_test.dart
ezmaxinc/eZmax-SDK-dart
5a02736620b669bc492c504be9dd3fc344a39505
[ "MIT" ]
null
null
null
// // AUTO-GENERATED FILE, DO NOT MODIFY! // // @dart=2.12 // ignore_for_file: unused_element, unused_import // ignore_for_file: always_put_required_named_parameters_first // ignore_for_file: constant_identifier_names // ignore_for_file: lines_longer_than_80_chars import 'package:openapi/api.dart'; import 'package:test/test.dart'; // tests for WebsiteRequest void main() { // final instance = WebsiteRequest(); group('test WebsiteRequest', () { // The unique ID of the Websitetype. Valid values: |Value|Description| |-|-| |1|Website| |2|Twitter| |3|Facebook| |4|Survey| // int fkiWebsitetypeID test('to test the property `fkiWebsitetypeID`', () async { // TODO }); // The URL of the website. // String sWebsiteAddress test('to test the property `sWebsiteAddress`', () async { // TODO }); }); }
24.457143
130
0.679907
142531f497c002c0bd57373e04baaec02257a5aa
317
ts
TypeScript
src/1925.count-square-sum-triples.2037/1925.count-square-sum-triples.2037.ts
jiangshanmeta/meta
8f9d084cda91988d42208ac7a029612e9edc693b
[ "MIT" ]
221
2018-10-26T07:05:12.000Z
2022-03-30T03:23:10.000Z
src/1925.count-square-sum-triples.2037/1925.count-square-sum-triples.2037.ts
ralap18/meta
82d660a6eabb15e398a7dcc2a0fa99342143bb12
[ "MIT" ]
23
2018-09-24T14:50:58.000Z
2020-09-17T14:23:45.000Z
src/1925.count-square-sum-triples.2037/1925.count-square-sum-triples.2037.ts
ralap18/meta
82d660a6eabb15e398a7dcc2a0fa99342143bb12
[ "MIT" ]
45
2019-03-29T03:36:19.000Z
2022-03-25T20:57:13.000Z
function countTriples (n: number): number { let result = 0; for (let i = 1; i < n; i++) { for (let j = i + 1; j < n; j++) { const c = Math.sqrt(i * i + j * j); if (Number.isInteger(c) && c <= n) { result += 2; } } } return result; }
24.384615
48
0.388013
b888128432b7d4e7b3cb42dc42f7909dd410c1b5
465
h
C
Inc/freertos_vars.h
wanglong1107/foc_one
eec987574c39f6d727bcb50bc4c292c395202aec
[ "MIT" ]
null
null
null
Inc/freertos_vars.h
wanglong1107/foc_one
eec987574c39f6d727bcb50bc4c292c395202aec
[ "MIT" ]
null
null
null
Inc/freertos_vars.h
wanglong1107/foc_one
eec987574c39f6d727bcb50bc4c292c395202aec
[ "MIT" ]
null
null
null
/* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __FREERTOS_H #define __FREERTOS_H // List of semaphore extern osSemaphoreId sem_usb_irq; extern osSemaphoreId sem_uart_dma; extern osSemaphoreId sem_usb_rx; extern osSemaphoreId sem_usb_tx; // List of threads extern osThreadId thread_motor_0; extern osThreadId thread_motor_1; extern osThreadId thread_cmd_parse; extern osThreadId thread_usb_pump; #endif /* __FREERTOS_H */
27.352941
80
0.765591
ecdf9999a3e8437774e7676c7cffd039617548ef
459
swift
Swift
AlgunLayout/AlgunLayout/ViewController.swift
DonMag/AlgunLayout
42ce41a122e038b0edafaf308aaed3bf5e596520
[ "MIT" ]
null
null
null
AlgunLayout/AlgunLayout/ViewController.swift
DonMag/AlgunLayout
42ce41a122e038b0edafaf308aaed3bf5e596520
[ "MIT" ]
null
null
null
AlgunLayout/AlgunLayout/ViewController.swift
DonMag/AlgunLayout
42ce41a122e038b0edafaf308aaed3bf5e596520
[ "MIT" ]
null
null
null
// // ViewController.swift // AlgunLayout // // Created by Don Mag on 8/8/17. // Copyright © 2017 DonMag. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var theWhiteView: UIView! @IBOutlet weak var theWhiteViewWidth: NSLayoutConstraint! @IBAction func doGrow(_ sender: Any) { theWhiteViewWidth.constant += 10 } @IBAction func doShrink(_ sender: Any) { theWhiteViewWidth.constant -= 10 } }
17.653846
58
0.714597
388e5207a0370a1e022c2e8d4f41e77920e9dbda
2,070
ctp
PHP
app/View/Elements/pagination.ctp
muisit/comanage-registry
e30bcca10bedd4c817debf2f30252d4c729034e0
[ "Apache-2.0" ]
null
null
null
app/View/Elements/pagination.ctp
muisit/comanage-registry
e30bcca10bedd4c817debf2f30252d4c729034e0
[ "Apache-2.0" ]
null
null
null
app/View/Elements/pagination.ctp
muisit/comanage-registry
e30bcca10bedd4c817debf2f30252d4c729034e0
[ "Apache-2.0" ]
null
null
null
<?php /** * COmanage Registry CO Bread Crumb * * Portions licensed to the University Corporation for Advanced Internet * Development, Inc. ("UCAID") under one or more contributor license agreements. * See the NOTICE file distributed with this work for additional information * regarding copyright ownership. * * UCAID 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. * * @link http://www.internet2.edu/comanage COmanage Project * @package registry * @since COmanage Registry v0.9.4 * @license Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) */ ?> <div id="pagination"> <span class="paginationCounter"> <?php // pagination information print $this->Paginator->counter(array( 'format' => _txt('in.pagination.format') )); ?> </span> <?php if($this->paginator->hasPage(2)): ?> <span class="paginationPrev"> <?php // Shows the previous link print $this->Paginator->prev( _txt('op.previous'), null, null, array('class' => 'disabled') ); ?> </span> <span class="paginationNumbers"> <?php // Shows the page numbers print $this->Paginator->numbers(); ?> </span> <span class="paginationNext"> <?php // Shows the next link print $this->Paginator->next( _txt('op.next'), null, null, array('class' => 'disabled') ); ?> </span> <?php endif; ?> </div>
29.571429
90
0.619324
da66fdaa1d22d2eba827ba4399f52476c2b31868
7,409
php
PHP
resources/views/transfers/transferForm.blade.php
P-Sintija/mini-bank
1dde7ea4739d891df062a8907decbd895d3288e4
[ "MIT" ]
null
null
null
resources/views/transfers/transferForm.blade.php
P-Sintija/mini-bank
1dde7ea4739d891df062a8907decbd895d3288e4
[ "MIT" ]
null
null
null
resources/views/transfers/transferForm.blade.php
P-Sintija/mini-bank
1dde7ea4739d891df062a8907decbd895d3288e4
[ "MIT" ]
null
null
null
@extends('layout') @section('content') <div class="h-screen w-full flex overflow-hidden"> <nav class="flex flex-col bg-gray-200 dark:bg-gray-900 w-64 px-12 pt-4 pb-6"> <!-- SideNavBar --> <div class="mt-8"> <img class="h-26 w-26 rounded-full object-cover" src="/logo.jpg" alt="?"/> </div> <!-- Back Logout --> <div class="mt-auto flex items-center text-green-700 dark:text-green-400"> <form method="GET" action="{{ route('basicAccount.index',['id' => $account->id]) }}"> <button type="submit" class="flex items-center"> <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2M3 12l6.414 6.414a2 2 0 001.414.586H19a2 2 0 002-2V7a2 2 0 00-2-2h-8.172a2 2 0 00-1.414.586L3 12z"/> </svg> <span class="ml-2 capitalize font-medium">Back to account</span> </button> </form> </div> </nav> <!-- main --> <main class="flex-1 flex flex-col bg-gray-100 dark:bg-gray-700 transition duration-500 ease-in-out overflow-y-auto"> <!-- header--> <div class="mx-10 my-2"> <span class="my-4 text-4xl font-semibold dark:text-gray-400"> {{ $account->name }} {{$account->surname}} </span> <span class=" text-4xl font-semibold text-green-600 dark:text-green-300"> ( {{$account->User_ID}} ) </span> </div> <!-- session/errors --> @if ($errors->any()) <div class="mx-10 my-2"> <div class="mt-2 flex px-4 py-4 justify-between bg-red-50 dark:bg-gray-600 shadow-xl rounded-lg cursor-pointer "> <!-- Card --> <div class="bg-red-50 p-4 rounded flex items-start text-red-600 "> <div class="text-lg"> <svg xmlns="http://www.w3.org/2000/svg" class="fill-current w-5 pt-1" viewBox="0 0 24 24"> <path d="M12 0c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm-1.959 17l-4.5-4.319 1.395-1.435 3.08 2.937 7.021-7.183 1.422 1.409-8.418 8.591z"/> </svg> </div> <div class=" px-3"> <h3 class="text-red-800 font-semibold tracking-wider"> Error </h3> @foreach ($errors->all() as $error) <p class="py-2 text-red-700"> {{ $error }} </p> @endforeach </div> </div> </div> </div> @endif <!-- info --> <div class="mx-10 my-2"> <!-- Form --> <div class="mt-8 flex justify-between bg-white dark:bg-gray-600 shadow-xl rounded-lg cursor-pointer"> <div class=" flex flex-col items-center justify-center"> <form id="form" class="bg-white rounded-lg px-8 pt-6 pb-8 mb-4 " method="POST" action="{{ route('transferInfo.inform',['id' => $account->id]) }}"> @csrf <h1 class=" flex capitalize text-2xl text-gray-600 dark:text-gray-400"> Transfer to another account </h1> <h1 class=" flex capitalize text-m text-gray-600 dark:text-gray-400"> Balance: {{ number_format($account->balance / 100, 2) }} {{ $account->currency }} </h1> <br> <div class="mb-4"> <label class="block text-gray-700 text-sm font-bold mb-2" for="name"> Name </label> <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" name="name" id="name" type="text" placeholder="Name"> </div> <div class="mb-4"> <label class="block text-gray-700 text-sm font-bold mb-2" for="surname"> Surname </label> <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" name="surname" id="surname" type="text" placeholder="Surname"> </div> <div class="mb-4"> <label class="block text-gray-700 text-sm font-bold mb-2" for="account_number"> Account number </label> <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" name="account_number" id="account_number" type="text" placeholder="Account number"> </div> <div class="mb-4"> <label class="block text-gray-700 text-sm font-bold mb-2" for="amount"> Amount </label> <input class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" name="amount" id="amount" type="text" placeholder="Amount"> </div> <div class="flex items-center justify-between"> <button class="bg-green-700 hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" id="submit" type="submit"> Check transaction </button> </div> </form> </div> </div> </div> </main> </div> @endsection
55.291045
114
0.405993
0147c28364ceb78ae8105ba31428b2d91ea33962
3,824
rb
Ruby
app/models/c80_map/map_json.rb
c80609a/c80_map
ebfbda6a5db517b4b571765a3804e546cbe6a999
[ "MIT" ]
null
null
null
app/models/c80_map/map_json.rb
c80609a/c80_map
ebfbda6a5db517b4b571765a3804e546cbe6a999
[ "MIT" ]
null
null
null
app/models/c80_map/map_json.rb
c80609a/c80_map
ebfbda6a5db517b4b571765a3804e546cbe6a999
[ "MIT" ]
null
null
null
module C80Map class MapJson < ActiveRecord::Base # этот метод вызовается после update Area def self.update_json locations_path = Rails.root.join("public", "locations.json") locs = File.read(locations_path) # puts "<MapJson.update_json> #{ Rails.root.join("public", "locations.json") }" locs_hash = JSON.parse(locs) # обходим все Building и составляем массив вида # [{id, object_type=object_type, coords, building_hash, img, childs:[<areas>]},..] buildings_to_location_json = [] Building.all.each do |b| # Rails.logger.debug "[TRACE] <MapJson.update_json> building: #{b}; building_representator: #{b.building_representator}" # сначала соберём детей - Area childs = [] b.areas.each do |area| # Rails.logger.debug "[TRACE] <MapJson.update_json> [1] area #{area}; area_representator: #{area.area_representator}" # соберём хэш привязанной к полигону площади har = {} if area.area_representator.present? # Rails.logger.debug "[TRACE] <MapJson.update_json> [2] area #{area}; area_representator: #{area.area_representator}" har = area.area_representator.to_hash_a har["is_free"] = area.area_representator.is_free? end ab = { id: area.id, object_type: 'area', coords: area.coords.split(','), area_hash: har # area_hash: { # id: 2, # title: "Площадь #{area.id}.#{area.id}", # is_free: true, # props: { # square: "124 кв.м.", # floor_height: "6 кв. м", # column_step: "2 м", # gate_type: "распашные", # communications: "Интернет, электричество, водоснабжение", # price: "от 155 руб/кв.м в месяц" # } # } } childs << ab end # соберём хэш привязанного к полигону здания hbu = {} if b.building_representator.present? hbu = b.building_representator.to_hash # har["is_free"] = area.area_representator.is_free? end cc = nil if b.coords.present? cc = b.coords.split(",") else Rails.logger.debug "[TRACE] <Map_json.update_json> nil! #{b.id}" end ob = { id: b.id, object_type: 'building', coords: cc, building_hash: hbu, # building_hash: { # id: 2, # title: "Здание 2", # props: { # square: "1234 кв.м.", # square_free: "124 кв. м", # floor_height: "6 кв. м", # column_step: "2 м", # gate_type: "рaспашные", # communications: "Интернет, электричество, водоснабжение", # price: "от 155 руб/кв.м в месяц" # } # }, img: { bg: { src: b.img_bg.url }, overlay: { src: b.img_overlay.url } }, childs: childs } buildings_to_location_json << ob end # просто заменяем всех детей locs_hash["childs"] = buildings_to_location_json Rails.logger.debug "<MapJson.update_json> #{locs_hash}" File.open(locations_path, 'w') do |f| f.write(locs_hash.to_json) end end def self.fetch_json locations_path = Rails.root.join("public", "locations.json") locs = File.read(locations_path) JSON.parse(locs) end end end
32.683761
129
0.500523
8ba28ff03da15c0a5cb5153110691a1c26d1d033
518
rb
Ruby
spec/dpic_spec.rb
djencks/asciidoctor-diagram
730665c919c43d35a427f5219f4cf29b856c5390
[ "MIT" ]
1
2021-01-14T09:28:56.000Z
2021-01-14T09:28:56.000Z
spec/dpic_spec.rb
djencks/asciidoctor-diagram
730665c919c43d35a427f5219f4cf29b856c5390
[ "MIT" ]
null
null
null
spec/dpic_spec.rb
djencks/asciidoctor-diagram
730665c919c43d35a427f5219f4cf29b856c5390
[ "MIT" ]
null
null
null
require_relative 'test_helper' code = <<-eos arrow "$u$" above S: circle rad 10/72.27 # 10 pt line right 0.35 G: box "$G(s)$" arrow "$y$" above line -> down G.ht from last arrow then left last arrow.c.x-S.x then to S.s "$-\;$" below rjust eos describe Asciidoctor::Diagram::DpicBlockMacroProcessor, :broken_on_windows do include_examples "block_macro", :dpic, code, [:svg] end describe Asciidoctor::Diagram::DpicBlockProcessor, :broken_on_windows do include_examples "block", :dpic, code, [:svg] end
25.9
77
0.708494
3cc90197ee70787fd4539ecfe13cece4aec4354a
313
lua
Lua
game/GameScreen.lua
elemel/chatterbox
52442b5bf6bdd7e58aad3f3a046f130393ae1bce
[ "MIT" ]
null
null
null
game/GameScreen.lua
elemel/chatterbox
52442b5bf6bdd7e58aad3f3a046f130393ae1bce
[ "MIT" ]
null
null
null
game/GameScreen.lua
elemel/chatterbox
52442b5bf6bdd7e58aad3f3a046f130393ae1bce
[ "MIT" ]
null
null
null
local Class = require("game.Class") local Engine = require("game.Engine") local M = Class.new() function M:init() self.engine = Engine.new({}) end function M:draw() self.engine:draw() end function M:resize(w, h) self.engine:resize(w, h) end function M:update(dt) self.engine:update(dt) end return M
13.608696
37
0.690096
dd7d3989f3df409418b673afd1936655ba06489e
1,422
asm
Assembly
projects/08/FunctionCalls/StaticsTest/Class2.asm
nadavWeisler/Nand2Tetris
59c2e616c45044c15b99aeb8459d39b59e5e07ba
[ "MIT" ]
null
null
null
projects/08/FunctionCalls/StaticsTest/Class2.asm
nadavWeisler/Nand2Tetris
59c2e616c45044c15b99aeb8459d39b59e5e07ba
[ "MIT" ]
null
null
null
projects/08/FunctionCalls/StaticsTest/Class2.asm
nadavWeisler/Nand2Tetris
59c2e616c45044c15b99aeb8459d39b59e5e07ba
[ "MIT" ]
null
null
null
(Class2.set) @0 D=A @i M=D D=M @Class2.set.0 D;JEQ (Class2.set..0) @SP A=M M=0 @SP D=M D=D+1 M=D @i D=M D=D-1 M=D @Class2.set..0 D;JNE (Class2.set.0) @0 D=A @ARG A=M+D D=M @SP A=M M=D @SP M=M+1 @SP M=M-1 A=M D=M @C:\Weisler\Study\Nand2Tetris\projects\08\FunctionCalls\StaticsTest\Class2.asm.0 M=D @1 D=A @ARG A=M+D D=M @SP A=M M=D @SP M=M+1 @SP M=M-1 A=M D=M @C:\Weisler\Study\Nand2Tetris\projects\08\FunctionCalls\StaticsTest\Class2.asm.1 M=D @0 D=A @SP A=M M=D @SP M=M+1 @LCL D=M @FRAME M=D @FRAME D=M @5 D=D-A A=D D=M @RET M=D @SP D=M D=D-1 A=D D=M @ARG A=M M=D @ARG D=M D=D+1 @SP M=D @FRAME D=M D=D-1 A=D D=M @THAT M=D @FRAME D=M @2 D=D-A A=D D=M @THIS M=D @FRAME D=M @3 D=D-A A=D D=M @ARG M=D @FRAME D=M @4 D=D-A A=D D=M @LCL M=D @RET A=M 0;JMP (Class2.get) @0 D=A @i M=D D=M @Class2.get.0 D;JEQ (Class2.get..0) @SP A=M M=0 @SP D=M D=D+1 M=D @i D=M D=D-1 M=D @Class2.get..0 D;JNE (Class2.get.0) @C:\Weisler\Study\Nand2Tetris\projects\08\FunctionCalls\StaticsTest\Class2.asm.0 D=M @SP A=M M=D @SP M=M+1 @C:\Weisler\Study\Nand2Tetris\projects\08\FunctionCalls\StaticsTest\Class2.asm.1 D=M @SP A=M M=D @SP M=M+1 @SP M=M-1 A=M D=M A=A-1 M=M-D @LCL D=M @FRAME M=D @FRAME D=M @5 D=D-A A=D D=M @RET M=D @SP D=M D=D-1 A=D D=M @ARG A=M M=D @ARG D=M D=D+1 @SP M=D @FRAME D=M D=D-1 A=D D=M @THAT M=D @FRAME D=M @2 D=D-A A=D D=M @THIS M=D @FRAME D=M @3 D=D-A A=D D=M @ARG M=D @FRAME D=M @4 D=D-A A=D D=M @LCL M=D @RET A=M 0;JMP
6.32
80
0.613924
4449f63d64f806f97fc56fec2b0441578c1c090e
3,789
py
Python
core/file_handler.py
VuongTuanKhanh/Airborne-Object-Detection
5d2c91797138501e782d35f5ec1bdf5821e7e17b
[ "MIT" ]
5
2021-08-24T13:18:39.000Z
2021-12-20T15:25:40.000Z
core/file_handler.py
VuongTuanKhanh/Airborne-Object-Detection
5d2c91797138501e782d35f5ec1bdf5821e7e17b
[ "MIT" ]
null
null
null
core/file_handler.py
VuongTuanKhanh/Airborne-Object-Detection
5d2c91797138501e782d35f5ec1bdf5821e7e17b
[ "MIT" ]
1
2021-12-17T15:11:19.000Z
2021-12-17T15:11:19.000Z
import os from urllib.parse import urlparse import cv2 from PIL import Image import numpy import multiprocessing import boto3 from botocore import UNSIGNED from botocore.client import Config from loguru import logger class FileHandler: def __init__(self, local_path, s3_path, download_if_required=True): self.local_path = local_path self.download_if_required = download_if_required self.s3_client = self.init_s3_client() self.s3_bucket, self.s3_path = self.parse_s3_path(s3_path) @staticmethod def init_s3_client(): s3_client = boto3.client('s3', config=Config(signature_version=UNSIGNED)) return s3_client @staticmethod def parse_s3_path(s3_path): o = urlparse(s3_path, allow_fragments=False) return o.netloc, o.path.lstrip('/') def download_file_if_needed(self, s3_path, local_path): if not self.file_exist_locally(local_path): if self.download_if_required: logger.info("[download_from_s3] File not found locally, downloading: %s" % s3_path) self.download_from_s3(s3_path, local_path) return self.file_exist_locally(local_path) def get_file_content(self, s3_path, type='None', local_path=None): if not local_path: local_path = s3_path if not self.download_file_if_needed(s3_path, local_path): raise FileNotFoundError full_path = self.absolute_path_to_file_locally(local_path) if type.lower() == "cv2": return cv2.imread(full_path) if type.lower() == "pil": return Image.open(full_path) if type.lower() == "numpy": return numpy.asarray(Image.open(full_path)) return open(full_path).read() def create_local_directory(self, path): if type(path) == list: path = path[1] os.makedirs(os.path.dirname(self.absolute_path_to_file_locally(path)), exist_ok=True) def absolute_path_to_file_locally(self, path): return os.path.join(self.local_path, path) def absolute_path_to_file_on_s3(self, path): return os.path.join(self.s3_path, path) def file_exist_locally(self, path): return os.path.isfile(self.absolute_path_to_file_locally(path)) def download_from_s3(self, s3_path, local_path): self.create_local_directory(local_path) self._download_from_s3([self.s3_bucket, self.absolute_path_to_file_on_s3(s3_path), self.absolute_path_to_file_locally(local_path)]) @staticmethod def _download_from_s3(config): if os.path.isfile(config[2]): return s3_client = boto3.client('s3', config=Config(signature_version=UNSIGNED)) s3_client.download_file(config[0], config[1], config[2]) def download_from_s3_parallel(self, paths, parallel=None): if parallel is None: parallel = multiprocessing.cpu_count() self.create_local_directory(paths[0]) prepare = [] for path in paths: if type(path) == list: prepare.append([self.s3_bucket, self.absolute_path_to_file_on_s3(path[0]), self.absolute_path_to_file_locally(path[1])]) else: prepare.append([self.s3_bucket, self.absolute_path_to_file_on_s3(path), self.absolute_path_to_file_locally(path)]) with multiprocessing.Pool(parallel) as pool: pool.map(self._download_from_s3, prepare) if __name__ == "__main__": local_path = '/Users/skbly7/Terminal/aicrowd/repos/airborne-detection-starter-kit/data' s3_path_ = 's3://airborne-obj-detection-challenge-training/part1/' file_handler = FileHandler(local_path, s3_path_)
36.085714
99
0.671153
b005ff2a59eba38f68ec943a403757dfeb0e0a67
2,586
lua
Lua
scripts/PHRA-JP/c101102053.lua
Xylen09/ygopro-pre-script
7a6a08d31704306bb90c3886df789a6a3e97963e
[ "Unlicense" ]
null
null
null
scripts/PHRA-JP/c101102053.lua
Xylen09/ygopro-pre-script
7a6a08d31704306bb90c3886df789a6a3e97963e
[ "Unlicense" ]
null
null
null
scripts/PHRA-JP/c101102053.lua
Xylen09/ygopro-pre-script
7a6a08d31704306bb90c3886df789a6a3e97963e
[ "Unlicense" ]
null
null
null
--鉄獣の凶襲 -- --Script by JustFish function c101102053.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,TIMING_END_PHASE) e1:SetCountLimit(1,101102053+EFFECT_COUNT_CODE_OATH) e1:SetTarget(c101102053.sptg) e1:SetOperation(c101102053.spop) c:RegisterEffect(e1) end function c101102053.spfilter1(c,e,tp) return c:IsFaceup() and c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and Duel.IsExistingMatchingCard(c101102053.spfilter2,tp,LOCATION_DECK,0,1,nil,e,tp,c:GetAttack(),c:GetRace()) end function c101102053.spfilter2(c,e,tp,atk,race) return c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and c:IsAttackBelow(atk) and not c:IsRace(race) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE) end function c101102053.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and c101102053.spfilter1(chkc,e,tp) end if chk==0 then return Duel.GetMZoneCount(tp)>0 and Duel.IsExistingTarget(c101102053.spfilter1,tp,LOCATION_MZONE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c101102053.spfilter1,tp,LOCATION_MZONE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c101102053.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c101102053.spfilter2,tp,LOCATION_DECK,0,1,1,nil,e,tp,tc:GetAttack(),tc:GetRace()) local tc=g:GetFirst() if tc then Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DISABLE) e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_DISABLE_EFFECT) tc:RegisterEffect(e2) Duel.SpecialSummonComplete() end end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetTarget(c101102053.splimit) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) end function c101102053.splimit(e,c) return not c:IsType(TYPE_LINK) and c:IsLocation(LOCATION_EXTRA) end
40.40625
118
0.804718
b88c59558b9d9d070fe4654ea356e76af32e7f4f
4,254
swift
Swift
CLPBRD/Services/WebSocketClientService/PocketSocketClient.swift
ego-cms/CLPBRD_iOS
9c3bd54da95ff861a95cec8568d9b89bd4fec02f
[ "MIT", "Unlicense" ]
null
null
null
CLPBRD/Services/WebSocketClientService/PocketSocketClient.swift
ego-cms/CLPBRD_iOS
9c3bd54da95ff861a95cec8568d9b89bd4fec02f
[ "MIT", "Unlicense" ]
null
null
null
CLPBRD/Services/WebSocketClientService/PocketSocketClient.swift
ego-cms/CLPBRD_iOS
9c3bd54da95ff861a95cec8568d9b89bd4fec02f
[ "MIT", "Unlicense" ]
null
null
null
import Foundation import Result import SwiftyJSON class PocketSocketClient: NSObject, WebSocketClientService { private(set) var url: URL? var webSocket: PSWebSocket? var onReceivedText: ((String) -> Void)? var onConnected: VoidClosure? var onDisconnected: ((Error?) -> Void)? fileprivate var initialText: String? func connect(host: String) { print("Connecting socket client to \(host)") if let ws = webSocket, ws.readyState == .open { return } requestHostParameters(host: host) { [weak self](result) in print("Got http /clipboard response from \(host): \(result)") switch result { case .success(let json): print("---- JSON: \(json)") guard let port = json["port"].uInt else { call(closure: self?.onDisconnected, parameter: NSError.error(text: "Can't parse the port of server device \(host)")) return } print("Received port: \(port)") self?.initialText = json["text"].string guard let webSocketURL = URL.createWebSocketURL(with: host, port: port) else { call(closure: self?.onDisconnected, parameter: NSError.error(text: "Can't build websocket url")) return } print("Websocket url: \(webSocketURL)") self?.url = webSocketURL let webSocketRequest = URLRequest(url: webSocketURL) self?.webSocket = PSWebSocket.clientSocket(with: webSocketRequest) self?.webSocket?.delegate = self self?.webSocket?.delegateQueue = DispatchQueue.main self?.webSocket?.open() case .failure(let error): print("---- Error: \(error)") call(closure: self?.onDisconnected, parameter: error) } } } private func requestHostParameters(host: String, completion: @escaping (Result<JSON, NSError>) -> Void) { guard let httpServerURL = URL.createParametersURL(with: host) else { let error = NSError.error(text: "Wrong host \(host)") completion(.failure(error)) return } URLSession.shared.dataTask(with: httpServerURL) { (data, response, error) in if let error = error { completion(.failure(NSError.error(from: error))) return } guard let data = data else { completion( .failure( NSError.error(text: "Can't get port from clipboard JSON (\(String(describing: response?.url)))") ) ) return } let json = JSON(data: data) completion(.success(json)) }.resume() } func send(text: String) { print("Sending \(text)") webSocket?.send(text) } func disconnect() { print("Disconnecting") guard let ws = webSocket, ws.readyState != .closed else { return } webSocket?.close() webSocket = nil print("Socket closed") } } extension PocketSocketClient: PSWebSocketDelegate { func webSocketDidOpen(_ webSocket: PSWebSocket!) { print("PSWebSocketDelegate: Socket did open") onConnected?() if let initialText = self.initialText { onReceivedText?(initialText) self.initialText = nil } } func webSocket(_ webSocket: PSWebSocket!, didFailWithError error: Error!) { print("PSWebSocketDelegate: Socket did fail with error \(error)") onDisconnected?(error) } func webSocket(_ webSocket: PSWebSocket!, didReceiveMessage message: Any!) { print("PSWebSocketDelegate: Socket did receive message \(message)") guard let text = message as? String else { return } onReceivedText?(text) } func webSocket(_ webSocket: PSWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) { print("PSWebSocketDelegate: Socket did close with code \(code), reason \(reason), was clean \(wasClean)") } }
37.646018
136
0.567936
af7ce4a188d7ed17ee726c4e48d5cc832567a3e9
457
lua
Lua
spec/lua/test_switch_repeat_expr.lua
DarkShadow44/kaitai_struct_tests
4bb13cef82965cca66dda2eb2b77cd64e9f70a12
[ "MIT" ]
11
2018-04-01T03:58:15.000Z
2021-08-14T09:04:55.000Z
spec/lua/test_switch_repeat_expr.lua
DarkShadow44/kaitai_struct_tests
4bb13cef82965cca66dda2eb2b77cd64e9f70a12
[ "MIT" ]
73
2016-07-20T10:27:15.000Z
2020-12-17T18:56:46.000Z
spec/lua/test_switch_repeat_expr.lua
DarkShadow44/kaitai_struct_tests
4bb13cef82965cca66dda2eb2b77cd64e9f70a12
[ "MIT" ]
37
2016-08-15T08:25:56.000Z
2021-08-28T14:48:46.000Z
-- Autogenerated from KST: please remove this line if doing any edits by hand! local luaunit = require("luaunit") require("switch_repeat_expr") TestSwitchRepeatExpr = {} function TestSwitchRepeatExpr:test_switch_repeat_expr() local r = SwitchRepeatExpr:from_file("src/switch_tlv.bin") luaunit.assertEquals(r.code, 17) luaunit.assertEquals(r.size, 9) luaunit.assertEquals(r.body[0 + 1].first, "\083\116\117\102\102\000\077\101\000") end
28.5625
85
0.748359
2d7c89d6c78fdba874bb301698c4d86a283fe127
1,176
css
CSS
node_modules/react-preloading-component/src/lib/components/PreLoader/Flag/Flag.css
build-week-weight-journal/weight-journal-FE
36f82a2ae4c55789f67d9da2dc393e15d8cd0c36
[ "MIT" ]
null
null
null
node_modules/react-preloading-component/src/lib/components/PreLoader/Flag/Flag.css
build-week-weight-journal/weight-journal-FE
36f82a2ae4c55789f67d9da2dc393e15d8cd0c36
[ "MIT" ]
null
null
null
node_modules/react-preloading-component/src/lib/components/PreLoader/Flag/Flag.css
build-week-weight-journal/weight-journal-FE
36f82a2ae4c55789f67d9da2dc393e15d8cd0c36
[ "MIT" ]
null
null
null
.PreLoading-Flag { display: flex; justify-content: center; align-items: center; flex-direction: column; height: 100%; width: 100%; } .PreLoading-row { display: flex; } .Flag-circle { border-radius: 100%; animation: Flag 1.4s ease-in-out infinite; } .PreLoading-row:nth-of-type(1) .Flag-circle:nth-of-type(2) { animation-delay: .2s; } .PreLoading-row:nth-of-type(1) .Flag-circle:nth-of-type(3) { animation-delay: .4s; } .PreLoading-row:nth-of-type(2) .Flag-circle:nth-of-type(1) { animation-delay: .1s; } .PreLoading-row:nth-of-type(2) .Flag-circle:nth-of-type(2) { animation-delay: .3s; } .PreLoading-row:nth-of-type(2) .Flag-circle:nth-of-type(3) { animation-delay: .5s; } .PreLoading-row:nth-of-type(3) .Flag-circle:nth-of-type(1) { animation-delay: .3s; } .PreLoading-row:nth-of-type(3) .Flag-circle:nth-of-type(2) { animation-delay: .5s; } .PreLoading-row:nth-of-type(3) .Flag-circle:nth-of-type(3) { animation-delay: .7s; } @keyframes Flag { 0% { transform: rotate(0.001deg) scale(1.2); } 80% { transform: rotate(0.001deg) scale(.8); opacity: .72; } }
20.275862
61
0.623299
3a4fc2386415c0e92299eb034288aeb9c2d28ff3
1,478
kt
Kotlin
dispatch-android-viewmodel/src/test/java/dispatch/android/viewmodel/samples/ViewModelScopeSample.kt
awesome-android-library-and-tools/Dispatch
fecb29f2109b9b819e40bd780232de8d464abae2
[ "Apache-2.0" ]
109
2020-01-27T10:17:40.000Z
2022-03-28T23:10:50.000Z
dispatch-android-viewmodel/src/test/java/dispatch/android/viewmodel/samples/ViewModelScopeSample.kt
awesome-android-library-and-tools/Dispatch
fecb29f2109b9b819e40bd780232de8d464abae2
[ "Apache-2.0" ]
157
2020-02-03T21:45:58.000Z
2022-02-14T18:16:52.000Z
dispatch-android-viewmodel/src/test/java/dispatch/android/viewmodel/samples/ViewModelScopeSample.kt
awesome-android-library-and-tools/Dispatch
fecb29f2109b9b819e40bd780232de8d464abae2
[ "Apache-2.0" ]
5
2020-03-29T22:26:56.000Z
2021-09-08T00:22:31.000Z
/* * Copyright (C) 2021 Rick Busarow * 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 dispatch.android.viewmodel.samples import dispatch.android.viewmodel.DispatchViewModel import dispatch.core.launchMain import dispatch.internal.test.Sample import io.kotest.matchers.shouldBe import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.isActive @ExperimentalCoroutinesApi class ViewModelScopeSample { @Sample fun viewModelScopeSample() { class SomeViewModel : DispatchViewModel() { init { // auto-created MainImmediateCoroutineScope which is auto-cancelled in onClear() viewModelScope // ... // it works as a normal CoroutineScope (because it is) viewModelScope.launchMain { } // this is the same CoroutineScope instance each time viewModelScope.launchMain { } } override fun onClear() { viewModelScope.isActive shouldBe false } } } }
28.980392
88
0.730041
4db80668b7e15f138e6bce87f9c75da610d69043
596
cs
C#
GraphLayout/Test/MSAGLTests/Infrastructure/DebugAssertRedirector.cs
MVoloshin/automatic-graph-layout
6485e61c0c2851a6c8ab854e720c82fe368ddf7b
[ "MIT" ]
443
2019-05-08T20:50:47.000Z
2022-03-26T20:58:09.000Z
GraphLayout/Test/MSAGLTests/Infrastructure/DebugAssertRedirector.cs
QPC-database/automatic-graph-layout
ff4a15f615bc122bd38c4699077b4fd106d2398f
[ "MIT" ]
105
2019-06-11T14:01:11.000Z
2022-03-14T17:38:03.000Z
GraphLayout/Test/MSAGLTests/Infrastructure/DebugAssertRedirector.cs
QPC-database/automatic-graph-layout
ff4a15f615bc122bd38c4699077b4fd106d2398f
[ "MIT" ]
130
2019-05-11T09:12:37.000Z
2022-03-31T13:37:25.000Z
//----------------------------------------------------------------------- // <copyright file="DebugAssertRedirector.cs" company="Microsoft"> // (c) Microsoft Corporation. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace Microsoft.Msagl.UnitTests { using System.Diagnostics; using Microsoft.VisualStudio.TestTools.UnitTesting; internal class DebugAssertRedirector : DefaultTraceListener { public override void Fail(string message) { Assert.Fail(message); } } }
29.8
74
0.511745
a3aa719665bd6d7540d0f9cf53c6445c789a770e
1,763
java
Java
fusion-endpoint/src/main/java/dev/hilla/mappedtypes/Order.java
mortensen/flow
c0b2ffb0c5d35df46cf416e195201450c1de9e8a
[ "Apache-2.0" ]
null
null
null
fusion-endpoint/src/main/java/dev/hilla/mappedtypes/Order.java
mortensen/flow
c0b2ffb0c5d35df46cf416e195201450c1de9e8a
[ "Apache-2.0" ]
10
2021-11-16T09:33:53.000Z
2022-02-26T08:46:21.000Z
fusion-endpoint/src/main/java/dev/hilla/mappedtypes/Order.java
mortensen/flow
c0b2ffb0c5d35df46cf416e195201450c1de9e8a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2000-2022 Vaadin Ltd. * * 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 dev.hilla.mappedtypes; import javax.validation.constraints.NotBlank; import dev.hilla.Nonnull; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.NullHandling; /** * A DTO for {@link org.springframework.data.domain.Sort.Order}. */ public class Order { @Nonnull private Direction direction; @Nonnull @NotBlank private String property; private boolean ignoreCase; private NullHandling nullHandling; public Direction getDirection() { return direction; } public void setDirection(Direction direction) { this.direction = direction; } public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } public boolean isIgnoreCase() { return ignoreCase; } public void setIgnoreCase(boolean ignoreCase) { this.ignoreCase = ignoreCase; } public NullHandling getNullHandling() { return nullHandling; } public void setNullHandling(NullHandling nullHandling) { this.nullHandling = nullHandling; } }
25.185714
80
0.704481
4587b5ab1a8065484f6a5ea90dbb3ee9d08e5913
5,936
py
Python
HXL/sentenceTrans.py
hxlnwpu/Sentence_pair_modeling
e0324711e27694ad22e070a118697184d23bca58
[ "Apache-2.0" ]
null
null
null
HXL/sentenceTrans.py
hxlnwpu/Sentence_pair_modeling
e0324711e27694ad22e070a118697184d23bca58
[ "Apache-2.0" ]
null
null
null
HXL/sentenceTrans.py
hxlnwpu/Sentence_pair_modeling
e0324711e27694ad22e070a118697184d23bca58
[ "Apache-2.0" ]
null
null
null
from sentence_transformers import SentenceTransformer, util import os import csv from sklearn import metrics def cal_acc(result_dir ="./result_file"): accuracy_file = os.path.join(result_dir, 'accuracy.txt') # 存放结果的文件 trainResult = os.path.join(result_dir, 'trainBertResult.csv') testResult = os.path.join(result_dir, 'testBertResult.csv') # 计算accuracy true_label_list = list() pre_label_list = list() with open(accuracy_file, 'a') as f: with open(trainResult, 'r', encoding='utf-8-sig') as csvfile: reader = csv.reader(csvfile) for index, row in enumerate(reader): if index == 0: continue true_label_list.append(int(row[3])) pre_label_list.append(int(row[4])) f.write("------------------train - ----------------------"+'\n') f.write("train accuracy: " + str(metrics.accuracy_score(true_label_list, pre_label_list)) + '\n') f.write("precision_score: " + str(metrics.precision_score(true_label_list, pre_label_list)) + '\n') f.write("recall_score: " + str(metrics.recall_score(true_label_list, pre_label_list)) + '\n') f.write("f1_score: " + str(metrics.f1_score(true_label_list, pre_label_list)) + '\n') print("------------------train-----------------------") print("accuracy_score: " + str(metrics.accuracy_score(true_label_list, pre_label_list))) print("precision_score: " + str(metrics.precision_score(true_label_list, pre_label_list))) print("recall_score: " + str(metrics.recall_score(true_label_list, pre_label_list))) print("f1_score: " + str(metrics.f1_score(true_label_list, pre_label_list))) true_label_list.clear() pre_label_list.clear() with open(testResult, 'r', encoding='utf-8-sig') as csvfile: reader = csv.reader(csvfile) for index, row in enumerate(reader): if index == 0: continue true_label_list.append(int(row[3])) pre_label_list.append(int(row[4])) f.write("------------------test ------------------------"+'\n') f.write("test accuracy: " + str(metrics.accuracy_score(true_label_list, pre_label_list)) + '\n') f.write("precision_score: " + str(metrics.precision_score(true_label_list, pre_label_list)) + '\n') f.write("recall_score: " + str(metrics.recall_score(true_label_list, pre_label_list)) + '\n') f.write("f1_score: " + str(metrics.f1_score(true_label_list, pre_label_list)) + '\n') print("------------------test-----------------------") print("accuracy_score: " + str(metrics.accuracy_score(true_label_list, pre_label_list))) print("precision_score: " + str(metrics.precision_score(true_label_list, pre_label_list))) print("recall_score: " + str(metrics.recall_score(true_label_list, pre_label_list))) print("f1_score: " + str(metrics.f1_score(true_label_list, pre_label_list))) def get_bert_sim1(data_dir = "../BQ Corpus/data",result_dir ="./result_file",model_name = 'distiluse-base-multilingual-cased-v1' ): train_data = os.path.join(data_dir,"train.csv") test_data = os.path.join(data_dir,"test.csv") trainResult = os.path.join(result_dir, "trainBertResult.csv") testResult = os.path.join(result_dir, "testBertResult.csv") model = SentenceTransformer(model_name) # 获取train预测结果 train_sample_num = 0 sentences1 = list() sentences2 = list() true_labels = list() with open(train_data, 'r', encoding='utf-8-sig') as csvfile: # 获取train所有句子 reader = csv.reader(csvfile) for index, row in enumerate(reader): if index == 0: continue sentence1 = row[0] sentence2 = row[1] label = int(row[2]) sentences1.append(sentence1) sentences2.append(sentence2) true_labels.append(label) train_sample_num += 1 with open(test_data, 'r', encoding='utf-8-sig') as csvfile: # 获取test所有句子 reader = csv.reader(csvfile) for index, row in enumerate(reader): if index == 0: continue sentence1 = row[0] sentence2 = row[1] sentences1.append(sentence1) sentences2.append(sentence2) true_labels.append(label) # Compute embedding for both lists embeddings1 = model.encode(sentences1, convert_to_tensor=True) embeddings2 = model.encode(sentences2, convert_to_tensor=True) # Compute cosine-similarits cosine_scores = util.pytorch_cos_sim(embeddings1, embeddings2) with open(trainResult, "w+", encoding='utf-8-sig', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(["id", "sentence1", "sentence2", "true_label", "label", "similarity"]) for i in range(0,train_sample_num): id = i sentence1 = sentences1[i] sentence2 =sentences2[i] true_label = true_labels[i] similarity = cosine_scores[i][i] label = 1 if similarity >= 0.5 else 0 writer.writerow([id, sentence1, sentence2, true_label, label, similarity]) with open(testResult, "w+", encoding='utf-8-sig', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow(["id", "sentence1", "sentence2", "true_label", "label", "similarity"]) for i in range(train_sample_num, len(true_labels)): id = i sentence1 = sentences1[i] sentence2 = sentences2[i] true_label = true_labels[i] similarity = cosine_scores[i] label = 1 if similarity >= 0.5 else 0 writer.writerow([id, sentence1, sentence2, true_label, label, similarity]) if __name__ == '__main__': get_bert_sim1() cal_acc()
48.260163
131
0.610681
cd72906ac424d43d068eba2fd1108aaf79674465
687
cs
C#
CSharp-OOP/Homeworks-And-Labs/01WorkingWithAbstractionLab/04HotelReservation/StartUp.cs
kalintsenkov/SoftUni-Software-Engineering
add12909bd0c82d721b8bae43144626173f6023a
[ "MIT" ]
8
2020-12-30T08:58:37.000Z
2022-01-15T12:52:14.000Z
CSharp-OOP/Homeworks-And-Labs/01WorkingWithAbstractionLab/04HotelReservation/StartUp.cs
zanovasevi/SoftUni-Software-Engineering
add12909bd0c82d721b8bae43144626173f6023a
[ "MIT" ]
null
null
null
CSharp-OOP/Homeworks-And-Labs/01WorkingWithAbstractionLab/04HotelReservation/StartUp.cs
zanovasevi/SoftUni-Software-Engineering
add12909bd0c82d721b8bae43144626173f6023a
[ "MIT" ]
52
2019-06-08T08:50:21.000Z
2022-03-21T21:20:21.000Z
namespace _04HotelReservation { using Informations; using System; public class StartUp { public static void Main() { var input = Console.ReadLine(); var informationParser = new InformationParser(); var information = informationParser.Parse(input); var pricePerDay = information.PricePerDay; var days = information.Days; var season = information.Season; var discountType = information.DiscountType; var totalPrice = PriceCalculator.Calculate(pricePerDay, days, season, discountType); Console.WriteLine($"{totalPrice:F2}"); } } }
25.444444
96
0.608443
9fec895215bbe790a701c0830f44c5fdee23afa7
4,599
py
Python
utils.py
kcwikizh/kancolle-shinkai-db
73808a91b5f59d158374f016e2d514225f1ca6bd
[ "MIT" ]
1
2019-02-11T08:57:07.000Z
2019-02-11T08:57:07.000Z
utils.py
kcwikizh/kancolle-shinkai-db
73808a91b5f59d158374f016e2d514225f1ca6bd
[ "MIT" ]
null
null
null
utils.py
kcwikizh/kancolle-shinkai-db
73808a91b5f59d158374f016e2d514225f1ca6bd
[ "MIT" ]
null
null
null
"""Utils """ import json __all__ = ['MyException', 'nedb_parser', 'python_data_to_lua_table'] LUA_INDENT = ' ' * 4 class MyException(Exception): """My Exception I don't want to check the return value of every function. Raise an exception, just easier to programming. """ def __init__(self, msg): super().__init__(msg) self.message = msg def __str__(self): return self.message def nedb_parser(nedb): """nedb_parser """ result = {} line_num = 1 print('Get raw data from {}'.format(nedb)) with open(nedb, 'r', encoding='utf-8') as nedb_f: for line in nedb_f: python_object = json.loads(line) if not isinstance(python_object, dict): raise MyException( 'Not a python dict, line number {}'.format(line_num)) line_num += 1 item_id = python_object['id'] result[item_id] = python_object print('Loaded {} datas from {}'.format(len(result), nedb)) return result def python_data_to_lua_table(data, level=0, indent=LUA_INDENT): """Generate Lua string via python structure only dict, list, string, number, bool are allowed :param data: data to parse :param level: indent level :param indent: indent characters :return: tuple (lua string in this level and whether it's a list only contains number and string """ lines = [] if isinstance(data, list): all_elements_is_pure_data = True for i in data: if isinstance(i, dict): line, _ = python_data_to_lua_table(i, level+1, indent) lines.append(level*indent + '{\n' + line + '\n' + level*indent + '}') all_elements_is_pure_data = False elif isinstance(i, list): line, pure_data_in_next_level = \ python_data_to_lua_table(i, level+1, indent) if pure_data_in_next_level: lines.append(level*indent + '{' + line + '}') else: lines.append(level*indent + '{\n' + line + '\n' + level*indent + '}') all_elements_is_pure_data = False elif isinstance(i, bool): # this must before int case lines.append(level*indent + '{}'.format( 'true' if i else 'false')) elif isinstance(i, int): lines.append(level*indent + str(i)) elif isinstance(i, str): lines.append(level*indent + '"{}"'.format(i)) else: raise MyException('Unsupported data\n' + str(i) + '\n' + 'with type:' + type(i)) if all_elements_is_pure_data: # All elements in list is pure data, not list or dict return ', '.join([i.strip() for i in lines]), True return ',\n'.join(lines), False if isinstance(data, dict): for i in data: if isinstance(data[i], dict): line, _ = python_data_to_lua_table(data[i], level+1, indent) lines.append(level*indent + '["{}"] = {{\n'.format(i) + line + '\n' + level*indent + '}') elif isinstance(data[i], list): line, pure_data_in_next_level = \ python_data_to_lua_table(data[i], level+1, indent) if pure_data_in_next_level: lines.append(level*indent + '["{}"] = {{'.format(i) + line + '}') else: lines.append(level*indent + '["{}"] = {{\n'.format(i) + line + '\n' + level*indent + '}') elif isinstance(data[i], bool): # this must before int case lines.append(level*indent + '["{}"] = {}'.format(i, 'true' if data[i] else 'false')) elif isinstance(data[i], int): lines.append(level*indent + '["{}"] = {}'.format(i, data[i])) elif isinstance(data[i], str): lines.append(level*indent + '["{}"] = "{}"'.format(i, data[i])) else: raise MyException('Unsupported data\n' + str(data[i]) + '\n' + 'with type:' + str(type(data[i]))) return ',\n'.join(lines), False else: raise MyException('Unsupported data\n' + str(data) + '\n' + 'with type:' + type(data))
38.008264
79
0.506414
a31ab62614dd8de40ed9a3cab7d5db0aa0e0f1e4
620
java
Java
Java/Greeter/Test/com/codewars/GreeterTest.java
JacobJO/Codewars
afe8cac78e97ef6dd8c527a0cae6aa8c3622607d
[ "MIT" ]
1
2018-03-07T17:42:49.000Z
2018-03-07T17:42:49.000Z
Java/Greeter/Test/com/codewars/GreeterTest.java
JacobJO/Codewars
afe8cac78e97ef6dd8c527a0cae6aa8c3622607d
[ "MIT" ]
null
null
null
Java/Greeter/Test/com/codewars/GreeterTest.java
JacobJO/Codewars
afe8cac78e97ef6dd8c527a0cae6aa8c3622607d
[ "MIT" ]
null
null
null
package com.codewars; import org.junit.Test; import static org.junit.Assert.*; public class GreeterTest { @Test public void ShouldWorkForThisExample() throws Exception{ assertEquals( "Should greet some people normally", "Hello, Jacob!", Greeter.greet("Jacob") ); assertEquals( "Should greet some people normally", "Hello, Kamil!", Greeter.greet("Kamil") ); assertEquals( "Should greet some people normally", "Hello, Jane!", Greeter.greet("Jane") ); assertEquals( "Should greet some people normally", "Hello, my love!", Greeter.greet("Johnny") ); } }
31
105
0.659677
da7ce712ff0555ba00ec8116909cea442d1de65c
763
php
PHP
application/controllers/News.php
bensoer/PHPLab2
0b4e51a5fe3b4ce764abb79027bb6b1b49627ada
[ "MIT" ]
null
null
null
application/controllers/News.php
bensoer/PHPLab2
0b4e51a5fe3b4ce764abb79027bb6b1b49627ada
[ "MIT" ]
null
null
null
application/controllers/News.php
bensoer/PHPLab2
0b4e51a5fe3b4ce764abb79027bb6b1b49627ada
[ "MIT" ]
null
null
null
<?php /** * Created by PhpStorm. * User: ben * Date: 15/01/15 * Time: 4:18 PM */ class News extends MY_Controller{ public function index() { // get the top articles $news = $this->directories->recentNews(); $clips = array(); foreach($news as $article){ $clips[] = array('title' => $article['title'], 'information' => $article['information']); } $this->data['newsfeed'] = $clips; //set the news icon as the selected icon $this->menu[3]['class'] = 'class="selected"'; $this->data['menu'] = $this->menu; //inject page into template and load //$this->load->view('news'); $this->data['pagebody'] = 'news'; $this->render(); } }
21.8
101
0.524246
93a8396e1c66e7ba1515c03336218cc660a7d324
986
asm
Assembly
scripts/museum2f.asm
adhi-thirumala/EvoYellow
6fb1b1d6a1fa84b02e2d982f270887f6c63cdf4c
[ "Unlicense" ]
null
null
null
scripts/museum2f.asm
adhi-thirumala/EvoYellow
6fb1b1d6a1fa84b02e2d982f270887f6c63cdf4c
[ "Unlicense" ]
null
null
null
scripts/museum2f.asm
adhi-thirumala/EvoYellow
6fb1b1d6a1fa84b02e2d982f270887f6c63cdf4c
[ "Unlicense" ]
null
null
null
Museum2FScript: call EnableAutoTextBoxDrawing ret Museum2FTextPointers: dw Museum2FText1 dw Museum2FText2 dw Museum2FText3 dw Museum2FText4 dw Museum2FText5 dw Museum2FText6 dw Museum2FText7 Museum2FText1: TX_FAR _Museum2FText1 db "@" Museum2FText2: TX_FAR _Museum2FText2 db "@" Museum2FText3: TX_FAR _Museum2FText3 db "@" Museum2FText4: TX_FAR _Museum2FText4 db "@" Museum2FText5: TX_ASM ld a, [wd472] bit 7, a jr nz, .asm_5c1f6 ld hl, Museum2FText_5c20e call PrintText jr .asm_5c20b .asm_5c1f6 ld a, [wPikachuHappiness] cp 101 jr c, .asm_5c205 ld hl, Museum2FText_5c218 call PrintText jr .asm_5c20b .asm_5c205 ld hl, Museum2FText_5c213 call PrintText .asm_5c20b jp TextScriptEnd Museum2FText_5c20e: TX_FAR _Museum2FText5 db "@" Museum2FText_5c213: TX_FAR _Museum2FPikachuText1 db "@" Museum2FText_5c218: TX_FAR _Museum2FPikachuText2 db "@" Museum2FText6: TX_FAR _Museum2FText6 db "@" Museum2FText7: TX_FAR _Museum2FText7 db "@"
13.694444
30
0.775862
daa0b2afcc01d1a86a106ab6bb6782fbbc6ef485
15,864
php
PHP
app/Http/Controllers/API/User/DataController.php
peacedev201/liga-backend
cc0845fff28816217a00c88b137ec3f143f87927
[ "MIT" ]
null
null
null
app/Http/Controllers/API/User/DataController.php
peacedev201/liga-backend
cc0845fff28816217a00c88b137ec3f143f87927
[ "MIT" ]
null
null
null
app/Http/Controllers/API/User/DataController.php
peacedev201/liga-backend
cc0845fff28816217a00c88b137ec3f143f87927
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\API\User; use App\Http\Resources\TournamentRoundMatchesResource; use App\Models\News; use App\Models\Tournament; use App\Models\ClubProfile; use Illuminate\Http\Request; use App\Models\PlayerProfile; use App\Http\Controllers\Controller; use App\Http\Resources\NewsResource; use App\Http\Resources\TournamentResource; use App\Http\Resources\ClubProfileResource; use App\Http\Resources\PlayerProfileResource; class DataController extends Controller { private $news; private $club; private $player; private $tournament; public function __construct(News $news, ClubProfile $club, PlayerProfile $player, Tournament $tournament) { $this->news = $news; $this->club = $club; $this->player = $player; $this->tournament = $tournament; } public function playerSignup() { $clubs = $this->club->latest()->select('id', 'name')->get(); return successResponse(ClubProfileResource::collection($clubs)); } public function clubsPage($page, $key=""){ $clubs = $this->club->where('name', 'LIKE', '%'.$key.'%')->latest()->get()->skip(($page-1)*16)->take(16); return successResponse(ClubProfileResource::collection($clubs)); } public function clubs() { $clubs = $this->club->latest()->get(); return successResponse(count($clubs)); } public function clubsAll($key) { $clubs = $this->club->where('name', 'LIKE', '%'.$key.'%')->latest()->get(); return successResponse(count($clubs)); } public function club($id) { $club = $this->club->with('members.player')->findorFail($id); return successResponse(new ClubProfileResource($club)); } public function playersPage($page, $key=""){ $players = $this->player->with([ 'firstTournamentRoundMatches' => function ($query) { $query->whereNotNull('first_player_score')->whereNotNull('first_player_points')->whereNotNull('second_player_points')->whereNotNull('second_player_score'); }, 'secondTournamentRoundMatches' => function ($query) { $query->whereNotNull('second_player_score')->whereNotNull('second_player_points')->whereNotNull('first_player_points')->whereNotNull('first_player_score'); }, ])->latest()->where('first_name', 'LIKE', '%'.$key.'%')->orWhere('last_name', 'LIKE', '%'.$key.'%')->orWhere('nick_name', 'LIKE', '%'.$key.'%')->get(); foreach ($players as $player) { $player->matches = $player->firstTournamentRoundMatches->merge($player->secondTournamentRoundMatches); $id = $player->id; $first = $player->matches->where('first_player_id', $id)->where('second_player_id', '!=', $id); $second = $player->matches->where('second_player_id', $id)->where('first_player_id', '!=', $id); $player->played_games = $player->matches->count(); $firstWins = $first->filter(function ($match) { return $match->first_player_score > $match->second_player_score; }); $secondWins = $second->filter(function ($match) { return $match->second_player_score > $match->first_player_score; }); $player->win_games = $firstWins->count() + $secondWins->count(); $firstDraw = $first->filter(function ($match) { return $match->first_player_score == $match->second_player_score; }); $secondDraw = $second->filter(function ($match) { return $match->second_player_score == $match->first_player_score; }); $player->draw_games = $firstDraw->count() + $secondDraw->count(); $firstLost = $first->filter(function ($match) { return $match->first_player_score < $match->second_player_score; }); $secondLost = $second->filter(function ($match) { return $match->second_player_score < $match->first_player_score; }); $player->lost_games = $firstLost->count() + $secondLost->count(); $firstGoals = $first->sum('first_player_score'); $secondGoals = $second->sum('second_player_score'); $player->goals = $firstGoals + $secondGoals; $firstPoints = $first->sum('first_player_points'); $secondPoints = $second->sum('second_player_points'); $player->points = $firstPoints + $secondPoints; } $players = $players->sortByDesc('points')->skip(($page-1)*25)->take(25); return successResponse(PlayerProfileResource::collection($players)); } public function players() { $players = $this->player->latest()->get(); return successResponse(count($players)); } public function playersAll($key) { $players = $this->player->where('first_name', 'LIKE', '%'.$key.'%')->orWhere('last_name', 'LIKE', '%'.$key.'%')->orWhere('nick_name', 'LIKE', '%'.$key.'%')->latest()->get(); return successResponse(count($players)); } public function player($id) { $player = $this->player->select('id', 'first_name', 'last_name', 'nick_name', 'biography', 'avatar')->with([ 'tournaments:id,name', 'membership.club:id,name,avatar', 'firstTournamentRoundMatches' => function ($query) use ($id) { $query->whereNull('first_player_score')->whereNull('first_player_points')->whereNull('second_player_points')->whereNull('second_player_score')->whereNotNull('held_date')->with(['firstPlayer:id,nick_name,avatar', 'secondPlayer:id,nick_name,avatar']); }, 'secondTournamentRoundMatches' => function ($query) use ($id) { $query->whereNull('second_player_score')->whereNull('second_player_points')->whereNull('first_player_points')->whereNull('first_player_score')->whereNotNull('held_date')->with(['firstPlayer:id,nick_name,avatar', 'secondPlayer:id,nick_name,avatar', 'tournamentRound:id,tournament_id', 'tournamentRound.tournament:id,name']); }, 'tournaments.matches' => function ($query) use ($id) { $query->whereNotNull('first_player_score')->whereNotNull('first_player_points')->whereNotNull('second_player_points')->whereNotNull('second_player_score') ->where(function ($query) use ($id) { $query->where(function ($query) use ($id) { $query->where('first_player_id', $id) ->where('second_player_id', '!=', $id); })->orWhere(function ($query) use ($id) { $query->where('second_player_id', $id) ->where('first_player_id', '!=', $id); }); }); }, ])->findorFail($id); $player = $this->getPlayerStates($player); return successResponse(new PlayerProfileResource($player)); } public function getPlayerStates($player) { $id = $player->id; $player->played_games = 0; $player->win_games = 0; $player->lost_games = 0; $player->draw_games = 0; $player->goals = 0; $player->points = 0; foreach ($player->tournaments as $tournament) { $first = $tournament->matches->where('first_player_id', $id)->where('second_player_id', '!=', $id); $second = $tournament->matches->where('second_player_id', $id)->where('first_player_id', '!=', $id); $tournament->played_games = $tournament->matches->count(); $firstWins = $first->filter(function ($match) { return $match->first_player_score > $match->second_player_score; }); $secondWins = $second->filter(function ($match) { return $match->second_player_score > $match->first_player_score; }); $tournament->win_games = $firstWins->count() + $secondWins->count(); $firstDraw = $first->filter(function ($match) { return $match->first_player_score == $match->second_player_score; }); $secondDraw = $second->filter(function ($match) { return $match->second_player_score == $match->first_player_score; }); $tournament->draw_games = $firstDraw->count() + $secondDraw->count(); $firstLost = $first->filter(function ($match) { return $match->first_player_score < $match->second_player_score; }); $secondLost = $second->filter(function ($match) { return $match->second_player_score < $match->first_player_score; }); $tournament->lost_games = $firstLost->count() + $secondLost->count(); $firstGoals = $first->sum('first_player_score'); $secondGoals = $second->sum('second_player_score'); $tournament->goals = $firstGoals + $secondGoals; $firstPoints = $first->sum('first_player_points'); $secondPoints = $second->sum('second_player_points'); $tournament->points = $firstPoints + $secondPoints; $player->played_games += $tournament->played_games; $player->win_games += $tournament->win_games; $player->lost_games += $tournament->lost_games; $player->draw_games += $tournament->draw_games; $player->goals += $tournament->goals; $player->points += $tournament->points; } $player->matches = $player->matches->sortBy('held_date'); return $player; } public function tournaments(Request $request) { $tournaments = $this->tournament->latest()->withCount('participants')->get(); $tournaments = TournamentResource::collection($tournaments); if (auth()->guard('user')->check()) { $registered = $this->tournament->whereHas('participants', function ($query) { $user = auth()->guard('user')->user(); $query->where('id', $user->profileable->id); })->select('id')->get(); $registered = $registered->modelKeys(); $tournaments->with = [ 'registered' => $registered ]; } return successResponse($tournaments); } public function tournament($id) { $tournament = $this->tournament->withCount('participants')->with([ 'rounds.tournamentRoundMatches.firstPlayer', 'rounds.tournamentRoundMatches.firstPlayer.membership' => function ($query) { $query->with('club:id,name')->whereStatus(1); }, 'rounds.tournamentRoundMatches.secondPlayer', 'rounds.tournamentRoundMatches.secondPlayer.membership' => function ($query) { $query->with('club:id,name')->whereStatus(1); }, ])->findorFail($id); return successResponse(new TournamentResource($tournament)); } public function latestfourgames() { $columns = ['first_player_id', 'second_player_id', 'held_date', 'held_time', 'first_player_score', 'second_player_score', 'first_player_points', 'second_player_points']; $games = $this->tournament->matches()->getRelated()->limit(4)->with(['firstPlayer', 'secondPlayer', 'tournamentRound.tournament']); foreach ($columns as $column) { $games = $games->whereNotNull($column); } $games = $games->get(); return successResponse(TournamentRoundMatchesResource::collection($games)); } public function bestplayers() { return $this->bestfiveplayers(25); } public function bestfiveplayers($limit = 5) { $players = $this->player // Points ->withCount([ 'firstTournamentRoundMatches as first_points' => function ($query) { $query->whereYear('held_date', now()->year)->select(\DB::raw("COALESCE(SUM(tournament_round_matches.first_player_points),0)")); }, 'secondTournamentRoundMatches as second_points' => function ($query) { $query->whereYear('held_date', now()->year)->select(\DB::raw("COALESCE(SUM(tournament_round_matches.second_player_points),0)")); } ]) ->selectRaw("(select first_points + second_points) as points") // Score ->withCount([ 'firstTournamentRoundMatches as first_score' => function ($query) { $query->whereYear('held_date', now()->year)->select(\DB::raw("COALESCE(SUM(tournament_round_matches.first_player_score),0)")); }, 'secondTournamentRoundMatches as second_score' => function ($query) { $query->whereYear('held_date', now()->year)->select(\DB::raw("COALESCE(SUM(tournament_round_matches.second_player_score),0)")); } ]) ->selectRaw("(select first_score + second_score) as goals") // Wins ->withCount([ 'firstTournamentRoundMatches as first_wins' => function ($query) { $query->whereYear('held_date', now()->year)->whereNotNull('first_player_score')->whereNotNull('second_player_score')->select(\DB::raw("COALESCE(SUM(tournament_round_matches.first_player_score > tournament_round_matches.second_player_score), 0)")); }, 'secondTournamentRoundMatches as second_wins' => function ($query) { $query->whereYear('held_date', now()->year)->whereNotNull('second_player_score')->whereNotNull('second_player_score')->select(\DB::raw("COALESCE(SUM(tournament_round_matches.second_player_score > tournament_round_matches.first_player_score), 0)")); } ]) ->selectRaw("(select first_wins + second_wins) as win_games") // Lost ->withCount([ 'firstTournamentRoundMatches as first_lost' => function ($query) { $query->whereYear('held_date', now()->year)->whereNotNull('first_player_score')->whereNotNull('second_player_score')->select(\DB::raw("COALESCE(SUM(tournament_round_matches.first_player_score < tournament_round_matches.second_player_score), 0)")); }, 'secondTournamentRoundMatches as second_lost' => function ($query) { $query->whereYear('held_date', now()->year)->whereNotNull('second_player_score')->whereNotNull('second_player_score')->select(\DB::raw("COALESCE(SUM(tournament_round_matches.second_player_score < tournament_round_matches.first_player_score), 0)")); } ]) ->selectRaw("(select first_lost + second_lost) as lost_games") ->orderBy('points', 'desc')->limit($limit)->get(); return successResponse(PlayerProfileResource::collection($players)); } public function news(Request $request) { $localParams = [ 'perPage' => 10, ]; $params = array_merge($localParams, $request->query()); $news = $this->news->latest()->select('id', 'title', 'slug', 'description', 'image', 'created_at')->paginate($params['perPage']); return successResponse(NewsResource::collection($news)); } public function newsSingle($slug) { $news = $this->news->whereSlug($slug)->firstorFail(); return successResponse(new NewsResource($news)); } }
44.813559
339
0.584468
b34a91f03917267a20b5a4316114275ffd0a2251
1,251
py
Python
schema/test_connection.py
ramrod-project/database-brain
b024cb44f34cabb9d80af38271ddb65c25767083
[ "MIT" ]
null
null
null
schema/test_connection.py
ramrod-project/database-brain
b024cb44f34cabb9d80af38271ddb65c25767083
[ "MIT" ]
13
2018-06-06T19:10:51.000Z
2021-06-01T22:11:11.000Z
schema/test_connection.py
ramrod-project/database-brain
b024cb44f34cabb9d80af38271ddb65c25767083
[ "MIT" ]
null
null
null
""" Pytest file for the connection wrapper """ from os import environ from pytest import fixture, raises import docker from .brain import connect, r from .brain.connection import DefaultConnection, BrainNotReady CLIENT = docker.from_env() @fixture(scope='module') def rethink(): try: tag = environ.get("TRAVIS_BRANCH", "dev").replace("master", "latest") except KeyError: tag = "latest" container_name = "brainmoduletest" CLIENT.containers.run( "ramrodpcp/database-brain:{}".format(tag), name=container_name, detach=True, ports={"28015/tcp": 28015}, remove=True ) yield True # Teardown for module tests containers = CLIENT.containers.list() for container in containers: if container.name == container_name: container.stop() break def test_brain_interface(rethink): return connect() def test_brain_interface_with_host(rethink): import rethinkdb return connect("localhost", rethinkdb.DEFAULT_PORT) def test_direct_interface(rethink): r.connect() if __name__ == "__main__": a = rethink() c = test_brain_interface(a.__next__()) try: a.__next__() except StopIteration: pass
22.339286
77
0.664269
b058e9684cd14bea378898ad8e23b5719bcb4847
966
swift
Swift
MVVMReactive/ViewModel/RepositoryCellViewModel.swift
yhoonshine/MVVMReactive
b6151850ef619ed15116bcf7e35f3435e4853c9d
[ "MIT" ]
null
null
null
MVVMReactive/ViewModel/RepositoryCellViewModel.swift
yhoonshine/MVVMReactive
b6151850ef619ed15116bcf7e35f3435e4853c9d
[ "MIT" ]
null
null
null
MVVMReactive/ViewModel/RepositoryCellViewModel.swift
yhoonshine/MVVMReactive
b6151850ef619ed15116bcf7e35f3435e4853c9d
[ "MIT" ]
null
null
null
// // RepositoryCellViewModel.swift // MVVMReactive // // Created by Lyrics on 2019/4/15. // Copyright © 2019 Albatross Lab. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa class RepositoryCellViewModel { let title: Driver<String> let subTitle: Driver<String> let detail: Driver<String> let imageUrl: Driver<URL?> let starCountText: Driver<String> let language: Driver<String> let repository: Repository init(with repository: Repository) { self.repository = repository title = Driver.just("\(repository.name ?? "")") subTitle = Driver.just("\(repository.owner?.login ?? "")") detail = Driver.just("\(repository.descriptionField ?? "")") starCountText = Driver.just("\((repository.stargazersCount ?? 0))") imageUrl = Driver.just(repository.owner?.avatarURL) language = Driver.just("\(repository.language ?? "")") } }
27.6
75
0.65528
f49e31826d87225e5c05e8ff9a7fa084034d26b7
589
tsx
TypeScript
src/fill/Detective.tsx
Joeao/phosphor-react-native
499e024cb4ac71e4bf1d1d5e11c0daa1fc7c598f
[ "MIT" ]
null
null
null
src/fill/Detective.tsx
Joeao/phosphor-react-native
499e024cb4ac71e4bf1d1d5e11c0daa1fc7c598f
[ "MIT" ]
null
null
null
src/fill/Detective.tsx
Joeao/phosphor-react-native
499e024cb4ac71e4bf1d1d5e11c0daa1fc7c598f
[ "MIT" ]
null
null
null
/* GENERATED FILE */ import * as React from "react"; import Svg, { Rect, Path } from "react-native-svg"; import { IconProps } from '../lib' function Detective(props: IconProps) { return <Svg viewBox="0 0 256 256" width={props.size} height={props.size} fill={props.color} {...props}><Rect width={256} height={256} fill="none" /><Path d="M216,180a36,36,0,0,1-71.1,8H111.1a36,36,0,1,1,0-16h33.8a36,36,0,0,1,71.1,8Zm32-68H220.2L173.3,45a16.1,16.1,0,0,0-26.5.3L128,73.6,109.2,45.3A16.1,16.1,0,0,0,82.7,45L35.8,112H8a8,8,0,0,0,0,16H248a8,8,0,0,0,0-16Z" /></Svg>; } export default Detective;
49.083333
304
0.675722
2f1e6d94d130ac6ea779db524a849237f44c55d9
1,377
lua
Lua
tests/comptests/inputs/21_matrixmul.lua
XmiliaH/ravi
a2ec53624d58b8d952a40868bd83fe4690c7d305
[ "MIT" ]
1,048
2015-01-22T07:36:44.000Z
2022-03-28T12:55:41.000Z
tests/comptests/inputs/21_matrixmul.lua
XmiliaH/ravi
a2ec53624d58b8d952a40868bd83fe4690c7d305
[ "MIT" ]
231
2015-01-29T00:09:32.000Z
2022-02-23T09:55:38.000Z
tests/comptests/inputs/21_matrixmul.lua
XmiliaH/ravi
a2ec53624d58b8d952a40868bd83fe4690c7d305
[ "MIT" ]
70
2015-01-25T14:15:03.000Z
2021-11-29T00:18:50.000Z
f = compiler.load([[ local matrix = {} function matrix.T(a: table) local m: integer, n: integer, x: table = #a, #a[1], {}; for i = 1, n do local xi: number[] = table.numarray(n, 0.0) x[i] = xi for j = 1, m do xi[j] = @number (a[j][i]) end end return x; end function matrix.mul(a: table, b: table) assert(@integer(#a[1]) == #b); local m: integer, n: integer, p: integer, x: table = #a, #a[1], #b[1], {}; local c: table = matrix.T(b); -- transpose for efficiency for i = 1, m do local xi: number[] = table.numarray(p, 0.0) x[i] = xi for j = 1, p do local sum: number, ai: number[], cj: number[] = 0.0, @number[](a[i]), @number[](c[j]); -- for luajit, caching c[j] or not makes no difference; lua is not so clever for k = 1, n do sum = sum + ai[k] * cj[k] end xi[j] = sum; end end return x; end function matrix.gen(n: integer) local a: table, tmp: number = {}, 1. / n / n; for i = 1, n do local ai: number[] = table.numarray(n, 0.0) a[i] = ai for j = 1, n do ai[j] = tmp * (i - j) * (i + j - 2) end end return a; end return matrix ]] ) assert(f and type(f) == 'function') matrix = f() assert(matrix and type(matrix) == 'table') local n = 1000; n = math.floor(n/2) * 2; local t1 = os.clock() local a = matrix.mul(matrix.gen(n), matrix.gen(n)) local t2 = os.clock() print("time taken ", t2-t1) print(a[n/2+1][n//2+1]) print 'Ok'
25.036364
89
0.577342
886d91b413b1dcc4a1925badba0f72751805dda5
326
cs
C#
WebAPIPeliculas/WebAPIPeliculas/Entities/Actor.cs
NSysX/CursoEF6
85e5d91a9c729100777081adf1d560a245c524d7
[ "MIT" ]
null
null
null
WebAPIPeliculas/WebAPIPeliculas/Entities/Actor.cs
NSysX/CursoEF6
85e5d91a9c729100777081adf1d560a245c524d7
[ "MIT" ]
null
null
null
WebAPIPeliculas/WebAPIPeliculas/Entities/Actor.cs
NSysX/CursoEF6
85e5d91a9c729100777081adf1d560a245c524d7
[ "MIT" ]
null
null
null
namespace WebAPIPeliculas.Entities { public class Actor { public int Id { get; set; } public string Nombre { get; set; } public string Biografia { get; set; } public DateTime? FechaNacimiento { get; set; } public virtual HashSet<PeliculaActor> Peliculas { get; set; } } }
25.076923
69
0.610429
a3931b82a819f4ae879f283aee9546ec7194ac0d
1,095
java
Java
src/main/java/org/opensearch/knn/plugin/transport/KNNWarmupResponse.java
reta/k-NN
580411e18f459810ffd89e2557ab50d92c073dbf
[ "Apache-2.0" ]
44
2021-04-20T18:06:56.000Z
2022-03-31T00:59:07.000Z
src/main/java/org/opensearch/knn/plugin/transport/KNNWarmupResponse.java
reta/k-NN
580411e18f459810ffd89e2557ab50d92c073dbf
[ "Apache-2.0" ]
227
2021-04-21T12:21:46.000Z
2022-03-31T22:43:04.000Z
src/main/java/org/opensearch/knn/plugin/transport/KNNWarmupResponse.java
reta/k-NN
580411e18f459810ffd89e2557ab50d92c073dbf
[ "Apache-2.0" ]
31
2021-04-21T02:18:09.000Z
2022-03-25T23:47:17.000Z
/* * Copyright OpenSearch Contributors * SPDX-License-Identifier: Apache-2.0 */ package org.opensearch.knn.plugin.transport; import org.opensearch.action.support.DefaultShardOperationFailedException; import org.opensearch.action.support.broadcast.BroadcastResponse; import org.opensearch.common.io.stream.StreamInput; import org.opensearch.common.xcontent.ToXContentObject; import java.io.IOException; import java.util.List; /** * Response returned for k-NN Warmup. Returns total number of shards Warmup was performed on, as well as * the number of shards that succeeded and the number of shards that failed. */ public class KNNWarmupResponse extends BroadcastResponse implements ToXContentObject { public KNNWarmupResponse() {} public KNNWarmupResponse(StreamInput in) throws IOException { super(in); } public KNNWarmupResponse(int totalShards, int successfulShards, int failedShards, List<DefaultShardOperationFailedException> shardFailures) { super(totalShards, successfulShards, failedShards, shardFailures); } }
33.181818
104
0.76895
0a523542cacd8ecf0944867a6d262a5d88cdf5f5
2,153
cs
C#
Widgets/WeatherClockWidget/WeatherAnimation/RainWiper.xaml.cs
mediaexplorer74/Weather2022
0668bdeedf88791a778cef17d0cf7dabd6a5c7f6
[ "MIT" ]
null
null
null
Widgets/WeatherClockWidget/WeatherAnimation/RainWiper.xaml.cs
mediaexplorer74/Weather2022
0668bdeedf88791a778cef17d0cf7dabd6a5c7f6
[ "MIT" ]
null
null
null
Widgets/WeatherClockWidget/WeatherAnimation/RainWiper.xaml.cs
mediaexplorer74/Weather2022
0668bdeedf88791a778cef17d0cf7dabd6a5c7f6
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using E = HTCHome.Core.Environment; using System.Windows.Media.Animation; namespace WeatherClockWidget.WeatherAnimation { /// <summary> /// Interaction logic for RainWiper.xaml /// </summary> public partial class RainWiper : UserControl { public RainWiper() { InitializeComponent(); } private int count; public void Initialize() { Wiper.Source = new BitmapImage(new Uri(Widget.ResourceManager.GetResourcePath("Weather\\rain_wiper.png"))); Streaks.Source = new BitmapImage(new Uri(Widget.ResourceManager.GetResourcePath("Weather\\raindrop_streaks.png"))); Canvas.SetLeft(this, 100); } private void UserControl_Loaded(object sender, RoutedEventArgs e) { Storyboard s = (Storyboard)Resources["MoveAnim"]; s.Begin(); Storyboard s1 = (Storyboard)Resources["StreaksAnim"]; s1.Begin(); } private void DoubleAnimation_CurrentStateInvalidated(object sender, EventArgs e) { if (((Clock)sender).CurrentState == ClockState.Active) { Opacity = 1; Streaks.Opacity = 0.5; } } private void DoubleAnimation_Completed(object sender, EventArgs e) { count++; if (count < 1) //2 { Storyboard s = (Storyboard)Resources["MoveAnim"]; s.Begin(); Storyboard s1 = (Storyboard)Resources["StreaksAnim"]; s1.Begin(); Streaks.Opacity = 0.5; } } private void DoubleAnimation_Completed_1(object sender, EventArgs e) { Streaks.Opacity = 0; } } }
28.706667
127
0.600093
8806a22cc66e3247d68a963cb2d708f969e8d2d1
970
lua
Lua
scenes/north_city.lua
PolyCement/swallow-squad
5fc9c5566e9c4164c1c2f7f51483338f3545fcda
[ "MIT" ]
2
2018-04-04T09:47:31.000Z
2021-08-11T22:46:37.000Z
scenes/north_city.lua
PolyCement/swallow-squad
5fc9c5566e9c4164c1c2f7f51483338f3545fcda
[ "MIT" ]
null
null
null
scenes/north_city.lua
PolyCement/swallow-squad
5fc9c5566e9c4164c1c2f7f51483338f3545fcda
[ "MIT" ]
null
null
null
local vector = require "lib.hump.vector" local sprite = require "engine.sprite" local Level = require "engine.scenes.base" -- level 1, north city local NorthCity = Level:extend() function NorthCity:enter() -- initialize geometry and player position NorthCity.super.new(self, "scenes/north_city.csv", 2500, 2767, 5000, 3050) -- set the background to grey love.graphics.setBackgroundColor(230, 230, 230) -- clouds clouds = sprite.Sprite("assets/images/bg_cloud.png", 0, 0) -- background bg = sprite.Sprite("assets/images/north_city.png", 0, 0) end function NorthCity:draw() -- draw clouds and level sprite clouds:draw() self.camera:attach() bg:draw() self.camera:detach() -- then draw everything else on top NorthCity.super.draw(self) end -- checks if the game has ended function NorthCity:gameEnded() if table.length(prey) == 0 then return true end return false end return NorthCity
23.658537
78
0.689691
c0b861a68d58df5d11c553e98d22b331cba2f02c
35,422
lua
Lua
prototypes/functions/icon-handling.lua
kirazy/reskins-library
7ec1d0fba85e36d4221ab01b4601f4c405739e20
[ "MIT" ]
4
2020-08-23T16:51:14.000Z
2021-11-06T04:21:33.000Z
prototypes/functions/icon-handling.lua
kirazy/reskins-library
7ec1d0fba85e36d4221ab01b4601f4c405739e20
[ "MIT" ]
3
2021-08-04T07:17:21.000Z
2022-03-19T17:39:54.000Z
prototypes/functions/icon-handling.lua
kirazy/reskins-library
7ec1d0fba85e36d4221ab01b4601f4c405739e20
[ "MIT" ]
null
null
null
-- Copyright (c) 2021 Kirazy -- Part of Artisanal Reskins: Library -- -- See LICENSE.md in the project directory for license information. ---------------------------------------------------------------------------------------------------- -- TECHNOLOGY ICON FUNCTIONS ---------------------------------------------------------------------------------------------------- function reskins.lib.construct_technology_icon(name, inputs) -- Inputs required by this function -- mod - String; Originating mod calling the function, used to determine the subtable to store icon information for later processing -- group - String; Mod/category folder within the graphics/icons folder -- One of the following inputs must be specified; icon_filename being set assumes a flat icon with 1 layer -- icon_filename - String; Used to provide direct reference to source icon outside of the regular format -- icon_name - String; Folder containing the icon files, and the assumed icon file prefix -- Optional inputs, used when each entity being fed to this function has unique base or mask images -- subgroup - String; Folder nested within group, e.g. group/subgroup -- icon_base - String; Prefix for the icon-base.png file -- icon_mask - String; Prefix for the icon-mask.png file -- icon_highlights - String; Prefix for the icon-highlights.png file -- icon_layers - Integer, 1-3; Specify the number of layers to make; 3 by defualt -- untinted_icon_mask - Boolean; determine whether to apply a tint -- technology_icon_extras - Table of additional icon layers to add -- Handle compatibility defaults local folder_path = inputs.group if inputs.subgroup then folder_path = inputs.group.."/"..inputs.subgroup end -- Handle mask tinting defaults local icon_tint = inputs.tint if inputs.untinted_icon_mask then icon_tint = nil end -- Handle icon_layers defaults local icon_layers if inputs.technology_icon_filename then icon_layers = inputs.technology_icon_layers or 1 else icon_layers = inputs.technology_icon_layers or 3 end -- Some entities have variable bases and masks local icon_base = inputs.icon_base or inputs.icon_name local icon_mask = inputs.icon_mask or inputs.icon_name local icon_highlights = inputs.icon_highlights or inputs.icon_name -- Setup icon layers local icon_base_layer = { icon = inputs.technology_icon_filename or reskins[inputs.mod].directory.."/graphics/technology/"..folder_path.."/"..inputs.icon_name.."/"..icon_base.."-technology-base.png" } local icon_mask_layer, icon_highlights_layer if icon_layers > 1 then icon_mask_layer = { icon = reskins[inputs.mod].directory.."/graphics/technology/"..folder_path.."/"..inputs.icon_name.."/"..icon_mask.."-technology-mask.png", tint = icon_tint } icon_highlights_layer = { icon = reskins[inputs.mod].directory.."/graphics/technology/"..folder_path.."/"..inputs.icon_name.."/"..icon_highlights.."-technology-highlights.png", tint = {1, 1, 1, 0} } end -- Construct single-layer icons (flat) if icon_layers == 1 then inputs.technology_icon = icon_base_layer.icon end -- Construct double-layer icons if icon_layers > 1 then inputs.technology_icon = { icon_base_layer, icon_mask_layer, } end -- Construct triple-layer icons if icon_layers > 2 then table.insert(inputs.technology_icon, icon_highlights_layer) end -- Append icon extras as needed if inputs.technology_icon_extras then -- If we have one layer, we need to convert to an icons table format if icon_layers == 1 then inputs.technology_icon = { { icon = inputs.technology_icon } } end -- Append icon_extras for n = 1, #inputs.technology_icon_extras do table.insert(inputs.technology_icon, inputs.technology_icon_extras[n]) end end -- It may be necessary to put icons back in final fixes, allow for that if inputs.defer_to_data_final_fixes or inputs.defer_to_data_updates then reskins.lib.store_icons(name, inputs, "technology") return end reskins.lib.assign_technology_icons(name, inputs) end function reskins.lib.assign_technology_icons(name, inputs) -- Inputs required by this function -- technology_icon - Table or string defining technology icon -- Optional inputs (required if making a flat icon) -- technology_icon_size - Pixel size of icons -- technology_icon_mipmaps - Number of mipmaps present in the icon image file -- Initialize paths local technology = data.raw["technology"][name] -- Ensure the technology in question exists if technology then -- Check whether icon or icons, ensure the key we're not using is erased if type(inputs.technology_icon) == "table" then -- Set icon_size and icon_mipmaps per icons specification for n = 1, #inputs.technology_icon do if not inputs.technology_icon[n].icon_size then inputs.technology_icon[n].icon_size = inputs.technology_icon_size end if not inputs.technology_icon[n].icon_mipmaps then inputs.technology_icon[n].icon_mipmaps = inputs.technology_icon_mipmaps end end technology.icon = nil technology.icons = inputs.technology_icon else technology.icon = inputs.technology_icon technology.icons = nil technology.icon_size = inputs.technology_icon_size technology.icon_mipmaps = inputs.technology_icon_mipmaps end end end function reskins.lib.technology_equipment_overlay(parameters) local equipment = "personal" local scale = 0.5 if parameters then if parameters.is_vehicle then equipment = "vehicle" end if parameters.scale then scale = parameters.scale end end return { icon = reskins.lib.directory.."/graphics/technology/"..equipment.."-equipment-overlay.png", icon_size = 128, icon_mipmaps = 3, shift = {64*scale, 100*scale}, scale = scale, } end local technology_constants = { ["battery"] = {icon = "__core__/graphics/icons/technology/constants/constant-battery.png"}, ["braking-force"] = {icon = "__core__/graphics/icons/technology/constants/constant-braking-force.png"}, ["capacity"] = {icon = "__core__/graphics/icons/technology/constants/constant-capacity.png"}, ["count"] = {icon = "__core__/graphics/icons/technology/constants/constant-count.png"}, ["damage"] = {icon = "__core__/graphics/icons/technology/constants/constant-damage.png"}, ["follower-count"] = {icon = "__core__/graphics/icons/technology/constants/constant-follower-count.png"}, ["ghost"] = {icon = "__core__/graphics/icons/technology/constants/constant-time-to-live-ghosts.png"}, ["health"] = {icon = "__core__/graphics/icons/technology/constants/constant-health.png"}, ["logistic-slot"] = {icon = "__core__/graphics/icons/technology/constants/constant-logistic-slot.png"}, ["map-zoom"] = {icon = "__core__/graphics/icons/technology/constants/constant-map-zoom.png"}, ["mining"] = {icon = "__core__/graphics/icons/technology/constants/constant-mining.png"}, ["mining-productivity"] = {icon = "__core__/graphics/icons/technology/constants/constant-mining-productivity.png"}, ["movement-speed"] = {icon = "__core__/graphics/icons/technology/constants/constant-movement-speed.png"}, ["range"] = {icon = "__core__/graphics/icons/technology/constants/constant-range.png"}, ["speed"] = {icon = "__core__/graphics/icons/technology/constants/constant-speed.png"}, } function reskins.lib.return_technology_effect_icon(effect, scale) return { icon = technology_constants[effect].icon, icon_size = 128, icon_mipmaps = 3, shift = {100*(scale and scale or 1), 100*(scale and scale or 1)}, scale = scale, } end ---------------------------------------------------------------------------------------------------- -- STANDARD ICON FUNCTIONS ---------------------------------------------------------------------------------------------------- function reskins.lib.construct_icon(name, tier, inputs) -- Inputs required by this function -- mod - String; Originating mod calling the function, used to determine the subtable to store icon information for later processing -- group - String; Mod/category folder within the graphics/icons folder -- One of the following inputs must be specified; technology_icon_filename being set assumes a flat icon with 1 layer -- icon_filename - String; Used to provide direct reference to source icon outside of the regular format -- icon_name - String; Folder containing the icon files, and the assumed icon file prefix -- Optional inputs, used when each entity being fed to this function has unique base or mask images -- subgroup - String; Folder nested within group, e.g. group/subgroup -- tier_labels - Boolean; Used to override appending tier labels -- icon_base - String; Prefix for the icon-base.png file -- icon_mask - String; Prefix for the icon-mask.png file -- icon_highlights - String; Prefix for the icon-highlights.png file -- icon_layers - Integer, 1-3; Specify the number of layers to make; 3 by defualt -- untinted_icon_mask - Boolean; determine whether to apply a tint -- icon_extras - Table of additional icon layers to add -- icon_picture_extras - Table of additional icon layers to add for on-the-ground items local function equipment_background(category) local tints = { ["offense"] = util.color("e62c2c"), ["defense"] = util.color("3282d1"), ["energy"] = util.color("32d167"), ["utility"] = util.color("cccccc"), } return { icon = reskins.lib.directory.."/graphics/icons/backgrounds/equipment-background.png", icon_size = 64, icon_mipmaps = 4, tint = tints[category], } end -- Handle compatibility defaults local folder_path = inputs.group if inputs.subgroup then folder_path = inputs.group.."/"..inputs.subgroup end -- Handle mask tinting defaults local icon_tint = inputs.tint if inputs.untinted_icon_mask then icon_tint = nil end -- Handle inputs defaults reskins.lib.parse_inputs(inputs) -- Handle icon_layers defaults local icon_layers if inputs.icon_filename then icon_layers = inputs.icon_layers or 1 else icon_layers = inputs.icon_layers or 3 end -- Some entities have variable bases and masks local icon_base = inputs.icon_base or inputs.icon_name local icon_mask = inputs.icon_mask or inputs.icon_name local icon_highlights = inputs.icon_highlights or inputs.icon_name -- Setup icon layers local icon_base_layer = { icon = inputs.icon_filename or reskins[inputs.mod].directory.."/graphics/icons/"..folder_path.."/"..inputs.icon_name.."/"..icon_base.."-icon-base.png" } local icon_mask_layer, icon_highlights_layer if icon_layers > 1 then icon_mask_layer = { icon = reskins[inputs.mod].directory.."/graphics/icons/"..folder_path.."/"..inputs.icon_name.."/"..icon_mask.."-icon-mask.png", tint = icon_tint } icon_highlights_layer = { icon = reskins[inputs.mod].directory.."/graphics/icons/"..folder_path.."/"..inputs.icon_name.."/"..icon_highlights.."-icon-highlights.png", tint = {1, 1, 1, 0} } end -- Setup picture layers local picture_base_layer = { filename = inputs.icon_filename or reskins[inputs.mod].directory.."/graphics/icons/"..folder_path.."/"..inputs.icon_name.."/"..icon_base.."-icon-base.png", size = inputs.icon_size, mipmaps = inputs.icon_mipmaps, scale = 0.25 } local picture_mask_layer, picture_highlights_layer if icon_layers > 1 then picture_mask_layer = { filename = reskins[inputs.mod].directory.."/graphics/icons/"..folder_path.."/"..inputs.icon_name.."/"..icon_mask.."-icon-mask.png", size = inputs.icon_size, mipmaps = inputs.icon_mipmaps, scale = 0.25, tint = icon_tint } picture_highlights_layer = { filename = reskins[inputs.mod].directory.."/graphics/icons/"..folder_path.."/"..inputs.icon_name.."/"..icon_highlights.."-icon-highlights.png", size = inputs.icon_size, mipmaps = inputs.icon_mipmaps, scale = 0.25, blend_mode = "additive" } end -- Construct single-layer icons (flat) if icon_layers == 1 then inputs.icon = icon_base_layer.icon inputs.icon_picture = { picture_base_layer } end -- Construct double-layer icons if icon_layers > 1 then inputs.icon = { icon_base_layer, icon_mask_layer, } inputs.icon_picture = { layers = { picture_base_layer, picture_mask_layer, } } end -- Construct triple-layer icons if icon_layers > 2 then table.insert(inputs.icon, icon_highlights_layer) table.insert(inputs.icon_picture.layers, picture_highlights_layer) end -- Append icon extras as needed if inputs.icon_extras then -- If we have one layer, we need to convert to an icons table format if icon_layers == 1 then inputs.icon = { { icon = inputs.icon } } end -- Append icon_extras for n = 1, #inputs.icon_extras do table.insert(inputs.icon, inputs.icon_extras[n]) end end if inputs.icon_picture_extras then -- If we have one layer, we need to convert to an icons table format if icon_layers == 1 then inputs.icon_picture = { layers = inputs.icon_picture } end for n = 1, #inputs.icon_picture_extras do table.insert(inputs.icon_picture.layers, inputs.icon_picture_extras[n]) end end -- Insert icon background if necessary if inputs.equipment_category then -- If we have one layer, we need to convert to an icons table format if icon_layers == 1 then inputs.icon = { { icon = inputs.icon } } end -- Insert the equipment background table.insert(inputs.icon, 1, equipment_background(inputs.equipment_category)) end -- Append tier labels reskins.lib.append_tier_labels(tier, inputs) -- It may be necessary to put icons back in final fixes, allow for that if inputs.defer_to_data_final_fixes or inputs.defer_to_data_updates then reskins.lib.store_icons(name, inputs) return end reskins.lib.assign_icons(name, inputs) end function reskins.lib.store_icons(name, inputs, storage) -- Inputs required by this function -- mod - Specifies the subtable of reskins where the icons should be stored local storage = storage or "icons" -- Which stage are we deferring to local data_stage if inputs.defer_to_data_final_fixes then data_stage = "data-final-fixes" elseif inputs.defer_to_data_updates then data_stage = "data-updates" else log("[Reskins] "..name.." was improperly stored for deferred icon assignment.") return -- Fail quietly; should never get here end -- Initialize the arrays if not reskins[inputs.mod][storage] then reskins[inputs.mod][storage] = {} end if not reskins[inputs.mod][storage][data_stage] then reskins[inputs.mod][storage][data_stage] = {} end -- Store the icon reskins[inputs.mod][storage][data_stage][name] = util.copy(inputs) end function reskins.lib.assign_icons(name, inputs) -- Inputs required by this function -- type - Entity type -- icon - Table or string defining icon -- icon_size - Pixel size of icons -- icon_mipmaps - Number of mipmaps present in the icon image file -- Initialize paths local entity if inputs.type then entity = data.raw[inputs.type][name] end -- Recipes are exceptions to the usual pattern local item, item_with_data, explosion, remnant if inputs.type ~= "recipe" then item = data.raw["item"][name] item_with_data = data.raw["item-with-entity-data"][name] explosion = data.raw["explosion"][name.."-explosion"] remnant = data.raw["corpse"][name.."-remnants"] end -- Check whether icon or icons, ensure the key we're not using is erased if type(inputs.icon) == "table" then -- Set icon_size and icon_mipmaps per icons specification for n = 1, #inputs.icon do if not inputs.icon[n].icon_size then inputs.icon[n].icon_size = inputs.icon_size end if not inputs.icon[n].icon_mipmaps then inputs.icon[n].icon_mipmaps = inputs.icon_mipmaps or 1 end end -- Create icons that have multiple layers if entity then entity.icon = nil entity.icons = inputs.icon end if item then item.icon = nil item.icons = inputs.icon end if item_with_data then item_with_data.icon = nil item_with_data.icons = inputs.icon end if explosion then explosion.icon = nil explosion.icons = inputs.icon end if remnant then remnant.icon = nil remnant.icons = inputs.icon end else -- Create icons that do not have multiple layers if entity then entity.icons = nil entity.icon = inputs.icon entity.icon_size = inputs.icon_size entity.icon_mipmaps = inputs.icon_mipmaps end if item then item.icons = nil item.icon = inputs.icon item.icon_size = inputs.icon_size item.icon_mipmaps = inputs.icon_mipmaps end if item_with_data then item_with_data.icons = nil item_with_data.icon = inputs.icon item_with_data.icon_size = inputs.icon_size item_with_data.icon_mipmaps = inputs.icon_mipmaps end if explosion then explosion.icons = nil explosion.icon = inputs.icon explosion.icon_size = inputs.icon_size explosion.icon_mipmaps = inputs.icon_mipmaps end if remnant then remnant.icons = nil remnant.icon = inputs.icon remnant.icon_size = inputs.icon_size remnant.icon_mipmaps = inputs.icon_mipmaps end end -- Handle picture definitions if entity then if inputs.icon_picture and inputs.make_entity_pictures then entity.pictures = inputs.icon_picture end end if item then if inputs.icon_picture and inputs.make_icon_pictures then item.pictures = inputs.icon_picture end end -- item-with-entity-data prototypes ignore pictures field as of 1.0 -- this has been left active in the hopes the default behavior is adjusted if item_with_data then if inputs.icon_picture and inputs.make_icon_pictures then item_with_data.pictures = inputs.icon_picture end end -- Clear out recipe so that icon is inherited properly if inputs.type ~= "recipe" then reskins.lib.clear_icon_specification(name, "recipe") end end function reskins.lib.append_tier_labels_to_vanilla_icon(name, tier, inputs) -- Inputs required by this function -- type - Entity type -- Prevent cross-contamination local inputs = util.copy(inputs) local type = inputs.type or "item" -- Handle required parameters reskins.lib.parse_inputs(inputs) -- Extact the icon if data.raw[type][name].icons then inputs.icon = util.copy(data.raw[type][name].icons) -- Set icon_size and icon_mipmaps per icons specification, setup icon_picture inputs.icon_picture = {} for n = 1, #inputs.icon do if not inputs.icon[n].icon_size then inputs.icon[n].icon_size = data.raw[type][name].icon_size end if not inputs.icon[n].icon_mipmaps then inputs.icon[n].icon_mipmaps = data.raw[type][name].icon_mipmaps or 1 end inputs.icon_picture[n] = { filename = inputs.icon[n].icon, size = inputs.icon[n].icon_size, tint = inputs.icon[n].tint, shift = inputs.icon[n].shift, scale = 0.25*(inputs.icon[n].scale or 1), mipmaps = inputs.icon[n].icon_mipmaps or 1, } end else inputs.icon = { { icon = data.raw[type][name].icon, icon_size = data.raw[type][name].icon_size, icon_mipmaps = data.raw[type][name].icon_mipmaps, } } inputs.icon_picture = { { filename = data.raw[type][name].icon, size = data.raw[type][name].icon_size, scale = 0.25, mipmaps = data.raw[type][name].icon_mipmaps, } } end reskins.lib.append_tier_labels(tier, inputs) -- It may be necessary to put icons back in final fixes, allow for that if inputs.defer_to_data_final_fixes or inputs.defer_to_data_updates then reskins.lib.store_icons(name, inputs) return end reskins.lib.assign_icons(name, inputs) end function reskins.lib.append_tier_labels(tier, inputs) -- Inputs required by this function -- icon - Table containing an icon/icons definition -- tier_labels - Determines whether tier labels are appended if settings.startup["reskins-lib-icon-tier-labeling"].value == true and tier > 0 and inputs.tier_labels == true then -- Ensure inputs.icon is the right format if type(inputs.icon) ~= "table" then inputs.icon = {{icon = inputs.icon}} end -- Append the tier labels local icon_style = settings.startup["reskins-lib-icon-tier-labeling-style"].value table.insert(inputs.icon, { icon = reskins.lib.directory.."/graphics/icons/tiers/"..icon_style.."/"..tier..".png", icon_size = 64, icon_mipmaps = 4, } ) table.insert(inputs.icon, { icon = reskins.lib.directory.."/graphics/icons/tiers/"..icon_style.."/"..tier..".png", icon_size = 64, icon_mipmaps = 4, tint = reskins.lib.adjust_alpha(reskins.lib.tint_index[tier], 0.75) }) end end ---------------------------------------------------------------------------------------------------- -- UNIVERSAL ICON FUNCTIONS ---------------------------------------------------------------------------------------------------- function reskins.lib.clear_icon_specification(name, type) -- Inputs required by this function: -- type - Entity type -- Fetch entity local entity = data.raw[type][name] -- If the entity exists, clear the icon specification if entity then entity.icon = nil entity.icons = nil entity.icon_size = nil entity.icon_mipmaps = nil end end function reskins.lib.create_icons_from_list(table, inputs) -- Setup input defaults reskins.lib.parse_inputs(inputs) for name, map in pairs(table) do -- Fetch the icon local icon_type = map.type or inputs.type or "item" local icon = data.raw[icon_type][name] -- Check if icon exists, if not, skip this iteration if not icon then goto continue end -- Work with a local copy of inputs local inputs = util.copy(inputs) -- Handle input parameters inputs.type = map.type or inputs.type or nil inputs.mod = map.mod or inputs.mod inputs.group = map.group or inputs.group inputs.icon_size = map.icon_size or inputs.icon_size inputs.icon_mipmaps = map.icon_mipmaps or inputs.icon_mipmaps inputs.technology_icon_size = map.technology_icon_size or inputs.technology_icon_size inputs.technology_icon_mipmaps = map.technology_icon_mipmaps or inputs.technology_icon_mipmaps inputs.subgroup = map.subgroup or inputs.subgroup or nil -- Transcribe icon properties inputs.technology_icon_layers = map.technology_icon_layers or inputs.technology_icon_layers or nil inputs.icon_layers = map.icon_layers or inputs.icon_layers or nil inputs.technology_icon_extras = map.technology_icon_extras or inputs.technology_icon_extras or nil inputs.icon_extras = map.icon_extras or inputs.icon_extras or nil inputs.icon_picture_extras = map.icon_picture_extras or inputs.icon_picture_extras or nil -- Handle all the boolean overrides if map.make_icon_pictures == false then inputs.make_icon_pictures = false else inputs.make_icon_pictures = map.make_icon_pictures or inputs.make_icon_pictures end if map.make_entity_pictures == false then inputs.make_entity_pictures = false else inputs.make_entity_pictures = map.make_entity_pictures or inputs.make_entity_pictures end if map.defer_to_data_updates == false then inputs.defer_to_data_updates = false else inputs.defer_to_data_updates = map.defer_to_data_updates or inputs.defer_to_data_updates end if map.defer_to_data_final_fixes == false then inputs.defer_to_data_final_fixes = false else inputs.defer_to_data_final_fixes = map.defer_to_data_final_fixes or inputs.defer_to_data_final_fixes end local flat_icon if map.flat_icon == false then flat_icon = false else flat_icon = map.flat_icon or inputs.flat_icon end -- Prevent double assignment if inputs.defer_to_data_final_fixes then inputs.defer_to_data_updates = nil end -- Construct the icon if flat_icon then -- Setup filename details local image = map.image or name local path = inputs.group if inputs.subgroup then path = inputs.group.."/"..inputs.subgroup end -- Make the icon if inputs.type == "technology" then inputs.technology_icon_filename = map.technology_icon_filename or inputs.technology_icon_filename or reskins[inputs.mod].directory.."/graphics/technology/"..path.."/"..image..".png" reskins.lib.construct_technology_icon(name, inputs) else inputs.icon_filename = map.icon_filename or inputs.icon_filename or reskins[inputs.mod].directory.."/graphics/icons/"..path.."/"..image..".png" reskins.lib.construct_icon(name, 0, inputs) end else -- Handle tier local tier = map.tier or 0 if reskins.lib.setting("reskins-lib-tier-mapping") == "progression-map" then tier = map.prog_tier or map.tier or 0 end -- Handle tints inputs.tint = map.tint or inputs.tint or reskins.lib.tint_index[tier] -- Adjust tint to belt-type if necessary if map.uses_belt_mask == true then inputs.tint = reskins.lib.belt_tint_index[tier] end -- Handle icon_name and related parameters inputs.icon_name = map.icon_name or inputs.icon_name inputs.icon_base = map.icon_base or inputs.icon_base or nil inputs.icon_mask = map.icon_mask or inputs.icon_mask or nil inputs.icon_highlights = map.icon_highlights or inputs.icon_highlights or nil -- Make the icon if inputs.type == "technology" then reskins.lib.construct_technology_icon(name, inputs) else reskins.lib.construct_icon(name, tier, inputs) end end -- Label to skip to next iteration ::continue:: end end function reskins.lib.assign_deferred_icons(mod, data_stage) -- Item Icons if reskins[mod].icons and reskins[mod].icons[data_stage] then for name, inputs in pairs(reskins[mod].icons[data_stage]) do reskins.lib.assign_icons(name, inputs) end end -- Technology Icons if reskins[mod].technology and reskins[mod].technology[data_stage] then for name, inputs in pairs(reskins[mod].technology[data_stage]) do reskins.lib.assign_technology_icons(name, inputs) end end end function reskins.lib.composite_existing_icons(target_name, target_type, icons) -- icons = table of ["name"] = {type, shift, scale} or ["name"] = {icon or icons}, where type, shift, and scale are optional, and icon/icons ignores other param values -- Check to ensure the target is available local target = data.raw[target_type][target_name] if not target then return end -- Initialize the icons table local composite_icon = {} -- Iterate through the list of icons to composite for name, params in pairs(icons) do if params.icons then for _, layer in pairs(params.icons) do table.insert(composite_icon, { icon = layer.icon, icon_size = layer.icon_size, icon_mipmaps = layer.icon_mipmaps, scale = layer.scale or (32 / layer.icon_size), shift = layer.shift, tint = layer.tint, }) end elseif params.icon then table.insert(composite_icon, { icon = params.icon.icon, icon_size = params.icon.icon_size, icon_mipmaps = params.icon.icon_mipmaps, scale = params.icon.scale or (32 / params.icon.icon_size), shift = params.icon.shift, tint = params.icon.tint, }) else -- Check to ensure the object is available to copy from; abort if not local source_type = params.type or "item" -- Copy the current entity, return if it doesn't exist if not data.raw[source_type][name] then return end local entity = util.copy(data.raw[source_type][name]) -- Check for icons definition if entity.icons then -- Transcribe layers to the composite_icon table for _, layer in pairs(entity.icons) do local icon_size = layer.icon_size or entity.icon_size table.insert(composite_icon, { icon = layer.icon, icon_size = icon_size, icon_mipmaps = layer.icon_mipmaps or entity.icon_mipmaps, tint = layer.tint, scale = layer.scale or (32 / icon_size) * (params.scale or 1), shift = { (layer.shift and (layer.shift[1] or layer.shift.x) or 0) * (params.scale or 1) + (params.shift and (params.shift[1] or params.shift.x) or 0), (layer.shift and (layer.shift[2] or layer.shift.y) or 0) * (params.scale or 1) + (params.shift and (params.shift[2] or params.shift.y) or 0), } }) end -- Standard icon else -- Fully define an icons layer table.insert(composite_icon, { icon = entity.icon, icon_size = entity.icon_size, icon_mipmaps = entity.icon_mipmaps, scale = params.scale and (params.scale * 32 / entity.icon_size) or (32 / entity.icon_size), shift = { (params.shift and (params.shift[1] or params.shift.x) or 0), (params.shift and (params.shift[2] or params.shift.y) or 0), } }) end end end -- Assign the composite icon reskins.lib.assign_icons(target_name, {type = target_type, icon = composite_icon}) end function reskins.lib.create_icon_variations(parameters) local icon_picture = {} local folder_path = parameters.group if parameters.subgroup then folder_path = parameters.group.."/"..parameters.subgroup end for n = 1, parameters.variations do local suffix = ".png" if n > 1 then suffix = "-"..(n-1)..".png" end if parameters.glows then table.insert(icon_picture, { layers = { { filename = reskins[parameters.mod].directory.."/graphics/icons/"..folder_path.."/"..parameters.icon.."/"..parameters.icon..suffix, size = 64, scale = 0.25, mipmap_count = 4 }, { filename = reskins[parameters.mod].directory.."/graphics/icons/"..folder_path.."/"..parameters.icon.."/"..parameters.icon..suffix, blend_mode = "additive", draw_as_light = true, tint = {r = 0.3, g = 0.3, b = 0.3, a = 0.3}, size = 64, scale = 0.25, mipmap_count = 4 } } }) else table.insert(icon_picture, { filename = reskins[parameters.mod].directory.."/graphics/icons/"..folder_path.."/"..parameters.icon.."/"..parameters.icon..suffix, size = 64, scale = 0.25, mipmap_count = 4 }) end end return icon_picture end function reskins.lib.lit_icon_pictures_layer(mod, light, tint) return { filename = reskins[mod].directory.."/graphics/icons/lights/"..light.."-light.png", draw_as_light = true, flags = {"light"}, tint = tint, size = 64, scale = 0.25, mipmap_count = 4, } end
38.460369
197
0.604314
abda4645142a481f4165fa5307845d1bdd6d1e11
2,192
lua
Lua
addons/ulx-banmysql/lua/globalban/gb_serverheartbeat.lua
jonathanlaberge/ICF-Server
a244cf1ea129a948495ce68e5851a8815ff4d2af
[ "Unlicense" ]
1
2021-06-08T11:24:56.000Z
2021-06-08T11:24:56.000Z
addons/ulx-banmysql/lua/globalban/gb_serverheartbeat.lua
jonathanlaberge/ICF-Server
a244cf1ea129a948495ce68e5851a8815ff4d2af
[ "Unlicense" ]
null
null
null
addons/ulx-banmysql/lua/globalban/gb_serverheartbeat.lua
jonathanlaberge/ICF-Server
a244cf1ea129a948495ce68e5851a8815ff4d2af
[ "Unlicense" ]
null
null
null
--ULX Global Ban --Adobe And NigNog ------------------ //Global Value; can be used in any other supported scripts. GB_SERVERID = 0 function GB_QueryDatabaseForServer() --Gather Identification Infos local HostName = GB_Escape(GetHostName()); local IPAddress = GetConVarString("ip"); local HostPort = GetConVarString("hostport"); -- Setting up the Query local HeartbeatQuery = ULX_DB:query("SELECT ServerID FROM ulx_servers WHERE IPAddress ='"..IPAddress.."' AND Port = '"..HostPort.."'"); HeartbeatQuery.onSuccess = function() local data = HeartbeatQuery:getData() local row = data[1] -- Query The Database to see if server exsits and retrieve the Server's ID if (#HeartbeatQuery:getData() == 1) then GB_SERVERID = tonumber(row['ServerID']); GB_UpdateServerName(); print("[ULX GB] - ServerID Set To: ".. GB_SERVERID); else -- If Database does not have IP and port create a new row and populate it accordingly print("[ULX GB] - Server not present, creating..."); GB_InsertNewServer() end end HeartbeatQuery.onError = function(db, err) print('[ULX GB] (HeartbeatQuery) - Error: ', err) end HeartbeatQuery:start() end function GB_UpdateServerName() --Gather Identification Infos local HostName = GB_Escape(GetHostName()); local UpdateName = ULX_DB:query(" UPDATE ulx_servers SET HostName='".. HostName .."' WHERE ServerID='"..GB_SERVERID.."' "); UpdateName.onSuccess = function() print("[ULX GB] - Updated HostName Successfully!"); end UpdateName.onError = function(db, err) print('[ULX GB] (UpdateName) - Error: ', err) end UpdateName:start() end function GB_InsertNewServer() --Gather Indentification Infos local HostName = GB_Escape(GetHostName()); local IPAddress = GetConVarString("ip"); local HostPort = GetConVarString("hostport"); local NewServer = ULX_DB:query("INSERT INTO ulx_servers VALUES ('','"..IPAddress.."','"..HostPort.."','"..HostName.."')"); NewServer.onSuccess = function() print("[ULX GB] - Inserted New Server!"); GB_QueryDatabaseForServer() end NewServer.onError = function(db, err) print('[ULX GB] (NewServer) - Error: ', err); GB_QueryDatabaseForServer() end NewServer:start() end
32.716418
136
0.705748
71a279302c96ff2cbfdfe59044e26b009649c80b
11,623
swift
Swift
SmoothWalker/Main View Controllers/WelcomeViewController.swift
markFalcone/iOSHealthApp
a2fedb6ec663d314765a10af0b03b0116d7edfe7
[ "MIT" ]
null
null
null
SmoothWalker/Main View Controllers/WelcomeViewController.swift
markFalcone/iOSHealthApp
a2fedb6ec663d314765a10af0b03b0116d7edfe7
[ "MIT" ]
null
null
null
SmoothWalker/Main View Controllers/WelcomeViewController.swift
markFalcone/iOSHealthApp
a2fedb6ec663d314765a10af0b03b0116d7edfe7
[ "MIT" ]
null
null
null
/* See LICENSE folder for this sample’s licensing information. Abstract: A view controller that onboards users to the app. */ import UIKit import HealthKit class WelcomeViewController: SplashScreenViewController, SplashScreenViewControllerDelegate, UITextFieldDelegate { let healthStore = HealthData.healthStore var userEmail:String! var firstName:String! var lastName:String! /// The HealthKit data types we will request to read. let readTypes = Set(HealthData.readDataTypes) /// The HealthKit data types we will request to share and have write access. let shareTypes = Set(HealthData.shareDataTypes) var hasRequestedHealthData: Bool = false // MARK: - View Life Cycle let emailTextField = UITextField(frame: CGRect(x: 20, y: 100, width: 300, height: 40)) let firstNameTextField = UITextField(frame: CGRect(x: 20, y: 150, width: 300, height: 40)) let lastNameTextField = UITextField(frame: CGRect(x: 20, y: 200, width: 300, height: 40)) override func viewDidLoad() { super.viewDidLoad() title = tabBarItem.title view.backgroundColor = .systemBackground splashScreenDelegate = self actionButton.setTitle("Authorize HealthKit Access", for: .normal) emailTextField.placeholder = "Enter email here" emailTextField.font = UIFont.systemFont(ofSize: 20) emailTextField.borderStyle = UITextField.BorderStyle.roundedRect emailTextField.autocorrectionType = UITextAutocorrectionType.no emailTextField.keyboardType = UIKeyboardType.default emailTextField.returnKeyType = UIReturnKeyType.done emailTextField.clearButtonMode = UITextField.ViewMode.whileEditing emailTextField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center self.view.addSubview(emailTextField) firstNameTextField.placeholder = "Enter First Name here" firstNameTextField.font = UIFont.systemFont(ofSize: 20) firstNameTextField.borderStyle = UITextField.BorderStyle.roundedRect firstNameTextField.autocorrectionType = UITextAutocorrectionType.no firstNameTextField.keyboardType = UIKeyboardType.default firstNameTextField.returnKeyType = UIReturnKeyType.done firstNameTextField.clearButtonMode = UITextField.ViewMode.whileEditing firstNameTextField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center self.view.addSubview(firstNameTextField) lastNameTextField.placeholder = "Enter Last Name here" lastNameTextField.font = UIFont.systemFont(ofSize: 20) lastNameTextField.borderStyle = UITextField.BorderStyle.roundedRect lastNameTextField.autocorrectionType = UITextAutocorrectionType.no lastNameTextField.keyboardType = UIKeyboardType.default lastNameTextField.returnKeyType = UIReturnKeyType.done lastNameTextField.clearButtonMode = UITextField.ViewMode.whileEditing lastNameTextField.contentVerticalAlignment = UIControl.ContentVerticalAlignment.center self.view.addSubview(lastNameTextField) let myFirstButton = UIButton() myFirstButton.setTitle("SAVE", for: .normal) myFirstButton.setTitleColor(.blue, for: .normal) myFirstButton.frame = CGRect(x: 15, y: 250, width: 300, height: 40) myFirstButton.addTarget(self, action: #selector(pressed), for: .touchUpInside) self.view.addSubview(myFirstButton) getHealthAuthorizationRequestStatus() } @objc func pressed() { print("Pressed") userEmail = emailTextField.text! firstName = firstNameTextField.text! lastName = lastNameTextField.text! // print(userEmail) // Call api // let data = ServerResponse(from: Decoder.self as! Decoder).weeklyReport //print(type(of: data)) //apiCall(firstName: firstName, lastName: lastName, email: userEmail, HealthData: <#T##[String : AnyHashable]#>) let pathName = "MockServerResponse" let file = Bundle.main.url(forResource: pathName, withExtension: "json") let data = try? Data(contentsOf: file!) let decoder = JSONDecoder() let serverResponse = try? decoder.decode(ServerResponse.self, from: data!) var healthData: [HealthDataTypeValue] = [] let weeklyClass = WeeklyQuantitySampleTableViewController(dataTypeIdentifier: "") weeklyClass.sendAPI(firstName: firstName, lastName: lastName, email: userEmail) } func getHealthAuthorizationRequestStatus() { print("Checking HealthKit authorization status...") if !HKHealthStore.isHealthDataAvailable() { presentHealthDataNotAvailableError() return } healthStore.getRequestStatusForAuthorization(toShare: shareTypes, read: readTypes) { (authorizationRequestStatus, error) in var status: String = "" if let error = error { status = "HealthKit Authorization Error: \(error.localizedDescription)" } else { switch authorizationRequestStatus { case .shouldRequest: self.hasRequestedHealthData = false status = "The application has not yet requested authorization for all of the specified data types." case .unknown: status = "The authorization request status could not be determined because an error occurred." case .unnecessary: self.hasRequestedHealthData = true status = "The application has already requested authorization for the specified data types. " status += self.createAuthorizationStatusDescription(for: self.shareTypes) default: break } } print(status) // Results come back on a background thread. Dispatch UI updates to the main thread. DispatchQueue.main.async { self.descriptionLabel.text = status } } } // MARK: - SplashScreenViewController Delegate func didSelectActionButton() { requestHealthAuthorization() } func apiCall(firstName:String, lastName: String, email:String, HealthData:[String:AnyHashable]){ guard let url = URL(string: "https://magicmirrorhealth-developer-edition.na163.force.com/services/apexrest/postHealth?firstname=\(firstName)&lastname=\(lastName)&email=\(email)")else{ return } var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") let body: [String:AnyHashable] = HealthData//TODO ADD HEALTH DATA request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .fragmentsAllowed) let task = URLSession.shared.dataTask(with: request){data, _, error in guard let data = data, error == nil else { return } do{ let responce = try JSONSerialization.jsonObject(with: data, options: .allowFragments) print("success") }catch{ print(error) } } task.resume() } func requestHealthAuthorization() { print("Requesting HealthKit authorization...") if !HKHealthStore.isHealthDataAvailable() { presentHealthDataNotAvailableError() return } healthStore.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) in var status: String = "" if let error = error { status = "HealthKit Authorization Error: \(error.localizedDescription)" } else { if success { if self.hasRequestedHealthData { status = "You've already requested access to health data. " } else { status = "HealthKit authorization request was successful! " } status += self.createAuthorizationStatusDescription(for: self.shareTypes) self.hasRequestedHealthData = true } else { status = "HealthKit authorization did not complete successfully." } } print(status) // Results come back on a background thread. Dispatch UI updates to the main thread. DispatchQueue.main.async { self.descriptionLabel.text = status } } } // MARK: - Helper Functions private func createAuthorizationStatusDescription(for types: Set<HKObjectType>) -> String { var dictionary = [HKAuthorizationStatus: Int]() for type in types { let status = healthStore.authorizationStatus(for: type) if let existingValue = dictionary[status] { dictionary[status] = existingValue + 1 } else { dictionary[status] = 1 } } var descriptionArray: [String] = [] if let numberOfAuthorizedTypes = dictionary[.sharingAuthorized] { let format = NSLocalizedString("AUTHORIZED_NUMBER_OF_TYPES", comment: "") let formattedString = String(format: format, locale: .current, arguments: [numberOfAuthorizedTypes]) descriptionArray.append(formattedString) } if let numberOfDeniedTypes = dictionary[.sharingDenied] { let format = NSLocalizedString("DENIED_NUMBER_OF_TYPES", comment: "") let formattedString = String(format: format, locale: .current, arguments: [numberOfDeniedTypes]) descriptionArray.append(formattedString) } if let numberOfUndeterminedTypes = dictionary[.notDetermined] { let format = NSLocalizedString("UNDETERMINED_NUMBER_OF_TYPES", comment: "") let formattedString = String(format: format, locale: .current, arguments: [numberOfUndeterminedTypes]) descriptionArray.append(formattedString) } // Format the sentence for grammar if there are multiple clauses. if let lastDescription = descriptionArray.last, descriptionArray.count > 1 { descriptionArray[descriptionArray.count - 1] = "and \(lastDescription)" } let description = "Sharing is " + descriptionArray.joined(separator: ", ") + "." return description } private func presentHealthDataNotAvailableError() { let title = "Health Data Unavailable" let message = "Aw, shucks! We are unable to access health data on this device. Make sure you are using device with HealthKit capabilities." let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) let action = UIAlertAction(title: "Dismiss", style: .default) alertController.addAction(action) present(alertController, animated: true) } }
41.809353
195
0.626344
93b75b92715de03647266d200a3a97d3c691b183
853
cs
C#
API/src/HBoard.API/Features/Maps/MapsController.cs
Physer/HBoard
fcf699e206b329590343398d7795b564466f9feb
[ "Apache-2.0" ]
null
null
null
API/src/HBoard.API/Features/Maps/MapsController.cs
Physer/HBoard
fcf699e206b329590343398d7795b564466f9feb
[ "Apache-2.0" ]
null
null
null
API/src/HBoard.API/Features/Maps/MapsController.cs
Physer/HBoard
fcf699e206b329590343398d7795b564466f9feb
[ "Apache-2.0" ]
null
null
null
using HBoard.Business.Maps; using Microsoft.AspNetCore.Mvc; using System; using System.Net; using System.Threading.Tasks; namespace HBoard.API.Features.Maps { [Route("api/[controller]")] public class MapsController : Controller { private readonly IMapsService _mapsService; public MapsController(IMapsService mapsService) { _mapsService = mapsService; } public async Task<IActionResult> Get(string origin, string destination) { try { return Ok(await _mapsService.GetDirections(WebUtility.UrlEncode(origin), WebUtility.UrlEncode(destination))); } catch(Exception e) { // Log error return BadRequest($"Something went wrong: {e.Message}"); } } } }
25.848485
125
0.596717
5ad2ece62e6e48dcdf150e533305c6d1905a58aa
580
cs
C#
MapColors.cs
Ved-s/MechTransfer
9bd1ddfe5109d87e2a262865e04bfaef5acc7d5c
[ "MIT" ]
8
2018-01-11T18:04:19.000Z
2021-04-27T04:24:40.000Z
MapColors.cs
Ved-s/MechTransfer
9bd1ddfe5109d87e2a262865e04bfaef5acc7d5c
[ "MIT" ]
10
2017-11-14T21:41:40.000Z
2022-01-07T13:25:35.000Z
MapColors.cs
Ved-s/MechTransfer
9bd1ddfe5109d87e2a262865e04bfaef5acc7d5c
[ "MIT" ]
11
2017-11-14T15:47:34.000Z
2021-12-28T14:17:57.000Z
using Microsoft.Xna.Framework; namespace MechTransfer { public static class MapColors { public static Color FillMid { get { return new Color(90, 90, 90); } } public static Color FillDark { get { return new Color(56, 56, 56); } } public static Color FillLight { get { return new Color(127, 127, 127); } } public static Color Input { get { return new Color(107, 0, 0); } } public static Color Output { get { return new Color(0, 107, 0); } } public static Color Passthrough { get { return new Color(255, 104, 0); } } } }
38.666667
82
0.622414
ff9c1018217422bd2104e55c553d20f3cfdbfde1
371
py
Python
cdn_static_website/settings/components/caches.py
soulraven/cdn_small
e2415b39089cb761ddfe1748e443abd9c4080e83
[ "MIT" ]
null
null
null
cdn_static_website/settings/components/caches.py
soulraven/cdn_small
e2415b39089cb761ddfe1748e443abd9c4080e83
[ "MIT" ]
null
null
null
cdn_static_website/settings/components/caches.py
soulraven/cdn_small
e2415b39089cb761ddfe1748e443abd9c4080e83
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- # Caching # https://docs.djangoproject.com/en/3.2/topics/cache/ CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', }, 'staticfiles': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } }
23.1875
67
0.595687
c6688c53bdf0944e2decf9c1074d53646b7d5869
28
css
CSS
katana/wui/core/static/core/css/panel_color.css
warriorframework/Katanaframework
9dc78df9d0c8f19ef5eaaa8690fbfa1ad885b323
[ "Apache-2.0" ]
1
2020-09-30T11:14:14.000Z
2020-09-30T11:14:14.000Z
katana/wui/core/static/core/css/panel_color.css
warriorframework/Katanaframework
9dc78df9d0c8f19ef5eaaa8690fbfa1ad885b323
[ "Apache-2.0" ]
4
2020-06-06T01:55:04.000Z
2021-06-10T22:57:50.000Z
katana/wui/core/static/core/css/panel_color.css
warriorframework/Katanaframework
9dc78df9d0c8f19ef5eaaa8690fbfa1ad885b323
[ "Apache-2.0" ]
1
2020-09-17T08:20:09.000Z
2020-09-17T08:20:09.000Z
.header {background:#343a40}
28
28
0.785714
069200b7e9b3b290e4aa090bc7dcb812c2571caf
9,963
kt
Kotlin
src/main/kotlin/pl/treksoft/kvision/form/select/SimpleSelectInput.kt
lorefnon/kvision
aafab981dbd09df6c4b69057c2028edb359d9f33
[ "MIT" ]
null
null
null
src/main/kotlin/pl/treksoft/kvision/form/select/SimpleSelectInput.kt
lorefnon/kvision
aafab981dbd09df6c4b69057c2028edb359d9f33
[ "MIT" ]
null
null
null
src/main/kotlin/pl/treksoft/kvision/form/select/SimpleSelectInput.kt
lorefnon/kvision
aafab981dbd09df6c4b69057c2028edb359d9f33
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017-present Robert Jaros * * 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 pl.treksoft.kvision.form.select import com.github.snabbdom.VNode import pl.treksoft.kvision.core.AttributeSetBuilder import pl.treksoft.kvision.core.ClassSetBuilder import pl.treksoft.kvision.core.Container import pl.treksoft.kvision.core.StringPair import pl.treksoft.kvision.form.FormInput import pl.treksoft.kvision.form.InputSize import pl.treksoft.kvision.form.ValidationStatus import pl.treksoft.kvision.html.TAG import pl.treksoft.kvision.html.Tag import pl.treksoft.kvision.panel.SimplePanel import pl.treksoft.kvision.state.ObservableState import pl.treksoft.kvision.state.bind import pl.treksoft.kvision.utils.set internal const val KVNULL = "#kvnull" /** * Simple select component. * * @constructor * @param options an optional list of options (value to label pairs) for the select control * @param value select input value * @param emptyOption determines if an empty option is automatically generated * @param multiple allows multiple value selection (multiple values are comma delimited) * @param selectSize the number of visible options * @param classes a set of CSS class names */ open class SimpleSelectInput( options: List<StringPair>? = null, value: String? = null, emptyOption: Boolean = false, multiple: Boolean = false, selectSize: Int? = null, classes: Set<String> = setOf() ) : SimplePanel(classes + "form-control"), FormInput, ObservableState<String?> { protected val observers = mutableListOf<(String?) -> Unit>() /** * A list of options (value to label pairs) for the select control. */ var options by refreshOnUpdate(options) { setChildrenFromOptions() } /** * Text input value. */ var value by refreshOnUpdate(value) { refreshState(); observers.forEach { ob -> ob(it) } } /** * The value of the selected child option. * * This value is placed directly in the generated HTML code, while the [value] property is dynamically * bound to the select component. */ var startValue by refreshOnUpdate(value) { this.value = it; selectOption() } /** * The name attribute of the generated HTML input element. */ override var name: String? by refreshOnUpdate() /** * Determines if the field is disabled. */ override var disabled by refreshOnUpdate(false) /** * Determines if the text input is automatically focused. */ var autofocus: Boolean? by refreshOnUpdate() /** * Determines if an empty option is automatically generated. */ var emptyOption by refreshOnUpdate(emptyOption) { setChildrenFromOptions() } /** * Determines if multiple value selection is allowed. */ var multiple by refreshOnUpdate(multiple) /** * The number of visible options. */ var selectSize: Int? by refreshOnUpdate(selectSize) /** * The size of the input. */ override var size: InputSize? by refreshOnUpdate() /** * The validation status of the input. */ override var validationStatus: ValidationStatus? by refreshOnUpdate() /** * The index of currently selected option or -1 if none. */ @Suppress("UnsafeCastFromDynamic") var selectedIndex: Int get() = getElement()?.asDynamic()?.selectedIndex ?: value?.let { v -> val emptyIndex = if (emptyOption) 1 else 0 options?.map(StringPair::first)?.indexOf(v)?.let { it + emptyIndex } } ?: -1 set(value) { getElement()?.asDynamic()?.selectedIndex = value if (value == -1) this.value = null options?.getOrNull(value)?.let { this.value = it.first } } init { setChildrenFromOptions() this.setInternalEventListener<SimpleSelectInput> { change = { val v = getElementJQuery()?.`val`() self.value = v?.let { calculateValue(it) } } } } protected open fun calculateValue(v: Any): String? { return if (this.multiple) { @Suppress("UNCHECKED_CAST") val arr = v as? Array<String> if (arr != null && arr.isNotEmpty()) { arr.filter { it != "" }.joinToString(",") } else { null } } else { val vs = v as String? if (vs != null && vs != "" && vs != KVNULL) { vs } else { null } } } override fun render(): VNode { return render("select", childrenVNodes()) } private fun setChildrenFromOptions() { super.removeAll() if (emptyOption) { super.add(Tag(TAG.OPTION, "", attributes = mapOf("value" to KVNULL))) } val valueSet = if (this.multiple) value?.split(",") ?: emptySet() else setOf(value) options?.let { val c = it.map { val attributes = if (valueSet.contains(it.first)) { mapOf("value" to it.first, "selected" to "selected") } else { mapOf("value" to it.first) } Tag(TAG.OPTION, it.second, attributes = attributes) } super.addAll(c) } } private fun selectOption() { val valueSet = if (this.multiple) value?.split(",") ?: emptySet() else setOf(value) children.forEach { child -> if (child is Tag && child.type == TAG.OPTION) { if (valueSet.contains(child.getAttribute("value"))) { child.setAttribute("selected", "selected") } else { child.removeAttribute("selected") } } } } override fun buildClassSet(classSetBuilder: ClassSetBuilder) { super.buildClassSet(classSetBuilder) classSetBuilder.add(validationStatus) classSetBuilder.add(size) } override fun buildAttributeSet(attributeSetBuilder: AttributeSetBuilder) { super.buildAttributeSet(attributeSetBuilder) name?.let { attributeSetBuilder.add("name", it) } if (multiple) { attributeSetBuilder.add("multiple") } selectSize?.let { attributeSetBuilder.add("size", "$it") } autofocus?.let { if (it) { attributeSetBuilder.add("autofocus") } } if (disabled) { attributeSetBuilder.add("disabled") } } override fun afterInsert(node: VNode) { refreshState() } protected open fun refreshState() { value?.let { if (this.multiple) { getElementJQuery()?.`val`(it.split(",").toTypedArray()) } else { getElementJQuery()?.`val`(it) } } ?: getElementJQueryD()?.`val`(null) } /** * Makes the input element focused. */ override fun focus() { getElementJQuery()?.focus() } /** * Makes the input element blur. */ override fun blur() { getElementJQuery()?.blur() } override fun getState(): String? = value override fun subscribe(observer: (String?) -> Unit): () -> Unit { observers += observer observer(value) return { observers -= observer } } } /** * DSL builder extension function. * * It takes the same parameters as the constructor of the built component. */ fun Container.simpleSelectInput( options: List<StringPair>? = null, value: String? = null, emptyOption: Boolean = false, multiple: Boolean = false, selectSize: Int? = null, classes: Set<String>? = null, className: String? = null, init: (SimpleSelectInput.() -> Unit)? = null ): SimpleSelectInput { val simpleSelectInput = SimpleSelectInput( options, value, emptyOption, multiple, selectSize, classes ?: className.set ).apply { init?.invoke(this) } this.add(simpleSelectInput) return simpleSelectInput } /** * DSL builder extension function for observable state. * * It takes the same parameters as the constructor of the built component. */ fun <S> Container.simpleSelectInput( state: ObservableState<S>, options: List<StringPair>? = null, value: String? = null, emptyOption: Boolean = false, multiple: Boolean = false, selectSize: Int? = null, classes: Set<String>? = null, className: String? = null, init: (SimpleSelectInput.(S) -> Unit) ) = simpleSelectInput( options, value, emptyOption, multiple, selectSize, classes, className ).bind(state, true, init)
31.429022
106
0.608953