repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
de-jcup/eclipse-bash-editor
basheditor-plugin/src/main/java/de/jcup/basheditor/debug/launch/CommandStringVariableReplaceSupport.java
/* * Copyright 2019 <NAME> * * 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 de.jcup.basheditor.debug.launch; import java.util.Map; public class CommandStringVariableReplaceSupport { public String replaceVariables(String commandLineWithVariables, Map<String,String> mapping) { if (mapping==null) { return commandLineWithVariables; } String result = ""+commandLineWithVariables; for (String key: mapping.keySet()) { String replace = mapping.get(key); if (replace==null) { continue; } String search = buildSearchString(key); int length = search.length(); int index = -1; while ( (index = result.indexOf(search))!=-1) { StringBuilder sb = new StringBuilder(); sb.append(result.substring(0,index)); sb.append(replace); int indexAfterReplace = index+length; if (result.length()>indexAfterReplace) { sb.append(result.substring(indexAfterReplace)); } result = sb.toString(); }; } return result; } private String buildSearchString(String key) { return "${"+key+"}"; } }
poy/loggrebutterfly
master/internal/end2end/helheim_fixed_test.go
<reponame>poy/loggrebutterfly // This file was generated by github.com/nelsam/hel. Do not // edit this code by hand unless you *really* know what you're // doing. Expect any changes made manually to be overwritten // the next time hel regenerates this file. package end2end_test import ( "github.com/poy/loggrebutterfly/api/intra" pb "github.com/poy/talaria/api/v1" "golang.org/x/net/context" ) type mockSchedulerServer struct { CreateCalled chan bool CreateInput struct { Arg0 chan context.Context Arg1 chan *pb.CreateInfo } CreateOutput struct { Ret0 chan *pb.CreateResponse Ret1 chan error } ListClusterInfoCalled chan bool ListClusterInfoInput struct { Arg0 chan context.Context Arg1 chan *pb.ListInfo } ListClusterInfoOutput struct { Ret0 chan *pb.ListResponse Ret1 chan error } } func newMockSchedulerServer() *mockSchedulerServer { m := &mockSchedulerServer{} m.CreateCalled = make(chan bool, 100) m.CreateInput.Arg0 = make(chan context.Context, 100) m.CreateInput.Arg1 = make(chan *pb.CreateInfo, 100) m.CreateOutput.Ret0 = make(chan *pb.CreateResponse, 100) m.CreateOutput.Ret1 = make(chan error, 100) m.ListClusterInfoCalled = make(chan bool, 100) m.ListClusterInfoInput.Arg0 = make(chan context.Context, 100) m.ListClusterInfoInput.Arg1 = make(chan *pb.ListInfo, 100) m.ListClusterInfoOutput.Ret0 = make(chan *pb.ListResponse, 100) m.ListClusterInfoOutput.Ret1 = make(chan error, 100) return m } func (m *mockSchedulerServer) Create(arg0 context.Context, arg1 *pb.CreateInfo) (*pb.CreateResponse, error) { m.CreateCalled <- true m.CreateInput.Arg0 <- arg0 m.CreateInput.Arg1 <- arg1 return <-m.CreateOutput.Ret0, <-m.CreateOutput.Ret1 } func (m *mockSchedulerServer) ListClusterInfo(arg0 context.Context, arg1 *pb.ListInfo) (*pb.ListResponse, error) { m.ListClusterInfoCalled <- true m.ListClusterInfoInput.Arg0 <- arg0 m.ListClusterInfoInput.Arg1 <- arg1 return <-m.ListClusterInfoOutput.Ret0, <-m.ListClusterInfoOutput.Ret1 } type mockDataNodeServer struct { ReadMetricsCalled chan bool ReadMetricsInput struct { Arg0 chan context.Context Arg1 chan *intra.ReadMetricsInfo } ReadMetricsOutput struct { Ret0 chan *intra.ReadMetricsResponse Ret1 chan error } } func newMockDataNodeServer() *mockDataNodeServer { m := &mockDataNodeServer{} m.ReadMetricsCalled = make(chan bool, 100) m.ReadMetricsInput.Arg0 = make(chan context.Context, 100) m.ReadMetricsInput.Arg1 = make(chan *intra.ReadMetricsInfo, 100) m.ReadMetricsOutput.Ret0 = make(chan *intra.ReadMetricsResponse, 100) m.ReadMetricsOutput.Ret1 = make(chan error, 100) return m } func (m *mockDataNodeServer) ReadMetrics(arg0 context.Context, arg1 *intra.ReadMetricsInfo) (*intra.ReadMetricsResponse, error) { m.ReadMetricsCalled <- true m.ReadMetricsInput.Arg0 <- arg0 m.ReadMetricsInput.Arg1 <- arg1 return <-m.ReadMetricsOutput.Ret0, <-m.ReadMetricsOutput.Ret1 }
FreCap/sql
legacy/src/main/java/com/amazon/opendistroforelasticsearch/sql/legacy/expression/domain/BindingTuple.java
<reponame>FreCap/sql /* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazon.opendistroforelasticsearch.sql.legacy.expression.domain; import com.amazon.opendistroforelasticsearch.sql.legacy.expression.model.ExprMissingValue; import com.amazon.opendistroforelasticsearch.sql.legacy.expression.model.ExprValue; import com.amazon.opendistroforelasticsearch.sql.legacy.expression.model.ExprValueFactory; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Singular; import org.json.JSONObject; import java.util.Map; import java.util.stream.Collectors; /** * BindingTuple represents the a relationship between bindingName and ExprValue. * e.g. The operation output column name is bindingName, the value is the ExprValue. */ @Builder @Getter @EqualsAndHashCode public class BindingTuple { @Singular("binding") private final Map<String, ExprValue> bindingMap; /** * Resolve the Binding Name in BindingTuple context. * * @param bindingName binding name. * @return binding value. */ public ExprValue resolve(String bindingName) { return bindingMap.getOrDefault(bindingName, new ExprMissingValue()); } @Override public String toString() { return bindingMap.entrySet() .stream() .map(entry -> String.format("%s:%s", entry.getKey(), entry.getValue())) .collect(Collectors.joining(",", "<", ">")); } public static BindingTuple from(Map<String, Object> map) { return from(new JSONObject(map)); } public static BindingTuple from(JSONObject json) { Map<String, Object> map = json.toMap(); BindingTupleBuilder bindingTupleBuilder = BindingTuple.builder(); map.forEach((key, value) -> bindingTupleBuilder.binding(key, ExprValueFactory.from(value))); return bindingTupleBuilder.build(); } }
JamesCao2048/BlizzardData
Corpus/birt/4507.java
/************************************************************************************* * Copyright (c) 2004 Actuate Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - Initial implementation. ************************************************************************************/ package org.eclipse.birt.report.taglib.util; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspWriter; import org.eclipse.birt.report.engine.api.IReportDocument; import org.eclipse.birt.report.engine.api.IReportRunnable; import org.eclipse.birt.report.exception.ViewerException; import org.eclipse.birt.report.model.api.IModuleOption; import org.eclipse.birt.report.resource.ResourceConstants; import org.eclipse.birt.report.service.BirtViewerReportDesignHandle; import org.eclipse.birt.report.service.ReportEngineService; import org.eclipse.birt.report.service.api.IViewerReportDesignHandle; import org.eclipse.birt.report.taglib.component.ViewerField; import org.eclipse.birt.report.utility.BirtUtility; import org.eclipse.birt.report.utility.ParameterAccessor; /** * Utilities for Birt tags * */ public class BirtTagUtil { /** * Convert String to correct boolean value. * * @param bool * @return */ public static String convertBooleanValue( String bool ) { boolean b = Boolean.valueOf( bool ).booleanValue( ); return String.valueOf( b ); } /** * Convert String to boolean. * * @param bool * @return */ public static boolean convertToBoolean( String bool ) { if ( bool == null ) return false; return Boolean.valueOf( bool ).booleanValue( ); } /** * Returns the output format.Default value is html. * * @param format * @return */ public static String getFormat( String format ) { if ( format == null || format.length( ) <= 0 ) return ParameterAccessor.PARAM_FORMAT_HTML; if ( format.equalsIgnoreCase( ParameterAccessor.PARAM_FORMAT_HTM ) ) return ParameterAccessor.PARAM_FORMAT_HTML; return format; } /** * Get report locale. * * @param request * HttpServletRequest * @param locale * String * @return locale */ public static Locale getLocale( HttpServletRequest request, String sLocale ) { Locale locale = null; // Get Locale from String value locale = ParameterAccessor.getLocaleFromString( sLocale ); // Get Locale from client browser if ( locale == null ) locale = request.getLocale( ); // Get Locale from Web Context if ( locale == null ) locale = ParameterAccessor.getWebAppLocale(); return locale; } /** * Get report time zone. * * @param request * HttpServletRequest * @param timeZone time zone * String * @return locale */ public static TimeZone getTimeZone( HttpServletRequest request, String sTimeZone ) { TimeZone timeZone = null; // Get Locale from String value timeZone = ParameterAccessor.getTimeZoneFromString( sTimeZone ); // Get Locale from Web Context if ( timeZone == null ) timeZone = ParameterAccessor.getWebAppTimeZone(); return timeZone; } /** * If a report file name is a relative path, it is relative to document * folder. So if a report file path is relative path, it's absolute path is * synthesized by appending file path to the document folder path. * * @param file * @return */ public static String createAbsolutePath( String filePath ) { if ( filePath != null && filePath.trim( ).length( ) > 0 && ParameterAccessor.isRelativePath( filePath ) ) { return ParameterAccessor.workingFolder + File.separator + filePath; } return filePath; } /** * Returns report design handle * * @param request * @param viewer * @return * @throws Exception */ public static IViewerReportDesignHandle getDesignHandle( HttpServletRequest request, ViewerField viewer ) throws Exception { if ( viewer == null ) return null; IViewerReportDesignHandle design = null; IReportRunnable reportRunnable = null; // Get the absolute report design and document file path String designFile = ParameterAccessor.getReport( request, viewer .getReportDesign( ) ); String documentFile = ParameterAccessor.getReportDocument( request, viewer.getReportDocument( ), false ); // check if document file path is valid boolean isValidDocument = ParameterAccessor.isValidFilePath( request, viewer .getReportDocument( ) ); if ( documentFile != null && isValidDocument ) { // open the document instance try { IReportDocument reportDocumentInstance = ReportEngineService .getInstance( ).openReportDocument( designFile, documentFile, getModuleOptions( viewer ) ); if ( reportDocumentInstance != null ) { viewer.setDocumentInUrl( true ); reportRunnable = reportDocumentInstance.getReportRunnable( ); reportDocumentInstance.close( ); } } catch ( Exception e ) { } } // if report runnable is null, then get it from design file if ( reportRunnable == null ) { // if only set __document parameter, throw exception directly if ( documentFile != null && designFile == null ) { if ( isValidDocument ) throw new ViewerException( ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_FILE_ERROR, new String[]{documentFile} ); else throw new ViewerException( ResourceConstants.GENERAL_EXCEPTION_DOCUMENT_ACCESS_ERROR, new String[]{documentFile} ); } // check if the report file path is valid if ( !ParameterAccessor.isValidFilePath( request, viewer.getReportDesign( ) ) ) { throw new ViewerException( ResourceConstants.GENERAL_EXCEPTION_REPORT_ACCESS_ERROR, new String[]{designFile} ); } else { reportRunnable = BirtUtility.getRunnableFromDesignFile( request, designFile, getModuleOptions( viewer ) ); if ( reportRunnable == null ) { throw new ViewerException( ResourceConstants.GENERAL_EXCEPTION_REPORT_FILE_ERROR, new String[]{ new File( designFile ).getName( ) } ); } } } if ( reportRunnable != null ) { design = new BirtViewerReportDesignHandle( IViewerReportDesignHandle.RPT_RUNNABLE_OBJECT, reportRunnable ); } return design; } /** * Create Module Options * * @param viewer * @return */ public static Map getModuleOptions( ViewerField viewer ) { if ( viewer == null ) return null; Map options = new HashMap( ); String resourceFolder = viewer.getResourceFolder( ); if ( resourceFolder == null || resourceFolder.trim( ).length( ) <= 0 ) resourceFolder = ParameterAccessor.birtResourceFolder; options.put( IModuleOption.RESOURCE_FOLDER_KEY, resourceFolder ); options.put( IModuleOption.PARSER_SEMANTIC_CHECK_KEY, Boolean.FALSE ); return options; } public static void writeScript(JspWriter writer, String content ) throws IOException { writer.write( "\n<script language=\"JavaScript\">\n" ); //$NON-NLS-1$ writer.write( content ); writer.write( "</script>\n" ); //$NON-NLS-1$ } public static void writeExtScript(JspWriter writer, String fileName ) throws IOException { writer .write( "<script src=\"" //$NON-NLS-1$ + fileName + "\" type=\"text/javascript\"></script>\n" ); //$NON-NLS-1$ } public static void writeExtScripts( JspWriter writer, String baseUrl, String[] files ) throws IOException { for ( int i = 0; i < files.length; i++ ) { writeExtScript(writer, baseUrl + files[i]); } } public static void writeOption(JspWriter writer, String label, String value, boolean selected ) throws IOException { writer.write( "<option " ); //$NON-NLS-1$ writer .write( " value=\"" + ParameterAccessor.htmlEncode( value ) + "\" " ); //$NON-NLS-1$ //$NON-NLS-2$ if ( selected ) { writer.write( " selected " ); //$NON-NLS-1$ } writer.write( ">"); //$NON-NLS-1$ writer.write( ParameterAccessor .htmlEncode( label ) + "</option>\n" ); //$NON-NLS-1$ } }
TheoStanica/Lunch
Backend/src/middleware/authValidation.js
<gh_stars>1-10 const jwt = require('jsonwebtoken'); const ForbiddenError = require('../errors/forbiddenError'); const UnauthorizedError = require('../errors/unauthorizedError'); const { accountRole } = require('../utils/enums'); const authValidation = (req, res, next) => { const accessToken = req.header('authorization'); if (!accessToken) { throw new ForbiddenError(); } try { return jwt.verify( accessToken.split(' ')[1], process.env.ACCESS_TOKEN_SECRET ); } catch (errror) { throw new UnauthorizedError(); } }; const userAuthValidation = (req, res, next) => { const payload = authValidation(req, res, next); req.user = payload; next(); }; const adminAuthValidation = (req, res, next) => { const payload = authValidation(req, res, next); if (payload.role === accountRole.admin) { req.user = payload; next(); } else { throw new UnauthorizedError(); } }; module.exports = { userAuthValidation, adminAuthValidation, };
nathancashmore/GliderRider
src/main/java/uk/co/staticvoid/gliderrider/domain/CourseTime.java
<filename>src/main/java/uk/co/staticvoid/gliderrider/domain/CourseTime.java package uk.co.staticvoid.gliderrider.domain; import org.bukkit.configuration.serialization.ConfigurationSerializable; import java.util.HashMap; import java.util.Map; public class CourseTime implements Comparable<CourseTime>, ConfigurationSerializable { private String player; private Long time; public CourseTime() {} public CourseTime(String player, Long time) { this.player = player; this.time = time; } public CourseTime(Map<String, Object> courseTimeAsMap) { this.player = (String)courseTimeAsMap.get("player"); Integer timeAsInteger = (Integer)courseTimeAsMap.get("time"); this.time = timeAsInteger.longValue(); } public String getPlayer() { return player; } public Long getTime() { return time; } @Override public String toString() { return "Player: " + player + " - " + time + " ms"; } @Override public int compareTo(CourseTime o) { return Long.compare(this.getTime(), o.getTime()); } @Override public Map<String, Object> serialize() { Map<String, Object> courseTimeAsMap = new HashMap<>(); courseTimeAsMap.put("player", this.player); courseTimeAsMap.put("time", this.time); return courseTimeAsMap; } }
AeonGames/AeonGUI
common/pcx/pcx.cpp
<reponame>AeonGames/AeonGUI<filename>common/pcx/pcx.cpp<gh_stars>1-10 /****************************************************************************** Copyright 2010-2013 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "pcx.h" #include <iostream> #include <fstream> Pcx::Pcx() : pixels ( NULL ), pixels_size ( 0 ) { memset ( &header, 0, sizeof ( Header ) ); } Pcx::~Pcx() { Unload(); } bool Pcx::Encode ( uint32_t width, uint32_t height, void* buffer, uint32_t buffer_size ) { header.Identifier = 0x0A; header.Version = 5; header.Encoding = 1; header.BitsPerPixel = 8; header.XStart = 0; header.YStart = 0; header.XEnd = width - 1; header.YEnd = height - 1; header.HorzRes = 300; header.VertRes = 300; header.NumBitPlanes = 3; header.BytesPerLine = width; header.PaletteType = 1; pixels_size = PadPixels ( width, height, buffer, buffer_size ); pixels = new uint8_t[pixels_size]; PadPixels ( width, height, buffer, buffer_size ); return true; } uint32_t Pcx::PadPixels ( uint32_t width, uint32_t height, void* buffer, uint32_t buffer_size ) { // This function is untested uint32_t datasize = 0; uint8_t counter = 0; uint8_t* scanline = ( uint8_t* ) buffer; uint8_t* encoded_pixel = ( uint8_t* ) pixels; uint8_t* encoded_scanline = new uint8_t[width * 2]; // worst case scenario all bytes are different uint32_t scanline_count = 0; uint8_t byte; for ( uint32_t y = 0; y < height; ++y ) { byte = scanline[0]; counter = 1; scanline_count = 0; for ( uint32_t x = 1; x < width; ++x ) { if ( ( byte == scanline[x] ) && ( counter < 63 ) ) { counter++; } else { if ( encoded_pixel != NULL ) { encoded_scanline[scanline_count++] = counter | 0xC0; encoded_scanline[scanline_count++] = byte; } datasize += 2; byte = scanline[x]; counter = 1; } } // we're done a scanline, write the remnant and advance to the next. if ( encoded_pixel != NULL ) { encoded_scanline[scanline_count++] = counter | 0xC0; encoded_scanline[scanline_count++] = byte; memcpy ( encoded_pixel, encoded_scanline, scanline_count ); encoded_pixel += scanline_count; memcpy ( encoded_pixel, encoded_scanline, scanline_count ); encoded_pixel += scanline_count; memcpy ( encoded_pixel, encoded_scanline, scanline_count ); encoded_pixel += scanline_count; } datasize += 2; scanline += width; } delete[] encoded_scanline; return datasize * 3; } bool Pcx::Save ( const char* filename ) { std::ofstream pcx; pcx.open ( filename, std::ios_base::out | std::ios_base::binary ); if ( !pcx.is_open() ) { std::cerr << "Problem opening " << filename << " for writting." << std::endl; return false; } pcx.write ( ( const char* ) &header, sizeof ( Header ) ); pcx.write ( ( const char* ) pixels, sizeof ( char ) *pixels_size ); pcx.close(); return true; } uint32_t Pcx::GetWidth() { return header.XEnd - header.XStart + 1; } uint32_t Pcx::GetHeight() { return header.YEnd - header.YStart + 1; } const uint8_t* Pcx::GetPixels() { return pixels; } uint8_t Pcx::GetNumBitPlanes() { return header.NumBitPlanes; } uint16_t Pcx::GetXStretchStart() { return header.XStretchStart; } uint16_t Pcx::GetXStretchEnd() { return header.XStretchEnd; } uint16_t Pcx::GetStretchWidth() { return header.XStretchEnd - header.XStretchStart; } uint16_t Pcx::GetXPadStart() { return header.XPadStart; } uint16_t Pcx::GetXPadEnd() { return header.XPadEnd; } uint16_t Pcx::GetPadWidth() { return header.XPadEnd - header.XPadStart; } uint16_t Pcx::GetYStretchStart() { return header.YStretchStart; } uint16_t Pcx::GetYStretchEnd() { return header.YStretchEnd; } uint16_t Pcx::GetStretchHeight() { return header.YStretchEnd - header.YStretchStart; } uint16_t Pcx::GetYPadStart() { return header.YPadStart; } uint16_t Pcx::GetYPadEnd() { return header.YPadEnd; } uint16_t Pcx::GetPadHeight() { return header.YPadEnd - header.YPadStart; } bool Pcx::Decode ( uint32_t buffer_size, void* buffer ) { memcpy ( &header, buffer, sizeof ( Header ) ); if ( ( header.Version != 5 ) && ( header.Encoding != 1 ) && ( header.BitsPerPixel != 8 ) ) { // Support only file format version 5 for now. Unload(); return false; } uint32_t scanline_length = header.NumBitPlanes * header.BytesPerLine; uint8_t* byte = reinterpret_cast<uint8_t*> ( buffer ) + sizeof ( Header ); pixels = new uint8_t[ scanline_length * GetHeight() ]; for ( uint32_t i = 0; i < GetHeight(); ++i ) { for ( uint8_t j = 0; j < header.NumBitPlanes; ++j ) { uint8_t* pixel = pixels + ( scanline_length * i ) + j; for ( uint16_t k = 0; k < header.BytesPerLine; ) { if ( ( byte[0] & 0xC0 ) == 0xC0 ) { uint8_t count = byte[0] & 0x3F; for ( uint8_t l = 0; l < count; ++l ) { *pixel = byte[1]; pixel += header.NumBitPlanes; } byte += 2; k += count; } else { *pixel = byte[0]; pixel += header.NumBitPlanes; ++byte; ++k; } } } } return true; } bool Pcx::Load ( const char* filename ) { uint8_t* buffer = NULL; uint32_t buffer_size = 0; bool retval; std::ifstream pcx; pcx.open ( filename, std::ios_base::in | std::ios_base::binary ); if ( !pcx.is_open() ) { std::cerr << "Problem opening " << filename << " for reading." << std::endl; return false; } pcx.seekg ( 0, std::ios_base::end ); buffer_size = static_cast<uint32_t> ( pcx.tellg() ); pcx.seekg ( 0, std::ios_base::beg ); buffer = new uint8_t[buffer_size]; pcx.read ( reinterpret_cast<char*> ( buffer ), buffer_size ); pcx.close(); retval = Decode ( buffer_size, buffer ); delete[] buffer; return retval; } void Pcx::Unload ( ) { if ( pixels != NULL ) { delete[] pixels; pixels = NULL; pixels_size = 0; memset ( &header, 0, sizeof ( Header ) ); } }
hobbypunk90/SMBJ
UI/SplashScreen/src/main/java/de/thm/mni/mhpp11/smbj/ui/splashscreen/SplashActorManagerPlugin.java
<reponame>hobbypunk90/SMBJ package de.thm.mni.mhpp11.smbj.ui.splashscreen; import de.thm.mni.mhpp11.smbj.actors.IActor; import de.thm.mni.mhpp11.smbj.manager.ActorManagerPlugin; import de.thm.mni.mhpp11.smbj.ui.splashscreen.actors.SplashActor; public class SplashActorManagerPlugin extends ActorManagerPlugin{ @Override protected Class<? extends IActor> isActorClass() { return SplashActor.class; } }
BuildForSDG/Team-037-Products-backend
src/middleware/validation/farm.js
import Joi from '@hapi/joi'; import { name } from '../index'; export const createFarmSchema = Joi.object({ userId: Joi.string(), farmName: name('farmName').required(), address: Joi.string().required(), country: Joi.string().required(), farmSize: Joi.string().required(), description: Joi.string().required(), imageUrl: Joi.string().uri().required(), farmType: Joi.string().required(), farmingExperience: Joi.string().required() }); export const editFarmSchema = Joi.object({ farmId: Joi.string(), farmName: name('farmName'), address: Joi.string(), country: Joi.string(), farmSize: Joi.string(), description: Joi.string(), imageUrl: Joi.string().uri(), farmType: Joi.string(), farmingExperience: Joi.string() });
kagemeka/atcoder-submissions
jp.atcoder/abc138/abc138_c/12000660.py
import sys n, *v = map(int, sys.stdin.read().split()) v.sort() def main(): res = v[0] for i in range(1, n): res = (res + v[i]) / 2 print(res) if __name__ == '__main__': main()
anthonykoch/bladejs
test/boilerplate.js
'use strict'; const test = require('tape'); test('Testname', (assert) => { const actual = true; const expected = false; assert.equals(actual, expected); assert.end(); });
jqueguiner/cds
engine/hatchery/vsphere/helper_test.go
<reponame>jqueguiner/cds<gh_stars>1000+ package vsphere import ( "testing" "github.com/golang/mock/gomock" "github.com/ovh/cds/engine/hatchery/vsphere/mock_vsphere" ) func NewVSphereClientTest(t *testing.T) *mock_vsphere.MockVSphereClient { ctrl := gomock.NewController(t) t.Cleanup(func() { ctrl.Finish() }) mockClient := mock_vsphere.NewMockVSphereClient(ctrl) return mockClient }
SemanticBeeng/frameless
core/src/main/scala/frameless/CatalystNaN.scala
package frameless import scala.annotation.implicitNotFound /** Spark does NaN check only for these types */ @implicitNotFound("Columns of type ${A} cannot be NaN.") trait CatalystNaN[A] object CatalystNaN { private[this] val theInstance = new CatalystNaN[Any] {} private[this] def of[A]: CatalystNaN[A] = theInstance.asInstanceOf[CatalystNaN[A]] implicit val framelessFloatNaN : CatalystNaN[Float] = of[Float] implicit val framelessDoubleNaN : CatalystNaN[Double] = of[Double] }
sebastian-software/jasy
jasy/env/Task.py
<reponame>sebastian-software/jasy<gh_stars>1-10 # # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # Copyright 2013-2014 <NAME> # """Tasks are basically functions with some managment code allow them to run in jasyscript.py.""" import types import os import sys import inspect import subprocess import jasy.core.Console as Console import jasy.core.Util as Util from jasy.env.State import session from jasy import UserError __all__ = ("task", "executeTask", "runTask", "printTasks", "setCommand", "setOptions", "getOptions") class Task(object): __slots__ = ["func", "name", "curry", "availableArgs", "hasFlexArgs", "__doc__", "__name__"] def __init__(self, func, **curry): """Creates a task bound to the given function and currying in static parameters.""" self.func = func self.name = func.__name__ self.__name__ = "Task: %s" % func.__name__ # Circular reference to connect both, function and task func.task = self # The are curried in arguments which are being merged with # dynamic command line arguments on each execution self.curry = curry # Extract doc from function and attach it to the task self.__doc__ = inspect.getdoc(func) # Analyse arguments for help screen result = inspect.getfullargspec(func) self.availableArgs = result.args self.hasFlexArgs = result.varkw is not None # Register task globally addTask(self) def __call__(self, **kwargs): # Let session know about current task session.setCurrentTask(self.name) # Combine all arguments merged = {} merged.update(self.curry) merged.update(kwargs) # Execute internal function retval = self.func(**merged) # Let session know about current task session.setCurrentTask(None) # Return result return retval def __repr__(self): return "Task: " + self.__name__ def task(*args, **kwargs): """Specifies that this function is a task.""" if len(args) == 1: func = args[0] if isinstance(func, Task): return func elif isinstance(func, types.FunctionType): return Task(func) # Compat to old Jasy 0.7.x task declaration elif isinstance(func, str): return task(**kwargs) else: raise UserError("Invalid task") else: def wrapper(func): return Task(func, **kwargs) return wrapper # Local task managment __taskRegistry = {} def addTask(task): """Registers the given task with its name.""" if task.name in __taskRegistry: Console.debug("Overriding task: %s" % task.name) else: Console.debug("Registering task: %s" % task.name) __taskRegistry[task.name] = task def executeTask(taskname, **kwargs): """Executes the given task by name with any optional named arguments.""" if taskname in __taskRegistry: try: camelCaseArgs = {Util.camelize(key) : kwargs[key] for key in kwargs} return __taskRegistry[taskname](**camelCaseArgs) except UserError as err: raise except: Console.error("Unexpected error! Could not finish task %s successfully!" % taskname) raise else: raise UserError("No such task: %s" % taskname) def printTasks(indent=16): """Prints out a list of all avaible tasks and their descriptions.""" for name in sorted(__taskRegistry): obj = __taskRegistry[name] formattedName = name if obj.__doc__: space = (indent - len(name)) * " " print(" %s: %s%s" % (formattedName, space, Console.colorize(obj.__doc__, "magenta"))) else: print(" %s" % formattedName) if obj.availableArgs or obj.hasFlexArgs: text = "" if obj.availableArgs: text += Util.hyphenate("--%s <var>" % " <var> --".join(obj.availableArgs)) if obj.hasFlexArgs: if text: text += " ..." else: text += "--<name> <var>" print(" %s" % (Console.colorize(text, "grey"))) # Jasy reference for executing remote tasks __command = None __options = None def setCommand(cmd): """Sets the jasy command which should be used to execute tasks with runTask()""" global __command __command = cmd def getCommand(): """Returns the "jasy" command which is currently executed.""" return __command def setOptions(options): """ Sets currently configured command line options. Mainly used for printing help screens. """ global __options __options = options def getOptions(): """ Returns the options as passed to the jasy command. Useful for printing all command line arguments. """ return __options def runTask(project, task, **kwargs): """ Executes the given task of the given projects. This happens inside a new sandboxed session during which the current session is paused/resumed automatically. """ remote = session.getProjectByName(project) if remote is not None: remotePath = remote.getPath() remoteName = remote.getName() elif os.path.isdir(project): remotePath = project remoteName = os.path.basename(project) else: raise UserError("Unknown project or invalid path: %s" % project) Console.info("Running %s of project %s...", Console.colorize(task, "bold"), Console.colorize(remoteName, "bold")) # Pauses this session to allow sub process fully accessing the same projects session.pause() # Build parameter list from optional arguments params = ["--%s=%s" % (key, kwargs[key]) for key in kwargs] if not "prefix" in kwargs: params.append("--prefix=%s" % session.getCurrentPrefix()) # Full list of args to pass to subprocess args = [__command, task] + params # Change into sub folder and execute jasy task oldPath = os.getcwd() os.chdir(remotePath) returnValue = subprocess.call(args, shell=sys.platform == "win32") os.chdir(oldPath) # Resumes this session after sub process was finished session.resume() # Error handling if returnValue != 0: raise UserError("Executing of sub task %s from project %s failed" % (task, project))
injulkarnilesh/design-principles
CODE_SMELLS/MESSAGE_OBSESSION/example/fix/Direction.java
<reponame>injulkarnilesh/design-principles package CODE_SMELLS.MESSAGE_OBSESSION.example.fix; public class Direction { private final int deltaRow; private final int deltaColumn; private Direction(final int deltaRow, final int deltaColumn) { this.deltaRow = deltaRow; this.deltaColumn = deltaColumn; } public static Direction withDelta(final int deltaX, final int deltaY) { return new Direction(deltaX, deltaY); } public int getDeltaRow() { return deltaRow; } public int getDeltaColumn() { return deltaColumn; } }
greg-k-taylor/biothings.api
biothings/utils/sqlite3.py
<reponame>greg-k-taylor/biothings.api import os import sqlite3 import json from biothings import config from biothings.utils.hub_db import IDatabase from biothings.utils.dotfield import parse_dot_fields from biothings.utils.dataload import update_dict_recur from biothings.utils.common import json_serial def get_hub_db_conn(): return Database() def get_src_dump(): db = Database() return db[db.CONFIG.DATA_SRC_DUMP_COLLECTION] def get_src_master(): db = Database() return db[db.CONFIG.DATA_SRC_MASTER_COLLECTION] def get_src_build(): db = Database() return db[db.CONFIG.DATA_SRC_BUILD_COLLECTION] def get_src_build_config(): db = Database() return db[db.CONFIG.DATA_SRC_BUILD_CONFIG_COLLECTION] def get_data_plugin(): db = Database() return db[db.CONFIG.DATA_PLUGIN_COLLECTION] def get_api(): db = Database() return db[db.CONFIG.API_COLLECTION] def get_cmd(): db = Database() return db[db.CONFIG.CMD_COLLECTION] def get_event(): db = Database() return db[db.CONFIG.EVENT_COLLECTION] def get_last_command(): #dummy... return {"_id":1} def get_source_fullname(col_name): """ Assuming col_name is a collection created from an upload process, find the main source & sub_source associated. """ src_dump = get_src_dump() info = None for doc in src_dump.find(): if col_name in doc.get("upload",{}).get("jobs",{}).keys(): info = doc if info: name = info["_id"] if name != col_name: # col_name was a sub-source name return "%s.%s" % (name,col_name) else: return name class Database(IDatabase): def __init__(self): super(Database,self).__init__() self.name = self.CONFIG.DATA_HUB_DB_DATABASE if not os.path.exists(self.CONFIG.HUB_DB_BACKEND["sqlite_db_folder"]): os.makedirs(self.CONFIG.HUB_DB_BACKEND["sqlite_db_folder"]) self.dbfile = os.path.join(self.CONFIG.HUB_DB_BACKEND["sqlite_db_folder"],self.name) self.cols = {} @property def address(self): return self.dbfile def get_conn(self): return sqlite3.connect(self.dbfile) def collection_names(self): tables = self.get_conn().execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall() return [name[0] for name in tables] def create_collection(self,colname): return self[colname] def create_if_needed(self,table): existings = [tname[0] for tname in self.get_conn().execute("SELECT name FROM sqlite_master WHERE type='table' and " + \ "name = ?",(table,)).fetchall()] if not table in existings: # TODO: injection... self.get_conn().execute("CREATE TABLE %s (_id TEXT PRIMARY KEY, document TEXT)" % table).fetchone() def __getitem__(self, colname): if not colname in self.cols: self.create_if_needed(colname) self.cols[colname] = Collection(colname,self) return self.cols[colname] class Collection(object): def __init__(self, colname, db): self.colname = colname self.db = db def get_conn(self): return sqlite3.connect(self.db.dbfile) @property def name(self): return self.colname @property def database(self): return self.db def find_one(self,*args,**kwargs): if args and len(args) == 1 and type(args[0]) == dict: if len(args[0]) == 1 and "_id" in args[0]: strdoc = self.get_conn().execute("SELECT document FROM %s WHERE _id = ?" % self.colname,(args[0]["_id"],)).fetchone() if strdoc: return json.loads(strdoc[0]) else: return None else: return self.find(*args,find_one=True) elif args or kwargs: raise NotImplementedError("find(): %s %s" % (repr(args),repr(kwargs))) else: return self.find(find_one=True) def find(self,*args,**kwargs): results = [] if args and len(args) == 1 and type(args[0]) == dict and len(args[0]) > 0: # it's key/value search, let's iterate for doc in self.get_conn().execute("SELECT document FROM %s" % self.colname).fetchall(): found = False doc = json.loads(doc[0]) for k,v in args[0].items(): if k in doc: if doc[k] == v: found = True else: found = False break if found: if "find_one" in kwargs: return doc else: results.append(doc) return results elif not args or len(args) == 1 and len(args[0]) == 0: # nothing or empty dict return [json.loads(doc[0]) for doc in \ self.get_conn().execute("SELECT document FROM %s" % self.colname).fetchall()] else: raise NotImplementedError("find: args=%s kwargs=%s" % (repr(args),repr(kwargs))) def insert_one(self,doc): assert "_id" in doc with self.get_conn() as conn: conn.execute("INSERT INTO %s (_id,document) VALUES (?,?)" % self.colname, \ (doc["_id"],json.dumps(doc,default=json_serial))).fetchone() conn.commit() def update_one(self,query,what): assert len(what) == 1 and ("$set" in what or \ "$unset" in what or "$push" in what), "$set/$unset/$push operators not found" doc = self.find_one(query) if doc: if "$set" in what: # parse_dot_fields uses json.dumps internally, we can to make # sure everything is serializable first what = json.loads(json.dumps(what,default=json_serial)) what = parse_dot_fields(what["$set"]) doc = update_dict_recur(doc,what) elif "$unset" in what: for keytounset in what["$unset"].keys(): doc.pop(keytounset,None) elif "$push" in what: for listkey,elem in what["$push"].items(): assert not "." in listkey, "$push not supported for nested keys: %s" % listkey doc.setdefault(listkey,[]).append(elem) self.save(doc) def update(self,query,what): docs = self.find(query) for doc in docs: self.update_one({"_id":doc["_id"]},what) def save(self,doc): if self.find_one({"_id":doc["_id"]}): with self.get_conn() as conn: conn.execute("UPDATE %s SET document = ? WHERE _id = ?" % self.colname, (json.dumps(doc,default=json_serial),doc["_id"])) conn.commit() else: self.insert_one(doc) def replace_one(self,query,doc): orig = self.find_one(query) if orig: with self.get_conn() as conn: conn.execute("UPDATE %s SET document = ? WHERE _id = ?" % self.colname, (json.dumps(doc,default=json_serial),orig["_id"])) conn.commit() def remove(self,query): docs = self.find(query) with self.get_conn() as conn: for doc in docs: conn.execute("DELETE FROM %s WHERE _id = ?" % self.colname,(doc["_id"],)).fetchone() conn.commit() def count(self): return self.get_conn().execute("SELECT count(_id) FROM %s" % self.colname).fetchone()[0] def __getitem__(self, _id): return self.find_one({"_id":_id}) def __getstate__(self): self.__dict__.pop("db",None) return self.__dict__
emrys8/Questioner
server/controllers/rsvp.js
import db from '../db'; import { Meetup, Rsvp } from '../models/all'; import { sendResponse, sendServerErrorResponse } from './helpers'; export default { async getRsvps(req, res) { try { const rsvps = await Rsvp.find({ where: { meetup: req.params.meetupId } }); if (rsvps.length > 0) { return sendResponse({ res, status: 200, payload: { status: 200, data: rsvps } }); } return sendResponse({ res, status: 404, payload: { status: 404, error: 'There are no RSVPs for this meetup at the moment' } }); } catch (e) { return sendServerErrorResponse(res); } }, async makeRsvp(req, res) { try { const { meetupId } = req.params; const meetup = await Meetup.findById(meetupId); const { response } = req.body; const { userId } = req.decodedToken; if (meetup) { const rsvps = await Rsvp.find({ where: { '"user"': userId, meetup: meetupId } }); if (rsvps.length) { return sendResponse({ res, status: 409, payload: { status: 409, error: 'You have already rsvped for this meetup' } }); } const rsvpQueryResult = await db.queryDb({ text: `INSERT INTO Rsvp ("user", meetup, response) VALUES ($1, $2, $3) RETURNING *`, values: [userId, meetupId, response] }); const rsvp = rsvpQueryResult.rows[0]; const { id, topic } = meetup; const newRsvp = { meetup: id, topic, status: rsvp.response }; return sendResponse({ res, status: 201, payload: { status: 201, data: [newRsvp] } }); } return sendResponse({ res, status: 404, payload: { status: 404, error: 'The requested meetup does not exist' } }); } catch (e) { return sendServerErrorResponse(res); } }, async updateRsvp(req, res) { try { const { meetupId, rsvpId } = req.params; const { userId } = req.decodedToken; const rsvps = await Rsvp.find({ where: { id: rsvpId, meetup: meetupId, '"user"': userId } }); const rsvp = rsvps[0]; if (rsvp) { const updatedRsvpQueryResult = await db.queryDb({ text: `UPDATE Rsvp SET response=$1 WHERE id=$2 RETURNING *`, values: [req.body.response, rsvp.id] }); const updatedRsvp = updatedRsvpQueryResult.rows[0]; return sendResponse({ res, status: 200, payload: { status: 200, data: [updatedRsvp] } }); } return sendResponse({ res, status: 404, payload: { status: 404, error: 'You have not rsvped for this meetup' } }); } catch (e) { return sendServerErrorResponse(res); } }, async getRsvp(req, res) { try { const { meetupId, rsvpId } = req.params; const rsvps = await Rsvp.find({ where: { id: rsvpId, meetup: meetupId } }); const rsvp = rsvps[0]; if (rsvp) { return sendResponse({ res, status: 200, payload: { status: 200, data: [rsvp] } }); } return sendResponse({ res, status: 404, payload: { status: 404, error: 'The rsvp for the requested meetup does not exist' } }); } catch (e) { return sendServerErrorResponse(res); } } };
DFE-Digital/find-teacher-training
app/controllers/search/age_groups_controller.rb
module Search class AgeGroupsController < ApplicationController include FilterParameters before_action :build_backlink_query_parameters def new @age_groups_form = AgeGroupsForm.new(age_group: params[:age_group]) end def create @age_groups_form = AgeGroupsForm.new(age_group: form_params[:age_group]) if @age_groups_form.valid? if form_params[:age_group] == 'further_education' redirect_to results_path(further_education_params) else redirect_to subjects_path(filter_params[:search_age_groups_form]) end else render :new end end private def further_education_params filter_params[:search_age_groups_form].merge(age_group: @age_groups_form.age_group, subject_codes: ['41']) end def form_params params .require(:search_age_groups_form) .permit(:age_group) end def build_backlink_query_parameters @backlink_query_parameters = ResultsView.new(query_parameters: request.query_parameters) .query_parameters_with_defaults .except(:search_age_groups_form) end end end
PatrickTorgerson/Envy-docs
search/files_4.js
var searchData= [ ['utf8_2ehpp_0',['utf8.hpp',['../utf8_8hpp.html',1,'']]] ];
bulya/ramona
test.py
<filename>test.py<gh_stars>10-100 #!/usr/bin/env python2 # # Released under the BSD license. See LICENSE.txt file for details. # import ramona class TestConsoleApp(ramona.console_app): """ This application serves mostly for testing and as example. The programs run by this application usually fails to test different corner cases. """ pass if __name__ == '__main__': app = TestConsoleApp(configuration='./test.conf') app.run()
yoyooli8/jackrabbit-oak
oak-core/src/test/java/org/apache/jackrabbit/oak/security/user/UserInitializerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.security.user; import org.apache.jackrabbit.api.security.user.Authorizable; import org.apache.jackrabbit.api.security.user.User; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.jackrabbit.oak.AbstractSecurityTest; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.plugins.index.IndexConstants; import org.apache.jackrabbit.oak.spi.security.ConfigurationParameters; import org.apache.jackrabbit.oak.spi.security.principal.AdminPrincipal; import org.apache.jackrabbit.oak.spi.security.user.UserConstants; import org.apache.jackrabbit.oak.spi.security.user.util.UserUtility; import org.apache.jackrabbit.oak.util.NodeUtil; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * UserInitializerTest... TODO */ public class UserInitializerTest extends AbstractSecurityTest { private UserManager userMgr; private ConfigurationParameters config; @Override @Before public void before() throws Exception { super.before(); userMgr = getUserManager(); config = getUserConfiguration().getConfigurationParameters(); } @Test public void testBuildInUserExist() throws Exception { assertNotNull(userMgr.getAuthorizable(UserUtility.getAdminId(config))); assertNotNull(userMgr.getAuthorizable(UserUtility.getAnonymousId(config))); } @Test public void testAdminUser() throws Exception { Authorizable a = userMgr.getAuthorizable(UserUtility.getAdminId(config)); assertFalse(a.isGroup()); User admin = (User) a; assertTrue(admin.isAdmin()); assertTrue(admin.getPrincipal() instanceof AdminPrincipal); assertTrue(admin.getPrincipal() instanceof TreeBasedPrincipal); assertEquals(admin.getID(), admin.getPrincipal().getName()); } @Test public void testAnonymous() throws Exception { Authorizable a = userMgr.getAuthorizable(UserUtility.getAnonymousId(config)); assertFalse(a.isGroup()); User anonymous = (User) a; assertFalse(anonymous.isAdmin()); assertFalse(anonymous.getPrincipal() instanceof AdminPrincipal); assertTrue(anonymous.getPrincipal() instanceof TreeBasedPrincipal); assertEquals(anonymous.getID(), anonymous.getPrincipal().getName()); } @Test public void testUserContent() throws Exception { Authorizable a = userMgr.getAuthorizable(UserUtility.getAdminId(config)); assertNotNull(root.getTree(a.getPath())); a = userMgr.getAuthorizable(UserUtility.getAnonymousId(config)); assertNotNull(root.getTree(a.getPath())); } @Test public void testUserIndexDefinitions() throws Exception { Tree oakIndex = root.getTree('/' +IndexConstants.INDEX_DEFINITIONS_NAME); assertNotNull(oakIndex); Tree id = oakIndex.getChild("authorizableId"); assertIndexDefinition(id, UserConstants.REP_AUTHORIZABLE_ID, true); Tree princName = oakIndex.getChild("principalName"); assertIndexDefinition(princName, UserConstants.REP_PRINCIPAL_NAME, true); Tree members = oakIndex.getChild("members"); assertIndexDefinition(members, UserConstants.REP_MEMBERS, false); } private static void assertIndexDefinition(Tree tree, String propName, boolean isUnique) { assertNotNull(tree); NodeUtil node = new NodeUtil(tree); assertEquals(isUnique, node.getBoolean(IndexConstants.UNIQUE)); assertArrayEquals(new String[] {propName}, node.getNames(IndexConstants.PROPERTY_NAMES)); } }
hjc851/Dataset2-HowToDetectAdvancedSourceCodePlagiarism
Variant Programs/1-4/24/register/BreederCeremonies.java
package register; import indiscernible.YearWarder; import exporter.Operator; public class BreederCeremonies extends register.TournamentShow implements java.lang.Comparable<BreederCeremonies> { public exporter.Operator lessor; public static final java.lang.String BunsCommences = "CAN_START"; public static final java.lang.String ShallFinaleObjective = "WILL_FINISH_OBJECT"; public static final double infernalMinimum = 0.8658215609260662; public BreederCeremonies(double chance, String tip, Operator possessor) { this.opportunity = chance; this.stuff = tip; this.lessor = possessor; } public synchronized int compareTo(BreederCeremonies see) { double importance; importance = 0.792871771102463; if (this.opportunity < see.opportunity) return 1; else if (this.opportunity == see.opportunity) return 0; else return -1; } public synchronized void systemContest() { double premiumDepth; premiumDepth = 0.5407064573816783; indiscernible.YearWarder.readyDay(this.opportunity); this.lessor.procedureFutureObjective(); } public synchronized String toString() { double higherBound; higherBound = 0.749836031984433; return "owner: " + lessor + " info: " + stuff + " chrono: " + opportunity; } }
joansmith3/cloudify
restful/src/main/java/org/cloudifysource/rest/deploy/DeploymentConfig.java
/******************************************************************************* * Copyright (c) 2013 GigaSpaces Technologies Ltd. All rights reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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.cloudifysource.rest.deploy; import java.io.File; import org.cloudifysource.domain.Service; import org.cloudifysource.domain.cloud.Cloud; import org.cloudifysource.dsl.rest.request.InstallServiceRequest; /** * required deployment configuration. * * @author adaml * */ public class DeploymentConfig { private InstallServiceRequest installRequest; private String absolutePUName; private String applicationName; private String templateName; private Cloud cloud; private Service service; private String locators; private File packedFile; private byte[] cloudConfig; private String cloudOverrides; private String deploymentId; private String authGroups; public String getApplicationName() { return applicationName; } public void setApplicationName(final String applicationName) { this.applicationName = applicationName; } public String getTemplateName() { return templateName; } public void setTemplateName(final String templateName) { this.templateName = templateName; } public String getAbsolutePUName() { return absolutePUName; } public void setAbsolutePUName(final String absolutePUName) { this.absolutePUName = absolutePUName; } public Cloud getCloud() { return cloud; } public void setCloud(final Cloud cloud) { this.cloud = cloud; } public Service getService() { return service; } public void setService(final Service service) { this.service = service; } public String getLocators() { return locators; } public void setLocators(final String locators) { this.locators = locators; } public File getPackedFile() { return packedFile; } public void setPackedFile(final File packedFile) { this.packedFile = packedFile; } public byte[] getCloudConfig() { return cloudConfig; } public void setCloudConfig(final byte[] cloudConfig) { this.cloudConfig = cloudConfig; } public String getCloudOverrides() { return this.cloudOverrides; } public void setCloudOverrides(final String cloudOverrides) { this.cloudOverrides = cloudOverrides; } public String getDeploymentId() { return deploymentId; } public void setDeploymentId(final String deploymentId) { this.deploymentId = deploymentId; } public InstallServiceRequest getInstallRequest() { return installRequest; } public void setInstallRequest(final InstallServiceRequest installRequest) { this.installRequest = installRequest; } public String getAuthGroups() { return authGroups; } public void setAuthGroups(String authGroups) { this.authGroups = authGroups; } }
greenhand88/bootstrap-4-login-page
node_modules/colors/lib/maps/zebra.js
<reponame>greenhand88/bootstrap-4-login-page module['exports'] = function (colors) { return function (letter, i, exploded) { return i % 2 === 0 ? letter : colors.inverse(letter); }; };
dylanlee101/leetcode
code_week34_1214_1220/patching_array.py
<reponame>dylanlee101/leetcode ''' 给定一个已排序的正整数数组 nums,和一个正整数 n 。从 [1, n] 区间内选取任意个数字补充到 nums 中,使得 [1, n] 区间内的任何数字都可以用 nums 中某几个数字的和来表示。请输出满足上述要求的最少需要补充的数字个数。 示例 1: 输入: nums = [1,3], n = 6 输出: 1 解释: 根据 nums 里现有的组合 [1], [3], [1,3],可以得出 1, 3, 4。 现在如果我们将 2 添加到 nums 中, 组合变为: [1], [2], [3], [1,3], [2,3], [1,2,3]。 其和可以表示数字 1, 2, 3, 4, 5, 6,能够覆盖 [1, 6] 区间里所有的数。 所以我们最少需要添加一个数字。 示例 2: 输入: nums = [1,5,10], n = 20 输出: 2 解释: 我们需要添加 [2, 4]。 示例 3: 输入: nums = [1,2,2], n = 5 输出: 0 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/patching-array ''' class Solution: def minPatches(self, nums: List[int], n: int) -> int: patches, x = 0, 1 length, index = len(nums), 0 while x <= n: if index < length and nums[index] <= x: x += nums[index] index += 1 else: x <<= 1 patches += 1 return patches
rozhuk-im/opentoonz
toonz/sources/stdfx/gradients.h
#pragma once #ifndef GRADIENTS_H #define GRADIENTS_H #include "tfxparam.h" #include "trop.h" #include "trasterfx.h" struct MultiRAdialParams { int m_shrink; double m_scale; double m_intensity; double m_gridStep; }; enum GradientCurveType { EaseInOut = 0, Linear, EaseIn, EaseOut }; /*---------------------------------------------------------------------------*/ //! Deals with raster tiles and invokes multiradial functions void multiRadial(const TRasterP &ras, TPointD posTrasf, const TSpectrumParamP colors, double period, double count, double cycle, const TAffine &aff, double frame, double inner = 0.0, GradientCurveType type = Linear); void multiLinear(const TRasterP &ras, TPointD posTrasf, const TSpectrumParamP colors, double period, double count, double amplitude, double freq, double phase, double cycle, const TAffine &aff, double frame, GradientCurveType type = EaseInOut); #endif
luckymaosh/MicroCommunity
CommonService/src/main/java/com/java110/common/dao/impl/AdvertItemServiceDaoImpl.java
<reponame>luckymaosh/MicroCommunity package com.java110.common.dao.impl; import com.alibaba.fastjson.JSONObject; import com.java110.common.dao.IAdvertItemServiceDao; import com.java110.core.base.dao.BaseServiceDao; import com.java110.utils.constant.ResponseConstant; import com.java110.utils.exception.DAOException; import com.java110.utils.util.DateUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * 广告项信息服务 与数据库交互 * Created by wuxw on 2017/4/5. */ @Service("advertItemServiceDaoImpl") //@Transactional public class AdvertItemServiceDaoImpl extends BaseServiceDao implements IAdvertItemServiceDao { private static Logger logger = LoggerFactory.getLogger(AdvertItemServiceDaoImpl.class); /** * 广告项信息信息封装 * * @param businessAdvertItemInfo 广告项信息信息 封装 * @throws DAOException DAO异常 */ @Override public void saveBusinessAdvertItemInfo(Map businessAdvertItemInfo) throws DAOException { businessAdvertItemInfo.put("month", DateUtil.getCurrentMonth()); // 查询business_user 数据是否已经存在 logger.debug("保存广告项信息信息 入参 businessAdvertItemInfo : {}", businessAdvertItemInfo); int saveFlag = sqlSessionTemplate.insert("advertItemServiceDaoImpl.saveBusinessAdvertItemInfo", businessAdvertItemInfo); if (saveFlag < 1) { throw new DAOException(ResponseConstant.RESULT_PARAM_ERROR, "保存广告项信息数据失败:" + JSONObject.toJSONString(businessAdvertItemInfo)); } } /** * 查询广告项信息信息 * * @param info bId 信息 * @return 广告项信息信息 * @throws DAOException DAO异常 */ @Override public List<Map> getBusinessAdvertItemInfo(Map info) throws DAOException { logger.debug("查询广告项信息信息 入参 info : {}", info); List<Map> businessAdvertItemInfos = sqlSessionTemplate.selectList("advertItemServiceDaoImpl.getBusinessAdvertItemInfo", info); return businessAdvertItemInfos; } /** * 保存广告项信息信息 到 instance * * @param info bId 信息 * @throws DAOException DAO异常 */ @Override public void saveAdvertItemInfoInstance(Map info) throws DAOException { logger.debug("保存广告项信息信息Instance 入参 info : {}", info); int saveFlag = sqlSessionTemplate.insert("advertItemServiceDaoImpl.saveAdvertItemInfoInstance", info); if (saveFlag < 1) { throw new DAOException(ResponseConstant.RESULT_PARAM_ERROR, "保存广告项信息信息Instance数据失败:" + JSONObject.toJSONString(info)); } } /** * 查询广告项信息信息(instance) * * @param info bId 信息 * @return List<Map> * @throws DAOException DAO异常 */ @Override public List<Map> getAdvertItemInfo(Map info) throws DAOException { logger.debug("查询广告项信息信息 入参 info : {}", info); List<Map> businessAdvertItemInfos = sqlSessionTemplate.selectList("advertItemServiceDaoImpl.getAdvertItemInfo", info); return businessAdvertItemInfos; } /** * 修改广告项信息信息 * * @param info 修改信息 * @throws DAOException DAO异常 */ @Override public void updateAdvertItemInfoInstance(Map info) throws DAOException { logger.debug("修改广告项信息信息Instance 入参 info : {}", info); int saveFlag = sqlSessionTemplate.update("advertItemServiceDaoImpl.updateAdvertItemInfoInstance", info); if (saveFlag < 1) { throw new DAOException(ResponseConstant.RESULT_PARAM_ERROR, "修改广告项信息信息Instance数据失败:" + JSONObject.toJSONString(info)); } } /** * 查询广告项信息数量 * * @param info 广告项信息信息 * @return 广告项信息数量 */ @Override public int queryAdvertItemsCount(Map info) { logger.debug("查询广告项信息数据 入参 info : {}", info); List<Map> businessAdvertItemInfos = sqlSessionTemplate.selectList("advertItemServiceDaoImpl.queryAdvertItemsCount", info); if (businessAdvertItemInfos.size() < 1) { return 0; } return Integer.parseInt(businessAdvertItemInfos.get(0).get("count").toString()); } }
josecmarcucci005/licket
licket-module-semanticui/src/main/java/org/licket/semantic/component/loader/SemanticUILoader.java
<reponame>josecmarcucci005/licket<gh_stars>10-100 package org.licket.semantic.component.loader; import org.licket.core.view.LicketStaticLabel; import org.licket.core.view.container.AbstractLicketMonoContainer; import static org.licket.core.model.LicketComponentModel.ofString; import static org.licket.core.view.LicketComponentView.fromComponentClass; /** * @author lukaszgrabski */ public class SemanticUILoader extends AbstractLicketMonoContainer<String> { private static final String DEFAULT_LOADING_TEXT = "Loading ..."; public SemanticUILoader(String id, String label) { super(id, String.class, ofString(label), fromComponentClass(SemanticUILoader.class)); } @Override protected void onInitializeContainer() { add(new LicketStaticLabel("loader-content", ofString(getComponentModel().get().orElse(DEFAULT_LOADING_TEXT)))); } }
three-Vs/hedera-services
hedera-node/src/test/java/com/hedera/services/txns/token/TokenBurnTransitionLogicTest.java
<filename>hedera-node/src/test/java/com/hedera/services/txns/token/TokenBurnTransitionLogicTest.java package com.hedera.services.txns.token; /*- * ‌ * Hedera Services Node * ​ * Copyright (C) 2018 - 2021 <NAME>, LLC * ​ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ‍ */ import com.google.protobuf.ByteString; import com.hedera.services.context.TransactionContext; import com.hedera.services.context.properties.GlobalDynamicProperties; import com.hedera.services.store.models.Account; import com.hedera.services.store.models.Id; import com.hedera.services.txns.validation.OptionValidator; import com.hedera.services.utils.TxnAccessor; import com.hedera.test.utils.IdUtils; import com.hederahashgraph.api.proto.java.TokenBurnTransactionBody; import com.hederahashgraph.api.proto.java.TokenID; import com.hederahashgraph.api.proto.java.TokenMintTransactionBody; import com.hederahashgraph.api.proto.java.TransactionBody; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.time.Instant; import java.util.List; import java.util.stream.Collectors; import java.util.stream.LongStream; import static com.hederahashgraph.api.proto.java.ResponseCodeEnum.*; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) class TokenBurnTransitionLogicTest { private final long amount = 123L; private final TokenID grpcId = IdUtils.asToken("1.2.3"); private final Id id = new Id(1, 2, 3); private final Id treasuryId = new Id(2, 4, 6); private final Account treasury = new Account(treasuryId); @Mock private TransactionContext txnCtx; @Mock private TxnAccessor accessor; @Mock private TransactionBody transactionBody; @Mock private TokenBurnTransactionBody burnTransactionBody; @Mock private OptionValidator validator; @Mock private GlobalDynamicProperties dynamicProperties; @Mock private BurnLogic burnLogic; private TransactionBody tokenBurnTxn; private TokenBurnTransitionLogic subject; @BeforeEach private void setup() { subject = new TokenBurnTransitionLogic(validator, txnCtx, dynamicProperties, burnLogic); } @Test void hasCorrectApplicability() { givenValidTxnCtx(); // expect: assertTrue(subject.applicability().test(tokenBurnTxn)); assertFalse(subject.applicability().test(TransactionBody.getDefaultInstance())); } @Test void acceptsValidTxn() { givenValidTxnCtx(); // expect: assertEquals(OK, subject.semanticCheck().apply(tokenBurnTxn)); } @Test void rejectsUniqueWhenNftsNotEnabled() { givenValidUniqueTxnCtx(); given(dynamicProperties.areNftsEnabled()).willReturn(false); // expect: assertEquals(NOT_SUPPORTED, subject.semanticCheck().apply(tokenBurnTxn)); } @Test void rejectsMissingToken() { givenMissingToken(); // expect: assertEquals(INVALID_TOKEN_ID, subject.semanticCheck().apply(tokenBurnTxn)); } @Test void rejectsInvalidNegativeAmount() { givenInvalidNegativeAmount(); // expect: assertEquals(INVALID_TOKEN_BURN_AMOUNT, subject.semanticCheck().apply(tokenBurnTxn)); } @Test void rejectsInvalidZeroAmount() { givenInvalidZeroAmount(); // expect: assertEquals(INVALID_TOKEN_BURN_AMOUNT, subject.semanticCheck().apply(tokenBurnTxn)); } @Test void rejectsInvalidTxnBodyWithBothProps() { given(dynamicProperties.areNftsEnabled()).willReturn(true); tokenBurnTxn = TransactionBody.newBuilder() .setTokenBurn( TokenBurnTransactionBody.newBuilder() .addAllSerialNumbers(List.of(1L)) .setAmount(1) .setToken(grpcId)) .build(); assertEquals(INVALID_TRANSACTION_BODY, subject.semanticCheck().apply(tokenBurnTxn)); } @Test void rejectsInvalidTxnBodyWithNoProps() { tokenBurnTxn = TransactionBody.newBuilder() .setTokenBurn( TokenBurnTransactionBody.newBuilder() .setToken(grpcId)) .build(); assertEquals(INVALID_TOKEN_BURN_AMOUNT, subject.semanticCheck().apply(tokenBurnTxn)); } @Test void rejectsInvalidTxnBodyWithInvalidBatch() { given(dynamicProperties.areNftsEnabled()).willReturn(true); tokenBurnTxn = TransactionBody.newBuilder() .setTokenBurn( TokenBurnTransactionBody.newBuilder() .addAllSerialNumbers(LongStream.range(-20L, 0L).boxed().collect(Collectors.toList())) .setToken(grpcId)) .build(); given(validator.maxBatchSizeBurnCheck(tokenBurnTxn.getTokenBurn().getSerialNumbersCount())).willReturn(OK); assertEquals(INVALID_NFT_ID, subject.semanticCheck().apply(tokenBurnTxn)); } @Test void propagatesErrorOnBatchSizeExceeded() { given(dynamicProperties.areNftsEnabled()).willReturn(true); tokenBurnTxn = TransactionBody.newBuilder() .setTokenBurn( TokenBurnTransactionBody.newBuilder() .addAllSerialNumbers(LongStream.range(1, 5).boxed().collect(Collectors.toList())) .setToken(grpcId)) .build(); given(validator.maxBatchSizeBurnCheck(tokenBurnTxn.getTokenBurn().getSerialNumbersCount())).willReturn( BATCH_SIZE_LIMIT_EXCEEDED); assertEquals(BATCH_SIZE_LIMIT_EXCEEDED, subject.semanticCheck().apply(tokenBurnTxn)); } @Test void callsBurnLogicWithCorrectParams() { var consensus = Instant.now(); var grpcId = IdUtils.asToken("0.0.1"); var amount = 4321L; List<Long> serialNumbersList = List.of(1L, 2L, 3L); given(txnCtx.accessor()).willReturn(accessor); given(accessor.getTxn()).willReturn(transactionBody); given(transactionBody.getTokenBurn()).willReturn(burnTransactionBody); given(burnTransactionBody.getToken()).willReturn(grpcId); given(burnTransactionBody.getAmount()).willReturn(amount); given(burnTransactionBody.getSerialNumbersList()).willReturn(serialNumbersList); subject.doStateTransition(); verify(burnLogic).burn(Id.fromGrpcToken(grpcId), amount, serialNumbersList); } private void givenValidTxnCtx() { tokenBurnTxn = TransactionBody.newBuilder() .setTokenBurn(TokenBurnTransactionBody.newBuilder() .setToken(grpcId) .setAmount(amount)) .build(); } private void givenValidUniqueTxnCtx() { tokenBurnTxn = TransactionBody.newBuilder() .setTokenBurn(TokenBurnTransactionBody.newBuilder() .setToken(grpcId) .addAllSerialNumbers(List.of(1L))) .build(); } private void givenMissingToken() { tokenBurnTxn = TransactionBody.newBuilder() .setTokenBurn( TokenBurnTransactionBody.newBuilder() .build() ).build(); } private void givenInvalidNegativeAmount() { tokenBurnTxn = TransactionBody.newBuilder() .setTokenBurn( TokenBurnTransactionBody.newBuilder() .setToken(grpcId) .setAmount(-1) .build() ).build(); } private void givenInvalidZeroAmount() { tokenBurnTxn = TransactionBody.newBuilder() .setTokenBurn( TokenBurnTransactionBody.newBuilder() .setToken(grpcId) .setAmount(0) .build() ).build(); } }
dvorka/coaching-notebook
src/com/mindforger/coachingnotebook/server/store/beans/BackupCommentBean.java
package com.mindforger.coachingnotebook.server.store.beans; import java.util.Date; import com.mindforger.coachingnotebook.server.store.BackupBean; public class BackupCommentBean implements BackupBean { private String key; private String authorUserKey; private String questionKey; private Date created; private String comment; private String growKey; public BackupCommentBean( String key, String authorUserKey, String questionKey, String growKey, Date created, String comment) { super(); this.key=key; this.authorUserKey=authorUserKey; this.questionKey=questionKey; this.growKey=growKey; this.created=created; this.comment=comment; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public String getAuthorUserKey() { return authorUserKey; } public void setAuthorUserKey(String authorUserKey) { this.authorUserKey = authorUserKey; } public String getQuestionKey() { return questionKey; } public void setQuestionKey(String questionKey) { this.questionKey = questionKey; } public String getGrowKey() { return growKey; } public void setGrowKey(String growKey) { this.growKey = growKey; } }
utils-common/iceroot
src/main/java/com/icexxx/util/IceDbUtil.java
<reponame>utils-common/iceroot package com.icexxx.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; /** * 数据库操作相关工具类 * @author IceWater * @date 2017-03-03 * @version 1.0 */ public class IceDbUtil { /** * 获取数据库连接 * @param driver 数据库驱动名称 * @param url 数据库url * @param username 用户名 * @param password 密码 * @return */ public static Connection getConnection(String driver, String url, String username, String password) { try { Class.forName(driver); } catch (ClassNotFoundException e) { throw new RuntimeException("数据库驱动jar包无法加载"); } Connection connection = null; try { connection = DriverManager.getConnection(driver, username, password); } catch (SQLException e) { String errorMessage = e.getMessage(); if (errorMessage.indexOf("No suitable driver found for com.mysql.jdbc.Driver") != -1) { if (url.indexOf("?") != -1) { url = url.substring(0, url.indexOf("?")); } url = url + "?user=" + username + "&password=" + password + "&useUnicode=true&characterEncoding=utf-8"; try { connection = DriverManager.getConnection(url); } catch (SQLException e1) { e1.printStackTrace(); } } } return connection; } /** * 执行sql语句 * * @param connection * 数据库连接 * @param sql * 需要执行的sql语句 * @return 成功执行的sql条数 */ public static int exeSql(Connection connection, String sql) { Statement createStatement = null; int executeUpdate = 0; try { sql = sql.replace("&lt;", "<"); sql = sql.replace("&gt;", ">"); sql = sql.replace("&amp;", "&"); sql = sql.replace("&quot;", "\""); sql = sql.replace("&apos;", "'"); createStatement = connection.createStatement(); executeUpdate = createStatement.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } finally { if (createStatement != null) { try { createStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return executeUpdate; } /** * 执行sql语句 * * @param connection * 数据库连接 * @param sql * 需要执行的sql * @param params * sql中的参数 * @return 执行成功的条数 */ public static int exeSql(Connection connection, String sql, Object[] params) { PreparedStatement prepareStatement = null; int executeUpdate = 0; try { sql = sql.replace("&lt;", "<"); sql = sql.replace("&gt;", ">"); sql = sql.replace("&amp;", "&"); sql = sql.replace("&quot;", "\""); sql = sql.replace("&apos;", "'"); prepareStatement = connection.prepareStatement(sql); for (int i = 0; i < params.length; i++) { Object param = params[i]; if (param instanceof String) { prepareStatement.setString(i + 1, (String) param); } else if (param instanceof Integer) { prepareStatement.setInt(i + 1, (Integer) param); } else if (param instanceof Long) { prepareStatement.setLong(i + 1, (Long) param); } else if (param instanceof Boolean) { prepareStatement.setBoolean(i + 1, (Boolean) param); } else if (param instanceof java.sql.Date) { prepareStatement.setDate(i + 1, (java.sql.Date) param); } else if (param instanceof Date) { prepareStatement.setDate(i + 1, new java.sql.Date(((Date) param).getTime())); } else if (param instanceof Double) { prepareStatement.setDouble(i + 1, (Double) param); } else if (param instanceof Byte) { prepareStatement.setByte(i + 1, (Byte) param); } else if (param instanceof Short) { prepareStatement.setShort(i + 1, (Short) param); } } prepareStatement.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { if (prepareStatement != null) { try { prepareStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return executeUpdate; } }
tikken/beget2
src/components/banner/banners_mob.js
<gh_stars>0 import React from 'react'; const BannersMob = () => { return ( <div className="banners"> <div className="banners_wrap"> <div className="banners_wrap-item"> <div className="banners_wrap-item_inner"> <div className="banners_wrap-item_inner_title"> <span>Картридж</span> <span>Т2</span> </div> <div className="banners_wrap-item_inner_img"> <img src={"/unnecessary/product_mob.png"} alt="banner"/> </div> </div> <div className="banners_wrap-item_inner"> <div className="banners_wrap-item_inner_text"> <div className="banners_wrap-item_inner_text-item"></div> <div className="banners_wrap-item_inner_text-btn"> <span>Cмотреть все <br/>картриджи Т2</span> <img src={"/icons/details_btn.svg"} alt="details"/> </div> </div> </div> </div> <div className="banners_wrap-item"> <div className="banners_wrap-item_inner"> <div className="banners_wrap-item_inner_title"> <span>Картридж</span> <span>EASYPRINT</span> </div> <div className="banners_wrap-item_inner_img banners_wrap-item_inner_img2"> <img src={"/unnecessary/product_mob2.png"} alt="banner"/> </div> </div> <div className="banners_wrap-item_inner"> <div className="banners_wrap-item_inner_text"> <div className="banners_wrap-item_inner_text-item"></div> <div className="banners_wrap-item_inner_text-btn"> <span>Cмотреть все <br/>картриджи <span className="banners_wrap-item_inner_text-btn-title">EASYPRINT</span></span> <img src={"/icons/details_btn.svg"} alt="details"/> </div> </div> </div> </div> </div> </div> ); }; export default BannersMob;
Daij-Djan/DDUtils
objC/ddutils-common/model/SKPaymentQueue+TransactionForProduct [ios+osx]/SKPaymentQueue+TransactionForProduct.h
<gh_stars>10-100 // // SKPaymentQueue+successfulTransactionForProduct.h // Project // // Created by <NAME> on 04.11.09. // Copyright 2009 Medicus 42 GmbH. All rights reserved. // #import <StoreKit/StoreKit.h> @interface SKPaymentQueue (TransactionForProduct) - (SKPaymentTransaction *)anyTransactionForProductIdentifier:(NSString *)identifier; - (SKPaymentTransaction *)successfulTransactionForProductIdentifier:(NSString *)identifier; @end
LuizHenriqudesouza419/Exercicios-de-Python3-main
Exercicios-Python/034.py
<gh_stars>1-10 #Aumento salarial salário = float(input('Qual é o seu salario ? ')) if salário <= 1250.00: novo = salário + (salário * 15 / 100) print('Seu novo salário com 15% de aumento ficou {}'.format(novo)) else: novo = salário + (salário * 10 / 100) print('Seu salário com 10% de aumento ficou {}'.format(novo))
aclrys/pg-general-planner
src/main/java/org/prebid/pg/gp/server/breaker/CircuitBreakerSecuredClient.java
<reponame>aclrys/pg-general-planner<gh_stars>1-10 package org.prebid.pg.gp.server.breaker; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * A {@link PlannerCircuitBreaker} with logging support. */ public class CircuitBreakerSecuredClient { private static final Logger logger = LoggerFactory.getLogger(CircuitBreakerSecuredClient.class); protected final PlannerCircuitBreaker plannerCircuitBreaker; public CircuitBreakerSecuredClient(PlannerCircuitBreaker plannerCircuitBreaker) { this.plannerCircuitBreaker = plannerCircuitBreaker; this.plannerCircuitBreaker .openHandler(ignored -> circuitOpened()) .halfOpenHandler(ignored -> circuitHalfOpened()) .closeHandler(ignored -> circuitClosed()); } private void circuitOpened() { logger.warn("Circuit {0} opened", plannerCircuitBreaker.getBreaker().name()); } private void circuitHalfOpened() { logger.warn("Circuit {0} is half-open, ready to try again", plannerCircuitBreaker.getBreaker().name()); } private void circuitClosed() { logger.info("Circuit {0} is closed", plannerCircuitBreaker.getBreaker().name()); } public PlannerCircuitBreaker getPlannerCircuitBreaker() { return plannerCircuitBreaker; } }
DavideCorradiDev/houzi-game-engine
docs/search/classes_3.js
var searchData= [ ['display_5fformat_5fmask',['display_format_mask',['../classhou_1_1display__format__mask.html',1,'hou']]], ['display_5fmode',['display_mode',['../classhou_1_1display__mode.html',1,'hou']]] ];
bhojpur/web
pkg/template/tags_ssi.go
<filename>pkg/template/tags_ssi.go package template // Copyright (c) 2018 Bhojpur Consulting Private Limited, India. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import ( "io/ioutil" ) type tagSSINode struct { filename string content string template *Template } func (node *tagSSINode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error { if node.template != nil { // Execute the template within the current context includeCtx := make(Context) includeCtx.Update(ctx.Public) includeCtx.Update(ctx.Private) err := node.template.execute(includeCtx, writer) if err != nil { return err.(*Error) } } else { // Just print out the content writer.WriteString(node.content) } return nil } func tagSSIParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) { SSINode := &tagSSINode{} if fileToken := arguments.MatchType(TokenString); fileToken != nil { SSINode.filename = fileToken.Val if arguments.Match(TokenIdentifier, "parsed") != nil { // parsed temporaryTpl, err := doc.template.set.FromFile(doc.template.set.resolveFilename(doc.template, fileToken.Val)) if err != nil { return nil, err.(*Error).updateFromTokenIfNeeded(doc.template, fileToken) } SSINode.template = temporaryTpl } else { // plaintext buf, err := ioutil.ReadFile(doc.template.set.resolveFilename(doc.template, fileToken.Val)) if err != nil { return nil, (&Error{ Sender: "tag:ssi", OrigError: err, }).updateFromTokenIfNeeded(doc.template, fileToken) } SSINode.content = string(buf) } } else { return nil, arguments.Error("First argument must be a string.", nil) } if arguments.Remaining() > 0 { return nil, arguments.Error("Malformed SSI-tag argument.", nil) } return SSINode, nil } func init() { RegisterTag("ssi", tagSSIParser) }
georghinkel/ttc2017smartGrids
solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/Informative/Reservation/TransmissionService.java
<reponame>georghinkel/ttc2017smartGrids /** */ package gluemodel.CIM.IEC61970.Informative.Reservation; import gluemodel.CIM.IEC61970.Core.IdentifiedObject; import gluemodel.CIM.IEC61970.Informative.EnergyScheduling.AvailableTransmissionCapacity; import gluemodel.CIM.IEC61970.Informative.Financial.OpenAccessProduct; import gluemodel.CIM.IEC61970.Informative.Financial.TransmissionProduct; import gluemodel.CIM.IEC61970.Informative.Financial.TransmissionProvider; import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Transmission Service</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionService#getOffering <em>Offering</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionService#getOfferedAs <em>Offered As</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionService#getScheduledBy <em>Scheduled By</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionService#getReservedBy_ServiceReservation <em>Reserved By Service Reservation</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionService#getTransContractFor <em>Trans Contract For</em>}</li> * <li>{@link gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionService#getOffers <em>Offers</em>}</li> * </ul> * * @see gluemodel.CIM.IEC61970.Informative.Reservation.ReservationPackage#getTransmissionService() * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Transmission products along posted transmission path.'" * annotation="http://langdale.com.au/2005/UML Profile\040documentation='Transmission products along posted transmission path.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Transmission products along posted transmission path.' Profile\040documentation='Transmission products along posted transmission path.'" * @generated */ public interface TransmissionService extends IdentifiedObject { /** * Returns the value of the '<em><b>Offering</b></em>' reference list. * The list contents are of type {@link gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionPath}. * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionPath#getOfferedOn <em>Offered On</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Offering</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Offering</em>' reference list. * @see gluemodel.CIM.IEC61970.Informative.Reservation.ReservationPackage#getTransmissionService_Offering() * @see gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionPath#getOfferedOn * @model opposite="OfferedOn" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A transmission service is offered on a transmission path.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A transmission service is offered on a transmission path.'" * @generated */ EList<TransmissionPath> getOffering(); /** * Returns the value of the '<em><b>Offered As</b></em>' reference list. * The list contents are of type {@link gluemodel.CIM.IEC61970.Informative.Financial.TransmissionProduct}. * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Informative.Financial.TransmissionProduct#getOffers <em>Offers</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Offered As</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Offered As</em>' reference list. * @see gluemodel.CIM.IEC61970.Informative.Reservation.ReservationPackage#getTransmissionService_OfferedAs() * @see gluemodel.CIM.IEC61970.Informative.Financial.TransmissionProduct#getOffers * @model opposite="Offers" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A transmission product is offered as a transmission service along a transmission path.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A transmission product is offered as a transmission service along a transmission path.'" * @generated */ EList<TransmissionProduct> getOfferedAs(); /** * Returns the value of the '<em><b>Scheduled By</b></em>' reference list. * The list contents are of type {@link gluemodel.CIM.IEC61970.Informative.EnergyScheduling.AvailableTransmissionCapacity}. * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Informative.EnergyScheduling.AvailableTransmissionCapacity#getScheduleFor <em>Schedule For</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Scheduled By</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Scheduled By</em>' reference list. * @see gluemodel.CIM.IEC61970.Informative.Reservation.ReservationPackage#getTransmissionService_ScheduledBy() * @see gluemodel.CIM.IEC61970.Informative.EnergyScheduling.AvailableTransmissionCapacity#getScheduleFor * @model opposite="ScheduleFor" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A transmission schedule posts the available transmission capacity for a transmission line.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A transmission schedule posts the available transmission capacity for a transmission line.'" * @generated */ EList<AvailableTransmissionCapacity> getScheduledBy(); /** * Returns the value of the '<em><b>Reserved By Service Reservation</b></em>' reference list. * The list contents are of type {@link gluemodel.CIM.IEC61970.Informative.Reservation.ServiceReservation}. * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Informative.Reservation.ServiceReservation#getReserves_TransmissionService <em>Reserves Transmission Service</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Reserved By Service Reservation</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Reserved By Service Reservation</em>' reference list. * @see gluemodel.CIM.IEC61970.Informative.Reservation.ReservationPackage#getTransmissionService_ReservedBy_ServiceReservation() * @see gluemodel.CIM.IEC61970.Informative.Reservation.ServiceReservation#getReserves_TransmissionService * @model opposite="Reserves_TransmissionService" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A service reservation reserves a particular transmission service.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A service reservation reserves a particular transmission service.'" * @generated */ EList<ServiceReservation> getReservedBy_ServiceReservation(); /** * Returns the value of the '<em><b>Trans Contract For</b></em>' reference. * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Informative.Financial.OpenAccessProduct#getProvidedBy_TransmissionService <em>Provided By Transmission Service</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Trans Contract For</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Trans Contract For</em>' reference. * @see #setTransContractFor(OpenAccessProduct) * @see gluemodel.CIM.IEC61970.Informative.Reservation.ReservationPackage#getTransmissionService_TransContractFor() * @see gluemodel.CIM.IEC61970.Informative.Financial.OpenAccessProduct#getProvidedBy_TransmissionService * @model opposite="ProvidedBy_TransmissionService" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='A TransmissionService is sold according to the terms of a particular OpenAccessProduct agreement.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='A TransmissionService is sold according to the terms of a particular OpenAccessProduct agreement.'" * @generated */ OpenAccessProduct getTransContractFor(); /** * Sets the value of the '{@link gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionService#getTransContractFor <em>Trans Contract For</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Trans Contract For</em>' reference. * @see #getTransContractFor() * @generated */ void setTransContractFor(OpenAccessProduct value); /** * Returns the value of the '<em><b>Offers</b></em>' reference. * It is bidirectional and its opposite is '{@link gluemodel.CIM.IEC61970.Informative.Financial.TransmissionProvider#getOfferedBy <em>Offered By</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Offers</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Offers</em>' reference. * @see #setOffers(TransmissionProvider) * @see gluemodel.CIM.IEC61970.Informative.Reservation.ReservationPackage#getTransmissionService_Offers() * @see gluemodel.CIM.IEC61970.Informative.Financial.TransmissionProvider#getOfferedBy * @model opposite="OfferedBy" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='The combination of a TransmissionProduct on a TransmissionPath is a TransmissionService, for which the TransmissionProvider must post one or two ATC\'s (AvailableTransmissionCapacity - Amount of possible flow by \ndirection).'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='The combination of a TransmissionProduct on a TransmissionPath is a TransmissionService, for which the TransmissionProvider must post one or two ATC\'s (AvailableTransmissionCapacity - Amount of possible flow by \ndirection).'" * @generated */ TransmissionProvider getOffers(); /** * Sets the value of the '{@link gluemodel.CIM.IEC61970.Informative.Reservation.TransmissionService#getOffers <em>Offers</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Offers</em>' reference. * @see #getOffers() * @generated */ void setOffers(TransmissionProvider value); } // TransmissionService
shaozj/silk
scripts/download-spa-template.js
<reponame>shaozj/silk const download = require('./download'); const program = require('commander'); const colors = require('colors'); const inquirer = require('inquirer'); program .version('0.0.1') .option('get', '获取模板') .command('get [pageName]', '请输入新建页面名称') .parse(process.argv); if (program.get) { console.log(process.argv.slice(3)) download(process.argv); }
dllen/WeChatMina
wechat-engine/src/main/java/edu/buaa/scse/niu/wechat/engine/entity/Account.java
package edu.buaa.scse.niu.wechat.engine.entity; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.annotations.GenericGenerator; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.format.annotation.DateTimeFormat.ISO; /** * 用户帐户实体类 其中profile储存用户信息 * * @author Niu * */ @Entity @Table(name = Account.TABLE_NAME) public class Account extends BaseEntity implements Serializable { /** * */ private static final long serialVersionUID = 1L; public static final String TABLE_NAME = "USER_ACCOUNT"; public static final String ID = "ID"; public static final String NAME = "NAME"; public static final String SALT = "SALT"; public static final String PASSWORD = "PASSWORD"; public static final String PROFILE_ID = "PROFILE_ID"; public static final String LOGIN_TIME = "LOGIN_TIME"; public static final String CHAT_GROUPS = "CHAT_GROUPS"; public static final int INVALID_ID = -1; /** * 用户Id */ @Id @GenericGenerator(name = "idGenerator", strategy = "identity") @GeneratedValue(generator = "idGenerator") @Column(name = ID, updatable = false) private int id; /** * 加密盐 */ @Column(name = SALT, length = 32, updatable = false) private String salt; /** * 加密后的密码 */ @NotNull @Column(name = PASSWORD, length = 40, nullable = false) private String password; /** * 登录用的用户名 */ @NotNull @Size(min = 3, max = 40) @Column(name = NAME, length = 40, nullable = false) private String name; /** * 用户基本信息 */ @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, optional = false) @JoinColumn(name = PROFILE_ID, unique = true, nullable = false) private Profile profile; /** * 上次登录时间 */ @DateTimeFormat(iso = ISO.DATE_TIME) @Column(name = LOGIN_TIME) private Date loginTime; /** * 属于该用户的聊天组集合 */ @OneToMany(mappedBy = "account", fetch = FetchType.LAZY, orphanRemoval = true) private List<ChatGroupAccount> chatGroupAccounts; public Account() { createTime = new Date(); status = DataStatus.INACTIVE; chatGroupAccounts = new ArrayList<ChatGroupAccount>(); } /** * * @param salt * @param password * @param name */ public Account(String name, String password, String salt) { this(); this.name = name; this.password = password; this.salt = salt; } /** * 客户端接收到服务端发来的其它用户的信息 不包括密码、加密盐、登录时间、注册时间等 * @param id * @param name * @param profile */ public Account(int id, String name, Profile profile) { this.id = id; this.name = name; this.profile = profile; status=DataStatus.ACTIVE; } @Override public String toString() { return "Account [id=" + id + ", salt=" + salt + ", password=" + password + ", name=" + name + ", status=" + status + ", createTime=" + createTime + ", loginTime=" + loginTime + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getLoginTime() { return loginTime; } public void setLoginTime(Date loginTime) { this.loginTime = loginTime; } public List<ChatGroupAccount> getChatGroupAccounts() { return chatGroupAccounts; } public void setChatGroupAccounts(List<ChatGroupAccount> chatGroupAccounts) { this.chatGroupAccounts = chatGroupAccounts; } public Profile getProfile() { return profile; } public void setProfile(Profile profile) { this.profile = profile; } }
Gueust/DTA-PC
src/jUnit/JUnitState.java
package jUnit; import dta_solver.adjointMethod.JavaSystemState; public class JUnitState implements JavaSystemState { public double[] state; }
weixiang0815/javapractice
self practice/Ex20210118/src/ntu/genedu/java/studentdatabase/Student.java
package ntu.genedu.java.studentdatabase; import java.io.FileWriter; import java.io.IOException; import ntu.genedu.java.studentdatabase.exception.IllegalChineseScoreException; import ntu.genedu.java.studentdatabase.exception.IllegalEnglishScoreException; import ntu.genedu.java.studentdatabase.exception.IllegalMathScoreException; public class Student implements FileInterface { // Field 欄位 /** * 學生姓名 */ private String name; /** * 國文成績 */ private int chinese; /** * 英文成績 */ private int english; /** * 數學成績 */ private int math; // 將資料實體化 /** * 分別輸入學生姓名、國文、英文及數學成績的建構子 * * @param name 學生姓名 * @param chinese 國文成績 * @param english 英文成績 * @param math 數學成績 * @throws IllegalChineseScoreException 當國文成績非 0 到 100 時所產生的例外 * @throws IllegalEnglishScoreException 當英文成績非 0 到 100 時所產生的例外 * @throws IllegalMathScoreException 當數學成績非 0 到 100 時所產生的例外 */ Student(String name, int chinese, int english, int math) throws IllegalChineseScoreException, IllegalEnglishScoreException, IllegalMathScoreException { boolean isChineseError = chinese < 0 || chinese > 100; boolean isEnglishError = english < 0 || english > 100; boolean isMathError = math < 0 || math > 100; if (isChineseError || isEnglishError || isMathError) { if (isChineseError) throw new IllegalChineseScoreException(); if (isEnglishError) throw new IllegalEnglishScoreException(); if (isMathError) throw new IllegalMathScoreException(); } this.name = name; this.chinese = chinese; this.english = english; this.math = math; } /** * 輸入CSV格式的學生資料 * @param strCSV 一個格式為「姓名,國文,英文,數學」的字串 */ Student(String strCSV) throws java.lang.IllegalArgumentException { String[] strField = strCSV.split(","); if (strField.length < 4) throw new java.lang.IllegalArgumentException("CSV格式錯誤,資料個數少於4個"); this.name = strField[0]; try { this.chinese = Integer.parseInt(strField[1]); } catch (NumberFormatException e) { throw new NumberFormatException("國文成績錯誤:"+e.getMessage()); } try { this.english = Integer.parseInt(strField[2]); } catch (NumberFormatException e) { throw new NumberFormatException("英文成績錯誤:"+e.getMessage()); } try { this.math = Integer.parseInt(strField[3]); } catch (NumberFormatException e) { throw new NumberFormatException("數學成績錯誤:"+e.getMessage()); } } /** * 取得學生姓名 * * @return 學生姓名 */ public String getName() { return this.name; } /** * 取得國文成績 * * @return 國文成績 */ public int getChinese() { return this.chinese; } /** * 取得英文成績 * * @return 英文成績 */ public int getEnglish() { return this.english; } /** * 取得數學成績 * * @return 數學成績 */ public int getMath() { return this.math; } /** * 取得國英文的總分 * * @return 國英文的總分 */ public int getSum() { return this.chinese + this.english + this.math; } /** * 取得國英文的平均值 * * @return 國英文的平均值 */ public double getAverage() { return this.getSum() / 3.0; } /** * 取得學生資料的CSV格式 * @return 學生資料的CSV格式 */ public String getCSV() { return this.getJoinString(","); } public String getJoinString(String sp) { StringBuilder str = new StringBuilder(128); str.append(this.name); str.append(sp); str.append(this.chinese); str.append(sp); str.append(this.english); str.append(sp); str.append(this.math); str.append(sp); str.append(this.getSum()); str.append(sp); str.append(getAverage()); return str.toString(); } /** * 改寫 toString() */ @Override public String toString() { return this.getJoinString("\t"); } @Override public void saveFile(String fileName) throws IOException { FileWriter fw = new FileWriter(fileName); String sp = "\t"; fw.write(this.name); fw.write(sp); fw.write(Integer.toString(this.chinese)); fw.write(sp); fw.write(Integer.toString(this.english)); fw.write(sp); fw.write(Integer.toString(this.math)); fw.write(sp); fw.write(Integer.toString(this.getSum())); fw.write(sp); fw.write(Double.toString(this.getAverage())); fw.close(); } @Override public void readFile(String fileName) throws IOException{ // TODO Auto-generated method stub } }
nistefan/cmssw
CondTools/RunInfo/interface/RunInfoRead.h
#ifndef CondTools_RunInfo_RunInfoRead_h #define CondTools_RunInfo_RunInfoRead_h #include "CondFormats/RunInfo/interface/RunInfo.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include <string> class RunInfoRead { public: RunInfoRead(const std::string& connectionString, const edm::ParameterSet& connectionPset); ~RunInfoRead(); RunInfo readData(const std::string& runinfo_schema, const std::string& dcsenv_schema, const int r_number); private: std::string m_connectionString; edm::ParameterSet m_connectionPset; }; #endif
pickthreeusername/easy-shop
ssm-easy-shop/easy-shop-web-admin/src/main/java/com/cyc/easy/shop/web/admin/dao/TbUserDao.java
<gh_stars>0 package com.cyc.easy.shop.web.admin.dao; import com.cyc.easy.shop.commons.persistence.BaseDao; import com.cyc.easy.shop.domain.TbUser; import org.springframework.stereotype.Repository; @Repository public interface TbUserDao extends BaseDao<TbUser> { /** * 根据email查询用户信息 * @param email * @return */ public TbUser getUserByEmail(String email); }
oliviercailloux/JARiS
src/test/java/io/github/oliviercailloux/jaris/xml/XmlUtilsTests.java
package io.github.oliviercailloux.jaris.xml; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.collect.ImmutableList; import io.github.oliviercailloux.jaris.xml.XmlUtils.DomHelper; import io.github.oliviercailloux.jaris.xml.XmlUtils.XmlException; import java.nio.file.Files; import java.nio.file.Path; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.stream.StreamSource; import net.sf.saxon.TransformerFactoryImpl; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; class XmlUtilsTests { @SuppressWarnings("unused") private static final Logger LOGGER = LoggerFactory.getLogger(XmlUtilsTests.class); private Document document; private Element html; private Element head; private void initDoc() throws ParserConfigurationException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); document = builder.newDocument(); html = document.createElementNS(XmlUtils.XHTML_NS_URI.toString(), "html"); html.setAttribute("lang", "en"); document.appendChild(html); head = document.createElementNS(XmlUtils.XHTML_NS_URI.toString(), "head"); html.appendChild(head); final Element meta = document.createElementNS(XmlUtils.XHTML_NS_URI.toString(), "meta"); meta.setAttribute("http-equiv", "Content-type"); meta.setAttribute("content", "text/html; charset=utf-8"); head.appendChild(meta); final Element body = document.createElementNS(XmlUtils.XHTML_NS_URI.toString(), "body"); html.appendChild(body); } @Test void testToStringDoc() throws Exception { initDoc(); final String expected = Files.readString(Path.of(getClass().getResource("simple.html").toURI())); assertEquals(expected, XmlUtils.loadAndSave().toString(document)); } @Test void testToStringNode() throws Exception { initDoc(); final String expected = Files.readString(Path.of(getClass().getResource("partial.xml").toURI())); assertEquals(expected, XmlUtils.loadAndSave().toString(head)); } @Test void testToElements() throws Exception { initDoc(); assertEquals(ImmutableList.of(html), DomHelper.toElements(document.getChildNodes())); } @Test void testTransformSimple() throws Exception { final StreamSource style = new StreamSource(XmlUtilsTests.class.getResource("short.xsl").toString()); final StreamSource input = new StreamSource(XmlUtilsTests.class.getResource("short.xml").toString()); final String expected = Files.readString(Path.of(XmlUtilsTests.class.getResource("transformed.txt").toURI())); assertEquals(expected, XmlUtils.transformer().transform(input, style)); } @Test void testTransformComplex() throws Exception { final StreamSource docBook = new StreamSource(XmlUtilsTests.class.getResource("docbook howto.xml").toString()); final StreamSource myStyle = new StreamSource(XmlUtilsTests.class.getResource("mystyle.xsl").toString()); /* This is too complex for JDK embedded transformer (Apache Xalan). */ // XmlUtils.transformer().transform(docBook, myStyle); final String transformed = XmlUtils.transformer(new TransformerFactoryImpl()).transform(docBook, myStyle); LOGGER.debug("Transformed docbook howto: {}.", transformed); assertTrue(transformed .contains("<fo:root xmlns:fo=\"http://www.w3.org/1999/XSL/Format\" font-family=")); } @Test void testTransformInvalidXsl() throws Exception { final StreamSource style = new StreamSource(XmlUtilsTests.class.getResource("short invalid.xsl").toString()); final StreamSource input = new StreamSource(XmlUtilsTests.class.getResource("short.xml").toString()); assertThrows(XmlException.class, () -> XmlUtils.transformer().transform(input, style)); } @Test void testTransformInvalidXml() throws Exception { final StreamSource style = new StreamSource(XmlUtilsTests.class.getResource("short.xsl").toString()); final StreamSource input = new StreamSource(XmlUtilsTests.class.getResource("short invalid.xml").toString()); assertThrows(XmlException.class, () -> XmlUtils.transformer().transform(input, style)); } @Test void testTransformMessaging() throws Exception { final StreamSource style = new StreamSource(XmlUtilsTests.class.getResource("short messaging.xsl").toString()); final StreamSource input = new StreamSource(XmlUtilsTests.class.getResource("short.xml").toString()); assertThrows(XmlException.class, () -> XmlUtils.transformer().transform(input, style)); } }
AsahiOS/gate
usr/src/cmd/cmd-inet/lib/nwamd/known_wlans.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. */ #include <ctype.h> #include <errno.h> #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <libdladm.h> #include <libdllink.h> #include <libdlwlan.h> #include <libgen.h> #include <libnwam.h> #include "events.h" #include "known_wlans.h" #include "ncu.h" #include "objects.h" #include "util.h" /* * known_wlans.c - contains routines which handle the known WLAN abstraction. */ #define KNOWN_WIFI_NETS_FILE "/etc/nwam/known_wifi_nets" /* enum for parsing each line of /etc/nwam/known_wifi_nets */ typedef enum { ESSID = 0, BSSID, MAX_FIELDS } known_wifi_nets_fields_t; /* Structure for one BSSID */ typedef struct bssid { struct qelem bssid_links; char *bssid; } bssid_t; /* Structure for an ESSID and its BSSIDs */ typedef struct kw { struct qelem kw_links; char kw_essid[NWAM_MAX_NAME_LEN]; uint32_t kw_num_bssids; struct qelem kw_bssids; } kw_t; /* Holds the linked-list of ESSIDs to make Known WLANs out of */ static struct qelem kw_list; /* Used in walking secobjs looking for an ESSID prefix match. */ struct nwamd_secobj_arg { char nsa_essid_prefix[DLADM_WLAN_MAX_KEYNAME_LEN]; char nsa_keyname[DLADM_WLAN_MAX_KEYNAME_LEN]; dladm_wlan_key_t *nsa_key; uint64_t nsa_secmode; }; static void kw_list_init(void) { kw_list.q_forw = kw_list.q_back = &kw_list; } static void kw_list_free(void) { kw_t *kw; bssid_t *b; while (kw_list.q_forw != &kw_list) { kw = (kw_t *)kw_list.q_forw; /* free kw_bssids */ while (kw->kw_bssids.q_forw != &kw->kw_bssids) { b = (bssid_t *)kw->kw_bssids.q_forw; remque(&b->bssid_links); free(b->bssid); free(b); } remque(&kw->kw_links); free(kw); } } /* Returns the entry in kw_list for the given ESSID. NULL if non-existent */ static kw_t * kw_lookup(const char *essid) { kw_t *kw; if (essid == NULL) return (NULL); for (kw = (kw_t *)kw_list.q_forw; kw != (kw_t *)&kw_list; kw = (kw_t *)kw->kw_links.q_forw) { if (strcmp(essid, kw->kw_essid) == 0) return (kw); } return (NULL); } /* Adds an ESSID/BSSID combination to kw_list. Returns B_TRUE on success. */ static boolean_t kw_add(const char *essid, const char *bssid) { kw_t *kw; bssid_t *b; if ((b = calloc(1, sizeof (bssid_t))) == NULL) { nlog(LOG_ERR, "kw_add: cannot allocate for bssid_t: %m"); return (B_FALSE); } if ((kw = calloc(1, sizeof (kw_t))) == NULL) { nlog(LOG_ERR, "kw_add: cannot allocate for kw_t: %m"); free(b); return (B_FALSE); } kw->kw_bssids.q_forw = kw->kw_bssids.q_back = &kw->kw_bssids; b->bssid = strdup(bssid); (void) strlcpy(kw->kw_essid, essid, sizeof (kw->kw_essid)); kw->kw_num_bssids = 1; insque(&b->bssid_links, kw->kw_bssids.q_back); insque(&kw->kw_links, kw_list.q_back); nlog(LOG_DEBUG, "kw_add: added Known WLAN %s, BSSID %s", essid, bssid); return (B_TRUE); } /* * Add the BSSID to the given kw. Since /etc/nwam/known_wifi_nets is * populated such that the wifi networks visited later are towards the end * of the file, remove the give kw from its current position and append it * to the end of kw_list. This ensures that kw_list is in the reverse * order of visited wifi networks. Returns B_TRUE on success. */ static boolean_t kw_update(kw_t *kw, const char *bssid) { bssid_t *b; if ((b = calloc(1, sizeof (bssid_t))) == NULL) { nlog(LOG_ERR, "kw_update: cannot allocate for bssid_t: %m"); return (B_FALSE); } b->bssid = strdup(bssid); insque(&b->bssid_links, kw->kw_bssids.q_back); kw->kw_num_bssids++; /* remove kw from current position */ remque(&kw->kw_links); /* and insert at end */ insque(&kw->kw_links, kw_list.q_back); nlog(LOG_DEBUG, "kw_update: appended BSSID %s to Known WLAN %s", bssid, kw->kw_essid); return (B_TRUE); } /* * Parses /etc/nwam/known_wifi_nets and populates kw_list, with the oldest * wifi networks first in the list. Returns the number of unique entries * in kw_list (to use for priority values). */ static int parse_known_wifi_nets(void) { FILE *fp; char line[LINE_MAX]; char *cp, *tok[MAX_FIELDS]; int lnum, num_kw = 0; kw_t *kw; kw_list_init(); /* * The file format is: * essid\tbssid (essid followed by tab followed by bssid) */ fp = fopen(KNOWN_WIFI_NETS_FILE, "r"); if (fp == NULL) return (0); for (lnum = 1; fgets(line, sizeof (line), fp) != NULL; lnum++) { cp = line; while (isspace(*cp)) cp++; if (*cp == '#' || *cp == '\0') continue; if (bufsplit(cp, MAX_FIELDS, tok) != MAX_FIELDS) { syslog(LOG_ERR, "%s:%d: wrong number of tokens; " "ignoring entry", KNOWN_WIFI_NETS_FILE, lnum); continue; } if ((kw = kw_lookup(tok[ESSID])) == NULL) { if (!kw_add(tok[ESSID], tok[BSSID])) { nlog(LOG_ERR, "%s:%d: cannot add entry (%s,%s) to list", KNOWN_WIFI_NETS_FILE, lnum, tok[ESSID], tok[BSSID]); } else { num_kw++; } } else { if (!kw_update(kw, tok[BSSID])) { nlog(LOG_ERR, "%s:%d:cannot update entry (%s,%s) to list", KNOWN_WIFI_NETS_FILE, lnum, tok[ESSID], tok[BSSID]); } } /* next line ... */ } (void) fclose(fp); return (num_kw); } /* * Walk security objects looking for one that matches the essid prefix. * Store the key and keyname if a match is found - we use the last match * as the key for the known WLAN, since it is the most recently updated. */ /* ARGSUSED0 */ static boolean_t find_secobj_matching_prefix(dladm_handle_t dh, void *arg, const char *secobjname) { struct nwamd_secobj_arg *nsa = arg; if (strncmp(nsa->nsa_essid_prefix, secobjname, strlen(nsa->nsa_essid_prefix)) == 0) { nlog(LOG_DEBUG, "find_secobj_matching_prefix: " "found secobj with prefix %s : %s\n", nsa->nsa_essid_prefix, secobjname); /* Free last key found (if any) */ if (nsa->nsa_key != NULL) free(nsa->nsa_key); /* Retrive key so we can get security mode */ nsa->nsa_key = nwamd_wlan_get_key_named(secobjname, 0); (void) strlcpy(nsa->nsa_keyname, secobjname, sizeof (nsa->nsa_keyname)); switch (nsa->nsa_key->wk_class) { case DLADM_SECOBJ_CLASS_WEP: nsa->nsa_secmode = DLADM_WLAN_SECMODE_WEP; nlog(LOG_DEBUG, "find_secobj_matching_prefix: " "got WEP key %s", nsa->nsa_keyname); break; case DLADM_SECOBJ_CLASS_WPA: nsa->nsa_secmode = DLADM_WLAN_SECMODE_WPA; nlog(LOG_DEBUG, "find_secobj_matching_prefix: " "got WPA key %s", nsa->nsa_keyname); break; default: /* shouldn't happen */ nsa->nsa_secmode = DLADM_WLAN_SECMODE_NONE; nlog(LOG_ERR, "find_secobj_matching_prefix: " "key class for key %s was invalid", nsa->nsa_keyname); break; } } return (B_TRUE); } /* Upgrade /etc/nwam/known_wifi_nets file to new libnwam-based config model */ void upgrade_known_wifi_nets_config(void) { kw_t *kw; bssid_t *b; nwam_known_wlan_handle_t kwh; char **bssids; nwam_error_t err; uint64_t priority; int i, num_kw; struct nwamd_secobj_arg nsa; nlog(LOG_INFO, "Upgrading %s to Known WLANs", KNOWN_WIFI_NETS_FILE); /* Parse /etc/nwam/known_wifi_nets */ num_kw = parse_known_wifi_nets(); /* Create Known WLANs for each unique ESSID */ for (kw = (kw_t *)kw_list.q_forw, priority = num_kw-1; kw != (kw_t *)&kw_list; kw = (kw_t *)kw->kw_links.q_forw, priority--) { nwam_value_t priorityval = NULL; nwam_value_t bssidsval = NULL; nwam_value_t secmodeval = NULL; nwam_value_t keynameval = NULL; nlog(LOG_DEBUG, "Creating Known WLAN %s", kw->kw_essid); if ((err = nwam_known_wlan_create(kw->kw_essid, &kwh)) != NWAM_SUCCESS) { nlog(LOG_ERR, "upgrade wlan %s: " "could not create known wlan: %s", kw->kw_essid, nwam_strerror(err)); continue; } /* priority of this ESSID */ if ((err = nwam_value_create_uint64(priority, &priorityval)) != NWAM_SUCCESS) { nlog(LOG_ERR, "upgrade wlan %s: " "could not create priority value: %s", kw->kw_essid, nwam_strerror(err)); nwam_known_wlan_free(kwh); continue; } err = nwam_known_wlan_set_prop_value(kwh, NWAM_KNOWN_WLAN_PROP_PRIORITY, priorityval); nwam_value_free(priorityval); if (err != NWAM_SUCCESS) { nlog(LOG_ERR, "upgrade wlan %s: " "could not set priority value: %s", kw->kw_essid, nwam_strerror(err)); nwam_known_wlan_free(kwh); continue; } /* loop through kw->kw_bssids and create an array of bssids */ bssids = calloc(kw->kw_num_bssids, sizeof (char *)); if (bssids == NULL) { nwam_known_wlan_free(kwh); nlog(LOG_ERR, "upgrade wlan %s: " "could not calloc for bssids: %m", kw->kw_essid); continue; } for (b = (bssid_t *)kw->kw_bssids.q_forw, i = 0; b != (bssid_t *)&kw->kw_bssids; b = (bssid_t *)b->bssid_links.q_forw, i++) { bssids[i] = strdup(b->bssid); } /* BSSIDs for this ESSID */ if ((err = nwam_value_create_string_array(bssids, kw->kw_num_bssids, &bssidsval)) != NWAM_SUCCESS) { nlog(LOG_ERR, "upgrade wlan %s: " "could not create bssids value: %s", kw->kw_essid, nwam_strerror(err)); for (i = 0; i < kw->kw_num_bssids; i++) free(bssids[i]); free(bssids); nwam_known_wlan_free(kwh); continue; } err = nwam_known_wlan_set_prop_value(kwh, NWAM_KNOWN_WLAN_PROP_BSSIDS, bssidsval); nwam_value_free(bssidsval); for (i = 0; i < kw->kw_num_bssids; i++) free(bssids[i]); free(bssids); if (err != NWAM_SUCCESS) { nlog(LOG_ERR, "upgrade wlan %s: " "could not set bssids: %s", kw->kw_essid, nwam_strerror(err)); nwam_known_wlan_free(kwh); continue; } /* * Retrieve last key matching ESSID prefix if any, and set * the retrieved key name and security mode. */ nwamd_set_key_name(kw->kw_essid, NULL, nsa.nsa_essid_prefix, sizeof (nsa.nsa_essid_prefix)); nsa.nsa_key = NULL; nsa.nsa_secmode = DLADM_WLAN_SECMODE_NONE; (void) dladm_walk_secobj(dld_handle, &nsa, find_secobj_matching_prefix, DLADM_OPT_PERSIST); if (nsa.nsa_key != NULL) { if ((err = nwam_value_create_string(nsa.nsa_keyname, &keynameval)) == NWAM_SUCCESS) { (void) nwam_known_wlan_set_prop_value(kwh, NWAM_KNOWN_WLAN_PROP_KEYNAME, keynameval); } free(nsa.nsa_key); nwam_value_free(keynameval); } if ((err = nwam_value_create_uint64(nsa.nsa_secmode, &secmodeval)) != NWAM_SUCCESS || (err = nwam_known_wlan_set_prop_value(kwh, NWAM_KNOWN_WLAN_PROP_SECURITY_MODE, secmodeval)) != NWAM_SUCCESS) { nlog(LOG_ERR, "upgrade wlan %s: " "could not set security mode: %s", kw->kw_essid, nwam_strerror(err)); nwam_value_free(secmodeval); nwam_known_wlan_free(kwh); continue; } /* commit, no collision checking by libnwam */ err = nwam_known_wlan_commit(kwh, NWAM_FLAG_KNOWN_WLAN_NO_COLLISION_CHECK); nwam_known_wlan_free(kwh); if (err != NWAM_SUCCESS) { nlog(LOG_ERR, "upgrade wlan %s: " "could not commit wlan: %s", kw->kw_essid, nwam_strerror(err)); } /* next ... */ } kw_list_free(); } nwam_error_t known_wlan_get_keyname(const char *essid, char *name) { nwam_known_wlan_handle_t kwh = NULL; nwam_value_t keynameval = NULL; char *keyname; nwam_error_t err; if ((err = nwam_known_wlan_read(essid, 0, &kwh)) != NWAM_SUCCESS) return (err); if ((err = nwam_known_wlan_get_prop_value(kwh, NWAM_KNOWN_WLAN_PROP_KEYNAME, &keynameval)) == NWAM_SUCCESS && (err = nwam_value_get_string(keynameval, &keyname)) == NWAM_SUCCESS) { (void) strlcpy(name, keyname, NWAM_MAX_VALUE_LEN); } if (keynameval != NULL) nwam_value_free(keynameval); if (kwh != NULL) nwam_known_wlan_free(kwh); return (err); } /* Performs a scan on a wifi link NCU */ /* ARGSUSED */ static int nwamd_ncu_known_wlan_committed(nwamd_object_t object, void *data) { nwamd_ncu_t *ncu_data = object->nwamd_object_data; if (ncu_data->ncu_type != NWAM_NCU_TYPE_LINK) return (0); /* network selection will be done only if possible */ if (ncu_data->ncu_link.nwamd_link_media == DL_WIFI) (void) nwamd_wlan_scan(ncu_data->ncu_name); return (0); } /* Handle known WLAN initialization/refresh event */ /* ARGSUSED */ void nwamd_known_wlan_handle_init_event(nwamd_event_t known_wlan_event) { /* * Since the Known WLAN list has changed, do a rescan so that the * best network is selected. */ (void) nwamd_walk_objects(NWAM_OBJECT_TYPE_NCU, nwamd_ncu_known_wlan_committed, NULL); } void nwamd_known_wlan_handle_action_event(nwamd_event_t known_wlan_event) { switch (known_wlan_event->event_msg->nwe_data.nwe_object_action. nwe_action) { case NWAM_ACTION_ADD: case NWAM_ACTION_REFRESH: nwamd_known_wlan_handle_init_event(known_wlan_event); break; case NWAM_ACTION_DESTROY: /* Nothing needs to be done for destroy */ break; /* all other events are invalid for known WLANs */ case NWAM_ACTION_ENABLE: case NWAM_ACTION_DISABLE: default: nlog(LOG_INFO, "nwam_known_wlan_handle_action_event: " "unexpected action"); break; } } int nwamd_known_wlan_action(const char *known_wlan, nwam_action_t action) { nwamd_event_t known_wlan_event = nwamd_event_init_object_action (NWAM_OBJECT_TYPE_KNOWN_WLAN, known_wlan, NULL, action); if (known_wlan_event == NULL) return (1); nwamd_event_enqueue(known_wlan_event); return (0); }
jasonsbarr/types
packages/types/lib/conversions/effectToId.js
<filename>packages/types/lib/conversions/effectToId.js import { Id } from "@jasonsbarr/functional-core/lib/types/Id.js"; export const effectToId = (effect) => effect.fold(Id);
alexanderkurash/edge-sip2
src/test/java/org/folio/edge/sip2/parser/PatronInformationMessageParserTests.java
package org.folio.edge.sip2.parser; import static java.lang.Character.valueOf; import static java.time.temporal.ChronoUnit.SECONDS; import static org.folio.edge.sip2.domain.messages.enumerations.Language.ENGLISH; import static org.folio.edge.sip2.domain.messages.enumerations.Summary.CHARGED_ITEMS; import static org.folio.edge.sip2.domain.messages.enumerations.Summary.FINE_ITEMS; import static org.folio.edge.sip2.domain.messages.enumerations.Summary.HOLD_ITEMS; import static org.folio.edge.sip2.domain.messages.enumerations.Summary.OVERDUE_ITEMS; import static org.folio.edge.sip2.domain.messages.enumerations.Summary.RECALL_ITEMS; import static org.folio.edge.sip2.domain.messages.enumerations.Summary.UNAVAILABLE_HOLDS; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; import java.util.stream.Stream; import org.folio.edge.sip2.api.support.TestUtils; import org.folio.edge.sip2.domain.messages.enumerations.Summary; import org.folio.edge.sip2.domain.messages.requests.PatronInformation; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; class PatronInformationMessageParserTests { @ParameterizedTest @MethodSource("providePatronInformationSummary") void testParse(String summaryString, Summary summary) { PatronInformationMessageParser parser = new PatronInformationMessageParser(valueOf('|'), TestUtils.UTCTimeZone); final OffsetDateTime transactionDate = TestUtils.getOffsetDateTimeUtc().truncatedTo(SECONDS); final DateTimeFormatter formatter = DateTimeFormatter .ofPattern("yyyyMMdd HHmmss"); final String transactionDateString = formatter.format(transactionDate); final PatronInformation patronInformation = parser.parse( "001" + transactionDateString + summaryString + "AApatron_id|AD1234|AC|" + "AOuniversity_id|BP1|BQ10|"); assertEquals(ENGLISH, patronInformation.getLanguage()); assertEquals(transactionDate, patronInformation.getTransactionDate()); assertEquals(summary, patronInformation.getSummary()); assertEquals("university_id", patronInformation.getInstitutionId()); assertEquals("patron_id", patronInformation.getPatronIdentifier()); assertEquals("", patronInformation.getTerminalPassword()); assertEquals("<PASSWORD>4", patronInformation.getPatronPassword()); assertEquals(Integer.valueOf(1), patronInformation.getStartItem()); assertEquals(Integer.valueOf(10), patronInformation.getEndItem()); } @Test void testParseIgnoresUnknownField() { PatronInformationMessageParser parser = new PatronInformationMessageParser(valueOf('|'), TestUtils.UTCTimeZone); final OffsetDateTime transactionDate = TestUtils.getOffsetDateTimeUtc().truncatedTo(SECONDS); final DateTimeFormatter formatter = DateTimeFormatter .ofPattern("yyyyMMdd HHmmss"); final String transactionDateString = formatter.format(transactionDate); final PatronInformation patronInformation = parser.parse( "001" + transactionDateString + " " + "AApatron_id|AD1234|AC|" + "AOuniversity_id|BP1|BQ10|XXInvalid|"); assertEquals(ENGLISH, patronInformation.getLanguage()); assertEquals(transactionDate, patronInformation.getTransactionDate()); assertNull(patronInformation.getSummary()); assertEquals("university_id", patronInformation.getInstitutionId()); assertEquals("patron_id", patronInformation.getPatronIdentifier()); assertEquals("", patronInformation.getTerminalPassword()); assertEquals("<PASSWORD>", patronInformation.getPatronPassword()); assertEquals(Integer.valueOf(1), patronInformation.getStartItem()); assertEquals(Integer.valueOf(10), patronInformation.getEndItem()); } private static Stream<Arguments> providePatronInformationSummary() { return Stream.of( Arguments.of("Y ", HOLD_ITEMS), Arguments.of(" Y ", OVERDUE_ITEMS), Arguments.of(" Y ", CHARGED_ITEMS), Arguments.of(" Y ", FINE_ITEMS), Arguments.of(" Y ", RECALL_ITEMS), Arguments.of(" Y ", UNAVAILABLE_HOLDS), Arguments.of(" ", null) ); } }
mykumar/netflex
src/config/api.js
const topTVPicks = { page: 1, total_results: 73736, total_pages: 3687, results: [ { original_title: "The Big Bang Theory", genre_ids: [35], name: "The Big Bang Theory", popularity: 326.987531, origin_country: ["US"], vote_count: 2963, first_air_date: "2007-09-24", backdrop_path: "/nGsNruW3W27V6r4gkyc3iiEGsKR.jpg", original_language: "en", id: 1418, vote_average: 6.8, overview: "The Big Bang Theory is centered on five characters living in Pasadena, California: roommates <NAME> and <NAME>; Penny, a waitress and aspiring actress who lives across the hall; and Leonard and Sheldon's equally geeky and socially awkward friends and co-workers, mechanical engineer <NAME> and astrophysicist <NAME>. The geekiness and intellect of the four guys is contrasted for comic effect with Penny's social skills and common sense.", poster_path: "/ooBGRQBdbGzBxAVfExiO8r7kloA.jpg" }, { original_title: "Westworld", genre_ids: [878, 37], name: "Westworld", popularity: 150.867844, origin_country: ["US"], vote_count: 1332, first_air_date: "2016-10-02", backdrop_path: "/yp94aOXzuqcQHva90B3jxLfnOO9.jpg", original_language: "en", id: 63247, vote_average: 8.2, overview: "A dark odyssey about the dawn of artificial consciousness and the evolution of sin. Set at the intersection of the near future and the reimagined past, it explores a world in which every human appetite, no matter how noble or depraved, can be indulged.", poster_path: "/6aj09UTMQNyfSfk0ZX8rYOEsXL2.jpg" }, { original_title: "The Walking Dead", genre_ids: [18, 10759, 10765], name: "The Walking Dead", popularity: 112.668407, origin_country: ["US"], vote_count: 3390, first_air_date: "2010-10-31", backdrop_path: "/xVzvD5BPAU4HpleFSo8QOdHkndo.jpg", original_language: "en", id: 1402, vote_average: 7.3, overview: "Sheriff's deputy <NAME> awakens from a coma to find a post-apocalyptic world dominated by flesh-eating zombies. He sets out to find his family and encounters many other survivors along the way.", poster_path: "/yn7psGTZsHumHOkLUmYpyrIcA2G.jpg" }, { original_title: "Mindhunter", genre_ids: [80, 18], name: "Mindhunter", popularity: 103.908784, origin_country: ["US"], vote_count: 347, first_air_date: "2017-10-13", backdrop_path: "/a906PH7CDmSOdS7kmnAgdWk5mhv.jpg", original_language: "en", id: 67744, vote_average: 7.5, overview: "An agent in the FBI's Elite Serial Crime Unit develops profiling techniques as he pursues notorious serial killers and rapists.", poster_path: "/r7RIwuceOaDP4KTmU1EFeDniRq4.jpg" }, { original_title: "Law & Order: Special Victims Unit", id: 2734, name: "Law & Order: Special Victims Unit", popularity: 96.865156, vote_count: 453, vote_average: 6.2, first_air_date: "1999-09-20", poster_path: "/yzMQBlirydvKp4Zgr5FbXlsrRmw.jpg", genre_ids: [80, 18], original_language: "en", backdrop_path: "/kOvt2BOOwSAQCT8yo3pM3X2GXjh.jpg", overview: "In the criminal justice system, sexually-based offenses are considered especially heinous. In New York City, the dedicated detectives who investigate these vicious felonies are members of an elite squad known as the Special Victims Unit. These are their stories.", origin_country: ["US"] }, { original_title: "<NAME>", genre_ids: [16, 35], name: "<NAME>", popularity: 95.704109, origin_country: ["US"], vote_count: 1513, first_air_date: "1989-12-17", backdrop_path: "/f5uNbUC76oowt5mt5J9QlqrIYQ6.jpg", original_language: "en", id: 456, vote_average: 7.2, overview: "Set in Springfield, the average American town, the show focuses on the antics and everyday adventures of the Simpson family; Homer, Marge, Bart, Lisa and Maggie, as well as a virtual cast of thousands. Since the beginning, the series has been a pop culture icon, attracting hundreds of celebrities to guest star. The show has also made name for itself in its fearless satirical take on politics, media and American life in general.", poster_path: "/yTZQkSsxUFJZJe67IenRM0AEklc.jpg" }, { original_title: "The Flash", genre_ids: [18, 10765], name: "The Flash", popularity: 83.304389, origin_country: ["US"], vote_count: 2102, first_air_date: "2014-10-07", backdrop_path: "/mmxxEpTqVdwBlu5Pii7tbedBkPC.jpg", original_language: "en", id: 60735, vote_average: 6.7, overview: 'After a particle accelerator causes a freak storm, CSI Investigator <NAME> is struck by lightning and falls into a coma. Months later he awakens with the power of super speed, granting him the ability to move through Central City like an unseen guardian angel. Though initially excited by his newfound powers, Barry is shocked to discover he is not the only "meta-human" who was created in the wake of the accelerator explosion -- and not everyone is using their new powers for good. Barry partners with <NAME> and dedicates his life to protect the innocent. For now, only a few close friends and associates know that Barry is literally the fastest man alive, but it won\'t be long before the world learns what <NAME> has become...The Flash.', poster_path: "/lUFK7ElGCk9kVEryDJHICeNdmd1.jpg" }, { original_title: "The Expanse", genre_ids: [18, 9648, 10765], name: "The Expanse", popularity: 82.891143, origin_country: ["US"], vote_count: 533, first_air_date: "2015-12-14", backdrop_path: "/beIjmWr3OBOtcWK4tKMObOIDJ1C.jpg", original_language: "en", id: 63639, vote_average: 7.5, overview: "A thriller set two hundred years in the future following the case of a missing young woman who brings a hardened detective and a rogue ship's captain together in a race across the solar system to expose the greatest conspiracy in human history.", poster_path: "/prJFWxJ0x8tBPTliMjj51wgYnSK.jpg" }, { original_title: "The Missing", genre_ids: [18, 9648], name: "The Missing", popularity: 78.970169, origin_country: ["GB"], vote_count: 109, first_air_date: "2014-10-28", backdrop_path: "/2hF2RnjVwHvxfhH2lkB9H9FdQHb.jpg", original_language: "en", id: 61555, vote_average: 7.1, overview: "A gripping anthological relationship thriller series exploring the emotional fallout of a child's abduction not only on the family but on the wider community, told over two time frames.", poster_path: "/w1FDeOGoFS1qsSRHlj2Jzp2P0e1.jpg" }, { original_title: "13 Reasons Why", genre_ids: [18, 9648], name: "13 Reasons Why", popularity: 77.492646, origin_country: ["US"], vote_count: 519, first_air_date: "2017-03-31", backdrop_path: "/sZb21d6EWKAEKZ9GrLQeMwX4cWN.jpg", original_language: "en", id: 66788, vote_average: 7.3, overview: "After a teenage girl's perplexing suicide, a classmate receives a series of tapes that unravel the mystery of her tragic choice.", poster_path: "/gpULvrgvq1Qidu8EpWevrRUfVhw.jpg" }, { original_title: "Cops", genre_ids: [10764], name: "Cops", popularity: 74.963769, origin_country: ["US"], vote_count: 71, first_air_date: "1989-03-11", backdrop_path: "/7xQR6ixywZofrEHKfI1z6CWKFsC.jpg", original_language: "en", id: 3670, vote_average: 5.9, overview: "Follow real-life law enforcement officers from various regions and departments of the United States armed with nothing but with cameras to capture their actions, performing their daily duty to serve and protect the public.", poster_path: "/zZy2Eg2ioxRgWc9WjMIu67ueT97.jpg" }, { original_title: "Supernatural", genre_ids: [18, 9648, 10765], name: "Supernatural", popularity: 74.521084, origin_country: ["US"], vote_count: 1399, first_air_date: "2005-09-13", backdrop_path: "/koMUCyGWNtH5LXYbGqjsUwvgtsT.jpg", original_language: "en", id: 1622, vote_average: 7.2, overview: "When they were boys, Sam and <NAME> lost their mother to a mysterious and demonic supernatural force. Subsequently, their father raised them to be soldiers. He taught them about the paranormal evil that lives in the dark corners and on the back roads of America ... and he taught them how to kill it. Now, the Winchester brothers crisscross the country in their '67 Chevy Impala, battling every kind of supernatural threat they encounter along the way. ", poster_path: "/pui1V389cQft0BVFu9pbsYLEW1Q.jpg" }, { original_title: "ポケモン", genre_ids: [16, 10759], name: "Pokémon", popularity: 73.90747, origin_country: ["JP"], vote_count: 195, first_air_date: "1997-04-01", backdrop_path: "/uxBFkJNwp9DEIE7k6YhKAorVpkp.jpg", original_language: "ja", id: 60572, vote_average: 6.1, overview: "Join Ash Ketchum, accompanied by his partner Pikachu, as he travels through many regions, meets new friends and faces new challenges on his quest to become a Pokémon Master.", poster_path: "/2pcTUs20ysCdA6DZclaPmGXD6ph.jpg" }, { original_title: "The Daily Show with <NAME>", genre_ids: [35, 10763], name: "The Daily Show with <NAME>", popularity: 71.401688, origin_country: ["US"], vote_count: 164, first_air_date: "1996-07-22", backdrop_path: "/uyilhJ7MBLjiaQXboaEwe44Z0jA.jpg", original_language: "en", id: 2224, vote_average: 6.8, overview: "The Daily Show is an American late night satirical television program airing each Monday through Thursday on Comedy Central and, in Canada, The Comedy Network. Describing itself as a fake news program, The Daily Show draws its comedy and satire from recent news stories, political figures, media organizations, and often, aspects of the show itself.", poster_path: "/tZlqGXWGzEJNRl9QCCUN8ioSv2D.jpg" }, { original_title: "The 100", genre_ids: [18, 10765], name: "The 100", popularity: 68.226679, origin_country: ["US"], vote_count: 1076, first_air_date: "2014-03-19", backdrop_path: "/qYTIuJJ7fIehicAt3bl0vW70Sq6.jpg", original_language: "en", id: 48866, vote_average: 6.4, overview: "Based on the books by <NAME>, this show takes place 100 years in the future, when the Earth has been abandoned due to radioactivity. The last surviving humans live on an ark orbiting the planet — but the ark won't last forever. So the repressive regime picks 100 expendable juvenile delinquents to send down to Earth to see if the planet is still habitable.", poster_path: "/fjJAcCmeSRQIpFttRX6NGdjnTIh.jpg" }, { original_title: "Grey's Anatomy", genre_ids: [18], name: "Grey's Anatomy", popularity: 67.943216, origin_country: ["US"], vote_count: 704, first_air_date: "2005-03-27", backdrop_path: "/y6JABtgWMVYPx84Rvy7tROU5aNH.jpg", original_language: "en", id: 1416, vote_average: 6.1, overview: "Follows the personal and professional lives of a group of doctors at Seattle’s Grey Sloan Memorial Hospital.", poster_path: "/mgOZSS2FFIGtfVeac1buBw3Cx5w.jpg" }, { original_title: "Game of Thrones", genre_ids: [18, 10759, 10765], name: "Game of Thrones", popularity: 66.224206, origin_country: ["US"], vote_count: 4530, first_air_date: "2011-04-17", backdrop_path: "/gX8SYlnL9ZznfZwEH4KJUePBFUM.jpg", original_language: "en", id: 1399, vote_average: 8.1, overview: "Seven noble families fight for control of the mythical land of Westeros. Friction between the houses leads to full-scale war. All while a very ancient evil awakens in the farthest north. Amidst the war, a neglected military order of misfits, the Night's Watch, is all that stands between the realms of men and icy horrors beyond.", poster_path: "/gwPSoYUHAKmdyVywgLpKKA4BjRr.jpg" }, { original_title: "Marvel's Iron Fist", genre_ids: [80, 18, 10759, 10765], name: "Marvel's Iron Fist", popularity: 63.119308, origin_country: ["US"], vote_count: 546, first_air_date: "2017-03-17", backdrop_path: "/xHCfWGlxwbtMeeOnTvxUCZRGnkk.jpg", original_language: "en", id: 62127, vote_average: 6.1, overview: "<NAME> resurfaces 15 years after being presumed dead. Now, with the power of the Iron Fist, he seeks to reclaim his past and fulfill his destiny.", poster_path: "/nv4nLXbDhcISPP8C1mgaxKU50KO.jpg" }, { original_title: "Arrow", genre_ids: [28, 12, 80, 18, 9648, 878], name: "Arrow", popularity: 62.813885, origin_country: ["US"], vote_count: 1864, first_air_date: "2012-10-10", backdrop_path: "/dKxkwAJfGuznW8Hu0mhaDJtna0n.jpg", original_language: "en", id: 1412, vote_average: 5.9, overview: "Spoiled billionaire playboy <NAME> is missing and presumed dead when his yacht is lost at sea. He returns five years later a changed man, determined to clean up the city as a hooded vigilante armed with a bow.", poster_path: "/mo0FP1GxOFZT4UDde7RFDz5APXF.jpg" }, { original_title: "Marvel's Agents of S.H.I.E.L.D.", genre_ids: [18, 10759, 10765], name: "Marvel's Agents of S.H.I.E.L.D.", popularity: 62.390795, origin_country: ["US"], vote_count: 1075, first_air_date: "2013-09-24", backdrop_path: "/qtr5i6hOm6oVzTYl3jOQAYP3oc7.jpg", original_language: "en", id: 1403, vote_average: 6.6, overview: "Agent <NAME> of S.H.I.E.L.D. (Strategic Homeland Intervention, Enforcement and Logistics Division) puts together a team of agents to investigate the new, the strange and the unknown around the globe, protecting the ordinary from the extraordinary.", poster_path: "/xjm6uVktPuKXNILwjLXwVG5d5BU.jpg" } ] }; const movie = { page: 1, total_results: 362020, total_pages: 18101, results: [ { vote_count: 1088, id: 383498, video: false, vote_average: 8, title: "Deadpool 2", popularity: 469.317561, poster_path: "/to0spRl1CMDvyUbOnbb4fTk3VAd.jpg", original_language: "en", original_title: "Deadpool 2", genre_ids: [28, 35, 878], backdrop_path: "/3P52oz9HPQWxcwHOwxtyrVV1LKi.jpg", adult: false, overview: "Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad guys to save a boy's life.", release_date: "2018-05-15" }, { vote_count: 4018, id: 299536, video: false, vote_average: 8.5, title: "Avengers: Infinity War", popularity: 407.526722, poster_path: "/7WsyChQLEftFiDOVTGkv3hFpyyt.jpg", original_language: "en", original_title: "Avengers: Infinity War", genre_ids: [12, 878, 14, 28], backdrop_path: "/bOGkgRGdhrBYJSLpXaxhXVstddV.jpg", adult: false, overview: "As the Avengers and their allies have continued to protect the world from threats too large for any one hero to handle, a new danger has emerged from the cosmic shadows: Thanos. A despot of intergalactic infamy, his goal is to collect all six Infinity Stones, artifacts of unimaginable power, and use them to inflict his twisted will on all of reality. Everything the Avengers have fought for has led up to this moment - the fate of Earth and existence itself has never been more uncertain.", release_date: "2018-04-25" }, { vote_count: 1894, id: 337167, video: false, vote_average: 6, title: "Fifty Shades Freed", popularity: 291.806972, poster_path: "/jjPJ4s3DWZZvI4vw8Xfi4Vqa1Q8.jpg", original_language: "en", original_title: "Fifty Shades Freed", genre_ids: [18, 10749], backdrop_path: "/9ywA15OAiwjSTvg3cBs9B7kOCBF.jpg", adult: false, overview: "Believing they have left behind shadowy figures from their past, newlyweds Christian and Ana fully embrace an inextricable connection and shared life of luxury. But just as she steps into her role as Mrs. Grey and he relaxes into an unfamiliar stability, new threats could jeopardize their happy ending before it even begins.", release_date: "2018-02-07" }, { vote_count: 6350, id: 284053, video: false, vote_average: 7.4, title: "Thor: Ragnarok", popularity: 203.557592, poster_path: "/rzRwTcFvttcN1ZpX2xv4j3tSdJu.jpg", original_language: "en", original_title: "Thor: Ragnarok", genre_ids: [28, 12, 14, 878, 35], backdrop_path: "/kaIfm5ryEOwYg8mLbq8HkPuM1Fo.jpg", adult: false, overview: "Thor is imprisoned on the other side of the universe and finds himself in a race against time to get back to Asgard to stop Ragnarok, the prophecy of destruction to his homeworld and the end of Asgardian civilization, at the hands of an all-powerful new threat, the ruthless Hela.", release_date: "2017-10-25" }, { vote_count: 5544, id: 284054, video: false, vote_average: 7.3, title: "Black Panther", popularity: 190.62402, poster_path: "/uxzzxijgPIY7slzFvMotPv8wjKA.jpg", original_language: "en", original_title: "Black Panther", genre_ids: [28, 12, 14, 878], backdrop_path: "/AlFqBwJnokrp9zWTXOUv7uhkaeq.jpg", adult: false, overview: "King T'Challa returns home from America to the reclusive, technologically advanced African nation of Wakanda to serve as his country's new leader. However, T'Challa soon finds that he is challenged for the throne by factions within his own country as well as without. Using powers reserved to Wakandan kings, T'Challa assumes the Black Panther mantel to join with girlfriend Nakia, the queen-mother, his princess-kid sister, members of the Dora Milaje (the Wakandan 'special forces') and an American secret agent, to prevent Wakanda from being dragged into a world war.", release_date: "2018-02-13" }, { vote_count: 10, id: 510819, video: false, vote_average: 3.5, title: "Dirty Dead Con Men", popularity: 159.639036, poster_path: "/r70GGoZ5PqqokDDRnVfTN7PPDtJ.jpg", original_language: "en", original_title: "Dirty Dead Con Men", genre_ids: [28, 80, 18], backdrop_path: "/75RJi3yVZnZtVj4Kn1bYGzkhiEx.jpg", adult: false, overview: "A cool and dangerous neo-noir crime film that revolves around the disturbed lives of two unlikely partners: <NAME>, a rogue undercover cop and <NAME>, a smooth and charismatic con man. Together they rip off those operating outside of the law...for their own personal gain. But things go awry when one heist suck them deep into a city-wide conspiracy...", release_date: "2018-03-30" }, { vote_count: 23, id: 499772, video: false, vote_average: 5, title: "Meet Me In St. Gallen", popularity: 140.753645, poster_path: "/kZJEQFk6eiZ9X2x70ve6R1dczus.jpg", original_language: "tl", original_title: "Meet Me In St. Gallen", genre_ids: [18, 10749], backdrop_path: "/7tvwYJPostpjFybjOeygnBHVxrW.jpg", adult: false, overview: "The story of Jesse and Celeste who meets at an unexpected time in their lives. They then realize their names are the same as the characters in the popular break-up romantic comedy, Celeste and <NAME>.", release_date: "2018-02-07" }, { vote_count: 7261, id: 269149, video: false, vote_average: 7.7, title: "Zootopia", popularity: 114.013622, poster_path: "/sM33SANp9z6rXW8Itn7NnG1GOEs.jpg", original_language: "en", original_title: "Zootopia", genre_ids: [16, 12, 10751, 35], backdrop_path: "/mhdeE1yShHTaDbJVdWyTlzFvNkr.jpg", adult: false, overview: "Determined to prove herself, Officer <NAME>, the first bunny on Zootopia's police force, jumps at the chance to crack her first case - even if it means partnering with scam-artist fox <NAME> to solve the mystery.", release_date: "2016-02-11" }, { vote_count: 13043, id: 118340, video: false, vote_average: 7.9, title: "Guardians of the Galaxy", popularity: 112.75331, poster_path: "/y31QB9kn3XSudA15tV7UWQ9XLuW.jpg", original_language: "en", original_title: "Guardians of the Galaxy", genre_ids: [28, 878, 12], backdrop_path: "/bHarw8xrmQeqf3t8HpuMY7zoK4x.jpg", adult: false, overview: "Light years from Earth, 26 years after being abducted, <NAME> finds himself the prime target of a manhunt after discovering an orb wanted by <NAME>.", release_date: "2014-07-30" }, { vote_count: 218, id: 348350, video: false, vote_average: 6.9, title: "Solo: A Star Wars Story", popularity: 106.592928, poster_path: "/3IGbjc5ZC5yxim5W0sFING2kdcz.jpg", original_language: "en", original_title: "Solo: A Star Wars Story", genre_ids: [28, 12, 878], backdrop_path: "/96B1qMN9RxrAFu6uikwFhQ6N6J9.jpg", adult: false, overview: "Through a series of daring escapades deep within a dark and dangerous criminal underworld, Han Solo meets his mighty future copilot Chewbacca and encounters the notorious gambler Lando Calrissian.", release_date: "2018-05-23" }, { vote_count: 8740, id: 297762, video: false, vote_average: 7.2, title: "Wonder Woman", popularity: 105.750982, poster_path: "/imekS7f1OuHyUP2LAiTEM0zBzUz.jpg", original_language: "en", original_title: "Wonder Woman", genre_ids: [28, 12, 14, 10752, 878], backdrop_path: "/6iUNJZymJBMXXriQyFZfLAKnjO6.jpg", adult: false, overview: "An Amazon princess comes to the world of Man in the grips of the First World War to confront the forces of evil and bring an end to human conflict.", release_date: "2017-05-30" }, { vote_count: 14853, id: 293660, video: false, vote_average: 7.5, title: "Deadpool", popularity: 98.501762, poster_path: "/inVq3FRqcYIRl2la8iZikYYxFNR.jpg", original_language: "en", original_title: "Deadpool", genre_ids: [28, 12, 35], backdrop_path: "/n1y094tVDFATSzkTnFxoGZ1qNsG.jpg", adult: false, overview: "Deadpool tells the origin story of former Special Forces operative turned mercenary <NAME>, who after being subjected to a rogue experiment that leaves him with accelerated healing powers, adopts the alter ego Deadpool. Armed with his new abilities and a dark, twisted sense of humor, Deadpool hunts down the man who nearly destroyed his life.", release_date: "2016-02-09" }, { vote_count: 1202, id: 401981, video: false, vote_average: 6.4, title: "Red Sparrow", popularity: 94.650443, poster_path: "/uZwnaMQTdwZz1kwtrrU3IOqxnDu.jpg", original_language: "en", original_title: "Red Sparrow", genre_ids: [9648, 53], backdrop_path: "/cOb2X4ik7UEplQ42jz4lzozuOLt.jpg", adult: false, overview: "<NAME>, <NAME> faces a bleak and uncertain future after she suffers an injury that ends her career. She soon turns to Sparrow School, a secret intelligence service that trains exceptional young people to use their minds and bodies as weapons. Dominika emerges as the most dangerous Sparrow after completing the sadistic training process. As she comes to terms with her new abilities, she meets a CIA agent who tries to convince her that he is the only person she can trust.", release_date: "2018-03-01" }, { vote_count: 8233, id: 321612, video: false, vote_average: 6.8, title: "Beauty and the Beast", popularity: 90.899378, poster_path: "/tWqifoYuwLETmmasnGHO7xBjEtt.jpg", original_language: "en", original_title: "Beauty and the Beast", genre_ids: [10751, 14, 10749], backdrop_path: "/6aUWe0GSl69wMTSWWexsorMIvwU.jpg", adult: false, overview: "A live-action adaptation of Disney's version of the classic tale of a cursed prince and a beautiful young woman who helps him break the spell.", release_date: "2017-03-16" }, { vote_count: 612, id: 427641, video: false, vote_average: 5.9, title: "Rampage", popularity: 86.410197, poster_path: "/30oXQKwibh0uANGMs0Sytw3uN22.jpg", original_language: "en", original_title: "Rampage", genre_ids: [28, 12, 878], backdrop_path: "/wrqUiMXttHE4UBFMhLHlN601MZh.jpg", adult: false, overview: "Primatologist <NAME> shares an unshakable bond with George, the extraordinarily intelligent, silverback gorilla who has been in his care since birth. But a rogue genetic experiment gone awry mutates this gentle ape into a raging creature of enormous size. To make matters worse, it’s soon discovered there are other similarly altered animals. As these newly created alpha predators tear across North America, destroying everything in their path, Okoye teams with a discredited genetic engineer to secure an antidote, fighting his way through an ever-changing battlefield, not only to halt a global catastrophe but to save the fearsome creature that was once his friend.", release_date: "2018-04-12" }, { vote_count: 5514, id: 181808, video: false, vote_average: 7.1, title: "Star Wars: The Last Jedi", popularity: 84.712449, poster_path: "/kOVEVeg59E0wsnXmF9nrh6OmWII.jpg", original_language: "en", original_title: "Star Wars: The Last Jedi", genre_ids: [14, 12, 878], backdrop_path: "/bIUaCtWaRgd78SnoHJDI8TNf7Sd.jpg", adult: false, overview: "Rey develops her newly discovered abilities with the guidance of <NAME>, who is unsettled by the strength of her powers. Meanwhile, the Resistance prepares to do battle with the First Order.", release_date: "2017-12-13" }, { vote_count: 14867, id: 24428, video: false, vote_average: 7.5, title: "The Avengers", popularity: 78.312316, poster_path: "/cezWGskPY5x7GaglTTRN4Fugfb8.jpg", original_language: "en", original_title: "The Avengers", genre_ids: [878, 28, 12], backdrop_path: "/hbn46fQaRmlpBuUrEiFqv0GDL6Y.jpg", adult: false, overview: "When an unexpected enemy emerges and threatens global safety and security, <NAME>, director of the international peacekeeping agency known as S.H.I.E.L.D., finds himself in need of a team to pull the world back from the brink of disaster. Spanning the globe, a daring recruitment effort begins!", release_date: "2012-04-25" }, { vote_count: 4481, id: 354912, video: false, vote_average: 7.8, title: "Coco", popularity: 78.169877, poster_path: "/eKi8dIrr8voobbaGzDpe8w0PVbC.jpg", original_language: "en", original_title: "Coco", genre_ids: [12, 35, 10751, 16], backdrop_path: "/askg3SMvhqEl4OL52YuvdtY40Yb.jpg", adult: false, overview: "Despite his family’s baffling generations-old ban on music, Miguel dreams of becoming an accomplished musician like his idol, <NAME>. Desperate to prove his talent, Miguel finds himself in the stunning and colorful Land of the Dead following a mysterious chain of events. Along the way, he meets charming trickster Hector, and together, they set off on an extraordinary journey to unlock the real story behind Miguel's family history.", release_date: "2017-10-27" }, { vote_count: 7877, id: 198663, video: false, vote_average: 7, title: "The Maze Runner", popularity: 76.089849, poster_path: "/coss7RgL0NH6g4fC2s5atvf3dFO.jpg", original_language: "en", original_title: "The Maze Runner", genre_ids: [28, 9648, 878, 53], backdrop_path: "/lkOZcsXcOLZYeJ2YxJd3vSldvU4.jpg", adult: false, overview: "Set in a post-apocalyptic world, young Thomas is deposited in a community of boys after his memory is erased, soon learning they're all trapped in a maze that will require him to join forces with fellow “runners” for a shot at escape.", release_date: "2014-09-10" }, { vote_count: 664, id: 445571, video: false, vote_average: 7, title: "Game Night", popularity: 70.794715, poster_path: "/85R8LMyn9f2Lev2YPBF8Nughrkv.jpg", original_language: "en", original_title: "Game Night", genre_ids: [9648, 35, 80, 53], backdrop_path: "/nFQYnpri9kqJ91sG1IfyhukhdrD.jpg", adult: false, overview: "Max and Annie's weekly game night gets kicked up a notch when Max's brother Brooks arranges a murder mystery party -- complete with fake thugs and federal agents. So when Brooks gets kidnapped, it's all supposed to be part of the game. As the competitors set out to solve the case, they start to learn that neither the game nor Brooks are what they seem to be. The friends soon find themselves in over their heads as each twist leads to another unexpected turn over the course of one chaotic night.", release_date: "2018-02-22" } ] }; const horror = { id: 27, page: 1, results: [ { adult: false, backdrop_path: "/ufyPovbgRKlKTWrlzDFgULfgfyi.jpg", genre_ids: [27], id: 462593, original_language: "es", original_title: "Los olvidados", overview: "Epecuén was one of the most important touristic villages of Argentina. Thousands of people concurred, attracted by the healing properties of its thermal waters. On November 10th 1985, a huge volume of water broke the protecting embankment and the village was submerged under ten meters of salt water. Epecuén disappeared. Thirty years later, the waters receded and the ruins of Epecuén emerged exposing a bleak and deserted landscape. The residents never returned. The plot revolves around a group of young people that take a trip to the ruins in order to film a documentary about Epecuén. Ignoring the warnings, and after a brief tour, they get stranded in the abandoned village. Contrary to what they thought, they begin to realize that they are really not alone…", release_date: "2017-10-11", poster_path: "/4lJS2NUtcgyJPjOPfFlXcHzHu0D.jpg", popularity: 70.017735, title: "What the Waters Left Behind", video: false, vote_average: 5.3, vote_count: 21 }, { adult: false, backdrop_path: "/5zfVNTrkhMu673zma6qhFzG01ig.jpg", genre_ids: [9648, 878, 18, 12, 14, 27, 53], id: 300668, original_language: "en", original_title: "Annihilation", overview: "A biologist signs up for a dangerous, secret expedition into a mysterious zone where the laws of nature don't apply.", release_date: "2018-02-22", poster_path: "/e3P2Ed0sbmQ6RsoS4dcT3aeEPR.jpg", popularity: 60.103615, title: "Annihilation", video: false, vote_average: 6.3, vote_count: 1888 }, { adult: false, backdrop_path: "/roYyPiQDQKmIKUEhO912693tSja.jpg", genre_ids: [18, 27, 53, 878, 10751], id: 447332, original_language: "en", original_title: "A Quiet Place", overview: "A family is forced to live in silence while hiding from creatures that hunt by sound.", release_date: "2018-04-05", poster_path: "/nAU74GmpUk7t5iklEp3bufwDq4n.jpg", popularity: 59.341026, title: "A Quiet Place", video: false, vote_average: 7.3, vote_count: 1104 }, { adult: false, backdrop_path: "/eQ5xu2pQ5Kergubto5PbbUzey28.jpg", genre_ids: [53, 27], id: 460019, original_language: "en", original_title: "Truth or Dare", overview: "A harmless game of “Truth or Dare” among friends turns deadly when someone—or something—begins to punish those who tell a lie—or refuse the dare.", release_date: "2018-04-12", poster_path: "/zbvziwnZa91AJD78Si0hUb5JP5X.jpg", popularity: 32.063478, title: "Truth or Dare", video: false, vote_average: 5.9, vote_count: 147 }, { adult: false, backdrop_path: "/tcheoA2nPATCm2vvXw2hVQoaEFD.jpg", genre_ids: [18, 27, 53], id: 346364, original_language: "en", original_title: "It", overview: "In a small town in Maine, seven children known as The Losers Club come face to face with life problems, bullies and a monster that takes the shape of a clown called Pennywise.", release_date: "2017-09-05", poster_path: "/9E2y5Q7WlCVNEhP5GiVTjhEhx1o.jpg", popularity: 27.213838, title: "It", video: false, vote_average: 7.1, vote_count: 7636 }, { adult: false, backdrop_path: "/6jajFcaY2YsfGQstJ5HaqZNVseX.jpg", genre_ids: [27, 878, 53], id: 126889, original_language: "en", original_title: "Alien: Covenant", overview: "Bound for a remote planet on the far side of the galaxy, the crew of the colony ship 'Covenant' discovers what is thought to be an uncharted paradise, but is actually a dark, dangerous world – which has its sole inhabitant the 'synthetic', David, survivor of the doomed Prometheus expedition.", release_date: "2017-05-09", poster_path: "/zecMELPbU5YMQpC81Z8ImaaXuf9.jpg", popularity: 25.784415, title: "Alien: Covenant", video: false, vote_average: 5.8, vote_count: 3793 }, { adult: false, backdrop_path: "/zWGAnbxjjwY3xFGuOeR26LGbBlG.jpg", genre_ids: [27, 53], id: 238636, original_language: "en", original_title: "The Purge: Anarchy", overview: "Three groups of people are trying to survive Purge Night, when their stories intertwine and are left stranded in The Purge trying to survive the chaos and violence that occurs.", release_date: "2014-07-17", poster_path: "/l1DRl40x2OWUoPP42v8fjKdS1Z3.jpg", popularity: 25.262608, title: "The Purge: Anarchy", video: false, vote_average: 6.6, vote_count: 2629 }, { adult: false, backdrop_path: "/fLL6WfUXvdQee1fD4xuzNnWfVBk.jpg", genre_ids: [27, 9648, 80], id: 176, original_language: "en", original_title: "Saw", overview: "Obsessed with teaching his victims the value of life, a deranged, sadistic serial killer abducts the morally wayward. Once captured, they must face impossible choices in a horrific game of survival. The victims must fight to win their lives back, or die trying...", release_date: "2004-10-01", poster_path: "/dHYvIgsax8ZFgkz1OslE4V6Pnf5.jpg", popularity: 25.18716, title: "Saw", video: false, vote_average: 7.3, vote_count: 3355 }, { adult: false, backdrop_path: "/gHBdkHJQglK0pjX7L8NE8bp8TLj.jpg", genre_ids: [9648, 53, 27], id: 419430, original_language: "en", original_title: "Get Out", overview: "Chris and his girlfriend Rose go upstate to visit her parents for the weekend. At first, Chris reads the family's overly accommodating behavior as nervous attempts to deal with their daughter's interracial relationship, but as the weekend progresses, a series of increasingly disturbing discoveries lead him to a truth that he never could have imagined.", release_date: "2017-02-24", poster_path: "/1SwAVYpuLj8KsHxllTF8Dt9dSSX.jpg", popularity: 25.122189, title: "Get Out", video: false, vote_average: 7.4, vote_count: 5549 }, { adult: false, backdrop_path: "/7Yup0zaw4AhNyw1JvyAE1EytWsq.jpg", genre_ids: [80, 27, 9648, 53], id: 298250, original_language: "en", original_title: "Jigsaw", overview: "Dead bodies begin to turn up all over the city, each meeting their demise in a variety of grisly ways. All investigations begin to point the finger at deceased killer <NAME>.", release_date: "2017-10-25", poster_path: "/gvBVIlcMaeWKhGjgGjlShiL4w4r.jpg", popularity: 23.816752, title: "Jigsaw", video: false, vote_average: 6, vote_count: 1120 }, { adult: false, backdrop_path: "/4G6FNNLSIVrwSRZyFs91hQ3lZtD.jpg", genre_ids: [27, 53], id: 381288, original_language: "en", original_title: "Split", overview: "Though Kevin has evidenced 23 personalities to his trusted psychiatrist, Dr. Fletcher, there remains one still submerged who is set to materialize and dominate all the others. Compelled to abduct three teenage girls led by the willful, observant Casey, Kevin reaches a war for survival among all of those contained within him — as well as everyone around him — as the walls between his compartments shatter apart.", release_date: "2017-01-19", poster_path: "/rXMWOZiCt6eMX22jWuTOSdQ98bY.jpg", popularity: 23.807294, title: "Split", video: false, vote_average: 7.1, vote_count: 6556 }, { adult: false, backdrop_path: "/fGUOtM4IVkuyPQr42XIsGnwRA2h.jpg", genre_ids: [28, 53, 27], id: 467938, original_language: "en", original_title: "Revenge", overview: "The story sees three wealthy, middle-aged CEOs – all married family men – get together for their annual hunting game in a desert canyon. It’s a way for them to let off steam and affirm their manhood with guns. But this time, one of them has come along with his young mistress, a sexy Lolita who quickly arouses the interest of the two others... Things get out of hand... Left for dead in the middle of this arid hell, the young woman comes back to life, and the hunting game turns into a ruthless manhunt...", release_date: "2018-02-07", poster_path: "/lqRS44Ow197JWt2R32FkcQsIvAT.jpg", popularity: 23.686752, title: "Revenge", video: false, vote_average: 6.8, vote_count: 69 }, { adult: false, backdrop_path: "/6hBIRNqGhaFxMHLRyudhRJOJGHt.jpg", genre_ids: [27, 53], id: 13186, original_language: "en", original_title: "Wrong Turn 2: Dead End", overview: "Retired military commander Colonel <NAME> hosts the simulated post-apocalyptic reality show where participants are challenged to survive a remote West Virginia wasteland. But the show turns into a nightmarish showdown when each realizes they are being hunted by an inbred family of cannibals determined to make them all dinner!", release_date: "2007-08-25", poster_path: "/ftmiyfrTrqTi5Qod62nGRP9BGPn.jpg", popularity: 22.076779, title: "Wrong Turn 2: Dead End", video: false, vote_average: 5.5, vote_count: 376 }, { adult: false, backdrop_path: "/uuQpQ8VDOtVL2IO4y2pR58odkS5.jpg", genre_ids: [18, 27, 9648], id: 381283, original_language: "en", original_title: "mother!", overview: "A couple's relationship is tested when uninvited guests arrive at their home, disrupting their tranquil existence.", release_date: "2017-09-13", poster_path: "/2yOKarmL8B4oXaLXUdHu882SUbu.jpg", popularity: 21.75052, title: "mother!", video: false, vote_average: 7, vote_count: 1986 }, { adult: false, backdrop_path: "/PwI3EfasE9fVuXsmMu9ffJh0Re.jpg", genre_ids: [9648, 27, 53], id: 406563, original_language: "en", original_title: "Insidious: The Last Key", overview: "Parapsychologist Elise Rainier and her team travel to Five Keys, N.M., to investigate a man's claim of a haunting. Terror soon strikes when Rainier realizes that the house he lives in was her family's old home.", release_date: "2018-01-03", poster_path: "/nb9fc9INMg8kQ8L7sE7XTNsZnUX.jpg", popularity: 21.523197, title: "Insidious: The Last Key", video: false, vote_average: 6, vote_count: 674 }, { adult: false, backdrop_path: "/sAMbPP5APevu6oJdUT4YNgpyR8o.jpg", genre_ids: [27, 80], id: 41439, original_language: "en", original_title: "Saw 3D", overview: "As a deadly battle rages over Jigsaw's brutal legacy, a group of Jigsaw survivors gathers to seek the support of self-help guru and fellow survivor <NAME>, a man whose own dark secrets unleash a new wave of terror.", release_date: "2010-10-21", poster_path: "/mBQX4TCfDEk2a5mvu0Z0PFeFoUp.jpg", popularity: 21.38969, title: "Saw: The Final Chapter", video: false, vote_average: 5.8, vote_count: 1070 }, { adult: false, backdrop_path: "/aUtLuEvTI1Z0vItORUYho4UiU6z.jpg", genre_ids: [27, 53], id: 371608, original_language: "en", original_title: "The Strangers: Prey at Night", overview: "A family's road trip takes a dangerous turn when they arrive at a secluded mobile home park to stay with some relatives and find it mysteriously deserted. Under the cover of darkness, three masked psychopaths pay them a visit to test the family's every limit as they struggle to survive.", release_date: "2018-03-07", poster_path: "/vdxLpPsZkPZdFrREp7eSeSzcimj.jpg", popularity: 20.774499, title: "The Strangers: Prey at Night", video: false, vote_average: 5.5, vote_count: 79 }, { adult: false, backdrop_path: "/pOgXUXUJDhbRl6u1kPAb7ixzvsR.jpg", genre_ids: [12, 27, 35], id: 257445, original_language: "en", original_title: "Goosebumps", overview: "After moving to a small town, <NAME> finds a silver lining when he meets next door neighbor Hannah, the daughter of bestselling Goosebumps series author <NAME>. When Zach unintentionally unleashes real monsters from their manuscripts and they begin to terrorize the town, it’s suddenly up to Stine, Zach and Hannah to get all of them back in the books where they belong.", release_date: "2015-08-05", poster_path: "/cvuNet2rxPiTf9L0eQRNpBi7zgp.jpg", popularity: 20.690156, title: "Goosebumps", video: false, vote_average: 6.1, vote_count: 1349 }, { adult: false, backdrop_path: "/sQuUUghbFZmdl8pjlqbrcj9C0k7.jpg", genre_ids: [35, 27, 28, 80], id: 489939, original_language: "en", original_title: "Daphne & Velma", overview: "Before their eventual team-up with Scooby and the gang, bright and optimistic Daphne and whip-smart and analytical Velma are both mystery-solving teens who are best friends but have only met online - until now. Daphne has just transferred to Velma's school, Ridge Valley High, an incredible tech-savvy institute with all the latest gadgets provided by the school's benefactor, tech billionaire Tobias Bloom. And while competition is fierce among the students for a coveted internship at Bloom Innovative, Daphne and Velma dig beyond all the gadgets and tech to investigate what is causing some of the brightest students in school to disappear - only to emerge again in a zombie-fied state.", release_date: "2018-04-29", poster_path: "/zG2DHbo2GNxSmcFWqGkAPgS6hC8.jpg", popularity: 20.327273, title: "Daphne & Velma", video: false, vote_average: 5.4, vote_count: 5 }, { adult: false, backdrop_path: "/xywrNUGd9TYsa2lxRMbVRd8hsom.jpg", genre_ids: [27, 53], id: 23823, original_language: "en", original_title: "Wrong Turn 3: Left for Dead", overview: "A group of people find themselves trapped in the backwoods of West Virginia, fighting for their lives against a group of vicious and horribly disfigured inbred cannibals.", release_date: "2009-01-01", poster_path: "/9J4Me7ZxiTqtF7KyFWp15j0PKqh.jpg", popularity: 20.148226, title: "Wrong Turn 3: Left for Dead", video: false, vote_average: 4.9, vote_count: 288 } ], total_pages: 943, total_results: 18854 }; const sciFi = { id: 878, page: 1, results: [ { adult: false, backdrop_path: "/3P52oz9HPQWxcwHOwxtyrVV1LKi.jpg", genre_ids: [28, 35, 878], id: 383498, original_language: "en", original_title: "Deadpool 2", overview: "Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad guys to save a boy's life.", release_date: "2018-05-15", poster_path: "/to0spRl1CMDvyUbOnbb4fTk3VAd.jpg", popularity: 469.317561, title: "Deadpool 2", video: false, vote_average: 8, vote_count: 1088 }, { adult: false, backdrop_path: "/bOGkgRGdhrBYJSLpXaxhXVstddV.jpg", genre_ids: [12, 878, 14, 28], id: 299536, original_language: "en", original_title: "Avengers: Infinity War", overview: "As the Avengers and their allies have continued to protect the world from threats too large for any one hero to handle, a new danger has emerged from the cosmic shadows: Thanos. A despot of intergalactic infamy, his goal is to collect all six Infinity Stones, artifacts of unimaginable power, and use them to inflict his twisted will on all of reality. Everything the Avengers have fought for has led up to this moment - the fate of Earth and existence itself has never been more uncertain.", release_date: "2018-04-25", poster_path: "/7WsyChQLEftFiDOVTGkv3hFpyyt.jpg", popularity: 407.526722, title: "Avengers: Infinity War", video: false, vote_average: 8.5, vote_count: 3972 }, { adult: false, backdrop_path: "/kaIfm5ryEOwYg8mLbq8HkPuM1Fo.jpg", genre_ids: [28, 12, 14, 878, 35], id: 284053, original_language: "en", original_title: "Thor: Ragnarok", overview: "Thor is imprisoned on the other side of the universe and finds himself in a race against time to get back to Asgard to stop Ragnarok, the prophecy of destruction to his homeworld and the end of Asgardian civilization, at the hands of an all-powerful new threat, the ruthless Hela.", release_date: "2017-10-25", poster_path: "/rzRwTcFvttcN1ZpX2xv4j3tSdJu.jpg", popularity: 203.557592, title: "Thor: Ragnarok", video: false, vote_average: 7.4, vote_count: 6350 }, { adult: false, backdrop_path: "/AlFqBwJnokrp9zWTXOUv7uhkaeq.jpg", genre_ids: [28, 12, 14, 878], id: 284054, original_language: "en", original_title: "<NAME>", overview: "King T'Challa returns home from America to the reclusive, technologically advanced African nation of Wakanda to serve as his country's new leader. However, T'Challa soon finds that he is challenged for the throne by factions within his own country as well as without. Using powers reserved to Wakandan kings, T'Challa assumes the Black Panther mantel to join with girlfriend Nakia, the queen-mother, his princess-kid sister, members of the Dora Milaje (the Wakandan 'special forces') and an American secret agent, to prevent Wakanda from being dragged into a world war.", release_date: "2018-02-13", poster_path: "/uxzzxijgPIY7slzFvMotPv8wjKA.jpg", popularity: 190.62402, title: "Black Panther", video: false, vote_average: 7.3, vote_count: 5544 }, { adult: false, backdrop_path: "/bHarw8xrmQeqf3t8HpuMY7zoK4x.jpg", genre_ids: [28, 878, 12], id: 118340, original_language: "en", original_title: "Guardians of the Galaxy", overview: "Light years from Earth, 26 years after being abducted, <NAME> finds himself the prime target of a manhunt after discovering an orb wanted by <NAME>.", release_date: "2014-07-30", poster_path: "/y31QB9kn3XSudA15tV7UWQ9XLuW.jpg", popularity: 112.75331, title: "Guardians of the Galaxy", video: false, vote_average: 7.9, vote_count: 13043 }, { adult: false, backdrop_path: "/96B1qMN9RxrAFu6uikwFhQ6N6J9.jpg", genre_ids: [28, 12, 878], id: 348350, original_language: "en", original_title: "Solo: A Star Wars Story", overview: "Through a series of daring escapades deep within a dark and dangerous criminal underworld, <NAME> meets his mighty future copilot Chewbacca and encounters the notorious gambler Lando Calrissian.", release_date: "2018-05-23", poster_path: "/3IGbjc5ZC5yxim5W0sFING2kdcz.jpg", popularity: 106.592928, title: "Solo: A Star Wars Story", video: false, vote_average: 6.9, vote_count: 202 }, { adult: false, backdrop_path: "/6iUNJZymJBMXXriQyFZfLAKnjO6.jpg", genre_ids: [28, 12, 14, 10752, 878], id: 297762, original_language: "en", original_title: "Wonder Woman", overview: "An Amazon princess comes to the world of Man in the grips of the First World War to confront the forces of evil and bring an end to human conflict.", release_date: "2017-05-30", poster_path: "/imekS7f1OuHyUP2LAiTEM0zBzUz.jpg", popularity: 105.750982, title: "Wonder Woman", video: false, vote_average: 7.2, vote_count: 8740 }, { adult: false, backdrop_path: "/wrqUiMXttHE4UBFMhLHlN601MZh.jpg", genre_ids: [28, 12, 878], id: 427641, original_language: "en", original_title: "Rampage", overview: "Primatologist <NAME> shares an unshakable bond with George, the extraordinarily intelligent, silverback gorilla who has been in his care since birth. But a rogue genetic experiment gone awry mutates this gentle ape into a raging creature of enormous size. To make matters worse, it’s soon discovered there are other similarly altered animals. As these newly created alpha predators tear across North America, destroying everything in their path, Okoye teams with a discredited genetic engineer to secure an antidote, fighting his way through an ever-changing battlefield, not only to halt a global catastrophe but to save the fearsome creature that was once his friend.", release_date: "2018-04-12", poster_path: "/30oXQKwibh0uANGMs0Sytw3uN22.jpg", popularity: 86.410197, title: "Rampage", video: false, vote_average: 5.9, vote_count: 612 }, { adult: false, backdrop_path: "/bIUaCtWaRgd78SnoHJDI8TNf7Sd.jpg", genre_ids: [14, 12, 878], id: 181808, original_language: "en", original_title: "Star Wars: The Last Jedi", overview: "Rey develops her newly discovered abilities with the guidance of <NAME>, who is unsettled by the strength of her powers. Meanwhile, the Resistance prepares to do battle with the First Order.", release_date: "2017-12-13", poster_path: "/kOVEVeg59E0wsnXmF9nrh6OmWII.jpg", popularity: 84.71244900000001, title: "Star Wars: The Last Jedi", video: false, vote_average: 7.1, vote_count: 5503 }, { adult: false, backdrop_path: "/hbn46fQaRmlpBuUrEiFqv0GDL6Y.jpg", genre_ids: [878, 28, 12], id: 24428, original_language: "en", original_title: "The Avengers", overview: "When an unexpected enemy emerges and threatens global safety and security, <NAME>, director of the international peacekeeping agency known as S.H.I.E.L.D., finds himself in need of a team to pull the world back from the brink of disaster. Spanning the globe, a daring recruitment effort begins!", release_date: "2012-04-25", poster_path: "/cezWGskPY5x7GaglTTRN4Fugfb8.jpg", popularity: 78.312316, title: "The Avengers", video: false, vote_average: 7.5, vote_count: 14867 }, { adult: false, backdrop_path: "/lkOZcsXcOLZYeJ2YxJd3vSldvU4.jpg", genre_ids: [28, 9648, 878, 53], id: 198663, original_language: "en", original_title: "The Maze Runner", overview: "Set in a post-apocalyptic world, young Thomas is deposited in a community of boys after his memory is erased, soon learning they're all trapped in a maze that will require him to join forces with fellow “runners” for a shot at escape.", release_date: "2014-09-10", poster_path: "/coss7RgL0NH6g4fC2s5atvf3dFO.jpg", popularity: 76.089849, title: "The Maze Runner", video: false, vote_average: 7, vote_count: 7877 }, { adult: false, backdrop_path: "/t7VSsAbIQS6kpO4ikuCNSiugsSy.jpg", genre_ids: [878, 28, 18, 53], id: 119450, original_language: "en", original_title: "Dawn of the Planet of the Apes", overview: "A group of scientists in San Francisco struggle to stay alive in the aftermath of a plague that is wiping out humanity, while Caesar tries to maintain dominance over his community of intelligent apes.", release_date: "2014-06-26", poster_path: "/2EUAUIu5lHFlkj5FRryohlH6CRO.jpg", popularity: 68.286303, title: "Dawn of the Planet of the Apes", video: false, vote_average: 7.2, vote_count: 5700 }, { adult: false, backdrop_path: "/gBmrsugfWpiXRh13Vo3j0WW55qD.jpg", genre_ids: [28, 12, 878], id: 351286, original_language: "en", original_title: "Jurassic World: Fallen Kingdom", overview: "A volcanic eruption threatens the remaining dinosaurs on the island of Isla Nublar, where the creatures have freely roamed for several years after the demise of an animal theme park known as Jurassic World. <NAME>, the former park manager, has now founded the Dinosaur Protection Group, an organization dedicated to protecting the dinosaurs. To help with her cause, Claire has recruited <NAME>, a former dinosaur trainer who worked at the park, to prevent the extinction of the dinosaurs once again.", release_date: "2018-06-06", poster_path: "/c9XxwwhPHdaImA2f1WEfEsbhaFB.jpg", popularity: 62.336305, title: "Jurassic World: Fallen Kingdom", video: false, vote_average: 0, vote_count: 28 }, { adult: false, backdrop_path: "/ulMscezy9YX0bhknvJbZoUgQxO5.jpg", genre_ids: [18, 878, 10752], id: 281338, original_language: "en", original_title: "War for the Planet of the Apes", overview: "Caesar and his apes are forced into a deadly conflict with an army of humans led by a ruthless Colonel. After the apes suffer unimaginable losses, Caesar wrestles with his darker instincts and begins his own mythic quest to avenge his kind. As the journey finally brings them face to face, Caesar and the Colonel are pitted against each other in an epic battle that will determine the fate of both their species and the future of the planet.", release_date: "2017-07-11", poster_path: "/3vYhLLxrTtZLysXtIWktmd57Snv.jpg", popularity: 60.562924, title: "War for the Planet of the Apes", video: false, vote_average: 6.9, vote_count: 3746 }, { adult: false, backdrop_path: "/5zfVNTrkhMu673zma6qhFzG01ig.jpg", genre_ids: [9648, 878, 18, 12, 14, 27, 53], id: 300668, original_language: "en", original_title: "Annihilation", overview: "A biologist signs up for a dangerous, secret expedition into a mysterious zone where the laws of nature don't apply.", release_date: "2018-02-22", poster_path: "/e3P2Ed0sbmQ6RsoS4dcT3aeEPR.jpg", popularity: 60.103615, title: "Annihilation", video: false, vote_average: 6.3, vote_count: 1888 }, { adult: false, backdrop_path: "/roYyPiQDQKmIKUEhO912693tSja.jpg", genre_ids: [18, 27, 53, 878, 10751], id: 447332, original_language: "en", original_title: "A Quiet Place", overview: "A family is forced to live in silence while hiding from creatures that hunt by sound.", release_date: "2018-04-05", poster_path: "/nAU74GmpUk7t5iklEp3bufwDq4n.jpg", popularity: 59.341026, title: "A Quiet Place", video: false, vote_average: 7.3, vote_count: 1104 }, { adult: false, backdrop_path: "/t5KONotASgVKq4N19RyhIthWOPG.jpg", genre_ids: [28, 12, 878, 53], id: 135397, original_language: "en", original_title: "Jurassic World", overview: "Twenty-two years after the events of Jurassic Park, Isla Nublar now features a fully functioning dinosaur theme park, Jurassic World, as originally envisioned by <NAME>.", release_date: "2015-06-06", poster_path: "/jjBgi2r5cRt36xF6iNUEhzscEcb.jpg", popularity: 55.126669, title: "Jurassic World", video: false, vote_average: 6.5, vote_count: 10794 }, { adult: false, backdrop_path: "/vc8bCGjdVp0UbMNLzHnHSLRbBWQ.jpg", genre_ids: [28, 12, 35, 878, 18], id: 315635, original_language: "en", original_title: "Spider-Man: Homecoming", overview: "Following the events of Captain America: Civil War, <NAME>, with the help of his mentor <NAME>, tries to balance his life as an ordinary high school student in Queens, New York City, with fighting crime as his superhero alter ego Spider-Man as a new threat, the Vulture, emerges.", release_date: "2017-07-05", poster_path: "/c24sv2weTHPsmDa7jEMN0m2P3RT.jpg", popularity: 51.168563, title: "Spider-Man: Homecoming", video: false, vote_average: 7.3, vote_count: 7476 }, { adult: false, backdrop_path: "/5pAGnkFYSsFJ99ZxDIYnhQbQFXs.jpg", genre_ids: [28, 18, 878], id: 263115, original_language: "en", original_title: "Logan", overview: "In the near future, a weary Logan cares for an ailing Professor X in a hideout on the Mexican border. But Logan's attempts to hide from the world and his legacy are upended when a young mutant arrives, pursued by dark forces.", release_date: "2017-02-28", poster_path: "/gGBu0hKw9BGddG8RkRAMX7B6NDB.jpg", popularity: 50.252329, title: "Logan", video: false, vote_average: 7.7, vote_count: 9053 }, { adult: false, backdrop_path: "/rFtsE7Lhlc2jRWF7SRAU0fvrveQ.jpg", genre_ids: [28, 12, 878], id: 99861, original_language: "en", original_title: "Avengers: Age of Ultron", overview: "When <NAME> tries to jumpstart a dormant peacekeeping program, things go awry and Earth’s Mightiest Heroes are put to the ultimate test as the fate of the planet hangs in the balance. As the villainous Ultron emerges, it is up to The Avengers to stop him from enacting his terrible plans, and soon uneasy alliances and unexpected action pave the way for an epic and unique global adventure.", release_date: "2015-04-22", poster_path: "/t90Y3G8UGQp0f0DrP60wRu9gfrH.jpg", popularity: 49.780669, title: "Avengers: Age of Ultron", video: false, vote_average: 7.3, vote_count: 9288 } ], total_pages: 455, total_results: 9099 }; const comedy = { id: 35, page: 1, results: [ { adult: false, backdrop_path: "/3P52oz9HPQWxcwHOwxtyrVV1LKi.jpg", genre_ids: [28, 35, 878], id: 383498, original_language: "en", original_title: "Deadpool 2", overview: "Wisecracking mercenary Deadpool battles the evil and powerful Cable and other bad guys to save a boy's life.", release_date: "2018-05-15", poster_path: "/to0spRl1CMDvyUbOnbb4fTk3VAd.jpg", popularity: 469.317561, title: "Deadpool 2", video: false, vote_average: 8, vote_count: 1088 }, { adult: false, backdrop_path: "/kaIfm5ryEOwYg8mLbq8HkPuM1Fo.jpg", genre_ids: [28, 12, 14, 878, 35], id: 284053, original_language: "en", original_title: "Thor: Ragnarok", overview: "Thor is imprisoned on the other side of the universe and finds himself in a race against time to get back to Asgard to stop Ragnarok, the prophecy of destruction to his homeworld and the end of Asgardian civilization, at the hands of an all-powerful new threat, the ruthless Hela.", release_date: "2017-10-25", poster_path: "/rzRwTcFvttcN1ZpX2xv4j3tSdJu.jpg", popularity: 203.557592, title: "Thor: Ragnarok", video: false, vote_average: 7.4, vote_count: 6350 }, { adult: false, backdrop_path: "/mhdeE1yShHTaDbJVdWyTlzFvNkr.jpg", genre_ids: [16, 12, 10751, 35], id: 269149, original_language: "en", original_title: "Zootopia", overview: "Determined to prove herself, Officer <NAME>, the first bunny on Zootopia's police force, jumps at the chance to crack her first case - even if it means partnering with scam-artist fox <NAME> to solve the mystery.", release_date: "2016-02-11", poster_path: "/sM33SANp9z6rXW8Itn7NnG1GOEs.jpg", popularity: 114.013622, title: "Zootopia", video: false, vote_average: 7.7, vote_count: 7261 }, { adult: false, backdrop_path: "/n1y094tVDFATSzkTnFxoGZ1qNsG.jpg", genre_ids: [28, 12, 35], id: 293660, original_language: "en", original_title: "Deadpool", overview: "Deadpool tells the origin story of former Special Forces operative turned mercenary <NAME>, who after being subjected to a rogue experiment that leaves him with accelerated healing powers, adopts the alter ego Deadpool. Armed with his new abilities and a dark, twisted sense of humor, Deadpool hunts down the man who nearly destroyed his life.", release_date: "2016-02-09", poster_path: "/inVq3FRqcYIRl2la8iZikYYxFNR.jpg", popularity: 98.501762, title: "Deadpool", video: false, vote_average: 7.5, vote_count: 14853 }, { adult: false, backdrop_path: "/askg3SMvhqEl4OL52YuvdtY40Yb.jpg", genre_ids: [12, 35, 10751, 16], id: 354912, original_language: "en", original_title: "Coco", overview: "Despite his family’s baffling generations-old ban on music, Miguel dreams of becoming an accomplished musician like his idol, <NAME>. Desperate to prove his talent, Miguel finds himself in the stunning and colorful Land of the Dead following a mysterious chain of events. Along the way, he meets charming trickster Hector, and together, they set off on an extraordinary journey to unlock the real story behind Miguel's family history.", release_date: "2017-10-27", poster_path: "/eKi8dIrr8voobbaGzDpe8w0PVbC.jpg", popularity: 78.169877, title: "Coco", video: false, vote_average: 7.8, vote_count: 4481 }, { adult: false, backdrop_path: "/nFQYnpri9kqJ91sG1IfyhukhdrD.jpg", genre_ids: [9648, 35, 80, 53], id: 445571, original_language: "en", original_title: "Game Night", overview: "Max and Annie's weekly game night gets kicked up a notch when Max's brother Brooks arranges a murder mystery party -- complete with fake thugs and federal agents. So when Brooks gets kidnapped, it's all supposed to be part of the game. As the competitors set out to solve the case, they start to learn that neither the game nor Brooks are what they seem to be. The friends soon find themselves in over their heads as each twist leads to another unexpected turn over the course of one chaotic night.", release_date: "2018-02-22", poster_path: "/85R8LMyn9f2Lev2YPBF8Nughrkv.jpg", popularity: 70.794715, title: "Game Night", video: false, vote_average: 7, vote_count: 664 }, { adult: false, backdrop_path: "/6SOLRw0mLepY83uonpbhWIe8mWx.jpg", genre_ids: [28, 35, 36], id: 490214, original_language: "cn", original_title: "时空行者2", overview: "The imperial guard and his three traitorous childhood friends ordered to hunt him down get accidentally buried and kept frozen in time. 400 years later pass and they are defrosted continuing the battle they left behind", release_date: "2018-05-18", poster_path: "/enZENHd2gwVAw4sJKJxtJl1vJ09.jpg", popularity: 58.577681, title: "Iceman 2", video: false, vote_average: 1, vote_count: 1 }, { adult: false, backdrop_path: "/vc8bCGjdVp0UbMNLzHnHSLRbBWQ.jpg", genre_ids: [28, 12, 35, 878, 18], id: 315635, original_language: "en", original_title: "Spider-Man: Homecoming", overview: "Following the events of Captain America: Civil War, <NAME>, with the help of his mentor <NAME>, tries to balance his life as an ordinary high school student in Queens, New York City, with fighting crime as his superhero alter ego Spider-Man as a new threat, the Vulture, emerges.", release_date: "2017-07-05", poster_path: "/c24sv2weTHPsmDa7jEMN0m2P3RT.jpg", popularity: 51.168563, title: "Spider-Man: Homecoming", video: false, vote_average: 7.3, vote_count: 7476 }, { adult: false, backdrop_path: "/rmQszCUBlCeqdtFWTWhGqGTlBW1.jpg", genre_ids: [35], id: 343111, original_language: "hi", original_title: "आगे की सोच", overview: "Aage Ki Soch is 1988 Hindi language movie directed by <NAME> and starring <NAME>apoor, <NAME>, Swapna, <NAME>, and <NAME>", release_date: "1988-01-01", poster_path: "/qSJ0j8PQrhEzmd7jlwpxS4liQI7.jpg", popularity: 50.58721, title: "Aage Ki Soch", video: false, vote_average: 0, vote_count: 0 }, { adult: false, backdrop_path: "/aJn9XeesqsrSLKcHfHP4u5985hn.jpg", genre_ids: [28, 12, 35, 878], id: 283995, original_language: "en", original_title: "Guardians of the Galaxy Vol. 2", overview: "The Guardians must fight to keep their newfound family together as they unravel the mysteries of <NAME>'s true parentage.", release_date: "2017-04-19", poster_path: "/y4MBh0EjBlMuOzv9axM4qJlmhzz.jpg", popularity: 44.270109, title: "Guardians of the Galaxy Vol. 2", video: false, vote_average: 7.6, vote_count: 8170 }, { adult: false, backdrop_path: "/7C921eWK06n12c1miRXnYoEu5Yv.jpg", genre_ids: [12, 28, 14, 35], id: 166426, original_language: "en", original_title: "Pirates of the Caribbean: Dead Men Tell No Tales", overview: "Thrust into an all-new adventure, a down-on-his-luck Capt. <NAME> feels the winds of ill-fortune blowing even more strongly when deadly ghost sailors led by his old nemesis, the evil Capt. Salazar, escape from the Devil's Triangle. Jack's only hope of survival lies in seeking out the legendary Trident of Poseidon, but to find it, he must forge an uneasy alliance with a brilliant and beautiful astronomer and a headstrong young man in the British navy.", release_date: "2017-05-23", poster_path: "/xbpSDU3p7YUGlu9Mr6Egg2Vweto.jpg", popularity: 40.749027, title: "Pirates of the Caribbean: Dead Men Tell No Tales", video: false, vote_average: 6.5, vote_count: 4792 }, { adult: false, backdrop_path: "/OqCXGt5nl1cHPeotxCDvXLLe6p.jpg", genre_ids: [878, 28, 12, 14, 35], id: 98566, original_language: "en", original_title: "Teenage Mutant Ninja Turtles", overview: "The city needs heroes. Darkness has settled over New York City as Shredder and his evil Foot Clan have an iron grip on everything from the police to the politicians. The future is grim until four unlikely outcast brothers rise from the sewers and discover their destiny as Teenage Mutant Ninja Turtles. The Turtles must work with fearless reporter April and her wise-cracking cameraman <NAME> to save the city and unravel Shredder's diabolical plan.", release_date: "2014-08-07", poster_path: "/oDL2ryJ0sV2bmjgshVgJb3qzvwp.jpg", popularity: 31.85093, title: "Teenage Mutant Ninja Turtles", video: false, vote_average: 5.8, vote_count: 3284 }, { adult: false, backdrop_path: "/rz3TAyd5kmiJmozp3GUbYeB5Kep.jpg", genre_ids: [28, 12, 35, 14], id: 353486, original_language: "en", original_title: "Jumanji: Welcome to the Jungle", overview: "The tables are turned as four teenagers are sucked into Jumanji's world - pitted against rhinos, black mambas and an endless variety of jungle traps and puzzles. To survive, they'll play as characters from the game.", release_date: "2017-12-09", poster_path: "/bXrZ5iHBEjH7WMidbUDQ0U2xbmr.jpg", popularity: 31.277376, title: "Jumanji: Welcome to the Jungle", video: false, vote_average: 6.6, vote_count: 4224 }, { adult: false, backdrop_path: "/szytSpLAyBh3ULei3x663mAv5ZT.jpg", genre_ids: [18, 35, 16, 10751], id: 150540, original_language: "en", original_title: "Inside Out", overview: "Growing up can be a bumpy road, and it's no exception for Riley, who is uprooted from her Midwest life when her father starts a new job in San Francisco. Like all of us, Riley is guided by her emotions - Joy, Fear, Anger, Disgust and Sadness. The emotions live in Headquarters, the control center inside Riley's mind, where they help advise her through everyday life. As Riley and her emotions struggle to adjust to a new life in San Francisco, turmoil ensues in Headquarters. Although Joy, Riley's main and most important emotion, tries to keep things positive, the emotions conflict on how best to navigate a new city, house and school.", release_date: "2015-06-09", poster_path: "/aAmfIX3TT40zUHGcCKrlOZRKC7u.jpg", popularity: 30.499225, title: "Inside Out", video: false, vote_average: 7.9, vote_count: 9164 }, { adult: false, backdrop_path: "/zrAO2OOa6s6dQMQ7zsUbDyIBrAP.jpg", genre_ids: [28, 12, 35, 80, 9648, 53], id: 291805, original_language: "en", original_title: "Now You See Me 2", overview: "One year after outwitting the FBI and winning the public’s adulation with their mind-bending spectacles, the Four Horsemen resurface only to find themselves face to face with a new enemy who enlists them to pull off their most dangerous heist yet.", release_date: "2016-06-02", poster_path: "/hU0E130tsGdsYa4K9lc3Xrn5Wyt.jpg", popularity: 29.219216, title: "Now You See Me 2", video: false, vote_average: 6.7, vote_count: 4720 }, { adult: false, backdrop_path: "/yo1ef57MEPkEE4BDZKTZGH9uDcX.jpg", genre_ids: [16, 10751, 35], id: 20352, original_language: "en", original_title: "Despicable Me", overview: "Villainous Gru lives up to his reputation as a despicable, deplorable and downright unlikable guy when he hatches a plan to steal the moon from the sky. But he has a tough time staying on task after three orphans land in his care.", release_date: "2010-07-08", poster_path: "/4zHJhBSY4kNZXfhTlmy2TzXD51M.jpg", popularity: 29.036352, title: "Despicable Me", video: false, vote_average: 7.2, vote_count: 7946 }, { adult: false, backdrop_path: "/jyvWcB4PH1BSPo82t4h8sU4wr2a.jpg", genre_ids: [10751, 35, 16], id: 387592, original_language: "en", original_title: "Early Man", overview: "Set at the dawn of time when dinosaurs and woolly mammoths roamed the earth, Early Man tells the story of how one plucky caveman unites his tribe against a mighty enemy and saves the day.", release_date: "2018-01-26", poster_path: "/hXukFwTKOe7izDsf3ZOdeYikRxF.jpg", popularity: 28.986045, title: "Early Man", video: false, vote_average: 5.9, vote_count: 96 }, { adult: false, backdrop_path: "/oDqbewoFuIEWA7UWurole6MzDGn.jpg", genre_ids: [16, 35, 10751, 12], id: 425, original_language: "en", original_title: "Ice Age", overview: "With the impending ice age almost upon them, a mismatched trio of prehistoric critters – Manny the woolly mammoth, Diego the saber-toothed tiger and Sid the giant sloth – find an orphaned infant and decide to return it to its human parents. Along the way, the unlikely allies become friends but, when enemies attack, their quest takes on far nobler aims.", release_date: "2002-03-10", poster_path: "/zpaQwR0YViPd83bx1e559QyZ35i.jpg", popularity: 27.897055, title: "Ice Age", video: false, vote_average: 7.2, vote_count: 5351 }, { adult: false, backdrop_path: "/dji4Fm0gCDVb9DQQMRvAI8YNnTz.jpg", genre_ids: [16, 35, 10751], id: 862, original_language: "en", original_title: "Toy Story", overview: "Led by Woody, Andy's toys live happily in his room until Andy's birthday brings Buzz Lightyear onto the scene. Afraid of losing his place in Andy's heart, Woody plots against Buzz. But when circumstances separate Buzz and Woody from their owner, the duo eventually learns to put aside their differences.", release_date: "1995-10-30", poster_path: "/rhIRbceoE9lR4veEXuwCC2wARtG.jpg", popularity: 26.985169, title: "Toy Story", video: false, vote_average: 7.8, vote_count: 7308 }, { adult: false, backdrop_path: "/2BXd0t9JdVqCp9sKf6kzMkr7QjB.jpg", genre_ids: [12, 10751, 16, 28, 35], id: 177572, original_language: "en", original_title: "Big Hero 6", overview: "The special bond that develops between plus-sized inflatable robot Baymax, and prodigy Hiro Hamada, who team up with a group of friends to form a band of high-tech heroes.", release_date: "2014-10-24", poster_path: "/9gLu47Zw5ertuFTZaxXOvNfy78T.jpg", popularity: 26.652226, title: "Big Hero 6", video: false, vote_average: 7.7, vote_count: 7976 } ], total_pages: 2973, total_results: 59455 }; export { topTVPicks, movie, horror, sciFi, comedy };
hexisyztem/lightseq
examples/inference/python/export/huggingface/hf_vit_export.py
""" Export Hugging Face ViT models to hdf5 format. """ import os import h5py from collections import OrderedDict from transformers import ViTModel from lightseq.training.ops.pytorch.export import fill_hdf5_layer os.environ["CUDA_VISIBLE_DEVICES"] = "-1" """ For the mapping dictionary: key is the value of the proto parameter, value is a powerful expression, each && split tensor name of the matching path or expression. The sub-pattern of the path is separated by spaces, and the expression starts with a expression_. You can operate separately on each tensor and support multiple expressions. Multiple matching paths and the expression will finally be concatenated on axis = -1. """ enc_layer_mapping_dict = OrderedDict( { # VIT is pre_layernorm # NOTE: add an additional "final" at the beginning for some weight # to distinguish them from "attention output *" "multihead_norm_scale": "layernorm_before weight", "multihead_norm_bias": "layernorm_before bias", "multihead_project_kernel_qkv": "attention attention query weight&&attention attention key weight&&attention attention value weight&&expression_.transpose(0, 1)", "multihead_project_bias_qkv": "attention attention query bias&&attention attention key bias&&attention attention value bias", "multihead_project_kernel_output": "attention output dense weight&&expression_.transpose(0, 1)", "multihead_project_bias_output": "attention output dense bias", "ffn_norm_scale": "layernorm_after weight", "ffn_norm_bias": "layernorm_after bias", "ffn_first_kernel": "intermediate dense weight&&expression_.transpose(0, 1)", "ffn_first_bias": "intermediate dense bias", "ffn_second_kernel": "final output dense weight&&expression_.transpose(0, 1)", "ffn_second_bias": "final output dense bias", } ) src_emb_mapping_dict = OrderedDict( { "conv_weight": "embeddings patch_embeddings projection weight", "conv_bias": "embeddings patch_embeddings projection bias", "position_embedding": "embeddings position_embeddings", "cls_embedding": "embeddings cls_token", "norm_scale": "layernorm weight", "norm_bias": "layernorm bias", } ) def extract_vit_weights( output_file, model_dir, head_num, image_size, patch_size, ): # load var names encoder_state_dict = ViTModel.from_pretrained(model_dir).state_dict() # Insert additional "final" to some weight to prevent ambiguous match def _insert_final(key): l = key.split(".") l.insert(3, "final") return ".".join(l) encoder_state_dict = OrderedDict( [ (_insert_final(k), v) if len(k.split(".")) > 3 and k.split(".")[3] == "output" else (k, v) for k, v in encoder_state_dict.items() ] ) enc_var_name_list = list(encoder_state_dict.keys()) # initialize output file output_file += ".hdf5" print("Saving model to hdf5...") print("Writing to {0}".format(output_file)) hdf5_file = h5py.File(output_file, "w") # fill each encoder layer's params enc_tensor_names = {} for name in enc_var_name_list: name_split = name.split(".") if len(name_split) <= 2 or not name_split[2].isdigit(): continue layer_id = int(name_split[2]) enc_tensor_names.setdefault(layer_id, []).append(name) # fill encoder_stack for layer_id in sorted(enc_tensor_names.keys()): fill_hdf5_layer( enc_tensor_names[layer_id], encoder_state_dict, hdf5_file, f"encoder_stack/{layer_id}/", enc_layer_mapping_dict, ) # fill src_embedding - except for position embedding fill_hdf5_layer( enc_var_name_list, encoder_state_dict, hdf5_file, "src_embedding/", src_emb_mapping_dict, ) # save number of layers metadata hdf5_file.create_dataset( "model_conf/n_encoder_stack", data=len(enc_tensor_names), dtype="i4" ) # fill in model_conf hdf5_file.create_dataset("model_conf/head_num", data=head_num, dtype="i4") hdf5_file.create_dataset("model_conf/use_gelu", data=True, dtype="?") hdf5_file.create_dataset("model_conf/is_post_ln", data=False, dtype="?") hdf5_file.create_dataset("model_conf/image_size", data=image_size, dtype="i4") hdf5_file.create_dataset("model_conf/patch_size", data=patch_size, dtype="i4") hdf5_file.close() # read-in again to double check hdf5_file = h5py.File(output_file, "r") def _print_pair(key, value): value = value[()] print(f"{key}: {value}") list(map(lambda x: _print_pair(*x), hdf5_file["model_conf"].items())) if __name__ == "__main__": output_lightseq_model_name = "lightseq_vit" input_huggingface_vit_model = "google/vit-base-patch16-224-in21k" head_number = 12 image_size = 224 patch_size = 16 extract_vit_weights( output_lightseq_model_name, input_huggingface_vit_model, head_number, image_size, patch_size, )
773c/qlemusic
qlemusic-security/src/main/java/com/cjj/qlemusic/security/service/OssService.java
<gh_stars>1-10 package com.cjj.qlemusic.security.service; import com.cjj.qlemusic.security.entity.OssCallback; import com.cjj.qlemusic.security.entity.OssPolicy; import javax.servlet.http.HttpServletRequest; import java.io.InputStream; /** * OSS上传管理Service */ public interface OssService { /** * 生成OSS上传策略 */ OssPolicy policy(); /** * 上传成功回调 */ OssCallback callback(HttpServletRequest request); /** * 将文件上传到OSS * @param filename * @param inputStream */ String uploadOss(String filename, InputStream inputStream); /** * 获取OSS上传路径 * @param filename * @return */ String getOssFileApiPath(String filename); }
privacore/open-source-search-engine
test/unit/ScalingFunctionsTest.cpp
<reponame>privacore/open-source-search-engine<gh_stars>100-1000 #include <gtest/gtest.h> #include "ScalingFunctions.h" TEST(ScalingFunctionTest, ScaleLinear) { EXPECT_EQ( 0, scale_linear( 0, 0.0,10.0, 0.0,100.0)); EXPECT_EQ(100, scale_linear( 10, 0.0,10.0, 0.0,100.0)); EXPECT_EQ( 50, scale_linear( 5, 0.0,10.0, 0.0,100.0)); EXPECT_EQ( 0, scale_linear( -4, 0.0,10.0, 0.0,100.0)); EXPECT_EQ(100, scale_linear( 15, 0.0,10.0, 0.0,100.0)); } TEST(ScalingFunctionTest, ScaleQuadratic) { EXPECT_EQ( 0, scale_quadratic( 0, 0.0,10.0, 0.0,100.0)); EXPECT_EQ(100, scale_quadratic( 10, 0.0,10.0, 0.0,100.0)); EXPECT_EQ( 1, scale_quadratic( 1.0, 1.0,2.0, 1.0,4.0)); EXPECT_EQ( 4, scale_quadratic( 2.0, 1.0,2.0, 1.0,4.0)); EXPECT_TRUE(scale_quadratic( 1.1, 1.0,2.0, 1.0,4.0) < 1.5); EXPECT_TRUE(scale_quadratic( 1.5, 1.0,2.0, 1.0,4.0) < 2.5); EXPECT_TRUE(scale_quadratic( 1.9, 1.0,2.0, 1.0,4.0) > 3); }
onmyway133/Runtime-Headers
macOS/10.12/CoreData.framework/NSSQLProperty.h
<filename>macOS/10.12/CoreData.framework/NSSQLProperty.h /* Generated by RuntimeBrowser Image: /System/Library/Frameworks/CoreData.framework/Versions/A/CoreData */ @interface NSSQLProperty : NSStoreMapping { NSSQLEntity * _entity; NSString * _name; NSPropertyDescription * _propertyDescription; unsigned int _propertyType; } - (void)_setName:(id)arg1; - (id)columnName; - (void)copyValuesForReadOnlyFetch:(id)arg1; - (void)dealloc; - (id)description; - (id)entity; - (id)externalName; - (id)initWithEntity:(id)arg1 propertyDescription:(id)arg2; - (BOOL)isAttribute; - (BOOL)isColumn; - (BOOL)isEntityKey; - (BOOL)isEqual:(id)arg1; - (BOOL)isForeignEntityKey; - (BOOL)isForeignKey; - (BOOL)isForeignOrderKey; - (BOOL)isManyToMany; - (BOOL)isOptLockKey; - (BOOL)isPrimaryKey; - (BOOL)isRelationship; - (BOOL)isToMany; - (BOOL)isToOne; - (id)name; - (id)propertyDescription; - (unsigned int)propertyType; - (void)setEntityForReadOnlyFetch:(id)arg1; - (void)setPropertyDescription:(id)arg1; - (unsigned int)slot; @end
vashman/range_layer
include/bits/range/decor/range/string.hpp
<filename>include/bits/range/decor/range/string.hpp // // Copyright <NAME> 2015 - 2017. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef RANGE_LAYER_BITS_RANGE_STRING_HPP #define RANGE_LAYER_BITS_RANGE_STRING_HPP #include <string> #include "range.hpp" namespace range_layer { /*=========================================================== string range ===========================================================*/ template <typename T, typename Traits, typename Alloc> class range <std::basic_string<T, Traits, Alloc> * const> : public range <const std::basic_string<T, Traits, Alloc> * const> { using string_t = std::basic_string<T, Traits, Alloc>; public: using write_type = T; explicit range (string_t * const); range (range const &) = delete; range (range &&) = default; range & operator = (range const &) = delete; range & operator = (range &&) = default; void write (T const & _var){(*this->handle)[this->pos-1] = _var;} void expand (std::size_t _n){this->handle->resize(this->handle->size()+_n);} void shrink (std::size_t _n){this->handle->resize(this->handle->size()-_n);} void insert (T const & _var){this->handle->insert(this->position(), _var);} void erase (){this->handle->erase(this->position(), 1);} void erase_all (){this->handle->clear();} private: string_t * const handle; }; //--------------------------------------------string range /*=========================================================== const string range ===========================================================*/ template <typename T, typename Traits, typename Alloc> class range <const std::basic_string<T, Traits, Alloc> * const> { using string_t = std::basic_string<T, Traits, Alloc>; public: explicit range (const string_t * const); std::size_t size () const{return this->const_handle->size();} std::size_t position () const{return this->pos;} const T & read () const {return (*this->const_handle)[this->pos-1];} void advance(){++this->pos;} void reverse(){--this->pos;} void advance_n (std::size_t const _n){this->pos += _n;} void reverse_n (std::size_t const _n){this->pos -= _n;} bool has_readable () const {return this->pos <= this->const_handle->size();} bool has_writable () const {return this->has_readable();} protected: const string_t * const const_handle; std::size_t pos; }; //--------------------------------------const string range } //----------------------------------------------range layer #endif #include "string.tcc"
saltzm/yadi
yadi/interpreter/interpreter_parse.py
__author__ = 'Manuel' from pyparsing import * class InterpreterException(Exception): pass class IntParse: def parse_command(self, cmd_str): assert_dl = Literal("/assert ") + Word(printables) loadfile = Literal("/script ") + dblQuotedString + StringEnd() quit = Literal("/quit") + StringEnd() help = Literal("/help") + StringEnd() clrscr = Literal("/clrscr") + StringEnd() dbs = Literal("/dbschema") + StringEnd() setdb = Literal("/setdb") + StringEnd() curdb = Literal("/curdb") + StringEnd() drop = Literal("/dropview") + Word(printables) drop_t = Literal("/droptable") + Word(printables) rule = (assert_dl | loadfile | help | quit | clrscr | dbs | setdb | curdb | drop | drop_t).setFailAction(self.syntax) expression = rule.parseString(cmd_str) return expression def syntax(self, s, loc, expr, err): x = "Command {0!r} does not exist.".format(s) raise InterpreterException(x)
Interel-Group/core3
src/main/scala/core3/database/containers/JsonContainerDefinition.scala
package core3.database.containers import play.api.libs.json.JsValue /** * Definition trait for containers supporting JSON data handling. */ trait JsonContainerDefinition extends ContainerDefinition { /** * Converts the supplied container to a JSON value. * * @param container the container to be converted * @return the container as a JSON value */ def toJsonData(container: Container): JsValue /** * Converts the supplied JSON value to a container. * * @param data the JSON value to be converted * @return the converted container */ def fromJsonData(data: JsValue): Container }
ruebel/dropbox-demo-tape-web
src/components/Button.js
<filename>src/components/Button.js import styled from "styled-components"; export default styled.button` background-color: ${p => p.theme.color.background}; border-radius: 10px; border: 1px solid ${p => p.theme.color.white}; color: ${p => p.theme.color.white}; cursor: pointer; display: flex; font-size: 14px; justify-content: center; outline: none; padding: 10px 20px; text-transform: uppercase; transition: ${p => p.theme.transition}; :hover, :focus { background-color: ${p => p.theme.color.white}; color: ${p => p.theme.color.background}; } ${p => p.disabled ? ` color: ${p.theme.color.disabled}; cursor: unset; border-color: ${p.theme.color.disabled}; :hover, :focus { background-color: ${p.theme.color.background}; color: ${p.theme.color.disabled}; } ` : ""} `;
Max-Qiu/demo
demo-Elasticsearch/src/main/java/com/maxqiu/demo/document/multi/ReindexApi.java
<filename>demo-Elasticsearch/src/main/java/com/maxqiu/demo/document/multi/ReindexApi.java package com.maxqiu.demo.document.multi; import java.io.IOException; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.reindex.BulkByScrollResponse; import org.elasticsearch.index.reindex.ReindexRequest; import com.maxqiu.demo.common.ClientUtils; /** * * 重建索引(用于索引拷贝,多索引合并) * * @author Max_Qiu */ public class ReindexApi { private static final RestHighLevelClient CLIENT; static { // 获取客户端 CLIENT = ClientUtils.create(); } public static void main(String[] args) { try { reindexRequest(); } catch (IOException e) { e.printStackTrace(); } // 关闭客户端 try { CLIENT.close(); } catch (IOException e) { e.printStackTrace(); } } private static void reindexRequest() throws IOException { // 创建一个 ReindexRequest 请求 ReindexRequest request = new ReindexRequest(); // 添加要复制的来源列表 request.setSourceIndices("source1", "source2"); // 添加目标索引 request.setDestIndex("dest"); // 执行 BulkByScrollResponse bulkResponse = CLIENT.reindex(request, RequestOptions.DEFAULT); } }
cuappdev/archives
register-client-ios/SwiftRegister.podspec
#!/usr/bin/ruby Pod::Spec.new do |s| s.name = 'SwiftRegister' s.version = '0.0.4' s.summary = 'register client library for iOS' s.description = <<-DESC register client library for iOS DESC s.homepage = 'https://github.com/cuappdev/register-client-ios' s.license = 'MIT' s.author = { '<NAME>' => '<EMAIL>' } s.source = { :git => 'https://github.com/cuappdev/register-client-ios.git', :tag => 'v'+s.version.to_s } s.ios.deployment_target = '10.0' s.source_files = 'SwiftRegister/Classes/**/*' s.dependency 'PromiseKit', '~> 4.4' s.dependency 'PromiseKit/Alamofire', '~> 4.0' s.dependency 'SwiftyJSON', '~> 4.0.0' s.dependency 'RealmSwift', '~> 3.0.2' s.dependency 'Log', '1.0' end
MistressAlison/M10RobotMod
TheM10Robot/src/main/java/M10Robot/cutStuff/relics/ModularBody.java
//package M10Robot.cutStuff.relics; // //import M10Robot.M10RobotMod; //import M10Robot.cutStuff.powers.ModulesPower; //import M10Robot.util.TextureLoader; //import basemod.abstracts.CustomRelic; //import com.badlogic.gdx.graphics.Texture; //import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; //import com.megacrit.cardcrawl.actions.common.RelicAboveCreatureAction; //import com.megacrit.cardcrawl.dungeons.AbstractDungeon; // //import static M10Robot.M10RobotMod.makeRelicOutlinePath; //import static M10Robot.M10RobotMod.makeRelicPath; // //public class ModularBody extends CustomRelic /*implements CustomSavable<Integer>, ClickableRelic*/ { // // // ID, images, text. // public static final String ID = M10RobotMod.makeID("ModularBody"); // // private static final Texture IMG = TextureLoader.getTexture(makeRelicPath("ArmorModule.png")); // private static final Texture OUTLINE = TextureLoader.getTexture(makeRelicOutlinePath("ArmorModule.png")); // // public static final int AMOUNT = 4; // // public ModularBody() { // super(ID, IMG, OUTLINE, RelicTier.STARTER, LandingSound.CLINK); // } // // // Description // @Override // public String getUpdatedDescription() { // return DESCRIPTIONS[0] + AMOUNT + DESCRIPTIONS[1]; // } // // @Override // public void atBattleStart() { // flash(); // this.addToTop(new RelicAboveCreatureAction(AbstractDungeon.player, this)); // this.addToTop(new ApplyPowerAction(AbstractDungeon.player, AbstractDungeon.player, new ModulesPower(AbstractDungeon.player, AMOUNT))); // } //}
defstream/nl3
lib/rules-engine/parse/rules.js
<filename>lib/rules-engine/parse/rules.js /*jslint node: true */ /*global module, require*/ 'use strict'; var parseSubjects = require('./subjects'); var parsePredicates = require('./reduce-predicates'); var parseObjects = require('./objects'); var singularize = require('../../text/singularize'); /** * parses the grammar rules from a string array. * @param {Object} ruleset The ruleset to apply the parsed grammar rules to. * @param {Array} data An array of strings representing the grammar rules. * @return {Object} The parsed grammar rules. */ module.exports = function rules(ruleset, data) { data = data.toString().split(' '); var subject = singularize(data[0]); var predicate = singularize(data[1]); var object = singularize(data[2]); ruleset = parseSubjects(ruleset, subject, predicate, object); ruleset = parsePredicates(ruleset, predicate); ruleset = parseObjects(ruleset, subject, predicate, object); return ruleset; };
zhangpf/fuchsia-rs
garnet/public/lib/fsl/vmo/strings.h
<gh_stars>1-10 // Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LIB_FSL_VMO_STRINGS_H_ #define LIB_FSL_VMO_STRINGS_H_ #include <string> #include <fuchsia/mem/cpp/fidl.h> #include <lib/zx/vmo.h> #include "lib/fsl/vmo/sized_vmo.h" #include "src/lib/fxl/fxl_export.h" #include "src/lib/fxl/strings/string_view.h" namespace fsl { // Make a new shared buffer with the contents of a string. FXL_EXPORT bool VmoFromString(const fxl::StringView& string, SizedVmo* handle_ptr); // Make a new shared buffer with the contents of a string. FXL_EXPORT bool VmoFromString(const fxl::StringView& string, fuchsia::mem::Buffer* buffer_ptr); // Copy the contents of a shared buffer into a string. FXL_EXPORT bool StringFromVmo(const SizedVmo& handle, std::string* string_ptr); // Copy the contents of a shared buffer into a string. FXL_EXPORT bool StringFromVmo(const fuchsia::mem::Buffer& handle, std::string* string_ptr); // Copy the contents of a shared buffer upto |num_bytes| into a string. // |num_bytes| should be <= |handle.size|. FXL_EXPORT bool StringFromVmo(const fuchsia::mem::Buffer& handle, size_t num_bytes, std::string* string_ptr); } // namespace fsl #endif // LIB_FSL_VMO_STRINGS_H_
Bobfrat/ooi-ui-services
ooiservices/app/m2m/routes.py
#!/usr/bin/env python ''' uframe endpoints ''' # base from flask import jsonify, request, current_app from ooiservices.app.m2m import m2m as api from ooiservices.app.main.authentication import auth from ooiservices.app.main.errors import internal_server_error # data imports from ooiservices.app.uframe.data import get_data import requests import urllib2 requests.adapters.DEFAULT_RETRIES = 2 CACHE_TIMEOUT = 86400 @api.route('/get_metadata/<string:ref>', methods=['GET']) <EMAIL>(timeout=3600) def get_metadata(ref): ''' Returns the uFrame metadata response for a given stream ''' try: mooring, platform, instrument = ref.split('-', 2) uframe_url, timeout, timeout_read = get_uframe_info() url = "/".join([uframe_url, mooring, platform, instrument, 'metadata']) response = requests.get(url, timeout=(timeout, timeout_read)) if response.status_code == 200: data = response.json() return jsonify(data) return jsonify(metadata={}), 404 except Exception as e: return internal_server_error('uframe connection cannot be made.' + str(e.message)) def get_uframe_info(): ''' returns uframe configuration information. (uframe_url, uframe timeout_connect and timeout_read.) ''' uframe_url = current_app.config['UFRAME_URL'] + current_app.config['UFRAME_URL_BASE'] timeout = current_app.config['UFRAME_TIMEOUT_CONNECT'] timeout_read = current_app.config['UFRAME_TIMEOUT_READ'] return uframe_url, timeout, timeout_read @auth.login_required @api.route('/get_data/<string:ref>/<string:method>/<string:stream>/<string:start_time>/<string:end_time>', methods=['GET']) def get_data(ref, method, stream, start_time, end_time): mooring, platform, instrument = ref.split('-', 2) method = method.replace('-','_') uframe_url, timeout, timeout_read = get_uframe_info() user = request.args.get('user', '') email = request.args.get('email', '') prov = request.args.get('provenance','false') pids = request.args.get('pid','') data_format = 'application/'+request.args.get('format', '') possible_data_format = ['application/netcdf','application/json','application/csv','application/tsv'] if data_format not in possible_data_format: data_format = 'applciation/netcdf' limit = request.args.get('limit', 'NONE') if limit is 'NONE': query = '?beginDT=%s&endDT=%s&include_provenance=%s&include_annotations=true&user=%s&email=%s&format=%s&pid=%s' % (start_time, end_time, prov, user, email, data_format, pids) else: if int(limit) > 1001 or int(limit) <1: limit = 1000 query = '?beginDT=%s&endDT=%s&include_provenance=%s&include_annotations=true&user=%s&email=%s&format=%s&limit=%s&pid=%s' % (start_time, end_time, prov, user, email, data_format,limit,pids) uframe_url, timeout, timeout_read = get_uframe_info() url = "/".join([uframe_url, mooring, platform, instrument, method, stream + query]) current_app.logger.debug('***** url: ' + url) response = requests.get(url, timeout=(timeout, timeout_read)) try: GA_URL = current_app.config['GOOGLE_ANALYTICS_URL']+'&ec=m2m&ea=%s&el=%s' % ('-'.join([mooring, platform, instrument, stream]), '-'.join([start_time, end_time])) urllib2.urlopen(GA_URL) except KeyError: pass return response.text, response.status_code
lovelife-li/javaDemo
worktest/src/main/java/com/study/javanewspecial/java8/demo02/reduce/ReduceTest.java
<filename>worktest/src/main/java/com/study/javanewspecial/java8/demo02/reduce/ReduceTest.java package com.study.javanewspecial.java8.demo02.reduce; import com.study.utils.web.User; import org.junit.Test; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * todo * * @author ldb * @date 2020/06/05 */ public class ReduceTest { public static void main(String[] args) { Cat cat1 = new Cat(1, "xiaoxiao"); Cat cat2 = new Cat(2, "huahau"); Cat cat3 = new Cat(3, "baibai"); List<Cat> cats = Arrays.asList(cat1, cat2, cat3); Cat res = cats.stream().reduce(new Cat(1,"boss"),(x, y) -> { x.setAge(x.getAge() + y.getAge()); return x; }); System.out.println(res); System.out.println(cats); System.out.println(UUID.randomUUID().toString()); } @Test public void test01(){ ArrayList<User> users = new ArrayList<>(); Long id = users.stream().map(User::getId).min(Long::compareTo).orElse(0L); System.out.println(id); Set<Integer> sets = IntStream.of(16, 32, 64, 256).boxed().collect(Collectors.toSet()); Integer a1 = new Integer(16); Integer a2 = new Integer(32); Integer a3 = new Integer(64); Integer a4 = new Integer(256); System.out.println(sets.contains(a1)); System.out.println(sets.contains(a2)); System.out.println(sets.contains(a3)); System.out.println(sets.contains(a4)); } }
fogmeng/lion
lion-client/src/main/java/com/gupao/edu/vip/lion/client/push/PushClientFactory.java
<reponame>fogmeng/lion package com.gupao.edu.vip.lion.client.push; import com.gupao.edu.vip.lion.api.push.PushSender; import com.gupao.edu.vip.lion.api.spi.Spi; import com.gupao.edu.vip.lion.api.spi.client.PusherFactory; /** * Created by yxx on 2016/5/18. * * @author <EMAIL> */ @Spi public class PushClientFactory implements PusherFactory { private volatile PushClient client; @Override public PushSender get() { if (client == null) { synchronized (PushClientFactory.class) { if (client == null) { client = new PushClient(); } } } return client; } }
FeiyangJin/hclib
test/performance-regression/full-apps/qmcpack/src/Message/BoostMpiAdaptor.h
#ifndef QMCPLUSPLUS_COLLECTIVE_OPERATIONS_H #define QMCPLUSPLUS_COLLECTIVE_OPERATIONS_H /** allreduce of single **/ #define QMCPP_ALLREDUCE(CppType, MPIType) \ template<> inline void \ Communicate::allreduce(CppType& g) \ { \ CppType gt(g); \ MPI_Allreduce(&(gt), &(g), 1, MPIType, MPI_SUM, myMPI);\ } QMCPP_ALLREDUCE(double,MPI_DOUBLE); QMCPP_ALLREDUCE(int,MPI_INT); /** allreduce of container **/ #define QMCPP_ALLREDUCE_C(Container,MPIType) \ template<> inline void \ Communicate::allreduce(Container& g) \ { \ Container gt(g) \ MPI_Allreduce(&(g[0]), &(gt[0]), g.size(), MPIType, MPI_SUM, myMPI);\ g=gt; \ } QMCPP_ALLREDUCE_C(vector<double>,MPI_DOUBLE); QMCPP_ALLREDUCE_C(vector<int>,MPI_INT); QMCPP_ALLREDUCE_C(qmcplusplus::Matrix<double>,MPI_DOUBLE); /** gather operations **/ #define QMCPP_GATHER(CONTAINER,CppType, MPIType) \ template<> \ inline void \ Communicate::gather(CONTAINER< CppType >&sb, CONTAINER< CppType >& rb, int dest) \ { \ MPI_Gather(&(sb[0]),sb.size(),MPI_UNSIGNED, &(rb[0]),sb.size(),MPIType,dest,myMPI);\ } QMCPP_GATHER(vector,uint32_t,MPI_UNSIGNED); QMCPP_GATHER(vector,double,MPI_DOUBLE); QMCPP_GATHER(vector,int,MPI_INT); /** scatter operations **/ #define QMCPP_SCATTER(CONTAINER,CppType, MPIType) \ template<> \ inline void \ Communicate::gather(CONTAINER< CppType >&sb, CONTAINER< CppType >& rb, int dest) \ { \ MPI_Scatter(&(sb[0]),sb.size(),MPI_UNSIGNED, &(rb[0]),sb.size(),MPIType,dest,myMPI);\ } QMCPP_SCATTER(vector,uint32_t,MPI_UNSIGNED); #endif /*************************************************************************** * $RCSfile$ $Author: jnkim $ * $Revision: 2458 $ $Date: 2008-02-20 10:45:51 -0500 (Wed, 20 Feb 2008) $ * $Id: CommOperators.h 2458 2008-02-20 15:45:51Z jnkim $ ***************************************************************************/
negativetwelve/react-x
modules/keychain/src/Keychain.js
// Libraries import invariant from 'invariant'; import omit from 'lodash.omit'; // Modules import KeychainX from './KeychainX'; /** * Persistent secure storage for all apps. */ class Keychain { // -------------------------------------------------- // Initialize // -------------------------------------------------- constructor({namespace, domain, expires, path = '/', secure = false}) { this.initialized = false; this.all = {}; this.options = {domain, expires, path, secure}; this.keychain = new KeychainX({namespace}); } async initialize(keys) { this.all = await this.getEntries(keys); this.initialized = true; } // -------------------------------------------------- // Public // -------------------------------------------------- get(key) { this.assertInitialized('get'); return this.all[key]; } async set(key, value) { this.assertInitialized('set'); return this.setEntries({[key]: value}); } async reset() { this.assertInitialized('reset'); return this.clearKeys(Object.keys(this.all)); } // -------------------------------------------------- // Private // -------------------------------------------------- assertInitialized(method) { invariant(this.initialized, 'Keychain calling method before it has been initialized.'); } async setEntries(entries = {}) { this.assertInitialized('setEntries'); this.all = {...this.all, ...entries}; return this.save(this.all); } // -------------------------------------------------- // KeychainX // -------------------------------------------------- async getEntries(keys = []) { return this.keychain.getEntries(keys); } async save(all = {}) { return this.keychain.save(all, this.options); } async clearKeys(keys = []) { // Modify the cache before clearing the actual keychain. this.all = omit(this.all, keys); return this.keychain.clearKeys(keys, this.all, this.options); } } export default Keychain;
team-miracle/android-libs
org.apache.http.legacy_intermediates/src/org/apache/http/impl/client/EntityEnclosingRequestWrapper.java
<gh_stars>1-10 /* * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/impl/client/EntityEnclosingRequestWrapper.java $ * $Revision: 674186 $ * $Date: 2008-07-05 05:18:54 -0700 (Sat, 05 Jul 2008) $ * * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.impl.client; @java.lang.Deprecated() public class EntityEnclosingRequestWrapper extends org.apache.http.impl.client.RequestWrapper implements org.apache.http.HttpEntityEnclosingRequest { public EntityEnclosingRequestWrapper(org.apache.http.HttpEntityEnclosingRequest request) throws org.apache.http.ProtocolException { super((org.apache.http.HttpRequest)null); throw new RuntimeException("Stub!"); } public org.apache.http.HttpEntity getEntity() { throw new RuntimeException("Stub!"); } public void setEntity(org.apache.http.HttpEntity entity) { throw new RuntimeException("Stub!"); } public boolean expectContinue() { throw new RuntimeException("Stub!"); } public boolean isRepeatable() { throw new RuntimeException("Stub!"); } }
yiwork/Singularity
SingularityBase/src/main/java/com/hubspot/deploy/RemoteArtifact.java
package com.hubspot.deploy; import java.util.Objects; import java.util.Optional; import com.fasterxml.jackson.annotation.JsonIgnore; import io.swagger.v3.oas.annotations.media.Schema; @Schema( description = "A remote artifact to be downloaded", subTypes = { ExternalArtifact.class, S3Artifact.class } ) public abstract class RemoteArtifact extends Artifact { private final Optional<Long> filesize; private final Optional<Boolean> isArtifactList; public RemoteArtifact(String name, String filename, Optional<String> md5sum, Optional<Long> filesize, Optional<String> targetFolderRelativeToTask, Optional<Boolean> isArtifactList) { super(name, filename, md5sum, targetFolderRelativeToTask); this.filesize = filesize; this.isArtifactList = isArtifactList; } @Schema(description = "Size of the artifact") public Optional<Long> getFilesize() { return filesize; } @Schema( description = "If true, this file is a list of other `Artifact`s to download, represented as json", nullable = true, defaultValue = "false" ) public Optional<Boolean> getIsArtifactList() { return isArtifactList; } @JsonIgnore public boolean isArtifactList() { return isArtifactList.orElse(Boolean.FALSE).booleanValue(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } RemoteArtifact that = (RemoteArtifact) o; return Objects.equals(filesize, that.filesize) && Objects.equals(isArtifactList, that.isArtifactList); } @Override public int hashCode() { return Objects.hash(super.hashCode(), filesize, isArtifactList); } @Override public String toString() { return "RemoteArtifact{" + "filesize=" + filesize + "isArtifactList" + isArtifactList + "} " + super.toString(); } }
jordynmackool/sdl_java_suite
base/src/main/java/com/smartdevicelink/proxy/rpc/GetDTCs.java
<reponame>jordynmackool/sdl_java_suite<gh_stars>100-1000 /* * Copyright (c) 2017 - 2019, SmartDeviceLink Consortium, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the SmartDeviceLink Consortium, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.smartdevicelink.proxy.rpc; import androidx.annotation.NonNull; import com.smartdevicelink.protocol.enums.FunctionID; import com.smartdevicelink.proxy.RPCRequest; import java.util.Hashtable; /** * This RPC allows to request diagnostic module trouble codes from a certain * vehicle module. * * <p> Function Group: ProprietaryData</p> * * <p> <b>HMILevel needs to be FULL, LIMITED or BACKGROUND</b></p> * * <p><b>Parameter List</b></p> * <table border="1" rules="all"> * <tr> * <th>Name</th> * <th>Type</th> * <th>Description</th> * <th>Reg.</th> * <th>Notes</th> * <th>Version</th> * </tr> * <tr> * <td>ecuName</td> * <td>Integer</td> * <td>Name of ECU.</td> * <td>Y</td> * <td>Min Value: 0; Max Value: 65535</td> * <td>SmartDeviceLink 2.0 </td> * </tr> * <tr> * <td>dtcMask</td> * <td>Integer</td> * <td>DTC Mask Byte to be sent in diagnostic request to module.</td> * <td>N</td> * <td>Min Value: 0; Max Value: 255</td> * <td>SmartDeviceLink 2.0 </td> * </tr> * </table> * <p><b>Response</b></p> * * <p><b>Non-default Result Codes:</b></p> * <p> SUCCESS</p> * <p>INVALID_DATA</p> * <p> OUT_OF_MEMORY</p> * <p>TOO_MANY_PENDING_REQUESTS</p> * <p>APPLICATION_NOT_REGISTERED</p> * <p>GENERIC_ERROR</p> * <p>REJECTED</p> * <p>DISALLOWED </p> * <p>USER_DISALLOWED</p> * * @since SmartDeviceLink 2.0 */ public class GetDTCs extends RPCRequest { public static final String KEY_DTC_MASK = "dtcMask"; public static final String KEY_ECU_NAME = "ecuName"; /** * Constructs a new GetDTCs object */ public GetDTCs() { super(FunctionID.GET_DTCS.toString()); } /** * <p>Constructs a new GetDTCs object indicated by the Hashtable parameter * </p> * * @param hash The Hashtable to use */ public GetDTCs(Hashtable<String, Object> hash) { super(hash); } /** * Constructs a new GetDTCs object * * @param ecuName an Integer value representing a name of the module to receive the DTC form <br> * <b>Notes: </b>Minvalue:0; Maxvalue:65535 */ public GetDTCs(@NonNull Integer ecuName) { this(); setEcuName(ecuName); } /** * Sets a name of the module to receive the DTC form * * @param ecuName an Integer value representing a name of the module to receive * the DTC form * <p> * <b>Notes:</p> </b>Minvalue:0; Maxvalue:65535 */ public GetDTCs setEcuName(@NonNull Integer ecuName) { setParameters(KEY_ECU_NAME, ecuName); return this; } /** * Gets a name of the module to receive the DTC form * * @return Integer -an Integer value representing a name of the module to * receive the DTC form */ public Integer getEcuName() { return getInteger(KEY_ECU_NAME); } public GetDTCs setDtcMask(Integer dtcMask) { setParameters(KEY_DTC_MASK, dtcMask); return this; } public Integer getDtcMask() { return getInteger(KEY_DTC_MASK); } }
FreddyChen/KulaChat
app/src/main/java/com/freddy/kulachat/presenter/NullablePresenter.java
package com.freddy.kulachat.presenter; import javax.inject.Inject; /** * @author FreddyChen * @name * @date 2020/05/23 21:01 * @email <EMAIL> * @github https://github.com/FreddyChen * @desc */ public class NullablePresenter extends BasePresenter { @Inject public NullablePresenter() { } }
benilovj/slack-incident-bot
spec/bot/actions/slack_incident_actions_spec.rb
<reponame>benilovj/slack-incident-bot<filename>spec/bot/actions/slack_incident_actions_spec.rb require 'rails_helper' describe 'actions/slack_incident_actions' do let(:client) { Slack::Web::Client.new(token: ENV['SLACK_TOKEN']) } let(:incident_payload) do { 'payload' => { 'view' => { 'state' => { 'values' => { 'incident_title_block' => { 'incident_title' => { 'type' => 'plain_text_input', 'value' => 'hello' } }, 'incident_description_block' => { 'incident_description' => { 'type' => 'plain_text_input', 'value' => 'hello' } }, 'service_selection_block' => { 'service_selection' => { 'type' => 'static_select', 'selected_option' => { 'text' => { 'type' => 'plain_text', 'text' => 'Apply', 'emoji' => true }, 'value' => 'value-0' } } }, 'incident_priority_block' => { 'incident_priority' => { 'type' => 'static_select', 'selected_option' => { 'text' => { 'type' => 'plain_text', 'text' => 'P1 (High) - 60-100% of users affected', 'emoji' => true }, 'value' => 'value-0' } } }, 'incident_comms_lead_block' => { 'comms_lead_select_action' => { 'type' => 'users_select', 'selected_user' => 'U01RVKPGZDL' } }, 'incident_tech_lead_block' => { 'tech_lead_select_action' => { 'type' => 'users_select', 'selected_user' => 'U01RVKPGZDL' } }, 'incident_support_lead_block' => { 'support_lead_select_action' => { 'type' => 'users_select', 'selected_user' => 'U01RVKPGZDL' } } } }, 'app_id' => 'A021D8M1RT9' } }, }.with_indifferent_access end let(:update_payload) do { 'payload' => { view: { state: { values: { incident_support_lead_block: { support_lead_select_action: { type: 'users_select', selected_user: 'U027SPH3TKP', }, }, }, }, } }, }.with_indifferent_access end let(:channel_id) { { ok: true, channel: { id: 'C018Y6VH39D' } } } let(:timestamp) { { ok: true, ts: '1625836853.000800' } } let(:conversation_info) { { ok: true, channel: { topic: { value: 'Description: Test\n Priority: P2 (Medium) - 20-59% of users affected\n Comms lead: <@U01RVKPGZDL>\n Tech lead: <@U01RVKPGZDL>\n Support lead: <@U01RVKPGZDL>' } } } } let(:current_members) { { 'ok' => true, 'members' => %w[U01RVKPGZDL U0224J2AHJP U01RVKPGZDL] } } let(:members_invite) { { 'ok' => true, 'channel' => { 'topic' => { 'value' => "Description: Again\n Priority: P2 (Medium) - 20-59% of users affected\n Comms lead: <@U01RVKPGZDL>\n Tech lead: <@U01RVKPGZDL>\n Support lead: <@U027SPH3TKP>" } } } } it 'performs the incident actions' do conversation_stub = stub_request(:post, 'https://slack.com/api/conversations.create').to_return(status: 200, body: channel_id.to_json, headers: { 'Content-Type' => 'application/json' }) invite_stub = stub_request(:post, 'https://slack.com/api/conversations.invite').to_return(status: 200, body: '', headers: {}) topic_stub = stub_request(:post, 'https://slack.com/api/conversations.setTopic').to_return(status: 200, body: '', headers: {}) message_stub = stub_request(:post, 'https://slack.com/api/chat.postMessage').to_return(status: 200, body: timestamp.to_json, headers: { 'Content-Type' => 'application/json' }) pin_stub = stub_request(:post, 'https://slack.com/api/pins.add').to_return(status: 200, body: '', headers: {}) SlackIncidentActions.new.open_incident(incident_payload, channel_id) expect(conversation_stub).to have_been_requested expect(invite_stub).to have_been_requested expect(topic_stub).to have_been_requested expect(message_stub).to have_been_requested.times(4) expect(pin_stub).to have_been_requested.times(2) end it 'performs the update action' do conversation_info_stub = stub_request(:post, 'https://slack.com/api/conversations.info').to_return( status: 200, body: conversation_info.to_json, headers: { 'Content-Type' => 'application/json' }, ) conversation_members_stub = stub_request(:post, 'https://slack.com/api/conversations.members').to_return( status: 200, body: current_members.to_json, headers: { 'Content-Type' => 'application/json' }, ) conversation_topic_stub = stub_request(:post, 'https://slack.com/api/conversations.setTopic').to_return( status: 200, body: '', headers: {}, ) post_message_stub = stub_request(:post, 'https://slack.com/api/chat.postMessage').to_return( status: 200, body: timestamp.to_json, headers: { 'Content-Type' => 'application/json' }, ) conversation_invite_stub = stub_request(:post, 'https://slack.com/api/conversations.invite').to_return( status: 200, body: members_invite.to_json, headers: { 'Content-Type' => 'application/json' }, ) SlackIncidentActions.new.update_incident(update_payload, channel_id) expect(conversation_info_stub).to have_been_requested expect(conversation_members_stub).to have_been_requested expect(conversation_topic_stub).to have_been_requested expect(post_message_stub).to have_been_requested expect(conversation_invite_stub).to have_been_requested end it 'sets a topic', vcr: { cassette_name: 'web/conversations_setTopic' } do rc = client.conversations_setTopic({ channel: 'C027ZFNML6Q', topic: 'New topic' }) expect(rc.channel.topic.value).to eq 'New topic' end it 'posts advice', vcr: { cassette_name: 'web/chat_postMessage_advice' } do rc = client.chat_postMessage(channel: 'C027ZFNML6Q', text: "Welcome to the incident channel. Please review the following docs:\n> <#{ENV['INCIDENT_PLAYBOOK']}|Incident playbook> \n><#{ENV['INCIDENT_CATEGORIES']}|Incident categorisation>") expect(rc.message.text).to include 'Welcome to the incident channel.' end it 'pins a message', vcr: { cassette_name: 'web/pins_add' } do rc = client.pins_add({ channel: 'C027ZFNML6Q', timestamp: '1626109416.000300' }) expect(rc.ok).to eq true end it 'invites the incident leads', vcr: { cassette_name: 'web/conversations_invite' } do rc = client.conversations_invite({ channel: 'C027ZFNML6Q', users: 'U01RVKPGZDL,U01RVKPGZDL,U01RVKPGZDL' }) expect(rc.ok).to eq true end it 'posts an alert', vcr: { cassette_name: 'web/chat_postMessage' } do rc = client.chat_postMessage({ channel: 'C01RZAVQ6QM', text: 'test' }) expect(rc.message.text).to include ':rotating_light: &lt;!here&gt; A new incident has been opened :rotating_light:&gt; *Title:* Testing title&gt;*Priority:* P1 (High) - 60-100% of users affected' end it 'creates a channel', vcr: { cassette_name: 'web/conversations_create' } do rc = client.conversations_create({ name: 'incident_apply_210709_hello', is_private: false }) expect(rc.channel.name).to eq 'incident_apply_210709_hello' end end
guoop/ZKHR_ST
src/main/java/com/ruoyi/project/locator/common/GPSLocation.java
package com.ruoyi.project.locator.common; public class GPSLocation { private double latitude; private double longitude; public double getLatitude() { return latitude; } public GPSLocation setLatitude(double latitude) { this.latitude = latitude; return this; } public double getLongitude() { return longitude; } public GPSLocation setLongitude(double longitude) { this.longitude = longitude; return this; } public GPSLocation(double latitude, double longitude) { this.latitude = latitude; this.longitude = longitude; } public GPSLocation() { } }
hdpolover/ybb-scholarship-web
assets/vendor/tom-select/test/tests/plugins/clear_button.js
<gh_stars>0 describe('plugin: clear_button', function() { it_n('should remove all item when button is clicked', function(done) { var on_change_calls = 0; let test = setup_test('AB_Multi', { plugins: ['clear_button'], onChange:function(){ on_change_calls++; } }); test.instance.addItem('a'); test.instance.addItem('b'); on_change_calls = 0; assert.equal( test.instance.items.length, 2 ); var button = test.instance.control.querySelector('.clear-button'); syn.click( button, function() { assert.equal( test.instance.items.length, 0, 'should clear items array' ); assert.equal( on_change_calls, 1,'should only call onChange once' ); done(); }); }); });
shehand/PhishChain
QuorumNode/consensus/istanbul/validator/validator.go
// Copyright 2017 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package validator import ( "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/consensus/istanbul" ) func New(addr common.Address) istanbul.Validator { return &defaultValidator{ address: addr, } } func NewSet(addrs []common.Address, policy istanbul.ProposerPolicy) istanbul.ValidatorSet { return newDefaultSet(addrs, policy) } func ExtractValidators(extraData []byte) []common.Address { // get the validator addresses addrs := make([]common.Address, (len(extraData) / common.AddressLength)) for i := 0; i < len(addrs); i++ { copy(addrs[i][:], extraData[i*common.AddressLength:]) } return addrs } // Check whether the extraData is presented in prescribed form func ValidExtraData(extraData []byte) bool { return len(extraData)%common.AddressLength == 0 }
DataDog/istio
galley/pkg/crd/mapping_test.go
// Copyright 2018 Istio Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package crd import ( "fmt" "strings" "testing" "k8s.io/apimachinery/pkg/runtime/schema" ) func TestNewMapping_Errors(t *testing.T) { tests := []struct { input map[schema.GroupVersion]schema.GroupVersion err string }{ { input: map[schema.GroupVersion]schema.GroupVersion{ { Group: "g1", Version: "v1", }: { Group: "g1", Version: "v2", }, }, err: `cycling mapping not allowed: g1`, }, { input: map[schema.GroupVersion]schema.GroupVersion{ { Group: "g1", Version: "v1", }: { Group: "g2", Version: "v2", }, { Group: "g1", Version: "v2", }: { Group: "g3", Version: "v3", }, }, err: `mapping already exists: g1`, }, { input: map[schema.GroupVersion]schema.GroupVersion{ { Group: "g1", Version: "v1", }: { Group: "g2", Version: "v2", }, { Group: "g3", Version: "v3", }: { Group: "g2", Version: "v1", }, }, err: `reverse mapping is not unique: g2`, }, } for i, tst := range tests { t.Run(fmt.Sprintf("%d", i), func(tt *testing.T) { _, err := NewMapping(tst.input) if err == nil { tt.Fatalf("error not found: %v", tst.err) } if strings.TrimSpace(tst.err) != strings.TrimSpace(err.Error()) { tt.Fatalf("Unexpected error: got:\n%v\n, wanted:\n%v\n", err, tst.err) } }) } } func TestMapping_GetGroupVersion(t *testing.T) { m, _ := NewMapping(map[schema.GroupVersion]schema.GroupVersion{ { Group: "g1", Version: "v1", }: { Group: "g2", Version: "v2", }, }) tests := []struct { input string source schema.GroupVersion destination schema.GroupVersion found bool }{ { input: "zoo", found: false, }, { input: "g1", source: schema.GroupVersion{Group: "g1", Version: "v1"}, destination: schema.GroupVersion{Group: "g2", Version: "v2"}, found: true, }, { input: "g2", source: schema.GroupVersion{Group: "g1", Version: "v1"}, destination: schema.GroupVersion{Group: "g2", Version: "v2"}, found: true, }, } for _, tst := range tests { t.Run(tst.input, func(tt *testing.T) { as, ad, af := m.GetGroupVersion(tst.input) if af != tst.found { tt.Fatalf("Unexpected 'found': got:'%v', wanted:'%v'", af, tst.found) } if as != tst.source { tt.Fatalf("Unexpected 'source': got:'%v', wanted:'%v'", as, tst.source) } if ad != tst.destination { tt.Fatalf("Unexpected 'destination': got:'%v', wanted:'%v'", ad, tst.destination) } }) } } func TestMapping_GetVersion(t *testing.T) { m, _ := NewMapping(map[schema.GroupVersion]schema.GroupVersion{ { Group: "g1", Version: "v1", }: { Group: "g2", Version: "v2", }, }) tests := []struct { input string expected string }{ { input: "g1", expected: "v1", }, { input: "g2", expected: "v2", }, { input: "g3", expected: "", }, } for _, tst := range tests { t.Run(tst.input, func(tt *testing.T) { actual := m.GetVersion(tst.input) if actual != tst.expected { tt.Fatalf("Unexpected result: got:'%v', wanted:'%v'", actual, tst.expected) } }) } } func TestMapping_String(t *testing.T) { tests := []struct { input map[schema.GroupVersion]schema.GroupVersion expected string }{ { input: map[schema.GroupVersion]schema.GroupVersion{}, expected: ` --- Mapping --- ---------------`, }, { input: map[schema.GroupVersion]schema.GroupVersion{ { Group: "g1", Version: "v1", }: { Group: "g2", Version: "v2", }, }, expected: ` --- Mapping --- g1/v1 => g2/v2 --------------- `, }, } for i, tst := range tests { t.Run(fmt.Sprintf("%d", i), func(tt *testing.T) { m, err := NewMapping(tst.input) if err != nil { t.Fatalf("Unexpected error: %v", err) } actual := m.String() if strings.TrimSpace(actual) != strings.TrimSpace(tst.expected) { tt.Fatalf("Unexpected result: got:\n%v\n, wanted:\n%v\n", actual, tst.expected) } }) } }
ugorji/collab-wiki
src/main/java/net/ugorji/oxygen/wiki/WikiIndexingManager.java
<filename>src/main/java/net/ugorji/oxygen/wiki/WikiIndexingManager.java /* <<< COPYRIGHT START >>> * Copyright 2006-Present OxygenSoftwareLibrary.com * Licensed under the GNU Lesser General Public License. * http://www.gnu.org/licenses/lgpl.html * * @author: <NAME> * <<< COPYRIGHT END >>> */ package net.ugorji.oxygen.wiki; import java.io.BufferedReader; import java.io.File; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Pattern; import org.apache.lucene.document.DateTools; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Filter; import org.apache.lucene.search.Hits; import org.apache.lucene.search.ParallelMultiSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Searchable; import org.apache.lucene.search.Searcher; import org.apache.lucene.search.TermQuery; import net.ugorji.oxygen.markup.MarkupLink; import net.ugorji.oxygen.markup.indexing.HitsHandler; import net.ugorji.oxygen.markup.indexing.MarkupAnalyzer; import net.ugorji.oxygen.markup.indexing.MarkupIndexingManager; import net.ugorji.oxygen.markup.indexing.MarkupIndexingParser; import net.ugorji.oxygen.markup.indexing.MarkupIndexingParserBase; import net.ugorji.oxygen.util.ObjectWrapper; import net.ugorji.oxygen.util.OxygenConstants; import net.ugorji.oxygen.util.OxygenSearchResults; import net.ugorji.oxygen.util.OxygenUtils; import net.ugorji.oxygen.util.SimpleInt; import net.ugorji.oxygen.util.StringUtils; /** * Manages our indexes. When a category engine is initialized, it creates an index on all the pages * available. This index is used for searches, and for looking up references. At init, create index * on save et al, refresh index */ public class WikiIndexingManager extends MarkupIndexingManager { private static final String[] EMPTY = new String[0]; private static DateTools.Resolution dateResolution = DateTools.Resolution.DAY; // static { // linkPattern = Pattern.compile("(\\[[\\p{Space}]*(.+?)[\\p{Space}]*\\])" + "|" + // "([\\p{Space}]([\\w\\./]+:[^\\p{Space}]+))" + "|" + // "([\\p{Space}]([\\w\\./]+?[#|\\^]?[\\w\\./]*))"); // } private WikiCategoryEngine wce; private boolean onlyIndexPublishedPages = false; private boolean supportFullTextSearch = true; // hold a map of page name (String) to all its references (Set) // this map thus only knows about pages which exist // Map<String, Set> private Map refs = new HashMap(); // holds all the pages contained in this category // Set<String> private Set allrefs = new TreeSet(); // let read, and write, lock on the same object. // private Object WIM_GET_READER_LOCK = new Object(); // private Object WIM_WRITE_LOCK = WIM_GET_READER_LOCK; // private Object WIM_WRITE_LOCK = new Object(); public WikiIndexingManager(WikiCategoryEngine _wce) throws Exception { wce = _wce; onlyIndexPublishedPages = "true".equals(wce.getProperty(WikiConstants.ONLY_INDEX_PUBLISHED_PAGES_KEY)); supportFullTextSearch = "true".equals(wce.getProperty(OxygenConstants.FULL_TEXT_SEARCH_SUPPORTED_KEY)); // analyzer = // (Analyzer)Class.forName(wce.getProperty(WikiConstants.INDEXING_ANALYZER_CLASSNAME_KEY)).newInstance(); analyzer = new MarkupAnalyzer(this); analyzerForSearching = new MarkupAnalyzer(this); } public void close() { super.close(); refs.clear(); allrefs.clear(); wce = null; } /** * clears everything, recreates the lucene index'es and fills up the tables which hold the * normalized references * * @throws Exception */ public synchronized void resetAll(boolean forceRecreateIndex) throws Exception { WikiCategoryEngine oldwce = WikiLocal.getWikiCategoryEngine(); try { WikiLocal.setWikiCategoryEngine(wce); refs.clear(); allrefs.clear(); // escapeHTML = "true".equals(wce.getProperty(WikiConstants.ESCAPE_HTML_KEY)); // freeLinkSupported = "true".equals(wce.getProperty(WikiConstants.FREELINK_SUPPORTED_KEY)); // camelCaseWordIsLink = "true".equals(wce.getProperty(WikiConstants.CAMEL_CASE_IS_LINK_KEY)); // slashSeparatedWordIsLink = // "true".equals(wce.getProperty(WikiConstants.SLASH_SEPARATED_IS_LINK_KEY)); recreateIndex(forceRecreateIndex); initRefs(); // System.out.println("wce: " + wce.getName() + " | allrefs: " + allrefs + "\nrefs: " + refs); } finally { WikiLocal.setWikiCategoryEngine(oldwce); } } /** * @param pagerep a wiki page name * @return true if a page is referenced, false otherwise */ public boolean isReferenced(String pagerep) { return allrefs.contains(pagerep); } /** * @param pagerep a wiki page name * @return true if a page is a referer(which is a cheap way of checking if a page exists), false * otherwise */ public boolean isAReferrer(String pagerep) { return refs.containsKey(pagerep); } public WikiCategoryEngine getWikiCategoryEngine() { return wce; } /** * This map will take the following keys: All keys are keywords, except - SEARCH_INDEX_CONTENTS * and - SEARCH_INDEX_COMMENTS (These should be parsed via Queryparser) SEARCH_INDEX_TAGS: should * be tokenized, and OR'ed */ public void search(Map m, boolean allRequired, HitsHandler hhdlr) throws Exception { Query query = getSearchQuery(m, allRequired); Filter filter = getSearchFilter(m); search(query, filter, hhdlr); } public OxygenSearchResults searchCategories( Map m, boolean allRequired, String[] categories, int maxHits, double minScore, double thresholdScore) throws Exception { OxygenSearchResults srch = new OxygenSearchResults(); if (m.size() > 1) { WikiEngine we = WikiLocal.getWikiEngine(); IndexReader[] indexReaders = new IndexReader[categories.length]; Searchable[] indexSearchers = new Searchable[categories.length]; WikiIndexingManager[] wim = new WikiIndexingManager[categories.length]; Searcher multiSearcher = null; try { for (int i = 0; i < categories.length; i++) { wim[i] = we.retrieveWikiCategoryEngine(categories[i]).getIndexingManager(); indexReaders[i] = wim[i].getIndexReader(); indexSearchers[i] = wim[i].isearcher0; } multiSearcher = new ParallelMultiSearcher(indexSearchers); Query query = getSearchQuery(m, allRequired); Filter filter = getSearchFilter(m); Hits hits = multiSearcher.search(query, filter); int numhits = hits.length(); int numResultsAdded = 0; // numhits = Math.min(maxHits, numhits); for (int i = 0; i < numhits; i++) { Document doc = hits.doc(i); double score0 = (double) hits.score(i); if (score0 >= thresholdScore || (numResultsAdded < maxHits && score0 >= minScore)) { srch.addResult( doc.get(WikiConstants.SEARCH_INDEX_CATEGORY), doc.get(WikiConstants.SEARCH_INDEX_PAGENAME), (double) hits.score(i)); numResultsAdded++; } } } finally { for (int i = 0; i < categories.length; i++) { // close(indexSearchers[i]); if (wim[i] != null) { wim[i].returnIndexReader(indexReaders[i]); } } // close(multiSearcher); } } return srch; } /** * Whenever a page is created, updated or deleted, its references get out of sync. This method * allows us reset its references, by recreating it in the lucene index, and then reset'ing its * references in our tables. * * @param pagename * @throws Exception */ public synchronized void resetWikiPage(String pagename) throws Exception { File f = getIndexDir(); waitTillNoMoreReaders(); IndexReader ireader = getIndexReader(); try { removeDocuments(pagename, ireader); refs.remove(pagename); allrefs.remove(pagename); } finally { returnIndexReader(ireader); setWriteDone(); } ireader = null; if (wce.getPageProvider().pageExists(pagename)) { IndexWriter iwriter = null; ireader = getIndexReader(); try { iwriter = new IndexWriter(f, analyzer, false); iwriter.setMergeFactor(5); createDocuments(pagename, iwriter); resetRefForWikiPage(pagename, ireader); } finally { returnIndexReader(ireader); close(iwriter); setWriteDone(); } } } /** * Get all referers matching a given regex. This allows us to do things like - get all pages * starting with M - get all pages matching M.*abc - get all pages under Main (e.g. Main/a, * Main/b, etc) If the regex passed is null, we return all the pages * * @param regex * @return * @throws Exception */ public String[] getAllReferersMatching(String regex) throws Exception { if (regex == null || regex.trim().length() == 0) { return (String[]) allrefs.toArray(new String[0]); } Pattern pattern = Pattern.compile(regex); List list = new ArrayList(); for (Iterator itr = allrefs.iterator(); itr.hasNext(); ) { String s = (String) itr.next(); if (pattern.matcher(s).matches()) { list.add(s); } } return (String[]) list.toArray(new String[0]); } /** * Get all pages that reference a given page. This allows us do things like: - get pages that * reference this non-existent page * * @param pagename * @return */ public String[] getPagesThatReference(String pagename) { Set set = new HashSet(); for (Iterator itr = allrefs.iterator(); itr.hasNext(); ) { String s = (String) itr.next(); Set set1 = (Set) refs.get(s); if (set1.contains(pagename)) { set.add(s); } } String[] arr = (String[]) set.toArray(new String[0]); return arr; } /** * Get all pages which are referenced by a given page E.g. get all pages that Main has links to. * * @param pagename * @return */ public String[] getPagesReferencedBy(String pagename) { String[] arr = EMPTY; Set set = (Set) refs.get(pagename); if (set != null) { arr = (String[]) set.toArray(new String[0]); } return arr; } /** Get all pages which exist, but are not references at all (orphaned pages) */ public String[] getNonReferencedPages() { Set set = new HashSet(); List list = Arrays.asList(getAllReferences()); for (Iterator itr = allrefs.iterator(); itr.hasNext(); ) { String s = (String) itr.next(); if (!list.contains(s)) { set.add(s); } } String[] arr = (String[]) set.toArray(new String[0]); return arr; } /** * Get all non-existent pages (they are referenced, but do not exist) * * @return */ public String[] getNonExistentPages() { Set set = new HashSet(); List list = Arrays.asList(getAllReferences()); for (Iterator itr = list.iterator(); itr.hasNext(); ) { String s = (String) itr.next(); if (!allrefs.contains(s)) { set.add(s); } } String[] arr = (String[]) set.toArray(new String[0]); return arr; } /** * Get all the pages which are referenced within this category So if Main references a, b, c a * references b, c, d Then we return a, b, c, d * * @return */ public String[] getAllReferences() { Set set = new HashSet(); for (Iterator itr = allrefs.iterator(); itr.hasNext(); ) { Set set2 = (Set) refs.get(itr.next()); set.addAll(set2); } String[] arr = (String[]) set.toArray(new String[0]); return arr; } public String[] lookupAttachmentNames(String pagename, Date from, Date to) throws Exception { Map m = new HashMap(); m.put(WikiConstants.SEARCH_INDEX_PAGENAME, pagename); m.put(WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_ATTACHMENT_NAME); m.put(WikiConstants.SEARCH_INDEX_LAST_MODIFIED, getDateRangeQueryString(from, to)); // System.out.println("lookupAttachmentNames: " + from + " ... " + to + " ... " + // m.get(WikiConstants.SEARCH_INDEX_LAST_MODIFIED) + "..."); return getMatchingStringsForLookup(m, WikiConstants.SEARCH_INDEX_ATTACHMENT_NAME); } public String[] lookupPageReviewNames(String pagename, Date from, Date to) throws Exception { Map m = new HashMap(); m.put(WikiConstants.SEARCH_INDEX_PAGENAME, pagename); m.put(WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_COMMENT_NAME); m.put(WikiConstants.SEARCH_INDEX_LAST_MODIFIED, getDateRangeQueryString(from, to)); return getMatchingStringsForLookup(m, WikiConstants.SEARCH_INDEX_COMMENT_NAME); } public String[] lookupPageNames(Date from, Date to) throws Exception { Map m = new HashMap(); m.put(WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_PAGE); m.put(WikiConstants.SEARCH_INDEX_LAST_MODIFIED, getDateRangeQueryString(from, to)); String[] sa = getMatchingStringsForLookup(m, WikiConstants.SEARCH_INDEX_PAGENAME); // Thread.currentThread().dumpStack(); // System.out.println("lookupPageNames: [" + from + "] TO [" + to + "] " + Arrays.asList(sa)); return sa; } public String[] lookupExistingTags() throws Exception { Map m = new HashMap(); m.put(WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_PAGE); return getMatchingStringsForLookup(m, WikiConstants.SEARCH_INDEX_TAGS); } public Map lookupExistingTagsWithCount() throws Exception { Map m = new HashMap(); // so that the keys are sorted m.put(WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_PAGE); Map hmap = new TreeMap(); getMatchesForLookup(m, WikiConstants.SEARCH_INDEX_TAGS, hmap, null); // System.out.println("lookupExistingTagsWithCount: " + wce.getName() + ": " + hmap); return hmap; } public String[] lookupPageNamesGivenTag(String tag) throws Exception { Map m = new HashMap(); m.put(WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_PAGE); m.put(WikiConstants.SEARCH_INDEX_TAGS, tag.toLowerCase()); return getMatchingStringsForLookup(m, WikiConstants.SEARCH_INDEX_PAGENAME); } public boolean isOnlyIndexPublishedPages() { return onlyIndexPublishedPages; } public WikiProvidedObject getWikiPageFromIndex(String pagename) throws Exception { WikiProvidedObject wp = new WikiProvidedObject(pagename); final ObjectWrapper ow = new ObjectWrapper(null); HitsHandler myhithdlr = new HitsHandler() { public void handleHits(Hits hits) throws Exception { ow.setObject(hits); } }; Map m = new HashMap(); m.put(WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_PAGE); m.put(WikiConstants.SEARCH_INDEX_PAGENAME, pagename); search(m, true, myhithdlr); Hits hits = (Hits) ow.obj(); if (hits.length() > 0) { Document doc = hits.doc(0); Field field = null; if ((field = doc.getField(WikiConstants.SEARCH_INDEX_VERSION)) != null) { wp.setVersion(Integer.parseInt(field.stringValue())); } if ((field = doc.getField(WikiConstants.SEARCH_INDEX_LAST_MODIFIED)) != null) { wp.setDate(DateTools.stringToDate(field.stringValue())); } if ((field = doc.getField(WikiConstants.SEARCH_INDEX_LAST_EDITOR)) != null) { wp.setAttribute(WikiConstants.ATTRIBUTE_AUTHOR, field.stringValue()); } if ((field = doc.getField(WikiConstants.SEARCH_INDEX_PAGE_EDITOR_COMMENT)) != null) { wp.setAttribute(WikiConstants.ATTRIBUTE_COMMENTS, field.stringValue()); } Field[] fields = doc.getFields(WikiConstants.SEARCH_INDEX_TAGS); if (fields != null && fields.length > 0) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < fields.length; i++) { buf.append(fields[i].stringValue()).append(" "); } wp.setAttribute(WikiConstants.ATTRIBUTE_TAGS, buf.toString().trim()); } } return wp; } protected File getIndexDir() throws Exception { File f = new File(wce.getWikiEngine().getRuntimeDirectory(), "searchindex"); f = new File(f, wce.getName()); OxygenUtils.mkdirs(f); return f; } protected MarkupIndexingParser newParser(String name, Reader r, List _tokenstrings, HashSet _hs) throws Exception { WIMMarkupParserBase x = new WIMMarkupParserBase(name, r, _tokenstrings, _hs); MarkupIndexingParser mx = new MarkupIndexingParser(x.getMarkupParser(), x); return mx; } private synchronized void recreateIndex(boolean forceRecreateIndex) throws Exception { String[] sarr = wce.getPageProvider().getPageNames("/", Integer.MAX_VALUE, false); // System.out.println("In WikiIndexingManager<init>: wps: " + Arrays.asList(sarr)); OxygenUtils.debug("In WikiIndexingManager<init>: wps: " + Arrays.asList(sarr)); // initialize index File f = getIndexDir(); if (forceRecreateIndex) { // Thread.dumpStack(); // System.out.println("***** Calling deleteFile: " + f.getAbsolutePath()); OxygenUtils.deleteFile(f); } // if directory does not exist or it is empty, recreate it and index // if(!f.exists() || f.isFile() || f.listFiles().length == 0) { if (!IndexReader.indexExists(f)) { waitTillNoMoreReaders(); OxygenUtils.deleteFile(f); OxygenUtils.mkdirs(f); IndexWriter iwriter = null; try { iwriter = new IndexWriter(f, analyzer, true); iwriter.setMergeFactor(50); for (int i = 0; i < sarr.length; i++) { // System.out.println("Creating Index document for: " + wce.getName() + ":" + sarr[i]); createDocuments(sarr[i], iwriter); } iwriter.optimize(); } finally { close(iwriter); setWriteDone(); } } } private void initRefs() throws Exception { // File f = getIndexDir(); // initialize the refs maps List allpagesinindex = new ArrayList(); IndexReader ireader = getIndexReader(); try { int numdocs = ireader.numDocs(); // doc.add(new Field(WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_PAGE, // Field.Store.YES, Field.Index.UN_TOKENIZED)); for (int i = 0; i < numdocs; i++) { Document doc = ireader.document(i); Field field = doc.getField(WikiConstants.SEARCH_INDEX_INDEX_TYPE); // System.out.println("indextype: " + field); if (WikiConstants.SEARCH_INDEX_PAGE.equals(field.stringValue())) { field = doc.getField(WikiConstants.SEARCH_INDEX_PAGENAME); String pagename = field.stringValue(); allpagesinindex.add(pagename); } } for (Iterator itr = allpagesinindex.iterator(); itr.hasNext(); ) { resetRefForWikiPage((String) itr.next(), ireader); } } finally { returnIndexReader(ireader); // close(ireader); } } private void search(Query query, Filter filter, HitsHandler hhdlr) throws Exception { File f = getIndexDir(); IndexReader ireader = getIndexReader(); try { Hits hits = isearcher0.search(query, filter); hhdlr.handleHits(hits); } finally { returnIndexReader(ireader); } } private Query getSearchQuery(Map m, boolean allRequired) throws Exception { BooleanClause.Occur occur = (allRequired) ? BooleanClause.Occur.MUST : BooleanClause.Occur.SHOULD; BooleanQuery query = new BooleanQuery(); for (Iterator itr = m.keySet().iterator(); itr.hasNext(); ) { String key = (String) itr.next(); String val = (String) m.get(key); if (!StringUtils.isBlank(val)) { if (WikiConstants.SEARCH_INDEX_TAGS.equals(key)) { BooleanQuery q2 = new BooleanQuery(); StringTokenizer stz = new StringTokenizer(val.trim().toLowerCase(), ", "); while (stz.hasMoreTokens()) { q2.add( new BooleanClause( new TermQuery(new Term(key, stz.nextToken())), BooleanClause.Occur.SHOULD)); } query.add(new BooleanClause(q2, occur)); } else if (WikiConstants.SEARCH_INDEX_CONTENTS.equals(key) || WikiConstants.SEARCH_INDEX_COMMENTS.equals(key)) { query.add( new BooleanClause(new QueryParser(key, analyzerForSearching).parse(val), occur)); } else if (WikiConstants.SEARCH_INDEX_LAST_MODIFIED.equals(key)) { query.add( new BooleanClause(new QueryParser(key, analyzerForSearching).parse(val), occur)); } else { query.add(new BooleanClause(new TermQuery(new Term(key, val)), occur)); } } } return query; } private Filter getSearchFilter(Map m) throws Exception { return null; } private void removeDocuments(String pagename, IndexReader ireader) throws Exception { Term term = new Term(WikiConstants.SEARCH_INDEX_PAGENAME, pagename); ireader.deleteDocuments(term); } private void createDocuments(String pagename, IndexWriter iwriter) throws Exception { try { analyzer.setTextSourceName(WikiUtils.fullQualifiedWikiName(wce.getName(), pagename)); Document doc = new Document(); int version = WikiProvidedObject.VERSION_LATEST_DETAILS_NECESSARY; String s = null; // System.out.println("default version: " + version); WikiProvidedObject wp = wce.getPageProvider().getPage(pagename, version); if (onlyIndexPublishedPages && !("true".equals(wp.getAttribute(WikiConstants.ATTRIBUTE_PUBLISHED)))) { return; } if (version == WikiProvidedObject.VERSION_LATEST_DETAILS_NECESSARY) { WikiProvidedObject wp22 = wce.getPageProvider().getPage(pagename, wce.getPageProvider().getInitialVersion()); if ((s = wp22.getAttribute(WikiConstants.ATTRIBUTE_AUTHOR)) != null) { doc.add( new Field( WikiConstants.SEARCH_INDEX_AUTHOR, s, Field.Store.YES, Field.Index.UN_TOKENIZED)); } if ((s = wp22.getAttribute(WikiConstants.ATTRIBUTE_COMMENTS)) != null) { doc.add( new Field( WikiConstants.SEARCH_INDEX_PAGE_EDITOR_COMMENT, s, Field.Store.YES, Field.Index.UN_TOKENIZED)); } } doc.add( new Field( WikiConstants.SEARCH_INDEX_CATEGORY, wce.getName(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_PAGENAME, wp.getName(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_VERSION, String.valueOf(wp.getVersion()), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_LAST_MODIFIED, DateTools.dateToString(wp.getDate(), dateResolution), Field.Store.YES, Field.Index.UN_TOKENIZED)); if (wp.getAttribute(WikiConstants.ATTRIBUTE_AUTHOR) != null) { doc.add( new Field( WikiConstants.SEARCH_INDEX_LAST_EDITOR, wp.getAttribute(WikiConstants.ATTRIBUTE_AUTHOR), Field.Store.YES, Field.Index.UN_TOKENIZED)); } if (wp.getAttribute(WikiConstants.ATTRIBUTE_TAGS) != null) { StringTokenizer stz = new StringTokenizer(wp.getAttribute(WikiConstants.ATTRIBUTE_TAGS), ", "); while (stz.hasMoreTokens()) { doc.add( new Field( WikiConstants.SEARCH_INDEX_TAGS, stz.nextToken().trim().toLowerCase(), Field.Store.YES, Field.Index.UN_TOKENIZED)); } } int oldrealver = wp.getVersion(); wp.setVersion(version); Reader r = wce.getPageProvider().getPageReader(wp); wp.setVersion(oldrealver); String pagetext = StringUtils.readerToString(r); if (supportFullTextSearch) { doc.add( new Field( WikiConstants.SEARCH_INDEX_CONTENTS, pagetext, Field.Store.YES, Field.Index.TOKENIZED)); } // now add the references to the index // note: errors found while trying to index individual pages, should not stop the document // from being created HashSet myrefs = new HashSet(); try { MarkupIndexingParser wimap = newParser(pagename, new BufferedReader(new StringReader(pagetext)), null, myrefs); wimap.markupToHTML(); } catch (Exception exc) { OxygenUtils.error( "Exception getting references while parsing wiki page during indexing: " + wce.getName() + ":" + pagename, exc); } // System.out.println("analyzer.references: pagename: " + pagename + " --- " + myrefs); for (Iterator itr = myrefs.iterator(); itr.hasNext(); ) { doc.add( new Field( WikiConstants.SEARCH_INDEX_REFERENCES, (String) itr.next(), Field.Store.YES, Field.Index.UN_TOKENIZED)); } String[] sarr = wce.getAttachmentProvider().getAttachmentNames(wp.getName(), false); WikiProvidedObject[] attachments = new WikiProvidedObject[sarr.length]; for (int i = 0; i < attachments.length; i++) { attachments[i] = wce.getAttachmentProvider().getAttachment(pagename, sarr[i], version); doc.add( new Field( WikiConstants.SEARCH_INDEX_ATTACHMENT_NAME, attachments[i].getName(), Field.Store.YES, Field.Index.UN_TOKENIZED)); } sarr = wce.getPageReviewProvider().getPageReviewNames(wp.getName(), false); WikiProvidedObject[] comments = new WikiProvidedObject[sarr.length]; for (int i = 0; i < comments.length; i++) { comments[i] = wce.getPageReviewProvider().getPageReview(pagename, sarr[i], version); if (supportFullTextSearch) { r = wce.getPageReviewProvider().getPageReviewReader(pagename, comments[i]); doc.add( new Field( WikiConstants.SEARCH_INDEX_COMMENTS, StringUtils.readerToString(r), Field.Store.YES, Field.Index.TOKENIZED)); } } doc.add( new Field( WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_PAGE, Field.Store.YES, Field.Index.UN_TOKENIZED)); iwriter.addDocument(doc); // System.out.println("analyzer.tokenstringlist: pagename: " + pagename + " --- " + // analyzer.tokenstringlist); for (int i = 0; i < comments.length; i++) { doc = new Document(); doc.add( new Field( WikiConstants.SEARCH_INDEX_CATEGORY, wce.getName(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_COMMENT_NAME, Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_COMMENT_NAME, comments[i].getName(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_PAGENAME, pagename, Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_LAST_MODIFIED, DateTools.dateToString(comments[i].getDate(), dateResolution), Field.Store.YES, Field.Index.UN_TOKENIZED)); iwriter.addDocument(doc); } for (int i = 0; i < attachments.length; i++) { doc = new Document(); doc.add( new Field( WikiConstants.SEARCH_INDEX_CATEGORY, wce.getName(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_ATTACHMENT_NAME, Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_ATTACHMENT_NAME, attachments[i].getName(), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_PAGENAME, pagename, Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_VERSION, String.valueOf(attachments[i].getVersion()), Field.Store.YES, Field.Index.UN_TOKENIZED)); doc.add( new Field( WikiConstants.SEARCH_INDEX_LAST_MODIFIED, DateTools.dateToString(attachments[i].getDate(), dateResolution), Field.Store.YES, Field.Index.UN_TOKENIZED)); iwriter.addDocument(doc); } } finally { analyzer.setTextSourceName(null); } } private void resetRefForWikiPage(String pagename, IndexReader ireader) throws Exception { HashSet hs = new HashSet(); try { Map m = new HashMap(); m.put(WikiConstants.SEARCH_INDEX_PAGENAME, pagename); m.put(WikiConstants.SEARCH_INDEX_INDEX_TYPE, WikiConstants.SEARCH_INDEX_PAGE); String[] refs = getMatchingStringsForLookup(m, WikiConstants.SEARCH_INDEX_REFERENCES); hs.addAll(Arrays.asList(refs)); } catch (Exception exc) { // exc.printStackTrace(); OxygenUtils.info("Error resetRefForWikiPage: " + pagename); OxygenUtils.error(exc); } finally { refs.put(pagename, hs); allrefs.add(pagename); } } private String[] getMatchingStringsForLookup(final Map m, final String fieldname) throws Exception { final HashSet list = new HashSet(); getMatchesForLookup(m, fieldname, null, list); String[] sarr = (String[]) list.toArray(new String[0]); Arrays.sort(sarr); return sarr; } private void getMatchesForLookup( final Map m, final String fieldname, final Map hmap, final Set hset) throws Exception { HitsHandler myhithdlr = new HitsHandler() { public void handleHits(Hits hits) throws Exception { int numhits = hits.length(); for (int i = 0; i < numhits; i++) { Document doc = hits.doc(i); Field[] fields = doc.getFields(fieldname); if (fields != null && fields.length > 0) { for (int j = 0; j < fields.length; j++) { String s = fields[j].stringValue(); if (hset != null) { hset.add(s); } if (hmap != null) { SimpleInt si = (SimpleInt) hmap.get(s); if (si == null) { si = new SimpleInt(); hmap.put(s, si); } si.increment(); } } } } } }; search(m, true, myhithdlr); } public static String getDateRangeQueryString(Date from, Date to) throws Exception { // do nothing if both from and to are null (ie the dates are not included in the query) if (from == null && to == null) { return null; } StringBuffer buf = new StringBuffer(); String fromint = "0"; String toint = String.valueOf(Integer.MAX_VALUE); if (from == null) { from = new Date(0); } if (to == null) { to = new Date(); } // use minute resolution, else sometimes, U'd get the TooManyClausesException buf.append("[") .append(DateTools.dateToString(from, dateResolution)) .append(" TO ") .append(DateTools.dateToString(to, dateResolution)) .append("]"); return buf.toString(); } private class WIMMarkupParserBase extends MarkupIndexingParserBase { private WikiParser2Base wp2 = null; public WIMMarkupParserBase(String name, Reader r, List _tokenstrings, HashSet _hs) throws Exception { super(wce.getMarkupParserFactory().newMarkupParser(r), _tokenstrings, _hs); setRenderContext(new WikiRenderContext(wce, new WikiProvidedObject(name), false)); setRenderEngine(wce.getRenderEngine()); setTextSourceName(name); wp2 = new WikiParser2Base(); wp2.setRenderContext(getRenderContext()); wp2.setRenderEngine(getRenderEngine()); } public void link(MarkupLink mlink, boolean doPrint) throws Exception { super.link(mlink, doPrint); if (hs != null) { WikiLinkHolder wlh = wp2.do_link(mlink, false); _addlh(wlh); } } public void word(String s, boolean isSlashSeperated, boolean doPrint) throws Exception { super.word(s, isSlashSeperated, doPrint); if (hs != null) { WikiLinkHolder wlh = wp2.do_word(s, isSlashSeperated, false); _addlh(wlh); } } private void _addlh(WikiLinkHolder lh) throws Exception { // if(lh != null) System.out.println("calling _addlh: " + lh.getCategory() + " | " + // lh.isExtLink() + " | " + lh.getCategory() + " | " + lh.getWikiPage()); if (hs != null && lh != null && !lh.isExtLink() && lh.getCategory().equals(wce.getName()) && lh.getWikiPage() != null) { hs.add(lh.getWikiPage()); // System.out.println("calling _addlh: added: " + lh.getWikiPage()); } } } } /* private class WIMMarkupParser extends MarkupIndexingParser { private WikiParser2 wp2; public WIMMarkupParser(String name, Reader r, List _tokenstrings, HashSet _hs) throws Exception { super(new WikiRenderContext(wce, new WikiProvidedObject(name), false), wce.getRenderEngine(), name, r, _tokenstrings, _hs); wp2 = new WikiParser2(r, new PrintWriter(new NullWriter()), rc, re); } protected void link(MarkupLink mlink, boolean doPrint) throws Exception { super.link(mlink, doPrint); if(hs != null) { WikiLinkHolder wlh = wp2.do_link(mlink, false); _addlh(wlh); } } protected void word(String s, boolean isSlashSeperated, boolean doPrint) throws Exception { super.word(s, isSlashSeperated, doPrint); if(hs != null) { WikiLinkHolder wlh = wp2.do_word(s, isSlashSeperated, false); _addlh(wlh); } } private void _addlh(WikiLinkHolder lh) throws Exception { //if(lh != null) System.out.println("calling _addlh: " + lh.getCategory() + " | " + lh.isExtLink() + " | " + lh.getCategory() + " | " + lh.getWikiPage()); if(hs != null && lh != null && !lh.isExtLink() && lh.getCategory().equals(wce.getName()) && lh.getWikiPage() != null) { hs.add(lh.getWikiPage()); //System.out.println("calling _addlh: added: " + lh.getWikiPage()); } } } */ /* private void _resetRefForWikiPage_via_regex(String pagename, String pagetext, HashSet hs) throws Exception { WikiUtils.debug("In WikiIndexingManager.resetRefForWikiPage: Pagename: " + pagename); Matcher m = linkPattern.matcher(pagetext); WikiUtils.info("resetting ref for category: " + wce.getName() + " Page: " + pagename); while(m.find()) { WikiUtils.info("=== found string: " + m.group(0)); String s1 = m.group(2); String s2 = m.group(4); String s3 = m.group(6); if(s1 != null && s1.length() > 0) { WikiLinkHolder lh = new WikiLinkHolder(wce, pagename, s1, true); if(!lh.isExtLink() && lh.getCategory().equals(wce.getName()) && lh.getWikiPage() != null) { hs.add(lh.getWikiPage()); } } else if(s2 != null && s2.length() > 0) { WikiLinkHolder lh = new WikiLinkHolder(wce, pagename, s2, false); if(!lh.isExtLink() && lh.getCategory().equals(wce.getName()) && lh.getWikiPage() != null) { hs.add(lh.getWikiPage()); } } else if(s3 != null && s3.length() > 0) { if(allrefs.contains(s3)) { hs.add(s3); } } } } */ /** * performs a search (delegating to lucene) * * @param searchkey string to search on, that lucene understands * @param indexkey the index to search on * @return the search results (non-null) * @throws Exception */ /* private void search(String searchkey, HitsHandler hhdlr) throws Exception { Query query = new QueryParser(WikiConstants.SEARCH_INDEX_CONTENTS, analyzer).parse(searchkey); search(query, hhdlr); } */ /* private Filter getSearchFilter(Map m) throws Exception { //List filters = new ArrayList(2); Filter f = null; //FOR NOW, handle dates within the getSearchQuery method //if U want this handled here, do nothing within the corresponding stuff under getSearchQuery //String val = (String)m.get(WikiConstants.SEARCH_INDEX_LAST_MODIFIED); //if(!StringUtils.isBlank(val)) { // int len = val.length(); // int i0 = val.indexOf(" TO "); // //System.out.println(val + " ... " + val.substring(1, i0) + " ... " + val.substring(i0+4, len-1)); // f = new RangeFilter(WikiConstants.SEARCH_INDEX_LAST_MODIFIED, // val.substring(1, i0), val.substring(i0+4, len-1), // true, true); //} //handle all others with SEARCH_INDEX_ANY_HIT_IDENTIFIER // (especially so that PageIndex works, if too many attachments) // actually - comment out, 'cos if ANY, then don't include at all in search query or filter //for(Iterator itr = m.keySet().iterator(); itr.hasNext(); ) { // String key = (String)itr.next(); // String val = (String)m.get(key); // if(!StringUtils.isBlank(val)) { // if(WikiConstants.SEARCH_INDEX_TAGS.equals(key) || // WikiConstants.SEARCH_INDEX_CONTENTS.equals(key) || WikiConstants.SEARCH_INDEX_COMMENTS.equals(key) || // WikiConstants.SEARCH_INDEX_LAST_MODIFIED.equals(key)) { // continue; // } // if(WikiConstants.SEARCH_INDEX_ANY_HIT_IDENTIFIER.equals(val)) { // //handle in filter ... actually, if ANY, then don't include it in the search query // f = new RangeFilter(key, "0", null, false, false); // filters.add(f); // } // } //} //now, figure out the filter - disable all for now, since we don't use filters at all //Filter[] filterArr = (Filter[])filters.toArray(new Filter[0]); //if(filterArr.length > 1) { // //f = new ChainedFilter(filterArr, ChainedFilter.AND); // throw new UnsupportedOperationException("Multiple Filters cannot be used at a time"); //} else if(filterArr.length == 1) { // f = filterArr[0]; //} else { // f = null; //} return f; } */
jassem-lab/LMS_MERN
client/src/screens/App/shared/common/Modal/ModalSingleButton.js
import React, { Fragment, Component } from 'react'; import styles from './Modal.module.scss'; import { ButtonModalPrimary } from '../Button'; class ModalSingleButton extends Component { state = { transitionEnd: false }; componentDidMount = () => { if (typeof this.button !== 'undefined') setTimeout(() => { this.button.focus(); }, 100); setTimeout(() => { this.setState({ ...this.state, transitionEnd: true }); }, 0); }; setRef = element => { this.button = element; }; modalConfirmHandler = event => { event.preventDefault(); this.toggle(); }; toggle = () => { this.setState({ ...this.state, transitionEnd: false }, () => { setTimeout(() => { this.props.hidePopout(); }, 100); }); }; render = () => { const { title, message, buttonPrimary = true, buttonContent, buttonDanger = false, buttonLink = false } = this.props; return ( <Fragment> <div onClick={this.toggle} className={`${styles.modalBg} ${ this.state.transitionEnd ? styles.transitionEnd : null }`} /> <div className={`${styles.modal} ${ this.state.transitionEnd ? styles.transitionEnd : null }`}> <div className={styles.inner}> <div className={`${styles.modalInner} ${styles.container} ${ styles.small }`}> <div className={`${styles.flexItem} ${styles.header}`}> <h4 className={styles.title}>{title}</h4> </div> <div className={`${styles.flexItem} ${styles.body} ${ styles.scrollWrap }`}> <div className={`${styles.scroller} ${styles.bodyInner}`}> <div className={styles.contentText} dangerouslySetInnerHTML={{ __html: message }} /> </div> </div> <div className={`${styles.flexItem} ${styles.footer}`}> {buttonPrimary ? ( <ButtonModalPrimary setRef={this.setRef} onClick={this.modalConfirmHandler}> {buttonContent} </ButtonModalPrimary> ) : null} {buttonDanger ? ( <button ref={input => { this.button = input; }} onClick={this.modalConfirmHandler} className={`${styles.button} ${styles.lookFilled} ${ styles.buttonRed }`}> {buttonContent} </button> ) : null} {buttonLink ? ( <button ref={input => { this.button = input; }} onClick={this.modalConfirmHandler} className={`${styles.button} ${styles.lookLink}`}> <div className={styles.contents}>Cancel</div> {buttonContent} </button> ) : null} </div> </div> </div> </div> </Fragment> ); }; } export default ModalSingleButton;
jessicadavies-intel/llvm
sycl/include/CL/sycl/buffer.hpp
//==----------- buffer.hpp --- SYCL buffer ---------------------------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #pragma once #include <CL/sycl/ONEAPI/accessor_property_list.hpp> #include <CL/sycl/detail/buffer_impl.hpp> #include <CL/sycl/detail/common.hpp> #include <CL/sycl/detail/stl_type_traits.hpp> #include <CL/sycl/exception.hpp> #include <CL/sycl/property_list.hpp> #include <CL/sycl/stl.hpp> __SYCL_INLINE_NAMESPACE(cl) { namespace sycl { class handler; class queue; template <int dimensions> class range; /// Defines a shared array that can be used by kernels in queues. /// /// Buffers can be 1-, 2-, and 3-dimensional. They have to be accessed using /// accessor classes. /// /// \sa sycl_api_acc /// /// \ingroup sycl_api template <typename T, int dimensions = 1, typename AllocatorT = cl::sycl::buffer_allocator, typename = typename detail::enable_if_t<(dimensions > 0) && (dimensions <= 3)>> class buffer { public: using value_type = T; using reference = value_type &; using const_reference = const value_type &; using allocator_type = AllocatorT; template <int dims> using EnableIfOneDimension = typename detail::enable_if_t<1 == dims>; // using same requirement for contiguous container as std::span template <class Container> using EnableIfContiguous = detail::void_t<detail::enable_if_t<std::is_convertible< detail::remove_pointer_t<decltype( std::declval<Container>().data())> (*)[], const T (*)[]>::value>, decltype(std::declval<Container>().size())>; template <class It> using EnableIfItInputIterator = detail::enable_if_t< std::is_convertible<typename std::iterator_traits<It>::iterator_category, std::input_iterator_tag>::value>; template <typename ItA, typename ItB> using EnableIfSameNonConstIterators = typename detail::enable_if_t< std::is_same<ItA, ItB>::value && !std::is_const<ItA>::value, ItA>; buffer(const range<dimensions> &bufferRange, const property_list &propList = {}) : Range(bufferRange) { impl = std::make_shared<detail::buffer_impl>( size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>()); } buffer(const range<dimensions> &bufferRange, AllocatorT allocator, const property_list &propList = {}) : Range(bufferRange) { impl = std::make_shared<detail::buffer_impl>( size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>( allocator)); } buffer(T *hostData, const range<dimensions> &bufferRange, const property_list &propList = {}) : Range(bufferRange) { impl = std::make_shared<detail::buffer_impl>( hostData, size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>()); } buffer(T *hostData, const range<dimensions> &bufferRange, AllocatorT allocator, const property_list &propList = {}) : Range(bufferRange) { impl = std::make_shared<detail::buffer_impl>( hostData, size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>( allocator)); } template <typename _T = T> buffer(EnableIfSameNonConstIterators<T, _T> const *hostData, const range<dimensions> &bufferRange, const property_list &propList = {}) : Range(bufferRange) { impl = std::make_shared<detail::buffer_impl>( hostData, size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>()); } template <typename _T = T> buffer(EnableIfSameNonConstIterators<T, _T> const *hostData, const range<dimensions> &bufferRange, AllocatorT allocator, const property_list &propList = {}) : Range(bufferRange) { impl = std::make_shared<detail::buffer_impl>( hostData, size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>( allocator)); } buffer(const std::shared_ptr<T> &hostData, const range<dimensions> &bufferRange, AllocatorT allocator, const property_list &propList = {}) : Range(bufferRange) { impl = std::make_shared<detail::buffer_impl>( hostData, size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>( allocator)); } buffer(const std::shared_ptr<T[]> &hostData, const range<dimensions> &bufferRange, AllocatorT allocator, const property_list &propList = {}) : Range(bufferRange) { impl = std::make_shared<detail::buffer_impl>( hostData, size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>( allocator)); } buffer(const std::shared_ptr<T> &hostData, const range<dimensions> &bufferRange, const property_list &propList = {}) : Range(bufferRange) { impl = std::make_shared<detail::buffer_impl>( hostData, size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>()); } buffer(const std::shared_ptr<T[]> &hostData, const range<dimensions> &bufferRange, const property_list &propList = {}) : Range(bufferRange) { impl = std::make_shared<detail::buffer_impl>( hostData, size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>()); } template <class InputIterator, int N = dimensions, typename = EnableIfOneDimension<N>, typename = EnableIfItInputIterator<InputIterator>> buffer(InputIterator first, InputIterator last, AllocatorT allocator, const property_list &propList = {}) : Range(range<1>(std::distance(first, last))) { impl = std::make_shared<detail::buffer_impl>( first, last, size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>( allocator)); } template <class InputIterator, int N = dimensions, typename = EnableIfOneDimension<N>, typename = EnableIfItInputIterator<InputIterator>> buffer(InputIterator first, InputIterator last, const property_list &propList = {}) : Range(range<1>(std::distance(first, last))) { impl = std::make_shared<detail::buffer_impl>( first, last, size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>()); } // This constructor is a prototype for a future SYCL specification template <class Container, int N = dimensions, typename = EnableIfOneDimension<N>, typename = EnableIfContiguous<Container>> buffer(Container &container, AllocatorT allocator, const property_list &propList = {}) : Range(range<1>(container.size())) { impl = std::make_shared<detail::buffer_impl>( container.data(), size() * sizeof(T), detail::getNextPowerOfTwo(sizeof(T)), propList, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>( allocator)); } // This constructor is a prototype for a future SYCL specification template <class Container, int N = dimensions, typename = EnableIfOneDimension<N>, typename = EnableIfContiguous<Container>> buffer(Container &container, const property_list &propList = {}) : buffer(container, {}, propList) {} buffer(buffer<T, dimensions, AllocatorT> &b, const id<dimensions> &baseIndex, const range<dimensions> &subRange) : impl(b.impl), Range(subRange), OffsetInBytes(getOffsetInBytes<T>(baseIndex, b.Range)), IsSubBuffer(true) { if (b.is_sub_buffer()) throw cl::sycl::invalid_object_error( "Cannot create sub buffer from sub buffer.", PI_INVALID_VALUE); if (isOutOfBounds(baseIndex, subRange, b.Range)) throw cl::sycl::invalid_object_error( "Requested sub-buffer size exceeds the size of the parent buffer", PI_INVALID_VALUE); if (!isContiguousRegion(baseIndex, subRange, b.Range)) throw cl::sycl::invalid_object_error( "Requested sub-buffer region is not contiguous", PI_INVALID_VALUE); } template <int N = dimensions, typename = EnableIfOneDimension<N>> __SYCL2020_DEPRECATED("OpenCL interop APIs are deprecated") buffer(cl_mem MemObject, const context &SyclContext, event AvailableEvent = {}) : Range{0} { size_t BufSize = detail::SYCLMemObjT::getBufSizeForContext( detail::getSyclObjImpl(SyclContext), MemObject); Range[0] = BufSize / sizeof(T); impl = std::make_shared<detail::buffer_impl>( MemObject, SyclContext, BufSize, make_unique_ptr<detail::SYCLMemObjAllocatorHolder<AllocatorT>>(), AvailableEvent); } buffer(const buffer &rhs) = default; buffer(buffer &&rhs) = default; buffer &operator=(const buffer &rhs) = default; buffer &operator=(buffer &&rhs) = default; ~buffer() = default; bool operator==(const buffer &rhs) const { return impl == rhs.impl; } bool operator!=(const buffer &rhs) const { return !(*this == rhs); } /* -- common interface members -- */ /* -- property interface members -- */ range<dimensions> get_range() const { return Range; } __SYCL2020_DEPRECATED("get_count() is deprecated, please use size() instead") size_t get_count() const { return size(); } size_t size() const noexcept { return Range.size(); } size_t get_size() const { return size() * sizeof(T); } AllocatorT get_allocator() const { return impl->template get_allocator<AllocatorT>(); } template <access::mode Mode, access::target Target = access::target::global_buffer> accessor<T, dimensions, Mode, Target, access::placeholder::false_t, ONEAPI::accessor_property_list<>> get_access(handler &CommandGroupHandler) { return accessor<T, dimensions, Mode, Target, access::placeholder::false_t, ONEAPI::accessor_property_list<>>(*this, CommandGroupHandler); } template <access::mode mode> accessor<T, dimensions, mode, access::target::host_buffer, access::placeholder::false_t, ONEAPI::accessor_property_list<>> get_access() { return accessor<T, dimensions, mode, access::target::host_buffer, access::placeholder::false_t, ONEAPI::accessor_property_list<>>(*this); } template <access::mode mode, access::target target = access::target::global_buffer> accessor<T, dimensions, mode, target, access::placeholder::false_t, ONEAPI::accessor_property_list<>> get_access(handler &commandGroupHandler, range<dimensions> accessRange, id<dimensions> accessOffset = {}) { return accessor<T, dimensions, mode, target, access::placeholder::false_t, ONEAPI::accessor_property_list<>>( *this, commandGroupHandler, accessRange, accessOffset); } template <access::mode mode> accessor<T, dimensions, mode, access::target::host_buffer, access::placeholder::false_t, ONEAPI::accessor_property_list<>> get_access(range<dimensions> accessRange, id<dimensions> accessOffset = {}) { return accessor<T, dimensions, mode, access::target::host_buffer, access::placeholder::false_t, ONEAPI::accessor_property_list<>>(*this, accessRange, accessOffset); } #if __cplusplus > 201402L template <typename... Ts> auto get_access(Ts... args) { return accessor{*this, args...}; } template <typename... Ts> auto get_access(handler &commandGroupHandler, Ts... args) { return accessor{*this, commandGroupHandler, args...}; } template <typename... Ts> auto get_host_access(Ts... args) { return host_accessor{*this, args...}; } template <typename... Ts> auto get_host_access(handler &commandGroupHandler, Ts... args) { return host_accessor{*this, commandGroupHandler, args...}; } #endif template <typename Destination = std::nullptr_t> void set_final_data(Destination finalData = nullptr) { impl->set_final_data(finalData); } void set_write_back(bool flag = true) { impl->set_write_back(flag); } bool is_sub_buffer() const { return IsSubBuffer; } template <typename ReinterpretT, int ReinterpretDim> buffer<ReinterpretT, ReinterpretDim, AllocatorT> reinterpret(range<ReinterpretDim> reinterpretRange) const { if (sizeof(ReinterpretT) * reinterpretRange.size() != get_size()) throw cl::sycl::invalid_object_error( "Total size in bytes represented by the type and range of the " "reinterpreted SYCL buffer does not equal the total size in bytes " "represented by the type and range of this SYCL buffer", PI_INVALID_VALUE); return buffer<ReinterpretT, ReinterpretDim, AllocatorT>( impl, reinterpretRange, OffsetInBytes, IsSubBuffer); } template <typename ReinterpretT, int ReinterpretDim = dimensions> typename std::enable_if< (sizeof(ReinterpretT) == sizeof(T)) && (dimensions == ReinterpretDim), buffer<ReinterpretT, ReinterpretDim, AllocatorT>>::type reinterpret() const { return buffer<ReinterpretT, ReinterpretDim, AllocatorT>( impl, get_range(), OffsetInBytes, IsSubBuffer); } template <typename ReinterpretT, int ReinterpretDim = dimensions> typename std::enable_if< (ReinterpretDim == 1) && ((dimensions != ReinterpretDim) || (sizeof(ReinterpretT) != sizeof(T))), buffer<ReinterpretT, ReinterpretDim, AllocatorT>>::type reinterpret() const { long sz = get_size(); // TODO: switch to byte_size() once implemented if (sz % sizeof(ReinterpretT) != 0) throw cl::sycl::invalid_object_error( "Total byte size of buffer is not evenly divisible by the size of " "the reinterpreted type", PI_INVALID_VALUE); return buffer<ReinterpretT, ReinterpretDim, AllocatorT>( impl, range<1>{sz / sizeof(ReinterpretT)}, OffsetInBytes, IsSubBuffer); } template <typename propertyT> bool has_property() const { return impl->template has_property<propertyT>(); } template <typename propertyT> propertyT get_property() const { return impl->template get_property<propertyT>(); } private: std::shared_ptr<detail::buffer_impl> impl; template <class Obj> friend decltype(Obj::impl) detail::getSyclObjImpl(const Obj &SyclObject); template <typename A, int dims, typename C, typename Enable> friend class buffer; template <typename DataT, int dims, access::mode mode, access::target target, access::placeholder isPlaceholder, typename PropertyListT> friend class accessor; range<dimensions> Range; // Offset field specifies the origin of the sub buffer inside the parent // buffer size_t OffsetInBytes = 0; bool IsSubBuffer = false; // Reinterpret contructor buffer(std::shared_ptr<detail::buffer_impl> Impl, range<dimensions> reinterpretRange, size_t reinterpretOffset, bool isSubBuffer) : impl(Impl), Range(reinterpretRange), OffsetInBytes(reinterpretOffset), IsSubBuffer(isSubBuffer){}; template <typename Type, int N> size_t getOffsetInBytes(const id<N> &offset, const range<N> &range) { return detail::getLinearIndex(offset, range) * sizeof(Type); } bool isOutOfBounds(const id<dimensions> &offset, const range<dimensions> &newRange, const range<dimensions> &parentRange) { bool outOfBounds = false; for (int i = 0; i < dimensions; ++i) outOfBounds |= newRange[i] + offset[i] > parentRange[i]; return outOfBounds; } bool isContiguousRegion(const id<1> &, const range<1> &, const range<1> &) { // 1D sub buffer always has contiguous region return true; } bool isContiguousRegion(const id<2> &offset, const range<2> &newRange, const range<2> &parentRange) { // For 2D sub buffer there are 2 cases: // 1) Offset {Any, Any} | a piece of any line of a buffer // Range {1, Any} | // 2) Offset {Any, 0 } | any number of full lines // Range {Any, Col} | // where Col is a number of columns of original buffer if (offset[1]) return newRange[0] == 1; return newRange[1] == parentRange[1]; } bool isContiguousRegion(const id<3> &offset, const range<3> &newRange, const range<3> &parentRange) { // For 3D sub buffer there are 3 cases: // 1) Offset {Any, Any, Any} | a piece of any line in any slice of a buffer // Range {1, 1, Any} | // 2) Offset {Any, Any, 0 } | any number of full lines in any slice // Range {1, Any, Col} | // 3) Offset {Any, 0, 0 } | any number of slices // Range {Any, Row, Col} | // where Row and Col are numbers of rows and columns of original buffer if (offset[2]) return newRange[0] == 1 && newRange[1] == 1; if (offset[1]) return newRange[0] == 1 && newRange[2] == parentRange[2]; return newRange[1] == parentRange[1] && newRange[2] == parentRange[2]; } }; #ifdef __cpp_deduction_guides template <class InputIterator, class AllocatorT> buffer(InputIterator, InputIterator, AllocatorT, const property_list & = {}) ->buffer<typename std::iterator_traits<InputIterator>::value_type, 1, AllocatorT>; template <class InputIterator> buffer(InputIterator, InputIterator, const property_list & = {}) ->buffer<typename std::iterator_traits<InputIterator>::value_type, 1>; template <class Container, class AllocatorT> buffer(Container &, AllocatorT, const property_list & = {}) ->buffer<typename Container::value_type, 1, AllocatorT>; template <class Container> buffer(Container &, const property_list & = {}) ->buffer<typename Container::value_type, 1>; template <class T, int dimensions, class AllocatorT> buffer(const T *, const range<dimensions> &, AllocatorT, const property_list & = {}) ->buffer<T, dimensions, AllocatorT>; template <class T, int dimensions> buffer(const T *, const range<dimensions> &, const property_list & = {}) ->buffer<T, dimensions>; #endif // __cpp_deduction_guides } // namespace sycl } // __SYCL_INLINE_NAMESPACE(cl) namespace std { template <typename T, int dimensions, typename AllocatorT> struct hash<cl::sycl::buffer<T, dimensions, AllocatorT>> { size_t operator()(const cl::sycl::buffer<T, dimensions, AllocatorT> &b) const { return hash<std::shared_ptr<cl::sycl::detail::buffer_impl>>()( cl::sycl::detail::getSyclObjImpl(b)); } }; } // namespace std
khengleng/khathor
hathor/cli/oracle_create_key.py
import base64 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import ec def main(): from hathor.cli.util import create_parser from hathor.crypto.util import get_hash160, get_private_key_bytes, get_public_key_bytes_compressed parser = create_parser() parser.add_argument('filepath', help='Create a new private key in the given file') args = parser.parse_args() new_key = ec.generate_private_key(ec.SECP256K1(), default_backend()) private_key_bytes = get_private_key_bytes(new_key) with open(args.filepath, 'w') as key_file: key_file.write(base64.b64encode(private_key_bytes).decode('utf-8')) print('key created!') public_key_bytes = get_public_key_bytes_compressed(new_key.public_key()) print('base64 pubkey hash:', base64.b64encode(get_hash160(public_key_bytes)).decode('utf-8'))
ravitejavalluri/catapult
dashboard/dashboard/update_test_suites_test.py
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest import webapp2 import webtest from google.appengine.ext import ndb from dashboard import update_test_suites from dashboard.common import datastore_hooks from dashboard.common import stored_object from dashboard.common import testing_common from dashboard.common import utils from dashboard.models import graph_data class ListTestSuitesTest(testing_common.TestCase): def setUp(self): super(ListTestSuitesTest, self).setUp() app = webapp2.WSGIApplication( [('/update_test_suites', update_test_suites.UpdateTestSuitesHandler)]) self.testapp = webtest.TestApp(app) datastore_hooks.InstallHooks() testing_common.SetIsInternalUser('<EMAIL>', True) self.UnsetCurrentUser() def testFetchCachedTestSuites_NotEmpty(self): # If the cache is set, then whatever's there is returned. key = update_test_suites._NamespaceKey( update_test_suites._LIST_SUITES_CACHE_KEY) stored_object.Set(key, {'foo': 'bar'}) self.assertEqual( {'foo': 'bar'}, update_test_suites.FetchCachedTestSuites()) def _AddSampleData(self): testing_common.AddTests( ['Chromium'], ['win7', 'mac'], { 'dromaeo': { 'dom': {}, 'jslib': {}, }, 'scrolling': { 'commit_time': { 'www.yahoo.com': {}, 'www.cnn.com': {}, }, 'commit_time_ref': {}, }, 'really': { 'nested': { 'very': { 'deeply': { 'subtest': {} } }, 'very_very': {} } }, }) def testPost_ForcesCacheUpdate(self): key = update_test_suites._NamespaceKey( update_test_suites._LIST_SUITES_CACHE_KEY) stored_object.Set(key, {'foo': 'bar'}) self.assertEqual( {'foo': 'bar'}, update_test_suites.FetchCachedTestSuites()) self._AddSampleData() # Because there is something cached, the cache is # not automatically updated when new data is added. self.assertEqual( {'foo': 'bar'}, update_test_suites.FetchCachedTestSuites()) # Making a request to /udate_test_suites forces an update. self.testapp.post('/update_test_suites') self.assertEqual( { 'dromaeo': { 'mas': {'Chromium': {'mac': False, 'win7': False}}, }, 'scrolling': { 'mas': {'Chromium': {'mac': False, 'win7': False}}, }, 'really': { 'mas': {'Chromium': {'mac': False, 'win7': False}}, }, }, update_test_suites.FetchCachedTestSuites()) def testPost_InternalOnly(self): self.SetCurrentUser('<EMAIL>') self._AddSampleData() master_key = ndb.Key('Master', 'Chromium') graph_data.Bot( id='internal_mac', parent=master_key, internal_only=True).put() graph_data.TestMetadata( id='Chromium/internal_mac/internal_test', internal_only=True).put() self.testapp.post('/update_test_suites?internal_only=true') self.assertEqual( { 'dromaeo': { 'mas': {'Chromium': {'mac': False, 'win7': False}}, }, 'internal_test': { 'mas': {'Chromium': {'internal_mac': False}}, }, 'scrolling': { 'mas': {'Chromium': {'mac': False, 'win7': False}}, }, 'really': { 'mas': {'Chromium': {'mac': False, 'win7': False}}, }, }, update_test_suites.FetchCachedTestSuites()) def testFetchCachedTestSuites_Empty_UpdatesWhenFetching(self): # If the cache is not set at all, then FetchCachedTestSuites # just updates the cache before returning the list. self._AddSampleData() self.assertEqual( { 'dromaeo': { 'mas': {'Chromium': {'mac': False, 'win7': False}}, }, 'scrolling': { 'mas': {'Chromium': {'mac': False, 'win7': False}}, }, 'really': { 'mas': {'Chromium': {'mac': False, 'win7': False}}, }, }, update_test_suites.FetchCachedTestSuites()) def testCreateTestSuitesDict(self): self._AddSampleData() # For one test suite, add a monitored test and set the suite as deprecated. # Only set it as deprecated on one of two bots; this test suite should not # be marked as deprecated in the response dict, but only the non-deprecated # bot (mac in the this sample data) should be listed. test = utils.TestKey('Chromium/win7/dromaeo').get() test.monitored = [utils.TestKey( 'Chromium/win7/dromaeo/commit_time/www.yahoo.com')] test.put() # For another test suite, set it as deprecated on both bots -- it should # be marked as deprecated in the response dict. for bot in ['win7', 'mac']: test = utils.TestKey('Chromium/%s/really' % bot).get() test.deprecated = True test.put() # Set the description string for two test suites on both bots. It doesn't # matter whether this description is set for both bots or just one. for test_path in ['Chromium/win7/scrolling', 'Chromium/mac/scrolling']: test = utils.TestKey(test_path).get() test.description = 'Description string.' test.put() self.assertEqual( { 'dromaeo': { 'mas': {'Chromium': {'mac': False, 'win7': False}}, 'mon': ['commit_time/www.yahoo.com'], }, 'scrolling': { 'mas': {'Chromium': {'mac': False, 'win7': False}}, 'des': 'Description string.', }, 'really': { 'dep': True, 'mas': {'Chromium': {'mac': True, 'win7': True}} }, }, update_test_suites._CreateTestSuiteDict()) def testFetchSuites(self): self._AddSampleData() suites = update_test_suites._FetchSuites() suite_keys = [s.key for s in suites] self.assertEqual( map(utils.TestKey, [ 'Chromium/mac/dromaeo', 'Chromium/mac/really', 'Chromium/mac/scrolling', 'Chromium/win7/dromaeo', 'Chromium/win7/really', 'Chromium/win7/scrolling', ]), suite_keys) def testCreateSuiteMastersDict(self): self._AddSampleData() suites = update_test_suites._FetchSuites() self.assertEqual( { 'dromaeo': {'Chromium': {'mac': False, 'win7': False}}, 'really': {'Chromium': {'mac': False, 'win7': False}}, 'scrolling': {'Chromium': {'mac': False, 'win7': False}}, }, update_test_suites._CreateSuiteMastersDict(suites)) def testMasterToBotsToDeprecatedDict(self): self._AddSampleData() suites = [ utils.TestKey('Chromium/mac/dromaeo').get(), utils.TestKey('Chromium/win7/dromaeo').get(), ] suites[0].deprecated = True suites[0].put() self.assertEqual( {'Chromium': {'mac': True, 'win7': False}}, update_test_suites._MasterToBotsToDeprecatedDict(suites)) def testCreateSuiteMonitoredDict(self): self._AddSampleData() test_win = utils.TestKey('Chromium/win7/dromaeo').get() test_win.monitored = [utils.TestKey( 'Chromium/win7/dromaeo/commit_time/www.yahoo.com')] test_win.put() test_mac = utils.TestKey('Chromium/mac/dromaeo').get() test_mac.monitored = [utils.TestKey( 'Chromium/mac/dromaeo/commit_time/www.cnn.com')] test_mac.put() self.assertEqual( { 'dromaeo': [ 'commit_time/www.cnn.com', 'commit_time/www.yahoo.com', ] }, update_test_suites._CreateSuiteMonitoredDict()) def testGetSubTestPath(self): key = utils.TestKey('Chromium/mac/my_suite/foo/bar') self.assertEqual('foo/bar', update_test_suites._GetTestSubPath(key)) def testCreateSuiteDescriptionDict(self): self._AddSampleData() suites = [] for test_path in ['Chromium/win7/dromaeo', 'Chromium/mac/dromaeo']: test = utils.TestKey(test_path).get() test.description = 'Foo.' test.put() suites.append(test) self.assertEqual( {'dromaeo': 'Foo.'}, update_test_suites._CreateSuiteDescriptionDict(suites)) if __name__ == '__main__': unittest.main()
ProjectFFF/FFF
closets/migrations/0006_newcloth_closet.py
<filename>closets/migrations/0006_newcloth_closet.py # Generated by Django 3.1.1 on 2020-10-21 12:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('closets', '0005_auto_20201014_0539'), ] operations = [ migrations.CreateModel( name='Newcloth_closet', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('cloth_name_c', models.CharField(max_length=255)), ('shoulder_c', models.DecimalField(decimal_places=3, max_digits=6)), ('chest_c', models.DecimalField(decimal_places=3, max_digits=6)), ('arm_c', models.DecimalField(decimal_places=3, max_digits=6)), ('total_length_c', models.DecimalField(decimal_places=3, max_digits=6)), ('image_c', models.ImageField(blank=True, null=True, upload_to='images/')), ('shopping_link_c', models.CharField(blank=True, max_length=255, null=True)), ('tag', models.CharField(blank=True, max_length=255, null=True)), ('review', models.CharField(blank=True, max_length=255, null=True)), ('pub_date', models.DateTimeField(blank=True, null=True, verbose_name='date published')), ], ), ]
uagg/SoftwareUniversity
3. Professional Module/Java Web Developer/1. Java Fundamentals/1. Java Advanced/07. Stream API/Lab/7. MapDistricts/src/Main.java
/* On the first line, you are given the population count of districts in different cities, separated by a single space in the format "city:district population". On the second line, you are given the minimum population for filtering of the towns. The population of a town is the sum of populations of all of its districts. Print all cities with population greater than a given. Sort cities and districts by descending population and print top 5 districts for a given city. */ import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Map<String, List<Integer>> cities = new HashMap<>(); List<String> tokens = Arrays.asList(scanner.nextLine().split("\\s+")); for (String token : tokens) { String[] tokenArgs = token.split(":"); String city = tokenArgs[0]; int districtPopulation = Integer.parseInt(tokenArgs[1]); cities.putIfAbsent(city, new ArrayList<>()); cities.get(city).add(districtPopulation); } int bound = Integer.valueOf(scanner.nextLine()); cities.entrySet() .stream() .filter(getFilterByPopulationPredicate(bound)) .sorted(getSortByDescendingPopulationComparator()) .forEach(getPrintMapEntryConsumer()); } public static Predicate<Map.Entry<String, List<Integer>>> getFilterByPopulationPredicate(int bound) { return kv -> kv.getValue().stream().mapToInt(Integer::valueOf).sum() >= bound; } public static Comparator<Map.Entry<String, List<Integer>>> getSortByDescendingPopulationComparator() { return (kv1, kv2) -> Integer.compare(kv2.getValue().stream().mapToInt(Integer::valueOf).sum(), kv1.getValue().stream().mapToInt(Integer::valueOf).sum()); } public static Consumer<Map.Entry<String, List<Integer>>> getPrintMapEntryConsumer() { return kv -> { System.out.print(kv.getKey() + ": "); kv.getValue() .stream() .sorted(Comparator.reverseOrder()) .limit(5) .forEach(dp -> System.out.print(dp + " ")); System.out.println(); }; } }
FunctionX/fx-wallet-android
libs_blockchain/src/main/java/com/pundix/core/binance/BinanceTransaction.java
<reponame>FunctionX/fx-wallet-android<filename>libs_blockchain/src/main/java/com/pundix/core/binance/BinanceTransaction.java package com.pundix.core.binance; import com.pundix.core.factory.ITransation; import com.pundix.core.factory.TransationData; import com.pundix.core.factory.TransationResult; import java.io.IOException; import java.security.NoSuchAlgorithmException; /** * @ClassName: BinanceTransaction * @Author: Joker * @Date: 2020/6/15 */ public class BinanceTransaction implements ITransation { @Override public TransationResult sendTransation(TransationData data) { TransationResult resp = new TransationResult(); //fee 37500 try { String transfer = BinanceServices.getInstance().transfer(data.getValue(), data.getFromAddress(), data.getToAddress(), data.getPrivateKey(), false); resp.setCode(0); resp.setHash(transfer); } catch (IOException | NoSuchAlgorithmException e) { e.printStackTrace(); resp.setCode(-1); } return resp; } @Override public String getBalance(String address) { return null; } }
szepeviktor/WebClient
src/app/organization/factories/organizationModel.js
<reponame>szepeviktor/WebClient<filename>src/app/organization/factories/organizationModel.js angular.module('proton.organization') .factory('organizationModel', (organizationApi, organizationKeysModel, setupKeys, authentication, $rootScope, gettextCatalog, CONSTANTS, notification, networkActivityTracker, changeOrganizationPasswordModal, loginPasswordModal, changeOrganizationPassword) => { let CACHE = {}; const I18N = { CREATE_ERROR: gettextCatalog.getString('Error during organization request', null, 'Error organization'), FETCH_ERROR: gettextCatalog.getString('Organization request failed', null, 'Error organization'), KEYS_ERROR: gettextCatalog.getString('Error during the generation of new organization keys', null, 'Error organization'), UPDATING_NAME_ERROR: gettextCatalog.getString('Error updating organization name', null, 'Error'), UPDATING_NAME_SUCCESS: gettextCatalog.getString('Organization updated', null, 'Info'), UPDATE_PASSWORD_SUCCESS: gettextCatalog.getString('Password updated', null, 'Info') }; const fakeOrganization = { PlanName: 'free', MaxMembers: 1, HasKeys: 0 }; const fakeResult = { data: { Code: 1000, Organization: fakeOrganization } }; const clear = () => (CACHE = {}); const get = (key = 'organization') => CACHE[key]; const set = (data = {}, key = 'organization') => { CACHE[key] = data; if (key === 'organization') { $rootScope.$emit('organizationChange', data); } }; const isFreePlan = () => (CACHE.organization || {}).PlanName === 'free'; function fetch() { if (authentication.user.Role === CONSTANTS.FREE_USER_ROLE) { set(fakeOrganization); return Promise.resolve(fakeResult); } return organizationApi.get() .then(({ data = {} } = {}) => { if (data.Code === 1000) { set(data.Organization); return data.Organization; } throw new Error(data.Error || I18N.FETCH_ERROR); }); } function create() { if (!isFreePlan()) { return Promise.resolve(); } generateKeys() .then(organizationApi.create) .then(({ data = {} } = {}) => { if (data.Code === 1000) { return data; } throw new Error(data.Error || I18N.CREATE_ERROR); }, () => { throw new Error(I18N.CREATE_ERROR); }); } function generateKeys() { if (!isFreePlan()) { return Promise.resolve(); } return setupKeys.generateOrganization(authentication.getPassword()) .then(({ privateKeyArmored: PrivateKey }) => ({ PrivateKey })) .catch(() => { throw new Error(I18N.KEYS_ERROR); }); } const saveName = (DisplayName) => { const promise = organizationApi.updateOrganizationName({ DisplayName }) .then(({ data = {} } = {}) => { if (data.Code === 1000) { return notification.success(I18N.UPDATING_NAME_SUCCESS); } throw new Error(data.Error || I18N.UPDATING_NAME_ERROR); }); networkActivityTracker.track(promise); }; const updatePassword = (newPassword) => { const submit = (Password, TwoFactorCode) => { const creds = { Password, TwoFactorCode }; const organizationKey = organizationKeysModel.get('organizationKey'); const promise = changeOrganizationPassword({ newPassword, creds, organizationKey }) .then(() => { notification.success(I18N.UPDATE_PASSWORD_SUCCESS); loginPasswordModal.deactivate(); }); networkActivityTracker.track(promise); }; loginPasswordModal.activate({ params: { submit, cancel() { loginPasswordModal.deactivate(); } } }); }; const changePassword = () => { changeOrganizationPasswordModal.activate({ params: { close(newPassword) { changeOrganizationPasswordModal.deactivate(); newPassword && updatePassword(newPassword); } } }); }; const changeKeys = organizationKeysModel.changeKeys; return { set, get, clear, isFreePlan, fetch, create, generateKeys, saveName, changePassword, changeKeys }; });
atsuky/RepoFIBtori
Obligatories/Q1/PRO1/CN1/P64976/prog1.cc
#include <iostream> using namespace std; //P64979 //pre: natural n. //post: escriure les n primeres linies de la taula de multiplicar de n. int main () { int n; cin >> n; for (int i = 1; i <= n; ++i) { cout << n << " x " << i << " = " << n*i << endl; } return 0; }
mengxy/swc
crates/swc/tests/tsc-references/checkJsdocTypeTag2_es5.2.minified.js
0..concat("hi");
maoa3/scalpel
psx/_dump_/43/_dump_ida_/overlay_d/make_psx.py
set_name(0x8014B488, "EA_cd_seek", SN_NOWARN) set_name(0x8014B490, "MY_CdGetSector", SN_NOWARN) set_name(0x8014B4C4, "init_cdstream", SN_NOWARN) set_name(0x8014B4D4, "flush_cdstream", SN_NOWARN) set_name(0x8014B4F8, "check_complete_frame", SN_NOWARN) set_name(0x8014B578, "reset_cdstream", SN_NOWARN) set_name(0x8014B5A0, "kill_stream_handlers", SN_NOWARN) set_name(0x8014B600, "stream_cdready_handler", SN_NOWARN) set_name(0x8014B7F4, "CD_stream_handler", SN_NOWARN) set_name(0x8014B8F4, "install_stream_handlers", SN_NOWARN) set_name(0x8014B964, "cdstream_service", SN_NOWARN) set_name(0x8014B9FC, "cdstream_get_chunk", SN_NOWARN) set_name(0x8014BB20, "cdstream_is_last_chunk", SN_NOWARN) set_name(0x8014BB38, "cdstream_discard_chunk", SN_NOWARN) set_name(0x8014BC38, "close_cdstream", SN_NOWARN) set_name(0x8014BCB0, "open_cdstream", SN_NOWARN) set_name(0x8014BE48, "set_mdec_img_buffer", SN_NOWARN) set_name(0x8014BE7C, "start_mdec_decode", SN_NOWARN) set_name(0x8014C000, "DCT_out_handler", SN_NOWARN) set_name(0x8014C09C, "init_mdec", SN_NOWARN) set_name(0x8014C10C, "init_mdec_buffer", SN_NOWARN) set_name(0x8014C128, "split_poly_area", SN_NOWARN) set_name(0x8014C518, "rebuild_mdec_polys", SN_NOWARN) set_name(0x8014C6EC, "clear_mdec_frame", SN_NOWARN) set_name(0x8014C6F8, "draw_mdec_polys", SN_NOWARN) set_name(0x8014CA44, "invalidate_mdec_frame", SN_NOWARN) set_name(0x8014CA58, "is_frame_decoded", SN_NOWARN) set_name(0x8014CA64, "init_mdec_polys", SN_NOWARN) set_name(0x8014CDF4, "set_mdec_poly_bright", SN_NOWARN) set_name(0x8014CE5C, "init_mdec_stream", SN_NOWARN) set_name(0x8014CEAC, "init_mdec_audio", SN_NOWARN) set_name(0x8014CFB0, "kill_mdec_audio", SN_NOWARN) set_name(0x8014CFE0, "stop_mdec_audio", SN_NOWARN) set_name(0x8014D004, "play_mdec_audio", SN_NOWARN) set_name(0x8014D278, "set_mdec_audio_volume", SN_NOWARN) set_name(0x8014D344, "resync_audio", SN_NOWARN) set_name(0x8014D370, "stop_mdec_stream", SN_NOWARN) set_name(0x8014D3BC, "dequeue_stream", SN_NOWARN) set_name(0x8014D4A8, "dequeue_animation", SN_NOWARN) set_name(0x8014D658, "decode_mdec_stream", SN_NOWARN) set_name(0x8014D844, "play_mdec_stream", SN_NOWARN) set_name(0x8014D8F8, "clear_mdec_queue", SN_NOWARN) set_name(0x8014D924, "StrClearVRAM", SN_NOWARN) set_name(0x8014D9E4, "PlayFMVOverLay", SN_NOWARN) set_name(0x8014DDEC, "GetDown__C4CPad", SN_NOWARN) set_name(0x8013AE8C, "map_buf", SN_NOWARN) set_name(0x80149E8C, "imgbuf", SN_NOWARN) set_name(0x80149EE0, "br", SN_NOWARN) set_name(0x8014A520, "tmdc_pol", SN_NOWARN) set_name(0x8014AB60, "mdc_buf", SN_NOWARN) set_name(0x8014AB70, "tmdc_pol_offs", SN_NOWARN) set_name(0x8014B1B0, "mdc_idx", SN_NOWARN) set_name(0x8014B1D8, "mdec_queue", SN_NOWARN) set_name(0x8014B318, "mdec_drenv", SN_NOWARN) set_name(0x8014B398, "stream_buf", SN_NOWARN) set_name(0x8014B410, "stream_bufh", SN_NOWARN)
samtsai/doi-extractives-data
scripts/jekyll-watch.js
<reponame>samtsai/doi-extractives-data<gh_stars>0 var child_process = require('child_process'); var chokidar = require('chokidar') // Run the given command with the given args in the given directory. // // Returns a Promise that resolves once the command is finished, or // rejects if the process errored or exited with a non-zero status code. function run(cwd, command, args) { var cmdline = `${cwd}/${command} ${args.join(' ')}`; return new Promise((resolve, reject) => { console.log(`Running ${cmdline}.`); const child = child_process.spawn(command, args, { cwd: cwd, stdio: 'inherit', }); child.on('error', reject); child.on('exit', code => { if (code === 0) { resolve(); } else { reject(`${cmdline} exited with code ${code}!`); } }); }); } function runJekyll() { return run('/doi', 'jekyll', ['build', '--incremental', '--config', '_config.yml,_config-dev.yml']) } // Make it easy for Docker to terminate us. process.on('SIGTERM', () => { // TODO: Consider waiting for children and/or terminating them. process.exit(0); }); var opts = { ignored: /(^|[\/\\])\..|_site|node_modules|sass|css|img|js|nrrd-design-system|styleguide|test/, usePolling: true } var watcher = chokidar.watch('/doi', opts) runJekyll().catch(e => console.error(e)) watcher.on('change', (path, event) => { console.log(`Change recognized: ${path}`) runJekyll().catch(e => console.error(e)) })
a4x4kiwi/Exo-CC
extensions/cce/src/main/jni/lib_ccx/output.c
#include "lib_ccx.h" #include "cce.h" #include "ccx_common_option.h" #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif void dinit_write(struct ccx_s_write *wb) { #ifdef PYTHON_API return; #else if (wb->fh > 0) close(wb->fh); freep(&wb->filename); if (wb->with_semaphore && wb->semaphore_filename) unlink(wb->semaphore_filename); freep(&wb->semaphore_filename); #endif } int temporarily_close_output(struct ccx_s_write *wb) { close(wb->fh); wb->fh = -1; wb->temporarily_closed = 1; return 0; } int temporarily_open_output(struct ccx_s_write *wb) { /* int t = 0; // Try a few times before giving up. This is because this close/open stuff exists for processes // that demand exclusive access to the file, so often we'll find out that we cannot reopen the // file immediately. while (t < 5 && wb->fh == -1) { wb->fh = open(wb->filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, S_IREAD | S_IWRITE); sleep(1); } if (wb->fh == -1) { return CCX_COMMON_EXIT_FILE_CREATION_FAILED; } wb->temporarily_closed = 0; return EXIT_OK;*/ return EXIT_OK; } int init_write(struct ccx_s_write *wb, char *filename, int with_semaphore) { return EXIT_OK; /*#ifdef PYTHON_API return EXIT_OK; #else memset(wb, 0, sizeof(struct ccx_s_write)); wb->fh = -1; wb->temporarily_closed = 0; wb->filename = filename; wb->with_semaphore = with_semaphore; wb->append_mode = ccx_options.enc_cfg.append_mode; if (!(wb->append_mode)) wb->fh = open(filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, S_IREAD | S_IWRITE); else wb->fh = open(filename, O_RDWR | O_CREAT | O_APPEND | O_BINARY, S_IREAD | S_IWRITE); wb->renaming_extension = 0; if (wb->fh == -1) { return CCX_COMMON_EXIT_FILE_CREATION_FAILED; } if (with_semaphore) { wb->semaphore_filename = (char *)malloc(strlen(filename) + 6); if (!wb->semaphore_filename) return EXIT_NOT_ENOUGH_MEMORY; sprintf(wb->semaphore_filename, "%s.sem", filename); int t = open(wb->semaphore_filename, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, S_IREAD | S_IWRITE); if (t == -1) { close(wb->fh); return CCX_COMMON_EXIT_FILE_CREATION_FAILED; } close(t); } return EXIT_OK; #endif*/ } int writeraw(const unsigned char *data, int length, void *private_data, struct cc_subtitle *sub) { unsigned char *sub_data = NULL; // Don't do anything for empty data if (data == NULL) return -1; sub->data = realloc(sub->data, length + sub->nb_data); if (!sub->data) return EXIT_NOT_ENOUGH_MEMORY; sub_data = sub->data; sub->datatype = CC_DATATYPE_GENERIC; memcpy(sub_data + sub->nb_data, data, length); sub->got_output = 1; sub->nb_data += length; sub->type = CC_RAW; return EXIT_SUCCESS; } void writeDVDraw(const unsigned char *data1, int length1, const unsigned char *data2, int length2, struct cc_subtitle *sub) { /* these are only used by DVD raw mode: */ static int loopcount = 1; /* loop 1: 5 elements, loop 2: 8 elements, loop 3: 11 elements, rest: 15 elements */ static int datacount = 0; /* counts within loop */ if (datacount == 0) { writeraw(DVD_HEADER, sizeof(DVD_HEADER), NULL, sub); if (loopcount == 1) writeraw(lc1, sizeof(lc1), NULL, sub); if (loopcount == 2) writeraw(lc2, sizeof(lc2), NULL, sub); if (loopcount == 3) { writeraw(lc3, sizeof(lc3), NULL, sub); if (data2 && length2) writeraw(data2, length2, NULL, sub); } if (loopcount > 3) { writeraw(lc4, sizeof(lc4), NULL, sub); if (data2 && length2) writeraw(data2, length2, NULL, sub); } } datacount++; writeraw(lc5, sizeof(lc5), NULL, sub); if (data1 && length1) writeraw(data1, length1, NULL, sub); if (((loopcount == 1) && (datacount < 5)) || ((loopcount == 2) && (datacount < 8)) || ((loopcount == 3) && (datacount < 11)) || ((loopcount > 3) && (datacount < 15))) { writeraw(lc6, sizeof(lc6), NULL, sub); if (data2 && length2) writeraw(data2, length2, NULL, sub); } else { if (loopcount == 1) { writeraw(lc6, sizeof(lc6), NULL, sub); if (data2 && length2) writeraw(data2, length2, NULL, sub); } loopcount++; datacount = 0; } } void printdata(struct lib_cc_decode *ctx, const unsigned char *data1, int length1, const unsigned char *data2, int length2, struct cc_subtitle *sub) { if (ctx->write_format == CCX_OF_DVDRAW) writeDVDraw(data1, length1, data2, length2, sub); else /* Broadcast raw or any non-raw */ { if (length1 && ctx->extract != 2) { ctx->current_field = 1; ctx->writedata(data1, length1, ctx, sub); } if (length2) { ctx->current_field = 2; if (ctx->extract != 1) ctx->writedata(data2, length2, ctx, sub); else // User doesn't want field 2 data, but we want XDS. { ctx->writedata(data2, length2, ctx, sub); } } } } /* Buffer data with the same FTS and write when a new FTS or data==NULL * is encountered */ void writercwtdata(struct lib_cc_decode *ctx, const unsigned char *data, struct cc_subtitle *sub) { static LLONG prevfts = -1; LLONG currfts = ctx->timing->fts_now + ctx->timing->fts_global; static uint16_t cbcount = 0; static int cbempty = 0; static unsigned char cbbuffer[0xFFFF * 3]; // TODO: use malloc static unsigned char cbheader[8 + 2]; if ((prevfts != currfts && prevfts != -1) || data == NULL || cbcount == 0xFFFF) { // Remove trailing empty or 608 padding caption blocks if (cbcount != 0xFFFF) { unsigned char cc_valid; unsigned char cc_type; int storecbcount = cbcount; for (int cb = cbcount - 1; cb >= 0; cb--) { cc_valid = (*(cbbuffer + 3 * cb) & 4) >> 2; cc_type = *(cbbuffer + 3 * cb) & 3; // The -fullbin option disables pruning of 608 padding blocks if ((cc_valid && cc_type <= 1 // Only skip NTSC padding packets && !ctx->fullbin // Unless we want to keep them && *(cbbuffer + 3 * cb + 1) == 0x80 && *(cbbuffer + 3 * cb + 2) == 0x80) || !(cc_valid || cc_type == 3)) // or unused packets { cbcount--; } else { cb = -1; } } dbg_print(CCX_DMT_CBRAW, "%s Write %d RCWT blocks - skipped %d padding / %d unused blocks.\n", print_mstime_static(prevfts), cbcount, storecbcount - cbcount, cbempty); } // New FTS, write data header // RCWT data header (10 bytes): //byte(s) value description //0-7 FTS int64_t number with current FTS //8-9 blocks Number of 3 byte data blocks with the same FTS that are // following this header memcpy(cbheader, &prevfts, 8); memcpy(cbheader + 8, &cbcount, 2); if (cbcount > 0) { ctx->writedata(cbheader, 10, ctx->context_cc608_field_1, sub); ctx->writedata(cbbuffer, 3 * cbcount, ctx->context_cc608_field_1, sub); } cbcount = 0; cbempty = 0; } if (data) { // Store the data while the FTS is unchanged unsigned char cc_valid = (*data & 4) >> 2; unsigned char cc_type = *data & 3; // Store only non-empty packets if (cc_valid || cc_type == 3) { // Store in buffer until we know how many blocks come with // this FTS. memcpy(cbbuffer + cbcount * 3, data, 3); cbcount++; } else { cbempty++; } } else { // Write a padding block for field 1 and 2 data if this is the final // call to this function. This forces the RCWT file to have the // same length as the source video file. // currfts currently holds the end time, subtract one block length // so that the FTS corresponds to the time before the last block is // written currfts -= 1001 / 30; memcpy(cbheader, &currfts, 8); cbcount = 2; memcpy(cbheader + 8, &cbcount, 2); memcpy(cbbuffer, "\x04\x80\x80", 3); // Field 1 padding memcpy(cbbuffer + 3, "\x05\x80\x80", 3); // Field 2 padding ctx->writedata(cbheader, 10, ctx->context_cc608_field_1, sub); ctx->writedata(cbbuffer, 3 * cbcount, ctx->context_cc608_field_1, sub); cbcount = 0; cbempty = 0; dbg_print(CCX_DMT_CBRAW, "%s Write final padding RCWT blocks.\n", print_mstime_static(currfts)); } prevfts = currfts; }
doggan/code-dump
tetris/java_src/hope/Actor.java
package hope; public abstract class Actor { private String actorLevel; public String getActorLevel() { return actorLevel; } public Actor(String actorLevel) { this.actorLevel = actorLevel; // Register. Application.getInstance().getActorCollector().registerActor(this); } private boolean mIsKilled = false; public boolean IsKilled() { return mIsKilled; } public void Kill() { mIsKilled = true; } protected void finalize() throws Throwable { try { // Unregister. // Application.getInstance().getActorCollector().unregisterActor(this); } finally { super.finalize(); } } protected void update(float timeStep) { } }
jolkdarr/ithaka-digraph
src/main/java/de/odysseus/ithaka/digraph/DigraphProvider.java
<filename>src/main/java/de/odysseus/ithaka/digraph/DigraphProvider.java /* * Copyright 2012 Odysseus Software GmbH * * 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 de.odysseus.ithaka.digraph; /** * Digraph provider interface. * * @param <T> digraph sub-type * @param <G> digraph type */ public interface DigraphProvider<T, G extends Digraph<?,?>> { /** * Get a digraph. * @param value value associated with a digraph * @return digraph */ public G get(T value); }
Ronald545/sambal-sos-app
packages/server/src/controllers/flag.controller.js
const logger = require("../../winston-config"); const db = require("../models"); const sequelize = require("sequelize"); const moment = require("moment"); // TODO: only send back reports made in the past week /** * @swagger * * paths: * /api/flag/getall: * get: * description: Get All flags in DB * tags: * - Flag * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * offset: * type: integer * limit: * type: integer * responses: * 200: * description: sucessfully gotten all flags * content: * application/json: * schema: * type: array * items: * type: object * properties: * id: * type: string * format: uuid * coordinates: * type: object * properties: * coordinates: * type: array * items: * type: integer * example: [0, 0] * * address: * type: string * description: * type: string * image: * type: string * status: * type: string * enum: ['PENDING', 'APPROVED', 'UNDER REVIEW', 'REJECTED'] * 500: * description: Error * */ module.exports.getAllFlags = (req, res) => { const { offset, limit } = req.body; db.flag .findAll({ limit: !limit ? null : limit, offset: !offset ? null : offset, where: { status: "APPROVED", updatedAt: { [sequelize.Op.gte]: moment().subtract(7, "days").toDate(), }, }, }) .then((flags) => { res.status(200).json(flags); }) .catch((err) => { res.status(500).send(err); }); }; // get flags within a radius /** * @swagger * * paths: * /api/flag/getallinradius: * get: * description: Get All flags in the radius of user * tags: * - Flag * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * radius: * type: integer * longitude: * type: number * latitude: * type: number * responses: * 200: * description: sucessfully gotten all flags * content: * application/json: * schema: * type: array * items: * type: object * properties: * id: * type: string * format: uuid * coordinates: * type: object * properties: * coordinates: * type: array * items: * type: integer * example: [0, 0] * * address: * type: string * description: * type: string * image: * type: string * status: * type: string * enum: ['PENDING', 'APPROVED', 'UNDER REVIEW', 'REJECTED'] * 500: * description: Error * */ // TODO: debug this module.exports.getAllFlagsInRadius = async (req, res) => { const { radius, latitude, longitude } = req.body; db.flag .findAll({ attributes: [ [ sequelize.literal( "6371 * acos(cos(radians(" + latitude + ")) * cos(radians(ST_X(coordinates))) * cos(radians(" + longitude + ") - radians(ST_Y(coordinates))) + sin(radians(" + latitude + ")) * sin(radians(ST_X(coordinates))))" ), "distance", ], ], order: sequelize.col("distance"), limit: 10, }) .then((inRadius) => { res.status(200).send(inRadius); }); }; // create new flag /** * @swagger * * paths: * /api/flag/createflag: * post: * description: Create a new flag * tags: * - Flag * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * longitude: * type: number * latitude: * type: number * description: * type: string * image: * type: string * responses: * 200: * description: sucessfully created a new flag * content: * application/json: * schema: * type: object * properties: * id: * type: string * format: uuid * coordinates: * type: object * properties: * coordinates: * type: array * items: * type: integer * example: [0, 0] * * address: * type: string * description: * type: string * image: * type: string * status: * type: string * enum: ['PENDING', 'APPROVED', 'UNDER REVIEW', 'REJECTED'] * 500: * description: Error * */ module.exports.createFlag = (req, res) => { // for now, send from frontend // after this, take the ID from JWT const { latitude, longitude, description, image, phonenumber } = req.body; const userId = req.decoded.data; const coordinates = { type: "Point", coordinates: [latitude, longitude], }; db.flag .create({ description: description, coordinates, userId, minioimage: image, phonenumber: phonenumber !== "" ? phonenumber : null, status: "PENDING", type: req.body.type !== undefined ? req.body.type : "GENERAL", }) .then((newFlag) => res.status(200).send(newFlag)) .catch((err) => { res.status(500).send(err); }); }; /** * @swagger * * paths: * /api/flag/getapproved: * get: * description: Get All Approved flags in DB * tags: * - Flag * requestBody: * required: true * content: * application/json: * schema: * type: object * properties: * offset: * type: integer * limit: * type: integer * responses: * 200: * description: sucessfully gotten all flags * content: * application/json: * schema: * type: array * items: * type: object * properties: * id: * type: string * format: uuid * coordinates: * type: object * properties: * coordinates: * type: array * items: * type: integer * example: [0, 0] * * address: * type: string * description: * type: string * image: * type: string * status: * type: string * enum: ['PENDING', 'APPROVED', 'UNDER REVIEW', 'REJECTED'] * 500: * description: Error * */ module.exports.getApprovedFlags = (req, res) => { const { offset, limit } = req.body; db.flag .findAll({ limit: !limit ? null : limit, offset: !offset ? null : offset, where: { status: "APPROVED", }, }) .then((flags) => { res.status(200).send(flags); }) .catch((err) => { res.status(500).send(err); }); }; // Delete this soon // module.exports.createTestFlag = (req, res) => { // let point = { type: "Point", coordinates: [39.807222, -76.984722] }; // db.flag // .create({ // coordinates: point, // description: "Test Description", // userId: "", // }) // .then((newFlag) => res.status(200).send(newFlag)) // .catch(err => { // res.status(500).send(err); // }) // };
polsevev/test262
test/built-ins/Temporal/PlainYearMonth/prototype/toPlainDate/argument-not-object.js
<filename>test/built-ins/Temporal/PlainYearMonth/prototype/toPlainDate/argument-not-object.js // Copyright (C) 2021 Igalia, S.L. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-temporal.plainyearmonth.prototype.toplaindate description: Throws a TypeError if the argument is not an Object, before any other observable actions includes: [compareArray.js, temporalHelpers.js] features: [BigInt, Symbol, Temporal] ---*/ [null, undefined, true, 3.1416, "a string", Symbol("symbol"), 7n].forEach((primitive) => { const calendar = TemporalHelpers.calendarThrowEverything(); const plainYearMonth = new Temporal.PlainYearMonth(2000, 5, calendar); assert.throws(TypeError, () => plainYearMonth.toPlainDate(primitive)); });
dashevo/dashpay-wallet-OLD
src/libraries/styles/types.js
/** * Copyright (c) 2014-present, Dash Core Group, Inc. * * @flow */ export type State = {}; export type Props = {};
brtjkzl/jottings
app/assets/javascripts/components/dropdown/toggle.js
<filename>app/assets/javascripts/components/dropdown/toggle.js Vue.component('dropdown-toggle', { computed: { isVisible: { get() { return this.$parent.isVisible; }, set(newValue) { App.bus.$emit("closeDropdowns"); this.$parent.isVisible = newValue; } } }, template: ` <a class="dropdown-toggle" @click.stop="isVisible = !isVisible"> <slot></slot> </a> ` });
zn0507/config-keeper
suixingpay-config-server/src/main/java/com/suixingpay/config/server/exception/ConfigException.java
package com.suixingpay.config.server.exception; import com.suixingpay.config.common.to.ResponseDTO; /** * @author: qiujiayu[<EMAIL>] * @date: 2017年8月30日 下午2:55:59 * @version: V1.0 * @review: qiujiayu[<EMAIL>]/2017年8月30日 下午2:55:59 */ public class ConfigException extends Exception { private static final long serialVersionUID = 1L; private final ResponseDTO<Object> response = new ResponseDTO<Object>(); public ConfigException() { super(); } public ConfigException(Exception e) { super(e); addErrorMessage(e.getMessage()); } public ConfigException(String message) { super(message); addErrorMessage(message); } public ConfigException(String paramName, String message) { super(message); addErrorMessage(paramName, message); } /** * 添加错误消息 * * @param message 错误信息 */ public void addErrorMessage(String message) { response.addErrorMessage(message); } /** * 增加非法参数错误信息 * * @param paramName 错误名称 * @param message 错误信息 */ public void addErrorMessage(String paramName, String message) { response.addErrorMessage(paramName, message); } public ResponseDTO<Object> getResponse() { return response; } @Override public String getMessage() { if (response.hasError()) { return response.getErrorMessage(); } return super.getMessage(); } public boolean hasError() { return response.hasError(); } }
Spruik/libre-common
common/core/domain/calendar_test.go
<reponame>Spruik/libre-common<filename>common/core/domain/calendar_test.go package domain import ( "fmt" "testing" "time" ) func mustMakeTime(str string) (t time.Time) { t, _ = time.Parse(time.RFC3339, str) return t } type weekdaySliceAsIntsTestCase struct { Name string Weekdays []Weekday Expected []int } var weekdaySliceAsIntsTestCases = []weekdaySliceAsIntsTestCase{ { Name: "Simple WeekdaySliceAsInts Test", Weekdays: []Weekday{Monday, Tuesday, Thursday, Sunday}, Expected: []int{1, 2, 4, 0}, }, } func TestWeekdaySliceAsIntsTestCases(t *testing.T) { for _, tc := range weekdaySliceAsIntsTestCases { result := WeekdaySliceAsInts(tc.Weekdays) for i := range result { if result[i] != tc.Expected[i] { t.Errorf("Test Case '%s': at index %d got %d; want %d", tc.Name, i, result[i], tc.Expected[i]) } } } t.Log("Complete TestWeekdaySliceAsIntsTestCases") } type compareWorkCalendarEntryTypeTestCase struct { Name string Old WorkCalendarEntryType New WorkCalendarEntryType Expected WorkCalendarEntryType Changed bool } // Test cases to compare two WorkCalendarEntryTypes to determine presedence var compareWorkCalendarEntryTypeTestCases = []compareWorkCalendarEntryTypeTestCase{ { Name: "Same", Old: PlannedShutdown, New: PlannedShutdown, Expected: PlannedShutdown, Changed: false, }, { Name: "Transition PlannedShutdown to PlannedBusytime", Old: PlannedShutdown, New: PlannedBusyTime, Expected: PlannedBusyTime, Changed: true, }, { Name: "Transition PlannedBusytime to PlannedShutdown", Old: PlannedBusyTime, New: PlannedShutdown, Expected: PlannedBusyTime, Changed: false, }, { Name: "Transition PlannedShutdown to PlannedDowntime", Old: PlannedShutdown, New: PlannedDowntime, Expected: PlannedDowntime, Changed: true, }, { Name: "Transition PlannedDowntime to PlannedBusyTime", Old: PlannedDowntime, New: PlannedBusyTime, Expected: PlannedBusyTime, Changed: true, }, { Name: "Transition PlannedDowntime to PlannedBusyTime", Old: PlannedBusyTime, New: PlannedDowntime, Expected: PlannedBusyTime, Changed: false, }, } func TestCompareWorkCalendarEntryType(t *testing.T) { for _, tc := range compareWorkCalendarEntryTypeTestCases { changed, result := CompareWorkCalendarEntryType(tc.Old, tc.New) if result != tc.Expected { t.Errorf("Test Case '%s': got %s; want %s", tc.Name, result, tc.Expected) } if changed != tc.Changed { t.Errorf("Test Case '%s': got %t; want %t", tc.Name, changed, tc.Changed) } } t.Log("Complete TestCompareWorkCalendarEntryType") } type entryTestCase struct { Name string WorkCalendar WorkCalendar Now time.Time Entries []WorkCalendarEntry Error bool } var entryTestCases = []entryTestCase{ { Name: "WorkCalendar No Definitions", WorkCalendar: WorkCalendar{ ID: "abc123", IsActive: true, Name: "Work Calendar - No Definitions", Description: "Description", Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, Definition: []WorkCalendarDefinitionEntry{}, }, Now: mustMakeTime("2021-08-13T00:00:00Z"), Entries: []WorkCalendarEntry{}, Error: false, }, { Name: "WorkCalendar Single Definition", WorkCalendar: WorkCalendar{ ID: "abc123", IsActive: true, Name: "Work Calendar - Single Definition", Description: "Description", Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, Definition: []WorkCalendarDefinitionEntry{ { ID: "abc123", IsActive: true, Description: "Shift A", Freq: Weekly, StartDateTime: mustMakeTime("2021-01-01T00:00:00Z"), EndDateTime: mustMakeTime("2022-01-01T00:00:00Z"), Count: 365, Interval: 0, Weekday: Monday, ByWeekDay: []Weekday{Monday, Tuesday, Wednesday, Thursday, Friday}, ByMonth: []int{}, BySetPos: []int{}, ByMonthDay: []int{}, ByWeekNo: []int{}, ByHour: []int{8}, ByMinute: []int{0}, BySecond: []int{0}, ByYearDay: []int{}, Duration: "PT8H", EntryType: PlannedBusyTime, }, }, }, Now: mustMakeTime("2021-08-13T12:00:00Z"), Entries: []WorkCalendarEntry{ { ID: "abc123", IsActive: true, Description: "Shift A", StartDateTime: mustMakeTime("2021-08-13T08:00:00Z"), EndDateTime: mustMakeTime("2021-08-13T16:00:00Z"), EntryType: PlannedBusyTime, }, }, Error: false, }, { Name: "WorkCalendar Single Definition query before", WorkCalendar: WorkCalendar{ ID: "abc123", IsActive: true, Name: "Work Calendar - Single Definition", Description: "Description", Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, Definition: []WorkCalendarDefinitionEntry{ { ID: "abc123", IsActive: true, Description: "Shift A", Freq: Weekly, StartDateTime: mustMakeTime("2021-01-01T00:00:00Z"), EndDateTime: mustMakeTime("2022-01-01T00:00:00Z"), Count: 365, Interval: 0, Weekday: Monday, ByWeekDay: []Weekday{Monday, Tuesday, Wednesday, Thursday, Friday}, ByMonth: []int{}, BySetPos: []int{}, ByMonthDay: []int{}, ByWeekNo: []int{}, ByHour: []int{8}, ByMinute: []int{0}, BySecond: []int{0}, ByYearDay: []int{}, Duration: "PT8H", EntryType: PlannedBusyTime, }, }, }, Now: mustMakeTime("2020-01-01T01:00:00Z"), Entries: []WorkCalendarEntry{}, Error: false, }, { Name: "WorkCalendar Single Definition query after", WorkCalendar: WorkCalendar{ ID: "abc123", IsActive: true, Name: "Work Calendar - Single Definition", Description: "Description", Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, Definition: []WorkCalendarDefinitionEntry{ { ID: "abc123", IsActive: true, Description: "Shift A", Freq: Daily, StartDateTime: mustMakeTime("2021-01-01T00:00:00Z"), EndDateTime: mustMakeTime("2022-01-01T00:00:00Z"), Count: 365, Interval: 0, Weekday: Monday, ByWeekDay: []Weekday{Monday, Tuesday, Wednesday, Thursday, Friday}, ByMonth: []int{}, BySetPos: []int{}, ByMonthDay: []int{}, ByWeekNo: []int{}, ByHour: []int{8}, ByMinute: []int{0}, BySecond: []int{0}, ByYearDay: []int{}, Duration: "PT8H", EntryType: PlannedBusyTime, }, }, }, Now: mustMakeTime("2023-01-01T01:00:00Z"), Entries: []WorkCalendarEntry{}, Error: false, }, { Name: "WorkCalendar Single Definition - Time aligns at start of first calendar entry", WorkCalendar: WorkCalendar{ ID: "abc123", IsActive: true, Name: "Work Calendar - Single Definition", Description: "Description", Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, Definition: []WorkCalendarDefinitionEntry{ { ID: "abc123", IsActive: true, Description: "Shift A", Freq: Weekly, StartDateTime: mustMakeTime("2021-01-04T08:00:00Z"), EndDateTime: mustMakeTime("2022-01-01T00:00:00Z"), Count: 365, Interval: 0, Weekday: Monday, ByWeekDay: []Weekday{Monday, Tuesday, Wednesday, Thursday, Friday}, ByMonth: []int{}, BySetPos: []int{}, ByMonthDay: []int{}, ByWeekNo: []int{}, ByHour: []int{8}, ByMinute: []int{0}, BySecond: []int{0}, ByYearDay: []int{}, Duration: "PT8H", EntryType: PlannedBusyTime, }, }, }, Now: mustMakeTime("2021-01-04T08:00:00Z"), Entries: []WorkCalendarEntry{ { ID: "abc123", IsActive: true, Description: "Shift A", StartDateTime: mustMakeTime("2021-01-04T08:00:00Z"), EndDateTime: mustMakeTime("2021-01-04T16:00:00Z"), EntryType: PlannedBusyTime, }, }, Error: false, }, { Name: "WorkCalendar Single Definition - Time aligns at end of first calendar entry", WorkCalendar: WorkCalendar{ ID: "abc123", IsActive: true, Name: "Work Calendar - Single Definition", Description: "Description", Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, Definition: []WorkCalendarDefinitionEntry{ { ID: "abc123", IsActive: true, Description: "Shift A", Freq: Weekly, StartDateTime: mustMakeTime("2021-01-04T08:00:00Z"), EndDateTime: mustMakeTime("2022-01-01T00:00:00Z"), Count: 365, Interval: 0, Weekday: Monday, ByWeekDay: []Weekday{Monday, Tuesday, Wednesday, Thursday, Friday}, ByMonth: []int{}, BySetPos: []int{}, ByMonthDay: []int{}, ByWeekNo: []int{}, ByHour: []int{8}, ByMinute: []int{0}, BySecond: []int{0}, ByYearDay: []int{}, Duration: "PT8H", EntryType: PlannedBusyTime, }, }, }, Now: mustMakeTime("2021-01-04T16:00:00Z"), Entries: []WorkCalendarEntry{}, Error: false, }, { Name: "WorkCalendar Daily with EndDateTIme", WorkCalendar: WorkCalendar{ ID: "abc123", IsActive: true, Name: "Work Calendar - Daily with EndDateTIme", Description: "Description", Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, Definition: []WorkCalendarDefinitionEntry{ { ID: "abc123", IsActive: true, Description: "Daily Shift", Freq: Daily, StartDateTime: mustMakeTime("2021-01-01T08:00:00Z"), EndDateTime: mustMakeTime("2021-01-07T08:00:00Z"), Count: 0, Interval: 0, Weekday: Monday, ByWeekDay: []Weekday{Monday, Tuesday, Wednesday, Thursday, Friday}, ByMonth: []int{}, BySetPos: []int{}, ByMonthDay: []int{}, ByWeekNo: []int{}, ByHour: []int{}, ByMinute: []int{}, BySecond: []int{}, ByYearDay: []int{}, Duration: "PT8H", EntryType: PlannedBusyTime, }, }, }, Now: mustMakeTime("2021-01-04T12:00:00Z"), Entries: []WorkCalendarEntry{ { ID: "abc123", IsActive: true, Description: "Daily Shift", StartDateTime: mustMakeTime("2021-01-04T08:00:00Z"), EndDateTime: mustMakeTime("2021-01-04T16:00:00Z"), EntryType: PlannedBusyTime, }, }, Error: false, }, { Name: "WorkCalendar Daily with Count", WorkCalendar: WorkCalendar{ ID: "abc123", IsActive: true, Name: "Work Calendar - Daily with EndDateTIme", Description: "Description", Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, Definition: []WorkCalendarDefinitionEntry{ { ID: "abc123", IsActive: true, Description: "Daily Shift", Freq: Daily, StartDateTime: mustMakeTime("2021-01-01T08:00:00Z"), EndDateTime: mustMakeTime("0001-01-01T00:00:00Z"), Count: 20, Interval: 0, Weekday: Monday, ByWeekDay: []Weekday{Monday, Tuesday, Wednesday, Thursday, Friday}, ByMonth: []int{}, BySetPos: []int{}, ByMonthDay: []int{}, ByWeekNo: []int{}, ByHour: []int{}, ByMinute: []int{}, BySecond: []int{}, ByYearDay: []int{}, Duration: "PT8H", EntryType: PlannedBusyTime, }, }, }, Now: mustMakeTime("2021-01-06T12:12:12Z"), Entries: []WorkCalendarEntry{ { ID: "abc123", IsActive: true, Description: "Daily Shift", StartDateTime: mustMakeTime("2021-01-06T08:00:00Z"), EndDateTime: mustMakeTime("2021-01-06T16:00:00Z"), EntryType: PlannedBusyTime, }, }, Error: false, }, } func TestWorkCalendarGetEntriesAtTime(t *testing.T) { for _, tc := range entryTestCases { entries, err := tc.WorkCalendar.GetEntriesAtTime(tc.Now) // Expect Error if tc.Error && err == nil { t.Errorf("Test Case '%s': got no error; want error", tc.Name) } // Don't Expect Error if !tc.Error && err != nil { t.Errorf("Test Case '%s': got error: %s; want no error", tc.Name, err) } // Expect Same Entry Count if len(entries) != len(tc.Entries) { t.Errorf("Test Case '%s': got %d entries; want %d", tc.Name, len(entries), len(tc.Entries)) } // Expect Same Entries for _, expectedEntry := range tc.Entries { found := false for _, actualEntry := range entries { if expectedEntry.Description == actualEntry.Description && expectedEntry.StartDateTime.Equal(actualEntry.StartDateTime) && expectedEntry.EndDateTime.Equal(actualEntry.EndDateTime) && actualEntry.EntryType == expectedEntry.EntryType { found = true break } } if !found { t.Errorf("Test Case '%s': expected to find entry %v; but didn't", tc.Name, expectedEntry) } } } t.Log("Complete TestWorkCalendarGetEntries") } type getEntriesAtTimeTestCase struct { Name string WorkCalendar WorkCalendar Entries []WorkCalendarEntry Error bool } var getEntriesAtTimeTestCases = []getEntriesAtTimeTestCase{ { Name: "No Definitions - Empty Entries", WorkCalendar: WorkCalendar{ ID: "test", IsActive: true, Name: "Test", Description: "Test GetCurrentEntryType", Definition: []WorkCalendarDefinitionEntry{}, Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, }, Entries: []WorkCalendarEntry{}, Error: false, }, { Name: "One Definition, One Entry", WorkCalendar: WorkCalendar{ ID: "0x123", IsActive: true, Name: "Test", Description: "Test GetCurrentEntryType", Definition: []WorkCalendarDefinitionEntry{ { ID: "0x124", IsActive: true, Description: "Shift A", Freq: Daily, StartDateTime: mustMakeTime("2021-08-16T08:00:00Z"), EndDateTime: mustMakeTime("2021-08-17T08:00:00Z"), Count: 1, Interval: 1, Weekday: Monday, ByWeekDay: []Weekday{Monday}, ByMonth: []int{}, BySetPos: []int{}, ByMonthDay: []int{}, ByWeekNo: []int{}, ByHour: []int{}, ByMinute: []int{}, BySecond: []int{}, ByYearDay: []int{}, Duration: "PT8H", EntryType: PlannedBusyTime, }, }, Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, }, Entries: []WorkCalendarEntry{ { ID: "", IsActive: true, Description: "Shift A", StartDateTime: mustMakeTime("2021-08-16T08:00:00Z"), EndDateTime: mustMakeTime("2021-08-16T16:00:00Z"), EntryType: PlannedBusyTime, }, }, Error: false, }, } func TestGetEntriesAtTime(t *testing.T) { for _, tc := range getEntriesAtTimeTestCases { entries, err := tc.WorkCalendar.GetEntriesAtTime(mustMakeTime("2021-08-16T11:00:00Z")) if tc.Error && err == nil || !tc.Error && err != nil { var expected string if tc.Error { expected = " " } else { expected = "no " } var got string if err == nil { got = "no error" } else { got = fmt.Sprintf("%s", err) } t.Errorf("Test Case '%s': expected %serror, got %s", tc.Name, expected, got) } if len(entries) != len(tc.Entries) { t.Errorf("Test Case '%s': expected %d entries, got %d", tc.Name, len(tc.Entries), len(entries)) } else { for i := range entries { if entries[i] != tc.Entries[i] { t.Errorf("Test Case '%s': index %d want %v; got %v", tc.Name, i, tc.Entries[i], entries[i]) } } } } t.Log("Complete TestGetCurrentEntryType") } func TestGetCurrentEntryType(t *testing.T) { now := time.Now().UTC() var wkd Weekday switch now.Weekday() { case time.Sunday: wkd = Sunday case time.Monday: wkd = Monday case time.Tuesday: wkd = Tuesday case time.Wednesday: wkd = Wednesday case time.Thursday: wkd = Thursday case time.Friday: wkd = Friday case time.Saturday: wkd = Saturday } workCalendar := WorkCalendar{ ID: "test", Name: "Test", IsActive: true, Description: "Test Work Calendar", Definition: []WorkCalendarDefinitionEntry{ { ID: "Test", IsActive: true, Description: "test", Freq: Daily, StartDateTime: now.Add(-1 * 24 * time.Hour), EndDateTime: now.Add(30 * 24 * time.Hour), Count: 35, Interval: 1, Weekday: wkd, ByWeekDay: []Weekday{}, ByMonth: []int{}, BySetPos: []int{}, ByMonthDay: []int{}, ByWeekNo: []int{}, ByHour: []int{}, ByMinute: []int{}, BySecond: []int{}, ByYearDay: []int{}, Duration: "PT8H", EntryType: PlannedBusyTime, }, }, Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, } entryType, names, err := workCalendar.GetCurrentEntryTypeAndNames() if err != nil { t.Errorf("Failed to GetCurrentEntryType. Expected no error got %s", err) } if entryType != PlannedBusyTime { t.Errorf("Failed to GetCurrentEntryType") } for _, name := range names { if name != "test" { t.Errorf("Failed to get names of GetCurrentEntryType") } } } var testCasesGetEntries = []entryTestCase{ { Name: "Fortnightly Shift Pattern 12H Shifts, 3-2-2-3-2-2", WorkCalendar: WorkCalendar{ ID: "0x456", IsActive: true, Name: "<NAME>", Description: "Fortnightly Shift Pattern 12H Shifts, 3-2-2-3-2-2", Definition: []WorkCalendarDefinitionEntry{ { ID: "0x124", IsActive: true, Description: "Shift A - Odd", Freq: Daily, StartDateTime: mustMakeTime("2021-08-30T11:00:00Z"), EndDateTime: mustMakeTime("2021-10-04T11:00:00Z"), Count: 0, Interval: 0, Weekday: Sunday, ByWeekDay: []Weekday{Monday, Saturday, Wednesday, Tuesday}, ByMonth: []int{}, BySetPos: []int{}, ByMonthDay: []int{}, ByWeekNo: []int{43, 51, 49, 47, 41, 39, 35, 37, 45}, ByHour: []int{}, ByMinute: []int{}, BySecond: []int{}, ByYearDay: []int{}, Duration: "PT12H", EntryType: PlannedBusyTime, }, { ID: "0x125", IsActive: true, Description: "Shift A - Even", Freq: Daily, StartDateTime: mustMakeTime("2021-08-30T11:00:00Z"), EndDateTime: mustMakeTime("2021-10-04T11:00:00Z"), Count: 0, Interval: 0, Weekday: Sunday, ByWeekDay: []Weekday{Thursday, Sunday, Friday}, ByMonth: []int{}, BySetPos: []int{}, ByMonthDay: []int{}, ByWeekNo: []int{38, 40, 50, 48, 46, 44, 52, 42, 36}, ByHour: []int{}, ByMinute: []int{}, BySecond: []int{}, ByYearDay: []int{}, Duration: "PT12H", EntryType: PlannedBusyTime, }, }, Entries: []WorkCalendarEntry{}, Equipment: []Equipment{}, }, Now: mustMakeTime("2021-09-15T12:12:12Z"), Entries: []WorkCalendarEntry{ { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-08-30T11:00:00Z"), EndDateTime: mustMakeTime("2021-08-30T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-08-31T11:00:00Z"), EndDateTime: mustMakeTime("2021-08-31T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-09-01T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-01T23:00:00Z"), EntryType: PlannedBusyTime, }, // Off for two { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-09-04T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-04T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Even", StartDateTime: mustMakeTime("2021-09-05T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-05T23:00:00Z"), EntryType: PlannedBusyTime, }, // Off for three { ID: "", IsActive: true, Description: "Shift A - Even", StartDateTime: mustMakeTime("2021-09-09T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-09T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Even", StartDateTime: mustMakeTime("2021-09-10T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-10T23:00:00Z"), EntryType: PlannedBusyTime, }, // Off for two { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-09-13T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-13T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-09-14T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-14T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-09-15T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-15T23:00:00Z"), EntryType: PlannedBusyTime, }, // off for two { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-09-18T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-18T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Even", StartDateTime: mustMakeTime("2021-09-19T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-19T23:00:00Z"), EntryType: PlannedBusyTime, }, // off for three { ID: "", IsActive: true, Description: "Shift A - Even", StartDateTime: mustMakeTime("2021-09-23T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-23T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Even", StartDateTime: mustMakeTime("2021-09-24T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-24T23:00:00Z"), EntryType: PlannedBusyTime, }, // off for two { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-09-27T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-27T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-09-28T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-28T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-09-29T11:00:00Z"), EndDateTime: mustMakeTime("2021-09-29T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Odd", StartDateTime: mustMakeTime("2021-10-02T11:00:00Z"), EndDateTime: mustMakeTime("2021-10-02T23:00:00Z"), EntryType: PlannedBusyTime, }, { ID: "", IsActive: true, Description: "Shift A - Even", StartDateTime: mustMakeTime("2021-10-03T11:00:00Z"), EndDateTime: mustMakeTime("2021-10-03T23:00:00Z"), EntryType: PlannedBusyTime, }, }, Error: false, }, } func TestWorkCalendarGetEntries(t *testing.T) { for _, tc := range testCasesGetEntries { entries, err := tc.WorkCalendar.GetEntries() // Expect Error if tc.Error && err == nil { t.Errorf("Test Case '%s': got no error; want error", tc.Name) } // Don't Expect Error if !tc.Error && err != nil { t.Errorf("Test Case '%s': got error: %s; want no error", tc.Name, err) } // Expect Same Entry Count if len(entries) != len(tc.Entries) { t.Errorf("Test Case '%s': got %d entries; want %d", tc.Name, len(entries), len(tc.Entries)) } // Expect Same Entries for _, expectedEntry := range tc.Entries { found := false for _, actualEntry := range entries { if expectedEntry.Description == actualEntry.Description && expectedEntry.StartDateTime.Equal(actualEntry.StartDateTime) && expectedEntry.EndDateTime.Equal(actualEntry.EndDateTime) && actualEntry.EntryType == expectedEntry.EntryType { found = true break } } if !found { t.Errorf("Test Case '%s': expected to find entry %v; but didn't", tc.Name, expectedEntry) } } } t.Log("Complete TestWorkCalendarGetEntries") }
alex-dsouza777/Python-Basics
Chapter 8 - Functions & Recursion/07_pr_03.py
#How do you prevent a python print() function to print a new line at the end print("Hello", end=" ") print("How", end=" ") print("Are", end=" ") print("You?", end=" ")
paullewallencom/mern-978-1-8392-1754-8
_/Section 10/32. Checkout Customer Carts/pages/api/products.js
<gh_stars>0 // import products from "../../static/products.json"; import Product from "../../models/Product"; import connectDb from "../../utils/connectDb"; connectDb(); export default async (req, res) => { const products = await Product.find(); res.status(200).json(products); };