repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
narendravyas24/fallback-studio
src/pwa-studio/packages/venia-concept/src/components/SearchBar/suggestedCategories.js
<reponame>narendravyas24/fallback-studio import React, { useCallback } from 'react'; import { arrayOf, func, number, shape, string } from 'prop-types'; import { Link } from '@magento/venia-drivers'; import { mergeClasses } from '../../classify'; import getLocation from './getLocation'; import defaultClasses from './suggestedCategories.css'; const SuggestedCategories = props => { const { categories, limit, onNavigate, value } = props; const classes = mergeClasses(defaultClasses, props.classes); const handleClick = useCallback(() => { if (typeof onNavigate === 'function') { onNavigate(); } }, [onNavigate]); const items = categories .slice(0, limit) .map(({ label, value_string: categoryId }) => ( <li key={categoryId} className={classes.item}> <Link className={classes.link} to={getLocation(value, categoryId)} onClick={handleClick} > <strong className={classes.value}>{value}</strong> <span>{` in ${label}`}</span> </Link> </li> )); return <ul className={classes.root}>{items}</ul>; }; export default SuggestedCategories; SuggestedCategories.defaultProps = { limit: 4 }; SuggestedCategories.propTypes = { categories: arrayOf( shape({ label: string.isRequired, value_string: string.isRequired }) ).isRequired, classes: shape({ item: string, link: string, root: string, value: string }), limit: number.isRequired, onNavigate: func, value: string };
Katochimoto/calendar-grid
src/vendor.js
import _preact from 'preact' import _preact_compat from 'preact-compat' import _classnames from 'classnames' import _raf from 'raf' import _setimmediate2 from 'setimmediate2' import _prop_types from 'prop-types' import 'es6-symbol/implement' import './vendor.less' _raf.polyfill() _setimmediate2.polifill() export default { _classnames, _preact_compat, _preact, _prop_types, }
intern0t/leetcode
MedianofTwoSortedArrays.java
<reponame>intern0t/leetcode // https://leetcode.com/problems/median-of-two-sorted-arrays/ public class MedianofTwoSortedArrays { public static void main(String[] args) { int testCases[][] = { { 1, 3 }, { 2 }, { 1, 2 }, { 3, 4 } }; for (int i = 0; i < testCases.length; i += 2) { // System.out.println(testCases[i][]) } } static double findMedianSortedArrays(int[] nums1, int[] nums2) { return 0.0; } }
PucklaMotzer09/GoHomeEngine
src/gohome/shadermodulesbackbufferopengl.go
<filename>src/gohome/shadermodulesbackbufferopengl.go package gohome import ( "github.com/PucklaMotzer09/GLSLGenerator" "strings" ) var ( GlobalsBBMS = []glslgen.Variable{ glslgen.Variable{"vec2", "highp", "vertices[6]"}, glslgen.Variable{"vec2", "highp", "texCoords[6]"}, } SetValuesModuleBBMS = glslgen.Module{ Name: "setValues", Body: `vertices[0] = vec2(-1.0,-1.0); vertices[1] = vec2(1.0,-1.0); vertices[2] = vec2(1.0,1.0); vertices[3] = vec2(1.0,1.0); vertices[4] = vec2(-1.0,1.0); vertices[5] = vec2(-1.0,-1.0); texCoords[0] = vec2(0.0,0.0); texCoords[1] = vec2(1.0,0.0); texCoords[2] = vec2(1.0,1.0); texCoords[3] = vec2(1.0,1.0); texCoords[4] = vec2(0.0,1.0); texCoords[5] = vec2(0.0,0.0);`, } SetGLPositionBBMS = glslgen.Module{ Name: "setGLPosition", Body: "gl_Position = vec4(vertices[gl_VertexID],0.0,1.0);", } SetGLPositionBBNOMS = glslgen.Module{ Name: "setGLPosition", Body: "gl_Position = vec4(vertex,0.0,1.0);", } TextureMSModule = glslgen.Module{ Uniforms: []glslgen.Variable{ glslgen.Variable{"sampler2DMS", "highp", "texture0"}, }, Functions: []glslgen.Function{ glslgen.Function{ "vec4 fetchColor()", `vec4 color = vec4(0.0); ivec2 texCoords = ivec2(fragTexCoord * textureSize(texture0)); for(int i = 0;i<8;i++) { color += texelFetch(texture0,texCoords,i); } color /= 8.0; return color;`, }, }, Name: "textureMSModule", Body: "globalColor = fetchColor();", } SetFragTexCoordModuleBBMS = glslgen.Module{ Name: "setFragTexCoord", Body: "fragTexCoord = texCoords[gl_VertexID];", } ) const ( SHADER_FLAG_NO_MS uint32 = (1 << 0) ) func GenerateShaderBackBuffer(flags uint32) (n, v, f string) { var vertex glslgen.VertexGenerator var fragment glslgen.FragmentGenerator if flags&SHADER_FLAG_NO_MS == 0 { if Render.GetName() == "WebGL" { vertex.SetVersion("WebGL") fragment.SetVersion("WebGL") } else if strings.Contains(Render.GetName(), "OpenGLES") { vertex.SetVersion("300 es") fragment.SetVersion("300 es") } else { vertex.SetVersion("150") fragment.SetVersion("150") } vertex.AddOutputs(Outputs2D) vertex.AddGlobals(GlobalsBBMS) vertex.AddModule(SetValuesModuleBBMS) vertex.AddModule(SetGLPositionBBMS) vertex.AddModule(DepthModuleVertex2D) vertex.AddModule(SetFragTexCoordModuleBBMS) fragment.AddMakros(MakrosFragment2D) fragment.AddInputs(Outputs2D) fragment.AddGlobals(GlobalsFragment2D) fragment.AddModule(InitModuleFragment2D) fragment.AddModule(TextureMSModule) fragment.AddModule(FinishColorModuleFragment2D) } else { if Render.GetName() == "WebGL" { vertex.SetVersion("WebGL") fragment.SetVersion("WebGL") } else if strings.Contains(Render.GetName(), "OpenGLES") { vertex.SetVersion("100") fragment.SetVersion("100") } else { vertex.SetVersion(ShaderVersion) fragment.SetVersion(ShaderVersion) } vertex.AddAttributes(Attributes2D) vertex.AddOutputs(Outputs2D) vertex.AddGlobals(GlobalsVertex2D) vertex.AddModule(InitTexCoordModule2D) vertex.AddModule(SetGLPositionBBNOMS) vertex.AddModule(DepthModuleVertex2D) vertex.AddModule(FinishTexCoordModule2D) fragment.AddMakros(MakrosFragment2D) fragment.AddInputs(Outputs2D) fragment.AddGlobals(GlobalsFragment2D) fragment.AddModule(TextureModuleFragment2D) fragment.AddModule(FinishColorModuleFragment2D) } n = "BackBufferShader" v, f = vertex.String(), fragment.String() return }
egovernments/iFix-Dev
domain-services/ifix-master-data-service/src/main/java/org/egov/repository/ExpenditureRepository.java
<reponame>egovernments/iFix-Dev package org.egov.repository; import org.egov.repository.queryBuilder.ExpenditureQueryBuilder; import org.egov.web.models.Expenditure; import org.egov.web.models.ExpenditureSearchCriteria; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Repository; import java.util.List; @Repository public class ExpenditureRepository { @Autowired private MongoTemplate mongoTemplate; @Autowired ExpenditureQueryBuilder expenditureQueryBuilder; /** * @param expenditureSearchCriteria * @return */ public List<Expenditure> findAllByCriteria(ExpenditureSearchCriteria expenditureSearchCriteria) { return mongoTemplate.find(expenditureQueryBuilder.buildQuerySearch(expenditureSearchCriteria), Expenditure.class); } public void save(Expenditure expenditure) { mongoTemplate.save(expenditure); } }
l33j00n325/myfifa-api
spec/models/fixture_leg_spec.rb
<reponame>l33j00n325/myfifa-api # frozen_string_literal: true # == Schema Information # # Table name: fixture_legs # # id :bigint not null, primary key # away_score :string # home_score :string # created_at :datetime not null # updated_at :datetime not null # fixture_id :bigint # # Indexes # # index_fixture_legs_on_fixture_id (fixture_id) # require 'rails_helper' describe FixtureLeg, type: :model do let(:fixture_leg) { create(:fixture_leg) } it 'has a valid factory' do expect(fixture_leg).to be_valid end end
patriotemeritus/LO-PHI
python-lophi/lophi/sensors/memory/__init__.py
<reponame>patriotemeritus/LO-PHI """ Abstract class for interacting with our memory sensors (c) 2015 Massachusetts Institute of Technology """ # Native import time import logging logger = logging.getLogger(__name__) # LO-PHI from lophi.sensors import Sensor CACHE_CHUNK = 7680 # 7680 is the max class MemorySensor(Sensor): """" This is an abstract class to help manage both physical and virtual implementations. This will also allow us to expand to new implementations very easily. """ # Format: [START,END) BAD_MEM_REGIONS = [] def __init__(self): """ Initialize our class """ # Ensure that this class is never initialized directly if self.__class__ == MemorySensor: raise ("Interface initialized directly!") Sensor.__init__(self) def _read_from_sensor(self, address, length): """ Read memory from the sensor directly """ raise NotImplementedError("ERROR: Unimplemented function.") def _read_cached(self, address, length): """ Read memory from the sensor, caching values if enabled. @param address: Starting physical memory address @param length: Length of memory to read @return: RAW data string from memory @todo: CLEAN UP THE CACHE! """ # Is the cache disabled? if self.CACHE_TIMEOUT <= 0: rtn = self._read_from_sensor(address, length) if rtn is None: return "" else: return rtn # Temp variable for cached data datas = "" NOW = time.time() # Loop over each chunk in the cache while (length > 0): cacheindex = address / CACHE_CHUNK chunkstart = cacheindex * CACHE_CHUNK cacheoffset = address - chunkstart inchunk = CACHE_CHUNK - cacheoffset # See if we have a cached version, and if its expired if cacheindex not in self.cache or self.cache_timeouts[ cacheindex] <= NOW - self.CACHE_TIMEOUT: # Read the memory from our sensor entry = self._read_from_sensor(chunkstart, CACHE_CHUNK) if entry is None: logger.error("Problem reading from sensor!") return datas # Cache this entry self.cache[cacheindex] = entry # Save the time that we got this entry self.cache_timeouts[cacheindex] = NOW # Only append what was requested if length > CACHE_CHUNK - cacheoffset: datas += self.cache[cacheindex][cacheoffset:] else: datas += self.cache[cacheindex][ cacheoffset:cacheoffset + length] address += inchunk length -= inchunk return datas def read(self, address, length): """ Read memory from our sensor NOTE: This will use our temporal cache if it's set and handle any memory holes @param address: Starting physical memory address @param length: Length of memory to read @return: RAW data string from memory """ logger.debug("Got read (0x%x,%d)" % (address, length)) if length < 1: logger.error("Read length must be >= 1") READS = [] # Given a read like below, we'll want to read the - sections and fill in # zeros for the * sections where # # S--------b1s***b1e-----b2s***b2e------E # # S - address, E - address+length, bX(s/e) - bad region start/end # # NOTE: BAD_MEM_REGIONS is assumed to be sorted! # There are also faster ways to do this, but this is already likely a # rare case to have many bad regions last_bad = None for bad in self.BAD_MEM_REGIONS: # Does the entire requested region fall in a bad sector? if bad[0] <= address and bad[1] >= address + length: logger.debug( "Entire region is in bad memory %s, returning 0s" % str( bad)) return "\x00" * length # Does this region start within our read? if bad[0] >= address and bad[0] < address + length: logger.debug("Region starts in bad memory. %s" % str(bad)) # We'll need to do one read from the start of the previous bad # region to the beginning of this bad region if last_bad is None and address != bad[0]: READS.append((address, bad[0])) elif last_bad is not None: READS.append((last_bad[1], bad[0])) last_bad = bad # Does this read request start in a bad region? elif bad[1] > address and bad[1] < address + length: last_bad = bad # Are we oustide of the region that we are worried about? elif bad[0] > address + length: continue # Are we doing multiple reads? if len(READS) > 0 or last_bad is not None: # Do we need a final read to pick up the left over case? # i.e. b2e------E if last_bad[1] < address + length: READS.append((last_bad[1], address + length)) # variable to store our data data = "" # Do we need to prepend zeros? if READS[0][0] > address: data += "\x00" * (READS[0][0] - address) logger.debug("Issuing the following reads: %s" % READS) last_read = None for read in READS: # Append any zeros for the bad sections # ..--b1s***b1e--.. # bs1 = last_read[1], bs1e = read[0] if last_read is not None: data += "\x00" * (read[0] - last_read[1]) read_data = self._read_cached(read[0], read[1] - read[0]) if read_data is None or len(read_data) == 0: logger.error("Got no data back from sensor. (Timeout)") return None data += read_data last_read = read # Do we need to append zero's to the end to hit our length? if len(data) < length: data += "\x00" * (length - len(data)) return data else: return self._read_cached(address, length) def write(self, address, data): """ Write memory """ raise NotImplementedError("ERROR: Unimplemented function.") def subscribe(self): """ Subscribe to a memory region """ raise NotImplementedError("ERROR: Unimplemented function.") def unsubscribe(self): """ Un-subscribe from a memory region """ raise NotImplementedError("ERROR: Unimplemented function.")
djg4554/NyaaMailer
src/main/java/cat/nyaa/mailer/inbox/listeners/Load.java
package cat.nyaa.mailer.inbox.listeners; import cat.nyaa.mailer.NyaaMailer; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; public class Load implements Listener { private final NyaaMailer plugin; public Load(NyaaMailer plugin) { this.plugin = plugin; plugin.getServer().getPluginManager().registerEvents(this, plugin); } @EventHandler public void onLoad(PlayerJoinEvent event) { plugin.getInboxManager().loadInbox(event.getPlayer()); } }
Planning-Inspectorate/appeal-planning-decision
packages/lpa-questionnaire-web-app/__tests__/unit/validators/custom/file-size.test.js
const validateFileSize = require('../../../../src/validators/custom/file-size'); describe('validators/custom/file-size', () => { it('should be valid when given a smaller file size than the configured maximum', () => { expect(validateFileSize(1024, 2048)).toBeTruthy(); }); it('should be valid when given a file size that matches the configured maximum', () => { expect(validateFileSize(1024, 1024)).toBeTruthy(); }); describe('should throw when oversize', () => { const testSetup = () => [ { givenFileSize: 1, maxFileSize: 0, expectedErrorMessage: (filename) => `${filename} must be smaller than 0 Bytes`, }, { givenFileSize: 2, maxFileSize: 1, expectedErrorMessage: (filename) => `${filename} must be smaller than 1 Bytes`, }, { givenFileSize: 2048, maxFileSize: 1024, expectedErrorMessage: (filename) => `${filename} must be smaller than 1 KB`, }, { givenFileSize: 1024 ** 2 + 1, maxFileSize: 1024 ** 2, expectedErrorMessage: (filename) => `${filename} must be smaller than 1 MB`, }, { givenFileSize: 1024 ** 3 + 1, maxFileSize: 1024 ** 3, expectedErrorMessage: (filename) => `${filename} must be smaller than 1 GB`, }, { givenFileSize: 1024 ** 4 + 1, maxFileSize: 1024 ** 4, expectedErrorMessage: (filename) => `${filename} must be smaller than 1 TB`, }, { givenFileSize: 1024 ** 5 + 1, maxFileSize: 1024 ** 5, expectedErrorMessage: (filename) => `${filename} must be smaller than 1 PB`, }, { givenFileSize: 1024 ** 7, maxFileSize: 1024 ** 6, expectedErrorMessage: (filename) => `${filename} must be smaller than 1 EB`, }, { givenFileSize: 1024 ** 8, maxFileSize: 1024 ** 7, expectedErrorMessage: (filename) => `${filename} must be smaller than 1 ZB`, }, { givenFileSize: 1024 ** 9, maxFileSize: 1024 ** 8, expectedErrorMessage: (filename) => `${filename} must be smaller than 1 YB`, }, ]; testSetup().forEach(({ givenFileSize, maxFileSize, expectedErrorMessage }) => { it(`generic file name - ${givenFileSize}`, () => { expect(() => validateFileSize(givenFileSize, maxFileSize)).toThrow( expectedErrorMessage('The file') ); }); }); testSetup().forEach(({ givenFileSize, maxFileSize, expectedErrorMessage }) => { it(`specific file name - ${givenFileSize}`, () => { const fileName = 'Some file name.png'; expect(() => validateFileSize(givenFileSize, maxFileSize, fileName)).toThrow( expectedErrorMessage(fileName) ); }); }); }); });
saikrishna2409/My-First-Repo
CollectionActivity/src/javaapp/daoimpl/EmployDAOImpl.java
package javaapp.daoimpl; import java.util.ArrayList; import java.util.List; import javaapp.bean.Employ; import javaapp.bean.dao.EmployDAO; public class EmployDAOImpl implements EmployDAO{ static ArrayList<Employ> list =null; static { list = new ArrayList<Employ>(); Employ emp1 = new Employ(101, "Abin", "Hydrabad", 22, 6678687687L, 6786868.00); Employ emp2 = new Employ(102, "Anu", "Chennai", 21, 345354354L, 45464646.00); list.add(emp1); list.add(emp2); } @Override public boolean addEmploy(Employ employ) { try { list.add(employ); return true; } catch (Exception e) { e.printStackTrace(); return false; } } @Override public boolean updateEmploy(Employ employ) { for(Employ emp : list) { if(emp.getId()==employ.getId()) { list.set(list.indexOf(emp), employ); return true; } } return false; } @Override public boolean deleteEmployee(Employ employ) { // try { //list.remove //} return false; } @Override public Employ getEmployById(int id) { for (Employ employ : list) { if (employ.getId() == id) { return employ; } } return null; } @Override public List<Employ> getAllEmploy() { // TODO Auto-generated method stub for(Employ e2:list) { System.out.println(list); } } }
Flavio-96/IDWork-Data-Integration-Project
IDWork/api/helpers/global-scheme/course-interface.js
<filename>IDWork/api/helpers/global-scheme/course-interface.js module.exports = { friendlyName: 'Course interface', description: 'Return courses find on Coursera (on the fly) and udacity (from datawarehouse)', inputs: { keyword: { description: 'argument', type: 'string', required: true } }, exits: { success: { description: 'Output all the courses inherent to the keyword', }, }, fn: async function ({ keyword }) { const coursera = require(`@wrappers/coursera_wrapper`); let global_courses = []; let coursera_courses = await coursera.getCourses(keyword); if(coursera_courses != null){ global_courses = global_courses.concat(coursera_courses); } // !!!! IMPORTANT: Update case insensitive research !!!! var udacity_courses = await Udacity.find({ or: [ { title: { contains: keyword } }, { description: { contains: keyword } }, { skills: { contains: keyword } } ] }); if(udacity_courses != null){ global_courses = global_courses.concat(udacity_courses); } return global_courses; } };
p3g4asus/moviz
app/src/main/java/com/moviz/lib/utils/CommandProcessor.java
package com.moviz.lib.utils; import com.moviz.lib.comunication.message.BaseMessage; public interface CommandProcessor { BaseMessage processCommand(BaseMessage hs2); }
andypymont/adventofcode
2015/day17.py
""" 2015 Day 17 https://adventofcode.com/2015/day/17 """ from typing import Iterable, Sequence import numpy as np import aocd # type: ignore def read_containers(text: str) -> Sequence[int]: """ Read the puzzle input into a list of integers representing the container sizes. """ return [int(line) for line in text.split("\n")] def valid_combos( containers: Sequence[int], target: int = 150 ) -> Iterable[Sequence[int]]: """ Calculate all valid container combinations which add up to the total target quantity. """ format_str = "{:0>" + str(len(containers)) + "}" def binary(number): """ Convert a number into the appropriate-length binary representation. """ return format_str.format(np.base_repr(number, 2)) for combo in range(1, 2 ** len(containers)): bits = binary(combo) selected = [ container for c, container in enumerate(containers) if bits[c] == "1" ] if sum(selected) == target: yield selected def main(): """ Calculate and output the solutions based on the real puzzle input. """ data = aocd.get_data(year=2015, day=17) containers = read_containers(data) combos = tuple(valid_combos(containers)) print(f"Part 1: {len(combos)}") min_containers = min(len(c) for c in combos) possibilities = [combo for combo in combos if len(combo) == min_containers] print(f"Part 2: {len(possibilities)}") if __name__ == "__main__": main()
shiningkiss/morn-boot-projects
morn-boot-test/src/test/java/site/morn/boot/json/package-info.java
/** * JSON单元测试 * * @author timely-rain * @since 1.2.1, 2020/6/25 */ package site.morn.boot.json; import java.util.ArrayList; import java.util.List; import site.morn.test.TestUser; /** * JSON测试常量类 * * @author timely-rain * @since 1.2.1, 2020/6/25 */ class Constant { /** * 用户集合 */ protected static final List<TestUser> USERS = new ArrayList<>(); //language=JSON protected static final String USERS_STRING = "[\n" + " {\n" + " \"id\": 1,\n" + " \"username\": \"Caramel\"\n" + " },\n" + " {\n" + " \"id\": 2,\n" + " \"username\": \"Mocha\"\n" + " }\n" + "]"; /** * 用户1 */ protected static final TestUser USER1 = new TestUser(1L, "Caramel"); //language=JSON protected static final String USER1_STRING = "{\n" + " \"id\": 1,\n" + " \"username\": \"Caramel\"\n" + "}"; /** * 用户2 */ protected static final TestUser USER2 = new TestUser(2L, "Mocha"); //language=JSON protected static final String USER2_STRING = "{\n" + " \"id\": 2,\n" + " \"username\": \"Mocha\"\n" + "}"; static { USERS.add(USER1); USERS.add(USER2); } }
halotroop2288/consulo
modules/base/lang-impl/src/main/java/com/intellij/codeInsight/generation/actions/SurroundWithAction.java
<filename>modules/base/lang-impl/src/main/java/com/intellij/codeInsight/generation/actions/SurroundWithAction.java // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.generation.actions; import com.intellij.codeInsight.CodeInsightActionHandler; import com.intellij.codeInsight.actions.BaseCodeInsightAction; import com.intellij.codeInsight.generation.surroundWith.SurroundWithHandler; import com.intellij.codeInsight.template.TemplateActionContext; import com.intellij.codeInsight.template.impl.TemplateManagerImpl; import com.intellij.lang.Language; import com.intellij.lang.LanguageSurrounders; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiUtilCore; import javax.annotation.Nonnull; public class SurroundWithAction extends BaseCodeInsightAction { public SurroundWithAction() { setEnabledInModalContext(true); } @Nonnull @Override protected CodeInsightActionHandler getHandler() { return new SurroundWithHandler(); } //@Override public boolean isUpdateInBackground() { return false; } @Override protected boolean isValidForFile(@Nonnull Project project, @Nonnull Editor editor, @Nonnull final PsiFile file) { final Language language = file.getLanguage(); if (!LanguageSurrounders.INSTANCE.allForLanguage(language).isEmpty()) { return true; } final PsiFile baseFile = PsiUtilCore.getTemplateLanguageFile(file); if (baseFile != null && baseFile != file && !LanguageSurrounders.INSTANCE.allForLanguage(baseFile.getLanguage()).isEmpty()) { return true; } if (!TemplateManagerImpl.listApplicableTemplateWithInsertingDummyIdentifier(TemplateActionContext.surrounding(file, editor)).isEmpty()) { return true; } return false; } }
mvxxx/MarsCombat
source/states/SubState.hpp
<reponame>mvxxx/MarsCombat /* mvxxx 2019 https://github.com/mvxxx */ #pragma once #include "../wrappers/EventWrapper.hpp" /** * @brief represents single substate */ class SubState { /* ===Objects=== */ public: protected: private: /* ===Methods=== */ public: /** * @brief onStart method */ virtual void onStart() = 0; /** * @brief onStop method */ virtual void onStop() = 0; /** * @brief run method */ virtual void run( eventWrapper_t& eventTypes ) = 0; protected: private: };
Pittor052/SoftUni-Studies
FirstStepsInPython/Basics/Exams/28 and 29 March 2020/01. Change Bureau.py
<reponame>Pittor052/SoftUni-Studies bitcoins = float(input()) * 1168 yuan = float(input()) commission = float(input()) total = ((bitcoins + ((yuan * 0.15) * 1.76)) / 1.95) * ((100 - commission) / 100) print(f"{total:.2f}")
wwjiang007/spring-xd
spring-xd-batch/src/main/java/org/springframework/xd/batch/hsqldb/server/package-info.java
/** * Package for HSQL database server. */ package org.springframework.xd.batch.hsqldb.server;
JamesLoveCurry/bione_input
bione-frame/src/main/java/org/sitemesh/content/tagrules/html/ExportTagToContentRule.java
package org.sitemesh.content.tagrules.html; import org.sitemesh.tagprocessor.BasicBlockRule; import org.sitemesh.tagprocessor.Tag; import org.sitemesh.content.ContentProperty; import java.io.IOException; /** * Exports the contents of a match tag to property of the passed in {@link ContentProperty}. * * Additionally, if this tag has attributes, they will be written as child properties. * * <h3>Example</h3> * * <pre> * // Java * myState.addRule("foo", new ExportTagToContentRule(content, "bar"); * * // Input * &lt;foo x=1 b=2&gt;hello&lt/foo&gt; * * // Exported properties of Content * bar=hello * bar.x=1 * bar.b=2 * </pre> * * @author <NAME> */ public class ExportTagToContentRule extends BasicBlockRule<Object> { private final ContentProperty targetProperty; private final boolean includeInContent; /** * @param targetProperty ContentProperty to export tag contents to. * @param includeInContent Whether the tag should be included in the content (if false, it will be stripped * from the current ContentProperty that is being written to. * @see ExportTagToContentRule */ public ExportTagToContentRule(ContentProperty targetProperty, boolean includeInContent) { this.targetProperty = targetProperty; this.includeInContent = includeInContent; } @Override protected Object processStart(Tag tag) throws IOException { // Some terminology: // Given a tag: '<foo>hello</foo>' // INNER contents refers to 'hello' // OUTER contents refers to '<foo>hello</foo>' // Export all attributes of the opening tag as child nodes on the target ContentProperty. for (int i = 0; i < tag.getAttributeCount(); i++) { targetProperty.getChild(tag.getAttributeName(i)).setValue(tag.getAttributeValue(i)); } // Push a buffer for the OUTER contents. if (!includeInContent) { // If the tag should NOT be included in the contents, we use a data-only buffer, // which means that although the contents won't be written // back to the ContentProperty, they will be available in the main Content data. // See Content.createDataOnlyBuffer() tagProcessorContext.pushBuffer(targetProperty.getOwningContent().createDataOnlyBuffer()); } else { tagProcessorContext.pushBuffer(); } // Write opening tag to OUTER buffer. tag.writeTo(tagProcessorContext.currentBuffer()); // Push a new buffer for storing the INNER contents. tagProcessorContext.pushBuffer(); return null; } @Override protected void processEnd(Tag tag, Object data) throws IOException { // Get INNER content, and pop the buffer for INNER contents. CharSequence innerContent = tagProcessorContext.currentBufferContents(); tagProcessorContext.popBuffer(); // Write the INNER content and closing tag, to OUTER buffer and pop it. tagProcessorContext.currentBuffer().append(innerContent); if (tag.getType() != Tag.Type.EMPTY) { // if the tag is empty we have already written it in processStart(). tag.writeTo(tagProcessorContext.currentBuffer()); } CharSequence outerContent = tagProcessorContext.currentBufferContents(); tagProcessorContext.popBuffer(); // Write the OUTER contents to the current buffer, which is now the buffer before the // tag was processed. Note that if !includeInContent, this buffer will not be written // to the ContentProperty (though it will be available in Content.getData()). // See comment in processStart(). tagProcessorContext.currentBuffer().append(outerContent); // Export the tag's inner contents to if (!targetProperty.hasValue()) { targetProperty.setValue(innerContent); } } }
MrUPGrade/prezentacje
pygda14/code/fixtures/test_fixture_finalizer.py
<filename>pygda14/code/fixtures/test_fixture_finalizer.py<gh_stars>1-10 import pytest @pytest.fixture(scope='module') #@pytest.fixture def initial_dict(request): def finalizer(): print('## finish ##', end='') request.addfinalizer(finalizer) return {'1': 1, '2': 2} def test_fixture_1(initial_dict): assert '1' in initial_dict def test_fixture_2(initial_dict): assert '2' in initial_dict
pjfanning/poi-ooxml-lite-build
src/main/java/org/etsi/uri/x01903/v13/DigestAlgAndValueType.java
<reponame>pjfanning/poi-ooxml-lite-build /* * XML Type: DigestAlgAndValueType * Namespace: http://uri.etsi.org/01903/v1.3.2# * Java type: org.etsi.uri.x01903.v13.DigestAlgAndValueType * * Automatically generated - do not modify. */ package org.etsi.uri.x01903.v13; import org.apache.xmlbeans.impl.schema.ElementFactory; import org.apache.xmlbeans.impl.schema.AbstractDocumentFactory; import org.apache.xmlbeans.impl.schema.DocumentFactory; import org.apache.xmlbeans.impl.schema.SimpleTypeFactory; /** * An XML DigestAlgAndValueType(@http://uri.etsi.org/01903/v1.3.2#). * * This is a complex type. */ public interface DigestAlgAndValueType extends org.apache.xmlbeans.XmlObject { DocumentFactory<org.etsi.uri.x01903.v13.DigestAlgAndValueType> Factory = new DocumentFactory<>(org.apache.poi.schemas.ooxml.system.ooxml.TypeSystemHolder.typeSystem, "digestalgandvaluetype234etype"); org.apache.xmlbeans.SchemaType type = Factory.getType(); /** * Gets the "DigestMethod" element */ org.w3.x2000.x09.xmldsig.DigestMethodType getDigestMethod(); /** * Sets the "DigestMethod" element */ void setDigestMethod(org.w3.x2000.x09.xmldsig.DigestMethodType digestMethod); /** * Appends and returns a new empty "DigestMethod" element */ org.w3.x2000.x09.xmldsig.DigestMethodType addNewDigestMethod(); /** * Gets the "DigestValue" element */ byte[] getDigestValue(); /** * Gets (as xml) the "DigestValue" element */ org.w3.x2000.x09.xmldsig.DigestValueType xgetDigestValue(); /** * Sets the "DigestValue" element */ void setDigestValue(byte[] digestValue); /** * Sets (as xml) the "DigestValue" element */ void xsetDigestValue(org.w3.x2000.x09.xmldsig.DigestValueType digestValue); }
Brest-Java-Course-2021-2/Maksim-Meliashchuk-Setlist-Organizer
rest-app/src/main/java/com/epam/brest/rest/TrackController.java
<gh_stars>0 package com.epam.brest.rest; import com.epam.brest.model.Track; import com.epam.brest.service.TrackService; import com.epam.brest.service.excel.TrackExportExcelService; import com.epam.brest.service.excel.TrackImportExcelService; import com.epam.brest.service.faker.TrackFakerService; import com.epam.brest.service.xml.TrackXmlService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.media.ArraySchema; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.media.Schema; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import io.swagger.v3.oas.annotations.tags.Tag; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.io.IOException; import java.util.Collection; import java.util.List; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo; import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.methodOn; /** * REST controller. */ @Tag(name = "Track", description = "the Track API") @RestController @CrossOrigin @SecurityRequirement(name = "keycloakOAuth") public class TrackController { private final TrackService trackService; private final TrackFakerService trackFakerService; private final TrackExportExcelService trackExportExcelService; private final TrackImportExcelService trackImportExcelService; private final TrackXmlService trackXmlService; private final Logger logger = LogManager.getLogger(TrackController.class); public TrackController(TrackService trackService, TrackFakerService trackFakerService, TrackExportExcelService trackExportExcelService, TrackImportExcelService trackImportExcelService, TrackXmlService trackXmlService) { this.trackService = trackService; this.trackFakerService = trackFakerService; this.trackExportExcelService = trackExportExcelService; this.trackImportExcelService = trackImportExcelService; this.trackXmlService = trackXmlService; } @Operation(summary = "Get information for all tracks based on their IDs") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "A set of tracks", content = { @Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = Track.class))) }) }) @GetMapping(value = "/repertoire") public final Collection<Track> tracks() { logger.debug("tracks()"); List<Track> trackList = trackService.findAllTracks(); trackList.forEach(track -> track.add(linkTo(methodOn(TrackController.class).getTrackById(track.getTrackId())).withSelfRel(), linkTo(methodOn(TrackController.class).createTrack(track)).withRel("createTrack"), linkTo(methodOn(TrackController.class).updateTrack(track)).withRel("updateTrack"), linkTo(methodOn(TrackController.class).deleteTrack(track.getTrackId())).withRel("deleteTrack"))); return trackList; } @Operation(summary = "Fill information for fake tracks based on their IDs") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "A set of fake tracks", content = { @Content(mediaType = "application/json", array = @ArraySchema(schema = @Schema(implementation = Track.class))) }) }) @GetMapping(value = "/repertoire/fill") public final Collection<Track> tracksFake(@RequestParam(defaultValue = "1", value = "size", required = false) Integer size, @RequestParam(defaultValue = "EN", value = "language", required = false) String language) { logger.debug("tracksFake()"); return trackFakerService.fillFakeTracks(size, language); } @Operation(summary = "Get information for a single track identified by its unique ID") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "A track", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Track.class)) }), @ApiResponse(responseCode = "404", description = "Trying to get a non-existent track", content = @Content)}) @GetMapping(value = "/repertoire/{id}") public ResponseEntity<Track> getTrackById(@PathVariable Integer id) { logger.debug("getTrackById()"); Track track = trackService.getTrackById(id); track.add(linkTo(methodOn(TrackController.class).getTrackById(track.getTrackId())).withSelfRel(), linkTo(methodOn(TrackController.class).createTrack(track)).withRel("createTrack"), linkTo(methodOn(TrackController.class).updateTrack(track)).withRel("updateTrack"), linkTo(methodOn(TrackController.class).deleteTrack(track.getTrackId())).withRel("deleteTrack")); return ResponseEntity.ok(track); } @Operation(summary = "Create a new track") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Track have been created. Returns the ID of the new track", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Integer.class)) }), @ApiResponse(responseCode = "400", description = "An attempt to create track with invalid fields", content = @Content)}) @PostMapping(path = "/repertoire", consumes = {"application/json"}, produces = {"application/json"}) public ResponseEntity<Integer> createTrack(@Valid @RequestBody Track track) { logger.debug("createTrack({})", track); Integer id = trackService.create(track); return new ResponseEntity<>(id, HttpStatus.OK); } @Operation(summary = "Update a track") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Track(s) have been updated. Returns the number of tracks affected", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Integer.class)) }), @ApiResponse(responseCode = "400", description = "Trying to update track with invalid fields", content = @Content), @ApiResponse(responseCode = "404", description = "Trying to update a non-existent track", content = @Content) }) @PutMapping(value = "/repertoire", consumes = {"application/json"}, produces = {"application/json"}) public ResponseEntity<Integer> updateTrack(@Valid @RequestBody Track track) { logger.debug("updateTrack({})", track); int result = trackService.update(track); return new ResponseEntity<>(result, HttpStatus.OK); } @Operation(summary = "Delete a track") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Track(s) have been removed. Returns the number of tracks affected", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Integer.class)) }), @ApiResponse(responseCode = "404", description = "Trying to delete a non-existent track", content = @Content)}) @DeleteMapping(value = "/repertoire/{id}", produces = {"application/json"}) public ResponseEntity<Integer> deleteTrack(@PathVariable Integer id) { logger.debug("delete({})", id); int result = trackService.delete(id); return new ResponseEntity<>(result, HttpStatus.OK); } @Operation(summary = "Export information for all tracks based on their IDs to Excel") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Successfully export to Excel", content = { @Content(mediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", schema = @Schema(implementation = MultipartFile.class, format = "binary"))}) }) @GetMapping(value = "/repertoire/export/excel") public final void exportToExcelAllTracks(HttpServletResponse response) { logger.debug("exportToExcelAllTracks()"); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); String headerKey = "Content-Disposition"; String headerValue = "attachment; filename=Tracks.xlsx"; response.setHeader(headerKey, headerValue); trackExportExcelService.exportTracksExcel(response); } @Operation(summary = "Import information in the table 'Track' from Excel") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Track(s) have been imported. Returns the number of tracks imported.", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = Integer.class)) })}) @PostMapping(value = "/repertoire/import/excel", consumes = MediaType.MULTIPART_FORM_DATA_VALUE ) public ResponseEntity<Integer> importTrackFromExcel(@RequestParam(value ="file") final MultipartFile files) throws IOException { logger.debug("importTrackFromExcel({})", files.getName()); int result = trackImportExcelService.importTrackExcel(files).size(); return new ResponseEntity<>(result, HttpStatus.OK); } @Operation(summary = "Export information for all tracks based on their IDs to XML") @ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Successfully export to XML", content = { @Content(mediaType = "application/xml", schema = @Schema(implementation = MultipartFile.class, format = "binary")) }), }) @GetMapping(value = "/repertoire/export/xml") public final void exportToXmlAlTracks(HttpServletResponse response) throws IOException { logger.debug("exportToXmlAlTracks()"); response.setContentType("application/xml"); String headerKey = "Content-Disposition"; String headerValue = "attachment; filename=Tracks.xml"; response.setHeader(headerKey, headerValue); trackXmlService.exportTracksXml(response); } }
JetBrains/teamcity-vmware-plugin
cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/VmwareCloudImageDetails.java
<filename>cloud-vmware-server/src/main/java/jetbrains/buildServer/clouds/vmware/VmwareCloudImageDetails.java<gh_stars>10-100 /* * Copyright 2000-2021 JetBrains s.r.o. * * 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 jetbrains.buildServer.clouds.vmware; import jetbrains.buildServer.clouds.CloudImageParameters; import jetbrains.buildServer.clouds.base.beans.CloudImageDetails; import jetbrains.buildServer.clouds.base.types.CloneBehaviour; import jetbrains.buildServer.util.StringUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Sergey.Pak * Date: 10/16/2014 * Time: 5:37 PM */ public class VmwareCloudImageDetails implements CloudImageDetails { @Nullable private final String myNickname; @NotNull private final String mySourceVmName; private final String myFolderId; private final String myResourcePoolId; @NotNull private final String mySnapshotName; private final CloneBehaviour myCloneBehaviour; private final int myMaxInstances; private final String myCustomizationSpec; private final Integer myAgentPoolId; @NotNull private final String mySourceId; public VmwareCloudImageDetails(@NotNull final CloudImageParameters imageParameters){ myCustomizationSpec = imageParameters.getParameter(VmwareConstants.CUSTOMIZATION_SPEC); myMaxInstances = StringUtil.parseInt(StringUtil.emptyIfNull(imageParameters.getParameter(VmwareConstants.MAX_INSTANCES)), 0); mySourceVmName = imageParameters.getParameter(VmwareConstants.SOURCE_VM_NAME); myFolderId = imageParameters.getParameter(VmwareConstants.FOLDER); myResourcePoolId = imageParameters.getParameter(VmwareConstants.RESOURCE_POOL); myCloneBehaviour = CloneBehaviour.valueOf(imageParameters.getParameter(VmwareConstants.BEHAVIOUR)); mySnapshotName = StringUtil.emptyIfNull(imageParameters.getParameter(VmwareConstants.SNAPSHOT)); myNickname = StringUtil.nullIfEmpty(imageParameters.getParameter(VmwareConstants.NICKNAME)); myAgentPoolId = imageParameters.getAgentPoolId(); if (myCloneBehaviour.isUseOriginal()){ mySourceId = mySourceVmName; } else { mySourceId = myNickname == null ? mySourceVmName : myNickname; } } @NotNull public String getSourceId() { return mySourceId; } @NotNull public String getSourceVmName() { return mySourceVmName; } public String getFolderId() { return myFolderId; } public String getResourcePoolId() { return myResourcePoolId; } @NotNull public String getSnapshotName() { return mySnapshotName; } public CloneBehaviour getBehaviour() { return myCloneBehaviour; } public int getMaxInstances() { return myMaxInstances; } public String getCustomizationSpec() { return myCustomizationSpec; } public boolean useCurrentVersion(){ return VmwareConstants.CURRENT_STATE.equals(mySnapshotName); } public Integer getAgentPoolId() { return myAgentPoolId; } }
mordor737/RestAPI_Complete
src/main/java/com/base/controller/UserController.java
<filename>src/main/java/com/base/controller/UserController.java package com.base.controller; import com.base.service.AddressService; import com.base.service.UserService; import com.base.shared.dto.AddressDto; import com.base.shared.dto.UserDto; import com.base.ui.model.request.UserDetailsRequestModel; import com.base.ui.model.response.*; import java.util.ArrayList; import org.modelmapper.ModelMapper; import org.modelmapper.TypeToken; import org.springframework.beans.BeanUtils; import org.springframework.hateoas.CollectionModel; import org.springframework.hateoas.EntityModel; import org.springframework.hateoas.Link; import org.springframework.hateoas.server.mvc.WebMvcLinkBuilder; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.Arrays; import java.util.List; @RestController @RequestMapping("/users") // http://localhost:8080/mobile-app-ws/users public class UserController { UserService userService; AddressService addressService; UserController(UserService userService, AddressService addressService) { this.userService = userService; this.addressService = addressService; } @GetMapping(path = "/{id}", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public UserRest getUser(@PathVariable String id) { UserRest userRest = new UserRest(); UserDto userDto = userService.getUserByUserId(id); BeanUtils.copyProperties(userDto, userRest); return userRest; } @PostMapping( consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE} ) public UserRest createUser(@RequestBody UserDetailsRequestModel userDetails) throws Exception { UserRest returnValue; /*UserDto userDto = new UserDto(); BeanUtils.copyProperties(userDetails, userDto);*/ ModelMapper modelMapper = new ModelMapper(); UserDto userDto = modelMapper.map(userDetails, UserDto.class); UserDto createdUser = userService.createUser(userDto); returnValue = modelMapper.map(createdUser, UserRest.class); return returnValue; } @PutMapping(path = "/{id}", consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}, produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE} ) public UserRest updateUser(@PathVariable String id, @RequestBody UserDetailsRequestModel userDetails) { UserRest returnValue = new UserRest(); UserDto userDto = new UserDto(); BeanUtils.copyProperties(userDetails, userDto); UserDto updatedUser = userService.updateUser(id, userDto); BeanUtils.copyProperties(updatedUser, returnValue); return returnValue; } @DeleteMapping(path = "/{id}", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE} ) public OperationStatusModel deleteUser(@PathVariable String id) { OperationStatusModel returnValue = new OperationStatusModel(); returnValue.setOperationName(RequestOperationName.DELETE.name()); userService.deleteUser(id); returnValue.setOperationResult(RequestOperationStatus.SUCCESS.name()); return returnValue; } @GetMapping( produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE} ) public List<UserRest> getUsers(@RequestParam(value = "page", defaultValue = "0") int page, @RequestParam(value = "limit", defaultValue = "25") int limit) { List<UserRest> returnValue = new ArrayList<>(); List<UserDto> users = userService.getUsers(page, limit); for (UserDto userDto : users) { UserRest userModel = new UserRest(); BeanUtils.copyProperties(userDto, userModel); returnValue.add(userModel); } return returnValue; } //http://localhost:8080/mobile-app-ws/users/jjdslkoalk/addresses @GetMapping(path = "/{id}/addresses", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public CollectionModel<AddressesRest> getUserAddresses(@PathVariable String id) { List<AddressesRest> returnValue = new ArrayList<>(); List<AddressDto> addressesDto = addressService.getAddresses(id); if (addressesDto != null && !addressesDto.isEmpty()) { java.lang.reflect.Type listType = new TypeToken<List<AddressesRest>>() { }.getType(); returnValue = new ModelMapper().map(addressesDto, listType); for (AddressesRest addressRest : returnValue) { Link selfLink = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(UserController.class).getUserAddress(id, addressRest.getAddressesId())) .withSelfRel(); addressRest.add(selfLink); } } //https://localhost:8080/users/<id> Link userLink = WebMvcLinkBuilder.linkTo(UserController.class).slash(id).withRel("user"); //https://localhost:8080/users/<id>/addresses/<addressId> Link selfLink = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(UserController.class) .getUserAddresses(id)) .withSelfRel(); return CollectionModel.of(returnValue, userLink, selfLink); } //http://localhost:8080/mobile-app-ws/users/jjdslkoalk/addresses/lskdmolkenfg @GetMapping(path = "/{userId}/addresses/{addressId}", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public EntityModel<AddressesRest> getUserAddress(@PathVariable String userId, @PathVariable String addressId) { AddressDto addressesDto = addressService.getAddress(addressId); ModelMapper modelMapper = new ModelMapper(); AddressesRest returnValue = modelMapper.map(addressesDto, AddressesRest.class); //https://localhost:8080/users/<id> Link userLink = WebMvcLinkBuilder.linkTo(UserController.class).slash(userId).withRel("user"); //https://localhost:8080/users/<id>/addresses Link userAddressesLink = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(UserController.class).getUserAddresses(userId)) //.slash(id) //.slash("addresses") .withRel("addresses"); //https://localhost:8080/users/<id>/addresses/<addressId> Link selfLink = WebMvcLinkBuilder.linkTo(WebMvcLinkBuilder.methodOn(UserController.class).getUserAddress(userId, addressId)) //.slash(id) //.slash("addresses") //.slash(addressId) .withSelfRel(); return EntityModel.of(returnValue, Arrays.asList(userLink, userAddressesLink, selfLink)); } //http://localhost:8080/mobile-app-ws/users/email-verification?token=<PASSWORD> @GetMapping(path = "/email-verification", produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}) public OperationStatusModel verifyEmailToken(@RequestParam(value = "token") String token) { OperationStatusModel returnValue = new OperationStatusModel(); returnValue.setOperationName(RequestOperationName.VERIFY_EMAIL.name()); boolean isVerified = userService.verifyEmailToken(token); if (isVerified) { returnValue.setOperationResult(RequestOperationStatus.SUCCESS.name()); } else { returnValue.setOperationResult(RequestOperationStatus.ERROR.name()); } return returnValue; } }
krastin/pp-cs3.0
chapter-14/sample04.py
<filename>chapter-14/sample04.py from members import Student, Faculty paul = Faculty('<NAME>', 'Ajax', '<EMAIL>', '1234') print(paul.name) print(paul.email) print(paul.faculty_number) print(paul) jen = Student('<NAME>', 'Toronto', '<EMAIL>', '4321') print(jen.name) print(jen.email) print(jen.student_number) print(jen)
JROB774/tein-editor
source/cursor.cpp
GLOBAL constexpr const char* CURSOR_FILE_ARROW = "textures/editor_ui/cursor_arrow.bmp"; GLOBAL constexpr const char* CURSOR_FILE_BEAM_D = "textures/editor_ui/cursor_beam_dark.bmp"; GLOBAL constexpr const char* CURSOR_FILE_BEAM_L = "textures/editor_ui/cursor_beam_light.bmp"; GLOBAL constexpr const char* CURSOR_FILE_POINTER = "textures/editor_ui/cursor_pointer.bmp"; GLOBAL constexpr const char* CURSOR_FILE_BRUSH = "textures/editor_ui/cursor_brush.bmp"; GLOBAL constexpr const char* CURSOR_FILE_FILL = "textures/editor_ui/cursor_fill.bmp"; GLOBAL constexpr const char* CURSOR_FILE_SELECT = "textures/editor_ui/cursor_select.bmp"; GLOBAL SDL_Cursor* cursors[CAST(size_t, Cursor::Total)]; GLOBAL Cursor current_cursor; GLOBAL bool cursors_enabled; GLOBAL bool cursors_loaded; FILDEF bool internal__load_cursor (Cursor cursor, const char* file_name, int x, int y) { SDL_Surface* surface = load_surface_resource(file_name); if (!surface) { LOG_ERROR(ERR_MIN, "Failed to load cursor file '%s'!", file_name); return false; } defer { SDL_FreeSurface(surface); }; // We need to color key the loaded surface because it is a bitmap so it // does not have any alpha transparency by default (our key is white). // // Whilst we could technically continue even if this part fails we would // rather not because no one will want to use cursors with giant white // boxes around them... So instead we just fail and instead fallback to // using the standard operating system cursor instead of custom cursors. u32 color_key = SDL_MapRGB(surface->format, 0xFF,<KEY>); if (SDL_SetColorKey(surface, SDL_TRUE, color_key) < 0) { LOG_ERROR(ERR_MIN, "Failed to color key cursor '%s'!", file_name); return false; } cursors[CAST(int, cursor)] = SDL_CreateColorCursor(surface, x, y); if (!cursors[CAST(int, cursor)]) { LOG_ERROR(ERR_MIN, "Failed to create cursor '%s'!", file_name); return false; } return true; } FILDEF bool load_editor_cursors () { // We have a special case for the beam cursor as we want a specific // version based on whether a light or dark UI is currently loaded. const char* CURSOR_FILE_BEAM = (is_ui_light()) ? CURSOR_FILE_BEAM_D : CURSOR_FILE_BEAM_L; // This needs to be here for when we potentially reload the cursors. free_editor_cursors(); cursors_enabled = false; cursors_loaded = false; if (!internal__load_cursor(Cursor::ARROW, CURSOR_FILE_ARROW , 6, 3)) return false; if (!internal__load_cursor(Cursor::BEAM, CURSOR_FILE_BEAM , 11, 12)) return false; if (!internal__load_cursor(Cursor::POINTER, CURSOR_FILE_POINTER, 8, 1)) return false; if (!internal__load_cursor(Cursor::BRUSH, CURSOR_FILE_BRUSH , 3, 20)) return false; if (!internal__load_cursor(Cursor::FILL, CURSOR_FILE_FILL , 19, 16)) return false; if (!internal__load_cursor(Cursor::SELECT, CURSOR_FILE_SELECT , 11, 12)) return false; cursors_enabled = editor_settings.custom_cursors; cursors_loaded = true; // By default we want to be using the arrow cursor. if (!cursors_enabled) { SDL_SetCursor(SDL_GetDefaultCursor()); current_cursor = Cursor::ARROW; } else { if (cursors_loaded) { SDL_SetCursor(cursors[CAST(int, Cursor::ARROW)]); current_cursor = Cursor::ARROW; } } return true; } FILDEF void free_editor_cursors () { for (int i=0; i<CAST(int, Cursor::Total); ++i) { SDL_FreeCursor(cursors[i]); cursors[i] = NULL; } cursors_enabled = false; cursors_loaded = false; } FILDEF void set_cursor (Cursor cursor) { if (cursors_enabled && cursors_loaded && current_cursor != cursor && cursors[CAST(int, cursor)]) { SDL_SetCursor(cursors[CAST(int, cursor)]); current_cursor = cursor; } } FILDEF Cursor get_cursor () { return ((cursors_enabled && cursors_loaded) ? current_cursor : Cursor::ARROW); } FILDEF bool custom_cursors_enabled () { return cursors_enabled; }
wbt/truffle
packages/truffle/test/sources/migrations/quorum/migrations/3_migrations_async.js
<filename>packages/truffle/test/sources/migrations/quorum/migrations/3_migrations_async.js const web3 = require("web3"); const Example = artifacts.require("Example"); const IsLibrary = artifacts.require("IsLibrary"); const UsesExample = artifacts.require("UsesExample"); const UsesLibrary = artifacts.require("UsesLibrary"); const PayableExample = artifacts.require("PayableExample"); module.exports = async function(deployer) { await deployer.deploy(Example); await deployer.deploy(Example, { overwrite: false }); await deployer.deploy(IsLibrary); await deployer.link(IsLibrary, UsesLibrary); await deployer.deploy(UsesExample, IsLibrary.address); await deployer.deploy(UsesLibrary); await deployer.deploy(PayableExample, { value: web3.utils.toWei("1", "ether") }); };
touxiong88/92_mediatek
packages/apps/MTKAndroidSuiteDaemon/src/com/mediatek/apst/target/data/proxy/message/FastMmsCursorParser.java
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein * is confidential and proprietary to MediaTek Inc. and/or its licensors. * Without the prior written permission of MediaTek inc. and/or its licensors, * any reproduction, modification, use or disclosure of MediaTek Software, * and information contained herein, in whole or in part, shall be strictly prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON * AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT. * NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE * SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR * SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH * THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES * THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES * CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK * SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND * CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE, * AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE, * OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO * MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek Software") * have been modified by MediaTek Inc. All revisions are subject to any receiver's * applicable license agreements with MediaTek Inc. */ package com.mediatek.apst.target.data.proxy.message; import android.database.Cursor; import com.mediatek.apst.target.data.provider.message.MmsContent; import com.mediatek.apst.target.data.proxy.FastCursorParser; import com.mediatek.apst.target.data.proxy.IRawBlockConsumer; import com.mediatek.apst.target.data.proxy.IRawBufferWritable; import com.mediatek.apst.target.util.Config; import com.mediatek.apst.target.util.Debugger; import com.mediatek.apst.target.util.StringUtils; import com.mediatek.apst.util.entity.message.Mms; import com.mediatek.apst.util.entity.message.TargetAddress; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.util.HashMap; /** * Class Name: FastMmsCursorParser * <p> * Package: com.mediatek.apst.target.data.proxy.message * <p> * <p> * Description: * <p> * Parse MMS basic information * <p> * * @author mtk54043 Yu.Chen * @version V1.0 */ public class FastMmsCursorParser extends FastCursorParser { private boolean mQueryContact; private MessageProxy mMessageProxy; private HashMap<String, TargetAddress> mMapAddressToContact; /** * @param c * @param consumer * @param buffer * @param queryContact * @param messageProxy */ public FastMmsCursorParser(Cursor c, IRawBlockConsumer consumer, ByteBuffer buffer, boolean queryContact, MessageProxy messageProxy) { super(c, consumer, buffer); mQueryContact = queryContact; mMessageProxy = messageProxy; if (mQueryContact) { mMapAddressToContact = new HashMap<String, TargetAddress>(); } } /** * @param c * @param consumer * @param queryContact * @param messageProxy */ public FastMmsCursorParser(Cursor c, IRawBlockConsumer consumer, boolean queryContact, MessageProxy messageProxy) { super(c, consumer); mQueryContact = queryContact; mMessageProxy = messageProxy; if (mQueryContact) { mMapAddressToContact = new HashMap<String, TargetAddress>(); } } @Override public int onParseCursorToRaw(Cursor c, ByteBuffer buffer) { if (null == c) { Debugger.logW(new Object[] { c, buffer }, "Cursor is null."); return IRawBufferWritable.RESULT_FAIL; } else if (c.getPosition() == -1 || c.getPosition() == c.getCount()) { Debugger.logW(new Object[] { c, buffer }, "Cursor has moved to the end."); return IRawBufferWritable.RESULT_FAIL; } else if (null == buffer) { Debugger.logW(new Object[] { c, buffer }, "Buffer is null."); return IRawBufferWritable.RESULT_FAIL; } Mms mms = MmsContent.cursorToMms(c); if (null == mms) { return IRawBufferWritable.RESULT_FAIL; } // A new way to get address 2012-5-16 mtk54043 mms.setTarget(mMessageProxy.getMmsAddress(mms)); // Cursor draftCursor = mMessageProxy // .getContentResolver() // .query(MmsContent.CONTENT_URI, // new String[] { "canonical_addresses.address " // + "from pdu,threads,canonical_addresses " // + // "where pdu.thread_id=threads._id and threads.recipient_ids=canonical_addresses._id and pdu.thread_id =" // + threadId + " --" }, null, null, null); // // if (draftCursor != null && draftCursor.moveToFirst()) { // String draftAddress = draftCursor.getString(draftCursor // .getColumnIndex("address")); // Debugger.logI(new Object[] { }, "draftAddress = " // + draftAddress + " mms id = " + mms.getId()); // TargetAddress mmsAddress = new TargetAddress(draftAddress); // mmsAddress.setMmsId(mms.getId()); // mms.setTarget(mmsAddress); // } else { // Debugger.logE(new Object[] { }, "No address in canonical_addresses" + // " mms id = " + mms.getId()); // TargetAddress mmsAddress = new TargetAddress(""); // mmsAddress.setMmsId(mms.getId()); // mms.setTarget(mmsAddress); // } // if(null != draftCursor) { // draftCursor.close(); // } // A new way to get address 2012-5-16 mtk54043 end // Cursor c_addr = null; // Uri uri_addr = Uri.parse("content://mms/" + mms.getId() + "/addr"); // c_addr = mMessageProxy.getContentResolver().query(uri_addr, null, // null, // null, null); // // Debugger.logI("c_addr count is" + c_addr.getCount()); // TargetAddress mmsAddress = null; // if (null != c_addr) { // int c_count = c_addr.getCount(); // if (c_count != 0) { // c_addr.moveToFirst(); // if ((mms.getBox() == Mms.BOX_SENT || mms.getBox() == Mms.BOX_DRAFT) // && c_count > 1) { // c_addr.moveToNext(); // } // mmsAddress = new TargetAddress(c_addr.getString(c_addr // .getColumnIndex(MmsContent.COLUMN_ADDR_ADDRESS))); // mmsAddress.setMmsId(c_addr.getLong(c_addr // .getColumnIndex(MmsContent.COLUMN_ADDR_MSG_ID))); // mms.setTarget(mmsAddress); // // Debugger.logI("mmsAddress is " + mmsAddress.getAddress()); // } else { // mms.setTarget(null); // } // if (!c_addr.isClosed()) { // // Release resources // c_addr.close(); // c_addr = null; // } // } // Need to query contact if (mQueryContact) { String address = null; if (mms.getTarget() != null) { address = mms.getTarget().getAddress(); } String number = StringUtils.dropServiceCenter(address); TargetAddress target; if (mMapAddressToContact.containsKey(number)) { // Address is already queried before, just get contact // info from map target = mMapAddressToContact.get(number); } else { // Address is not queried before target = mMessageProxy.lookupContact(number); // Store contact info in map mMapAddressToContact.put(number, target); } if (null != target) { mms.getTarget().setContactId(target.getContactId()); mms.getTarget().setName(target.getName()); } } // Mark the current start position of byte buffer in order to reset // later when there is not enough space left in buffer buffer.mark(); try { // mms.writeRaw(buffer); @mtk54043 Yu mms.writeRawWithVersion(buffer, Config.VERSION_CODE); } catch (NullPointerException e) { Debugger.logE(new Object[] { c, buffer }, null, e); buffer.reset(); return IRawBufferWritable.RESULT_FAIL; } catch (BufferOverflowException e) { /* * Debugger.logW(new Object[]{c, buffer}, * "Not enough space left in buffer. ", e); */ buffer.reset(); return IRawBufferWritable.RESULT_NOT_ENOUGH_BUFFER; } return IRawBufferWritable.RESULT_SUCCESS; } }
andrew-cockayne/hv-uikit-react
packages/core/src/Table/DropdownMenu/index.js
import React from "react"; import { MoreOptionsVertical } from "@hitachivantara/uikit-react-icons"; import HvDropDownMenu from "../../DropDownMenu"; // eslint-disable-next-line react/prop-types const DropDownMenu = ({ id, secondaryActions, dropdownMenuProps, original }) => { return ( <HvDropDownMenu id={id} disablePortal={false} icon={<MoreOptionsVertical style={{ width: 30, height: 30 }} />} dataList={secondaryActions} onClick={(event, item) => { event.stopPropagation(); item?.action?.(event, original); }} keepOpened={false} placement="left" {...dropdownMenuProps} /> ); }; export default DropDownMenu;
common-group/services-core
services/catarse/lib/e_notas/params_builders/product.rb
# frozen_string_literal: true module ENotas module ParamsBuilders class Product ATTRIBUTES = %i[nome idExterno valorTotal tags].freeze def initialize(project_fiscal) @project_fiscal = project_fiscal end def build ATTRIBUTES.index_with { |attribute| send(attribute.to_s.underscore.to_sym) } end def nome @project_fiscal.project.name end def id_externo @project_fiscal.project.id.to_s end def valor_total @project_fiscal.total_debit_invoice.to_f end def tags @project_fiscal.project.category.name_pt end end end end
jafri/eoslime
tests/contract-tests.js
const assert = require("assert"); const eoslime = require("./../").init(); const TOKEN_ABI_PATH = "./tests/testing-contracts/compiled/eosio.token.abi"; const TOKEN_WASM_PATH = "./tests/testing-contracts/compiled/eosio.token.wasm"; const FAUCET_ABI_PATH = "./tests/testing-contracts/compiled/faucet.abi"; const FAUCET_WASM_PATH = "./tests/testing-contracts/compiled/faucet.wasm"; /* You should have running local nodeos in order to run tests */ describe("Contract", function () { // Increase mocha(testing framework) time, otherwise tests fails this.timeout(15000); // Faucet account is the account on which the faucet contract is going to be deployed let faucetAccount; let tokenContract; const TOKEN_PRECISION = Math.pow(10, 4); const TOTAL_SUPPLY = "1000000000.0000 TKNS"; const PRODUCED_TOKENS_AMOUNT = "100.0000 TKNS"; /* Deploy eos token contract on local nodoes in order to send eos and buy ram / bandwidth */ async function createToken () { // Deploy a token contract try { const tokenAccount = await eoslime.Account.createRandom(); tokenContract = await eoslime.Contract.deployOnAccount(TOKEN_WASM_PATH, TOKEN_ABI_PATH, tokenAccount); await tokenContract.actions.create([faucetAccount.name, TOTAL_SUPPLY]); } catch (error) { console.log(error); } } async function createFaucet () { // Deploy a faucet contract try { faucetAccount = await eoslime.Account.createRandom(); await eoslime.Contract.deployOnAccount(FAUCET_WASM_PATH, FAUCET_ABI_PATH, faucetAccount); } catch (error) { console.log(error); } } beforeEach(async () => { await createFaucet(); await createToken(); }); describe("Instantiation", function () { const CONTRACT_NETWORK = { name: "local", url: "http://127.0.0.1:8888", chainId: "cf057bbfb72640471fd910bcb67639c22df9f92470936cddc1ade0e2f2e7dc4f" }; it("Should instantiate correct instance of Contract from ABI file", async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); assert(typeof faucetContract.actions.produce == "function"); assert(typeof faucetContract.actions.withdraw == "function"); assert(faucetContract.name == faucetAccount.name); assert(JSON.stringify(faucetContract.executor) == JSON.stringify(faucetAccount)); assert(JSON.stringify(faucetContract.provider.network) == JSON.stringify(CONTRACT_NETWORK)); }); it("Should instantiate correct instance of Contract from blockchain account name", async () => { const faucetContract = await eoslime.Contract.at(faucetAccount.name, faucetAccount); assert(typeof faucetContract.actions.produce == "function"); assert(typeof faucetContract.actions.withdraw == "function"); assert(faucetContract.name == faucetAccount.name); assert(JSON.stringify(faucetContract.executor) == JSON.stringify(faucetAccount)); assert(JSON.stringify(faucetContract.provider.network) == JSON.stringify(CONTRACT_NETWORK)); }); it("Should set default account as executor if none is provided", async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name); // In local network -> eosio is the preset default account assert(JSON.stringify(faucetContract.executor) == JSON.stringify(faucetContract.provider.defaultAccount)); }); it("Should throw if one provide incorrect account as a contract executor", async () => { try { const tokensHolder = await eoslime.Account.createRandom(); const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, "INVALID"); eoslime.Provider.defaultAccount = ''; await faucetContract.actions.produce([tokensHolder.name, "100.0000 TKNS", tokenContract.name, "memo"]); assert(false, "Should throw"); } catch (error) { assert(error.message.includes("Provided String is not an instance of BaseAccount")); } }); }); describe("Deployment", function () { it("Should deploy a contract from file on a random account", async () => { const faucetContract = await eoslime.Contract.deploy(FAUCET_WASM_PATH, FAUCET_ABI_PATH); const deployedABI = await eoslime.Provider.getABI(faucetContract.name); assert(deployedABI); }); it("Should deploy a contract from file on provided account", async () => { const contractAccount = await eoslime.Account.createRandom(); const initialABI = await eoslime.Provider.getABI(contractAccount.name); await eoslime.Contract.deployOnAccount(FAUCET_WASM_PATH, FAUCET_ABI_PATH, contractAccount); const deployedABI = await eoslime.Provider.getABI(contractAccount.name); assert(initialABI == undefined); assert(deployedABI); }); it("Should deploy a contract from raw data on a random account", async () => { const contractA = await eoslime.Contract.deploy(FAUCET_WASM_PATH, FAUCET_ABI_PATH); const contractA_ABI = await eoslime.Provider.getABI(contractA.name); const contractA_WASM = await eoslime.Provider.getRawWASM(contractA.name); const contractB = await eoslime.Contract.deployRaw(contractA_WASM, contractA_ABI); const contractB_ABI = await eoslime.Provider.getABI(contractB.name); const contractB_WASM = await eoslime.Provider.getRawWASM(contractB.name); assert(contractA_WASM == contractB_WASM); assert(JSON.stringify(contractA_ABI) == JSON.stringify(contractB_ABI)); }); it("Should deploy a contract from raw data on provided account", async () => { const contractA = await eoslime.Contract.deploy(FAUCET_WASM_PATH, FAUCET_ABI_PATH); const contractA_ABI = await eoslime.Provider.getABI(contractA.name); const contractA_WASM = await eoslime.Provider.getRawWASM(contractA.name); const contractB_Account = await eoslime.Account.createRandom(); const initialABI = await eoslime.Provider.getABI(contractB_Account.name); const contractB = await eoslime.Contract.deployRawOnAccount(contractA_WASM, contractA_ABI, contractB_Account); const contractB_ABI = await eoslime.Provider.getABI(contractB.name); const contractB_WASM = await eoslime.Provider.getRawWASM(contractB.name); assert(initialABI == undefined); assert(contractA_WASM == contractB_WASM); assert(JSON.stringify(contractA_ABI) == JSON.stringify(contractB_ABI)); }); }); describe("Blockchain methods", function () { it("Should execute a blockchain method from the provided executor", async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const tokensHolder = await eoslime.Account.createRandom(); // faucetAccount is the executor await faucetContract.actions.produce([tokensHolder.name, "100.0000 TKNS", tokenContract.name, "memo"]); const result = await faucetContract.tables.withdrawers.limit(1).equal(tokensHolder.name).find(); assert(result[0].quantity == PRODUCED_TOKENS_AMOUNT); assert(result[0].token_name == tokenContract.name); }); it("Should execute a blockchain method from another executor", async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const tokensHolder = await eoslime.Account.createRandom(); const executor = await eoslime.Account.createRandom(); await faucetContract.actions.produce([tokensHolder.name, "100.0000 TKNS", tokenContract.name, "memo"], { from: executor }); // After the execution, the contract executor should be the same as the initially provided one assert(faucetContract.executor.name == faucetAccount.name); }); it('Should process nonce-action', async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const tokensHolder = await eoslime.Account.createRandom(); const executor = await eoslime.Account.createRandom(); await faucetContract.actions.produce([tokensHolder.name, '100.0000 TKNS', tokenContract.name, 'memo'], { from: executor, unique: true }); await faucetContract.actions.produce([tokensHolder.name, '100.0000 TKNS', tokenContract.name, 'memo'], { from: executor, unique: true }); assert(true); }); it('Should throw with duplicate transaction error', async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const tokensHolder = await eoslime.Account.createRandom(); const executor = await eoslime.Account.createRandom(); try { await faucetContract.actions.produce([tokensHolder.name, '100.0000 TKNS', tokenContract.name, 'memo'], { from: executor }); await faucetContract.actions.produce([tokensHolder.name, '100.0000 TKNS', tokenContract.name, 'memo'], { from: executor }); } catch (error) { assert(error.includes('duplicate transaction')); } }); function assertRawTransaction (tx, contractName) { assert(tx.expiration != undefined); assert(tx.ref_block_num != undefined); assert(tx.ref_block_prefix != undefined); assert(tx.max_net_usage_words != undefined); assert(tx.max_cpu_usage_ms != undefined); assert(tx.delay_sec != undefined); assert(tx.context_free_actions != undefined); assert(tx.actions != undefined); assert(tx.actions[0].name == 'produce'); assert(tx.actions[0].account == contractName); assert(tx.actions[0].data != undefined); assert(tx.actions[0].authorization != undefined); } it('Should get a raw transaction from action', async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const tokensHolder = await eoslime.Account.createRandom(); const rawActionTx = await faucetContract.actions.produce.getRawTransaction([tokensHolder.name, '100.0000 TKNS', tokenContract.name, 'memo']); assertRawTransaction(rawActionTx, faucetContract.name); }); it('Should get a raw transaction from payable action', async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const tokensHolder = await eoslime.Account.createRandom(); const rawActionTx = await faucetContract.actions.produce.getRawTransaction([tokensHolder.name, '100.0000 TKNS', tokenContract.name, 'memo'], { tokens: '5.<PASSWORD>' }); assertRawTransaction(rawActionTx, faucetContract.name); assert(rawActionTx.actions[1].name == 'transfer'); assert(rawActionTx.actions[1].account == 'eosio.token'); assert(rawActionTx.actions[1].data != undefined); assert(rawActionTx.actions[1].authorization != undefined); }); it('Should get a raw transaction from unique action', async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const tokensHolder = await eoslime.Account.createRandom(); const rawActionTx = await faucetContract.actions.produce.getRawTransaction([tokensHolder.name, '100.0000 TKNS', tokenContract.name, 'memo'], { unique: true }); assertRawTransaction(rawActionTx, faucetContract.name); assert(rawActionTx.actions[1].name == 'nonce'); assert(rawActionTx.actions[1].account == 'eosio.null'); assert(rawActionTx.actions[1].data != undefined); assert(rawActionTx.actions[1].authorization != undefined); }); function assertSignedTransaction (tx, contractName) { assert(tx.signatures.length == 1); assertRawTransaction(tx.transaction, contractName); } it('Should sign an action without broadcasting it', async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const tokensHolder = await eoslime.Account.createRandom(); const signer = await eoslime.Account.createRandom(); const signedActionTx = await faucetContract.actions.produce.sign([tokensHolder.name, '100.0000 TKNS', tokenContract.name, 'memo'], { from: signer }); assertSignedTransaction(signedActionTx, faucetContract.name); }); it('Should sign a payable action ', async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const tokensHolder = await eoslime.Account.createRandom(); const signer = await eoslime.Account.createRandom(); const signedActionTx = await faucetContract.actions.produce.sign([tokensHolder.name, '100.0000 TKNS', tokenContract.name, 'memo'], { tokens: '5.<PASSWORD>', from: signer }); assertSignedTransaction(signedActionTx, faucetContract.name); assert(signedActionTx.transaction.actions[1].name == 'transfer'); assert(signedActionTx.transaction.actions[1].account == 'eosio.token'); assert(signedActionTx.transaction.actions[1].data != undefined); assert(signedActionTx.transaction.actions[1].authorization != undefined); }); it('Should sign unique action ', async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const tokensHolder = await eoslime.Account.createRandom(); const signer = await eoslime.Account.createRandom(); const signedActionTx = await faucetContract.actions.produce.sign([tokensHolder.name, '100.0000 TKNS', tokenContract.name, 'memo'], { unique: true, from: signer }); assertSignedTransaction(signedActionTx, faucetContract.name); assert(signedActionTx.transaction.actions[1].name == 'nonce'); assert(signedActionTx.transaction.actions[1].account == 'eosio.null'); assert(signedActionTx.transaction.actions[1].data != undefined); assert(signedActionTx.transaction.actions[1].authorization != undefined); }); it('Should throw if trying to sign the action with an invalid signer', async () => { try { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const tokensHolder = await eoslime.Account.createRandom(); await faucetContract.actions.produce.sign([tokensHolder.name, '100.0000 TKNS', tokenContract.name, 'memo'], { from: 'Fake signer' }); } catch (error) { assert(error.message.includes('String is not an instance of BaseAccount')); } }); }); describe("Blockchain tables", function () { it("Should have a default table getter", async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name); // withdrawers is a table in the contract assert(faucetContract.tables.withdrawers); }); it("Should apply the default query params if none provided", async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name); const tokensHolder = await eoslime.Account.createRandom(); // faucetAccount is the executor await faucetContract.actions.produce([tokensHolder.name, "100.0000 TKNS", tokenContract.name, "memo"]); const allWithdrawers = await faucetContract.tables.withdrawers.find(); assert(allWithdrawers[0].quantity == PRODUCED_TOKENS_AMOUNT); assert(allWithdrawers[0].token_name == tokenContract.name); }); it("Should query a table", async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name); const tokensHolder = await eoslime.Account.createRandom(); // faucetAccount is the executor await faucetContract.actions.produce([tokensHolder.name, "100.0000 TKNS", tokenContract.name, "memo"]); // With equal criteria const equalResult = await faucetContract.tables.withdrawers.equal(tokensHolder.name).find(); assert(equalResult[0].quantity == PRODUCED_TOKENS_AMOUNT); assert(equalResult[0].token_name == tokenContract.name); // With range criteria const rangeResult = await faucetContract.tables.withdrawers.range(0, 100 * TOKEN_PRECISION).index(2).find(); assert(rangeResult[0].quantity == PRODUCED_TOKENS_AMOUNT); assert(rangeResult[0].token_name == tokenContract.name); // With limit // There is only one withdrawer const allWithdrawers = await faucetContract.tables.withdrawers.limit(10).find(); assert(allWithdrawers.length == 1); assert(allWithdrawers[0].quantity == PRODUCED_TOKENS_AMOUNT); assert(allWithdrawers[0].token_name == tokenContract.name); // With different index (By Balance) const balanceWithdrawers = await faucetContract.tables.withdrawers.equal(100 * TOKEN_PRECISION).index(2).find(); assert(balanceWithdrawers[0].quantity == PRODUCED_TOKENS_AMOUNT); assert(balanceWithdrawers[0].token_name == tokenContract.name); }); }); describe("Inline a contract", function () { it("Should execute a blockchain method which makes inline transaction to another contract", async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); await faucetContract.makeInline(); const tokensHolder = await eoslime.Account.createRandom(); await faucetContract.actions.produce([tokensHolder.name, PRODUCED_TOKENS_AMOUNT, tokenContract.name, "memo"]); const tokensHolderBeforeBalance = await tokensHolder.getBalance("TKNS", tokenContract.name); assert(tokensHolderBeforeBalance.length == 0); // withdraw method behind the scene calls token's contract issue method await faucetContract.actions.withdraw([tokensHolder.name]); const tokensHolderAfterBalance = await tokensHolder.getBalance("TKNS", tokenContract.name); assert(tokensHolderAfterBalance[0] == PRODUCED_TOKENS_AMOUNT); }); it("Should throw if one tries to inline a contract, but the contract's executor is not the account on which the contract has been deployed", async () => { try { const contractExecutor = await eoslime.Account.createRandom(); const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, contractExecutor); await faucetContract.makeInline(); assert(false, "Should throw"); } catch (error) { assert( error.message.includes( "In order to make a contract inline one, the contract executor should be the account, on which the contract is deployed" ) ); } }); }); describe("Retrieve raw WASM", function () { it("Should retrieve contract raw WASM", async () => { const faucetContract = eoslime.Contract.fromFile(FAUCET_ABI_PATH, faucetAccount.name, faucetAccount); const contractWASM = await faucetContract.getRawWASM(); assert(contractWASM.endsWith('='), 'Not correctly encoded WASM'); }); }); });
all-of-us/raw-data-repository
tests/tool_tests/test_app_engine_manager.py
from datetime import datetime from rdr_service.tools.tool_libs.app_engine_manager import DeployAppClass from tests.helpers.unittest_base import BaseTestCase class AppEngineManagerTest(BaseTestCase): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.uses_database = False def test_deploy_date_calculation(self): expected_release_date = 'Jan 21, 2021' run_date = datetime(2021, 1, 14, 15, 49) # 2021-1-14 3:49pm self.assertEqual(expected_release_date, DeployAppClass.find_prod_release_date(run_date), 'Deploying on a Thursday should give a release date for the next Thursday') run_date = datetime(2021, 1, 15, 17, 16) # 2021-1-15 5:16pm self.assertEqual(expected_release_date, DeployAppClass.find_prod_release_date(run_date), 'Deploying on a Friday should also give a release date for the next Thursday') run_date = datetime(2021, 1, 18, 9, 43) # 2021-1-18 9:43am self.assertEqual(expected_release_date, DeployAppClass.find_prod_release_date(run_date), 'A late release on a Monday morning should give a release date for the upcoming Thursday') run_date = datetime(2021, 1, 13, 18, 9) # 2021-1-13 6:09pm self.assertEqual(expected_release_date, DeployAppClass.find_prod_release_date(run_date), 'Cutting a release early on Wednesday should set the deploy time for next week')
BarisSari/django_crud
salika/views/city_views.py
from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.list import ListView from ..models import City from ..forms import CityForm from django.urls import reverse_lazy from django.urls import reverse from django.http import Http404 class CityListView(ListView): model = City template_name = "salika/city_list.html" paginate_by = 20 context_object_name = "city_list" allow_empty = True page_kwarg = 'page' paginate_orphans = 0 def __init__(self, **kwargs): return super(CityListView, self).__init__(**kwargs) def dispatch(self, *args, **kwargs): return super(CityListView, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): return super(CityListView, self).get(request, *args, **kwargs) def get_queryset(self): return super(CityListView, self).get_queryset() def get_allow_empty(self): return super(CityListView, self).get_allow_empty() def get_context_data(self, *args, **kwargs): ret = super(CityListView, self).get_context_data(*args, **kwargs) return ret def get_paginate_by(self, queryset): return super(CityListView, self).get_paginate_by(queryset) def get_context_object_name(self, object_list): return super(CityListView, self).get_context_object_name(object_list) def paginate_queryset(self, queryset, page_size): return super(CityListView, self).paginate_queryset(queryset, page_size) def get_paginator(self, queryset, per_page, orphans=0, allow_empty_first_page=True): return super(CityListView, self).get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True) def render_to_response(self, context, **response_kwargs): return super(CityListView, self).render_to_response(context, **response_kwargs) def get_template_names(self): return super(CityListView, self).get_template_names() class CityDetailView(DetailView): model = City template_name = "salika/city_detail.html" context_object_name = "city" slug_field = 'slug' slug_url_kwarg = 'slug' pk_url_kwarg = 'pk' def __init__(self, **kwargs): return super(CityDetailView, self).__init__(**kwargs) def dispatch(self, *args, **kwargs): return super(CityDetailView, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): return super(CityDetailView, self).get(request, *args, **kwargs) def get_object(self, queryset=None): return super(CityDetailView, self).get_object(queryset) def get_queryset(self): return super(CityDetailView, self).get_queryset() def get_slug_field(self): return super(CityDetailView, self).get_slug_field() def get_context_data(self, **kwargs): ret = super(CityDetailView, self).get_context_data(**kwargs) return ret def get_context_object_name(self, obj): return super(CityDetailView, self).get_context_object_name(obj) def render_to_response(self, context, **response_kwargs): return super(CityDetailView, self).render_to_response(context, **response_kwargs) def get_template_names(self): return super(CityDetailView, self).get_template_names() class CityCreateView(CreateView): model = City form_class = CityForm # fields = ['city_id', 'city', 'country', 'last_update'] template_name = "salika/city_create.html" success_url = reverse_lazy("city_list") def __init__(self, **kwargs): return super(CityCreateView, self).__init__(**kwargs) def dispatch(self, request, *args, **kwargs): return super(CityCreateView, self).dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): return super(CityCreateView, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): return super(CityCreateView, self).post(request, *args, **kwargs) def get_form_class(self): return super(CityCreateView, self).get_form_class() def get_form(self, form_class=None): return super(CityCreateView, self).get_form(form_class) def get_form_kwargs(self, **kwargs): return super(CityCreateView, self).get_form_kwargs(**kwargs) def get_initial(self): return super(CityCreateView, self).get_initial() def form_invalid(self, form): return super(CityCreateView, self).form_invalid(form) def form_valid(self, form): obj = form.save(commit=False) obj.save() return super(CityCreateView, self).form_valid(form) def get_context_data(self, **kwargs): ret = super(CityCreateView, self).get_context_data(**kwargs) return ret def render_to_response(self, context, **response_kwargs): return super(CityCreateView, self).render_to_response(context, **response_kwargs) def get_template_names(self): return super(CityCreateView, self).get_template_names() def get_success_url(self): return reverse("salika:city_detail", args=(self.object.pk,)) class CityUpdateView(UpdateView): model = City form_class = CityForm # fields = ['city_id', 'city', 'country', 'last_update'] template_name = "salika/city_update.html" initial = {} slug_field = 'slug' slug_url_kwarg = 'slug' pk_url_kwarg = 'pk' context_object_name = "city" def __init__(self, **kwargs): return super(CityUpdateView, self).__init__(**kwargs) def dispatch(self, *args, **kwargs): return super(CityUpdateView, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): return super(CityUpdateView, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): return super(CityUpdateView, self).post(request, *args, **kwargs) def get_object(self, queryset=None): return super(CityUpdateView, self).get_object(queryset) def get_queryset(self): return super(CityUpdateView, self).get_queryset() def get_slug_field(self): return super(CityUpdateView, self).get_slug_field() def get_form_class(self): return super(CityUpdateView, self).get_form_class() def get_form(self, form_class=None): return super(CityUpdateView, self).get_form(form_class) def get_form_kwargs(self, **kwargs): return super(CityUpdateView, self).get_form_kwargs(**kwargs) def get_initial(self): return super(CityUpdateView, self).get_initial() def form_invalid(self, form): return super(CityUpdateView, self).form_invalid(form) def form_valid(self, form): obj = form.save(commit=False) obj.save() return super(CityUpdateView, self).form_valid(form) def get_context_data(self, **kwargs): ret = super(CityUpdateView, self).get_context_data(**kwargs) return ret def get_context_object_name(self, obj): return super(CityUpdateView, self).get_context_object_name(obj) def render_to_response(self, context, **response_kwargs): return super(CityUpdateView, self).render_to_response(context, **response_kwargs) def get_template_names(self): return super(CityUpdateView, self).get_template_names() def get_success_url(self): return reverse("salika:city_detail", args=(self.object.pk,)) class CityDeleteView(DeleteView): model = City template_name = "salika/city_delete.html" slug_field = 'slug' slug_url_kwarg = 'slug' pk_url_kwarg = 'pk' context_object_name = "city" def __init__(self, **kwargs): return super(CityDeleteView, self).__init__(**kwargs) def dispatch(self, *args, **kwargs): return super(CityDeleteView, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): raise Http404 def post(self, request, *args, **kwargs): return super(CityDeleteView, self).post(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return super(CityDeleteView, self).delete(request, *args, **kwargs) def get_object(self, queryset=None): return super(CityDeleteView, self).get_object(queryset) def get_queryset(self): return super(CityDeleteView, self).get_queryset() def get_slug_field(self): return super(CityDeleteView, self).get_slug_field() def get_context_data(self, **kwargs): ret = super(CityDeleteView, self).get_context_data(**kwargs) return ret def get_context_object_name(self, obj): return super(CityDeleteView, self).get_context_object_name(obj) def render_to_response(self, context, **response_kwargs): return super(CityDeleteView, self).render_to_response(context, **response_kwargs) def get_template_names(self): return super(CityDeleteView, self).get_template_names() def get_success_url(self): return reverse("salika:city_list")
chgogos/oop
lab2020-2021/wx_examples/5_layout/2_sizer/main.cpp
<reponame>chgogos/oop<filename>lab2020-2021/wx_examples/5_layout/2_sizer/main.cpp<gh_stars>10-100 #include "sizer.h" #include <wx/wx.h> class MyApp : public wxApp { public: virtual bool OnInit(); }; IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { Sizer *sizer = new Sizer(wxT("Sizer")); sizer->Show(true); return true; }
insad/jworkflow
samples/sample02/src/main/java/net/jworkflow/sample02/Main.java
package net.jworkflow.sample02; import net.jworkflow.kernel.interfaces.WorkflowHost; import net.jworkflow.WorkflowModule; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import net.jworkflow.providers.aws.DynamoDBPersistenceProvider; import software.amazon.awssdk.regions.Region; public class Main { public static void main(String[] args) throws Exception { Logger rootLogger = Logger.getLogger(""); rootLogger.setLevel(Level.SEVERE); WorkflowModule module = new WorkflowModule(); //module.useDistibutedLock(new DynamoDBLockProvider(Region.US_WEST_1, "jworkflowLocks")); module.usePersistence(new DynamoDBPersistenceProvider(Region.US_WEST_1, "j-sample2")); module.build(); WorkflowHost host = module.getHost(); host.registerWorkflow(DataWorkflow.class); host.start(); MyData data = new MyData(); data.value1 = 2; data.value2 = 3; String id = host.startWorkflow("data-workflow", 1, data); System.out.println("started workflow " + id); Scanner scanner = new Scanner(System.in); scanner.nextLine(); System.out.println("shutting down..."); host.stop(); } }
ectucker1/ectert
src/math/transform.h
#pragma once #include "matrix.h" Matrix translation(float x, float y, float z); Matrix scaling(float x, float y, float z); Matrix rotation_x(float r); Matrix rotation_y(float r); Matrix rotation_z(float r); Matrix shearing(float x_y, float x_z, float y_x, float y_z, float z_x, float z_y); Matrix view_transform(Tuple from, Tuple to, Tuple up);
AxaGuilDEv/ml-cli
src/Ml.Cli.WebApp/ClientApp/src/Server/Project/List/Home.container.spec.js
<filename>src/Ml.Cli.WebApp/ClientApp/src/Server/Project/List/Home.container.spec.js import '@testing-library/jest-dom/extend-expect'; import React from 'react'; import { render, waitFor } from '@testing-library/react'; import { HomeContainer } from './Home.container'; import {BrowserRouter as Router} from "react-router-dom"; const fetch = () => Promise.resolve([{ "id": "0001", "name": "<NAME>", "classification": "Publique", "numberTagToDo": 10, "createDate": "04/04/2011", "typeAnnotation": "NER", "text": "Enim ad ex voluptate culpa non cillum eu mollit nulla ex pariatur duis. Commodo officia deserunt elit sint officia consequat elit laboris tempor qui est ex. Laborum magna id deserunt ut fugiat aute nulla in Lorem pariatur. Nostrud elit consectetur exercitation exercitation incididunt consequat occaecat velit voluptate nostrud sunt. Consectetur velit eu amet minim quis sunt in.", }]); describe('Home.container', () => { it('HomeContainer render correctly', async () => { const { asFragment, getByText } = render(<Router><HomeContainer fetch={fetch} /></Router>); const messageEl = await waitFor(() => getByText('Publique')); expect(messageEl).toHaveTextContent( 'Publique' ); expect(asFragment()).toMatchSnapshot(); }); });
lowellmower/unum-sdk
src/unum/log/log_common.h
<reponame>lowellmower/unum-sdk<gh_stars>0 // Copyright 2018 Minim Inc // // 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. // Unum logging subsystem include #ifndef _LOG_COMMON_H #define _LOG_COMMON_H // Default log output destinations for log() and log_dbg() macros. // It can be redefined to make all the log() macros in a file point // to the different log destination. See also set_log_dst_*() functions. #define LOG_DST LOG_DST_UNUM #define LOG_DBG_DST LOG_DST_CONSOLE /*LOG_DST_DEBUG*/ // Logging macros (see note about LOG_DST/LOG_DBG_DST above) #define log(args...) unum_log(LOG_DST, args) #ifdef DEBUG # define log_dbg(args...) unum_log(LOG_DBG_DST, args) #else // DEBUG # define log_dbg(args...) /* Nothing */ #endif // DEBUG // Max log file pathsname length the code will deal with #define LOG_MAX_PATH 128 // Enum of available log output destinations typedef enum { LOG_DST_STDOUT, // logging to stdout (should be first) LOG_DST_CONSOLE, // logging to the serial console LOG_DST_UNUM, // generic agent logging to a file LOG_DST_HTTP, // HTTP req/rsp logging to a file LOG_DST_MONITOR, // monitor process logging to a file #ifdef FW_UPDATER_OPMODE LOG_DST_UPDATE, // firmware updater process, file LOG_DST_UPDATE_MONITOR, // updater monitor, file #endif // FW_UPDATER_OPMODE #ifdef SUPPORT_OPMODE LOG_DST_SUPPORT, // support portal process, file #endif // SUPPORT_OPMODE #ifdef DEBUG LOG_DST_DEBUG, // debug logging to a file #endif // DEBUG LOG_DST_DROP, // drop the messages (keep it last) LOG_DST_MAX } LOG_DST_t; // Patname template for building log file names when rotating. The // sprintf() parameters are the log name and the integer file number. #define LOG_ROTATE_TEMPLATE "%s.%d" // Log rotation cleanup number (if log setup changes from // X to Y, and Y < X log_init will clean up all the old // log names from Y to LOG_ROTATE_CLEANUP_MAX) #define LOG_ROTATE_CLEANUP_MAX 9 // The 16 lower bits are common flags. The upper 16bits are // platform specific flags (LOG_FLAG_FILE, LOG_FLAG_STDOUT... // see log_platform.h). #define LOG_FLAG_INIT_DONE 0x0001 // The entry has been initialized #define LOG_FLAG_INIT_FAIL 0x0002 // The log entry init has failed #define LOG_FLAG_MUTEX 0x0004 // The entry requre mutex protextion #define LOG_FLAG_INIT_MSG 0x0008 // Log the agent startup info at init // Logging control & configurtion structure (defines the elements of // the logging config array of LOG_DST_MAX size). typedef struct { unsigned int flags;// see LOG_FLAG_* above UTIL_MUTEX_t m; // mutex protection (across threads, not processes) char *name; // for the "file" mode file pathname template size_t max_size; // rotate file if reaches the max_size size_t cut_size; // cut to the size (in case exceeding max_size too much) unsigned int max; // files to keep when rotating (in addition to the log) FILE *f; // current log file pointer } LOG_CONFIG_t; // Logging configuration and control structure (see log_platform.c) extern LOG_CONFIG_t log_cfg[]; // Log print function void unum_log(LOG_DST_t dst, char *str, ...); // Set/clear default log destination for the process (until cleared overrides // LOG_DST macro value for the process and its children) int set_proc_log_dst(LOG_DST_t dst); void clear_proc_log_dst(); // Set disabled log destinations bitmask. Takes bitmask with // bits for the logs that should be disabled set. void set_disabled_log_dst_mask(unsigned long mask); // Log subsystem init function int log_init(int level); #endif // _LOG_COMMON_H
joergkrause/texxtoor
Texxtoor/Solution/Texxtoor.Portal/Scripts/reader/js/tools.js
Array.prototype.single = function(delegate) { if (delegate && typeof(delegate) == 'function') { for (var i = 0; i < this.length; ++i) { if (delegate(this[i])) return this[i]; } } return null; }; Array.prototype.each = function(delegate) { if (delegate && typeof(delegate) == 'function') { var arr = []; for (var i = 0; i < this.length; ++i) { arr.push(delegate(this[i])); } return arr; } return this; }; Array.prototype.pushAll = function(arr) { if (arr) { var $this = this; arr.each(function(item) { $this.push(item); }); } return this; }; Array.prototype.where = function(delegate) { if (delegate && typeof(delegate) == 'function') { var arr = []; for (var i = 0; i < this.length; ++i) { if (delegate(this[i])) arr.push(this[i]); } return arr; } return this; }; Array.prototype.last = function() { return this[this.length - 1]; }; Array.prototype.first = function() { return this[0]; }; Array.prototype.orderBy = function(strField, boolDescending) { var a = null, b = null, c = null; if (strField) { var fields = strField.split('.'); a = fields[0] ? fields[0] : null; b = fields[1] ? fields[1] : null; c = fields[2] ? fields[2] : null; } if (boolDescending) this.sort(function(x, y) { var arg1 = x, arg2 = y; if (a && x[a]) { arg1 = x[a]; arg2 = y[a]; if (b && x[a][b]) { arg1 = x[a][b]; arg2 = y[a][b]; if (c && x[a][b][c]) { arg1 = x[a][b][c]; arg2 = y[a][b][c]; } } } if (arg1 < arg2) return 1; else if (arg1 > arg2) return -1; return 0; }); else this.sort(function(x, y) { var arg1 = x, arg2 = y; if (a && x[a]) { arg1 = x[a]; arg2 = y[a]; if (b && x[a][b]) { arg1 = x[a][b]; arg2 = y[a][b]; if (c && x[a][b][c]) { arg1 = x[a][b][c]; arg2 = y[a][b][c]; } } } if (arg1 < arg2) return -1; else if (arg1 > arg2) return 1; return 0; }); return this; }; Array.prototype.isEmpty = function() { if (this.length > 0) return false; return true; };
javgat/devtest
BackEnd/restapi/operations/test/get_public_tests_responses.go
<reponame>javgat/devtest // Code generated by go-swagger; DO NOT EDIT. package test // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "net/http" "github.com/go-openapi/runtime" "uva-devtest/models" ) // GetPublicTestsOKCode is the HTTP code returned for type GetPublicTestsOK const GetPublicTestsOKCode int = 200 /*GetPublicTestsOK tests found swagger:response getPublicTestsOK */ type GetPublicTestsOK struct { /* In: Body */ Payload []*models.Test `json:"body,omitempty"` } // NewGetPublicTestsOK creates GetPublicTestsOK with default headers values func NewGetPublicTestsOK() *GetPublicTestsOK { return &GetPublicTestsOK{} } // WithPayload adds the payload to the get public tests o k response func (o *GetPublicTestsOK) WithPayload(payload []*models.Test) *GetPublicTestsOK { o.Payload = payload return o } // SetPayload sets the payload to the get public tests o k response func (o *GetPublicTestsOK) SetPayload(payload []*models.Test) { o.Payload = payload } // WriteResponse to the client func (o *GetPublicTestsOK) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(200) payload := o.Payload if payload == nil { // return empty array payload = make([]*models.Test, 0, 50) } if err := producer.Produce(rw, payload); err != nil { panic(err) // let the recovery middleware deal with this } } // GetPublicTestsBadRequestCode is the HTTP code returned for type GetPublicTestsBadRequest const GetPublicTestsBadRequestCode int = 400 /*GetPublicTestsBadRequest Incorrect Request, or invalida data swagger:response getPublicTestsBadRequest */ type GetPublicTestsBadRequest struct { /* In: Body */ Payload *models.Error `json:"body,omitempty"` } // NewGetPublicTestsBadRequest creates GetPublicTestsBadRequest with default headers values func NewGetPublicTestsBadRequest() *GetPublicTestsBadRequest { return &GetPublicTestsBadRequest{} } // WithPayload adds the payload to the get public tests bad request response func (o *GetPublicTestsBadRequest) WithPayload(payload *models.Error) *GetPublicTestsBadRequest { o.Payload = payload return o } // SetPayload sets the payload to the get public tests bad request response func (o *GetPublicTestsBadRequest) SetPayload(payload *models.Error) { o.Payload = payload } // WriteResponse to the client func (o *GetPublicTestsBadRequest) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(400) if o.Payload != nil { payload := o.Payload if err := producer.Produce(rw, payload); err != nil { panic(err) // let the recovery middleware deal with this } } } // GetPublicTestsForbiddenCode is the HTTP code returned for type GetPublicTestsForbidden const GetPublicTestsForbiddenCode int = 403 /*GetPublicTestsForbidden Not authorized to this content swagger:response getPublicTestsForbidden */ type GetPublicTestsForbidden struct { /* In: Body */ Payload *models.Error `json:"body,omitempty"` } // NewGetPublicTestsForbidden creates GetPublicTestsForbidden with default headers values func NewGetPublicTestsForbidden() *GetPublicTestsForbidden { return &GetPublicTestsForbidden{} } // WithPayload adds the payload to the get public tests forbidden response func (o *GetPublicTestsForbidden) WithPayload(payload *models.Error) *GetPublicTestsForbidden { o.Payload = payload return o } // SetPayload sets the payload to the get public tests forbidden response func (o *GetPublicTestsForbidden) SetPayload(payload *models.Error) { o.Payload = payload } // WriteResponse to the client func (o *GetPublicTestsForbidden) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.WriteHeader(403) if o.Payload != nil { payload := o.Payload if err := producer.Produce(rw, payload); err != nil { panic(err) // let the recovery middleware deal with this } } } // GetPublicTestsInternalServerErrorCode is the HTTP code returned for type GetPublicTestsInternalServerError const GetPublicTestsInternalServerErrorCode int = 500 /*GetPublicTestsInternalServerError Internal error swagger:response getPublicTestsInternalServerError */ type GetPublicTestsInternalServerError struct { } // NewGetPublicTestsInternalServerError creates GetPublicTestsInternalServerError with default headers values func NewGetPublicTestsInternalServerError() *GetPublicTestsInternalServerError { return &GetPublicTestsInternalServerError{} } // WriteResponse to the client func (o *GetPublicTestsInternalServerError) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses rw.WriteHeader(500) }
kschu91/harbor
src/server/middleware/security/session.go
// Copyright Project Harbor 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 security import ( "net/http" "net/http/httptest" "github.com/astaxie/beego" "github.com/goharbor/harbor/src/common/models" "github.com/goharbor/harbor/src/common/security" "github.com/goharbor/harbor/src/common/security/local" "github.com/goharbor/harbor/src/lib/log" ) type session struct{} func (s *session) Generate(req *http.Request) security.Context { log := log.G(req.Context()) store, err := beego.GlobalSessions.SessionStart(httptest.NewRecorder(), req) if err != nil { log.Errorf("failed to get the session store for request: %v", err) return nil } userInterface := store.Get("user") if userInterface == nil { return nil } user, ok := userInterface.(models.User) if !ok { log.Warning("can not convert the user in session to user model") return nil } log.Debugf("a session security context generated for request %s %s", req.Method, req.URL.Path) return local.NewSecurityContext(&user) }
gcruchon/react-toolkit
packages/Form/Input/switch/src/SwitchItem.js
import React from 'react'; import { InputManager } from '@axa-fr/react-toolkit-core'; const defaultClassName = 'af-form__radio-custom'; const SwitchItem = (props) => { const { disabled, value, isChecked, id, name, onChange, onBlur, onFocus, label, } = props; const newId = InputManager.getInputId(id); const newClassName = disabled ? `${defaultClassName} af-form__radio-custom--disabled` : defaultClassName; return ( <div className={newClassName} key={value}> <input className="af-form__input-radio" name={name} id={newId} type="radio" value={value} onChange={onChange} onBlur={onBlur} onFocus={onFocus} checked={isChecked} disabled={disabled} /> <label className="af-form__label" htmlFor={newId}> <span className="af-form__description">{label}</span> </label> </div> ); }; export default SwitchItem;
kivilu/ktf-dashboard-vue
src/store/modules/settings.js
<filename>src/store/modules/settings.js<gh_stars>0 import { getSettings } from '@/api/sys/dic' import { typeConvert } from '@/utils' import assign from 'lodash/assign' import defaultSettings from '@/settings' const { showSettings, tagsView, fixedHeader, sidebarLogo, settings } = defaultSettings const state = { showSettings: showSettings, tagsView: tagsView, fixedHeader: fixedHeader, sidebarLogo: sidebarLogo, settings: settings } const mutations = { CHANGE_SETTING: (state, { key, value }) => { if (state.hasOwnProperty(key)) { state[key] = value } } } const actions = { changeSetting({ commit }, data) { commit('CHANGE_SETTING', data) }, // get runtime setting getSettings({ commit, state }) { return new Promise((resolve, reject) => { getSettings() .then(({ code, msg, data }) => { if (data) { var settings = assign(defaultSettings.settings, data) // if (Array.isArray(data)) { // var settings = defaultSettings.settings // data.forEach(item => { // settings[item.key] = typeConvert( // item.value, // defaultSettings.settings[item.key] // ) // }) // var setting = { key: 'settings', value: settings } // commit('CHANGE_SETTING', setting) // } var setting = { key: 'settings', value: settings } commit('CHANGE_SETTING', setting) resolve(data) } }) .catch(error => { reject(error) }) }) } } export default { namespaced: true, state, mutations, actions }
NisalaNiroshana/developer-studio
capp/org.wso2.developerstudio.eclipse.capp.core/src/org/wso2/developerstudio/eclipse/capp/core/manifest/Artifacts.java
/* * Copyright (c) 2010, WSO2 Inc. (http://www.wso2.org) 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.wso2.developerstudio.eclipse.capp.core.manifest; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import javax.xml.stream.XMLStreamException; import org.apache.axiom.om.OMDocument; import org.apache.axiom.om.OMElement; import org.wso2.developerstudio.eclipse.capp.core.Activator; import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog; import org.wso2.developerstudio.eclipse.logging.core.Logger; public class Artifacts extends AbstractXMLDoc{ private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID); private List<Artifact> artifacts=new ArrayList<Artifact>(); protected String getDefaultName() { return "artifacts.xml"; } public void setArtifacts(List<Artifact> artifacts) { this.artifacts = artifacts; } public List<Artifact> getArtifacts() { return artifacts; } public OMElement getDocumentElement() { OMElement documentElement = getElement("artifacts", ""); for(Artifact artifact:getArtifacts()){ documentElement.addChild(artifact.getDocumentElement()); } return documentElement; } public String serialize() { String result = null; OMDocument document = factory.createOMDocument(); OMElement documentElement = getDocumentElement(); document.addChild(documentElement); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { prettify(documentElement, outputStream); } catch (XMLStreamException e) { log.error(e); return null; } catch (Exception e) { log.error(e); return null; } result = outputStream.toString(); return result; } protected void deserialize(OMElement documentElement) { } }
hychrisli/PyAlgorithms
src/solutions/part2/q090_subsets_ii.py
from src.base.solution import Solution from src.tests.part2.q090_test_subsets_ii import SubsetsIiTestCases class SubsetsIi(Solution): def verify_output(self, test_output, output): return test_output == output def run_test(self, input): return self.subsetsWithDup(input) def gen_test_cases(self): return SubsetsIiTestCases() def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() res, cnt, pre = [[]], 0, nums[0] nums.append('#') for num in nums: # print (pre, num, cnt) if pre == num: cnt += 1 continue tailsets, addset = [], [] while cnt > 0: addset.append(pre) cnt -= 1 # print(cnt, pre) for subset in res: newset = subset + addset tailsets.append(newset) res.extend(tailsets) pre, cnt = num, 1 return res if __name__ == '__main__': sol = SubsetsIi() sol.run_tests()
lob/rack
provider/local/system.go
package local import ( "bytes" "crypto/aes" "crypto/cipher" "encoding/hex" "fmt" "io" "io/ioutil" "net" "net/http" "os" "os/exec" "os/user" "text/template" "time" "github.com/lob/rack/pkg/structs" "github.com/pkg/errors" cv "github.com/convox/version" ) const ( aesKey = "AES256Key-32Characters1234567890" nonceHex = "37b8e8a308c354048d245f6d" ) var ( launcher = template.Must(template.New("launcher").Parse(launcherTemplate())) ) func (p *Provider) SystemDecrypt(data []byte) ([]byte, error) { log := p.logger("SystemDecrypt") block, err := aes.NewCipher([]byte(aesKey)) if err != nil { return nil, errors.WithStack(log.Error(err)) } nonce, err := hex.DecodeString(nonceHex) if err != nil { return nil, errors.WithStack(log.Error(err)) } aesgcm, err := cipher.NewGCM(block) if err != nil { return nil, errors.WithStack(log.Error(err)) } dec, err := aesgcm.Open(nil, nonce, data, nil) if err != nil { return nil, errors.WithStack(log.Error(err)) } return dec, log.Success() } func (p *Provider) SystemEncrypt(data []byte) ([]byte, error) { log := p.logger("SystemEncrypt") block, err := aes.NewCipher([]byte(aesKey)) if err != nil { return nil, errors.WithStack(log.Error(err)) } nonce, err := hex.DecodeString(nonceHex) if err != nil { return nil, errors.WithStack(log.Error(err)) } aesgcm, err := cipher.NewGCM(block) if err != nil { return nil, errors.WithStack(log.Error(err)) } enc, err := aesgcm.Seal(nil, nonce, data, nil), nil if err != nil { return nil, errors.WithStack(log.Error(err)) } return enc, log.Success() } func (p *Provider) SystemGet() (*structs.System, error) { log := p.logger("SystemGet") system := &structs.System{ Domain: fmt.Sprintf("rack.%s", p.Rack), Name: p.Rack, Provider: "local", Region: "local", Status: "running", Version: p.Version, } return system, log.Success() } func (p *Provider) SystemInstall(w io.Writer, opts structs.SystemInstallOptions) (string, error) { name := cs(opts.Name, "convox") var version string if opts.Version != nil { version = *opts.Version } else { v, err := cv.Latest() if err != nil { return "", err } version = v } id := cs(opts.Id, "") exe, err := os.Executable() if err != nil { return "", err } u, err := user.Current() if err != nil { return "", err } if u.Uid != "0" { return "", fmt.Errorf("must be root to install a local rack") } fmt.Fprintf(w, "pulling: convox/rack:%s\n", version) if err := launcherInstall("router", w, opts, exe, "router"); err != nil { return "", err } if err := launcherInstall(fmt.Sprintf("rack.%s", name), w, opts, exe, "rack", "start", "--id", id, "--name", name); err != nil { return "", err } url := fmt.Sprintf("https://rack.%s", name) fmt.Fprintf(w, "waiting for rack... ") tick := time.Tick(2 * time.Second) timeout := time.After(30 * time.Minute) ht := *(http.DefaultTransport.(*http.Transport)) ht.TLSClientConfig.InsecureSkipVerify = true hc := &http.Client{Transport: &ht} for { select { case <-tick: _, err := hc.Get(url) if err == nil { fmt.Fprintf(w, "OK\n") return url, nil } case <-timeout: return "", fmt.Errorf("timeout") } } } func (p *Provider) SystemLogs(opts structs.LogsOptions) (io.ReadCloser, error) { log := p.logger("SystemLogs") r, w := io.Pipe() hostname, err := os.Hostname() if err != nil { return nil, errors.WithStack(log.Error(err)) } args := []string{"logs"} if opts.Follow == nil || *opts.Follow { args = append(args, "-f") } if opts.Since != nil { args = append(args, "--since", time.Now().UTC().Add((*opts.Since)*-1).Format(time.RFC3339)) } args = append(args, hostname) cmd := exec.Command("docker", args...) cmd.Stdout = w cmd.Stderr = w if err := cmd.Start(); err != nil { return nil, errors.WithStack(log.Error(err)) } go func() { defer w.Close() cmd.Wait() }() return r, log.Success() } func (p *Provider) SystemMetrics(opts structs.MetricsOptions) (structs.Metrics, error) { return nil, fmt.Errorf("unimplemented") } func (p *Provider) SystemOptions() (map[string]string, error) { log := p.logger("SystemOptions") options := map[string]string{ "streaming": "websocket", } return options, log.Success() } func (p *Provider) SystemProcesses(opts structs.SystemProcessesOptions) (structs.Processes, error) { return nil, fmt.Errorf("unimplemented") } func (p *Provider) SystemProxy(host string, port int, in io.Reader) (io.ReadCloser, error) { log := p.logger("SystemProxy").Append("host=%s port=%d", host, port) cn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", host, port)) if err != nil { return nil, errors.WithStack(log.Error(err)) } go io.Copy(cn, in) return cn, log.Success() } func (p *Provider) SystemReleases() (structs.Releases, error) { return nil, fmt.Errorf("unimplemented") } func (p *Provider) SystemUninstall(name string, w io.Writer, opts structs.SystemUninstallOptions) error { u, err := user.Current() if err != nil { return err } if u.Uid != "0" { return fmt.Errorf("must be root to uninstall a local rack") } launcherRemove("rack", w) launcherRemove(fmt.Sprintf("rack.%s", name), w) return nil } func (p *Provider) SystemUpdate(opts structs.SystemUpdateOptions) error { log := p.logger("SystemUpdate").Append("version=%q", *opts.Version) if opts.Version != nil { v := *opts.Version if err := ioutil.WriteFile("/var/convox/version", []byte(v), 0644); err != nil { return errors.WithStack(log.Error(err)) } if err := exec.Command("docker", "pull", fmt.Sprintf("convox/rack:%s", v)).Run(); err != nil { return errors.WithStack(log.Error(err)) } go func() { time.Sleep(1 * time.Second) os.Exit(0) }() } return log.Success() } func launcherInstall(name string, w io.Writer, opts structs.SystemInstallOptions, command string, args ...string) error { var buf bytes.Buffer params := map[string]interface{}{ "Name": name, "Command": command, "Args": args, "Logs": fmt.Sprintf("/var/log/convox/%s.log", name), } if err := launcher.Execute(&buf, params); err != nil { return err } path := launcherPath(name) fmt.Fprintf(w, "installing: %s\n", path) if err := ioutil.WriteFile(path, buf.Bytes(), 0644); err != nil { return err } if err := launcherStart(name); err != nil { return err } return nil } func launcherRemove(name string, w io.Writer) error { path := launcherPath(name) fmt.Fprintf(w, "removing: %s\n", path) launcherStop(name) os.Remove(path) return nil }
Endervan/java_avancado
src/listas/duplamente/encadeadas/Main.java
package listas.duplamente.encadeadas; import listas.duplamente.encadeadas.ListaDuplamenteEncadeada; public class Main { public static void main(String[] args) { ListaDuplamenteEncadeada<String> minhaListaDuplaEncadeada = new ListaDuplamenteEncadeada<>(); minhaListaDuplaEncadeada.add("c1"); minhaListaDuplaEncadeada.add("c2"); minhaListaDuplaEncadeada.add("3"); minhaListaDuplaEncadeada.add("c4"); minhaListaDuplaEncadeada.add("c5"); minhaListaDuplaEncadeada.add("c6"); minhaListaDuplaEncadeada.add("c7"); System.out.println(minhaListaDuplaEncadeada); minhaListaDuplaEncadeada.remove(3); minhaListaDuplaEncadeada.add(3,"99"); System.out.println(minhaListaDuplaEncadeada); } }
cloudsmith-io/teku
ethereum/core/src/testFixtures/java/tech/pegasys/teku/core/BlockProposalTestUtil.java
<reponame>cloudsmith-io/teku /* * Copyright 2020 ConsenSys AG. * * 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 tech.pegasys.teku.core; import java.util.Optional; import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.crypto.Hash; import org.apache.tuweni.ssz.SSZ; import tech.pegasys.teku.bls.BLSSignature; import tech.pegasys.teku.core.signatures.Signer; import tech.pegasys.teku.infrastructure.unsigned.UInt64; import tech.pegasys.teku.spec.Spec; import tech.pegasys.teku.spec.config.SpecConfig; import tech.pegasys.teku.spec.datastructures.blocks.BeaconBlock; import tech.pegasys.teku.spec.datastructures.blocks.BeaconBlockAndState; import tech.pegasys.teku.spec.datastructures.blocks.Eth1Data; import tech.pegasys.teku.spec.datastructures.blocks.SignedBeaconBlock; import tech.pegasys.teku.spec.datastructures.blocks.SignedBlockAndState; import tech.pegasys.teku.spec.datastructures.operations.Attestation; import tech.pegasys.teku.spec.datastructures.operations.Deposit; import tech.pegasys.teku.spec.datastructures.operations.ProposerSlashing; import tech.pegasys.teku.spec.datastructures.operations.SignedVoluntaryExit; import tech.pegasys.teku.spec.datastructures.state.beaconstate.BeaconState; import tech.pegasys.teku.spec.datastructures.util.BeaconBlockBodyLists; import tech.pegasys.teku.spec.logic.common.statetransition.exceptions.EpochProcessingException; import tech.pegasys.teku.spec.logic.common.statetransition.exceptions.SlotProcessingException; import tech.pegasys.teku.spec.logic.common.statetransition.exceptions.StateTransitionException; import tech.pegasys.teku.ssz.SszList; public class BlockProposalTestUtil { private final Spec spec; private final BeaconBlockBodyLists blockBodyLists; public BlockProposalTestUtil(final Spec spec) { this.spec = spec; blockBodyLists = BeaconBlockBodyLists.ofSpec(spec); } public SignedBlockAndState createNewBlock( final Signer signer, final UInt64 newSlot, final BeaconState state, final Bytes32 parentBlockSigningRoot, final Eth1Data eth1Data, final SszList<Attestation> attestations, final SszList<ProposerSlashing> slashings, final SszList<Deposit> deposits, final SszList<SignedVoluntaryExit> exits) throws StateTransitionException, EpochProcessingException, SlotProcessingException { final UInt64 newEpoch = spec.computeEpochAtSlot(newSlot); final BLSSignature randaoReveal = signer.createRandaoReveal(newEpoch, state.getForkInfo()).join(); final BeaconState blockSlotState = spec.processSlots(state, newSlot); final BeaconBlockAndState newBlockAndState = spec.createNewUnsignedBlock( newSlot, spec.getBeaconProposerIndex(blockSlotState, newSlot), blockSlotState, parentBlockSigningRoot, builder -> builder .randaoReveal(randaoReveal) .eth1Data(eth1Data) .graffiti(Bytes32.ZERO) .attestations(attestations) .proposerSlashings(slashings) .attesterSlashings(blockBodyLists.createAttesterSlashings()) .deposits(deposits) .voluntaryExits(exits)); // Sign block and set block signature final BeaconBlock block = newBlockAndState.getBlock(); BLSSignature blockSignature = signer.signBlock(block, state.getForkInfo()).join(); final SignedBeaconBlock signedBlock = SignedBeaconBlock.create(spec, block, blockSignature); return new SignedBlockAndState(signedBlock, newBlockAndState.getState()); } public SignedBlockAndState createBlock( final Signer signer, final UInt64 newSlot, final BeaconState previousState, final Bytes32 parentBlockSigningRoot, final Optional<SszList<Attestation>> attestations, final Optional<SszList<Deposit>> deposits, final Optional<SszList<SignedVoluntaryExit>> exits, final Optional<Eth1Data> eth1Data) throws StateTransitionException, EpochProcessingException, SlotProcessingException { final UInt64 newEpoch = spec.computeEpochAtSlot(newSlot); return createNewBlock( signer, newSlot, previousState, parentBlockSigningRoot, eth1Data.orElse(get_eth1_data_stub(previousState, newEpoch)), attestations.orElse(blockBodyLists.createAttestations()), blockBodyLists.createProposerSlashings(), deposits.orElse(blockBodyLists.createDeposits()), exits.orElse(blockBodyLists.createVoluntaryExits())); } private Eth1Data get_eth1_data_stub(BeaconState state, UInt64 current_epoch) { final SpecConfig specConfig = spec.atSlot(state.getSlot()).getConfig(); final int epochsPerPeriod = specConfig.getEpochsPerEth1VotingPeriod(); UInt64 votingPeriod = current_epoch.dividedBy(epochsPerPeriod); return new Eth1Data( Hash.sha2_256(SSZ.encodeUInt64(epochsPerPeriod)), state.getEth1_deposit_index(), Hash.sha2_256(Hash.sha2_256(SSZ.encodeUInt64(votingPeriod.longValue())))); } public int getProposerIndexForSlot(final BeaconState preState, final UInt64 slot) { BeaconState state; try { state = spec.processSlots(preState, slot); } catch (SlotProcessingException | EpochProcessingException e) { throw new RuntimeException(e); } return spec.getBeaconProposerIndex(state, state.getSlot()); } }
tstarling/hhvm
hphp/third_party/libafdt/src/sync.c
<reponame>tstarling/hhvm #include <assert.h> #include <poll.h> #include <sys/time.h> #include "config.h" #include "afdt.h" #include "internal.h" int afdt_sync_client( const char* fname, const uint8_t* request, uint32_t request_length, uint8_t* response, uint32_t* response_length, int* received_fd, const struct timeval* timeout, struct afdt_error_t* err) { int ret; ret = afdt_connect(fname, err); if (ret < 0) { return ret; } int connfd = ret; ret = afdt_send_plain_msg(connfd, request, request_length, err); if (ret < 0) { return ret; } if (timeout != NULL) { struct pollfd pfd = { .fd = connfd, .events = POLLIN }; int timeout_ms = timeout->tv_sec * 1000 + timeout->tv_usec / 1000; ret = poll(&pfd, 1, timeout_ms); if (ret < 0) { set_error(err, AFDT_POLL, ""); return ret; } else if (ret == 0) { assert(!(pfd.revents & POLLIN)); set_error(err, AFDT_TIMEOUT, ""); return -1; } assert(ret == 1); assert(pfd.revents & POLLIN); } ret = afdt_recv_fd_msg(connfd, response, response_length, received_fd, err); if (ret < 0) { return ret; } return 0; }
marcomarasca/Synapse-Stack-Builder
src/main/java/org/sagebionetworks/template/repo/cloudwatchlogs/CloudwatchLogsConfigValidator.java
<reponame>marcomarasca/Synapse-Stack-Builder<gh_stars>0 package org.sagebionetworks.template.repo.cloudwatchlogs; import org.sagebionetworks.template.repo.beanstalk.EnvironmentType; import org.sagebionetworks.util.ValidateArgument; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; public class CloudwatchLogsConfigValidator { private CloudwatchLogsConfig config; public CloudwatchLogsConfigValidator(CloudwatchLogsConfig config) { this.config = config; } public CloudwatchLogsConfig validate() { Map<EnvironmentType, List<LogDescriptor>> logDescriptors = config.getLogDescriptors(); validateEnvironments(logDescriptors); for (EnvironmentType k: logDescriptors.keySet()) { List<LogDescriptor> descriptors = logDescriptors.get(k); if (descriptors.size() != 3) { throw new IllegalStateException("Each environment should have 3 logGroups"); } for (LogDescriptor d: descriptors) { this.validateLogDescriptor(d); } } return config; } private void validateLogDescriptor(LogDescriptor logDescriptor) { try { ValidateArgument.required(logDescriptor.getLogType(), "LogType"); ValidateArgument.required(logDescriptor.getDateFormat(), "dateFormat"); ValidateArgument.required(logDescriptor.getLogPath(), "logPath"); } catch (IllegalArgumentException e) { throw new IllegalStateException("Invalid log descriptor", e); } } private void validateEnvironments(Map<EnvironmentType, List<LogDescriptor>> logDescriptors) { Set<EnvironmentType> environmentTypes = logDescriptors.keySet(); if ((environmentTypes.size()!=3) || (!environmentTypes.containsAll(Arrays.asList(EnvironmentType.values())))) { throw new IllegalStateException("All environments types should appear once in configuration."); } } }
Acrisel/eventor
eventor/eventor/lib/utils.py
<filename>eventor/eventor/lib/utils.py ''' Created on Oct 19, 2016 @author: arnon ''' from acrilib import Sequence from logging.handlers import QueueListener import inspect import datetime import os import socket from types import FunctionType import yaml def is_require_op(op): if op in ['or', 'and']: return True return False def op_to_lambda(op): return "lambda x,y: x {} y".format(op) StepId = Sequence('_EventorStepId') EventId = Sequence('_EventorEventId') DelayId = Sequence('_EventorDelayId') def rest_sequences(): StepId.reset() EventId.reset() DelayId.reset() def get_step_id(): return "S%s" % StepId() def get_event_id(): return "E%s" % EventId() def get_delay_id(): return "d%s" % DelayId() def valid_step_name(name): return name.find('.') == -1 class CustomQueueListener(QueueListener): def __init__(self, queue, *handlers): super(CustomQueueListener, self).__init__(queue, *handlers) """ Initialise an instance with the specified queue and handlers. """ # Changing this to a list from tuple in the parent class self.handlers = list(handlers) def handle(self, record): """ Override handle a record. This just loops through the handlers offering them the record to handle. :param record: The record to handle. """ record = self.prepare(record) for handler in self.handlers: if record.levelno >= handler.level: # This check is not in the parent class handler.handle(record) def addHandler(self, hdlr): """ Add the specified handler to this logger. """ if not (hdlr in self.handlers): self.handlers.append(hdlr) def removeHandler(self, hdlr): """ Remove the specified handler from this logger. """ if hdlr in self.handlers: hdlr.close() self.handlers.remove(hdlr) def traces(trace): ''' File "/private/var/acrisel/sand/gradior/gradior/gradior/gradior/loop_task.py", line 41, in task_wrapper ''' result = ["File \"{}\", line {}, in {}\n {}" .format(frame.filename, frame.lineno, frame.function, frame.code_context[0].rstrip()) for frame in trace] return result def calling_module(depth=2): frame_records = inspect.stack()[depth] return frame_records.filename def store_from_module(module, module_location=False): location = os.path.dirname(module) name = os.path.basename(module) parts = name.rpartition('.') if parts[0]: if parts[2] == 'py': module_runner_file = parts[0] else: module_runner_file = name else: module_runner_file = parts[2] filename = '.'.join([module_runner_file, 'run.db']) if module_location: filename = os.path.join(location, filename) else: filename = os.path.join(os.getcwd(), filename) return filename # check if an object should be decorated def do_decorate(attr, value): # result = ('__' not in attr and result = (isinstance(value, FunctionType) and getattr(value, 'decorate', True)) return result # decorate all instance methods (unless excluded) with the same decorator def decorate_all(decorator): class DecorateAll(type): def __new__(cls, name, bases, dct): for attr, value in dct.items(): if do_decorate(attr, value): decorated = decorator(name, value) dct[attr] = decorated # print('decorated', attr, decorated) return super(DecorateAll, cls).__new__(cls, name, bases, dct) return DecorateAll # decorator to exclude methods def dont_decorate(f): f.decorate = False return f def print_method(print_func): def print_method_name(name, f): def wrapper(*args, **kwargs): print_func('entering method: %s.%s' % (name, f.__name__, )) start = datetime.datetime.now() result = f(*args, **kwargs) finish = datetime.datetime.now() print_func('exiting method: {}.{}, time span: {}' .format(name, f.__name__, str(finish - start))) return result return wrapper return print_method_name def port_is_open(host, port,): result = False try: s = socket.create_connection((host, port), 0.5) except socket.error: pass else: s.close() result = True return result LOCAL_HOST = '127.0.0.1' def get_free_port(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((LOCAL_HOST, 0)) host, port = s.getsockname() s.close() return host, port ''' Left here for reference only from acrilog import SSHLogger def logger_process_lambda(logger_info): logger_info = deepcopy(logger_info) def internal(name=None): if name is not None: logger_info['name'] = name logger = NwLogger.get_logger(logger_info) return logger return internal ''' if __name__ == '__main__': meta_decorator = decorate_all(print_method(print)) class Foo(metaclass=meta_decorator): def __init__(self): pass def bar(self): pass @dont_decorate def baz(self): pass @classmethod def test(self): pass foo = Foo() foo.bar() foo.bar()
AdamSwenson/TwitterProject
tests/TwitterDatabaseTests/DatabaseAccessObjectsTests/test_DataRepositories.py
import unittest from Repositories.DataRepositories import WordRepository class WordRespositoriesTest( unittest.TestCase ): def setUp(self): self.object = WordRepository() @unittest.skip def test_get_word_happy_modify_existing( self ): w = self.object.get_word( 'taco1' ) w.word = 'taco taco' result = self.object.write_to_db( w ) self.assertTrue( result ) if __name__ == '__main__': unittest.main( )
dmytrostriletskyi/dbnd
modules/dbnd-airflow/src/dbnd_airflow/export_plugin/api_functions.py
<filename>modules/dbnd-airflow/src/dbnd_airflow/export_plugin/api_functions.py<gh_stars>0 import collections import json import logging from functools import wraps from airflow.hooks.base_hook import BaseHook from airflow.models import DagModel from airflow.utils.db import provide_session from airflow.version import version as airflow_version import dbnd_airflow from dbnd._core.utils.json_utils import flatten_dict from dbnd._core.utils.uid_utils import get_airflow_instance_uid from dbnd_airflow.export_plugin.compat import get_api_mode from dbnd_airflow.export_plugin.dag_operations import ( get_current_dag_model, get_dags, load_dags_models, ) from dbnd_airflow.export_plugin.metrics import METRIC_COLLECTOR from dbnd_airflow.export_plugin.models import ( AirflowExportData, AirflowExportMeta, AirflowNewDagRun, DagRunsStatesData, FullRunsData, LastSeenData, NewRunsData, ) from dbnd_airflow.export_plugin.queries import ( find_all_logs_grouped_by_runs, find_full_dag_runs, find_max_dag_run_id, find_max_log_run_id, find_new_dag_runs, ) from dbnd_airflow.export_plugin.smart_dagbag import DbndDagLoader from dbnd_airflow.export_plugin.utils import AIRFLOW_VERSION_2 logger = logging.getLogger(__name__) DATABAND_AIRFLOW_CONN_ID = "dbnd_config" def safe_rich_result(f): @wraps(f) def wrapped(*args, **kwargs): with METRIC_COLLECTOR.use_local() as metrics: result = AirflowExportData() try: result = f(*args, **kwargs) except Exception as e: result = AirflowExportData() logger.exception("Exception during %s", f.__name__, exc_info=True) result.error_message = str(e) finally: result.airflow_export_meta = get_meta(metrics) return result return wrapped def get_meta(metrics): import flask meta = AirflowExportMeta( airflow_version=airflow_version, plugin_version=" ".join([dbnd_airflow.__version__, "v2"]), airflow_instance_uid=get_airflow_instance_uid(), api_mode=get_api_mode(), request_args=dict(flask.request.args) if flask.has_request_context() else {}, metrics={ "performance": metrics.get("perf_metrics", {}), "sizes": metrics.get("size_metrics", {}), }, ) return meta @safe_rich_result @provide_session def get_last_seen_values(session=None): max_dag_run_id = find_max_dag_run_id(session) max_log_id = find_max_log_run_id(session) return LastSeenData( last_seen_dag_run_id=max_dag_run_id, last_seen_log_id=max_log_id ) @safe_rich_result @provide_session def get_new_dag_runs( last_seen_dag_run_id, last_seen_log_id, extra_dag_runs_ids, dag_ids=None, include_subdags=True, session=None, ): max_dag_run_id = find_max_dag_run_id(session) max_log_id = find_max_log_run_id(session) if last_seen_dag_run_id is None: last_seen_dag_run_id = max_dag_run_id if last_seen_log_id is None: last_seen_log_id = max_log_id logs = find_all_logs_grouped_by_runs(last_seen_log_id, dag_ids, session) logs_dict = {(log.dag_id, log.execution_date): log for log in logs} dag_runs = find_new_dag_runs( last_seen_dag_run_id, extra_dag_runs_ids, logs_dict.keys(), dag_ids, include_subdags, session, ) new_dag_runs = [] for dag_run in dag_runs: log = logs_dict.get((dag_run.dag_id, dag_run.execution_date), None) if log is None: events = [] elif isinstance(log.events, str): # mysql, sqlite events = log.events.split(",") else: # postgres events = log.events new_dag_run = AirflowNewDagRun( id=dag_run.id, dag_id=dag_run.dag_id, execution_date=dag_run.execution_date, state=dag_run.state, is_paused=dag_run.is_paused, has_updated_task_instances=log is not None, events=events, max_log_id=log.id if log else None, ) new_dag_runs.append(new_dag_run) new_runs = NewRunsData( new_dag_runs=new_dag_runs, last_seen_dag_run_id=max_dag_run_id, last_seen_log_id=max_log_id, ) return new_runs @safe_rich_result @provide_session def get_full_dag_runs_for_plugin(dag_run_ids, include_sources, session=None): dbnd_dag_loader = DbndDagLoader() if AIRFLOW_VERSION_2: dbnd_dag_loader.load_dags_for_runs(dag_run_ids=dag_run_ids, session=session) else: import airflow if airflow.settings.RBAC: from airflow.www_rbac.views import dagbag else: from airflow.www.views import dagbag # this is preloaded dagbag, we are in UI context, dagbag is global variable which is loaded # we "load" all dags from the dagbag directly into DagLoader dbnd_dag_loader.load_from_dag_bag(dagbag) return get_full_dag_runs( dag_run_ids=dag_run_ids, include_sources=include_sources, dag_loader=dbnd_dag_loader, ) @safe_rich_result @provide_session def get_full_dag_runs(dag_run_ids, include_sources, dag_loader, session=None): old_get_current_dag = DagModel.get_current try: DagModel.get_current = get_current_dag_model load_dags_models(session) task_instances, dag_runs = find_full_dag_runs(dag_run_ids, session) dag_ids = set(run.dag_id for run in dag_runs) dags = get_dags(dag_loader, True, dag_ids, False, include_sources) full_runs = FullRunsData( task_instances=task_instances, dag_runs=dag_runs, dags=dags ) return full_runs finally: DagModel.get_current = old_get_current_dag @safe_rich_result @provide_session def get_dag_runs_states_data(dag_run_ids, session=None): task_instances, dag_runs = find_full_dag_runs(dag_run_ids, session) dag_runs_states_data = DagRunsStatesData( task_instances=task_instances, dag_runs=dag_runs ) return dag_runs_states_data def deep_update(source, overrides): """ Update a nested dictionary or similar mapping. Modify ``source`` in place. """ for key, value in overrides.items(): if isinstance(value, collections.Mapping) and value: returned = deep_update(source.get(key, {}), value) source[key] = returned else: source[key] = overrides[key] return source def remove_place_holders(dbnd_response): """Remove from configurations value which only have placeholders, so they won't override valid values.""" if dbnd_response.get("core") is not None: dbnd_response["core"].pop("databand_access_token", None) dbnd_response["core"].pop("databand_url", None) if not dbnd_response["core"]: dbnd_response.pop("core", None) def is_subset(subset, superset): return not (flatten_dict(subset).items() <= flatten_dict(superset).items()) @safe_rich_result @provide_session def check_syncer_config_and_set(dbnd_response, session=None): airflow_databand_connection = BaseHook.get_connection(DATABAND_AIRFLOW_CONN_ID) airflow_response = airflow_databand_connection.extra_dejson remove_place_holders(dbnd_response) if is_subset(dbnd_response, airflow_response): deep_update(airflow_response, dbnd_response) airflow_databand_connection.set_extra(json.dumps(airflow_response, indent=True)) session.add(airflow_databand_connection) session.commit() return AirflowExportData()
Kirishikesan/haiku
src/apps/icon-o-matic/generic/command/CompoundCommand.cpp
/* * Copyright 2006, Haiku. * Distributed under the terms of the MIT License. * * Authors: * <NAME> <<EMAIL>> */ #include "CompoundCommand.h" #include <stdio.h> // constructor CompoundCommand::CompoundCommand(Command** commands, int32 count, const char* name, int32 nameIndex) : Command(), fCommands(commands), fCount(count), fName(name), fNameIndex(nameIndex) { } // destructor CompoundCommand::~CompoundCommand() { for (int32 i = 0; i < fCount; i++) delete fCommands[i]; delete[] fCommands; } // InitCheck status_t CompoundCommand::InitCheck() { status_t status = fCommands && fCount > 0 ? B_OK : B_BAD_VALUE; return status; } // Perform status_t CompoundCommand::Perform() { status_t status = InitCheck(); if (status >= B_OK) { int32 i = 0; for (; i < fCount; i++) { if (fCommands[i]) status = fCommands[i]->Perform(); if (status < B_OK) break; } /* if (status < B_OK) { // roll back i--; for (; i >= 0; i--) { if (fCommands[i]) fCommands[i]->Undo(); } }*/ } return status; } // Undo status_t CompoundCommand::Undo() { status_t status = InitCheck(); if (status >= B_OK) { int32 i = fCount - 1; for (; i >= 0; i--) { if (fCommands[i]) status = fCommands[i]->Undo(); if (status < B_OK) break; } } return status; } // Redo status_t CompoundCommand::Redo() { return Perform(); } // GetName void CompoundCommand::GetName(BString& name) { name << _GetString(fNameIndex, fName.String()); }
DenysGurin/solnce
dgcrm/migrations/0028_auto_20170712_1405.py
<filename>dgcrm/migrations/0028_auto_20170712_1405.py # -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-07-12 14:05 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dgcrm', '0027_price_date'), ] operations = [ migrations.AlterField( model_name='price', name='brutto_price', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='price', name='currency', field=models.CharField(choices=[('UAH', 'UAH'), ('USD', 'USD'), ('EUR', 'EUR')], default='UAH', max_length=20), ), migrations.AlterField( model_name='price', name='discount', field=models.IntegerField(blank=True, default=0, null=True), ), ]
StuartMacKay/ebird-api
tests/validation/test_clean_max_results.py
<reponame>StuartMacKay/ebird-api import unittest from ebird.api.validation import clean_max_results class CleanMaxResultsTests(unittest.TestCase): """Tests for the clean_max_results validation function.""" def test_none_is_allowed(self): self.assertEqual(None, clean_max_results(None, 10000)) def test_string_converts_to_integer(self): self.assertEqual(10, clean_max_results("10", 10000)) def test_value_outside_range(self): self.assertRaises(ValueError, clean_max_results, 0, 10000) self.assertRaises(ValueError, clean_max_results, 10001, 10000)
bmunozi/onesaitplatform-cloud
sources/libraries/persistence/mongodb-impl/src/main/java/com/minsait/onesait/platform/persistence/mongodb/quasar/connector/QuasarMongoDBbHttpConnectorImpl.java
<reponame>bmunozi/onesaitplatform-cloud /** * Copyright Indra Soluciones Tecnologías de la Información, S.L.U. * 2013-2019 SPAIN * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.minsait.onesait.platform.persistence.mongodb.quasar.connector; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.util.EntityUtils; import org.springframework.beans.factory.annotation.Value; import com.minsait.onesait.platform.persistence.exceptions.DBPersistenceException; import lombok.extern.slf4j.Slf4j; @Slf4j @Deprecated public class QuasarMongoDBbHttpConnectorImpl implements QuasarMongoDBbHttpConnector { public static final String ACCEPT_TEXT_CSV = "text/csv; columnDelimiter=|&rowDelimiter=;&quoteChar='&escapeChar=\\\\"; public static final String ACCEPT_APPLICATION_JSON = "application/json"; static final String CONTENT_TYPE_HEADER = "Content-Type"; private static final String BUILDING_ERROR = "Error building URL"; @Value("${onesaitplatform.database.mongodb.quasar.maxHttpConnections:10}") private int maxHttpConnections; @Value("${onesaitplatform.database.mongodb.quasar.maxHttpConnectionsPerRoute:10}") private int maxHttpConnectionsPerRoute; @Value("${onesaitplatform.database.mongodb.quasar.connectionTimeout.millis:10000}") private int connectionTimeout; @Value("${onesaitplatform.database.mongodb.quasar.connector.http.endpoint:http://localhost:18200/query/fs/}") private String quasarEndpoint; @Value("${onesaitplatform.database.mongodb.database:onesaitplatform_rtdb}") private String database; private PoolingClientConnectionManager cm; private BasicHttpParams httpParams; @PostConstruct public void init() { /** * Using the new way we obtain a java.io.EOFException: Unexpected end of ZLIB * input stream It must be a bug in HttpClient */ cm = new PoolingClientConnectionManager(); httpParams = new BasicHttpParams(); cm.setMaxTotal(maxHttpConnections); cm.setDefaultMaxPerRoute(maxHttpConnectionsPerRoute); HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout); } @Override public String queryAsJson(String ontology, String query, int offset, int limit) { String url; try { url = buildUrl(query, offset, limit); } catch (final UnsupportedEncodingException e) { log.error(BUILDING_ERROR, e); throw new DBPersistenceException(BUILDING_ERROR, e); } return invokeQuasar(url, ACCEPT_APPLICATION_JSON); } @Override public String queryAsTable(String query, int offset, int limit) { String url; try { url = buildUrl(query, offset, limit); } catch (final UnsupportedEncodingException e) { log.error(BUILDING_ERROR, e); throw new DBPersistenceException(BUILDING_ERROR, e); } return invokeQuasar(url, ACCEPT_TEXT_CSV); } private String invokeQuasar(String endpoint, String accept) { HttpGet httpGet = null; HttpResponse httpResponse = null; String output = null; try (CloseableHttpClient httpClient = new DefaultHttpClient(cm, httpParams)) { httpClient.getConnectionManager().closeIdleConnections(0, TimeUnit.SECONDS); httpGet = createHttpGetRequest(endpoint, accept, null); if (httpGet != null) { try { log.info("Send message: to {}.", endpoint); httpResponse = httpClient.execute(httpGet); if (httpResponse != null && httpResponse.getStatusLine() != null) { final int httpStatusCode = httpResponse.getStatusLine().getStatusCode(); if (httpStatusCode != 200) { log.warn("Error notifying message to endpoint: {}. HTTP status code {}.", endpoint, httpStatusCode); } } else { log.error("Error notifying message to endpoint: {}. Malformed HTTP response.", endpoint); } if (httpResponse != null) { final HttpEntity en = httpResponse.getEntity(); output = EntityUtils.toString(en); } return output; } catch (final Exception e) { log.error("Error notifing message to endpoint: {}", endpoint, e); throw new DBPersistenceException(e); } finally { httpGet.releaseConnection(); } } } catch (final Exception e) { log.error("Unable to send message: error detected while building POST request.", e); } log.warn("Cannot notify message: the HTTPPost request cannot be build."); throw new DBPersistenceException("Cannot notify message: the HTTPPost request cannot be build."); } private HttpGet createHttpGetRequest(String endpoint, String accept, String contentType) { HttpGet httpGet; try { httpGet = new HttpGet(new URI(endpoint)); if (null != accept && accept.trim().length() > 0) { httpGet.setHeader("Accept", accept); } if (null != contentType && contentType.trim().length() > 0) { httpGet.setHeader(CONTENT_TYPE_HEADER, contentType); } httpGet.setHeader("Connection", "close"); } catch (final URISyntaxException e1) { throw new IllegalArgumentException("The URI of the endpoint is invalid."); } return httpGet; } /** * FORMAT QUERY: * /query/fs/[path]?q=[query]&offset=[offset]&limit=[limit]&var.[foo]=[value] * * @param query * @param offset * @param limit * @return * @throws UnsupportedEncodingException */ private String buildUrl(String query, int offset, int limit) throws UnsupportedEncodingException { String params = "q=" + URLEncoder.encode(query, "UTF-8"); if (offset > 0) { params += "&offset=" + offset; } if (limit > 0) { params += "&limit=" + limit; } return quasarEndpoint + database + "/?" + params; } @Override public String compileQueryAsJson(String collection, String query, int offset) { return null; } }
raven38/pytorch
caffe2/operators/sqrt_op.cc
<reponame>raven38/pytorch #include "caffe2/operators/sqrt_op.h" #include <string> #include <vector> namespace caffe2 { // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_CPU_OPERATOR( Sqrt, UnaryElementwiseOp< TensorTypes<float, double>, CPUContext, SqrtFunctor<CPUContext>>); // Input: X, output: Y // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) OPERATOR_SCHEMA(Sqrt) .NumInputs(1) .NumOutputs(1) .AllowInplace({{0, 0}}) .IdenticalTypeAndShape() .SetDoc(R"DOC( Performs element-wise square-root ($\sqrt{x}$) of input tensor $X$. Github Link: - https://github.com/pytorch/pytorch/blob/master/caffe2/operators/sqrt_op.cc <details> <summary> <b>Example</b> </summary> **Code** ``` workspace.ResetWorkspace() op = core.CreateOperator( "Sqrt", ["X"], ["Y"], ) workspace.FeedBlob("X", (np.random.randint(10, size=(3,3))).astype(np.float32)) print("X:", workspace.FetchBlob("X")) workspace.RunOperatorOnce(op) print("Y:", workspace.FetchBlob("Y")) ``` **Result** ``` X: [[8. 3. 3.] [4. 0. 0.] [1. 2. 5.]] Y: [[2.8284268 1.7320508 1.7320508 ] [1.9999999 0. 0. ] [0.99999994 1.4142134 2.236068 ]] ``` </details> )DOC") .Input(0, "X", "*(type: Tensor`<float>`)* Input data tensor.") .Output(0, "Y", "*(type: Tensor`<float>`)* Output tensor."); namespace { class GetSqrtGradient : public GradientMakerBase { using GradientMakerBase::GradientMakerBase; std::vector<OperatorDef> GetGradientDefs() override { Argument scale_arg; scale_arg.set_name("scale"); scale_arg.set_f(0.5); return std::vector<OperatorDef>{CreateOperatorDef( "Scale", "", std::vector<std::string>{GO(0)}, std::vector<std::string>{GI(0)}, std::vector<Argument>{scale_arg}), CreateOperatorDef( "Div", "", std::vector<std::string>{GI(0), O(0)}, std::vector<std::string>{GI(0)})}; } }; } // namespace // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_GRADIENT(Sqrt, GetSqrtGradient); } // namespace caffe2
Yuunagi-Yu/NumberDisk
Project/Temp/StagingArea/Data/il2cppOutput/UnityEngine_UnityEngine_GUI4082743951.h
<gh_stars>0 #pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // UnityEngine.GUISkin struct GUISkin_t1436893342; // UnityEngineInternal.GenericStack struct GenericStack_t3718539591; #include "mscorlib_System_Object2689449295.h" #include "mscorlib_System_DateTime693205669.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.GUI struct GUI_t4082743951 : public Il2CppObject { public: public: }; struct GUI_t4082743951_StaticFields { public: // System.Single UnityEngine.GUI::s_ScrollStepSize float ___s_ScrollStepSize_0; // System.DateTime UnityEngine.GUI::<nextScrollStepTime>k__BackingField DateTime_t693205669 ___U3CnextScrollStepTimeU3Ek__BackingField_1; // System.Int32 UnityEngine.GUI::s_HotTextField int32_t ___s_HotTextField_2; // System.Int32 UnityEngine.GUI::s_BoxHash int32_t ___s_BoxHash_3; // System.Int32 UnityEngine.GUI::s_RepeatButtonHash int32_t ___s_RepeatButtonHash_4; // System.Int32 UnityEngine.GUI::s_ToggleHash int32_t ___s_ToggleHash_5; // System.Int32 UnityEngine.GUI::s_ButtonGridHash int32_t ___s_ButtonGridHash_6; // System.Int32 UnityEngine.GUI::s_SliderHash int32_t ___s_SliderHash_7; // System.Int32 UnityEngine.GUI::s_BeginGroupHash int32_t ___s_BeginGroupHash_8; // System.Int32 UnityEngine.GUI::s_ScrollviewHash int32_t ___s_ScrollviewHash_9; // UnityEngine.GUISkin UnityEngine.GUI::s_Skin GUISkin_t1436893342 * ___s_Skin_10; // UnityEngineInternal.GenericStack UnityEngine.GUI::s_ScrollViewStates GenericStack_t3718539591 * ___s_ScrollViewStates_11; public: inline static int32_t get_offset_of_s_ScrollStepSize_0() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___s_ScrollStepSize_0)); } inline float get_s_ScrollStepSize_0() const { return ___s_ScrollStepSize_0; } inline float* get_address_of_s_ScrollStepSize_0() { return &___s_ScrollStepSize_0; } inline void set_s_ScrollStepSize_0(float value) { ___s_ScrollStepSize_0 = value; } inline static int32_t get_offset_of_U3CnextScrollStepTimeU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___U3CnextScrollStepTimeU3Ek__BackingField_1)); } inline DateTime_t693205669 get_U3CnextScrollStepTimeU3Ek__BackingField_1() const { return ___U3CnextScrollStepTimeU3Ek__BackingField_1; } inline DateTime_t693205669 * get_address_of_U3CnextScrollStepTimeU3Ek__BackingField_1() { return &___U3CnextScrollStepTimeU3Ek__BackingField_1; } inline void set_U3CnextScrollStepTimeU3Ek__BackingField_1(DateTime_t693205669 value) { ___U3CnextScrollStepTimeU3Ek__BackingField_1 = value; } inline static int32_t get_offset_of_s_HotTextField_2() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___s_HotTextField_2)); } inline int32_t get_s_HotTextField_2() const { return ___s_HotTextField_2; } inline int32_t* get_address_of_s_HotTextField_2() { return &___s_HotTextField_2; } inline void set_s_HotTextField_2(int32_t value) { ___s_HotTextField_2 = value; } inline static int32_t get_offset_of_s_BoxHash_3() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___s_BoxHash_3)); } inline int32_t get_s_BoxHash_3() const { return ___s_BoxHash_3; } inline int32_t* get_address_of_s_BoxHash_3() { return &___s_BoxHash_3; } inline void set_s_BoxHash_3(int32_t value) { ___s_BoxHash_3 = value; } inline static int32_t get_offset_of_s_RepeatButtonHash_4() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___s_RepeatButtonHash_4)); } inline int32_t get_s_RepeatButtonHash_4() const { return ___s_RepeatButtonHash_4; } inline int32_t* get_address_of_s_RepeatButtonHash_4() { return &___s_RepeatButtonHash_4; } inline void set_s_RepeatButtonHash_4(int32_t value) { ___s_RepeatButtonHash_4 = value; } inline static int32_t get_offset_of_s_ToggleHash_5() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___s_ToggleHash_5)); } inline int32_t get_s_ToggleHash_5() const { return ___s_ToggleHash_5; } inline int32_t* get_address_of_s_ToggleHash_5() { return &___s_ToggleHash_5; } inline void set_s_ToggleHash_5(int32_t value) { ___s_ToggleHash_5 = value; } inline static int32_t get_offset_of_s_ButtonGridHash_6() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___s_ButtonGridHash_6)); } inline int32_t get_s_ButtonGridHash_6() const { return ___s_ButtonGridHash_6; } inline int32_t* get_address_of_s_ButtonGridHash_6() { return &___s_ButtonGridHash_6; } inline void set_s_ButtonGridHash_6(int32_t value) { ___s_ButtonGridHash_6 = value; } inline static int32_t get_offset_of_s_SliderHash_7() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___s_SliderHash_7)); } inline int32_t get_s_SliderHash_7() const { return ___s_SliderHash_7; } inline int32_t* get_address_of_s_SliderHash_7() { return &___s_SliderHash_7; } inline void set_s_SliderHash_7(int32_t value) { ___s_SliderHash_7 = value; } inline static int32_t get_offset_of_s_BeginGroupHash_8() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___s_BeginGroupHash_8)); } inline int32_t get_s_BeginGroupHash_8() const { return ___s_BeginGroupHash_8; } inline int32_t* get_address_of_s_BeginGroupHash_8() { return &___s_BeginGroupHash_8; } inline void set_s_BeginGroupHash_8(int32_t value) { ___s_BeginGroupHash_8 = value; } inline static int32_t get_offset_of_s_ScrollviewHash_9() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___s_ScrollviewHash_9)); } inline int32_t get_s_ScrollviewHash_9() const { return ___s_ScrollviewHash_9; } inline int32_t* get_address_of_s_ScrollviewHash_9() { return &___s_ScrollviewHash_9; } inline void set_s_ScrollviewHash_9(int32_t value) { ___s_ScrollviewHash_9 = value; } inline static int32_t get_offset_of_s_Skin_10() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___s_Skin_10)); } inline GUISkin_t1436893342 * get_s_Skin_10() const { return ___s_Skin_10; } inline GUISkin_t1436893342 ** get_address_of_s_Skin_10() { return &___s_Skin_10; } inline void set_s_Skin_10(GUISkin_t1436893342 * value) { ___s_Skin_10 = value; Il2CppCodeGenWriteBarrier(&___s_Skin_10, value); } inline static int32_t get_offset_of_s_ScrollViewStates_11() { return static_cast<int32_t>(offsetof(GUI_t4082743951_StaticFields, ___s_ScrollViewStates_11)); } inline GenericStack_t3718539591 * get_s_ScrollViewStates_11() const { return ___s_ScrollViewStates_11; } inline GenericStack_t3718539591 ** get_address_of_s_ScrollViewStates_11() { return &___s_ScrollViewStates_11; } inline void set_s_ScrollViewStates_11(GenericStack_t3718539591 * value) { ___s_ScrollViewStates_11 = value; Il2CppCodeGenWriteBarrier(&___s_ScrollViewStates_11, value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
tapis-project/tapis-apps
tapis-appsapi/src/main/java/edu/utexas/tacc/tapis/apps/api/model/ParameterSet.java
package edu.utexas.tacc.tapis.apps.api.model; import edu.utexas.tacc.tapis.apps.api.utils.ApiUtils; import edu.utexas.tacc.tapis.apps.model.App; import edu.utexas.tacc.tapis.apps.model.AppArg; import java.util.ArrayList; import java.util.List; /* * Class for ParameterSet attributes in an App definition contained in a request. */ public final class ParameterSet { public List<ArgSpec> appArgs; public List<ArgSpec> containerArgs; public List<ArgSpec> schedulerOptions; public List<KeyValuePair> envVariables; public ArchiveFilter archiveFilter; public ParameterSet() { appArgs = new ArrayList<>(); containerArgs = new ArrayList<>(); schedulerOptions = new ArrayList<>(); envVariables = new ArrayList<>(); archiveFilter = new ArchiveFilter(); } public ParameterSet(App a) { appArgs = buildArgSpecList(a.getAppArgs()); containerArgs = buildArgSpecList(a.getContainerArgs()); schedulerOptions = buildArgSpecList(a.getSchedulerOptions()); envVariables = ApiUtils.getKeyValuesAsList(a.getEnvVariables()); archiveFilter = new ArchiveFilter(a); } // Build a list of api model Args based on the lib model Args List<ArgSpec> buildArgSpecList(List<AppArg> appArgs) { var retList = new ArrayList<ArgSpec>(); if (appArgs == null || appArgs.isEmpty()) return retList; for (AppArg appArg : appArgs) { ArgSpec argSpec = new ArgSpec(); ArgMetaSpec meta = new ArgMetaSpec(); argSpec.arg = appArg.getArgValue(); meta.name = appArg.getMetaName(); meta.description = appArg.getMetaDescription(); meta.required = appArg.isMetaRequired(); meta.keyValuePairs = ApiUtils.getKeyValuesAsList(appArg.getMetaKeyValuePairs()); argSpec.meta = meta; retList.add(argSpec); } return retList; } }
danfyfe/lets-do-something-front-end
src/containers/EventContainer.js
<reponame>danfyfe/lets-do-something-front-end<filename>src/containers/EventContainer.js import React from 'react' import { formatTime } from '../actions/general.js' import AttendeeCard from '../components/cards/AttendeeCard.js' import InvitesContainer from './InvitesContainer.js' import BudgetContainer from './BudgetContainer.js' const EventContainer = props => { const { id, title, description, start, end, users, owner_id, invites, budget, costs } = props.event const { currentUser } = props const { followers } = props.currentUser const owner = users.find( user => user.id === owner_id) const isOwner = () => { if (props.currentUser.id === owner.id) { return true } else { return false } } const pendingInviteUsers = (followers, currentUser) => { let users = [] if (followers) { let followersWithUser = [ ...followers, currentUser] invites.forEach( invite => { if (invite.rsvp === null) { let user = followersWithUser.find( follower => { return follower.id === invite.user.id }) if (user) { users.push(user) } } }) } return users } const renderAttendeeCards = () => { return users.map( user => { return <AttendeeCard key={user.id} user={user}/> }) } const renderEditButton = isOwner => { if (isOwner) { return <span className='link m-auto'>Edit</span> } else { return null } } return( <div className='d-flex flex-column most-width mx-auto my-2 med-padding main-wrapper border rounded'> <div className='d-flex flex-row justify-content-between small-padding'> <span className='large-font font-weight-bold'>{title}</span> {renderEditButton(isOwner())} </div> <div className='d-flex flex-row justify-content-around'> <span className='text-muted med-font'>{formatTime(start)}</span> <span className='text-muted med-font'>{formatTime(end)}</span> </div> <div className='d-flex flex-column med-padding'> <p className='m-auto small-indent med-norm-font'>{description}</p> <div className='d-flex flex-column small-padding'> <span className='font-weight-bold small-font text-muted'>Owner:</span> <span className='med-font small-indent small-padding'>{owner.username}</span> </div> </div> <div className='d-flex flex-column m-1v'> <span className='font-weight-bold small-font'>Attendees</span> <div className='d-flex flex-column small-padding'> {renderAttendeeCards()} </div> </div> <div className='d-flex flex-column m-1v'> <InvitesContainer eventId={id} isOwner={isOwner} pendingInviteUsers={pendingInviteUsers(followers, currentUser)} users={users}/> </div> <div className='d-flex flex-column m-1v'> <BudgetContainer budget={budget} costs={costs} users={users} currentUserId={currentUser.id} eventId={id} isOwner={isOwner()} /> </div> </div> ) } export default EventContainer
TimBest/case-issue-api
src/main/java/gov/usds/case_issues/db/model/projections/CaseSnoozeSummary.java
package gov.usds.case_issues.db.model.projections; import java.time.ZonedDateTime; /** * A projection that returns the information about a snooze that most people would want * (assuming you already had the key information required to look it up, and don't need to * see it again). */ public interface CaseSnoozeSummary { String getSnoozeReason(); ZonedDateTime getSnoozeStart(); ZonedDateTime getSnoozeEnd(); }
cribbslab/mclumi
mclumi/trim/UMIRuleOut.py
__version__ = "v1.0" __copyright__ = "Copyright 2021" __license__ = "MIT" __lab__ = "<NAME>s lab" from mclumi.util.Console import console class umiRuleOut(object): def __init__(self, read_summary, verbose=True): self.read_summary = read_summary self.verbose = verbose self.console = console() self.console.verbose = self.verbose def sequential(self, compo_struct, umi_pos_in_struct): """ Note ---- Starting positions of all UMIs. Example ------- rule_out_struct_dict returns all structures before each key of rule_out_struct_dict: { 'umi_1': [struct_1, struct_2, ..., struct_n], 'umi_2': [struct_1, struct_2, ..., struct_n], ..., 'umi_m': [struct_1, struct_2, ..., struct_n], } e.g., {'umi_1': ['primer_1'], 'umi_2': ['seq_1']} rule_out_rel_len_dict returns accumulated lengths of all structures in the list w.r.t each key of rule_out_struct_dict. rule_out_accumu_len_dict returns the starting positions of all UMIs. Parameters ---------- compo_struct 1d list of strings of seq_struct split by +. umi_pos_in_struct 1d list of indices of compo_struct. Returns ------- 1d dict: {umi_1: int, umi_2: int, ..., umi_n: int} """ self.console.print('======>finding the starting positions of all UMIs...') rule_out_struct_dict = {} for i in range(len(umi_pos_in_struct)): if i == 0: rule_out_struct_dict['umi_' + str(i + 1)] = compo_struct[:umi_pos_in_struct[i]] else: rule_out_struct_dict['umi_' + str(i + 1)] = compo_struct[umi_pos_in_struct[i - 1] + 1: umi_pos_in_struct[i]] rule_out_rel_len_dict = {} for key, val in rule_out_struct_dict.items(): rule_out_rel_len_dict[key] = 0 if val == []: rule_out_rel_len_dict[key] = 0 else: for j in val: rule_out_rel_len_dict[key] += self.read_summary[j]['len'] rule_out_accumu_len_dict = {} accumu = [] for key, val in rule_out_rel_len_dict.items(): accumu.append(val) rule_out_accumu_len_dict[key] = sum(accumu) accumu.append(self.read_summary[key]['len']) for k, v in rule_out_accumu_len_dict.items(): self.console.print('=========>{} starting position: {}'.format(k, v)) return rule_out_accumu_len_dict
Mikeccx/vanke-vant
es/cell-group/CellGroup.js
import { Fragment as _Fragment, createVNode as _createVNode, mergeProps as _mergeProps } from "vue"; import { defineComponent } from 'vue'; import { truthProp, createNamespace } from '../utils'; import { BORDER_TOP_BOTTOM } from '../utils/constant'; var [name, bem] = createNamespace('cell-group'); export default defineComponent({ name, inheritAttrs: false, props: { title: String, border: truthProp }, setup(props, { slots, attrs }) { var renderGroup = () => _createVNode("div", _mergeProps({ "class": [bem(), { [BORDER_TOP_BOTTOM]: props.border }] }, attrs), [slots.default == null ? void 0 : slots.default()]); var renderTitle = () => _createVNode("div", { "class": bem('title') }, [slots.title ? slots.title() : props.title]); return () => { if (props.title || slots.title) { return _createVNode(_Fragment, null, [renderTitle(), renderGroup()]); } return renderGroup(); }; } });
wanxiang-blockchain/2021Wanxiang-Blockchain-Hackathon-Filscan
lang/en.js
<gh_stars>0 // const isTest = window.location.href.indexOf("calibration") >= 0 const isTest = false const en = { links: {}, mixin:{ formatTime:{ before: 'ago', suffix: ['day', 'hr', 'min', 's'] } }, component: { empty: { label: 'No Data' }, heightDetail: { titles: ['Block Height', 'Block List'], heightLabels: ['WinCount', 'Rewards', 'Time'], blockLabels: ['Block Cid', 'Storage Provider', 'Rewards', 'Message Count'] }, filecoin: { labels: [ 'Market Cap', 'Market Dominance', 'Market Cap Rank', '24h Low/24h High', 'Volume', 'Diluted market value' ] }, overview: { btnText: 'Pool Detail' }, mesList: { title: 'Messages', heading: 'Message List', poolheading: 'Message Pool List', label: [ 'Message ID', 'Height', 'Time', 'From', 'To', 'Value', 'Status', 'Method' ], blockLabel: ['Message ID', 'Height', 'From', 'To', 'Method', 'Value'], poolLabels: [ 'Message ID', 'Time', 'From', 'To', 'Value', 'Gas Limit', 'Gas Premium', 'Method' ], mbLabel: ['Message ID', 'Time', 'From', 'To', 'Value', 'Gas Limit ','Gas Premium', 'Method' ], total: 'Latest {total} Messages <i>{extra}</i>', latest: '', // latest: "( latest 7 days )", range: '( {start} to {end} ) ', method: {}, placeholder: 'Method', tips: '(Showing records in the last 1 week)', receipt: ['Success', 'Failed', 'Unknown'], fail: 'Failed', selector: [ { label: 'IN', type: 'to' }, { label: 'OUT', type: 'from' } ], type: ['IN', 'OUT'] }, blockList: { label: ['Block Cid', 'Height', 'Time', 'Messages', 'Storage Provider', 'Reward'], mbLabel: ['Block Cid', 'Storage Provider', 'Time', 'Reward', '', 'Messages'], mb: { height: 'Height:', time: 'Time:', label: ['Storage Provider', 'Block Cid', 'Messages', 'Reward'] }, total: 'Total of <i>{total}</i> Blocks(<i>{fil}</i>FIL)', height: 'Tipset Height # {height}', start: 'start date', end: 'end date', title: 'Block details' }, transactionList: { total: 'Total of <i>{total}</i> message', label: ['Time', 'Message CID', 'From', 'To', 'Value', 'Type'], typeOptions: ['Send', 'Receive', 'Block Rewords', 'Other Penalty', 'Aggregate cost'] }, addressList:{ heading: "Rich Ranking" }, transferList: { heading: 'Large Amount Transfer', total: 'Total of {total} Message', labels: ['Height', 'Message ID', 'Time', 'From', 'To', 'Value', 'Method'], addressLabels: [ 'Time', 'Message ID', 'From', 'To', 'Value', 'Method', 'Type' ] }, timeSelector: [ { value: '24h', label: '24h' }, { value: '1w', label: '1w' }, { value: '1m', label: '1m' }, { value: '1y', label: '1y' }, { value: 'all', label: 'all' } ], times: { '6h': '6H', '24h': 'Today', '1d': 'Yesterday', '1w': '1Week', '1m': '30D', '6m': '6M', '0.5y': 'Half A Year', '1y': '1Year', all: 'All' }, timeGrowth: { '24h': '24h', '1d': 'Yesterday', '1w': '7D', '1m': '30D', '6m': '6M', '0.5y': 'Half A Year', '1y': '1Year' }, timeGrowth1: { '24h': 'Today', '1d': 'Yesterday', '1w': 'Week', '1m': '30D', '6m': '6M', '0.5y': 'Half A Year', '1y': '1Year' }, more: 'More' }, account: { login: { welcome: 'Welcome', account: 'Account', phoneLogin: ' Mobile login ', emailLogin: ' Email login ', phone: "Telephone", enterPhone: " Please enter your mobile number ", email: ' e-mail address ', enterEmail: " Please enter email address ", pass: 'Password', enterPass: " <PASSWORD> ", code: " Verification Code ", enterCode: " Please enter the verification code ", getCode: " Get verification code ", resetPass: " <PASSWORD> password ", sure: " Sign in ", byPass: ' Sign in with password ', byCode: ' Login with verification code ', registerPrefix: "No account yet?", register: " Register new users ", remember: 'Remember your password and log in' }, register: { welcome: 'Account registration', account: 'Account', setPwd: '<PASSWORD>', phoneRegister: " Mobile registration ", emailRegister: " Email registration ", phone: "Telephone", enterPhone: " Please enter the registered mobile phone number ", email: "e-mail address", enterEmail: " Please enter the registered email address ", pass: 'Password', enterPass: "<PASSWORD>", passAgain: " <PASSWORD> ", enterPassAgain: " Please confirm the password ", code: " Verification Code ", enterCode: " Please enter the verification code ", getCode: " Get verification code ", private: " Please agree to the service agreement and privacy terms ", hasPrefix: "Existing account?", has: "please log in ", sure: " Register " }, reset: { welcome: 'Forget password', phoneReset: ' Reset with Phone ', emailReset: ' Reset with Email ', phone: "Telephone", enterPhone: " Please enter your mobile number ", email: " E-mail address ", enterEmail: " Please enter email address ", pass: ' <PASSWORD> ', enterPass: " <PASSWORD> ", newPass: " <PASSWORD> ", enterNewPass: " <PASSWORD> ", code: " Verification Code ", enterCode: " Please enter the verification code ", getCode: " Get verification code ", has: " Existing account, please Reqister ", sure: "Sure", pre: ' Previous step ', next: ' Next step ' }, logout: { msg: ' You are about to log out. Do you want to continue ?', tip: 'Tips', confirm: 'Sure', cancel: 'Cancel', success: ' Log out successfully!', hasCancel: ' Cancelled ', }, error: { emptyPhone: ' Please enter your mobile number ', errorPhone: ' Please input the correct mobile number ', emptyAccount: ' Account number cannot be empty ', errorAccount: ' Please enter the correct mobile number or email address ', emptyCode: ' Verification code cannot be empty ', emptyPass: ' <PASSWORD> input a password ', emptyNewPass: ' Please enter a new password ', errorPass: ' Password should be 8-20 characters with at least letters and numbers (case sensitive) ', notRegister: ' The account has not been registered ', hasRegister: " The account has been registered ", sameWithPhone: " The password cannot be exactly the same as the mobile phone number ", emptyPassAgain: ' Please enter the password again ', emptyNewPassAgain: ' Please enter the new password again ', differentPass: " The two passwords are inconsistent ", agreePrivate: " Please agree to the service agreement and privacy terms ", emptyTag: " Please enter comments ", emptyAddress: ' Please enter wallet address ', emptyMail: ' Please enter the correct email address ', errorEmail: " Email address format error ", registerMail: " Mailbox is already registered ", emptyNumber: ' Please enter the ID number or passport ', emptyName: ' Please enter a name ', nameError: ' Name cannot exceed 64 characters ', areaCodeError: ' Please enter the correct international area code ', phoneError: ' Please enter the correct mobile number ', picTypeError: ' The uploaded picture can only be in JPG or PNG format ', picSizeError: ' The size of uploaded picture cannot exceed 5MB ', infoNotMatch: { title: 'Identity information does not match!', mes: "The identity authentication information you submitted does not match the identity information of the mobile phone number" }, mustHaveOne: 'Keep at least one security verification method' }, }, header: { network: 'Current network:', centerOption:[ { index: 'center', label: 'Your Profil' }, { index: 'monitor', label: 'Pool Panel' }, { index: 'LogOut', label: 'Logout' }, ], meta: { content1: 'Filscan,Filecoin,Latest Block,Filecoin Explorer,FIL,IPFS,FIL,Filecoin Browser For Blockchain Query ,FIL Browser,Filecoin Browser, Block Query of Filecoin, Search Engine of Blockchain,Block Height, Blockchain Transaction', content2: 'Filscan block browser, a blockchain search engine, is the basic ecological tool of filecoin. It is providing relevant data on the real-time chain, and which set query Filecoin block, transaction, fil token, wallet and other information, update filecoin all node information on real-time synchronous' }, seo: { index: 'Filscan--Filecoin Explorer', chain: 'Chain - Filscan Explorer', message: 'Messages - Filscan Explorer', pool: 'Messages In Flight - Filscan Explorer', address: 'Rich ranking - Filscan Explorer', largeTransfer: 'Large Transfer - Filscan Explorer ', addressDetail: 'Address {address} - Filscan Explorer', dsn: 'All Deals - Filscan Explorer', dsnDetail: 'Deal Detail {dealid} - Filscan Explorer', messageDetail: 'Message {message} - Filscan Explorer', mining: 'Pool Rank - Filscan Explorer', calculator: 'Calculator - Filscan Explorer', gas: 'Gas Fee Trend - Filscan Explorer', fil: 'FIL - Filscan Explorer', stats: 'Charts - Filscan Explorer', baseTrend: 'BaseLine & Power Trend - Filscan Explorer', map: 'Map - Filscan Explorer', resource: "Resource - Filscan Explorer" }, title: 'Filscan', placeholder: 'Search by Address/Message ID/Height/Block Cid/Peer ID', filter: [ { label: 'All filters', value: 0 }, { label: 'Address', value: 1 }, { label: 'Message ID', value: 2 }, { label: 'Height', value: 3 }, { label: 'Block Cid', value: 4 }, { label: 'Peer ID', value: 5 } ], nav: { home: { label: 'Home', index: 'home', path: '/' }, tipset: { label: 'Tipset', index: 'tipset', down: true, items: [ { label: 'Chain', path: '/tipset/chain', index: 'chain' }, { label: 'Message', path: '/tipset/message-list', index: 'message-list' }, { label: 'Rich Ranking', path: '/tipset/address-list', index: 'address-list' }, { label: 'Large Amount Transfer', path: '/tipset/transfer-list', index: 'transfer-list' }, { label: 'Dsn', path: '/tipset/dsn', index: 'dsn' }, { label: 'Pool Message', path: '/tipset/pool-message-list', index: 'pool-message-list' } ] }, mining: { label: 'Ranking', path: '/mining', index: 'mining' }, statistics: { label: 'Statistics', index: 'statistics', down: true, items: [ { label: 'Gas Fee', index: 'gas', path: '/statistics/gas' }, { label: 'BaseFee& Power', path: '/statistics/power', index: 'power' }, { label: 'FIL', path: '/statistics/fil', index: 'fil' }, { label: 'Charts', index: 'charts', path: '/statistics/charts' }, { label: 'Map', index: 'map', path: '/statistics/map' } ] }, resources: { label: 'Resources', index: 'resources', down: true, items: [ { label: 'Calculator', path: '/resources/calculator', index: 'calculator', }, { label: 'Tools', path: '/resources/tools', index: 'tools', } ] }, // filwallet: { // label: 'Wallet', // href: 'https://filecoinwallet.com/', // index: 'filwallet', // }, incubation: { label: 'Storage Provider', path: '/forcepool/center?type=1', index: 'incubation', pro: true } }, mbnav: { home: { label: 'Home', index: 'home', path: '/' }, tipset: { label: 'Tipset', index: 'tipset', isSubShow: false, close: 'icon-down', up: 'icon-up', items: [ { label: 'Tipset', path: '/tipset/chain', index: 'chain' }, { label: 'Messages', path: '/tipset/message-list', index: 'message-list' }, { label: 'View All Accounts', path: '/tipset/address-list', index: 'address-list' }, { label: 'Large Amount Transfer', path: '/mobile/tipset/transfer-list', index: 'transfer-list' }, { label: 'View All Deals', path: '/tipset/dsn', index: 'dsn' }, { label: 'Messages Pool', path: '/tipset/pool-message-list', index: 'pool-message-list' } ] }, mining: { label: 'Ranking', path: '/mining', index: 'mining' }, statistics: { label: 'Statistics', index: 'statistics', isSubShow: false, close: 'icon-down', up: 'icon-up', items: [ { label: 'Gas', index: 'gas', path: '/mobile/statistics/gas' }, { label: 'power Trend', path: '/mobile/statistics/power', index: 'power' }, { label: 'Fil', path: '/mobile/statistics/fil', index: 'fil' }, { label: 'Charts', index: 'charts', path: '/mobile/statistics/charts' } ] }, resources: { label: 'Resources', index: 'resources', isSubShow: false, close: 'icon-down', up: 'icon-up', items: [ { label: 'Calculator', path: '/resources/calculator', index: 'calculator', }, { label: 'Tools', path: '/resources/tools', index: 'tools', } ] }, filwallet: { label: 'Wallet', href: 'https://filwallet.ai/', index: 'filwallet', }, incubation: { label: 'Incubation Center', href: 'https://venus.filecoin.io/incubation/Rules.html#storage-provider-incubation-program', index: 'incubation', hot: true } }, mb: { title: 'Filecoin Search', search: 'Search' }, cancel: 'Cancel' }, footer: { mobile: [ { label: 'Filecoin', href: ' https://filecoin.io' }, { label: 'Faucet ', href: isTest ? 'https://faucet.calibration.fildev.network/' : 'https://faucet.glif.io/' }, { label: 'Docs', href: 'https://lotu.sh/' }, { label: 'Info', href: ' https://testnet.filecoin.io/' } ], links: [ { title: 'Filecoin', items: [ { label: 'Filecoin Blog', class: 'icon-github', href: 'https://filecoin.io/blog/' }, { label: 'Filecoin Slack', class: 'icon-forum', href: 'https://app.slack.com/client/TEHTVS1L6/CEHTVSEG6/' }, { label: 'Filecoin Github', class: 'icon-slack', href: 'https://github.com/filecoin-project' }, { label: 'Protocol Labs', class: 'icon-slack', href: 'https://protocol.ai/' }, { label: 'ProtoSchool', class: 'icon-slack', href: 'https://proto.school/' }, { label: 'Filecoin Twitter', class: 'icon-slack', href: 'https://twitter.com/Filecoin' }, { label: 'Filecoin WeChat', class: 'icon-wechat', popover: true }, { label: 'Filecoin Community Github', class: 'icon-matrix', href: 'https://github.com/filecoin-project/community' }, { label: 'Filecoin Foundation', class: 'icon-matrix', href: 'https://fil.org/' }, { label: 'Filecoin DevGrants', class: 'icon-ttww', href: 'https://github.com/filecoin-project/devgrants' }, // { // label: 'IPFSForce WeChat', // class: 'icon-wechat', // popover: true // }, { label: 'Feedback', href: 'http://ipfsforce.mikecrm.com/E6kYnYI' } ] }, { title: 'Implementations', items: [ { label: 'Lotus', href: 'https://github.com/filecoin-project/lotus/' }, { label: 'Venus', href: 'https://github.com/filecoin-project/venus' }, { // label: 'filwallet.ai', label: 'Fuhon', href: 'https://github.com/filecoin-project/cpp-filecoin' }, { label: 'Forest', href: 'https://github.com/ChainSafe/forest' } ] }, { title: 'Ecosystem Applications', items: [ // { // label: 'Filecoin Ecosystem Wallet', // href: 'https://filecoinwallet.com/' // }, { label: 'Slate', href: 'https://www.slate.io/' }, { label: 'Textile', href: 'https://textile.io/' }, { label: 'Timerose', href: 'https://timerose.io/' }, { label: 'Filedrive', href: 'http://filedrive.io/' }, { label: 'Brave', href: 'https://brave.com/' } ] }, { title: 'DevTools', items: [ { label: 'Filecoin Spec', href: 'https://spec.filecoin.io/' }, { label: 'Filecoin Doc', href: 'https://docs.filecoin.io/' }, { label: 'Spec-actors', href: 'https://github.com/filecoin-project/specs-actors' } ] } ], contact: 'Email: ', detail: 'Filscan browser is the filecoin blockchain browser and data service platform,It provides one-stop data services such as mining ranking, blockchain data query and visualization chart based on filecoin.', ipfs: 'IPFS', copyright: 'Copyright © Filecoin-Project devgrants. Distributed under the <a href="https://www.mit-license.org/" target="_blank"> MIT </a> and<a href="https://www.apache.org/licenses/LICENSE-2.0.html" target="_blank"> Apache 2.0 </a>license.', copyright1: 'Copyright © Filecoin-Project devgrants. Distributed under the <a href="https://www.mit-license.org/" target="_blank"> MIT </a> and<a href="https://www.apache.org/licenses/LICENSE-2.0.html" target="_blank"> Apache 2.0 </a>license. Dev. by <a href="https://ipfser.org" target="_blank"> IPFSFORCE</a>.' }, home: { tips: 'Lotus upgrading may cause data display errors. <span>We are working on it.</span> Sorry for troubleing you.', subtitle: { index: 'Data index of the whole network', charts: 'Charts Statistics', pool: 'Storage Pool', poolTips: 'This ranking only counts mining pools over 1 PiB', transfer: 'Large Amount Transfer', moreChart: 'More Chart' }, charts: { more: 'More Charts' }, blocksWon: { title: 'Latest Block', miner: 'Storage Provider', block: { title: 'Blocks', tips: 'Block count/rate of total block in the latest 30 minutes' }, blockRate: { title: 'Block Rate', tips: 'Block rate per tipset in the latest 30 minutes' }, win: { title: 'WinCount', tips: 'Wincount/rate of total wincount in the latest 30 minutes' }, more: 'More', latest: 'The Last block time:<i class="font-18 mark font-500">{time}</i> &nbsp;ago', chart: { title: 'No block found in the latest 30 minutes', tooltip: '<div>NodeID: {miner_id}</div><div>Height: {height}</div><div>BlockTime: {block_time}</div><div>BlockCid: {cid}</div><div>WinCount: {win_count}</div>' } }, metaList: { tabs: ['open', 'close'] }, meta: [ { label: 'Block Height' }, { label: 'Latest Block' }, { label: 'Network Storage Power', tips: 'The sum of the current effective computing power (effective storage space) of the whole network' }, { label: 'Latest 24h Power Growth' }, { label: 'Latest 24h Output Efficiency', tips: 'Ratio of total block reward to effective computing power in the last 24 hours' }, { label: 'Base Fee' }, { label: 'Current Sector Initial Pledge' }, { label: 'Gas Used of 32G Sectors', tips: 'Gas used of Sealing 32G Sectors.' }, { label: 'Cost of Sealing 32G Sectors', tips: 'The cost of sealing 32G sectors, including sector initial pledge and message fees' }, { label: 'Latest 24h Block Reward' }, { label: 'Total Block' }, { label: 'Total Block Rewards' }, { label: 'Gas Used of 64G Sectors', tips: 'Gas used of Sealing 64G Sectors.' }, { label: 'Cost of Sealing 64G Sectors', tips: 'The cost of sealing 64G sectors, including sector initial pledge and message fees' }, { label: 'Rewards Per Wincount' }, { label: 'Avg Messages per TipSet', tips: 'Average messages packaged per tipSet in 24h.' }, { label: 'Destruction Amount' }, { label: 'Active Nodes' }, { label: 'Circulation Amount' }, { label: 'Avg Blocks per TipSet', tips: 'Average blocks produced per tipSet in 24h.' } ], mbMeta: [ { label: 'Power Returns' }, { label: 'Rewards Per WinCount' }, { label: 'Efficiency' }, { label: 'Total Block Rewards' }, { label: 'Total Block' }, { label: 'Latest Block Height' }, { label: 'Total QualityAdjPower' }, { label: 'Active Nodes' } ], chart: { power: { title: 'baseline and storage power trend', yAxisName: ['Network Power', 'Baseline', 'Power Growth'], tips: 'The network baseline is the scale of network growth required by the Filecoin Network, which was 2.5 EiB when the Mainnet launched, with a growth rate of 100% per year.' }, blockReward: { title: '24h Base Fee Variations', subTitle: 'In the latest 24h', meta: ['Block Count: ', '', 'WinCount: ', '', 'Rewards: '], yAxisName: ['Base Fee', '32G Sector', '64G Sector'], chart: { yAxisName: ['Rewards / FIL', 'Block / no.'], tooltip: '<div>{lineMarker}Hourly Rewards: {lineCount} FIL</div><div>{barMarker}Hourly Block Count: {barCount}</div><div>Hourly WinCount:{winCount}</div>' } }, region: { title: 'FIL Distribution', total: "Power: <i class='mark'>{total}</i>", continent: [ { key: 'circulating', name: 'Circulating', color: '#5B8FF9' }, { key: 'locked', name: 'Locked Fund', color: '#5AD8A6' }, { key: 'vested', name: 'Initial Pledge', color: '#5D7092' }, { key: 'burnt', name: 'Burnt', color: '#F6BD16' }, { key: 'mined', name: 'Node Awards', color: '#E8684A' }, { key: "other", name: "", color: "#999999" }, ] } }, topPowerTable: { title: 'Top Nodes', label: ['Storage Provider', 'QualityAdjPower', 'RawBytePower', 'Blocks', 'Rewards'], mbLabel: ['Storage Provider', 'RawByte', 'Blocks', 'Rewards'] }, tag: 'If you want to update your Node Tag, please send email to <EMAIL>, or wechat:ipfsforce', lucky: 'Deviation of actual wincount rate of node compared with the average value of the total network', topPowerChartLabel: [ { label: 'RawBytePower', index: 'RawBytePower' }, { label: 'QualityAdjPower', index: 'QualityAdjPower' } ], rate: { title: "Node's Efficiency", table: { label: ['Storage Provider', 'Power Growth', 'Storage Rate', 'Power Returns'], mbLabel: ['Storage Provider', 'Increment', 'Storage Rate', 'Returns'] }, chart: { title: "Node's Efficiency" } }, latest: { block: { title: 'The Latest Blocks', time: 'Time:', more: 'More', height: 'Height:', hash: 'Cid:', miner: 'Storage Provider:', reward: 'BlockReward:' }, message: { title: 'The Latest Messages', more: 'More', id: 'Message ID:', from: 'From:', to: 'To:' } }, filType: { floating: 'Floating: ', pledge: 'Pledge Collateral: ', outstanding: 'Outstanding: ' }, watch: 'Chain Watch', transfer: { plabels: ['From', '', 'To', 'Height', 'Value'], labels: ['From', 'To', 'Value'] }, poolTable: { tips: 'The ratio of mining pool‘s accumulative block rewards to its Quality Adjusted Power within 7 days' } }, tipset: { height: 'Height', block: { overview: [ 'Cid', 'Height', 'Time', 'Messages', 'Storage Provider', 'WinCount', 'Reward', 'Parent Cid', 'Parent Weight', 'Parent BaseFee Rate', 'Ticket', 'State Root' ], rewards: '{reward} FIL ( {block} FIL Block Reward and {fee} FIL Fee Reward )' }, blockType: ['Null Block', 'Min Ticket Block', 'Other Block'], tips: 'Ticket is a random number', tooltip: [ { label: 'NodeId: ', key: 'node' }, { label: 'Height: ', key: 'height' }, { label: 'BlockTime: ', key: 'utcTime' }, { label: 'BlockCid: ', key: 'hash' }, { label: 'WinCount: ', key: 'win_count' } ], item: { height: 'Height:', time: 'Time:', labels: ['Height', 'Cid', 'Storage Provider', 'Tag', 'Message', 'Reward', 'Time'] } }, mining: { heading: 'Ranking List', efficiency: { title: "Node's efficiency", placeholder: "Search by Node ID, separate by ',' for multiple id", label: [ 'Rank', 'Storage Provider', 'Tag', 'Rewards/Ratio', 'Blocks', 'Wincount Rate', 'Adj.Power', 'Sector Size ' ], mblabel: [ 'Rank', 'Wincount Rate', 'Blocks', 'Rewards/Ratio', 'Adj.Power', 'Sector Size ' ], tips: [ '', 'In Filecoin CryptoEconomics, there may be multiple blocks under a tipset, and each block may receive multiple win counts.', "The ratio of node's cumulative block reward to the adjusted storage power in the selected period." ], mbLabel: ['Rank', 'Storage Provider', 'Tag', 'Storage Rate'], mbLabel2: ['Rank', 'Storage Provider', 'Tag', 'Power Returns '] }, poolranking: { label: [ 'Rank', 'Pool Name', 'Power Growth', 'Daily Power Growth', 'Power Growth', 'Adj.Power', 'Sector' ], mblabel: [ 'Rank', 'Owner ID', 'Adj.Power', 'Mining Efficiency', 'Power Growth', 'Lucky Value', 'Blocks Count' ] }, powerRate: { label: [ 'Rank', 'Storage Provider', 'Power Growth', 'Daily Power Growth', 'Adj.Power', 'Power Growth', 'Sector' ] }, poolRanking: { labels: [ 'Rank', // 'Pool Name', 'Owner ID', 'Adj.Power', 'Latest 24h Output Efficiency', 'Power Growth', // 'Lucky Value', 'Blocks Mined' ], mlabels: [ '排名', 'Owner ID', 'Adj.Power', 'Mining Efficiency', 'Power Growth', // 'Lucky Value', 'Blocks Count' ] }, minerRanking: { labels: [ 'Rank', 'Storage Provider', 'Tag', 'Adj.Power / Rate', '24h Power Growth', 'Blocks / Rate ', // 'WinCount', 'Wincount Rate', 'Balance' ], mblabels: [ 'Rank', 'Adj.Power / Rate', '24h Power Growth', 'Blocks / Rate ', // 'WinCount', 'Wincount Rate', 'Balance' ] }, powerRanking: { labels: [ 'Rank', 'Storage Provider', 'Tag', 'Power Growth', 'Daily Power Growth', 'Power Growth', 'Adj.Power', 'Sector Size' ], mblabels: [ 'Rank', 'Daily Power Growth', 'Power Growth', 'Adj.Power', 'RawBytePower', 'Sector Size' ], tips: [ 'Daily total adj. power of the sealed sectors within selected period.', "Node's adjusted storage power increment in the selected period." ], sectorOption: [ { index: '0', value: '', label: 'All Sectors' }, { index: '1', label: '32G Sector' }, { index: '2', label: '64G Sector' } ] }, topPowerTable: { title: 'Top Nodes', label: [ 'Rank', 'Storage Provider', 'Tag', 'QualityAdjPower', 'RawBytePower', 'Blocks', 'WinCount', 'Rewards', 'Last Block Tipset', 'Running Time', 'Balance' //"Area" ], mbLabel: ['Rank', 'Tag', 'Adj.Power/Rate'], mbLabel2: [ 'Rank', 'Pool Name', 'Owner ID', 'Adj.Power', 'Output Efficiency' ], lowBalance: 'Balance less than 200' }, switch: ['Top Nodes', 'Efficiency'], switch2: ['Storage Pool', 'Storage Provider', 'Power Growth', 'Rewards'] // switch2: ["Top Miners", "Power Growth", "Power Returns"] }, statistics: { fil: { filTips: '', allocationTips: '', allocationTitle: 'FIL Allocation', trend: 'FIL Spot price trend', trend2: 'FIL Allocation', tips: 'Price data sources:coingecko', continent: [ { key: 'Filecoin Foundation', name: 'Filecoin Foundation', value: '5', color: '#4f7edb' }, { key: 'PL Team & Contributors', name: 'PL Team & Contributors', value: '4.5', color: '#4fbc94' }, { key: 'Protocol Labs', name: 'Protocol Labs', value: '10.5', color: '#516383' }, { key: 'Fundraising-Remainder', name: 'Fundraising-Remainder', value: '2.5', color: '#D3A51A' }, { key: 'Fundraising-SAFT 2017', name: 'Fundraising-SAFT 2017', value: '7.5', color: '#C75c46' }, { key: 'Mining Reserve', name: 'Mining Reserve', value: '15', color: '#5Faed0' }, { key: 'Storage Mining Allocation', name: 'Storage Mining Allocation', value: '55', color: '#7E63b3' } ], sourceLabel: [ { label: 'Allocation', value: 'Value', Released: 'Released', description: 'Description' }, { label: 'FIL BASE', value: '2,000,000,000', Released: '2,000,000', description: 'The maximum amount of FIL that will ever be created.' }, { label: 'Mining Reserve', value: '300,000,000 ', Released: '300,000 ', description: 'Tokens reserved for funding mining to support growth of the Filecoin Economy, whose future usage will bedecided by the Filecoin community.' }, { label: 'Storage Mining Allocation', value: '1,100,000,000', Released: '1,100', description: 'The amount of FIL allocated tostorage nodes through block rewards, network initialization, etc.' }, { label: 'Fundraising - SAFT 2017', value: '150,000,000 ', Released: '50,000 ', description: '2017 TOKEN SALE' }, { label: 'Fundraising - Remainder', value: '50,000,000', Released: '50,000 ', description: 'allocated for ecosystem development, future fundraising' }, { label: 'Protocol Labs', value: '210,000,000', Released: '20,000', description: 'allocated for Protocol Labs' }, { label: 'PL Team &amp; Contributors', value: '90,000,000', Released: '9,000 ', description: '4.5% for the PL team & contributors' } ] }, charts: { title: 'chart statistics', pledgeTitle: 'Single T mortgage trend', rewardTitle: 'Block Reward', minerTitle: 'Active Storage Provider', messageTitle: 'Message Trend', blockReward: { names: ['Mining Output Efficiency', 'Cumulative Block Reward'] }, MessageTrend: { names: ['Message Trend of Each Block', 'Message Trend of All Blocks'] } } }, calculator: { filUnit: '$', subtitle: 'Start mining time:', switch: ['Full storage capacity', 'Storage Provider Mining rig '], labels1: ['Cycle', 'Rewards', 'submit WindowPoSt only'], columns1: ['Daily', 'Weekly', 'Monthly', 'Annually'], labels2: [ 'Period of static cost recovery', 'Mining cost(total cost+Gas Fee/540-day rewards)', '540-day rewards' ], input1: ['Daily power returns', 'FIL price', 'submit WindowPoSt only'], input2: ['Total storage power', 'hardware and operations'], input3: [ 'Sector size', 'Scale of capacity', 'Power growth', 'hardware and operations' ], input4: [ 'Daily power returns', 'FIL price', 'power growth', 'submit WindowPoSt only', 'Sector initial pledge' ], labels3: [ 'Number of days required', 'Initial pledge of full storage power', 'Cost of full storage power growth', 'Daily rewards (full storage power)', 'Static cost recovery', 'Mining cost(total cost+Gas Fee/540-day rewards)', '540-day rewards' ], buttonLabels: 'Start', tips: 'Disclaimer: this calculator is based on static data. In real situation, FIL price, daily rewards(FIL/T) and cost of submit WindowPoSt only are all dynamic values. Therefore, the result is for reference only, not for investment advice.' }, more: { gas: { title: 'Base Fee Variations', tb_title: '24h Gas Data', labels: [ 'Message Type', 'Gas Premium', 'Avg. Gas Limit', 'Avg. Gas Used', 'Avg. Gas Fee', 'Total Fees/Pencentage', 'Total Messages/Pencentage' ] }, stats: { meta: [ { label: 'Avg Blocks in Tipset', tips: 'Avg Blocks in Tipset in the last 24H' }, { label: 'Avg Messages in Block', tips: 'Avg Number of Messages per Tipset Height in the last 24H' }, { label: 'Avg Gas Price', tips: 'Avg Gas Price in the Last 24h' }, { label: 'Pledge Collateral', tips: 'Total Fil in Pledge Collateral' }, { label: 'Floating', tips: '' }, { label: 'Outstanding', tips: '' } ], filOutstanding: { filType: { floating: 'Floating: ', pledge: 'Pledge Collateral: ', outstanding: 'Outstanding: ' } }, top: { title: 'Top Nodes' }, rate: { title: "Node's Efficiency" }, activeMiner: { title: 'Active Storage Nodes', count: 'Storage Provider Count: ', tips: 'The StorageNodes who made sector or sent messages' }, blockTime: { label: 'Avg Blocktime', min: 'Min', max: 'Max', tips: 'Avg blocktime in the last 24H' } } }, stats: { metrics: { blockReward: { title: 'Cumulative Block Rewards' }, filecoin: { title: 'Filecoin Network Block Reward Curve' }, filVested: { title: 'FIL Vested' }, contact: 'If you want to show more Data, Please send email to ' }, peer: { title: 'Peer ID:', label: ['Peer ID', 'Storage Provider Address', 'IP', 'Location'] } }, address: { heading: 'Rich list', list: { pcLabel: ['height', 'Cid', 'Time', 'From', 'To', 'Value', 'Methods'], label: [ 'Rank', 'Address', 'Tag', 'Balance/Rate', 'Status', 'Last Seen Time' ], total: 'Total of {num} Accounts', options: [ { value: '', index: '0', label: 'All Types' }, { value: 'account', index: '1', label: 'account' }, { value: 'owner', index: '2', label: 'owner' }, { value: 'miner', index: '3', label: 'node' }, // { value:"system", index: "4", label:"system" }, // { value:"init", index: "5", label:"init" }, // { value:"cron", index: "6", label:"cron" }, // { value:"power", index: "7", label:"power" }, // { value:"market", index: "8", label:"market" }, { value: 'payment', index: '9', label: 'payment' }, { value: 'multisig', index: '10', label: 'multisig' } // { value:"reward", index: "11", label:"reward" }, ] }, detail: { mtitle: "Storage Provider Overview", titleAcount: 'Account Overview', account: 'Address:', pool: { title: 'Pool Detail', tips: 'The data of mine pool is collected from the data of nodes.', labels: ['Account', 'Owner Address', 'Nodes'], }, dialog: { updateName: 'Update Name>', updateNames: ['Update Name >', 'Apply Account >'], title: 'Signature verification', subtitle: 'Only open claim for accounts with storage power ≥ 32.00 GiB', labels: [ 'Owner address', 'Account abbreviation(En)', 'Account abbreviation(Zh)', 'Contact', 'Message', 'Sign code', 'Signature' ], placeholders: [ '', 'Cannot over 18 characters', 'Cannot over 18 characters', 'Email、telephone nemb...', '', '', 'Pleasa copy the above sign code,sign it with Filecoin wallet,and enter the signature' ], tips: 'Special notes: sensitive workds, prohibited words, celebrity names, etc. are not allowed in account names. If there is any violation, the signature will be deleted and prohibited. Thank you for your cooperation.', btnText: 'submit' }, title: 'Account changes', overview: [ 'Address', 'ID', 'Type', 'Balance', 'Message Count', 'Nonce', 'Code Cid', 'Create Time', 'Lastest Timestamp', 'Multisig Account', ], worker: 'Worker List', ownerOverview: [ 'Owner Account', 'Peer ID', 'RawBytePower', 'QualityAdjPower', 'Sector Size', 'Sector Number', 'Proving Sector Number', 'Fault Number' ], owner: [ 'Address', 'ID', 'Type', 'Balance', 'Message Count', 'Nonce', 'Code Cid', 'Create Time', 'Lastest Timestamp', 'Nodes List', 'Active Nodes List', 'Multisig Account', ], storageMiner: [ 'Address', 'Type', 'Balance', 'Owner', 'Peer ID', 'RawBytePower', 'QualityAdjPower', 'Sector Size', 'Sector Number', 'Proving Sector Number', 'Fault Number', 'Code Cid', 'Nonce' ], multisig: [ 'Address', 'Type', 'Robust Address', 'Balance', 'Available Balance', 'Initial Balance', 'Unlock Period', 'Locking Balance', 'Signers', 'Approval Threshold', 'Message Count', 'Nonce', 'Code Cid', 'Create Time', 'Lastest Timestamp' ], OwnerToMultisig: [ 'Address', 'Type', 'Robust Address', 'Balance', 'Available Balance', 'Initial Balance', 'Unlock Period', 'Locking Balance', 'Signers', 'Approval Threshold', 'Message Count', 'Nonce', 'Code Cid', 'Create Time', 'Lastest Timestamp', 'Nodes List', 'Active Nodes List' ], minerOverview: { balance: { title: 'Total Balance', balance: 'Address Balance', available: 'Available:', pledged: 'Initial Pledge:', deposits: 'PreCommitDeposits:', reward: 'Locked Rewards:' }, power: { title: 'Power Glance', rank: 'Ranking', subtitle: 'QualityAdjPower', raw: 'RawBytePower: ', rate: 'Power Rate: ', block: 'Total Blocks: ', reward: 'Total Reward: ', win: 'Total Wincount: ', size: 'Sector Size: ', status: 'Sector Status: ', total: 'Total ', proving: 'Active ', fault: 'Faults ', pre: 'Recoveries ' }, growth: { labels: [ { label: 'Power Increase: ' }, { label: 'Storage Provider Precommit Deposits:' }, { label: 'Block: ', tips: 'Blocks mined = the sum of blocks mined' }, { label: 'Efficiency: ', tips: "The ratio of node's cumulative block reward to the adjusted storage power in the selected period." }, { label: 'Power Ratio: ' }, { label: 'Gas Fee: ' }, { label: 'Block Rewards:' }, { label: 'Lucky:', tips: "Ratio of actual blocks produced and theoretical value. If the node's Adj. Power is less than 1PiB, the value has a large randomness and is for reference only." }, { label: 'Sector Increase: ' }, { label: 'Sector Ratio: ' }, { label: 'Winner Rewards: ', tips: 'In Filecoin mining model, there may be multiple blocks under a tipset, and each block may receive multiple win counts.' }, { label: 'consume per:', tips: 'Single T package sector size gas consumption in selected period' } ], title: 'Statistical Indicators', unit: ' Sectors' } }, accountOverview: { title: 'Account Overview', actor: 'Actor:', owner: 'Owner:', time: 'Create Time:', runningDays: 'Running Time:', type: 'Type: ', worker: 'Worker:', peer: 'Peer ID:', address: 'Address:', controller: 'Controller:', location: 'Region', // location: 'Region(Public IP):', unknown: 'unknown' }, mbaccountOverview: [ 'Account: ', 'Type: ', 'Address:', 'Owner:', 'Worker:', 'Controller:', 'Create Time:', 'Running Time:', 'Peer ID:', 'Region:' // 'Region(Public IP):' ], minerBalance: { title: 'Account changes', chart: { title: 'Total Power', tooltip: '<div>{time}</div><div>{marker} {name}: {value} FIL</div>' }, tooltip: ['Available', 'Pledge', 'PreCommitDeposits', 'Rewards'], balance: 'balance: ' }, minerPower: { title: 'QualityAdjPower', names: ['Power', 'Power Increase'], chart: { title: 'Total Power', tooltip: '<div>{time}</div><div>{marker}Total QualityAdjPower: {power}</div>' } }, minerBlock: { title: 'Node’s Block', chart: { title: ['Total Block', 'Growth'] } }, minerReward: { title: 'Node’s Rewards', chart: { title: ['Total Reward / FIL', 'Growth / FIL'] } }, claim: { title: 'Claim Account', subTitle: 'Only open claim for accounts with storage power ≥ 32.00 GiB', owner: { label: 'Owner address', placeholder: '' }, en: { label: 'Account abbreviation', placeholder: 'Cannot over 18 characters', error: 'please enter account abbreviation' }, nameEn: { label: 'Account name(En)', placeholder: 'Optional' }, zh: { label: 'Account abbreviation(Zh)', placeholder: 'Optional' }, nameZh: { label: 'Account name(Zh)', placeholder: 'Optional' }, contact: { label: 'Contact', placeholder: 'Email、telephone number…', error: 'please enter contact' }, message: { label: 'Message', placeholder: '' }, signcode: { label: 'Sign code', placeholder: '' }, signature: { label: 'Signature', placeholder: 'Pleasa copy the above sign code,sign it with Filecoin wallet,and enter the signature', error: 'please enter the signature' }, submit: 'Submit', tips: 'Special notes: sensitive workds, prohibited words, celebrity names, etc. are not allowed in account names. If there is any violation, the signature will be deleted and prohibited. Thank you for your cooperation.', copy: ['copy success', 'copy failed'] } }, type: { verifiedRegister: "Verified Registry", account: 'Account', owner: 'Account(Owner)', miner: 'StorageMiner', system: 'SystemActor', init: 'InitActor', cron: 'CronActor', power: 'StoragePowerActor', market: 'StorageMarketActor', payment: 'PaymentChannelActor', multisig: 'MultiSigActor', reward: 'RewardActor' }, trend: { switch: ['Node’s Power', 'Node’s Block'], chartSwitch: ['Node Trend Chart', 'Pack Up'] }, radio: ['Message', 'Blocks', 'Transaction'], radio1: ['Message', 'Transaction'] }, message: { detail: { transactionLabels: ['From', ' ', 'To', 'Value', 'Type'], mbTransferLabels: ['From:', 'To:', 'Value:', 'Type:'], consumeTypeArr: ['','Burn Fee','Storage Provider Fee','Transfer','Punishment','Report','Aggregate cost'], titles: ['Message Overview', 'Transactions', 'Others'], overview: [ 'Message ID', 'Height', 'Block', 'Time', 'From', 'To', 'Value', 'Receipt', 'Gas Premium', 'Gas Used', 'Gas Limit', 'Gas Fee Cap', 'Method', 'Nonce', 'Params' ], infoview: [ 'Message ID', 'Height', 'Time', 'Block', 'Value', 'From', 'To', 'Receipt', 'Method' ], otherview: [ 'Version(API)', 'Nonce', 'Gas Fee Cap', 'Gas Premium', 'Gas Limit', 'Gas Used', 'BaseFee', 'Gas Fee', 'Params', 'Returns' ], transfer: { from: 'From', to: 'To', value: 'Value', consume_type: 'Type' }, paramTip: 'Raw data in Base64', confirm: 'Confirmations' }, pool: { infoview: [ 'Message ID', 'Height', 'Time', 'Value', 'From', 'To', 'Method' ], otherview: ['Version(API)', 'Nonce', 'Gas Limit', 'Gas Premium', 'Params'] } }, dsn: { list: { heading: 'Order List', total: 'Total of {num} Deals', labels: [ 'Deal ID', 'Piece CID', 'PieceSize', 'Client', 'Provider', 'Start Time', 'End Time', 'Storage Fee', 'Verified Deal' ], mLabels: [ 'Deal ID', 'Piece CID', 'PieceSize', 'Client', 'Provider', 'Create Time', 'Storage Fee', 'Verified Deal' ], tips: 'This deal is initiated by the official certified client, the adjusted power is about ten times raw power', placeholder: 'Search Client/Provider' }, detail: { dsnTitle: 'dsn Detail', title: 'Storage Detail', client: 'Client', provider: 'Provider', pledge: 'Collateral:', storageCost: 'Storage Cost:', to: 'to', block: '(Force Area)', overview: [ 'Dsn ID', 'Create Time', 'Block', 'Message', 'Piece CID', 'Verified' ] } }, noResult: { res: 'Search Not Found', 404: 'Page not found! It will be back to the home page after {count} seconds!', key: 'Oops!The search string you enterd was:', invalid: 'Sorry! This is an invalid search string', back: 'Back Home' }, routeName: { blockDetail: 'Block Detail', messageDetail: 'Message Detail', addressDetail: 'Address Detail', messageList: 'View All Messages', addressList: 'View All Accounts', tipset: 'Tipset', mining: 'Mining', metrics: 'Metrics', map: 'Peer Map', peer: 'Peer Detail', stats: 'Stats', poolMessageList: 'Messages In Flight', dsn: 'View All Deals', blocksWon: 'Blocks Won', token: 'Token' }, chart: { blockRatio: 'Blocks', minerBlockTrend: '<div>{time}</div><div>{totalMarker}Total Block Count : {total} </div><div>{increaseMarker}{interval} Block Count : {increase}</div>', minerRewardTrend: '<div>{time}</div><div>{totalMarker}Total Rewards : {total}FIL </div><div>{increaseMarker}{interval} Rewards : {increase}FIL</div><div>{interval} WinCount : {winCount}</div>', blockTime: "<div style='margin-bottom:5px'>Avg Block Time: {value}s</div><div>Time: {name}</div>", mesHistory: '<div>Message: {count}</div><div>{time}</div>', mesHistoryTitle: 'Message History in 14 Days', pledge: '<div>Pledge Collateral: {pledge} FIL</div><div>{time}</div>', tipset: '<div>MinerID: {miner}</div><div>Height: {height}</div><div>BlockTime: {block_time}</div><div>BlockCid: {cid}</div>', filOutstanding: ['Floating', 'Pledge'], blockReward: ['# Of Blocked Nodes', 'Cumulative Block Reward(FIL)'], filecoin: 'Block Reward(FIL)', filVested: ['Cumulative FIL Vested', 'FIL Vested Daily'], coming: 'coming soon...', map: "<div style='margin-bottom:5px'><a href='/more/peer?peer_id={pid}'><span>Peer ID : </span><span>{pid}</span></a></div><div style='margin-bottom:5px'><a href='/tipset/address-detail?address={miner}'><span>Node : </span><span>{Node}</span></a></div><div style='margin-bottom:5px'><span>Location : </span><span>{name}</span></div><div><span>IP : </span><span>{ip}</span></div>" }, blockHeaderChart: { op: 'Drag to view more height', start: 'start height', latest: 'Latest height' }, pk: { title: 'Storage Provider PK', placeholder: 'Please enter or select a hot node', miner: { title: '', rows: [{ label: 'Storage Provider', key: 'node' }] }, overview: { title: 'Overview of nodes', rows: [ { label: 'Total power', key: 'active_power' }, { label: 'Total Block', key: 'active_block_count' }, { label: 'Total block reward', key: 'active_block_rewards' } ] }, recent: { title: 'Recent situation of nodes', rows: [ { label: 'Power increased in the latest 24h', key: 'increased' }, { label: 'Blocks won in the latest 24h', key: 'active_win_count' }, { label: 'Block Reward in the latest 24h', key: 'fil' } ] }, efficiency: { title: 'Mining efficiency', rows: [ { label: 'Total Power Returns', key: 'active_fil_per_t' }, { label: 'Power Returns in the latest 24h', key: 'fil_per_t' }, { label: 'Proven success rate in the latest 24h', key: 'success_rate' }, { label: 'Lucky value in the latest 24h', key: 'lucky_number' } ] }, go: 'Go and choose nodes for PK!', max: 'You can choose up to 6 nodes.' }, map: { label: 'Active Nodes', tips: 'The Nodes who sent messages in the latest 24 hour' }, chartIntervalMap: { '24h': 'Hourly', '1w': 'Daily', '1m': 'Daily', '6m': 'Daily' }, token: { allocation: { columns: [ { label: 'Allocation', key: 'label' }, { label: 'Value', key: 'value' }, { label: 'Description', key: 'des' } ], list: [ { label: 'FIL BASE', rate: '100%', des: 'The maximum amount of FIL that willever be created.' }, { label: 'Mining Reserve', rate: '15%', des: 'Tokens reserved for funding miningto support growth of the FilecoinEconomy, whose future usage will bedecided by the Filecoin community.' }, { label: 'Storage Mining Allocation', rate: '55%', des: 'The amount of FIL allocated tostorage nodes through blockrewards, network initialization, etc.' }, { label: 'Fundraising - SAFT 2017', des: '2017 TOKEN SALE', rate: '7.5%' }, { label: 'Fundraising - Remainder', rate: '2.5%', des: 'allocated for ecosystem development, future fundraising' }, { label: 'Protocol Labs', des: 'allocated for Protocol Labs', rate: '10.5%' }, { label: 'PL Team & Contributors', rate: '4.5%', des: '4.5% for the PL team & contributors' }, { label: 'Filecoin Foundation', rate: '5%', des: 'allocated for Filecoin Foundation' } ] }, supply: { columns: [ { label: '', key: 'label' }, { label: 'Value', key: 'value' }, { label: 'Description', key: 'des' } ], list: [ { label: 'Market Cap', des: 'CirculatingSupply * FIL Price', key: 'market_cap' }, { label: 'Circulating Supply', des: 'FIL Vested + FIL Mined - TotalBurntFunds - FIL Locked', key: 'circulating_supply' }, { label: 'Circulation Rate', des: 'Circulating Supply / Total Supply', key: 'circulating_rate' }, { label: 'Total Supply', des: 'Circulating Supply + FIL Locked', key: 'total_supply' }, { label: 'FIL BASE', des: 'The maximum amount of FIL that will ever be created.', key: 'base' }, { label: 'Total Burnt Funds', des: 'Total FIL burned as part of penalties and on-chain computations.', key: 'total_burnt' }, { label: 'Max Supply', des: 'FIL BASE - Total Burnt Funds', key: 'max_supply' }, { label: 'FIL Locked', des: 'The amount of FIL locked as part of mining, deals, and other mechanisms.', key: 'locked' }, { label: 'TotalPledgeCollateral', des: 'Total FIL locked as collateral in all nodes.', key: 'total_ntwk_pledge_collateral' }, { label: 'TotalProviderDealCollateral', des: 'Total FIL locked as provider deal collateral.', key: 'total_provider_locked_collateral' }, { label: 'TotalClientDealCollateral ', des: 'Total FIL locked as client deal collateral.', key: 'total_client_locked_collateral' }, { label: 'TotalPendingDealPayment ', des: 'Total FIL locked as pending client deal payment.', key: 'total_pending_payment' } ], state: { title: 'FIL Total Supply by State', subTitle: 'Total Supply = FIL Circulating Supply + FIL Locked + Total Burnt Funds', legend: ['FIL Circulating Supply', 'FIL Locked', 'Total Burnt Funds'] }, source: { title: 'FIL Total Supply by Source', subTitle: 'Total Supply = FIL Vested Supply + FIL Mined', legend: ['FIL Mined', 'FIL Vested'] } }, filecoin: { title: 'Filecoin [Futures] Charts', series: ['Market Cap', 'Price'] } }, forcePool:{ forceNav: [ { label: 'Account Info', name: 'info'}, { label: 'Preference', name: 'set'} ], navTips: [ { title: 'Your Profil', content: 'This page provides an overview of your account information. You can also update your account address and password here.'}, { title: 'Storage Provider Panel', content: ' You can create your own pools and add Nodes to them for monitoring and management. The created pools are only valid for your current account. ' } ], center: { tabs: ['Your Profile','Storage Provider Panel'], menuList:[ { label: "Your Profile", icon: 'iconfont icon-center' }, { label: "Storage Provider Panel", icon: 'iconfont icon-monitor'} ], accountInfo: { labels:[ { label: 'Nickname', icon: 'edit'}, { label: 'PhoneNumber', icon: 'edit'}, { label: 'Email' , icon: 'edit'}, { label: 'Storage Provider Panel List', icon: 'add' }, { label: 'Latest Login' }, ] }, errorTips: 'Nonexistent node:', successTips: 'Storage pool has created successfully', validateTips: 'At least Mobile or Email must be filled out', nodeCount: ' Storage Provider Pool', nodeTotal: ' Storage Provider', accountSet: { labels:[ { label: 'Nickname', placeholder: 'Please enter a Nickname,', model: 'nick_name', tips: ' up to 10 characters' }, { label: 'PhoneNumber', placeholder: 'Please enter phone number', model: 'phone', tips: 'please enter your new number to make a change' }, { label: 'Email', placeholder: 'Please enter email', model: 'email',tips: 'please enter your new number to make a change' }, { label: 'Old Password', placeholder: 'Please enter the old password', model: 'pwd', tips: 'If not changed, leave it blan' }, { label: 'New Password', placeholder: 'Please enter new password', model: 'newpwd', tips: 'If not changed, leave it blan' }, { label: 'Confirm Password', placeholder: 'Please enter your password again', model: 'surepwd', tips: 'If you have changed the password above, please re-enter the new password to confirm' } ], buttons: ['Confirm', 'Cancel', 'Delete Account'], dialog: { title: 'Are you sure to permanently delete your account?', content: 'Deleting your account will also delete all watch lists, address information, and the above will not be recovered after the deletion is confirmed', buttons: ['Confirm','Cancel'] } } }, monitor: { title: 'Storage Provider Panel', total: '{total} pools have been created (up to {count} pools)', button: 'Create Storage Provider', labels: ['Storage Provider Tag', 'Storage Provider QualityAdjPower', 'Total Reward', 'Nodes under your pool'], emptyText: 'No node pool created', dialog: { title: 'Create Storage Provider', labels: [ { label: 'Pool Tag', placeholder:'Up to 10 characters can be entered', text: 'Enter Storage Provider Pool Tag', name: 'name' }, { label: 'Storage Provider', placeholder:'Enter the Nodes of your pool, separated by commas', text: 'Enter the Nodes of your pool, separated by commas', name:'miners'}, ], buttons: ['Confirm', 'Cancel'], } }, admin: { title: 'Pool Management', labels: [ { label: 'Pool Tag', placeholder: 'Please enter the tag of your Pool' }, { label: 'Storage Provider Management ', placeholder: 'Please enter the Storage Provider you want to add' }, ], enter: 'Confirm enter', buttons: ['Save', 'Cancel', 'Delete Pool'], dialog: { title:'Are sure you want to delete your current account?', content: 'The Pool data will be completely deleted after that', buttons: ['Confirm', 'Cancel'] }, limit: ['Duplicate added miner', 'Added miner already exists',' Has reached the upper limit '], nullTips:'There are no nodes in the current node pool. Please add at least one node and save', chartTips: 'Please use English comma' }, notice: { title: 'Notification Setup', tips: 'Notification method: Start notifying when your address balance is estimated to be available for less than 120 minutes', labels: ['Address: ','Type: ','SMS: ','On Call: ','Email: '], phoneTips: '( Tip: Calling notifications are only supported for Chinese users currently )', emailBtn: 'Add notification account', buttons: ['Save', 'Cancel'], breadcrumbList: ['Pool Panel', 'notice'], msgDialog: { title:'SMS', placeholder: ['Please enter phone number','Please enter verification code'], buttons:['Confirm','Cancel', 'Get Verification Code'] }, phoneDialog: { title:'Phone notice', placeholder: ['Please enter phone number','Please enter verification code'], buttons:['Confirm','Cancel', 'Get Verification Code'] }, emailDialog: { title:'Email notice', placeholder: ['Please enter email','Please enter verification code'], buttons:['Confirm','Cancel', 'Get Verification Code'] } }, list:{ button: 'Pool Management', poolOverview:{ title: 'Storage Pool Overview', labels: [ { label:'StoragePower/Ratio' }, { label:'Total Rewards' }, { label:'Sector Pledges' }, { label:'PreCommitDeposits', tips: 'When Nodes seal sectors for PreCommits, they must provide some pre-deposit as a pledge, if this part of the sector is not completed in time for ProveCommitted, this part of the pre-deposit will be forfeited, if it is completed on time for Prove it will be released back.' }, { label: 'Locked Rewards' } ] }, nodeList:{ title: 'NodeList', labels: ['Storage Provider','Tag','QualityAdjPower','Total Reward','Available', 'Initial Pledge','PreCommitDeposits','Locked Reward'] } }, detail: { nodeOverview: { title: 'NodeOverview', nodePower: 'Storage Provider Power', panelLabels: [ { label: 'Total Reward'}, { label: 'Available'}, { label: 'Sector Pledges'}, { label: 'PreCommitDeposit', tips: 'When Nodes seal sectors for PreCommits, they must provide some pre-deposit as a pledge, if this part of the sector is not completed in time for ProveCommitted, this part of the pre-deposit will be forfeited, if it is completed on time for Prove it will be released back. '}, { label: 'Locked reward'} ], tableLabels: [ { label: 'Type' }, { label: 'Address' }, { label: 'Available' }, { label: 'Estimated remaining', tips: 'The estimated remaining available time will be displayed within 30 minutes after the address is added. If there is no Gas consumption for the corresponding address, the estimated remaining available time cannot be obtained' }, { label: 'Notification Center' } ] }, nodeData: { title: 'Storage Provider Info', button: 'Download Excel', datePick: ['To','Start date','End date'], panelLabels: [ // { label: 'QualityAdjPower' }, { label: 'QualityAdjPower Increased' }, { label: 'Reward' }, { label: 'Initial Pledge' }, { label: 'Gas Consumption' } ], tableLabels: ['Date','Storage Provider','QualityAdjPower','Sealed Power','Reward', 'Initial Pledge', 'Gas Consumption'] } }, }, apiStatus: [ { code: 0 , message: 'ok'}, { code: 1 , message: 'Verification code error'}, { code: 2 , message: 'Parameter error'}, { code: 3 , message: 'unsupported operator segment'}, { code: 4 , message: 'Account has been registered'}, { code: 5 , message: 'unknown error'}, { code: 6 , message: 'Password Error, please re-enter'}, { code: 7 , message: 'Account Error, please re-enter'}, { code: 8 , message: 'Account exception, login prohibited'}, { code: 9 , message: 'Login has expired, please login again'}, { code: 10 , message: 'The password entered the second time is incorrect, please re-ente'}, { code: 11 , message: 'invalid operation'}, { code: 12 , message: 'The verification code is sent too frequently, please try again later'}, { code: 13 , message: 'Storage pool name already exists, please re-enter'}, { code: 14 , message: 'node does not exist, please reconfirm'}, { code: 15 , message: 'the number of storage pools has reached the maximum'}, ] } export default en
Sharktower/ui-react
src/components/Fields/TextFieldEnums.js
// TextFieldVariant enum used by the TextField variant prop export const TextFieldVariant = Object.freeze({ // eslint-disable-line import/prefer-default-export DEFAULT: 'default', TITLE: 'title', });
goderbauer/easy-gwt-mock
java/com/google/gwt/testing/easygwtmock/client/ArgumentMatcher.java
/* * Copyright 2001-2010 the original author or authors. * Portions Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.gwt.testing.easygwtmock.client; /** * Decides whether an actual argument is accepted. * Implement this interface to write your own matcher. * * @author <NAME> * Originally written for EasyMock {@link "www.easymock.org"} by OFFIS, Tammo Freese */ public interface ArgumentMatcher { /** * Returns true if this matcher accepts the given argument. * <p> * Like Object.equals(), it should be aware that the argument passed might * be null and of any type. So you will usually start the method with an * instanceof and/or null check. * <p> * The method should <b>never</b> assert if the argument doesn't match. It * should only return false. EasyGwtMock will take care of asserting if the * call is really unexpected. */ boolean matches(Object argument); /** * Appends a string representation of this matcher to the given buffer. In * case of failure, the printed message will show this string to allow to * know which matcher was used for the failing call. */ void appendTo(StringBuffer buffer); }
sabatale/articulate
api/lib/services/server.services.js
import Schmervice from 'schmervice'; import TimingWrapper from '../../util/service-timing-wrapper'; import Create from './server/server.create.service'; import Get from './server/server.get.service'; import Update from './server/server.update.service.js'; module.exports = class ServerService extends Schmervice.Service { async create() { return await TimingWrapper({ cls: this, fn: Create, name: 'Create' }).apply(this, arguments); } async get() { return await TimingWrapper({ cls: this, fn: Get, name: 'Get' }).apply(this, arguments); } async update() { return await TimingWrapper({ cls: this, fn: Update, name: 'Update' }).apply(this, arguments); } };
lordfuoco/cornerstoneTools
src/util/drawArrow.js
<filename>src/util/drawArrow.js import { drawLine, drawJoinedLines } from './drawing.js'; export default function (context, start, end, color, lineWidth) { // Variables to be used when creating the arrow const headLength = 10; const angle = Math.atan2(end.y - start.y, end.x - start.x); // Starting path of the arrow from the start square to the end square and drawing the stroke let options = { color, lineWidth }; drawLine(context, undefined, start, end, options, 'canvas'); options = { color, lineWidth, fillStyle: color }; const points = [ { x: end.x - headLength * Math.cos(angle - Math.PI / 7), y: end.y - headLength * Math.sin(angle - Math.PI / 7) }, { x: end.x - headLength * Math.cos(angle + Math.PI / 7), y: end.y - headLength * Math.sin(angle + Math.PI / 7) }, end ]; drawJoinedLines(context, undefined, end, points, options, 'canvas'); }
zhangkn/iOS14Header
System/Library/PrivateFrameworks/ProximityUI.framework/PRDevicePoseValidator.h
<reponame>zhangkn/iOS14Header /* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 12:26:03 PM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/ProximityUI.framework/ProximityUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ @protocol OS_os_log; @class NSObject, PRPose; @interface PRDevicePoseValidator : NSObject { NSObject*<OS_os_log> _logger; double _maximumSpeed; PRPose* _previousPose; } @property (assign,nonatomic) double maximumSpeed; //@synthesize maximumSpeed=_maximumSpeed - In the implementation block @property (nonatomic,retain) PRPose * previousPose; //@synthesize previousPose=_previousPose - In the implementation block -(void)setMaximumSpeed:(double)arg1 ; -(PRPose *)previousPose; -(void)setPreviousPose:(PRPose *)arg1 ; -(double)maximumSpeed; -(id)initWithMaximumSpeed:(double)arg1 ; -(BOOL)validatePose:(id)arg1 ; @end
bbeck/twitch-plays-crosswords
api/crossword/settings.go
<filename>api/crossword/settings.go package crossword import ( "encoding/json" "fmt" "github.com/bbeck/puzzles-with-chat/api/db" "github.com/bbeck/puzzles-with-chat/api/model" "github.com/gomodule/redigo/redis" ) // Settings represents the optional behaviors that can be enabled or disabled // by a streamer for their channel's crossword solves. type Settings struct { // When enabled only correct answers will be filled into the puzzle grid. OnlyAllowCorrectAnswers bool `json:"only_allow_correct_answers"` // Which clues should be shown to users. Can be all of the clues, none of the // clues, only across clues or only down clues. CluesToShow ClueVisibility `json:"clues_to_show"` // What font size should the clues be rendered with. ClueFontSize model.FontSize `json:"clue_font_size"` // Whether or not notes field should shown. ShowNotes bool `json:"show_notes"` } // ClueVisibility is an enumeration representing which clues should be shown. type ClueVisibility int const ( AllCluesVisible ClueVisibility = iota NoCluesVisible OnlyDownCluesVisible OnlyAcrossCluesVisible ) func (v ClueVisibility) String() string { switch v { case AllCluesVisible: return "all" case NoCluesVisible: return "none" case OnlyDownCluesVisible: return "down" case OnlyAcrossCluesVisible: return "across" default: return "unknown" } } func (v ClueVisibility) MarshalJSON() ([]byte, error) { var ok bool switch v { case AllCluesVisible: ok = true case NoCluesVisible: ok = true case OnlyDownCluesVisible: ok = true case OnlyAcrossCluesVisible: ok = true } if !ok { return nil, fmt.Errorf("unable to marshal invalid clue visibility: %v", v) } return json.Marshal(v.String()) } func (v *ClueVisibility) UnmarshalJSON(bs []byte) error { var str string if err := json.Unmarshal(bs, &str); err != nil { return err } switch str { case "all": *v = AllCluesVisible case "none": *v = NoCluesVisible case "down": *v = OnlyDownCluesVisible case "across": *v = OnlyAcrossCluesVisible default: return fmt.Errorf("unable to unmarshal invalid clue visibility: %s", str) } return nil } // SettingsKey returns the key that should be used in redis to store a // particular channel's settings. func SettingsKey(name string) string { return fmt.Sprintf("%s:crossword:settings", name) } // GetSettings will load settings for the provided channel name. If the // settings can't be properly loaded then an error will be returned. func GetSettings(conn redis.Conn, channel string) (Settings, error) { var settings Settings if testSettingsLoadError != nil { return settings, testSettingsLoadError } err := db.Get(conn, SettingsKey(channel), &settings) return settings, err } // SetSettings will write settings for the provided channel name. If the // settings can't be properly written then an error will be returned. func SetSettings(conn redis.Conn, channel string, settings Settings) error { if testSettingsSaveError != nil { return testSettingsSaveError } return db.Set(conn, SettingsKey(channel), settings) }
amlalejini/signalgp-lite
include/sgpl/operations/actions/actions.hpp
#pragma once #ifndef SGPL_OPERATIONS_ACTIONS_ACTIONS_HPP_INCLUDE #define SGPL_OPERATIONS_ACTIONS_ACTIONS_HPP_INCLUDE #include "ForkIf.hpp" #include "Nop.hpp" #include "TerminateIf.hpp" #endif // #ifndef SGPL_OPERATIONS_ACTIONS_ACTIONS_HPP_INCLUDE
algoriddle/cp
uva/11340.cc
#include <iostream> #include <cstring> #include <iomanip> #include <limits> using namespace std; int t[256]; int main() { ios::sync_with_stdio(false); cout << setiosflags(ios::fixed) << setprecision(2); int q; cin >> q; //cout << q << endl; while (q--) { int k; cin >> k; //cout << k << endl; memset(t, 0, sizeof t); cin.ignore(); while (k--) { unsigned char c = cin.get(); int v; cin >> v; t[c] = v; cin.ignore(numeric_limits<std::streamsize>::max(), '\n'); //cout << c << ' ' << v << endl; } int m; cin >> m; cin.ignore(); long long total = 0; while (m--) { string line; getline(cin, line); //cout << line << endl; for (unsigned char c : line) { total += t[c]; } } cout << (double)total / 100.0L << '$' << endl; } return 0; }
david-castillo/TADkit
src/layout/home.controller.js
<reponame>david-castillo/TADkit (function() { 'use strict'; angular .module('TADkit') .controller('HomeController', HomeController); function HomeController ($scope){ } })();
alexandra-bucur/egeria-connector-ibm-information-server
igc-clientlibrary/src/main/java/org/odpi/egeria/connectors/ibm/igc/clientlibrary/model/base/Dsmfcolumninfo.java
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.egeria.connectors.ibm.igc.clientlibrary.model.base; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonTypeName; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE; import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.PUBLIC_ONLY; import com.fasterxml.jackson.annotation.JsonProperty; import org.odpi.egeria.connectors.ibm.igc.clientlibrary.model.common.Reference; /** * POJO for the {@code dsmfcolumninfo} asset type in IGC, displayed as '{@literal DSMFColumnInfo}' in the IGC UI. * <br><br> * (this code has been created based on out-of-the-box IGC metadata types. * If modifications are needed, eg. to handle custom attributes, * extending from this class in your own custom class is the best approach.) */ @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.EXISTING_PROPERTY, property="_type", visible=true, defaultImpl=Dsmfcolumninfo.class) @JsonAutoDetect(getterVisibility=PUBLIC_ONLY, setterVisibility=PUBLIC_ONLY, fieldVisibility=NONE) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIgnoreProperties(ignoreUnknown=true) @JsonTypeName("dsmfcolumninfo") public class Dsmfcolumninfo extends Reference { @JsonProperty("a_xmeta_locking_root") protected String aXmetaLockingRoot; @JsonProperty("aggregation") protected String aggregation; @JsonProperty("column_value") protected String columnValue; @JsonProperty("name") protected String name; @JsonProperty("of_ds_stage") protected Stage ofDsStage; @JsonProperty("sort_link") protected String sortLink; @JsonProperty("sort_order") protected Number sortOrder; @JsonProperty("usage_class") protected String usageClass; /** * Retrieve the {@code a_xmeta_locking_root} property (displayed as '{@literal A XMeta Locking Root}') of the object. * @return {@code String} */ @JsonProperty("a_xmeta_locking_root") public String getAXmetaLockingRoot() { return this.aXmetaLockingRoot; } /** * Set the {@code a_xmeta_locking_root} property (displayed as {@code A XMeta Locking Root}) of the object. * @param aXmetaLockingRoot the value to set */ @JsonProperty("a_xmeta_locking_root") public void setAXmetaLockingRoot(String aXmetaLockingRoot) { this.aXmetaLockingRoot = aXmetaLockingRoot; } /** * Retrieve the {@code aggregation} property (displayed as '{@literal Aggregation}') of the object. * @return {@code String} */ @JsonProperty("aggregation") public String getAggregation() { return this.aggregation; } /** * Set the {@code aggregation} property (displayed as {@code Aggregation}) of the object. * @param aggregation the value to set */ @JsonProperty("aggregation") public void setAggregation(String aggregation) { this.aggregation = aggregation; } /** * Retrieve the {@code column_value} property (displayed as '{@literal Column Value}') of the object. * @return {@code String} */ @JsonProperty("column_value") public String getColumnValue() { return this.columnValue; } /** * Set the {@code column_value} property (displayed as {@code Column Value}) of the object. * @param columnValue the value to set */ @JsonProperty("column_value") public void setColumnValue(String columnValue) { this.columnValue = columnValue; } /** * Retrieve the {@code name} property (displayed as '{@literal Name}') of the object. * @return {@code String} */ @JsonProperty("name") public String getTheName() { return this.name; } /** * Set the {@code name} property (displayed as {@code Name}) of the object. * @param name the value to set */ @JsonProperty("name") public void setTheName(String name) { this.name = name; } /** * Retrieve the {@code of_ds_stage} property (displayed as '{@literal Of DS Stage}') of the object. * @return {@code Stage} */ @JsonProperty("of_ds_stage") public Stage getOfDsStage() { return this.ofDsStage; } /** * Set the {@code of_ds_stage} property (displayed as {@code Of DS Stage}) of the object. * @param ofDsStage the value to set */ @JsonProperty("of_ds_stage") public void setOfDsStage(Stage ofDsStage) { this.ofDsStage = ofDsStage; } /** * Retrieve the {@code sort_link} property (displayed as '{@literal Sort Link}') of the object. * @return {@code String} */ @JsonProperty("sort_link") public String getSortLink() { return this.sortLink; } /** * Set the {@code sort_link} property (displayed as {@code Sort Link}) of the object. * @param sortLink the value to set */ @JsonProperty("sort_link") public void setSortLink(String sortLink) { this.sortLink = sortLink; } /** * Retrieve the {@code sort_order} property (displayed as '{@literal Sort Order}') of the object. * @return {@code Number} */ @JsonProperty("sort_order") public Number getSortOrder() { return this.sortOrder; } /** * Set the {@code sort_order} property (displayed as {@code Sort Order}) of the object. * @param sortOrder the value to set */ @JsonProperty("sort_order") public void setSortOrder(Number sortOrder) { this.sortOrder = sortOrder; } /** * Retrieve the {@code usage_class} property (displayed as '{@literal Usage Class}') of the object. * @return {@code String} */ @JsonProperty("usage_class") public String getUsageClass() { return this.usageClass; } /** * Set the {@code usage_class} property (displayed as {@code Usage Class}) of the object. * @param usageClass the value to set */ @JsonProperty("usage_class") public void setUsageClass(String usageClass) { this.usageClass = usageClass; } }
arkanovicz/velosurf
src/java/velosurf/util/FastHttpDateFormat.java
<filename>src/java/velosurf/util/FastHttpDateFormat.java /* * Copyright 2003 The Apache Software Foundation. * * 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 velosurf.util; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.TimeZone; /** * <p>Utility class to generate HTTP dates.</p> * <p>This source code is taken from Tomcat Apache</p> * * @author <NAME> * @author <NAME> <a href="mailto:<EMAIL>">&lt;<EMAIL>&gt;</a> */ public class FastHttpDateFormat { // -------------------------------------------------------------- Variables /** * HTTP date format. */ private static final SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); /** * The set of SimpleDateFormat formats to use in <code>getDateHeader()</code>. */ private static final SimpleDateFormat formats[] = { new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US), new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) }; /** * GMT timezone - all HTTP dates are on GMT */ private final static TimeZone gmtZone = TimeZone.getTimeZone("GMT"); static { format.setTimeZone(gmtZone); formats[0].setTimeZone(gmtZone); formats[1].setTimeZone(gmtZone); formats[2].setTimeZone(gmtZone); } /** * Instant on which the currentDate object was generated. */ private static long currentDateGenerated = 0L; /** * Current formatted date. */ private static String currentDate = null; /** * Formatter cache. */ private static final HashMap formatCache = new HashMap(); /** * Parser cache. */ private static final HashMap parseCache = new HashMap(); // --------------------------------------------------------- Public Methods /** * Gets the current date in HTTP format. * * @return Current date in HTTP format */ public static final String getCurrentDate() { long now = System.currentTimeMillis(); if((now - currentDateGenerated) > 1000) { synchronized(format) { if((now - currentDateGenerated) > 1000) { currentDateGenerated = now; currentDate = format.format(new Date(now)); } } } return currentDate; } /** * Formats a specified date to HTTP format. If local format is not * <code>null</code>, it's used instead. * * @param value Date value to format * @param threadLocalformat The format to use (or <code>null</code> -- then * HTTP format will be used) * @return Formatted date */ public static final String formatDate(long value, DateFormat threadLocalformat) { String cachedDate = null; Long longValue = Long.valueOf(value); try { cachedDate = (String)formatCache.get(longValue); } catch(Exception e) {} if(cachedDate != null) { return cachedDate; } String newDate = null; Date dateValue = new Date(value); if(threadLocalformat != null) { newDate = threadLocalformat.format(dateValue); synchronized(formatCache) { updateCache(formatCache, longValue, newDate); } } else { synchronized(formatCache) { newDate = format.format(dateValue); updateCache(formatCache, longValue, newDate); } } return newDate; } /** * Tries to parse the given date as an HTTP date. If local format list is not * <code>null</code>, it's used instead. * * @param value The string to parse * @param threadLocalformats Array of formats to use for parsing. * If <code>null</code>, HTTP formats are used. * @return Parsed date (or -1 if error occured) */ public static final long parseDate(String value, DateFormat[] threadLocalformats) { Long cachedDate = null; try { cachedDate = (Long)parseCache.get(value); } catch(Exception e) {} if(cachedDate != null) { return cachedDate.longValue(); } Long date = null; if(threadLocalformats != null) { date = internalParseDate(value, threadLocalformats); synchronized(parseCache) { updateCache(parseCache, value, date); } } else { synchronized(parseCache) { date = internalParseDate(value, formats); updateCache(parseCache, value, date); } } if(date == null) { return(-1L); } else { return date.longValue(); } } /** * Parses date with given formatters. * * @param value The string to parse * @param formats Array of formats to use * @return Parsed date (or <code>null</code> if no formatter mached) */ private static final Long internalParseDate(String value, DateFormat[] formats) { Date date = null; for(int i = 0; (date == null) && (i < formats.length); i++) { try { date = formats[i].parse(value); } catch(ParseException e) { ; } } if(date == null) { return null; } return Long.valueOf(date.getTime()); } /** * Updates cache. * * @param cache Cache to be updated * @param key Key to be updated * @param value New value */ private static final void updateCache(HashMap cache, Object key, Object value) { if(value == null) { return; } if(cache.size() > 1000) { cache.clear(); } cache.put(key, value); } }
broccoliboy/LedFx
frontend/src/components/BugTracker/index.js
import React from 'react'; import { useSelector } from 'react-redux'; import Button from '@material-ui/core/Button'; import TextField from '@material-ui/core/TextField'; import IconButton from '@material-ui/core/IconButton'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import BugReportIcon from '@material-ui/icons/BugReport'; export default function FormDialog() { const WEBHOOK_URL = 'https://discord.com/api/webhooks/<KEY>'; const [open, setOpen] = React.useState(false); const [name, setName] = React.useState(''); const [description, setDescription] = React.useState(''); const settings = useSelector(state => state.settings); const infos = { userAgent: navigator.userAgent, language: navigator.language, platform: navigator.platform, }; const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); sendMessage({ text: JSON.stringify(infos) }); }; const sendMessage = async ({ avatar = '' }) => { const request = new XMLHttpRequest(); request.open('POST', WEBHOOK_URL); request.setRequestHeader('Content-type', 'application/json'); const params = { username: name, avatar_url: avatar, content: ` Description: \`\`\`json ${JSON.stringify(description)} \`\`\` Infos: \`\`\`json ${JSON.stringify(infos)} \`\`\` Settings:\`\`\`json ${JSON.stringify(settings)} \`\`\`Logs-URL: \`\`\`https://logsurl-are-incoming.com\`\`\` `, }; request.send(JSON.stringify(params)); }; return ( <div style={{ display: 'inline-block' }}> <IconButton onClick={handleClickOpen}> <BugReportIcon aria-label="BugTracker" color="inherit" title="BugTracker" /> </IconButton> <Dialog open={open} onClose={handleClose} aria-labelledby="form-dialog-title"> <DialogTitle id="form-dialog-title">LedFx BugTracker</DialogTitle> <DialogContent> <DialogContentText> Attention, if you abuse this service, Blade will hack you... No, serious!! We need to pay 3,30€ per request </DialogContentText> <TextField autoFocus margin="dense" value={name} onChange={e => setName(e.target.value)} id="name" label="Name" type="text" fullWidth /> <TextField autoFocus margin="dense" value={description} onChange={e => setDescription(e.target.value)} id="description" label="Description" type="text" fullWidth /> </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary"> Cancel </Button> <Button onClick={handleClose} color="primary"> Subscribe </Button> </DialogActions> </Dialog> </div> ); }
nanyou0316/the_thrid
day05/code/be/db/index.js
//1. 引入需要的第三方库 const mongoose = require('mongoose') //2. 连接数据库 mongoose.connect('mongodb://localhost:27017/2005', { useNewUrlParser: true }, error => { if (error) throw error console.log('数据库连接成功') }) //3. 创建骨架 ---> 实质就是在做数据库的字段定义 const shopSchema = new mongoose.Schema({ shopId: String, shopTitle: String, shopDesc: String, shopNum: String, shopPrice: String, shopName: String, shopPic: String }) //4. 创建模型 // mongoose.model(集合名称【复数】,骨架) const shopModel = mongoose.model('shops', shopSchema) module.exports = { shop: { add(data) { return new Promise(async (resolve, reject) => { const docs = await this.query() const f = docs.data.some(item => item.shopId == data.shopId) if (f) { // 找到了 resolve({ status: 2, msg: '商品已添加,请勿重复添加' }) } else { // 没有找到 const shopEnity = new shopModel(data) shopEnity.save() resolve({ status: 1, msg: '添加成功' }) } }) }, del(_id) { return new Promise((resolve, reject) => { shopModel.findById(_id, (error, doc) => { // console.log('doc',doc) 就是_id的这条数据 if (error) reject({ status: 0, msg: '删除失败' }) doc.remove() resolve({ status: 1, msg: '删除成功' }) }) }) }, update(data) { console.log('data', data) const { _id } = data return new Promise((resolve, reject) => { shopModel.findById(_id, (error, doc) => { if (error) reject({ status: 0, msg: '修改失败了' }) // console.log('doc',doc) for (let key in data) { doc[key] = data[key] } doc.save(async (err) => { resolve({ status: 1, msg: '修改成功', data: await this.query() }) }) }) }) }, query() { return new Promise((resolve, reject) => { shopModel.find({}, (error, docs) => { if (error) { reject({ status: 0, msg: '查询失败' }) } else { resolve({ status: 1, msg: '查询成功', data: docs }) } }) }) } } }
cts2/twinkql
src/example/java/org/twinkql/example/alias/Tetris.java
<filename>src/example/java/org/twinkql/example/alias/Tetris.java<gh_stars>1-10 package org.twinkql.example.alias; import java.util.List; public class Tetris { private List<String> comments; public List<String> getComments() { return comments; } public void setComments(List<String> comments) { this.comments = comments; } @Override public String toString() { return "Tetris [comments=" + comments + "]"; } }
trinitroglycerin/key-conjurer
api/authenticators/okta/saml.go
package okta import ( "errors" "fmt" "io" "github.com/riotgames/key-conjurer/api/core" "golang.org/x/net/html" ) func walkHTMLTree(node *html.Node, condition func(*html.Node) bool) (*html.Node, bool) { if condition(node) { return node, true } for child := node.FirstChild; child != nil; child = child.NextSibling { if n, present := walkHTMLTree(child, condition); present { return n, true } } return nil, false } var errMalformedResponse = errors.New("malformed response") func getAttribute(node *html.Node, name string) (string, bool) { for _, attr := range node.Attr { if attr.Key == name { return attr.Val, true } } return "", false } func hasAttributeEquals(node *html.Node, name string, value string) bool { attr, present := getAttribute(node, name) return present && attr == value } func extractEncodedSAMLResponseFromBody(node *html.Node) (str string, err error) { node, ok := walkHTMLTree(node, func(n *html.Node) bool { return n.Type == html.ElementNode && n.Data == "form" }) if !ok { err = fmt.Errorf("could not find form: %w", errMalformedResponse) return } input, ok := walkHTMLTree(node, func(n *html.Node) bool { return n.Type == html.ElementNode && n.Data == "input" && hasAttributeEquals(n, "name", "SAMLResponse") }) if !ok { err = fmt.Errorf("could not find input with name SAMLResponse: %w", errMalformedResponse) return } value, ok := getAttribute(input, "value") if !ok { err = fmt.Errorf("could not find value attribute on input: %w", errMalformedResponse) return } return value, nil } func extractSAMLResponse(reader io.Reader) (*core.SAMLResponse, error) { document, err := html.Parse(reader) if err != nil { return nil, err } encoded, err := extractEncodedSAMLResponseFromBody(document) if err != nil { return nil, nil } return core.ParseEncodedResponse(encoded) }
prulloac/mddv
ui/src/redux/reducers/index.js
import { combineReducers } from 'redux' import userReducer from './user-reducer' import repositoryReducer from './repository-reducer' import notificationReducer from './notification-reducer' import businessObjectReducer from './business-objects-reducer' import technicalObjectReducer from './technical-objects-reducer' const rootReducer = combineReducers({ userReducer, repositoryReducer, notificationReducer, businessObjectReducer, technicalObjectReducer, }) export { rootReducer } export { userReducer } export { repositoryReducer } export { notificationReducer } export { businessObjectReducer } export { technicalObjectReducer }
johnobrien8642/JOB_Developer
client/src/components/posts/util/functions/feed_util.js
import React from 'react'; import TagResult from '../../../search/resultTypes/Tag_Result'; import UserResult from '../../../search/resultTypes/User_Result'; const header = (user, tag) => { if (user) { return ( <UserResult user={user} /> ) } else if (tag) { return ( <TagResult tag={tag} /> ) } } const infiniteScroll = ( client, updateCacheFunc, query, gqlQuery, cursorId, fetchMoreDiv, fetchMoreDivId ) => { return document.addEventListener('scroll', function(event) { fetchMoreDiv.current = document.querySelector(fetchMoreDivId.current) if (fetchMoreDiv.current) { var el = fetchMoreDiv.current.getBoundingClientRect() var elTop = el.top var elBottom = el.bottom var innerHeight = window.innerHeight if (elTop >= 0 && elBottom <= innerHeight) { client.query({ query: gqlQuery.current, variables: { query: query.current, cursorId: cursorId.current }, fetchPolicy: 'no-cache' }).then(res => { if (res.loading) return 'Loading...'; updateCacheFunc( res, client, query.current, gqlQuery.current, cursorId ) }) } } }) } const handlePostNotesScrollOutOfWindow = ( notesActive, setNotesActive ) => { return document.addEventListener('scroll', function(event) { var node = document.querySelector('.postNotes') if (node) { var el = node.getBoundingClientRect(), elTop = el.top, elBottom = el.bottom, innerHeight = window.innerHeight if (elTop > innerHeight + 10 || elBottom < -10) { setNotesActive(notesActive = false) } } }) } const updateCacheInfScroll = ( res, client, query, gqlQuery, cursorId ) => { var readFeed = client.readQuery({ query: gqlQuery, variables: { query: query, cursorId: cursorId.current }, }) if (readFeed) { var { fetchUserFeed } = readFeed; } var newData var oldArr var newArr if (fetchUserFeed) { oldArr = fetchUserFeed newData = res.data.fetchUserFeed newArr = [...oldArr, ...newData] client.writeQuery({ query: gqlQuery, variables: { query: query, cursorId: cursorId.current }, data: { fetchUserFeed: newArr } }) } if (newData) { cursorId.current = newData.length > 0 ? newData[newData.length - 1]._id : null } } const updateCacheInfScrollActivity = ( res, client, query, gqlQuery, cursorId ) => { var readFeed = client.readQuery({ query: gqlQuery, variables: { query: query, cursorId: cursorId.current }, }) if (readFeed) { var { fetchAllUserActivity } = readFeed; } var oldArr var newData if (fetchAllUserActivity) { oldArr = fetchAllUserActivity newData = res.data.fetchAllUserActivity var newArr = [...oldArr, ...newData] if (fetchAllUserActivity) { client.writeQuery({ query: gqlQuery, variables: { query: query, cursorId: cursorId.current }, data: { fetchAllUserActivity: newArr } }) } if (newData) { cursorId.current = newData.length > 0 ? newData[newData.length - 1]._id : null } } } const updateCacheInfScrollUserFollowers = ( res, client, query, gqlQuery, cursorId ) => { var readFeed = client.readQuery({ query: gqlQuery, variables: { query: query, cursorId: cursorId.current }, }) if (readFeed) { var { fetchUserFollowers } = readFeed; } var oldArr var newData var newArr if (fetchUserFollowers) { oldArr = fetchUserFollowers newData = res.data.fetchUserFollowers newArr = [...oldArr, ...newData] client.writeQuery({ query: gqlQuery, variables: { query: query, cursorId: cursorId.current }, data: { fetchUserFollowers: newArr } }) } if (newData) { cursorId.current = newData.length > 0 ? newData[newData.length - 1]._id : null } } const updateCacheInfScrollFollowedUsers = ( res, client, query, gqlQuery, cursorId ) => { var readFeed = client.readQuery({ query: gqlQuery, variables: { query: query, cursorId: cursorId.current }, }) if (readFeed) { var { fetchFollowedUsers } = readFeed; } var oldArr var newData var newArr if (fetchFollowedUsers) { oldArr = fetchFollowedUsers newData = res.data.fetchFollowedUsers newArr = [...oldArr, ...newData] client.writeQuery({ query: gqlQuery, variables: { query: query, cursorId: cursorId.current }, data: { fetchFollowedUsers: newArr } }) } if (newData) { cursorId.current = newData.length > 0 ? newData[newData.length - 1]._id : null } } const handleData = (data, feedArr, cursorId, endOfPosts) => { var { fetchFeed, searchPosts } = data if (fetchFeed) { feedArr.current = fetchFeed } else if (searchPosts) { feedArr.current = searchPosts } endOfPosts.current = feedArr.current.length === 0 ? true : false if (feedArr.current.length > 0) { cursorId.current = feedArr.current[feedArr.current.length - 1]._id } } const setgqlQueryAndQueryFeed = ( tag, user, userLikes, gqlQuery, query, FETCH_TAG_FEED, FETCH_USER_BLOG_FEED, FETCH_USER_LIKES, currentUser ) => { if (tag) { query.current = tag.title.slice(1) gqlQuery.current = FETCH_TAG_FEED } else if (user) { query.current = user.blogName gqlQuery.current = FETCH_USER_BLOG_FEED } else if (userLikes) { query.current = currentUser gqlQuery.current = FETCH_USER_LIKES } else { query.current = currentUser } } const setgqlQueryUserFollowedOrFollowingOrActivity = ( historyParam, gqlQuery, FETCH_USER_FOLLOWERS, FETCH_FOLLOWED_USERS, FETCH_ALL_ACTIVITY ) => { if (historyParam === '/followers') { gqlQuery.current = FETCH_USER_FOLLOWERS } else if (historyParam === '/following') { gqlQuery.current = FETCH_FOLLOWED_USERS } else if (historyParam === '/activity') { gqlQuery.current = FETCH_ALL_ACTIVITY } } const FeedUtil = { header, updateCacheInfScroll, infiniteScroll, updateCacheInfScrollActivity, updateCacheInfScrollUserFollowers, updateCacheInfScrollFollowedUsers, handlePostNotesScrollOutOfWindow, handleData, setgqlQueryAndQueryFeed, setgqlQueryUserFollowedOrFollowingOrActivity // doesUserFollowUser } export default FeedUtil;
r00ster91/serenity
Userland/Libraries/LibJS/Tests/builtins/WeakSet/WeakSet.prototype.delete.js
<reponame>r00ster91/serenity test("basic functionality", () => { expect(WeakSet.prototype.delete).toHaveLength(1); var original = [{ a: 1 }, { a: 2 }, { a: 3 }]; const weakSet = new WeakSet(original); expect(weakSet.delete(original[0])).toBeTrue(); expect(weakSet.delete(original[0])).toBeFalse(); expect(weakSet.delete(null)).toBeFalse(); });
EmilPi/PuzzleLib
Backend/Kernels/Pad.py
<reponame>EmilPi/PuzzleLib<filename>Backend/Kernels/Pad.py from PuzzleLib import Config reflectpad1d = None reflectpad1dBackward = None reflectpad2d = None reflectpad2dBackward = None def autoinit(): if not Config.shouldInit(): return if Config.backend == Config.Backend.cuda: initCuda() elif Config.backend == Config.Backend.hip: initHip() elif Config.isCPUBased(Config.backend): initCPU() else: raise Config.ConfigError(Config.backend) def initCuda(): from PuzzleLib.Cuda import Backend initGPU(Backend) def initHip(): from PuzzleLib.Hip import Backend initGPU(Backend) def initGPU(Backend): backend = Backend.getBackend(Config.deviceIdx, initmode=2, logger=Config.getLogger()) memoryPool, padmod = backend.memoryPool, backend.padmod def wrapReflectPad(data, pad): return padmod.reflectpad(data, pad, memoryPool) def wrapReflectPadBackward(grad, pad): return padmod.reflectpadBackward(grad, pad, memoryPool) global reflectpad1d, reflectpad1dBackward, reflectpad2d, reflectpad2dBackward reflectpad1d = reflectpad2d = wrapReflectPad reflectpad1dBackward = reflectpad2dBackward = wrapReflectPadBackward def initCPU(): from PuzzleLib.CPU.Kernels import Pad global reflectpad1d reflectpad1d = Pad.reflectpad1d global reflectpad2d reflectpad2d = Pad.reflectpad2d autoinit()
DevLabsDigital/consultoria_gem
app/javascript/components/app/util/date_util.js
<reponame>DevLabsDigital/consultoria_gem const addSecondZero = value => { const strValue = value.toString(); if (strValue.length === 1) return `0${strValue}`; return strValue; }; export const formatDateTime = orignalDate => { const date = new Date(orignalDate); return `${addSecondZero(date.getDate())}/${addSecondZero(date.getMonth() + 1)}/${date.getFullYear()} ${addSecondZero(date.getHours())}:${addSecondZero(date.getMinutes())}`; };
MarkStega/CQC
Source/AllProjects/CoreTech/CQCIR/CQCIR_BlasterDevModel.hpp
// // FILE NAME: CQCIR_BlasterDevModel.hpp // // AUTHOR: <NAME> // // CREATED: 02/23/2002 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (<NAME>.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This class represents an IR device model, and holds a set of commands // that are relevant to that device. At this level we need the name of the // device (which is the key field), a description of the device for display // purposes, and a keyed collection of TIRBlasterCmd objects. // // CAVEATS/GOTCHAS: // // LOG: // // $Log$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TIRBlasterDevModel // PREFIX: irbdm // --------------------------------------------------------------------------- class CQCIREXPORT TIRBlasterDevModel : public TObject, public MStreamable { public : // ------------------------------------------------------------------- // Class specific types // ------------------------------------------------------------------- using TCmdMap = TKeyedHashSet<TIRBlasterCmd, TString, TStringKeyOps>; using TCmdCursor = TCmdMap::TCursor; // ------------------------------------------------------------------- // Public, static methods // ------------------------------------------------------------------- static const TString& strKey ( const TIRBlasterDevModel& irbdmSrc ); static tCIDLib::TVoid StreamHeader ( TBinInStream& strmSrc , tCIDLib::TCard4& c4RepeatCount , TString& strDevModel , TString& strDevMake , TString& strDescr , tCQCKit::EDevCats& eCategory ); // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TIRBlasterDevModel(); TIRBlasterDevModel ( const TString& strModel , const tCQCKit::EDevCats eCategory ); TIRBlasterDevModel ( const TString& strModel , const TString& strMake , const TString& strDescr , const tCQCKit::EDevCats eCategory ); TIRBlasterDevModel(const TIRBlasterDevModel&) = default; TIRBlasterDevModel(TIRBlasterDevModel&&) = default; ~TIRBlasterDevModel(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TIRBlasterDevModel& operator=(const TIRBlasterDevModel&) = default; TIRBlasterDevModel& operator=(TIRBlasterDevModel&&) = default; // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TBoolean bCmdExists ( const TString& strCmdToFind ) const; tCIDLib::TCard4 c4RepeatCount() const; tCIDLib::TCard4 c4RepeatCount ( const tCIDLib::TCard4 c4ToSet ); TCmdCursor cursCmds() const; tCQCKit::EDevCats eCategory() const; tCQCKit::EDevCats eCategory ( const tCQCKit::EDevCats eToSet ); TIRBlasterCmd& irbcAdd ( const TString& strCmdName , const TMemBuf& mbufData , const tCIDLib::TCard4 c4DataBytes ); TIRBlasterCmd& irbcAddOrUpdate ( const TIRBlasterCmd& irbcToAdd , tCIDLib::TBoolean& bAdded ); const TIRBlasterCmd& irbcFromName ( const TString& strCmdName ) const; TIRBlasterCmd& irbcFromName ( const TString& strCmdName ); tCIDLib::TVoid LoadFromFile ( const TString& strSrcFile , const TString& strExpType , const tCIDLib::TBoolean bAllowDups ); tCIDLib::TVoid RemoveCmd ( const TString& strCmdName ); const TString& strDescription() const; const TString& strDescription ( const TString& strNew ); const TString& strMake() const; const TString& strMake ( const TString& strNew ); const TString& strModel() const; const TString& strModel ( const TString& strNew ); protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDLib::TVoid StreamFrom ( TBinInStream& strmToReadFrom ) final; tCIDLib::TVoid StreamTo ( TBinOutStream& strmToWriteTo ) const final; private : // ------------------------------------------------------------------- // Private, non-virtual mehods // ------------------------------------------------------------------- tCIDLib::TVoid Parse ( const TXMLTreeElement& xtnodeRoot , const tCIDLib::TBoolean bAllowDups ); // ------------------------------------------------------------------- // Private data members // // m_c4RepeatCount // The per-device model repeat count value. This is used by some // blasters to indicate how many times to repeat the command, // to make sure the device sees it. // // m_colCmdMap // A collection of rat commands, keyed on the command name, of // commands that are relevant to this device. // // m_eCategory // The device category of this device. This is just to allow users // to more easily locate particular types of devices. // // m_strDescr // The descriptive name of the command, which should be short and // to the point, usually 10 to 15 words. // // m_strMake // The make indentification of the device. This will be used for // sorting of the list of devices for selection by human. // // m_strModel // The model of the device. This is the key field, and it is case // sensitive. All model names must be unique. // ------------------------------------------------------------------- tCIDLib::TCard4 m_c4RepeatCount; TCmdMap m_colCmdMap; tCQCKit::EDevCats m_eCategory; TString m_strDescr; TString m_strMake; TString m_strModel; // ------------------------------------------------------------------- // Magic Macros // ------------------------------------------------------------------- RTTIDefs(TIRBlasterDevModel,TObject) }; #pragma CIDLIB_POPPACK
Esri/map-carousel-template
js/nls/resources.js
define({ root: ({ app: { title: "Map Carousel", errors: { noMaps: "This group does not contain any public web maps to display", noGroup: "Group not found", createGroup: "Unable to create group", bitly: 'bitly is used to shorten the url for sharing. View the readme file for details on creating and using a bitly key', general: "Error" }, mapcount: "Map ${page} of ${total}" } }), "ar": 1, "bs": 1, "cs": 1, "da": 1, "de": 1, "el": 1, "es": 1, "et": 1, "fi": 1, "fr": 1, "he": 1, "hi": 1, "hr": 1, "id": 1, "it": 1, "ja": 1, "ko": 1, "lt": 1, "lv": 1, "nl": 1, "nb": 1, "pl": 1, "pt-br": 1, "pt-pt": 1, "ro": 1, "ru": 1, "su": 1, "sr": 1, "sv": 1, "tr": 1, "th": 1, "vi": 1, "zh-cn": 1, "zh-hk": 1, "zh-tw": 1 });
cwl48/leetcode---go--
120/triangle.go
package minimumtotal /* * @lc app=leetcode.cn id=120 lang=golang * * [120] 三角形最小路径和 * * https://leetcode-cn.com/problems/triangle/description/ * * algorithms * Medium (55.18%) * Total Accepted: 6.6K * Total Submissions: 11.9K * Testcase Example: '[[2],[3,4],[6,5,7],[4,1,8,3]]' * * 给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。 * * 例如,给定三角形: * * [ * ⁠ [2], * ⁠ [3,4], * ⁠ [6,5,7], * ⁠ [4,1,8,3] * ] * * * 自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。 * * 说明: * * 如果你可以只使用 O(n) 的额外空间(n 为三角形的总行数)来解决这个问题,那么你的算法会很加分。 * */ func minimumTotal(triangle [][]int) int { m := len(triangle) // dp for i := m - 1; i >= 0; i-- { size := len(triangle[i]) for j := 0; j < size-1; j++ { triangle[i-1][j] += min(triangle[i][j], triangle[i][j+1]) } } return triangle[0][0] } func min(x int, y int) int { if x < y { return x } return y }
acHefei/anteater_hf
client/client-multi/client-java-core/src/main/java/org/kaaproject/kaa/client/persistence/KaaClientState.java
<gh_stars>1-10 /** * Copyright 2014-2016 CyberVision, Inc. * * 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.kaaproject.kaa.client.persistence; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Collection; import java.util.Map; import org.kaaproject.kaa.client.event.EndpointAccessToken; import org.kaaproject.kaa.client.event.EndpointKeyHash; import org.kaaproject.kaa.common.endpoint.gen.Topic; import org.kaaproject.kaa.common.hash.EndpointObjectHash; public interface KaaClientState { boolean isRegistered(); void setRegistered(boolean registered); PrivateKey getPrivateKey(); PublicKey getPublicKey(); EndpointKeyHash getEndpointKeyHash(); void setAppStateSeqNumber(int appStateSeqNumber); int getAppStateSeqNumber(); void setProfileHash(EndpointObjectHash hash); EndpointObjectHash getProfileHash(); void addTopic(Topic topic); void removeTopic(Long topicId); void addTopicSubscription(Long topicId); void removeTopicSubscription(Long topicId); boolean updateTopicSubscriptionInfo(Long topicId, Integer sequenceNumber); void setTopicListHash(Integer topicListHash); Integer getTopicListHash(); Map<Long, Integer> getNfSubscriptions(); Collection<Topic> getTopics(); void setAttachedEndpointsList(Map<EndpointAccessToken, EndpointKeyHash> attachedEndpoints); Map<EndpointAccessToken, EndpointKeyHash> getAttachedEndpointsList(); void setEndpointAccessToken(String token); String getEndpointAccessToken(); int getAndIncrementEventSeqNum(); int getEventSeqNum(); void setEventSeqNum(int newSeqNum); boolean isAttachedToUser(); void setAttachedToUser(boolean isAttached); boolean isConfigurationVersionUpdated(); void persist(); String refreshEndpointAccessToken(); void clean(); }
grondo/mvapich2-cce
src/mpi/group/group.h
/* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * (C) 2001 by Argonne National Laboratory. * See COPYRIGHT in top-level directory. */ /* MPIR_Group_create is needed by some of the routines that return groups from communicators, so it is in mpidimpl.h */ void MPIR_Group_setup_lpid_list( MPID_Group * ); int MPIR_Group_check_valid_ranks( MPID_Group *, int [], int ); int MPIR_Group_check_valid_ranges( MPID_Group *, int [][3], int ); void MPIR_Group_setup_lpid_pairs( MPID_Group *, MPID_Group * );
Kobrs/ncs
base/source/sim/DataBuffer.cpp
#include <ncs/sim/DataBuffer.h> namespace ncs { namespace sim { Mailbox::Mailbox() : failed(false) { } Publisher::Publisher() : device_(nullptr) { } Publisher::Subscription* Publisher::subscribe() { // Generate a subscription object Subscription* sub = new Subscription(this); // Make sure no one else is touching the subscription list std::unique_lock<std::mutex> lock(mutex_); // Add the subscription to the subscriber list subscriptions_.push_back(sub); // Return the newly generated object return sub; } void Publisher::unsubscribe(Publisher::Subscription* sub) { // Make sure on one else is touching the subscription list std::unique_lock<std::mutex> lock(mutex_); // Remove the subscription subscriptions_.remove(sub); } unsigned int Publisher::publish(DataBuffer* db) { // Make sure no one else is touching the subscriber list std::unique_lock<std::mutex> lock(mutex_); // This publication will be sent to all subscribers db->subscription_count += subscriptions_.size(); // Send the buffer out to all subscribers for (auto sub : subscriptions_) sub->push(db); // Return the number of subscribers we published to return subscriptions_.size(); } bool Publisher::clearSubscriptions() { // Make sure no one else is touching the subscriber list std::unique_lock<std::mutex> lock(mutex_); // Invalidate all subscribers for (auto sub : subscriptions_) { sub->invalidate(); } subscriptions_.clear(); return true; } bool Publisher::setDevice(DeviceBase* device) { device_ = device; return true; } DeviceBase* Publisher::getDevice() const { return device_; } Publisher::~Publisher() { } DataBuffer::Pin::Pin() : data_(nullptr), memory_type_(DeviceType::CPU) { } DataBuffer::Pin::Pin(const void* data, DeviceType::Type memory_type) : data_(data), memory_type_(memory_type) { } const void* DataBuffer::Pin::getData() const { return data_; } DeviceType::Type DataBuffer::Pin::getMemoryType() const { return memory_type_; } const DataBuffer::Pin& DataBuffer::getPin(const std::string& key) const { auto pt = pins_.find(key); if (pt == pins_.end()) { std::cerr << "Pin " << key << " does not exist" << std::endl; return null_pin_; } return pins_.find(key)->second; } void DataBuffer::release() { release_function(); } bool DataBuffer:: setPrereleaseFunction(std::function<void()> prerelease_function) { prerelease_function_ = prerelease_function; return true; } std::function<void()> DataBuffer::getPrereleaseFunction() const { return prerelease_function_; } std::mutex* DataBuffer::getWriteLock() { return &write_lock_; } } // namespace sim } // namespace ncs
Aarthas/android_json2view
sample/src/main/java/yiewdemo/SalesActivity.java
package yiewdemo; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.apkfuns.logutils.LogUtils; import com.arthas.xjsonview.XViewMain; import com.arthas.xjsonview.bean.XView; import com.arthas.xjsonview.bean.XViewBody; import com.lzy.okgo.OkGo; import com.lzy.okgo.callback.StringCallback; import java.util.Map; import okhttp3.Call; import okhttp3.Response; public class SalesActivity extends AppCompatActivity { private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = this; load(); } private void load() { OkGo.get("http://172.16.31.10:9999/sales.json") // 请求方式和请求url .execute(new StringCallback() { @Override public void onSuccess(String s, Call call, Response response) { XView yiew_1 = Util.gson.fromJson(s, XView.class); View aa = XViewMain.startProcess(context, yiew_1 ); setContentView(aa); } }); } public void refresh() { load(); } public void jumpToActivity(XViewBody yiew) { LogUtils.d("jumpToActivity"); Map data = yiew.data; LogUtils.d(data); Object name = data.get("route"); LogUtils.d(name); try { Class<?> aClass = Class.forName(name.toString()); startActivity(new Intent(context,aClass)); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
taxusyew/wrc
src/component/tabs/tab.js
<filename>src/component/tabs/tab.js import React from 'react'; import classNames from 'classnames'; import './style.less' export default class Tab extends React.Component { handleClick = (event) => { if (!this.props.disabled && this.props.onClick) { this.props.onClick(event); } }; componentDidMount() { // console.log('single tab, componentDidMount'); this.props.cb && this.props.cb(0); }; render () { console.log('single tab, render'); const {show , className, children, label, ...others} = this.props; const clsTab = classNames({ ['wrc-tab']: true, [className]: className }); return ( <label {...others} className={clsTab} onClick={this.handleClick}> {label} </label> ); } } Tab.propTypes = { show: React.PropTypes.bool, label: React.PropTypes.string, }; Tab.defaultProps = { show: false, label: 'tab' };
tahmid1234/Eidlandv2
app/src/main/java/com/eidland/auxilium/voice/only/helper/LeaderBoard.java
package com.eidland.auxilium.voice.only.helper; import android.os.Build; import com.eidland.auxilium.voice.only.model.Gift; import com.eidland.auxilium.voice.only.model.Leader; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import androidx.annotation.RequiresApi; public class LeaderBoard { static long time = 15 * 60000; List<String> uniqueContributor = new ArrayList<String>(); List<Leader> contributors = new ArrayList<Leader>(); List<String> uniqueWinner = new ArrayList<String>(); List<Leader> winners = new ArrayList<Leader>(); List<Gift> giftList = new ArrayList<Gift>(); public LeaderBoard(List<Gift> giftList, String roomId) { uniqueWinner.clear(); contributors.clear(); uniqueContributor.clear(); winners.clear(); this.giftList.clear(); for (Gift gift : giftList) { if ((gift.time + time) > System.currentTimeMillis()) { this.giftList.add(gift); if (!uniqueContributor.contains(gift.senderUID)) { uniqueContributor.add(gift.senderUID); contributors.add(new Leader(gift.senderName, gift.giftValue, gift.senderImg, gift.senderUID)); } else { for (Leader lead : contributors) { if (lead.uid.equals(gift.senderUID)) { lead.coins = lead.coins + gift.giftValue; } } } if (!gift.receiverUID.equals(roomId)) { if (!uniqueWinner.contains(gift.receiverUID)) { uniqueWinner.add(gift.receiverUID); winners.add(new Leader(gift.receiverName, gift.giftValue, gift.receiverImg, gift.receiverUID)); } else { for (Leader lead : winners) { if (lead.uid.equals(gift.receiverUID)) { lead.coins = lead.coins + gift.giftValue; } } } } } } } public List<Leader> getTopContributor() { Collections.sort(contributors, new Comparator<Leader>() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) public int compare(Leader obj1, Leader obj2) { return Long.compare(obj2.coins, obj1.coins); } }); return contributors; } public List<Leader> getTopSpeaker() { Collections.sort(winners, new Comparator<Leader>() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) public int compare(Leader obj1, Leader obj2) { return Long.compare(obj2.coins, obj1.coins); } }); return winners; } }
nowifi4u/Commando
src/types/string/baseString.js
<filename>src/types/string/baseString.js<gh_stars>1-10 const ArgumentType = require('../base'); module.exports = (name, strings = []) => { if(!Array.isArray(strings)) strings = [strings]; strings = strings.map(val => { if(typeof val !== 'string') throw new TypeError('Cannot pass non-string values'); return String(val).toLowerCase(); }); return class BaseDefaultStringArgumentType extends ArgumentType { constructor(client) { super(client, `string-${name}`); } validate(val) { const lower = val.toLowerCase(); return strings.includes(lower); } parse() { return name; } }; };
ceratic/VXA-OS
Client/Scripts/[VS] Sprite2.rb
#============================================================================== # ** Sprite #------------------------------------------------------------------------------ # Esta é a superclasse de alguns objetos gráficos. #------------------------------------------------------------------------------ # Autor: Valentine #============================================================================== class Bitmap alias vxaos_draw_text draw_text # Corrige a compressão de texto do RGD def draw_text(*args) if args[5] && args[5] == 1 args[2] += 20 args[0] -= 9 end vxaos_draw_text(*args) end end #============================================================================== # ** Sprite2 #============================================================================== class Sprite2 < Sprite attr_writer :dragable def initialize(viewport = nil) super(viewport) @dragable = false @dif_x = nil @dif_y = nil end def in_area?(x = 0, y = 0, w = self.bitmap.width, h = self.bitmap.height) Mouse.x >= self.x + x && Mouse.x <= self.x + x + w && Mouse.y >= self.y + y && Mouse.y <= self.y + y + h end def in_player_area?(x, y) x = (self.x + x) / 32 + $game_map.display_x y = (self.y + y) / 32 + $game_map.display_y $game_player.x >= x && $game_player.x <= x + self.bitmap.width / 32 && $game_player.y >= y && $game_player.y <= y + self.bitmap.height / 32 end def change_opacity(x = 0, y = 0) self.opacity = in_player_area?(x, y) ? 50 : 255 end def text_color(n) windowskin = Cache.system('Window') windowskin.get_pixel(64 + (n % 8) * 8, 96 + (n / 8) * 8) end def normal_color text_color(0) end def system_color text_color(16) end def crisis_color text_color(17) end def text_width(str) b = Bitmap.new(1, 1) wth = b.text_size(str).width b.dispose wth end def convert_gold(value) value.to_s.reverse.scan(/...|..|./).join('.').reverse end def update super update_dragging $dragging_window = Mouse.press?(:L) ? in_area? && !$dragging_window ? self : $dragging_window : nil end def update_dragging return unless @dragable return if $cursor.object if $dragging_window == self self.x = Mouse.x - @dif_x self.y = Mouse.y - @dif_y else @dif_x = Mouse.x - self.x @dif_y = Mouse.y - self.y end end end #============================================================================== # ** Color #============================================================================== class Color White = self.new(255, 255, 255) Black = self.new(0, 0, 0) Red = self.new(255, 120, 76) Green = self.new(0, 224, 96) Yellow = self.new(255, 255, 0) Blue = self.new(0, 162, 232) end
Duct-and-rice/KrswtkhrWiki4Android
app/src/main/java/org/wikipedia/feed/view/BigPictureCardView.java
package org.wikipedia.feed.view; import android.content.Context; import android.net.Uri; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.CardView; import android.view.View; import android.widget.TextView; import com.facebook.drawee.view.SimpleDraweeView; import org.wikipedia.R; import org.wikipedia.views.GoneIfEmptyTextView; import org.wikipedia.views.ViewUtil; import butterknife.BindView; import butterknife.ButterKnife; public class BigPictureCardView extends CardView { @BindView(R.id.view_big_picture_card_header) View headerView; @BindView(R.id.view_big_picture_card_footer) View footerView; @BindView(R.id.view_big_picture_card_image) SimpleDraweeView imageView; @BindView(R.id.view_big_picture_card_article_title) TextView articleTitleView; @BindView(R.id.view_big_picture_card_article_subtitle) GoneIfEmptyTextView articleSubtitleView; @BindView(R.id.view_big_picture_card_extract) TextView extractView; @BindView(R.id.view_big_picture_card_text_container) View textContainerView; public BigPictureCardView(@NonNull Context context) { super(context); inflate(getContext(), R.layout.view_big_picture_card, this); ButterKnife.bind(this); } protected void onClickListener(@Nullable OnClickListener listener) { textContainerView.setOnClickListener(listener); } protected void articleTitle(@NonNull String articleTitle) { articleTitleView.setText(articleTitle); } protected void articleSubtitle(@Nullable String articleSubtitle) { articleSubtitleView.setText(articleSubtitle); } protected void image(@Nullable Uri uri) { if (uri == null) { imageView.setVisibility(GONE); } else { imageView.setVisibility(VISIBLE); imageView.setImageURI(uri); } } protected void extract(@Nullable String extract) { extractView.setText(extract); } protected void header(@NonNull View view) { ViewUtil.replace(headerView, view); headerView = view; } protected void footer(@NonNull View view) { ViewUtil.replace(footerView, view); footerView = view; } }
hongframework/hamster
basic/src/main/java/com/hframework/hamster/cfg/service/interfaces/ICfgDatasourceSV.java
<reponame>hongframework/hamster<gh_stars>1-10 package com.hframework.hamster.cfg.service.interfaces; import java.util.*; import com.hframework.hamster.cfg.domain.model.CfgDatasource; import com.hframework.hamster.cfg.domain.model.CfgDatasource_Example; public interface ICfgDatasourceSV { /** * 创建数据源 * @param cfgDatasource * @return * @throws Exception */ public int create(CfgDatasource cfgDatasource) throws Exception; /** * 批量维护数据源 * @param cfgDatasources * @return * @throws Exception */ public int batchOperate(CfgDatasource[] cfgDatasources) throws Exception; /** * 更新数据源 * @param cfgDatasource * @return * @throws Exception */ public int update(CfgDatasource cfgDatasource) throws Exception; /** * 通过查询对象更新数据源 * @param cfgDatasource * @param example * @return * @throws Exception */ public int updateByExample(CfgDatasource cfgDatasource, CfgDatasource_Example example) throws Exception; /** * 删除数据源 * @param cfgDatasource * @return * @throws Exception */ public int delete(CfgDatasource cfgDatasource) throws Exception; /** * 删除数据源 * @param cfgDatasourceId * @return * @throws Exception */ public int delete(long cfgDatasourceId) throws Exception; /** * 查找所有数据源 * @return */ public List<CfgDatasource> getCfgDatasourceAll() throws Exception; /** * 通过数据源ID查询数据源 * @param cfgDatasourceId * @return * @throws Exception */ public CfgDatasource getCfgDatasourceByPK(long cfgDatasourceId) throws Exception; /** * 通过MAP参数查询数据源 * @param params * @return * @throws Exception */ public List<CfgDatasource> getCfgDatasourceListByParam(Map<String, Object> params) throws Exception; /** * 通过查询对象查询数据源 * @param example * @return * @throws Exception */ public List<CfgDatasource> getCfgDatasourceListByExample(CfgDatasource_Example example) throws Exception; /** * 通过MAP参数查询数据源数量 * @param params * @return * @throws Exception */ public int getCfgDatasourceCountByParam(Map<String, Object> params) throws Exception; /** * 通过查询对象查询数据源数量 * @param example * @return * @throws Exception */ public int getCfgDatasourceCountByExample(CfgDatasource_Example example) throws Exception; }
Mattlk13/rayo-server
rayo-storage/src/main/java/com/rayo/storage/riak/RiakPlatform.java
package com.rayo.storage.riak; import java.util.ArrayList; import java.util.Collection; import org.codehaus.jackson.annotate.JsonCreator; import org.codehaus.jackson.annotate.JsonProperty; import com.basho.riak.client.RiakLink; import com.basho.riak.client.convert.RiakKey; import com.basho.riak.client.convert.RiakLinks; public class RiakPlatform { @RiakKey private String name; @JsonProperty private String description; @RiakLinks private transient Collection<RiakLink> nodeLinks; @JsonCreator public RiakPlatform(@JsonProperty("name") String name) { this.name = name; this.description = name; nodeLinks = new ArrayList<RiakLink>(); } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void addNode(String hostname) { nodeLinks.add(new RiakLink("nodes", hostname, "nodes")); } public void removeNode(String hostname) { nodeLinks.remove(new RiakLink("nodes", hostname, "nodes")); } public Collection<RiakLink> getNodeLinks() { return nodeLinks; } public void setNodeLinks(Collection<RiakLink> nodeLinks) { this.nodeLinks = nodeLinks; } }
phanmduong/test
public/angularjs/group/directives/TopicItem.js
angular.module('groupApp') .directive('topicItem', function (__env) { var templateUrl = __env.baseUrl + "/angularjs/group/templates/directives/topicItem.html"; return { restrict: "E", templateUrl: templateUrl, scope: { topic: "=" }, controller: function ($scope, TopicData) { $scope.vote = function (value) { $scope.topic.voted = value; $scope.topic.vote = $scope.topic.vote + value; TopicData.vote($scope.topic.id, value).then( function (res) { $scope.topic.voted = value; }, function (err) { console.log(err); }); }; }, link: function (scope, el, attrs) { scope.totalStudents = __env.totalStudents; scope.showDes = false; scope.toggleDescription = function () { scope.showDes = !scope.showDes; }; } } });