identifier
stringlengths
42
383
collection
stringclasses
1 value
open_type
stringclasses
1 value
license
stringlengths
0
1.81k
date
float64
1.99k
2.02k
title
stringlengths
0
100
creator
stringlengths
1
39
language
stringclasses
157 values
language_type
stringclasses
2 values
word_count
int64
1
20k
token_count
int64
4
1.32M
text
stringlengths
5
1.53M
__index_level_0__
int64
0
57.5k
https://github.com/sancssss/Business-Information-Management-System/blob/master/views/city-admin/index.php
Github Open Source
Open Source
BSD-3-Clause
null
Business-Information-Management-System
sancssss
PHP
Code
86
502
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model app\models\YiiUser */ $this->title = "市级管理员中心"; $this->params['breadcrumbs'][] = $this->title; ?> <div class="county-admin-view"> <div class="row"> <div class="col-lg-3 col-md-3"> <?= $this->render('@app/views/layouts/admin_user/city_admin_left_menu') ?> </div> <div class="col-lg-9 col-md-9"> <div class="panel panel-default"> <div class="panel-heading"><span class="glyphicon glyphicon-user"></span> <?= Html::encode($this->title) ?></div> <div class="panel-body"> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'adminUserDetails.user_nickname', 'adminUserDetails.user_sex', 'adminUserDetails.user_phone_number', 'adminUserDetails.user_email', 'adminUserDetails.user_birthday', 'adminUserDetails.user_id_number', 'adminUserDetails.user_address', 'adminUserDetails.user_zip_code', 'adminUserDetails.user_legal_person', 'adminUserDetails.user_type', 'adminUserDetails.user_comment', 'adminUserDetails.region.region_id', 'adminUserDetails.region.region_name', 'identityStatus', ], ]) ?> <p> <?= Html::a('更新资料', ['/city-admin/update-user'], ['class'=>'btn btn-success']) ?> </p> </div> </div> </div> </div> </div>
39,249
https://github.com/taylorm7/HeaviNet/blob/master/batch_generate.sh
Github Open Source
Open Source
MIT
null
HeaviNet
taylorm7
Shell
Code
90
351
#!/bin/bash # At most XX minute of time #PBS -l walltime=80:00:00 # One core on any number of nodes #PBS -l procs=1,gpus=2 #newriver cluster #PBS -W group_list=newriver # queue #PBS -q p100_normal_q #PBS -A CASLAB_18_A # write output and error to the same file #PBS -j oe # Email when your job starts, completes, or aborts #PBS -M taylorm7@vt.edu #PBS -m ea module purge module load gcc/5.2.0 cuda/8.0.61 export PATH=$PATH:/home/taylorm7/opt_py35/bin export PYTHONUSERBASE=/home/taylorm7/opt_py35/newriver/python export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/taylorm7/cuda/lib64/ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/taylorm7/opt/lib/ dot=$PBS_O_WORKDIR cd $dot pwd export dot=$dot ./run_heavinet.sh generate beethoven_7.wav bach_10.wav 1 echo "Code finished!"
5,089
https://github.com/DavidBoddu1/sql-soccer-database-Examples/blob/master/Basic Queries Qustions/5.sql
Github Open Source
Open Source
Unlicense
null
sql-soccer-database-Examples
DavidBoddu1
SQL
Code
30
65
USE SOCCER_DB GO -- 5. Write a query in SQL to find the number of matches -- ended with draws. -- (match_mast) SELECT COUNT(results) FROM match_mast WHERE results = 'DRAW';
20,838
https://github.com/jpsingleton/reactube/blob/master/src/Reactube.NET/Views/Home/Index.cshtml
Github Open Source
Open Source
MIT
null
reactube
jpsingleton
C#
Code
19
167
@section scripts{ @Html.React("TubeStatus", new { initialData = Model }) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.1/react-dom.min.js"></script> <script src="@Url.Content("~/js/moment.min.js")"></script> <script src="@Url.Content("~/js/reactube.jsx")"></script> @Html.ReactInitJavaScript() }
18,904
https://github.com/JLLeitschuh/vid/blob/master/vid-app-common/src/main/java/org/onap/vid/aai/model/AaiGetNetworkCollectionDetails/AaiGetRelatedInstanceGroupsByVnfId.java
Github Open Source
Open Source
Apache-2.0
2,021
vid
JLLeitschuh
Java
Code
435
1,606
/*- * ============LICENSE_START======================================================= * VID * ================================================================================ * Copyright (C) 2017 - 2019 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= */ package org.onap.vid.aai.model.AaiGetNetworkCollectionDetails; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class AaiGetRelatedInstanceGroupsByVnfId { @JsonProperty("vnf-id") private String vnfId; @JsonProperty("vnf-name") private String vnfName; @JsonProperty("vnf-type") private String vnfType; @JsonProperty("prov-status") private String provStatus; @JsonProperty("operational-status") private String operationalStatus; @JsonProperty("equipment-role") private String equipmentRole; @JsonProperty("in-maint") private Boolean inMaint; @JsonProperty("is-closed-loop-disabled") private Boolean isClosedLoopDisabled; @JsonProperty("resource-version") private String resourceVersion; @JsonProperty("model-invariant-id") private String modelInvariantId; @JsonProperty("model-version-id") private String modelVersionId; @JsonProperty("model-customization-id") private String modelCustomizationId; @JsonProperty("selflink") private String selflink; @JsonProperty("relationship-list") private RelationshipList relationshipList; @JsonProperty("vnf-id") public String getVnfId() { return vnfId; } @JsonProperty("vnf-id") public void setVnfId(String vnfId) { this.vnfId = vnfId; } @JsonProperty("vnf-name") public String getVnfName() { return vnfName; } @JsonProperty("vnf-name") public void setVnfName(String vnfName) { this.vnfName = vnfName; } @JsonProperty("vnf-type") public String getVnfType() { return vnfType; } @JsonProperty("vnf-type") public void setVnfType(String vnfType) { this.vnfType = vnfType; } @JsonProperty("prov-status") public String getProvStatus() { return provStatus; } @JsonProperty("prov-status") public void setProvStatus(String provStatus) { this.provStatus = provStatus; } @JsonProperty("operational-status") public String getOperationalStatus() { return operationalStatus; } @JsonProperty("operational-status") public void setOperationalStatus(String operationalStatus) { this.operationalStatus = operationalStatus; } @JsonProperty("equipment-role") public String getEquipmentRole() { return equipmentRole; } @JsonProperty("equipment-role") public void setEquipmentRole(String equipmentRole) { this.equipmentRole = equipmentRole; } @JsonProperty("in-maint") public Boolean getInMaint() { return inMaint; } @JsonProperty("in-maint") public void setInMaint(Boolean inMaint) { this.inMaint = inMaint; } @JsonProperty("is-closed-loop-disabled") public Boolean getIsClosedLoopDisabled() { return isClosedLoopDisabled; } @JsonProperty("is-closed-loop-disabled") public void setIsClosedLoopDisabled(Boolean isClosedLoopDisabled) { this.isClosedLoopDisabled = isClosedLoopDisabled; } @JsonProperty("resource-version") public String getResourceVersion() { return resourceVersion; } @JsonProperty("resource-version") public void setResourceVersion(String resourceVersion) { this.resourceVersion = resourceVersion; } @JsonProperty("model-invariant-id") public String getModelInvariantId() { return modelInvariantId; } @JsonProperty("model-invariant-id") public void setModelInvariantId(String modelInvariantId) { this.modelInvariantId = modelInvariantId; } @JsonProperty("model-version-id") public String getModelVersionId() { return modelVersionId; } @JsonProperty("model-version-id") public void setModelVersionId(String modelVersionId) { this.modelVersionId = modelVersionId; } @JsonProperty("model-customization-id") public String getModelCustomizationId() { return modelCustomizationId; } @JsonProperty("model-customization-id") public void setModelCustomizationId(String modelCustomizationId) { this.modelCustomizationId = modelCustomizationId; } @JsonProperty("selflink") public String getSelflink() { return selflink; } @JsonProperty("selflink") public void setSelflink(String selflink) { this.selflink = selflink; } @JsonProperty("relationship-list") public RelationshipList getRelationshipList() { return relationshipList; } @JsonProperty("relationship-list") public void setRelationshipList(RelationshipList relationshipList) { this.relationshipList = relationshipList; } }
27,504
https://github.com/Geant-RnD/geant/blob/master/physics/electromagnetic/models/src/ELossTableRegister.cc
Github Open Source
Open Source
ECL-2.0, Apache-2.0
2,018
geant
Geant-RnD
C++
Code
60
257
#include "Geant/ELossTableRegister.h" namespace geantphysics { ELossTableRegister &ELossTableRegister::Instance() { static ELossTableRegister instance; return instance; } void ELossTableRegister::RegisterEnergyLossProcessForParticle(int internalpartindx, EMPhysicsProcess *elossprocess) { unsigned long ipartindx = internalpartindx; if (fELossProcessesPerParticle.size() < ipartindx + 1) { fELossProcessesPerParticle.resize(ipartindx + 1); } fELossProcessesPerParticle[ipartindx].push_back(elossprocess); } void ELossTableRegister::Clear() { for (unsigned long i = 0; i < fELossProcessesPerParticle.size(); ++i) { fELossProcessesPerParticle[i].clear(); } fELossProcessesPerParticle.clear(); } } // namespace geantphysics
1,944
https://github.com/andang72/architecture-community-core/blob/master/src/main/java/architecture/community/streams/DefaultStreamThread.java
Github Open Source
Open Source
Apache-2.0
2,021
architecture-community-core
andang72
Java
Code
388
1,536
package architecture.community.streams; import java.util.Date; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.lang3.StringUtils; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import architecture.community.model.Models; import architecture.community.model.PropertyModelObjectAwareSupport; import architecture.community.model.json.JsonDateSerializer; import architecture.community.streams.model.json.JsonStreamMessageDeserializer; import architecture.community.util.CommunityContextHelper; public class DefaultStreamThread extends PropertyModelObjectAwareSupport implements StreamThread { private long threadId; private Date creationDate; private Date modifiedDate; private StreamMessage latestMessage; private StreamMessage rootMessage; private AtomicInteger messageCount = new AtomicInteger(-1); public DefaultStreamThread() { super(UNKNOWN_OBJECT_TYPE, UNKNOWN_OBJECT_ID); this.threadId = UNKNOWN_OBJECT_ID; this.rootMessage = null; this.latestMessage = null; this.messageCount = new AtomicInteger(-1); } public DefaultStreamThread(long threadId) { super(UNKNOWN_OBJECT_TYPE, UNKNOWN_OBJECT_ID); this.threadId = threadId; this.rootMessage = null; this.latestMessage = null; this.messageCount = new AtomicInteger(-1); } public DefaultStreamThread(int objectType, long objectId, StreamMessage rootMessage) { super(objectType, objectId); this.threadId = -1L; this.rootMessage = rootMessage; this.latestMessage = null; boolean isNew = rootMessage.getThreadId() < 1L; if (isNew) { this.creationDate = rootMessage.getCreationDate(); this.modifiedDate = this.creationDate; } this.messageCount = new AtomicInteger(-1); } public void setMessageCount(int messageCount) { this.messageCount.set(messageCount); } public int getViewCount() { if (threadId < 1) return -1; return CommunityContextHelper.getViewCountServive().getViewCount(Models.STREAMS_THREAD.getObjectType(), threadId); } public int getMessageCount() { int count = messageCount.get(); if (count <= 0) return 1; else return count; } public void incrementMessageCount() { if (messageCount.get() < 0) messageCount.set(1); else messageCount.incrementAndGet(); } public void decrementMessageCount() { if (messageCount.get() > 0) messageCount.decrementAndGet(); } public long getThreadId() { return threadId; } public void setThreadId(long threadId) { this.threadId = threadId; } @JsonSerialize(using = JsonDateSerializer.class) public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } @JsonSerialize(using = JsonDateSerializer.class) public Date getModifiedDate() { return modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } public StreamMessage getLatestMessage() { return latestMessage; } @JsonDeserialize(using = JsonStreamMessageDeserializer.class) public void setLatestMessage(StreamMessage latestMessage) { this.latestMessage = latestMessage; } public StreamMessage getRootMessage() { return rootMessage; } @JsonDeserialize(using = JsonStreamMessageDeserializer.class) public void setRootMessage(StreamMessage rootMessage) { this.rootMessage = rootMessage; } private String coverImgSrc = null; public String getCoverImgSrc() { if(this.coverImgSrc == null && this.rootMessage != null && StringUtils.isNotEmpty(rootMessage.getBody())) { Document doc = Jsoup.parse(this.rootMessage.getBody()); Elements eles = doc.select("img"); String src = null; for( Element ele : eles ) { coverImgSrc = ele.attr("src"); break; } } return coverImgSrc; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("BoardThread [threadId=").append(threadId).append(", objectType=").append(getObjectType()) .append(", objectId=").append(getObjectId()).append(", "); if (creationDate != null) builder.append("creationDate=").append(creationDate).append(", "); if (modifiedDate != null) builder.append("modifiedDate=").append(modifiedDate).append(", "); if (latestMessage != null) builder.append("latestMessage=").append(latestMessage).append(", "); if (rootMessage != null) builder.append("rootMessage=").append(rootMessage).append(", "); if (messageCount != null) builder.append("messageCount=").append(messageCount); builder.append("]"); return builder.toString(); } }
23,566
https://github.com/Roboy/ss18_xylophone_recording/blob/master/Assets/ROSBridge/Scripts/Wrapper/ROSObject.cs
Github Open Source
Open Source
BSD-3-Clause
2,018
ss18_xylophone_recording
Roboy
C#
Code
82
193
using ROSBridge; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace ROSBridge { /// <summary> /// All ROSObjects tell the ROSBridge to add them when they are enabled and to remove them when they are disabled from the connection. /// </summary> public class ROSObject : MonoBehaviour { private void OnEnable() { ROSBridge.Instance.AddROSActor(this); } private void OnDisable() { // we need the check as ROSBridge is a singleton and we destroy it if the application is quitting. if (ROSBridge.Instance != null) ROSBridge.Instance.RemoveROSActor(this); } } }
18,534
https://github.com/ndueber/quiz_maker/blob/master/src/components/Repos/__tests__/Repos.spec.js
Github Open Source
Open Source
MIT
null
quiz_maker
ndueber
JavaScript
Code
186
720
/* eslint-disable no-unused-expressions, react/prop-types */ import { expect } from 'chai'; import React from 'react'; import { shallow } from 'enzyme'; import Repos from '../Repos'; import DisplayInfosPanel from '../../common/DisplayInfosPanel'; import DisplayStars from '../../common/DisplayStars'; function noop() {} describe('components/ProfileBox', () => { describe('state/render', () => { it('should render a placeholder if props.repositories.data not hydrated', () => { const mockRepositories = { fetching: false, pristineLogin: 'topheman' }; const wrapper = shallow(<Repos repositories={mockRepositories} reposGotoPage={noop} />); expect(wrapper.equals(<DisplayInfosPanel infos={mockRepositories} originalTitle="topheman's repositories"/>)).to.be.true; }); describe('check render for list of repositories', () => { const mockRepositories = { fetching: false, infos: {}, pristineLogin: 'topheman', data: [ { html_url: 'https://github.com/topheman/react-es6-redux', name: 'react-es6-redux', stargazers_count: 57, full_name: 'topheman/react-es6-redux' }, { html_url: 'https://github.com/topheman/webpack-babel-starter', name: 'webpack-babel-starter', stargazers_count: 39, full_name: 'topheman/webpack-babel-starter' }, { html_url: 'https://github.com/topheman/rxjs-experiments', name: 'rxjs-experiments', stargazers_count: 19, full_name: 'topheman/rxjs-experiments' } ] }; const wrapper = shallow(<Repos repositories={mockRepositories} reposGotoPage={noop} />); it('should render the correct amount of links to repos', () => { expect(wrapper.find('a').length).to.equal(3); }); it('should render links properly', () => { const anchor = wrapper.find('a').at(1); expect(anchor.prop('href')).to.equal('https://github.com/topheman/webpack-babel-starter'); expect(anchor.prop('title')).to.equal('topheman/webpack-babel-starter'); }); it('should render stargazer properly', () => { const displayStars = wrapper.find(DisplayStars).at(1); expect(displayStars.prop('number')).to.equal(39); }); }); describe('check paginators', () => { }); }); });
15,709
https://github.com/ronsaldo/sysmel-beta/blob/master/include/sysmel/Environment/ASTTrapNode.hpp
Github Open Source
Open Source
MIT
2,021
sysmel-beta
ronsaldo
C++
Code
93
275
#ifndef SYSMEL_ENVIRONMENT_AST_TRAP_NODE_HPP #define SYSMEL_ENVIRONMENT_AST_TRAP_NODE_HPP #pragma once #include "ASTNode.hpp" #include "TrapReason.hpp" namespace Sysmel { namespace Environment { /** * I am used for generating a runtime error. I might be compiled to throwing an exception, or aborting the program execution. */ class SYSMEL_COMPILER_LIB_EXPORT ASTTrapNode : public SubtypeOf<ASTNode, ASTTrapNode> { public: static constexpr char const __typeName__[] = "ASTTrapNode"; virtual bool isASTTrapNode() const override; virtual AnyValuePtr accept(const ASTVisitorPtr &visitor) override; virtual SExpression asSExpression() const override; TrapReason reason = TrapReason::Generic; std::string reasonMessage; }; } // End of namespace Environment } // End of namespace Sysmel #endif //SYSMEL_ENVIRONMENT_AST_TRAP_NODE_HPP
33,091
https://github.com/JetBrains/intellij-community/blob/master/python/testData/quickdoc/NumPyOnesDoc/numpy/core/numeric.py
Github Open Source
Open Source
Apache-2.0
2,023
intellij-community
JetBrains
Python
Code
143
385
from . import multiarray __all__ = ['ndarray', 'ones'] ndarray = multiarray.ndarray def ones(shape, dtype=None, order='C'): """ **Test docstring** Return a new array of given shape and type, filled with ones. Parameters ---------- shape : int or sequence of ints Shape of the new array, e.g., ``(2, 3)`` or ``2``. dtype : data-type, optional The desired data-type for the array, e.g., `numpy.int8`. Default is `numpy.float64`. order : {'C', 'F'}, optional Whether to store multidimensional data in C- or Fortran-contiguous (row- or column-wise) order in memory. Returns ------- out : ndarray Array of ones with the given shape, dtype, and order. See Also -------- zeros, ones_like Examples -------- >>> np.ones(5) array([ 1., 1., 1., 1., 1.]) >>> np.ones((5,), dtype=np.int) array([1, 1, 1, 1, 1]) >>> np.ones((2, 1)) array([[ 1.], [ 1.]]) >>> s = (2,2) >>> np.ones(s) array([[ 1., 1.], [ 1., 1.]]) """ pass
31,798
https://github.com/ParthMmm/albus/blob/master/components/Artist/TrendingArtists.js
Github Open Source
Open Source
MIT
2,021
albus
ParthMmm
JavaScript
Code
127
427
import React from "react"; import useSWR from "swr"; import { chartTopArtists } from "../../utils/fetch"; import Artist from "./Artist"; import { Box, Grid, Skeleton, Heading, Text } from "@chakra-ui/react"; import fetcher from "../../utils/fetcher"; import { useQuery } from "react-query"; import { fetchTopArtists } from "../../utils/queries/fetchTop"; function TrendingArtists() { // const { data, error, isValidating } = useSWR(chartTopArtists, fetcher); const { data, error, isLoading } = useQuery("chartTopArtists", () => fetchTopArtists() ); if (data) { return ( <> <Box mb={4}> <Heading>trending artists</Heading> <Text>this week</Text> </Box> <Grid gridTemplateColumns={[ "repeat(2, 1fr)", "repeat(2, 1fr)", "repeat(5, 1fr)", ]} gap={3} > {data.artists.artist.map((artist) => ( <Artist key={artist.url} artist={artist} /> ))} </Grid> </> ); } if (error || isLoading) { return ( <Box> <Skeleton startColor="orange.500" endColor="purple.500" height="25rem" /> </Box> ); } return null; } export default TrendingArtists;
35,074
https://github.com/DamianKursa/Remote-Norey/blob/master/src/styles/variables/breakpoints.sass
Github Open Source
Open Source
MIT
null
Remote-Norey
DamianKursa
Sass
Code
8
27
$small: 567px $medium: 768px $big: 992px $large: 1200px
40,323
https://github.com/ardamavi/labirent-oyunu/blob/master/Assets/Bölümler/Oyun/LightingData.asset.meta
Github Open Source
Open Source
Apache-2.0
2,016
labirent-oyunu
ardamavi
Unity3D Asset
Code
12
63
fileFormatVersion: 2 guid: 79b64dbec123c491092ae248d76e450b timeCreated: 1460994384 licenseType: Free NativeFormatImporter: userData: assetBundleName: assetBundleVariant:
47,296
https://github.com/wxiaofei/Li-MVPArms/blob/master/arms/src/main/java/com/jess/arms/utils/DateUtil.java
Github Open Source
Open Source
Apache-2.0
2,017
Li-MVPArms
wxiaofei
Java
Code
700
2,349
package com.jess.arms.utils; import android.content.Context; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateUtil { // yyyy-MM-dd hh:mm:ss 12小时制 // yyyy-MM-dd HH:mm:ss 24小时制 public static final String TYPE_01 = "yyyy-MM-dd HH:mm:ss"; public static final String TYPE_02 = "yyyy-MM-dd"; public static final String TYPE_03 = "HH:mm:ss"; public static final String TYPE_04 = "yyyy年MM月dd日"; public static final String TYPE_05 = "yyyy-MM-dd HH:mm"; public static final String TYPE_06 = "yyyy.MM.dd"; /** * 根据指定的格式格式话 毫秒数 * * @param time * @param pattern * @return 格式化后的String */ public static String formatDate(long time, String pattern) { if (time == 0) return "- -"; Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time); return new SimpleDateFormat(pattern).format(cal.getTime()); } public static String formatDate(String longStr, String pattern) { if (StringUtils.isEmpty(longStr)) return "- -"; try { return formatDate(Long.parseLong(longStr), pattern); } catch (Exception e) { e.printStackTrace(); } return "- -"; } public static String formatDate2Hnt(String longStr, String pattern) { try { return formatDate(Long.parseLong(longStr), pattern); } catch (Exception e) { } return "- -"; } public static long formatStr(String timeStr, String pattern) { SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { return sdf.parse(timeStr).getTime(); } catch (ParseException e) { e.printStackTrace(); } return 0; } /** * 转换long型日期格式 * * @param context * @param date * @return */ public static String formateDateNow(Context context, long date) { int format_flags = android.text.format.DateUtils.FORMAT_NO_NOON_MIDNIGHT | android.text.format.DateUtils.FORMAT_ABBREV_ALL | android.text.format.DateUtils.FORMAT_CAP_AMPM | android.text.format.DateUtils.FORMAT_SHOW_DATE | android.text.format.DateUtils.FORMAT_SHOW_DATE | android.text.format.DateUtils.FORMAT_SHOW_TIME; return android.text.format.DateUtils.formatDateTime(context, date, format_flags); } /** * 获取当前的时间 * * @param context * @return */ public static String getTime(Context context) { return formateDateNow(context, System.currentTimeMillis()); } /** * 以友好的方式显示时间 * * @param sdate * @return */ public static String friendlyTime(String sdate) { String timeStr; try { if (StringUtils.isEmpty(sdate)) return ""; Date date = toDate(sdate); if (date == null) { return ""; } Calendar cal = Calendar.getInstance(); // 判断是否是同一天 String curDate = dateFormater.get().format(cal.getTime()); String paramDate = dateFormater.get().format(date); if (curDate.equals(paramDate)) { int hour = (int) ((cal.getTimeInMillis() - date.getTime()) / 3600000); if (hour == 0) timeStr = Math.max((cal.getTimeInMillis() - date.getTime()) / 60000, 1) + "分钟前"; else timeStr = hour + "小时前"; return timeStr; } long lt = date.getTime() / 86400000; long ct = cal.getTimeInMillis() / 86400000; int days = (int) (ct - lt); if (days == 0 || days == 1) { int hour = (int) ((cal.getTimeInMillis() - date.getTime()) / 3600000); if (hour == 0) timeStr = Math.max((cal.getTimeInMillis() - date.getTime()) / 60000, 1) + "分钟前"; else timeStr = hour + "小时前"; } else { timeStr = formatDate(date.getTime(), TYPE_02); } } catch (Exception e) { e.printStackTrace(); timeStr = ""; } return timeStr; } /** * 比较两个时间的前后顺序 * @param firstDate 第一时间 * @param secondDate 第二时间 * @return true 代表第一个时间晚于第二个时间 */ public static boolean isEarly(String firstDate,String secondDate) { Date date = toDate(firstDate); Date sdate = toDate(secondDate); if (sdate != null&& date != null) { // LogUtils.e("date.getTime()="+date.getTime()+"****sdate.getTime()="+sdate.getTime()); if(date.getTime() - sdate.getTime() >0){ return true; }else{ return false; } }else{ return false; } } /** * 将字符串转位日期类型 * * @param sdate * @return */ public static Date toDate(String sdate) { try { return dateFormater.get().parse(sdate); } catch (Exception e) { e.printStackTrace(); return null; } } private final static ThreadLocal<SimpleDateFormat> dateFormater = new ThreadLocal<SimpleDateFormat>() { @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); } }; public static String changeYmd(String strYmd) { if (strYmd == null) { return " "; } else { strYmd = strYmd.replace("-", ""); return strYmd.substring(0, 4) + "年" + strYmd.substring(4, 6) + "月"; } } /** * @param timestr * @return */ public static String getFormatDate(String timestr) { if (timestr != null) { int index = timestr.indexOf(" "); if (index > 0) { return timestr.substring(0, index); } else { return timestr; } } else { return ""; } } /** * 获取年-月并去掉“-”的数字字符串 * * @param date * @return */ public static long changeStringDateToLong(String date) { date = date.substring(0, 7); String tmp = date.replace("-", ""); //LogUtils.i(tmp); return Long.parseLong(tmp); } /** * 日期格式字符串转换成时间戳 * * @param dateStr 字符串日期 * @param format 如:yyyy-MM-dd HH:mm:ss * @return */ public static long date2TimeStamp(String dateStr, String format) { try { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.parse(dateStr).getTime() / 1000; } catch (Exception e) { e.printStackTrace(); } return 0; } /** * 当前时间是否已经过了该时间 * * @param time 指定的时间 单位毫秒 * @return */ public static boolean isExpired(long time) { if (time == 0) return false; long currentTime = System.currentTimeMillis(); return currentTime > time; } }
4,601
https://github.com/MelvinG24/dust3d/blob/master/thirdparty/cgal/CGAL-5.1/include/CGAL/Alpha_shape_3.h
Github Open Source
Open Source
GPL-3.0-only, LGPL-2.1-or-later, LicenseRef-scancode-proprietary-license, GPL-1.0-or-later, LGPL-2.0-or-later, MIT, LicenseRef-scancode-free-unknown, LicenseRef-scancode-unknown-license-reference, MIT-0, LGPL-3.0-only, LGPL-3.0-or-later
2,021
dust3d
MelvinG24
C++
Code
5,837
19,805
// Copyright (c) 1997, 2012 INRIA Sophia-Antipolis (France). // All rights reserved. // // This file is part of CGAL (www.cgal.org). // // $URL: https://github.com/CGAL/cgal/blob/v5.1/Alpha_shapes_3/include/CGAL/Alpha_shape_3.h $ // $Id: Alpha_shape_3.h 0779373 2020-03-26T13:31:46+01:00 Sébastien Loriot // SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial // // Author(s) : Tran Kai Frank DA <Frank.Da@sophia.inria.fr> // Andreas Fabri <Andreas.Fabri@geometryfactory.com> // Mariette Yvinec <Mariette.Yvinec@sophia.inria.fr> #ifndef CGAL_ALPHA_SHAPE_3_H #define CGAL_ALPHA_SHAPE_3_H #include <CGAL/license/Alpha_shapes_3.h> #include <CGAL/internal/Lazy_alpha_nt_3.h> #include <CGAL/Alpha_shape_cell_base_3.h> // for Alpha_status #include <CGAL/basic.h> #include <CGAL/Compact_container.h> #include <CGAL/iterator.h> #include <CGAL/Object.h> #include <CGAL/Unique_hash_map.h> #ifdef CGAL_USE_GEOMVIEW #include <CGAL/IO/Geomview_stream.h> // TBC #endif #include <CGAL/Triangulation_utils_3.h> #include <boost/type_traits/is_same.hpp> #include <algorithm> #include <iostream> #include <map> #include <list> #include <set> #include <utility> #include <vector> //------------------------------------------------------------------- namespace CGAL { //------------------------------------------------------------------- template < class Dt, class ExactAlphaComparisonTag = Tag_false > class Alpha_shape_3 : public Dt { // DEFINITION The class Alpha_shape_3<Dt> represents the family // of alpha-shapes for a set of points (or a set of weighted points) // for all possible values of alpha. The alphashape is defined through // the Delaunay tetrahedralization of the points // (or the Regular tetrahedralization in case of weighted points) // and depends on the value of a parameter called alpha. // The alpha_shape is the domain of a subcomplex of this triangulation // called the Alpha_complex. The alpha_complex includes any simplex // having a circumscribing sphere (an orthogonal sphere // in case of weighted points) empty of other points // (or suborthogonal to other sites in case of weighted points) // with squared radius equal or less than alpha // The alpha_shapes comes in two versions : GENERAL or REGULARIZED // where the REGULARIZED version is onbtaining by restricting the // alpha complex ti is pure 3D component. // The cells of the triangulation are classified as INTERIOR // or EXTERIOR according to the value alpha_cell of their circumsphere // squared radius compared to alpha. // In GENERAL mode each k-dimensional simplex of the triangulation // for (k=0,1,2) // can be classified as EXTERIOR, SINGULAR, REGULAR // or INTERIOR with respect to the alpha shape. // In GENERAL mode a $k$ simplex is REGULAR if it is on the boundary // of the alpha_complex and belongs to a $k+1$ simplex in the complex // and it is SINGULAR simplex if it is a boundary simplex tht is not // included in a $k+1$ simplex of the complex. // In REGULARIZED mode each k-dimensional simplex of the triangulation // for (k=0,1,2) // can be classified as EXTERIOR, REGULAR // or INTERIOR with respect to the alpha shape. // A $k$ simplex is REGULAR if it is on the boundary of alpha complex // and belong to a tetrahedral cell of the complex. // Roughly, the Alpha_shapes data structure computes and stores, // for each simplex // the at most three critical value (alpha_min, alpha_mid and alpha_max) // which compared to the actual alpha value // determine the classification of the simplex. //------------------------- TYPES ------------------------------------ public: typedef Dt Triangulation; typedef typename Dt::Geom_traits Gt; typedef typename Dt::Triangulation_data_structure Tds; // The Exact Comparison Tag cannot be used in conjonction with periodic triangulations // because the periodic triangulations' point() function returns a temporary // value while the lazy predicate evaluations that are used when the Exact tag // is set to true rely on a permanent and safe access to the points. CGAL_static_assertion( (boost::is_same<ExactAlphaComparisonTag, Tag_false>::value) || (boost::is_same<typename Dt::Periodic_tag, Tag_false>::value)); //extra the type used for representing alpha according to ExactAlphaComparisonTag typedef typename internal::Alpha_nt_selector_3<Gt,ExactAlphaComparisonTag,typename Dt::Weighted_tag>::Type_of_alpha NT; typedef typename internal::Alpha_nt_selector_3<Gt,ExactAlphaComparisonTag,typename Dt::Weighted_tag>::Compute_squared_radius_3 Compute_squared_radius_3; typedef NT FT; typedef typename Gt::FT Coord_type; //checks whether tags are correctly set in Vertex and Cell classes CGAL_static_assertion( (boost::is_same<NT,typename Dt::Cell::NT>::value) ); CGAL_static_assertion( (boost::is_same<NT,typename Dt::Vertex::Alpha_status::NT>::value) ); typedef typename Dt::Point Point; typedef typename Dt::Cell_handle Cell_handle; typedef typename Dt::Vertex_handle Vertex_handle; typedef typename Dt::Facet Facet; typedef typename Dt::Edge Edge; typedef typename Dt::Cell_circulator Cell_circulator; typedef typename Dt::Facet_circulator Facet_circulator; typedef typename Dt::Cell_iterator Cell_iterator; typedef typename Dt::Facet_iterator Facet_iterator; typedef typename Dt::Edge_iterator Edge_iterator; typedef typename Dt::Vertex_iterator Vertex_iterator; typedef typename Dt::Finite_cells_iterator Finite_cells_iterator; typedef typename Dt::Finite_facets_iterator Finite_facets_iterator; typedef typename Dt::Finite_edges_iterator Finite_edges_iterator; typedef typename Dt::Finite_vertices_iterator Finite_vertices_iterator; typedef typename Dt::size_type size_type; typedef typename Dt::Locate_type Locate_type; typedef typename Dt::Weighted_tag Weighted_tag; using Dt::dimension; using Dt::finite_facets_begin; using Dt::finite_facets_end; using Dt::finite_edges_begin; using Dt::finite_edges_end; using Dt::finite_vertices_begin; using Dt::finite_vertices_end; using Dt::finite_cells_begin; using Dt::finite_cells_end; using Dt::vertex_triple_index; using Dt::is_infinite; using Dt::is_Gabriel; using Dt::incident_cells; using Dt::incident_vertices; using Dt::incident_facets; using Dt::locate; using Dt::point; using Dt::VERTEX; using Dt::EDGE; using Dt::FACET; using Dt::CELL; using Dt::OUTSIDE_CONVEX_HULL; using Dt::OUTSIDE_AFFINE_HULL; enum Classification_type {EXTERIOR, SINGULAR, REGULAR, INTERIOR}; enum Mode {GENERAL, REGULARIZED}; typedef CGAL::Alpha_status< NT > Alpha_status; typedef Compact_container<Alpha_status> Alpha_status_container; typedef typename Alpha_status_container::const_iterator Alpha_status_const_iterator; typedef typename Alpha_status_container::iterator Alpha_status_iterator; typedef std::vector< NT > Alpha_spectrum; typedef std::multimap< NT, Cell_handle > Alpha_cell_map; typedef std::multimap< NT, Facet> Alpha_facet_map; typedef std::multimap< NT, Edge > Alpha_edge_map; typedef std::multimap< NT, Vertex_handle> Alpha_vertex_map; typedef std::pair<Vertex_handle, Vertex_handle> Vertex_handle_pair; typedef std::map<Vertex_handle_pair,Alpha_status_iterator> Edge_alpha_map; typedef typename std::list< Vertex_handle >::iterator Alpha_shape_vertices_iterator; typedef typename std::list< Facet >::iterator Alpha_shape_facets_iterator; //test if a cell is exterior to the alphashape class Exterior_cell_test{ const Alpha_shape_3 * _as; public: Exterior_cell_test() {} Exterior_cell_test(const Alpha_shape_3 * as) {_as = as;} bool operator() ( const Finite_cells_iterator& fci) const { return _as->classify(fci) == EXTERIOR ; } }; typedef Filter_iterator< Finite_cells_iterator, Exterior_cell_test> Alpha_shape_cells_iterator; typedef typename Alpha_spectrum::const_iterator Alpha_iterator; // An iterator that allow to traverse the sorted sequence of // different alpha-values. The iterator is bidirectional and // non-mutable. Its value-type is NT private: typedef Unique_hash_map<Cell_handle, bool > Marked_cell_set; private: NT _alpha; NT _alpha_solid; Mode _mode; mutable bool use_vertex_cache; mutable bool use_facet_cache; // only finite facets and simplices are inserted into the maps Alpha_cell_map alpha_cell_map; Alpha_facet_map alpha_min_facet_map; Alpha_edge_map alpha_min_edge_map; Alpha_vertex_map alpha_min_vertex_map; Alpha_spectrum alpha_spectrum; Alpha_status_container alpha_status_container; Edge_alpha_map edge_alpha_map; //deprecated - for backward compatibility mutable std::list< Vertex_handle > alpha_shape_vertices_list; mutable std::list< Facet > alpha_shape_facets_list; //------------------------- CONSTRUCTORS ------------------------------ public: // Introduces an empty alpha-shape `A' for a // alpha-value `alpha'. Alpha_shape_3(NT alpha = 0, Mode m = REGULARIZED) : _alpha(alpha), _mode(m), use_vertex_cache(false), use_facet_cache(false) {} Alpha_shape_3(Dt& dt, NT alpha = 0, Mode m = REGULARIZED) :_alpha(alpha), _mode(m), use_vertex_cache(false), use_facet_cache(false) { Dt::swap(dt); if (dimension() == 3) initialize_alpha(); } // Introduces an alpha-shape `A' for the alpha-value // `alpha' that is initialized with the points in the range // from first to last template < class InputIterator > Alpha_shape_3(const InputIterator& first, const InputIterator& last, const NT& alpha = 0, Mode m = REGULARIZED) : _alpha(alpha), _mode(m), use_vertex_cache(false), use_facet_cache(false) { Dt::insert(first, last); if (dimension() == 3) initialize_alpha(); } public: //----------------------- OPERATIONS --------------------------------- template < class InputIterator > std::ptrdiff_t make_alpha_shape(const InputIterator& first, const InputIterator& last) { clear(); size_type n = Dt::insert(first, last); if (dimension() == 3){ initialize_alpha(); } return n; } // Introduces an alpha-shape `A' // that is initialized with the points in the range // from first to last private : //--------------------- INITIALIZATION OF PRIVATE MEMBERS ----------- // called with reinitialize=false on first initialization // reinitialize=true when switching the mode. void initialize_alpha_cell_map(); void initialize_alpha_facet_maps(bool reinitialize = false); void initialize_alpha_edge_maps(bool reinitialize = false); void initialize_alpha_vertex_maps(bool reinitialize = false); void initialize_alpha_spectrum(); void initialize_alpha(bool reinitialize = false) { if (reinitialize == false) initialize_alpha_cell_map(); initialize_alpha_facet_maps(reinitialize); initialize_alpha_edge_maps(reinitialize); initialize_alpha_vertex_maps(reinitialize); initialize_alpha_spectrum(); } private : Vertex_handle_pair make_vertex_handle_pair( Vertex_handle v1, Vertex_handle v2) const { return v1 < v2 ? std::make_pair(v1,v2) : std::make_pair(v2,v1); } Vertex_handle_pair make_vertex_handle_pair(const Edge& e) const { return make_vertex_handle_pair(e.first->vertex(e.second), e.first->vertex(e.third)); } // the version to be used with Tag_true is templated to avoid // instanciation through explicit instantiation of the whole class void set_alpha_min_of_vertices(Tag_false) { for( Finite_vertices_iterator vit = finite_vertices_begin(); vit != finite_vertices_end(); ++vit){ Alpha_status* as = vit->get_alpha_status(); as->set_is_Gabriel(true); as->set_alpha_min(NT(0)); } // insert a single vertex into the map because they all have the // same alpha_min value alpha_min_vertex_map.insert(typename Alpha_vertex_map::value_type ( NT(0), finite_vertices_begin())); } template <class Tag> void set_alpha_min_of_vertices(Tag) { for( Finite_vertices_iterator vit = finite_vertices_begin(); vit != finite_vertices_end(); ++vit) { if (is_Gabriel(vit)) { Alpha_status* as = vit->get_alpha_status(); as->set_is_Gabriel(true); as->set_alpha_min(squared_radius(vit)); alpha_min_vertex_map.insert(typename Alpha_vertex_map::value_type (as->alpha_min(),vit)); } } return; } //--------------------------------------------------------------------- public: void clear() { // clears the structure alpha_status_container.clear(); Dt::clear(); alpha_cell_map.clear(); alpha_min_facet_map.clear(); alpha_min_edge_map.clear(); alpha_min_vertex_map.clear(); alpha_spectrum.clear(); alpha_shape_vertices_list.clear(); alpha_shape_facets_list.clear(); use_vertex_cache = false; use_facet_cache = false; } //--------------------------------------------------------------------- public: NT set_alpha(const NT& alpha) // Sets the alpha-value to `alpha'. Precondition: `alpha' >= 0. // Returns the previous alpha { NT previous_alpha = _alpha; _alpha = alpha; use_vertex_cache = false; use_facet_cache = false; return previous_alpha; } const NT& get_alpha() const // Returns the current alpha-value. { return _alpha; } const NT& get_nth_alpha(int n) const // Returns the n-th alpha-value. // n < size() { CGAL_triangulation_assertion( n > 0 && n <= static_cast<int>(alpha_spectrum.size()) ); return alpha_spectrum[n-1]; } size_type number_of_alphas() const // Returns the number of different alpha-values { return alpha_spectrum.size(); } const Edge_alpha_map* get_edge_alpha_map() const { return &edge_alpha_map; } //--------------------------------------------------------------------- private: // the dynamic version is not yet implemented // desactivate the tetrahedralization member functions void insert(const Point& /*p*/) {} // Inserts point `p' in the alpha shape and returns the // corresponding vertex of the underlying Delaunay tetrahedralization. // If point `p' coincides with an already existing vertex, this // vertex is returned and the alpha shape remains unchanged. // Otherwise, the vertex is inserted in the underlying Delaunay // tetrahedralization and the associated intervals are updated. void remove(Vertex_handle /*v*/) {} // Removes the vertex from the underlying Delaunay tetrahedralization. // The created hole is retriangulated and the associated intervals // are updated. //--------------------------------------------------------------------- public: Mode set_mode(Mode mode = REGULARIZED ) // Sets `A' to its general or regularized version. Returns the // previous mode. { Mode previous_mode = _mode; _mode = mode; if (previous_mode != _mode) { initialize_alpha(true); use_vertex_cache = false; use_facet_cache = false; } return previous_mode; } Mode get_mode() const // Returns whether `A' is general or regularized. { return _mode; } //--------------------------------------------------------------------- private: void update_alpha_shape_vertex_list() const; void update_alpha_shape_facet_list() const; //--------------------------------------------------------------------- public: Alpha_shape_vertices_iterator alpha_shape_vertices_begin() const { if(!use_vertex_cache) update_alpha_shape_vertex_list(); return alpha_shape_vertices_list.begin(); } Alpha_shape_vertices_iterator Alpha_shape_vertices_begin() const { return alpha_shape_vertices_begin(); } //--------------------------------------------------------------------- Alpha_shape_vertices_iterator alpha_shape_vertices_end() const { return alpha_shape_vertices_list.end(); } Alpha_shape_vertices_iterator Alpha_shape_vertices_end() const { return alpha_shape_vertices_end(); } //--------------------------------------------------------------------- Alpha_shape_facets_iterator alpha_shape_facets_begin() const { if(! use_facet_cache) update_alpha_shape_facet_list(); return alpha_shape_facets_list.begin(); } Alpha_shape_facets_iterator Alpha_shape_facets_begin() const { return alpha_shape_facets_begin(); } //--------------------------------------------------------------------- Alpha_shape_facets_iterator alpha_shape_facets_end() const { return alpha_shape_facets_list.end(); } Alpha_shape_facets_iterator Alpha_shape_facets_end() const { return alpha_shape_facets_end(); } Alpha_shape_cells_iterator alpha_shape_cells_begin() const { return CGAL::filter_iterator(finite_cells_end(), Exterior_cell_test(this), finite_cells_begin()); } Alpha_shape_cells_iterator alpha_shape_cells_end() const { return CGAL::filter_iterator(finite_cells_end(), Exterior_cell_test(this)); } public: // Traversal of the alpha-Values // // The alpha shape class defines an iterator that allows to // visit the sorted sequence of alpha-values. This iterator is // non-mutable and bidirectional. Its value type is NT. Alpha_iterator alpha_begin() const { return alpha_spectrum.begin(); } Alpha_iterator alpha_end() const {return alpha_spectrum.end();} Alpha_iterator alpha_find(const NT& alpha) const // Returns an iterator pointing to an element with alpha-value // `alpha', or the corresponding past-the-end iterator if such an // element is not found. { return std::find(alpha_spectrum.begin(), alpha_spectrum.end(), alpha); } Alpha_iterator alpha_lower_bound(const NT& alpha) const // Returns an iterator pointing to the first element with // alpha-value not less than `alpha'. { return std::lower_bound(alpha_spectrum.begin(), alpha_spectrum.end(), alpha); } Alpha_iterator alpha_upper_bound(const NT& alpha) const // Returns an iterator pointing to the first element with // alpha-value greater than `alpha'. { return std::upper_bound(alpha_spectrum.begin(), alpha_spectrum.end(), alpha); } //--------------------- PREDICATES ----------------------------------- public: void compute_edge_status( const Cell_handle& c, int i, int j, Alpha_status& as) const; Classification_type classify(const Alpha_status& as, const NT& alpha) const; Classification_type classify(const Alpha_status* as, const NT& alpha) const; Classification_type classify(const Alpha_status_const_iterator as, const NT& alpha) const; public: Classification_type classify(const Point& p) const { return classify(p, get_alpha()); } Classification_type classify(const Point& p, const NT& alpha) const // Classifies a point `p' with respect to `A'. { Locate_type type; int i, j; Cell_handle pCell = locate(p, type, i, j); switch (type) { case VERTEX : return classify(pCell->vertex(i), alpha); case EDGE : return classify(pCell, i, j, alpha); case FACET : return classify(pCell, i, alpha); case CELL : return classify(pCell, alpha); case OUTSIDE_CONVEX_HULL : return EXTERIOR; case OUTSIDE_AFFINE_HULL : return EXTERIOR; default : return EXTERIOR; }; } //--------------------------------------------------------------------- Classification_type classify(const Cell_handle& s) const // Classifies the cell `f' of the underlying Delaunay // tetrahedralization with respect to `A'. { return classify(s, get_alpha()); } Classification_type classify(const Cell_handle& s, const NT& alpha) const // Classifies the cell `f' of the underlying Delaunay // tetrahedralization with respect to `A'. // s->radius == alpha => f interior { if (is_infinite(s)) return EXTERIOR; return (s->get_alpha() <= alpha) ? INTERIOR : EXTERIOR; } //--------------------------------------------------------------------- Classification_type classify(const Facet& f) const { return classify(f.first, f.second, get_alpha()); } Classification_type classify(const Cell_handle& s, int i) const { return classify(s, i, get_alpha()); } Classification_type classify(const Facet& f, const NT& alpha) const { return classify(f.first, f.second, alpha); } Classification_type classify(const Cell_handle& s, int i, const NT& alpha) const; // Classifies the face `f' of the underlying Delaunay // tetrahedralization with respect to `A'. //--------------------------------------------------------------------- Classification_type classify(const Edge& e) const { return classify(e.first, e.second, e.third, get_alpha()); } Classification_type classify(const Cell_handle& s, int i, int j) const { return classify(s, i, j, get_alpha()); } Classification_type classify(const Edge& e, const NT& alpha ) const { return classify(e.first, e.second, e.third, alpha); } Classification_type classify(const Cell_handle& s, int i, int j, const NT& alpha) const; // Classifies the edge `e' of the underlying Delaunay // tetrahedralization with respect to `A'. //--------------------------------------------------------------------- Classification_type classify(const Vertex_handle& v) const { return classify(v, get_alpha()); } Classification_type classify(const Vertex_handle& v, const NT& alpha) const; // Classifies the vertex `v' of the underlying Delaunay // tetrahedralization with respect to `A'. //--------------------- NB COMPONENTS --------------------------------- size_type number_solid_components() const { return number_of_solid_components(get_alpha()); } size_type number_of_solid_components() const { return number_of_solid_components(get_alpha()); } size_type number_solid_components(const NT& alpha) const { return number_of_solid_components(alpha); } size_type number_of_solid_components(const NT& alpha) const; // Determine the number of connected solid components // takes time O(#alpha_shape) amortized if STL_HASH_TABLES // O(#alpha_shape log n) otherwise private: void traverse(Cell_handle pCell, Marked_cell_set& marked_cell_set, const NT alpha) const; //---------------------------------------------------------------------- public: Alpha_iterator find_optimal_alpha(size_type nb_components) const; // find the minimum alpha that satisfies the properties // (1) all data points are on the boundary of some 3d component // or in its interior // (2) the nb of solid components is equal or less than nb_component NT find_alpha_solid() const; // compute the minumum alpha such that all data points // are either on the boundary or in the interior // not necessarily connected // starting point for searching // takes O(#alpha_shape) time //------------------- GEOMETRIC PRIMITIVES ---------------------------- private: NT squared_radius(const Cell_handle& s) const { return Compute_squared_radius_3()(*this)(point(s,0), point(s,1), point(s,2), point(s,3)); } NT squared_radius(const Cell_handle& s, const int& i) const { return Compute_squared_radius_3()(*this)(point(s,vertex_triple_index(i,0)), point(s,vertex_triple_index(i,1)), point(s,vertex_triple_index(i,2))); } NT squared_radius(const Facet& f) const { return squared_radius(f.first, f.second); } NT squared_radius(const Cell_handle& s, const int& i, const int& j) const { return Compute_squared_radius_3()(*this)(point(s,i), point(s,j)); } NT squared_radius(const Edge& e) const { return squared_radius(e.first,e.second,e.third); } NT squared_radius(const Vertex_handle& v) const { return Compute_squared_radius_3()(*this)(v->point()); } //--------------------------------------------------------------------- private: // prevent default copy constructor and default assigment Alpha_shape_3(const Alpha_shape_3&); void operator=(const Alpha_shape_3&); //--------------------------------------------------------------------- public: #ifdef CGAL_USE_GEOMVIEW void show_triangulation_edges(Geomview_stream &gv) const; void show_alpha_shape_faces(Geomview_stream &gv) const; #endif // to Debug void print_maps() const; void print_alphas() const; void print_alpha_status( const Alpha_status& as) const; // To extract the alpha_shape faces for a given alpha value template<class OutputIterator> OutputIterator get_alpha_shape_cells(OutputIterator it, Classification_type type, const NT& alpha) const { Finite_cells_iterator cit = finite_cells_begin(); for( ; cit != finite_cells_end() ; ++cit){ if (classify(cit, alpha) == type) *it++ = Cell_handle(cit); } return it; } template<class OutputIterator> OutputIterator get_alpha_shape_facets(OutputIterator it, Classification_type type, const NT& alpha) const { Finite_facets_iterator fit = finite_facets_begin(); for( ; fit != finite_facets_end() ; ++fit){ if (classify(*fit, alpha) == type) *it++ = *fit; } return it; } template<class OutputIterator> OutputIterator get_alpha_shape_edges(OutputIterator it, Classification_type type, const NT& alpha) const { Finite_edges_iterator eit = finite_edges_begin(); for( ; eit != finite_edges_end() ; ++eit){ if (classify(*eit, alpha) == type) *it++ = *eit; } return it; } template<class OutputIterator> OutputIterator get_alpha_shape_vertices(OutputIterator it, Classification_type type, const NT& alpha) const { Finite_vertices_iterator vit = finite_vertices_begin(); for( ; vit != finite_vertices_end() ; ++vit){ if (classify(vit, alpha) == type) *it++ = Vertex_handle(vit); } return it; } Alpha_status get_alpha_status(const Edge& e) const { return *edge_alpha_map.find(make_vertex_handle_pair(e))->second; } Alpha_status get_alpha_status(const Facet& f) const { return *(f.first->get_facet_status(f.second)); } template<class OutputIterator> OutputIterator get_alpha_shape_cells(OutputIterator it, Classification_type type) const { return get_alpha_shape_cells(it, type, get_alpha());} template<class OutputIterator> OutputIterator get_alpha_shape_facets(OutputIterator it, Classification_type type) const { return get_alpha_shape_facets(it, type, get_alpha());} template<class OutputIterator> OutputIterator get_alpha_shape_edges(OutputIterator it, Classification_type type) const { return get_alpha_shape_edges(it, type, get_alpha());} template<class OutputIterator> OutputIterator get_alpha_shape_vertices(OutputIterator it, Classification_type type) const { return get_alpha_shape_vertices(it, type, get_alpha());} template<class OutputIterator> OutputIterator filtration_with_alpha_values(OutputIterator it) const // scan the alpha_cell_map, alpha_min_facet_map, alpha_min_edge_map // and alpha_min_vertex in GENERAL mode // only alpha_cell_map in REGULARIZED mode // and output all the faces in order of alpha value of their appearing // in the alpha complexe { typename Alpha_cell_map::const_iterator cit ; typename Alpha_facet_map::const_iterator fit ; typename Alpha_edge_map::const_iterator eit ; typename Alpha_vertex_map::const_iterator vit; if (get_mode() == GENERAL) { cit = alpha_cell_map.begin(); fit = alpha_min_facet_map.begin(); eit = alpha_min_edge_map.begin(); vit = alpha_min_vertex_map.begin(); } else { //mode==REGULARIZED do not scan maps of Gabriel elements cit = alpha_cell_map.begin(); fit = alpha_min_facet_map.end(); eit = alpha_min_edge_map.end(); vit = alpha_min_vertex_map.end(); } // sets to avoid multiple output of the same face // as a regular subfaces of different faces std::set<Facet> facet_set; std::set<Vertex_handle_pair> edge_set; std::set<Vertex_handle> vertex_set; NT alpha_current = 0; while (cit != alpha_cell_map.end()) { if ( vit != alpha_min_vertex_map.end() && (eit == alpha_min_edge_map.end() || (vit->first <= eit->first)) && (fit == alpha_min_facet_map.end()|| (vit->first <= fit->first)) && (cit == alpha_cell_map.end() || (vit->first <= cit->first))) { //advance on vit filtration_set_management(vit, alpha_current, facet_set, edge_set, vertex_set); filtration_output(vit->first, vit->second, it); vit++; } if ( eit != alpha_min_edge_map.end() && ( fit == alpha_min_facet_map.end() || (eit->first <= fit->first) ) && ( cit == alpha_cell_map.end() || (eit->first <= cit->first) ) && ( vit == alpha_min_vertex_map.end()|| (vit->first > eit->first) ) ) { //advance on eit filtration_set_management(eit, alpha_current, facet_set, edge_set, vertex_set); filtration_output(eit->first, eit->second, it, vertex_set); eit++; } if ( fit != alpha_min_facet_map.end() && (cit == alpha_cell_map.end() || (fit->first <= cit->first)) && (eit == alpha_min_edge_map.end() || (eit->first > fit->first)) && (vit == alpha_min_vertex_map.end()|| (vit->first > fit->first)) ) { //advance on fit filtration_set_management(fit, alpha_current, facet_set, edge_set, vertex_set); filtration_output(fit->first, fit->second, it, edge_set, vertex_set); fit++; } if ( cit != alpha_cell_map.end() && (fit == alpha_min_facet_map.end() || (fit->first > cit->first) ) && (eit == alpha_min_edge_map.end() || (eit->first > cit->first) ) && (vit == alpha_min_vertex_map.end()|| (vit->first > cit->first) ) ) { //advance on cit filtration_set_management(cit, alpha_current, facet_set, edge_set, vertex_set); filtration_output(cit->first, cit->second, it, facet_set, edge_set, vertex_set); cit++; } } return it; } template<class OutputIterator> OutputIterator filtration(OutputIterator it) const { Dispatch_or_drop_output_iterator<std::tuple<CGAL::Object>, std::tuple<OutputIterator> > out(it); return std::template get<0>( filtration_with_alpha_values(out) ); } private: template<class Alpha_face_iterator> void filtration_set_management ( Alpha_face_iterator afit, NT& alpha_current, std::set<Facet>& facet_set, std::set<Vertex_handle_pair>& edge_set, std::set<Vertex_handle>& vertex_set) const { if (afit->first != alpha_current) { //new alpha_value alpha_current = afit->first; facet_set.clear(); edge_set.clear(); vertex_set.clear(); } return; } template<class OutputIterator> OutputIterator filtration_output( const NT & alpha, Vertex_handle vh, OutputIterator it, Tag_true) const { *it++ = make_object(vh); *it++ = alpha; //std::cerr << "filtration " << alpha << " \t VERTEX " << std::endl; return it; } template<class OutputIterator> OutputIterator filtration_output( const NT& alpha, Vertex_handle vh, OutputIterator it, Tag_false) const { // when Delaunay, the alpha_min_vertex_map contains a single vertex // because all vertices are Gabriel with the same alpha_min=0 // this affects only the GENERAL mode if (get_mode() == GENERAL){ Finite_vertices_iterator vit=finite_vertices_begin(); for( ; vit != finite_vertices_end(); vit++) { *it++ = make_object( Vertex_handle(vit)); *it++ = alpha; } } else { *it++ = make_object(vh); *it++ = alpha; } //std::cerr << "filtration " << alpha << " \t VERTEX " << std::endl; return it; } template<class OutputIterator> OutputIterator filtration_output( const NT& alpha, Vertex_handle vh, OutputIterator it) const { return filtration_output(alpha, vh, it, Weighted_tag()); } template<class OutputIterator> OutputIterator filtration_output( const NT& alpha, Edge e, OutputIterator it, std::set<Vertex_handle>& vertex_set) const { Vertex_handle vh[] = {e.first->vertex(e.second), e.first->vertex(e.third)}; for(int i=0; i<2; i++) { Alpha_status* as = vh[i]->get_alpha_status(); if ( (get_mode()== REGULARIZED || !as->is_Gabriel()) && as->alpha_mid() == alpha && vertex_set.find(vh[i]) == vertex_set.end() ) { filtration_output( alpha, vh[i], it); vertex_set.insert(vh[i]); } } *it++ = make_object(e); *it++ = alpha; //std::cerr << "filtration " << alpha << " \t EDGE " << std::endl; return it; } template<class OutputIterator> OutputIterator filtration_output( const NT& alpha, Facet f, OutputIterator it, std::set<Vertex_handle_pair>& edge_set, std::set<Vertex_handle>& vertex_set ) const { Cell_handle c = f.first; int facet_index = f.second; for(int k=0; k<3; k++) { int i = vertex_triple_index(facet_index, k ); int j = vertex_triple_index(facet_index, this->ccw(k)); Alpha_status as; Vertex_handle_pair vhp = make_vertex_handle_pair(c->vertex(i),c->vertex(j)); if (get_mode() == GENERAL) { as = *(edge_alpha_map.find(vhp)->second); } else{ //no edge map in REGULARIZED mode - classify on the fly compute_edge_status( c, i, j, as); } if ( (get_mode()== REGULARIZED || !as.is_Gabriel()) && as.alpha_mid() == alpha && edge_set.find(vhp)== edge_set.end() ) { filtration_output( alpha, make_triple(c,i,j), it, vertex_set); edge_set.insert(vhp); } } *it++ = make_object(f); *it++ = alpha; //std::cerr << "filtration " << alpha << " \t FACET " << std::endl; return it; } template<class OutputIterator> OutputIterator filtration_output( const NT& alpha, Cell_handle c, OutputIterator it, std::set<Facet>& facet_set, std::set<Vertex_handle_pair>& edge_set, std::set<Vertex_handle>& vertex_set) const { for(int i=0; i<4; i++) { Alpha_status_iterator as = c->get_facet_status(i); Facet f = std::make_pair(c,i); if ((get_mode()== REGULARIZED || !as->is_Gabriel()) && as->alpha_mid() == alpha && facet_set.find(f) == facet_set.end() && facet_set.find(std::make_pair(c->neighbor(i), this->mirror_index(c, i))) == facet_set.end()) { filtration_output( alpha, f, it, edge_set, vertex_set); facet_set.insert(f); } } *it++ = make_object(c); *it++ = alpha; //std::cerr << "filtration " << alpha << " \t CELL " << std::endl; return it; } }; //--------------------------------------------------------------------- //--------------------- MEMBER FUNCTIONS------------------------------- //--------------------------------------------------------------------- //--------------------- INITIALIZATION OF PRIVATE MEMBERS ------------- template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>::initialize_alpha_cell_map() { Finite_cells_iterator cell_it, done = finite_cells_end(); NT alpha ; for( cell_it = finite_cells_begin(); cell_it != done; ++cell_it) { alpha = squared_radius(cell_it); alpha_cell_map.insert(typename Alpha_cell_map::value_type(alpha, cell_it)); // cross references cell_it->set_alpha(alpha); } return; } //--------------------------------------------------------------------- template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>::initialize_alpha_facet_maps(bool reinitialize) { Finite_facets_iterator fit; Cell_handle pCell, pNeighbor ; int i, iNeigh; Alpha_status_iterator as; if (!reinitialize) { NT alpha_max, alpha_mid; for( fit = finite_facets_begin(); fit != finite_facets_end(); ++fit) { as = alpha_status_container.insert(Alpha_status()); pCell = fit->first; i = fit->second; pNeighbor = pCell->neighbor(i); iNeigh = pNeighbor->index(pCell); // not on the convex hull if(!is_infinite(pCell) && !is_infinite(pNeighbor)) { NT alpha_Cell = pCell->get_alpha(); NT alpha_Neighbor = pNeighbor->get_alpha(); if ( alpha_Cell < alpha_Neighbor) { alpha_mid = alpha_Cell; alpha_max = alpha_Neighbor; } else { alpha_mid = alpha_Neighbor; alpha_max = alpha_Cell; } as->set_is_on_chull(false); as->set_alpha_mid(alpha_mid); as->set_alpha_max(alpha_max); // alpha_mid_facet_map.insert(typename // Alpha_facet_map::value_type(alpha_mid, *fit)); } else { // on the convex hull alpha_mid = !is_infinite(pCell) ? pCell->get_alpha() : pNeighbor->get_alpha(); as->set_alpha_mid(alpha_mid); as->set_is_on_chull(true); } //cross links pCell->set_facet_status(i, as); pNeighbor->set_facet_status(iNeigh,as); } } // initialize alpha_min if mode GENERAL if(get_mode() == GENERAL && alpha_min_facet_map.empty()) { //already done if !alpha_min_facet_map.empty() NT alpha_min; for( fit = finite_facets_begin(); fit != finite_facets_end(); ++fit) { as = fit->first->get_facet_status(fit->second); if (is_Gabriel(*fit)) { as->set_is_Gabriel(true); alpha_min = squared_radius(*fit); as->set_alpha_min(alpha_min); alpha_min_facet_map.insert(typename Alpha_facet_map::value_type(alpha_min, *fit)); } else{ as->set_is_Gabriel(false); as->set_alpha_min(as->alpha_mid()); } } } return; } template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>::initialize_alpha_edge_maps(bool ) { // alpha_status for edges, edge_alpha_map // and alpha_mid_edge and alpha_min_edge // are initialized only in GENERAL mode if(get_mode() == REGULARIZED) {return;} //no_edge_map in REGULARIZED mode if ( !edge_alpha_map.empty()) return; // already done Finite_edges_iterator eit; Alpha_status_iterator as; for (eit = finite_edges_begin(); eit != finite_edges_end(); ++eit) { as = alpha_status_container.insert(Alpha_status()); compute_edge_status(eit->first, eit->second, eit->third, *as); if ( as->is_Gabriel()) { alpha_min_edge_map.insert(typename Alpha_edge_map::value_type(as->alpha_min(), *eit)); } //cross links Vertex_handle_pair vhp = make_vertex_handle_pair( eit->first->vertex(eit->second), eit->first->vertex(eit->third)); edge_alpha_map.insert(std::make_pair(vhp, as)); } return; } template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>::initialize_alpha_vertex_maps(bool reinitialize) { //for a vertex // alpha_max = max of alpha values of incident cells // alpha_mid = min of alpha values of incident cells in REGULAR mode // = min of alpha values of incidents faces in GENERAL mode // alpha_min = -squared_radius of weighted point, // if the vertex is Gabriel set only in GENERAL mode NT alpha, alpha_mid; Finite_vertices_iterator vit; if (reinitialize == false) _alpha_solid = alpha_cell_map.begin()->first; for( vit = finite_vertices_begin(); vit != finite_vertices_end(); ++vit) { Alpha_status* as = vit->get_alpha_status(); if (reinitialize == false) { // set is_on_chull, compute alpha_max // and alpha_mid (version REGULAR) // compute _alpha_solid (max of alpha_mid of vertices in REGULAR mode) as->set_is_on_chull(false); std::list<Cell_handle> incidents; incident_cells(static_cast<Vertex_handle>(vit), back_inserter(incidents)); typename std::list<Cell_handle>::iterator chit=incidents.begin(); if (is_infinite(*chit)) as->set_is_on_chull(true); while (is_infinite(*chit)) ++chit; //skip infinte cells alpha = (*chit)->get_alpha(); as->set_alpha_mid(alpha); as->set_alpha_max(alpha); ++chit; for( ; chit != incidents.end(); ++chit) { if (is_infinite(*chit)) as->set_is_on_chull(true); else { alpha = (*chit)->get_alpha(); if (alpha < as->alpha_mid()) as->set_alpha_mid(alpha); if (alpha > as->alpha_max()) as->set_alpha_max(alpha); } } if (as->alpha_mid() > _alpha_solid) _alpha_solid = as->alpha_mid(); } if (get_mode() == GENERAL) { //reset alpha_mid, set alph_min std::list<Vertex_handle> incidentv; incident_vertices(static_cast<Vertex_handle>(vit), back_inserter(incidentv)); typename std::list<Vertex_handle>::iterator vvit=incidentv.begin(); for( ; vvit != incidentv.end(); ++vvit) { if (!is_infinite(*vvit)) { Vertex_handle_pair vhp = make_vertex_handle_pair( *vvit, vit); Alpha_status_iterator asedge = edge_alpha_map[vhp]; alpha_mid = asedge->is_Gabriel() ? asedge->alpha_min() : asedge->alpha_mid(); if ( alpha_mid < as->alpha_mid()) as->set_alpha_mid(alpha_mid); } } } if (get_mode()== REGULARIZED && reinitialize == true) { // reset alpha_mid std::list<Cell_handle> incidents; incident_cells(static_cast<Vertex_handle>(vit), back_inserter(incidents)); typename std::list<Cell_handle>::iterator chit=incidents.begin(); while (is_infinite(*chit)) ++chit; //skip infinte cells alpha = (*chit)->get_alpha(); as->set_alpha_mid(alpha); for( ; chit != incidents.end(); ++chit) { if (is_infinite(*chit)) as->set_is_on_chull(true); else { alpha = (*chit)->get_alpha(); if (alpha < as->alpha_mid()) as->set_alpha_mid(alpha); } } } } // set alpha_min in case GENERAL if (get_mode() == GENERAL && alpha_min_vertex_map.empty()) { set_alpha_min_of_vertices(Weighted_tag()); } return; } //--------------------------------------------------------------------- template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>::initialize_alpha_spectrum() // merges the alpha values of alpha_cell_map // and alpha_min_facet_map alpha_min_edge_map alpha_min_vertex in GENERAL mode // only alpha_cell_map in REGULARIZED mode { typename Alpha_cell_map::iterator cit ; typename Alpha_facet_map::iterator fit ; typename Alpha_edge_map::iterator eit ; typename Alpha_vertex_map::iterator vit; alpha_spectrum.clear(); if (get_mode() == GENERAL) { cit = alpha_cell_map.begin(); fit = alpha_min_facet_map.begin(); eit = alpha_min_edge_map.begin(); vit = alpha_min_vertex_map.begin(); alpha_spectrum.reserve(alpha_cell_map.size() + alpha_min_facet_map.size() + alpha_min_edge_map.size() + alpha_min_vertex_map.size()); } else { alpha_spectrum.reserve(alpha_cell_map.size()); cit = alpha_cell_map.begin(); fit = alpha_min_facet_map.end(); eit = alpha_min_edge_map.end(); vit = alpha_min_vertex_map.end(); } while (cit != alpha_cell_map.end() || fit != alpha_min_facet_map.end() || eit != alpha_min_edge_map.end() ) { if ( cit != alpha_cell_map.end() && ( fit == alpha_min_facet_map.end() || !(fit->first < cit->first) ) && ( eit == alpha_min_edge_map.end() || !(eit->first < cit->first) ) && ( vit == alpha_min_vertex_map.end() || !(vit->first < cit->first) ) ) { //advance on cit if (alpha_spectrum.empty() || alpha_spectrum.back() < cit->first){ alpha_spectrum.push_back(cit->first); } cit++; } if ( fit != alpha_min_facet_map.end() && ( cit == alpha_cell_map.end() || !(cit->first < fit->first) ) && ( eit == alpha_min_edge_map.end() || !(eit->first < fit->first) ) && ( vit == alpha_min_vertex_map.end() || !(vit->first < fit->first) ) ) { //advance on fit if (alpha_spectrum.empty() || alpha_spectrum.back() < fit->first){ alpha_spectrum.push_back(fit->first); } fit++; } if ( eit != alpha_min_edge_map.end() && ( fit == alpha_min_facet_map.end() || !(fit->first < eit->first) ) && ( cit == alpha_cell_map.end() || !(cit->first < eit->first) ) && ( vit == alpha_min_vertex_map.end() || !(vit->first < eit->first) ) ) { //advance on eit if (alpha_spectrum.empty() || alpha_spectrum.back() < eit->first) { alpha_spectrum.push_back(eit->first); } eit++; } if ( vit != alpha_min_vertex_map.end() && ( fit == alpha_min_facet_map.end() || !(fit->first < vit->first) ) && ( cit == alpha_cell_map.end() || !(cit->first < vit->first) ) && ( eit == alpha_min_edge_map.end() || !(eit->first < vit->first) ) ) { //advance on vit if (alpha_spectrum.empty() || alpha_spectrum.back() < vit->first) { alpha_spectrum.push_back(vit->first); } vit++; } } } //--------------------------------------------------------------------- #if 0 // Obviously not ready yet template <class Dt,class EACT> std::istream& operator>>(std::istream& is, const Alpha_shape_3<Dt,EACT>& A) // Reads a alpha shape from stream `is' and assigns it to // Unknown creationvariable. Precondition: The extract operator must // be defined for `Point'. {} #endif //--------------------------------------------------------------------- template <class Dt,class EACT> std::ostream& operator<<(std::ostream& os, const Alpha_shape_3<Dt,EACT>& A) // Inserts the alpha shape into the stream `os' as an indexed face set. // Precondition: The insert operator must be defined for `Point' { typedef Alpha_shape_3<Dt,EACT> AS; typedef typename AS::size_type size_type; typedef typename AS::Vertex_handle Vertex_handle; typedef typename AS::Cell_handle Cell_handle; typedef typename AS::Alpha_shape_vertices_iterator Alpha_shape_vertices_iterator; typedef typename AS::Alpha_shape_facets_iterator Alpha_shape_facets_iterator; Unique_hash_map< Vertex_handle, size_type > V; size_type number_of_vertices = 0; Alpha_shape_vertices_iterator vit; for( vit = A.alpha_shape_vertices_begin(); vit != A.alpha_shape_vertices_end(); ++vit) { V[*vit] = number_of_vertices++; os << (*vit)->point() << std::endl; } Cell_handle c; int i; Alpha_shape_facets_iterator fit; for( fit = A.alpha_shape_facets_begin(); fit != A.alpha_shape_facets_end(); ++fit) { c = fit->first; i = fit->second; // the following ensures that regular facets are output // in ccw order if (A.classify(*fit) == AS::REGULAR && (A.classify(c) == AS::INTERIOR)){ c = c->neighbor(i); i = c->index(fit->first); } int i0 = Triangulation_utils_3::vertex_triple_index(i,0); int i1 = Triangulation_utils_3::vertex_triple_index(i,1); int i2 = Triangulation_utils_3::vertex_triple_index(i,2); os << V[c->vertex(i0)] << ' ' << V[c->vertex(i1)] << ' ' << V[c->vertex(i2)] << std::endl; } return os; } //--------------------------------------------------------------------- template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>::update_alpha_shape_vertex_list() const { alpha_shape_vertices_list.clear(); use_vertex_cache = true; std::back_insert_iterator<std::list< Vertex_handle > > it = back_inserter(alpha_shape_vertices_list); get_alpha_shape_vertices(it, REGULAR); if (get_mode()==GENERAL) get_alpha_shape_vertices(it, SINGULAR); return; } //--------------------------------------------------------------------- template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>::update_alpha_shape_facet_list() const { alpha_shape_facets_list.clear(); use_facet_cache = true; // Writes the faces of the alpha shape `A' for the current 'alpha'-value // to the container where 'out' refers to. std::back_insert_iterator<std::list< Facet> > it = back_inserter(alpha_shape_facets_list); get_alpha_shape_facets(it, REGULAR); if (get_mode()==GENERAL) get_alpha_shape_facets(it, SINGULAR); return; } //--------------------------------------------------------------------- template <class Dt,class EACT> typename Alpha_shape_3<Dt,EACT>::Classification_type Alpha_shape_3<Dt,EACT>::classify(const Alpha_status& as, const NT& alpha) const { //tetrahedra with circumradius=alpha are considered inside if ( !as.is_on_chull() && alpha >= as.alpha_max()) return INTERIOR; else if ( alpha >= as.alpha_mid()) return REGULAR; else if ( get_mode() == GENERAL && as.is_Gabriel() && alpha >= as.alpha_min()) return SINGULAR; else return EXTERIOR; } template <class Dt,class EACT> typename Alpha_shape_3<Dt,EACT>::Classification_type Alpha_shape_3<Dt,EACT>::classify(const Alpha_status* as, const NT& alpha) const { //tetrahedra with circumradius=alpha are considered inside if ( !as->is_on_chull() && alpha >= as->alpha_max()) return INTERIOR; else if ( alpha >= as->alpha_mid()) return REGULAR; else if ( get_mode() == GENERAL && as->is_Gabriel() && alpha >= as->alpha_min()) return SINGULAR; else return EXTERIOR; } template <class Dt,class EACT> typename Alpha_shape_3<Dt,EACT>::Classification_type Alpha_shape_3<Dt,EACT>::classify(Alpha_status_const_iterator as, const NT& alpha) const { return classify(&(*as), alpha); } template <class Dt,class EACT> typename Alpha_shape_3<Dt,EACT>::Classification_type Alpha_shape_3<Dt,EACT>::classify(const Cell_handle& s, int i, const NT& alpha) const // Classifies the face `f' of the underlying Delaunay // tetrahedralization with respect to `A'. { if (is_infinite(s,i)) return EXTERIOR; Alpha_status_iterator as = s->get_facet_status(i); return classify(as, alpha); } template <class Dt,class EACT> typename Alpha_shape_3<Dt,EACT>::Classification_type Alpha_shape_3<Dt,EACT>::classify(const Cell_handle& c, int i, int j, const NT& alpha) const // Classifies the edge `e' of the underlying Delaunay // tetrahedralization with respect to `A'. { if (is_infinite(c, i, j)) return EXTERIOR; if (get_mode() == GENERAL) { Alpha_status_iterator asit; Vertex_handle_pair vhp=make_vertex_handle_pair(c->vertex(i),c->vertex(j)); asit = edge_alpha_map.find(vhp)->second; return classify(asit,alpha); } //no edge map in REGULARIZED mode - classify on the fly Alpha_status as; compute_edge_status( c, i, j, as); return classify(as, alpha); } template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>:: compute_edge_status( const Cell_handle& c, int i, int j, Alpha_status& as) const { Facet_circulator fcirc, done; Alpha_status_iterator asf; NT alpha; as.set_is_on_chull(false); Cell_circulator ccirc, last; ccirc = incident_cells(c,i,j); last=ccirc; while (is_infinite(ccirc) ) ++ccirc; //skip infinite incident cells alpha = (*ccirc).get_alpha(); as.set_alpha_mid(alpha); // initialise as.alpha_mid to alpha value of an incident cell as.set_alpha_max(alpha); // same for as.alpha_max while (++ccirc != last) { if (!is_infinite(ccirc)) { alpha = (*ccirc).get_alpha(); if (alpha < as.alpha_mid()) as.set_alpha_mid(alpha); if ( ! as.is_on_chull()) { if( as.alpha_max() < alpha) as.set_alpha_max( alpha ); } } } fcirc = incident_facets(c,i,j); done = fcirc; do { if (!is_infinite(*fcirc)) { asf = (*fcirc).first->get_facet_status((*fcirc).second); if (get_mode() == GENERAL && asf->is_Gabriel()){ alpha = asf->alpha_min(); if (alpha < as.alpha_mid()) as.set_alpha_mid(alpha); } if (asf->is_on_chull()) as.set_is_on_chull(true); } } while (++fcirc != done); // initialize alphamin if ( get_mode() == GENERAL){ if (is_Gabriel(c,i,j)) { alpha = squared_radius(c,i,j); as.set_is_Gabriel(true); as.set_alpha_min(alpha); } else{ as.set_is_Gabriel(false); as.set_alpha_min(as.alpha_mid()); } } } //--------------------------------------------------------------------- template <class Dt,class EACT> typename Alpha_shape_3<Dt,EACT>::Classification_type Alpha_shape_3<Dt,EACT>::classify(const Vertex_handle& v, const NT& alpha) const // Classifies the vertex `v' of the underlying Delaunay // tetrahedralization with respect to `A'. { if (is_infinite(v)) return EXTERIOR; Alpha_status* as = v->get_alpha_status(); return classify(as, alpha); } //--------------------- NB COMPONENTS --------------------------------- template <class Dt,class EACT> typename Alpha_shape_3<Dt,EACT>::size_type Alpha_shape_3<Dt,EACT>::number_of_solid_components(const NT& alpha) const // Determine the number of connected solid components // takes time O(#alpha_shape) amortized if STL_HASH_TABLES // O(#alpha_shape log n) otherwise { typedef typename Marked_cell_set::Data Data; Marked_cell_set marked_cell_set(false); Finite_cells_iterator cell_it, done = finite_cells_end(); size_type nb_solid_components = 0; // only finite simplices for( cell_it = finite_cells_begin(); cell_it != done; ++cell_it) { Cell_handle pCell = cell_it; CGAL_triangulation_assertion(pCell != nullptr); if (classify(pCell, alpha) == INTERIOR){ Data& data = marked_cell_set[pCell]; if(data == false) { // we traverse only interior simplices data = true; traverse(pCell, marked_cell_set, alpha); nb_solid_components++; } } } return nb_solid_components; } template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>::traverse(Cell_handle pCell, Marked_cell_set& marked_cell_set, const NT alpha) const { typedef typename Marked_cell_set::Data Data; std::list<Cell_handle> cells; cells.push_back(pCell); Cell_handle pNeighbor; while(! cells.empty()){ pCell = cells.back(); cells.pop_back(); for (int i=0; i<=3; i++) { pNeighbor = pCell->neighbor(i); CGAL_triangulation_assertion(pNeighbor != nullptr); if (classify(pNeighbor, alpha) == INTERIOR){ Data& data = marked_cell_set[pNeighbor]; if(data == false){ data = true; cells.push_back(pNeighbor); } } } } } //---------------------------------------------------------------------- template <class Dt,class EACT> typename Alpha_shape_3<Dt,EACT>::Alpha_iterator Alpha_shape_3<Dt,EACT>::find_optimal_alpha(size_type nb_components) const // find the minimum alpha that satisfies the properties // (1) nb_components solid components <= nb_components // (2) all data points on the boundary or in its interior { NT alpha = find_alpha_solid(); // from this alpha on the alpha_solid satisfies property (2) Alpha_iterator first = alpha_lower_bound(alpha); if (number_of_solid_components(alpha) == nb_components) { // if ((first+1) < alpha_end()) // return (first+1); // else return first; } // do binary search on the alpha values // number_of_solid_components() is a monotone function // if we start with find_alpha_solid Alpha_iterator last = alpha_end(); Alpha_iterator middle; std::ptrdiff_t len = last - first - 1; std::ptrdiff_t half; while (len > 0) { half = len / 2; middle = first + half; #ifdef CGAL_DEBUG_ALPHA_SHAPE_3 std::cerr << "first : " << *first << " last : " << ((first+len != last) ? *(first+len) : *(last-1)) << " mid : " << *middle << " nb comps : " << number_of_solid_components(*middle) << std::endl; #endif if (number_of_solid_components(*middle) > nb_components) { first = middle + 1; len = len - half -1; } else // number_of_solid_components(*middle) <= nb_components { len = half; } } #ifdef CGAL_DEBUG_ALPHA_SHAPE_3 std::cerr << "In the end: " << std::endl << "first : " << *first << " nb comps : " << number_of_solid_components(*first) << std::endl; if ((first+1) < alpha_end()) std::cerr << "first+1 " << *(first+1) << " nb comps : " << number_of_solid_components(*(first+1)) << std::endl; std::cerr << std::endl; #endif if (number_of_solid_components(*first) <= nb_components ) return first; else return first+1; } //---------------------------------------------------------------------- template <class Dt,class EACT> typename Alpha_shape_3<Dt,EACT>::NT Alpha_shape_3<Dt,EACT>::find_alpha_solid() const // compute the minumum alpha such that all data points // are either on the boundary or in the interior // not necessarily connected { return _alpha_solid; } // TO DEBUG template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>::print_maps() const { typename Alpha_cell_map::const_iterator cit ; typename Alpha_facet_map::const_iterator fit ; typename Alpha_edge_map::const_iterator eit ; typename Alpha_vertex_map::const_iterator vit; std::cerr << "size of cell map " << alpha_cell_map.size() << std::endl; std::cerr << "size of facet map " << alpha_min_facet_map.size() << std::endl; std::cerr << "size of edge map " << alpha_min_edge_map.size() << std::endl; std::cerr << "size of vertex map " << alpha_min_vertex_map.size() << std::endl; std::cerr << std::endl; std::cerr << "alpha_cell_map " << std::endl; for(cit = alpha_cell_map.begin(); cit != alpha_cell_map.end(); ++cit) { std::cerr << cit->first << std::endl; } std::cerr << std::endl; std::cerr << "alpha_min_facet_map " << std::endl; for(fit = alpha_min_facet_map.begin(); fit != alpha_min_facet_map.end(); ++fit) { std::cerr << fit->first << std::endl; } std::cerr << std::endl; std::cerr << "alpha_min_edge_map " << std::endl; for(eit = alpha_min_edge_map.begin(); eit != alpha_min_edge_map.end(); ++eit) { std::cerr << eit->first << std::endl; } std::cerr << std::endl; std::cerr << "alpha_min_vertex_map " << std::endl; for(vit = alpha_min_vertex_map.begin(); vit != alpha_min_vertex_map.end(); ++vit) { std::cerr << vit->first << std::endl; } std::cerr << std::endl; } template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>::print_alphas() const { std::cerr << std::endl; std::cerr << " alpha values of facets" << std::endl; for(Finite_facets_iterator fit = finite_facets_begin(); fit != finite_facets_end(); ++fit) { Alpha_status_iterator as = fit->first->get_facet_status(fit->second); print_alpha_status(*as); } std::cerr << std::endl; std::cerr << " alpha values of edges " << std::endl; if (get_mode() == GENERAL) { for(Finite_edges_iterator eit = finite_edges_begin(); eit != finite_edges_end(); ++eit) { Vertex_handle_pair vhp = make_vertex_handle_pair(eit->first->vertex(eit->second), eit->first->vertex(eit->third)); Alpha_status_iterator as = edge_alpha_map.find(vhp)->second; print_alpha_status(*as); } } std::cerr << std::endl; std::cerr << " alpha values of vertices " << std::endl; for(Finite_vertices_iterator vit = finite_vertices_begin(); vit != finite_vertices_end(); ++vit) { Alpha_status* as = vit->get_alpha_status(); print_alpha_status(*as); } } template <class Dt,class EACT> void Alpha_shape_3<Dt,EACT>::print_alpha_status(const Alpha_status& as) const { if ( get_mode() == GENERAL && as.is_Gabriel()) std::cerr << as.alpha_min() ; else std::cerr << "--- " ; std::cerr << "\t"; std::cerr << as.alpha_mid() << "\t"; if(as.is_on_chull()) std::cerr << "--- "; else std::cerr << as.alpha_max(); std::cerr << std::endl; } } //namespace CGAL #ifdef CGAL_USE_GEOMVIEW #include <CGAL/IO/alpha_shape_geomview_ostream_3.h> #endif #endif //CGAL_ALPHA_SHAPE_3_H
32,905
https://github.com/eytb2/Ticket-Analysis/blob/master/androidutils/src/main/java/momo/cn/edu/fjnu/androidutils/utils/DeviceInfoUtils.java
Github Open Source
Open Source
MIT
null
Ticket-Analysis
eytb2
Java
Code
270
1,381
package momo.cn.edu.fjnu.androidutils.utils; import android.app.Activity; import android.content.Context; import android.graphics.Rect; import android.telephony.TelephonyManager; import android.util.DisplayMetrics; import android.view.WindowManager; import java.lang.reflect.Field; import momo.cn.edu.fjnu.androidutils.pojo.DeviceInfo; /** * 设备信息获取工具 * Created by GaoFei on 2016/1/3. */ public class DeviceInfoUtils { private DeviceInfoUtils(){ } /**获取设备信息*/ public static DeviceInfo getDeviceInfo(Context context){ DeviceInfo deviceInfo=new DeviceInfo(); deviceInfo.setDenstity(getDenstity(context)); deviceInfo.setDenstityDP(getDenstityDpi(context)); deviceInfo.setDeviceBrand(getDeviceBrand()); deviceInfo.setDeviceID(getDeviceID(context)); deviceInfo.setScreenHeight(getScreenHeight(context)); deviceInfo.setScreenWidth(getScreenWidth(context)); deviceInfo.setScaleDenstity(getScaleDenstity(context)); return deviceInfo; } /** * 获取屏幕宽度(以pix为单位) */ public static int getScreenWidth(Context context){ DisplayMetrics dm=new DisplayMetrics(); WindowManager windowManager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(dm); return dm.widthPixels; } /** * 获取屏幕宽度(以dp为单位) */ public static float getScreenDpWidth(Context context){ DisplayMetrics dm=new DisplayMetrics(); WindowManager windowManager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(dm); return dm.xdpi; } /** * 获取屏幕高度(以pix为单位) */ public static int getScreenHeight(Context context){ DisplayMetrics dm=new DisplayMetrics(); WindowManager windowManager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(dm); return dm.heightPixels; } /** * 获取屏幕高度(以dp为单位) */ public static float getScreenDpHeight(Context context){ DisplayMetrics dm=new DisplayMetrics(); WindowManager windowManager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(dm); return dm.ydpi; } /** * 获取屏幕密度(一个dp等于多少pix) */ public static float getDenstity(Context context){ DisplayMetrics dm=new DisplayMetrics(); WindowManager windowManager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(dm); return dm.density; } /** * 获取屏幕密度(一英寸等于多少dp) */ public static int getDenstityDpi(Context context){ DisplayMetrics dm=new DisplayMetrics(); WindowManager windowManager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(dm); return dm.densityDpi; } /**获取设备ID*/ public static String getDeviceID(Context context){ TelephonyManager telephonyManager=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); return telephonyManager.getDeviceId(); } /**获取设备型号*/ public static String getDeviceBrand(){ //TelephonyManager telephonyManager=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); return android.os.Build.MODEL; } public static float getScaleDenstity(Context context){ DisplayMetrics dm=new DisplayMetrics(); WindowManager windowManager=(WindowManager)context.getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getMetrics(dm); return dm.scaledDensity; } /** * 获取状态栏高度 * @param activity * @return 如果返回的是Integer.Min_VALUE,表示获取失败 */ public static int getStatusBarHeight(Activity activity) { Rect frame = new Rect(); activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusHeight = frame.top; if (statusHeight == 0) { Class<?> c; Object object; Field field; int x = 0; statusHeight = Integer.MIN_VALUE; try { c = Class.forName("com.android.internal.R$dimen"); object = c.newInstance(); field = c.getField("status_bar_height"); x = Integer.parseInt(field.get(object).toString()); statusHeight = activity.getResources().getDimensionPixelSize(x); } catch (Exception e1) { e1.printStackTrace(); } } return statusHeight; } }
36,041
https://github.com/natefaubion/slamdata/blob/master/src/SlamData/Dialog/License.purs
Github Open Source
Open Source
Apache-2.0
2,020
slamdata
natefaubion
PureScript
Code
486
1,189
{- Copyright 2017 SlamData, 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. -} module SlamData.Dialog.License where import SlamData.Prelude import Halogen.HTML as H import Halogen.HTML.Properties as HP import SlamData.Render.ClassName as CN import SlamData.Dialog.Render as DR data LaunchedBy = App | Other licenseDialogClasses ∷ Array H.ClassName licenseDialogClasses = [ CN.dialog, H.ClassName "license-dialog" ] advancedLicenseExpired ∷ ∀ f p. H.HTML p (f Unit) advancedLicenseExpired = H.div [ HP.classes licenseDialogClasses ] [ H.img [ HP.src "img/logo-center.svg" ] , DR.modalHeader "Your license has expired" , DR.modalBody $ H.div_ [ H.p_ [ H.text "Thanks for using SlamData Advanced!" ] , H.p_ [ H.text "Get in touch with us today to purchase SlamData Advanced or an extended trial period with raining for your team, configuration and optimization assistance and support ith queries, sharing and distribution." ] ] , DR.modalFooter [ H.a [ HP.classes [ CN.btn, CN.btnPrimary ] , HP.href "https://slamdata.com/contact-us/" ] [ H.text "Contact SlamData" ] , H.a [ HP.classes [ CN.btn, CN.btnDefault ] , HP.href "https://slamdata.com/slamdata-jump-start/" ] [ H.text "Request training" ] ] ] advancedTrialLicenseExpired ∷ ∀ f p. H.HTML p (f Unit) advancedTrialLicenseExpired = H.div [ HP.classes licenseDialogClasses ] [ H.div_ [ H.img [ HP.src "img/logo-center.svg" ] , DR.modalHeader "Your trial has expired" , DR.modalBody $ H.div_ [ H.p_ [ H.text "Thanks for trying SlamData Advanced!" ] , H.p_ [ H.text "Get in touch with us today to purchase a SlamData license or an extended trial period with training for your team, configuration, query optimization and support." ] ] , DR.modalFooter [ H.a [ HP.classes [ CN.btn, CN.btnPrimary ] , HP.href "https://slamdata.com/contact-us/" ] [ H.text "Contact SlamData" ] , H.a [ HP.classes [ CN.btn, CN.btnDefault ] , HP.href "https://slamdata.com/slamdata-jump-start/" ] [ H.text "Request training" ] ] ] ] licenseInvalid ∷ ∀ f p. H.HTML p (f Unit) licenseInvalid = H.div [ HP.classes licenseDialogClasses ] [ H.div_ [ H.img [ HP.src "img/logo-center.svg" ] , DR.modalHeader "Your license is invalid" , DR.modalBody $ H.div_ [ H.p_ [ H.text $ "Try double checking your license information and " <> howToFix App <> " before restarting SlamData. If you are still experiencing problems with your license after trying this please contact support." ] ] , DR.modalFooter [ H.a [ HP.classes [ CN.btn, CN.btnPrimary ] , HP.href "https://slamdata.com/contact-us/" ] [ H.text "Contact SlamData" ] , H.a [ HP.classes [ CN.btn, CN.btnDefault ] , HP.href "https://slamdata.com/slamdata-jump-start/" ] [ H.text "Request training" ] ] ] ] where howToFix ∷ LaunchedBy → String howToFix = case _ of App → "reinstalling" Other → "providing your Java system properties"
49,345
https://github.com/coltrida/andirivieni/blob/master/app/Models/Order.php
Github Open Source
Open Source
MIT
null
andirivieni
coltrida
PHP
Code
55
213
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Order extends Model { protected $table = 'orders'; protected $appends = ['orario', 'cameriere']; public function foods() { return $this->belongsToMany(Food::class, 'foods_orders', 'order_id', 'food_id') ->withPivot('quantity', 'mandata'); } public function getOrarioAttribute() { return $this->updated_at->format('H:i:s'); } public function getCameriereAttribute() { return $this->user->name; } public function user() { return $this->belongsTo(User::class, 'user_id', 'id'); } }
36,958
https://github.com/facebook/react-native/blob/master/packages/react-native/Libraries/Inspector/ElementProperties.js
Github Open Source
Open Source
MIT, CC-BY-4.0, CC-BY-NC-SA-4.0, CC-BY-SA-4.0
2,023
react-native
facebook
JavaScript
Code
360
1,205
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow */ 'use strict'; import type {ViewStyleProp} from '../StyleSheet/StyleSheet'; const TouchableHighlight = require('../Components/Touchable/TouchableHighlight'); const TouchableWithoutFeedback = require('../Components/Touchable/TouchableWithoutFeedback'); const View = require('../Components/View/View'); const openFileInEditor = require('../Core/Devtools/openFileInEditor'); const flattenStyle = require('../StyleSheet/flattenStyle'); const StyleSheet = require('../StyleSheet/StyleSheet'); const Text = require('../Text/Text'); const mapWithSeparator = require('../Utilities/mapWithSeparator'); const BoxInspector = require('./BoxInspector'); const StyleInspector = require('./StyleInspector'); const React = require('react'); type Props = $ReadOnly<{| hierarchy: Array<{|name: string|}>, style?: ?ViewStyleProp, source?: ?{ fileName?: string, lineNumber?: number, ... }, frame?: ?Object, selection?: ?number, setSelection?: number => mixed, |}>; class ElementProperties extends React.Component<Props> { render(): React.Node { const style = flattenStyle(this.props.style); const selection = this.props.selection; let openFileButton; const source = this.props.source; const {fileName, lineNumber} = source || {}; if (fileName && lineNumber) { const parts = fileName.split('/'); const fileNameShort = parts[parts.length - 1]; openFileButton = ( <TouchableHighlight style={styles.openButton} onPress={openFileInEditor.bind(null, fileName, lineNumber)}> <Text style={styles.openButtonTitle} numberOfLines={1}> {fileNameShort}:{lineNumber} </Text> </TouchableHighlight> ); } // Without the `TouchableWithoutFeedback`, taps on this inspector pane // would change the inspected element to whatever is under the inspector return ( <TouchableWithoutFeedback> <View style={styles.info}> <View style={styles.breadcrumb}> {mapWithSeparator( this.props.hierarchy, (hierarchyItem, i): React.MixedElement => ( <TouchableHighlight key={'item-' + i} style={[styles.breadItem, i === selection && styles.selected]} // $FlowFixMe[not-a-function] found when converting React.createClass to ES6 onPress={() => this.props.setSelection(i)}> <Text style={styles.breadItemText}>{hierarchyItem.name}</Text> </TouchableHighlight> ), (i): React.MixedElement => ( <Text key={'sep-' + i} style={styles.breadSep}> &#9656; </Text> ), )} </View> <View style={styles.row}> <View style={styles.col}> <StyleInspector style={style} /> {openFileButton} </View> {<BoxInspector style={style} frame={this.props.frame} />} </View> </View> </TouchableWithoutFeedback> ); } } const styles = StyleSheet.create({ breadSep: { fontSize: 8, color: 'white', }, breadcrumb: { flexDirection: 'row', flexWrap: 'wrap', alignItems: 'flex-start', marginBottom: 5, }, selected: { borderColor: 'white', borderRadius: 5, }, breadItem: { borderWidth: 1, borderColor: 'transparent', marginHorizontal: 2, }, breadItemText: { fontSize: 10, color: 'white', marginHorizontal: 5, }, row: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', }, col: { flex: 1, }, info: { padding: 10, }, openButton: { padding: 10, backgroundColor: '#000', marginVertical: 5, marginRight: 5, borderRadius: 2, }, openButtonTitle: { color: 'white', fontSize: 8, }, }); module.exports = ElementProperties;
16,748
https://github.com/thaliproject/Thali_Codovaplugin/blob/master/test/www/jxcore/lib/sinonTest.js
Github Open Source
Open Source
MIT
2,022
Thali_Codovaplugin
thaliproject
JavaScript
Code
70
234
'use strict'; var sinon = require('sinon'); function sinonTest (callback) { return function (t) { var config = sinon.getConfig(sinon.config); config.injectInto = config.injectIntoThis && this || config.injectInto; var sandbox = sinon.sandbox.create(config); var args = Array.prototype.slice.call(arguments); var ok; if (typeof t.end === 'function') { t.on('result', function(res) { ok = res.ok; }); t.on('end', function() { if (!ok) { sandbox.restore(); } else { sandbox.verifyAndRestore(); } }); } return callback.apply(this, args.concat(sandbox.args)); }; } module.exports = sinonTest;
38,110
https://github.com/oracle/weblogic-kubernetes-operator/blob/master/kubernetes/samples/scripts/create-kubernetes-secrets/create-azure-storage-credentials-secret.sh
Github Open Source
Open Source
BSD-3-Clause, LicenseRef-scancode-free-unknown, UPL-1.0, bzip2-1.0.6, LicenseRef-scancode-other-copyleft, LicenseRef-scancode-unknown-license-reference, Plexus, EPL-2.0, CDDL-1.0, MIT, GPL-2.0-only, Apache-2.0, LicenseRef-scancode-public-domain, CDDL-1.1, LicenseRef-scancode-generic-export-compliance, CC0-1.0, GPL-2.0-or-later, EPL-1.0, Classpath-exception-2.0, W3C, GPL-1.0-or-later, CPL-1.0
2,023
weblogic-kubernetes-operator
oracle
Shell
Code
375
907
#!/usr/bin/env bash # Copyright (c) 2018, 2022, Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. # # Description # This sample script creates a Kubernetes secret for Azure Storage to use Azure file share on AKS. # # The following pre-requisites must be handled prior to running this script: # * The kubernetes namespace must already be created # script="${BASH_SOURCE[0]}" # # Function to exit and print an error message # $1 - text of message fail() { echo [ERROR] $* exit 1 } # Try to execute ${KUBERNETES_CLI:-kubectl} to see whether ${KUBERNETES_CLI:-kubectl} is available validateKubernetesCLIAvailable() { if ! [ -x "$(command -v ${KUBERNETES_CLI:-kubectl})" ]; then fail "${KUBERNETES_CLI:-kubectl} is not installed" fi } usage() { echo usage: ${script} -c storageAccountName -k storageAccountKey [-s secretName] [-n namespace] [-h] echo " -a storage account name, must be specified." echo " -k storage account key, must be specified." echo " -s secret name, optional. Use azure-secret if not specified." echo " -n namespace, optional. Use the default namespace if not specified." echo " -h Help" exit $1 } # # Parse the command line options # secretName=azure-secret namespace=default while getopts "ha:k:s:n:" opt; do case $opt in a) storageAccountName="${OPTARG}" ;; k) storageAccountKey="${OPTARG}" ;; s) secretName="${OPTARG}" ;; n) namespace="${OPTARG}" ;; h) usage 0 ;; *) usage 1 ;; esac done if [ -z ${storageAccountName} ]; then echo "${script}: -e must be specified." missingRequiredOption="true" fi if [ -z ${storageAccountKey} ]; then echo "${script}: -p must be specified." missingRequiredOption="true" fi if [ "${missingRequiredOption}" == "true" ]; then usage 1 fi # check and see if the secret already exists result=`${KUBERNETES_CLI:-kubectl} get secret ${secretName} -n ${namespace} --ignore-not-found=true | grep ${secretName} | wc | awk ' { print $1; }'` if [ "${result:=Error}" != "0" ]; then fail "The secret ${secretName} already exists in namespace ${namespace}." fi # create the secret ${KUBERNETES_CLI:-kubectl} -n $namespace create secret generic $secretName \ --from-literal=azurestorageaccountname=$storageAccountName \ --from-literal=azurestorageaccountkey=$storageAccountKey # Verify the secret exists SECRET=`${KUBERNETES_CLI:-kubectl} get secret ${secretName} -n ${namespace} | grep ${secretName} | wc | awk ' { print $1; }'` if [ "${SECRET}" != "1" ]; then fail "The secret ${secretName} was not found in namespace ${namespace}" fi echo "The secret ${secretName} has been successfully created in the ${namespace} namespace."
10,207
https://github.com/Dorllen/eso/blob/master/src/main/java/com/zhidian/utils/Mybatis.java
Github Open Source
Open Source
Apache-2.0
null
eso
Dorllen
Java
Code
102
389
/** * @Title: Mybatis.java * @Package com.zhidian.utils * @Description: TODO(用一句话描述该文件做什么) * @author dongneng * @date 2017-3-18 下午9:14:26 * @version V1.0 */ package com.zhidian.utils; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; /** * @ClassName: Mybatis * @Description: TODO(这里用一句话描述这个类的作用) * @author dongneng * @date 2017-3-18 下午9:14:26 * */ public class Mybatis { public final static String PATH = "classpath:mybatis.xml"; private static SqlSessionFactory sqlSessionFactory; public static SqlSessionFactory getSqlSessionFactory() { if (sqlSessionFactory == null) { InputStream inputStream = null; try { inputStream = Resources.getResourceAsStream(PATH); } catch (IOException e) { e.printStackTrace(); return null; } sqlSessionFactory = new SqlSessionFactoryBuilder() .build(inputStream); } return sqlSessionFactory; } }
50,420
https://github.com/ScalablyTyped/SlinkyTyped/blob/master/d/docusign-esign/src/main/scala/typingsSlinky/docusignEsign/mod/BillingPlanUpdateResponse.scala
Github Open Source
Open Source
MIT
2,021
SlinkyTyped
ScalablyTyped
Scala
Code
398
1,269
package typingsSlinky.docusignEsign.mod import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @js.native trait BillingPlanUpdateResponse extends StObject { /** * The type of payment method used for the account. Valid values are: * * - `credit_card` * - */ var accountPaymentMethod: js.UndefOr[String] = js.native var billingPlanPreview: js.UndefOr[ /* Information used to provide a preview of a billing plan. */ BillingPlanPreview ] = js.native /** * Specifies the ISO currency code for the account. */ var currencyCode: js.UndefOr[String] = js.native /** * The number of seats (users) included in the plan. */ var includedSeats: js.UndefOr[String] = js.native /** * The payment cycle associated with the plan. The possible values are: * * - `Monthly` * - `Annually` */ var paymentCycle: js.UndefOr[String] = js.native /** * The payment method used for the billing plan. Valid values are: * * - `NotSupported` * - `CreditCard` * - `PurchaseOrder` * - `Premium` * - `Freemium` * - `FreeTrial` * - `AppStore` * - `DigitalExternal` * - `DirectDebit` */ var paymentMethod: js.UndefOr[String] = js.native /** * DocuSign's id for the account plan. */ var planId: js.UndefOr[String] = js.native /** * The name of the billing plan used for the account. * * Examples: * * - `Personal - Annual` * - `Unlimited Envelope Subscription - Annual Billing` */ var planName: js.UndefOr[String] = js.native } object BillingPlanUpdateResponse { @scala.inline def apply(): BillingPlanUpdateResponse = { val __obj = js.Dynamic.literal() __obj.asInstanceOf[BillingPlanUpdateResponse] } @scala.inline implicit class BillingPlanUpdateResponseMutableBuilder[Self <: BillingPlanUpdateResponse] (val x: Self) extends AnyVal { @scala.inline def setAccountPaymentMethod(value: String): Self = StObject.set(x, "accountPaymentMethod", value.asInstanceOf[js.Any]) @scala.inline def setAccountPaymentMethodUndefined: Self = StObject.set(x, "accountPaymentMethod", js.undefined) @scala.inline def setBillingPlanPreview(value: /* Information used to provide a preview of a billing plan. */ BillingPlanPreview): Self = StObject.set(x, "billingPlanPreview", value.asInstanceOf[js.Any]) @scala.inline def setBillingPlanPreviewUndefined: Self = StObject.set(x, "billingPlanPreview", js.undefined) @scala.inline def setCurrencyCode(value: String): Self = StObject.set(x, "currencyCode", value.asInstanceOf[js.Any]) @scala.inline def setCurrencyCodeUndefined: Self = StObject.set(x, "currencyCode", js.undefined) @scala.inline def setIncludedSeats(value: String): Self = StObject.set(x, "includedSeats", value.asInstanceOf[js.Any]) @scala.inline def setIncludedSeatsUndefined: Self = StObject.set(x, "includedSeats", js.undefined) @scala.inline def setPaymentCycle(value: String): Self = StObject.set(x, "paymentCycle", value.asInstanceOf[js.Any]) @scala.inline def setPaymentCycleUndefined: Self = StObject.set(x, "paymentCycle", js.undefined) @scala.inline def setPaymentMethod(value: String): Self = StObject.set(x, "paymentMethod", value.asInstanceOf[js.Any]) @scala.inline def setPaymentMethodUndefined: Self = StObject.set(x, "paymentMethod", js.undefined) @scala.inline def setPlanId(value: String): Self = StObject.set(x, "planId", value.asInstanceOf[js.Any]) @scala.inline def setPlanIdUndefined: Self = StObject.set(x, "planId", js.undefined) @scala.inline def setPlanName(value: String): Self = StObject.set(x, "planName", value.asInstanceOf[js.Any]) @scala.inline def setPlanNameUndefined: Self = StObject.set(x, "planName", js.undefined) } }
31,806
https://github.com/andes/turnos_online/blob/master/src/app/pages/turnos/buscar/turnos-buscar.ts
Github Open Source
Open Source
MIT
2,018
turnos_online
andes
TypeScript
Code
288
1,063
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Platform } from '@ionic/angular'; import { Subscription } from 'rxjs'; import { GeoProvider } from 'src/providers/geo-provider'; // src/providers import { AgendasProvider } from 'src/providers/agendas'; import { TurnosProvider } from 'src/providers/turnos'; import { CheckerGpsProvider } from 'src/providers/locations/checkLocation'; import { ErrorReporterProvider } from 'src/providers/errorReporter'; import { StorageService } from 'src/providers/storage-provider.service'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-turnos-buscar', templateUrl: 'turnos-buscar.html' }) export class TurnosBuscarPage implements OnInit, OnDestroy { prestacion: any; efectores: any[] = null; points: any[]; position: any = {}; lugares: any[]; geoSubcribe; myPosition = null; private onResumeSubscription: Subscription; familiar = false; private idPaciente; ngOnDestroy() { // always unsubscribe your subscriptions to prevent leaks this.onResumeSubscription.unsubscribe(); } constructor( private turnosProvider: TurnosProvider, private agendasService: AgendasProvider, private gMaps: GeoProvider, private checker: CheckerGpsProvider, private reporter: ErrorReporterProvider, private platform: Platform, private router: Router, private route: ActivatedRoute, private storage: StorageService, ) { } ngOnInit() { this.route.queryParams.subscribe(params => { this.idPaciente = params.idPaciente; }); this.storage.get('familiar').then((value) => { if (value) { this.familiar = value; } this.onResumeSubscription = this.platform.resume.subscribe(() => { this.checker.checkGPS(); }); this.storage.get('prestacion').then(prestacion => { this.prestacion = prestacion; this.getTurnosDisponibles(); }); }); } getTurnosDisponibles() { if (this.gMaps.actualPosition) { const userLocation = { lat: this.gMaps.actualPosition.latitude, lng: this.gMaps.actualPosition.longitude }; this.getTurnosDisponiblesAux(userLocation); } else { this.gMaps.getGeolocation().then(position => { const userLocation = { lat: position.coords.latitude, lng: position.coords.longitude }; this.getTurnosDisponiblesAux(userLocation); }); } } private getTurnosDisponiblesAux(userLocation) { this.agendasService.getAgendasDisponibles({ ...this.prestacion, userLocation: JSON.stringify(userLocation), idPaciente: this.idPaciente }). subscribe((data: any[]) => { this.efectores = data; }); } mostrarEfector(efector) { return efector.organizacion; } turnosDisponibles(efector) { const agendasEfector = []; const listaTurnosDisponibles = []; agendasEfector.forEach(agenda => { agenda.bloques.forEach(bloque => { bloque.turnos.forEach(turno => { if (turno.estado === 'disponible') { listaTurnosDisponibles.push(turno); } }); }); }); return listaTurnosDisponibles; } buscarTurno(efector) { this.storage.set('calendario', { efector, prestacion: this.prestacion }); this.router.navigate(['/turnos/calendario']); } onBugReport() { this.reporter.report(); } }
7,873
https://github.com/sleyzerzon/soar/blob/master/Domains/SoarQnA/src/main/java/edu/umich/soar/qna/dice/ComputeProbabilityQueryState.java
Github Open Source
Open Source
Unlicense
2,016
soar
sleyzerzon
Java
Code
198
835
package edu.umich.soar.qna.dice; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import edu.umich.dice.LiarsDice.Predicate; import edu.umich.soar.qna.ComputationalQueryState; public class ComputeProbabilityQueryState extends ComputationalQueryState { private static final String COMMAND_DICE = "number-of-dice"; private static final String COMMAND_SIDES = "number-of-faces"; private static final String COMMAND_COUNT = "count"; private static final String COMMAND_PREDICATE = "predicate"; private Integer myDice = null; private Integer mySides = null; private Integer myCount = null; private Predicate myPred = null; private Double myResult = null; public boolean initialize(String querySource, Map<Object, List<Object>> queryParameters) { boolean returnVal = false; if (queryParameters.size() == 4) { if (queryParameters.containsKey(COMMAND_DICE) && queryParameters.get(COMMAND_DICE).size()==1 && queryParameters.containsKey(COMMAND_SIDES) && queryParameters.get(COMMAND_SIDES).size()==1 && queryParameters.containsKey(COMMAND_COUNT) && queryParameters.get(COMMAND_COUNT).size()==1 && queryParameters.containsKey(COMMAND_PREDICATE) && queryParameters.get(COMMAND_PREDICATE).size()==1) { if ((queryParameters.get(COMMAND_DICE).iterator().next() instanceof Long) && (queryParameters.get(COMMAND_SIDES).iterator().next() instanceof Long) && (queryParameters.get(COMMAND_COUNT).iterator().next() instanceof Long) && (queryParameters.get(COMMAND_PREDICATE).iterator().next() instanceof String)) { myDice = ((Long) queryParameters.get(COMMAND_DICE).iterator().next()).intValue(); mySides = ((Long) queryParameters.get(COMMAND_SIDES).iterator().next()).intValue(); myCount = ((Long) queryParameters.get(COMMAND_COUNT).iterator().next()).intValue(); myPred = Predicate.valueOf((String) queryParameters.get(COMMAND_PREDICATE).iterator().next()); try { myResult = myPred.get(myDice, mySides, myCount); returnVal = true; hasComputed = false; } catch (Exception e) { } } } } return returnVal; } public Map<String, List<Object>> next() { if (!hasComputed) { hasComputed = true; HashMap<String, List<Object>> returnVal = new HashMap<String, List<Object>>(); List<Object> newList = new LinkedList<Object>(); newList.add(myResult); returnVal.put("probability", newList); return returnVal; } return null; } }
24,863
https://github.com/Thitthitmon/msphpsql/blob/master/test/functional/pdo_sqlsrv/pdo_033_binary_unicode.phpt
Github Open Source
Open Source
MIT
2,017
msphpsql
Thitthitmon
PHP
Code
125
399
--TEST-- Insert binary HEX data then fetch it back as string --DESCRIPTION-- Insert binary HEX data into an nvarchar field then read it back as UTF-8 string --SKIPIF-- <?php require('skipif.inc'); ?> --FILE-- <?php try { require_once("MsSetup.inc"); // Connect $conn = new PDO("sqlsrv:server=$server; database=$databaseName", $uid, $pwd); // Create table $tableName = '#pdo_033test'; $sql = "CREATE TABLE $tableName (c1 NVARCHAR(100))"; $stmt = $conn->exec($sql); $input = pack( "H*", '49006427500048005000' ); // I'LOVE_SYMBOL'PHP $stmt = $conn->prepare("INSERT INTO $tableName (c1) VALUES (?)"); $stmt->bindParam(1, $input, PDO::PARAM_STR, 0, PDO::SQLSRV_ENCODING_BINARY); $result = $stmt->execute(); if (! $result) echo "Failed to insert!\n"; $stmt = $conn->query("SELECT * FROM $tableName"); $utf8 = $stmt->fetchColumn(); echo "\n". $utf8 ."\n"; $stmt = null; $conn = null; } catch (Exception $e) { echo $e->getMessage(); } print "Done"; ?> --EXPECT-- I❤PHP Done
8,425
https://github.com/aic-develop/vietmaps-navigation-android/blob/master/examples/src/main/java/com/mapbox/navigation/examples/activity/OffboardRouterActivityJava.java
Github Open Source
Open Source
Apache-2.0, BSD-2-Clause
null
vietmaps-navigation-android
aic-develop
Java
Code
435
2,009
package com.mapbox.navigation.examples.activity; import android.annotation.SuppressLint; import android.os.Bundle; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.snackbar.Snackbar; import com.mapbox.api.directions.v5.models.DirectionsRoute; import com.mapbox.api.directions.v5.models.RouteOptions; import com.mapbox.geojson.Point; import com.mapbox.mapboxsdk.annotations.MarkerOptions; import com.mapbox.mapboxsdk.camera.CameraUpdateFactory; import com.mapbox.mapboxsdk.geometry.LatLng; import com.mapbox.mapboxsdk.maps.MapView; import com.mapbox.mapboxsdk.maps.MapboxMap; import com.mapbox.mapboxsdk.maps.OnMapReadyCallback; import com.mapbox.mapboxsdk.maps.Style; import com.mapbox.navigation.base.logger.model.Message; import com.mapbox.navigation.base.route.Router; import com.mapbox.navigation.core.accounts.MapboxNavigationAccounts; import com.mapbox.navigation.examples.R; import com.mapbox.navigation.examples.utils.Utils; import com.mapbox.navigation.logger.MapboxLogger; import com.mapbox.navigation.route.offboard.MapboxOffboardRouter; import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute; import com.mapbox.turf.TurfConstants; import com.mapbox.turf.TurfMeasurement; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.mapbox.navigation.base.extensions.MapboxRouteOptionsUtils.applyDefaultParams; import static com.mapbox.navigation.base.extensions.MapboxRouteOptionsUtils.coordinates; public class OffboardRouterActivityJava extends AppCompatActivity implements OnMapReadyCallback, MapboxMap.OnMapClickListener, Router.Callback { // Map variables @BindView(R.id.mapView) MapView mapView; private MapboxMap mapboxMap; private Router offboardRouter; private DirectionsRoute route; private NavigationMapRoute navigationMapRoute; private Point origin; private Point destination; private Point waypoint; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mock_navigation); ButterKnife.bind(this); mapView.onCreate(savedInstanceState); mapView.getMapAsync(this); } @OnClick(R.id.newLocationFab) public void onNewLocationClick() { newOrigin(); } private void newOrigin() { if (mapboxMap != null) { clearMap(); LatLng latLng = Utils.getRandomLatLng(new double[]{-77.1825, 38.7825, -76.9790, 39.0157}); origin = Point.fromLngLat(latLng.getLongitude(), latLng.getLatitude()); mapboxMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12)); } } @SuppressLint("MissingPermission") @Override public void onMapReady(@NonNull MapboxMap mapboxMap) { this.mapboxMap = mapboxMap; this.mapboxMap.addOnMapClickListener(this); mapboxMap.setStyle(Style.MAPBOX_STREETS, style -> { navigationMapRoute = new NavigationMapRoute(mapView, mapboxMap); Snackbar.make(findViewById(R.id.container), "Tap map to place waypoint", Snackbar.LENGTH_LONG).show(); newOrigin(); }); } @Override public boolean onMapClick(@NonNull LatLng point) { if (destination == null) { destination = Point.fromLngLat(point.getLongitude(), point.getLatitude()); mapboxMap.addMarker(new MarkerOptions().position(point)); findRoute(); } else if (waypoint == null) { waypoint = Point.fromLngLat(point.getLongitude(), point.getLatitude()); mapboxMap.addMarker(new MarkerOptions().position(point)); findRoute(); } else { Toast.makeText(this, "Only 2 waypoints supported for this example", Toast.LENGTH_LONG).show(); clearMap(); } return false; } private void clearMap() { if (mapboxMap != null) { mapboxMap.clear(); route = null; destination = null; waypoint = null; navigationMapRoute.updateRouteVisibilityTo(false); navigationMapRoute.updateRouteArrowVisibilityTo(false); } } private void findRoute() { if (origin != null && destination != null) { if (offboardRouter == null) { offboardRouter = new MapboxOffboardRouter( Utils.getMapboxAccessToken(this), this, MapboxNavigationAccounts.getInstance(this)); } else { offboardRouter.cancel(); } if (TurfMeasurement.distance(origin, destination, TurfConstants.UNIT_METERS) > 50) { List<Point> waypoints = new ArrayList<>(); if (waypoint != null) { waypoints.add(waypoint); } RouteOptions.Builder optionsBuilder = applyDefaultParams(RouteOptions.builder()) .accessToken(Utils.getMapboxAccessToken(this)); coordinates(optionsBuilder, origin, waypoints, destination); offboardRouter.getRoute(optionsBuilder.build(), this); } } } /* * Router.Callback */ @Override public void onResponse(@NotNull List<? extends DirectionsRoute> routes) { if (!routes.isEmpty()) { navigationMapRoute.addRoute(routes.get(0)); } } @Override public void onFailure(@NotNull Throwable throwable) { Toast.makeText(this, "Error: " + throwable.getMessage(), Toast.LENGTH_LONG).show(); MapboxLogger.INSTANCE.e(new Message("Router.Callback#onFailure"), throwable); } /* * Activity lifecycle methods */ @Override public void onResume() { super.onResume(); mapView.onResume(); } @Override public void onPause() { super.onPause(); mapView.onPause(); } @Override protected void onStart() { super.onStart(); mapView.onStart(); } @Override protected void onStop() { super.onStop(); mapView.onStop(); } @Override public void onLowMemory() { super.onLowMemory(); mapView.onLowMemory(); } @Override protected void onDestroy() { super.onDestroy(); if (offboardRouter != null) { offboardRouter.cancel(); } if (mapboxMap != null) { mapboxMap.removeOnMapClickListener(this); } mapView.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } }
31,877
https://github.com/darot-chen/flutter-crisp/blob/master/lib/crisp.dart
Github Open Source
Open Source
MIT
2,021
flutter-crisp
darot-chen
Dart
Code
6
44
export 'package:crisp/models/main.dart'; export 'package:crisp/models/user.dart'; export 'package:crisp/crisp_view.dart';
15,907
https://github.com/slim627/meggi/blob/master/src/Meggi/IndexBundle/Resources/views/Basket/basket.html.twig
Github Open Source
Open Source
MIT
null
meggi
slim627
Twig
Code
387
1,715
{% extends 'MeggiIndexBundle::layout.html.twig' %} {% block content %} <div class="h_block h_news"> <div class="wrap"> <h2 class="back">Редактирование заявки</h2> </div> </div> <div class="wrap bc"><span>Редактирование заявки</span> <i></i> Подтверждение заявки</div> <div class="k_tab"> <div class="k_tab_h"> <div class="wrap"> <div class="k_tab_col1"></div> <div class="k_tab_col2"></div> <div class="k_tab_col3">Наименование</div> <div class="k_tab_col4">Колличество</div> <div class="k_tab_col5">Итого</div> </div> </div> {% for product in prodItem if product is not empty%} <div class="k_tab_r" id="{{ product[0].id }}"> <div class="wrap"> <div class="k_tab_col1"><a prod_id="{{ product[0].id }}" class="delete" href="javascript:void(0)">Удалить</a></div> <div class="k_tab_col2"><img src="{{ product[0] | itm_ipw_url('picture') }}" alt=""></div> <div class="k_tab_col3"> <p>{{ product[0].name }}</p> <p>{{ product[0].article }}</p> </div> <div class="k_tab_col4 block-change-quantity"> <a prod_id="{{ product[0].id }}" class="minus" href="javascript:void(0)">-</a> <input prod_id="{{ product[0].id }}" class="quantity-input" type="text" value="{{ product[1] }}"> <a prod_id="{{ product[0].id }}" class="plus" href="javascript:void(0)">+</a> <p>шт.</p> </div> <div class="k_tab_col5 one-prod-sum">{{ (product[0].cost * product[1]) | format_amount }} р.</div> </div> </div> {% endfor %} </div> <div class="total"> <div class="wrap"> {% for flashMessage in app.session.flashbag.get('empty-basket') %} <div style="text-align: center; font-size: 40px">{{ flashMessage }}</div> {% endfor %} {% if finalCostForAllProducts > 0 %} <p>Для обеспечения наличия товара на складе оплатите и потдтвердите оплату в течении 2 суток.</p> <p class="sum">Итого: <span id="full-sum">{{ finalCostForAllProducts | format_amount }} р. (Без НДС)</span></p> <form action="{{ path('confirm') }}" method="post"> <p><input type="submit" value="Оформить"></p> </form> {% endif %} </div> </div> <script> $('.plus').on('click', function(){ var prod_id = this.getAttribute("prod_id"); var inputElement = $(document.getElementById(prod_id)).find('.quantity-input'); var quantity = +inputElement.val()+1; inputElement.val(quantity); changeProductQuantity(prod_id, quantity); }); $('.minus').on('click', function(){ var prod_id = this.getAttribute("prod_id"); var inputElement = $(document.getElementById(prod_id)).find('.quantity-input'); var quantity = +inputElement.val()-1; if(parseInt(quantity) >= 0){ inputElement.val(quantity); changeProductQuantity(prod_id, quantity); } }); $('.quantity-input').on('change', function(){ var prod_id = this.getAttribute('prod_id'); var quantity = this.value; changeProductQuantity(prod_id, quantity); }); function changeProductQuantity(prod_id, quantity){ var sum = 0; $.ajax({ url: '{{ path('change_product_quantity') }}', data: {prod_id : prod_id, quantity : quantity}, dataType : "json", success: function (data) { $(document.getElementById(prod_id)).find('.one-prod-sum').html((parseInt(quantity) * data.cost).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1 ') + ' р.'); var prod_sum_element = $('.one-prod-sum'); for(var i = 0; i < prod_sum_element.length; i++){ sum = sum + parseInt((prod_sum_element[i].textContent).replace(/\s+/g, '')); } var preg_string = /(\d)(?=(\d{3})+(?!\d))/g; $('.sum span').html(sum.toString().replace(preg_string, '$1 ') + ' р.'); $('.span--hide').html(sum.toString().replace(preg_string, '$1 ') + ' р.'); } }); } $('.delete').on('click', function(){ var prod_id = this.getAttribute('prod_id'); this.closest('.k_tab_r').remove(); var preg_string = /(\d)(?=(\d{3})+(?!\d))/g; $.ajax({ url: '{{ path('remove_from_basket') }}', data: {prod_id : prod_id}, dataType : "json", success: function (data) { } }); $.ajax({ url: '{{ path('change_header_basket') }}', data: {param : 1, prod_id : prod_id}, success: function (data) { $('#basket-products-number').html(data.quantityAssortment); $('.span--hide').html(data.finalCostForAllProducts.toString().replace(preg_string, '$1 ') + ' руб.'); $('.sum span').html(data.finalCostForAllProducts.toString().replace(preg_string, '$1 ') + ' р.'); if(!data.quantityAssortment){ document.location.reload(); } } }); }); </script> {% endblock %}
21,294
https://github.com/rbqren000/ZXHookUtil/blob/master/ZXHookUtil/UIKit/UIButton/UIButton+ZXAddAction.h
Github Open Source
Open Source
MIT
2,023
ZXHookUtil
rbqren000
Objective-C
Code
31
131
// // UIButton+ZXAddAction.h // ZXHookUtilDemoDylib // // Created by 李兆祥 on 2019/3/10. // Copyright © 2019 李兆祥. All rights reserved. // #import <UIKit/UIKit.h> typedef void(^ZXActionBlock)(UIButton *button); @interface UIButton (ZXAddAction) -(void)addClickAction:(ZXActionBlock)callBack; @end
22,002
https://github.com/gritwyplay/Storm/blob/master/src/lib/support/shouldRepeat.spec.js
Github Open Source
Open Source
Apache-2.0
2,019
Storm
gritwyplay
JavaScript
Code
435
894
import test from 'tape' import shouldRepeat from './shouldRepeat' test('shouldRepeat - Type', assert => { const expected = 'function' const actual = typeof shouldRepeat assert.equal(actual, expected, 'shouldRepeat should be a function') assert.end() }) // signature context, repeat, index, start test('shouldRepeat - repeat value as an integer', assert => { let repeat = 2 let results = [] // try 5 times, increasing the index as the test runner would do for (let i = 0; i < 5; i++) { results.push(shouldRepeat({}, repeat, i)) } let expected = 2 let actual = results.filter(item => item === true).length assert.equal(actual, expected, 'shouldRepeat should return `true` 2 times') assert.end() }) test('shouldRepeat - repeat value as an object with `times`', assert => { let repeat = { times: 3, } let results = [] // try 5 times, increasing the index as the test runner would do for (let i = 0; i < 5; i++) { results.push(shouldRepeat({}, repeat, i)) } let expected = 3 let actual = results.filter(item => item === true).length assert.equal(actual, expected, 'shouldRepeat should return `true` 3 times') assert.end() }) test('shouldRepeat - repeat value as an object with `seconds`', assert => { let repeat = { seconds: 5, } let results = [] let i = 0 let start = new Date() let end = false // repeat every 500ms let interval = setInterval(() => { const result = shouldRepeat({}, repeat, i, start) // set ending time first time when shouldRepeat is false if (result === false && end === false) { end = new Date() } results.push(result) i++ }, 500) // and try for 10 seconds setTimeout(() => { clearInterval(interval) let expected = 9 let actual = results.filter(item => item === true).length assert.equal( actual, expected, 'shouldRepeat should return `true` 9 times (every 500ms for 5 seconds)' ) let min = 5 let max = 6 actual = (end - start) / 1000 assert.ok( actual >= min && actual < max, 'should take between 5 and 6 seconds to finish (actual: ' + actual + ')' ) assert.end() }, 10 * 1000) }) test('shouldRepeat - repeat value as an object with `until` function', assert => { let context = { counter: 0, } let repeat = { until() { return this.counter >= 10 }, } let results = [] let i = 0 // repeat every 500ms let interval = setInterval(() => { results.push(shouldRepeat(context, repeat, i)) i++ context.counter = i }, 500) // and try for 10 seconds setTimeout(() => { clearInterval(interval) let expected = 10 let actual = results.filter(item => item === true).length assert.equal(actual, expected, 'shouldRepeat should return `true` 10 times') assert.end() }, 10 * 1000) })
12,957
https://github.com/Felind/QRS/blob/master/app/src/main/java/com/felind/qrs/DatabaseHelper.java
Github Open Source
Open Source
Apache-2.0
2,019
QRS
Felind
Java
Code
124
324
package com.felind.qrs; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import static nl.qbusict.cupboard.CupboardFactory.cupboard; public class DatabaseHelper extends SQLiteOpenHelper{ private static final String DATABASE_NAME = "cupboardCodeDB.db"; private static final int DATABASE_VERSION = 1; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } static { // register our models cupboard().register(Code.class); } @Override public void onCreate(SQLiteDatabase db) { // this will ensure that all tables are created cupboard().withDatabase(db).createTables(); // add indexes and other database tweaks in this method if you want } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // this will upgrade tables, adding columns and new tables. // Note that existing columns will not be converted cupboard().withDatabase(db).upgradeTables(); // do migration work if you have an alteration to make to your schema here } }
13,747
https://github.com/jomaleda/typescript-express-rest-template/blob/master/src/app/interfaces/logger.ts
Github Open Source
Open Source
MIT
null
typescript-express-rest-template
jomaleda
TypeScript
Code
36
89
export default interface Logger { Error: (newLog: string) => void; Warn: (newLog: string) => void; Info: (newLog: string) => void; Verbose: (newLog: string) => void; Debug: (newLog: string) => void; Silly: (newLog: string) => void; }
39,739
https://github.com/valery-shinkevich/http4s-poc-api/blob/master/src/main/scala/external/TeamOneHttpApi.scala
Github Open Source
Open Source
MIT
2,021
http4s-poc-api
valery-shinkevich
Scala
Code
51
134
package external import model.DomainModel._ import scala.concurrent.Future trait TeamOneHttpApi { def usersPreferences: UserId => Future[UserPreferences] def productPrice: Product => UserPreferences => Future[Price] } object TeamOneHttpApi { @inline def apply(): TeamOneHttpApi = new TeamOneHttpApi { def usersPreferences: UserId => Future[UserPreferences] = ??? def productPrice: Product => UserPreferences => Future[Price] = ??? } }
25,604
https://github.com/mindaffect/javamindaffectBCI/blob/master/matrixSpellerGdx/core/src/nl/ma/utopia/matrix_speller/screens/ElectrodeQualityScreen.java
Github Open Source
Open Source
MIT
null
javamindaffectBCI
mindaffect
Java
Code
471
1,698
package nl.ma.utopia.matrix_speller.screens; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.GlyphLayout; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import java.io.IOException; import java.util.List; // stuff for the trigger port import java.net.DatagramPacket; import java.net.DatagramSocket; import nl.ma.utopiaserver.messages.SignalQuality; import nl.ma.utopiaserver.UtopiaClient; import nl.ma.utopiaserver.messages.UtopiaMessage; public class ElectrodeQualityScreen extends StimulusScreen { private Color[] _colors={new Color(.05f,.05f,.05f, 1.0f), // bgColor dark GREY new Color(1f,0f,0f, 1.0f), // minColor RED new Color(0f,1f,0f, 1.0f) // maxColor GREEN }; private static final BitmapFont font = new BitmapFont(); // new BitmapFont(Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.fnt"), // Gdx.files.classpath("com/badlogic/gdx/utils/arial-15.png"), // false,true); SpriteBatch batch; private GlyphLayout layout[]; // used for the rendered strings private Texture background; private UtopiaClient client; private int nCh; private float[] quality; private float width; private float height; public ElectrodeQualityScreen(int nCh, UtopiaClient client){ // Initialize variables this.client = client; batch = new SpriteBatch(); width = Gdx.graphics.getWidth(); height = Gdx.graphics.getHeight(); setSymbols(nCh); } public void setSymbols(int nCh){ this.nCh = nCh; float scale = height/ (font.getLineHeight() * 5*5); font.getData().scaleX=scale; font.getData().scaleY=scale; // make the foreground letters layout = new GlyphLayout[nCh]; for ( int xi=0; xi<nCh; xi++){ layout[xi]=new GlyphLayout(); //setText(BitmapFont font, java.lang.CharSequence str, Color color, float targetWidth, int halign, boolean wrap) layout[xi].setText(font,"Ch"+(xi+1)); } //make the background Texture int bgwidth=256; int bgheight=bgwidth; int cornerRadius = (int)(bgwidth*.5f*.9f); int cornerOffset = (int)(bgwidth*.5f); // leave 10% margin between symbols Pixmap pm = new Pixmap(bgwidth, bgheight, Pixmap.Format.RGBA8888); pm.setColor(Color.WHITE); pm.fillCircle(cornerOffset, cornerOffset, cornerRadius); // circle background = new Texture(pm); } @Override // N.B. be sure to synchronize to work cross-thread synchronized public void update(float delta) { // client message stuff... // stuff to do if we changed what's on screen if (client != null && client.isConnected()) { try { // check for new prediction messages from the server List<UtopiaMessage> msgs = client.getNewMessages(); // get the last PredictedTargetProb message for (UtopiaMessage msg : msgs) { if (msg.msgID() == SignalQuality.MSGID) { SignalQuality eq = (SignalQuality) msg; this.quality = eq.signalQuality; } } if( !msgs.isEmpty() ) { System.out.println("Got " + msgs.size() + " messages"); if (this.quality !=null) { System.out.println("Qualities: " + this.quality); } } } catch (IOException e) { e.printStackTrace(); } } } @Override public void draw() { int nCh= this.nCh; if ( quality!=null ) nCh=Math.min(nCh,quality.length); float xstep = width / (nCh+1); float ystep = height / 5; float bsize = Math.min(xstep, ystep); Gdx.gl.glClearColor(WINDOWBACKGROUNDCOLOR.r,WINDOWBACKGROUNDCOLOR.g,WINDOWBACKGROUNDCOLOR.b,WINDOWBACKGROUNDCOLOR.a); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); int si = 0, yi=1; for (int xi = 0; xi < nCh; xi++) { float x = (xi + .5f) * xstep; float y = height - (yi + 1.5f) * ystep; float noisestr=1f;//(float)Math.random(); if( quality!=null && xi<quality.length ) noisestr=quality[xi]; noisestr=noisestr>1f?1f:noisestr; noisestr=noisestr<0f?0f:noisestr; // limit to 0-1 // color for this output is a linear mix btw red and green Color curColor = new Color(0,0,0,1); curColor.r= _colors[1].r*noisestr + _colors[2].r*(1-noisestr); curColor.g= _colors[1].g*noisestr + _colors[2].g*(1-noisestr); curColor.b= _colors[1].b*noisestr + _colors[2].b*(1-noisestr); batch.setColor(curColor);//curColor); // draw the block background batch.draw(background, x, y, xstep, ystep);//bsize, bsize); // draw the foreground text font.draw(batch, layout[xi], x+xstep*.4f, y+ystep*.6f); } // reset the current pen color batch.setColor(Color.WHITE); batch.end(); } };
10,000
https://github.com/Aman2244-hub/ducss-site-old/blob/master/project/events/migrations/0001_initial.py
Github Open Source
Open Source
MIT
2,020
ducss-site-old
Aman2244-hub
Python
Code
101
550
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Event' db.create_table('events_event', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=128)), ('slug', self.gf('django.db.models.fields.SlugField')(max_length=50)), ('date', self.gf('django.db.models.fields.DateTimeField')()), ('location', self.gf('django.db.models.fields.CharField')(max_length=128)), ('description', self.gf('django.db.models.fields.TextField')()), ('images', self.gf('django.db.models.fields.files.ImageField')(max_length=100)), )) db.send_create_signal('events', ['Event']) def backwards(self, orm): # Deleting model 'Event' db.delete_table('events_event') models = { 'events.event': { 'Meta': {'object_name': 'Event'}, 'date': ('django.db.models.fields.DateTimeField', [], {}), 'description': ('django.db.models.fields.TextField', [], {}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'images': ('django.db.models.fields.files.ImageField', [], {'max_length': '100'}), 'location': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '128'}) } } complete_apps = ['events']
32,123
https://github.com/PlexPt/summingbird/blob/master/summingbird-scalding/src/main/scala/com/twitter/summingbird/scalding/batch/BatchedStore.scala
Github Open Source
Open Source
Apache-2.0
null
summingbird
PlexPt
Scala
Code
1,986
4,946
/* Copyright 2013 Twitter, 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.twitter.summingbird.scalding.batch import com.twitter.algebird.bijection.BijectedSemigroup import com.twitter.algebird.{ Monoid, Semigroup } import com.twitter.algebird.{ Universe, Empty, Interval, Intersection, InclusiveLower, ExclusiveUpper, InclusiveUpper } import com.twitter.algebird.monad.{ StateWithError, Reader } import com.twitter.bijection.{ Bijection, ImplicitBijection } import com.twitter.scalding.{ Dsl, Mode, TypedPipe, IterableSource, MapsideReduce, TupleSetter, TupleConverter } import com.twitter.scalding.typed.Grouped import com.twitter.summingbird.scalding._ import com.twitter.summingbird.scalding import com.twitter.summingbird._ import com.twitter.summingbird.option._ import com.twitter.summingbird.batch.{ BatchID, Batcher, Timestamp, IteratorSums, PrunedSpace } import cascading.flow.FlowDef import org.slf4j.LoggerFactory import StateWithError.{ getState, putState, fromEither } import com.twitter.scalding.serialization.macros.impl.BinaryOrdering /** * This is the same as scala's Tuple2, except the hashCode is a val. * We do this so when the tuple2 is placed in the map we won't caculate the hash code * unnecessarily several times as the map grows or is transformed. */ case class LTuple2[T, U](_1: T, _2: U) { override val hashCode: Int = scala.runtime.ScalaRunTime._hashCode(this) override def equals(other: Any): Boolean = other match { case LTuple2(oT1, oT2) => hashCode == other.hashCode && _1 == oT1 && _2 == oT2 case _ => false } } trait BatchedStore[K, V] extends scalding.Store[K, V] { self => /** The batcher for this store */ def batcher: Batcher implicit def ordering: Ordering[K] /** * Override select if you don't want to materialize every * batch. Note that select MUST return a list containing the final * batch in the supplied list; otherwise data would be lost. */ def select(b: List[BatchID]): List[BatchID] = b /** * Override this to set up store pruning, by default, no (key,value) pairs * are pruned. This is a house keeping function to permanently remove entries * matching a criteria. */ def pruning: PrunedSpace[(K, V)] = PrunedSpace.neverPruned /** * For (firstNonZero - 1) we read empty. For all before we error on read. For all later, we proxy * On write, we throw if batchID is less than firstNonZero */ def withInitialBatch(firstNonZero: BatchID): BatchedStore[K, V] = new scalding.store.InitialBatchedStore(firstNonZero, self) /** * Get the most recent last batch and the ID (strictly less than the input ID) * The "Last" is the stream with only the newest value for each key, within the batch * combining the last from batchID and the deltas from batchID.next you get the stream * for batchID.next */ def readLast(exclusiveUB: BatchID, mode: Mode): Try[(BatchID, FlowProducer[TypedPipe[(K, V)]])] /** Record a computed batch of code */ def writeLast(batchID: BatchID, lastVals: TypedPipe[(K, V)])(implicit flowDef: FlowDef, mode: Mode): Unit @transient private val logger = LoggerFactory.getLogger(classOf[BatchedStore[_, _]]) /** The writeLast method as a FlowProducer */ private def writeFlow(batches: List[BatchID], lastVals: TypedPipe[(BatchID, (K, V))]): FlowProducer[Unit] = { logger.info("writing batches: {}", batches) Reader[FlowInput, Unit] { case (flow, mode) => // make sure we checkpoint to disk to avoid double computation: val checked = if (batches.size > 1) lastVals.forceToDisk else lastVals batches.foreach { batchID => val thisBatch = checked.filter { case (b, kv) => (b == batchID) && !pruning.prune(kv, batcher.latestTimeOf(b)) } writeLast(batchID, thisBatch.values)(flow, mode) } } } protected def sumByBatches[K1, V1: Semigroup](ins: TypedPipe[(Timestamp, (K1, V1))], capturedBatcher: Batcher, commutativity: Commutativity): TypedPipe[(LTuple2[K1, BatchID], (Timestamp, V1))] = { implicit val timeValueSemigroup: Semigroup[(Timestamp, V1)] = IteratorSums.optimizedPairSemigroup[Timestamp, V1](1000) val inits = ins.map { case (t, (k, v)) => val batch = capturedBatcher.batchOf(t) (LTuple2(k, batch), (t, v)) } (commutativity match { case Commutative => inits.sumByLocalKeys case NonCommutative => inits }) } /** * For each batch, collect up values with the same key on mapside * before the keys are expanded. */ override def partialMerge[K1](delta: PipeFactory[(K1, V)], sg: Semigroup[V], commutativity: Commutativity): PipeFactory[(K1, V)] = { logger.info("executing partial merge") implicit val semi = sg val capturedBatcher = batcher commutativity match { case Commutative => delta.map { flow => flow.map { typedP => sumByBatches(typedP, capturedBatcher, Commutative) .map { case (LTuple2(k, _), (ts, v)) => (ts, (k, v)) } } } case NonCommutative => delta } } /** * we are guaranteed to have sufficient input and deltas to cover these batches * and that the batches are given in order */ private def mergeBatched(inBatch: BatchID, input: FlowProducer[TypedPipe[(K, V)]], deltas: FlowToPipe[(K, V)], readTimespan: Interval[Timestamp], commutativity: Commutativity, reducers: Int)(implicit sg: Semigroup[V]): FlowToPipe[(K, (Option[V], V))] = { // get the batches read from the readTimespan val batchIntr = batcher.batchesCoveredBy(readTimespan) val batches = BatchID.toIterable(batchIntr).toList val finalBatch = batches.last // batches won't be empty, ensured by atLeastOneBatch method val filteredBatches = select(batches).sorted assert(filteredBatches.contains(finalBatch), "select must not remove the final batch.") import IteratorSums._ // get the groupedSum, partials function logger.debug("Previous written batch: {}, computing: {}", inBatch.asInstanceOf[Any], batches) def prepareOld(old: TypedPipe[(K, V)]): TypedPipe[(K, (BatchID, (Timestamp, V)))] = old.map { case (k, v) => (k, (inBatch, (Timestamp.Min, v))) } val capturedBatcher = batcher //avoid a closure on the whole store def prepareDeltas(ins: TypedPipe[(Timestamp, (K, V))]): TypedPipe[(K, (BatchID, (Timestamp, V)))] = sumByBatches(ins, capturedBatcher, commutativity) .map { case (LTuple2(k, batch), (ts, v)) => (k, (batch, (ts, v))) } /** * Produce a merged stream such that each BatchID, Key pair appears only one time. */ def mergeAll(all: TypedPipe[(K, (BatchID, (Timestamp, V)))]): TypedPipe[(K, (BatchID, (Option[Option[(Timestamp, V)]], Option[(Timestamp, V)])))] = { // Make sure to use sumOption on V implicit val timeValueSemigroup: Semigroup[(Timestamp, V)] = IteratorSums.optimizedPairSemigroup[Timestamp, V](1000) val grouped = all.group.withReducers(reducers) // We need the tuples to be sorted by batch ID to compute partials, and by time if the // monoid is not commutative. Although sorting by time is adequate for both, sorting // by batch is more efficient because the reducers' input is almost sorted. val sorted = commutativity match { case NonCommutative => grouped.sortBy { case (_, (t, _)) => t }(BinaryOrdering.ordSer[com.twitter.summingbird.batch.Timestamp]) case Commutative => grouped.sortBy { case (b, (_, _)) => b }(BinaryOrdering.ordSer[BatchID]) } sorted .mapValueStream { it: Iterator[(BatchID, (Timestamp, V))] => // each BatchID appears at most once, so it fits in RAM val batched: Map[BatchID, (Timestamp, V)] = groupedSum(it).toMap partials((inBatch :: batches).iterator.map { bid => (bid, batched.get(bid)) }) } .toTypedPipe } /** * There is no flatten on Option, this adds it */ def flatOpt[T](optopt: Option[Option[T]]): Option[T] = optopt.flatMap(identity) // This builds the format we write to disk, which is the total sum def toLastFormat(res: TypedPipe[(K, (BatchID, (Option[Option[(Timestamp, V)]], Option[(Timestamp, V)])))]): TypedPipe[(BatchID, (K, V))] = res.flatMap { case (k, (batchid, (prev, v))) => val totalSum = Semigroup.plus[Option[(Timestamp, V)]](flatOpt(prev), v) totalSum.map { case (_, sumv) => (batchid, (k, sumv)) } } // This builds the format we send to consumer nodes def toOutputFormat(res: TypedPipe[(K, (BatchID, (Option[Option[(Timestamp, V)]], Option[(Timestamp, V)])))]): TypedPipe[(Timestamp, (K, (Option[V], V)))] = res.flatMap { case (k, (batchid, (optopt, opt))) => opt.map { case (ts, v) => val prev = flatOpt(optopt).map(_._2) (ts, (k, (prev, v))) } } // Now in the flow-producer monad; do it: for { pipeInput <- input pipeDeltas <- deltas // fork below so scalding can make sure not to do the operation twice merged = mergeAll(prepareOld(pipeInput) ++ prepareDeltas(pipeDeltas)).fork lastOut = toLastFormat(merged) _ <- writeFlow(filteredBatches, lastOut) } yield toOutputFormat(merged) } /** * This gives the batches needed to cover the requested input * This will always be non-empty */ final def timeSpanToBatches: PlannerOutput[List[BatchID]] = StateWithError({ in: FactoryInput => val (timeSpan, _) = in // This object combines some common scalding batching operations: val batchOps = new BatchedOperations(batcher) (batchOps.coverIt(timeSpan).toList match { case Nil => Left(List("Timespan is covered by Nil: %s batcher: %s".format(timeSpan, batcher))) case list => Right((in, list)) }) }) /** * This is the monadic version of readLast, returns the BatchID actually on disk */ final def planReadLast: PlannerOutput[(BatchID, FlowProducer[TypedPipe[(K, V)]])] = for { batches <- timeSpanToBatches tsMode <- getState[FactoryInput] bfp <- fromEither(readLast(batches.min, tsMode._2)) } yield bfp /** * Adjist the Lower bound of the interval */ private def setLower(lb: InclusiveLower[Timestamp], interv: Interval[Timestamp]): Interval[Timestamp] = interv match { case u @ ExclusiveUpper(_) => lb && u case u @ InclusiveUpper(_) => lb && u case Intersection(_, u) => lb && u case Empty() => Empty() case _ => lb // Otherwise the upperbound is infinity. } /** * Reads the input data after the last batch written. * * Returns: * - the BatchID of the last batch written * - the snapshot of the store just before this state * - the data from this input covering all the time SINCE the last snapshot */ final def readAfterLastBatch[T](input: PipeFactory[T]): PlannerOutput[(BatchID, FlowProducer[TypedPipe[(K, V)]], FlowToPipe[T])] = { // StateWithError lacks filter, so it can't unpack tuples (scala limitation) // so unfortunately, this code has a lot of manual tuple unpacking for that reason for { // Get the BatchID and data for the last snapshot, bidFp <- planReadLast (lastBatch, lastSnapshot) = bidFp // Get latest time for the last batch written to store lastTimeWrittenToStore = batcher.latestTimeOf(lastBatch) // Now get the first timestamp that we need input data for. firstDeltaTimestamp = lastTimeWrittenToStore.next // Get the requested timeSpan. tsMode <- getState[FactoryInput] (timeSpan, mode) = tsMode // Get the batches covering the requested timeSpan so we can get the last time stamp we need to request. batchOps = new BatchedOperations(batcher) // Get the total time we want to cover. If the lower bound of the requested timeSpan // is not the firstDeltaTimestamp, adjust it to that. deltaTimes: Interval[Timestamp] = setLower(InclusiveLower(firstDeltaTimestamp), timeSpan) // Try to read the range covering the time we want; get the time we can completely // cover and the data from input in that range. readTimeFlow <- fromEither(batchOps.readAvailableTimes(deltaTimes, mode, input)) (readDeltaTimestamps, readFlow) = readTimeFlow // Make sure that the time we can read includes the time just after the last // snapshot. We can't roll the store forward without this. _ <- fromEither[FactoryInput](if (readDeltaTimestamps.contains(firstDeltaTimestamp)) Right(()) else Left(List("Cannot load initial timestamp " + firstDeltaTimestamp.toString + " of deltas " + " at " + this.toString + " only " + readDeltaTimestamps.toString))) // Record the timespan we actually read. _ <- putState((readDeltaTimestamps, mode)) } yield (lastBatch, lastSnapshot, readFlow) } /** * This combines the current inputs along with the last checkpoint on disk to get a log * of all deltas with a timestamp * This is useful to leftJoin against a store. * TODO: This should not limit to batch boundaries, the batch store * should handle only writing the data for full batches, but we can materialize * more data if it is needed downstream. * Note: the returned time interval NOT include the time of the snapshot data point * (which is exactly 1 millisecond before the start of the interval). */ def readDeltaLog(delta: PipeFactory[(K, V)]): PipeFactory[(K, V)] = readAfterLastBatch(delta).map { case (actualLast, snapshot, deltaFlow2Pipe) => val snapshotTs = batcher.latestTimeOf(actualLast) Scalding.merge( snapshot.map { pipe => pipe.map { (snapshotTs, _) } }, deltaFlow2Pipe) } /** * This is for ensuring there is at least one batch coverd by readTimespan. This is * required by mergeBatched */ private def atLeastOneBatch(readTimespan: Interval[Timestamp]) = fromEither[FactoryInput] { if (batcher.batchesCoveredBy(readTimespan) == Empty()) { Left(List("readTimespan is not convering at least one batch: " + readTimespan.toString)) } else { Right(()) } } /** * instances of this trait MAY NOT change the logic here. This always follows the rule * that we look for existing data (avoiding reading deltas in that case), then we fall * back to the last checkpointed output by calling readLast. In that case, we compute the * results by rolling forward */ final override def merge(delta: PipeFactory[(K, V)], sg: Semigroup[V], commutativity: Commutativity, reducers: Int): PipeFactory[(K, (Option[V], V))] = for { // get requested timespan before readAfterLastBatch tsModeRequested <- getState[FactoryInput] (tsRequested, _) = tsModeRequested readBatchedResult <- readAfterLastBatch(delta) (actualLast, snapshot, deltaFlow2Pipe) = readBatchedResult // get the actual timespan read by readAfterLastBatch tsModeRead <- getState[FactoryInput] (tsRead, _) = tsModeRead _ <- atLeastOneBatch(tsRead) /** * Once we have read the last snapshot and the available batched blocks of delta, just merge */ merged = mergeBatched(actualLast, snapshot, deltaFlow2Pipe, tsRead, commutativity, reducers)(sg) prunedFlow = Scalding.limitTimes(tsRequested && tsRead, merged) } yield (prunedFlow) }
34,605
https://github.com/exabrial/speakeasy/blob/master/src/main/java/com/github/exabrial/speakeasy/primitives/PasswordHasher.java
Github Open Source
Open Source
Apache-2.0
2,018
speakeasy
exabrial
Java
Code
265
440
/** * Copyright [2018] [Jonathan S. Fisher] * * 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.github.exabrial.speakeasy.primitives; /** * Similar to a Fingerprint, a PasswordHash is a deterministic hash-function * who's fixed-length output is stable for a given arbitrarily-sized input. * Whereas a Fingerprint is designed to be very fast, a PasswordHash is designed * to be very slow. This makes it difficult for an attacker to brute force * search a plaitnext for a given password hash. */ public interface PasswordHasher { /** * Compute the hash for a password. * * @param password * plaintext password * @return hash */ String hashPassword(String password); /** * Checks to see if a plaintext password hashes to the given hash. TODO: Turn on * logging at the trace level to receive stack traces for errors. * * @param password * plaintext password * @param hash * the hash to compare against * @return true if the resulting password hash equals the provided hash, false * if it does not, or false if there is an error. */ boolean checkPassword(String password, String hash); }
6,708
https://github.com/aifa-gov-it/invoices-processor/blob/master/src/main/java/it/gov/aifa/invoice_processor/entity/invoice/Attachment.java
Github Open Source
Open Source
MIT
null
invoices-processor
aifa-gov-it
Java
Code
170
628
package it.gov.aifa.invoice_processor.entity.invoice; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.persistence.Entity; import javax.persistence.Lob; import javax.persistence.Table; import javax.persistence.Transient; import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.NotBlank; import org.hibernate.validator.constraints.NotEmpty; import org.springframework.validation.annotation.Validated; import it.gov.aifa.invoice_processor.entity.impl.AbstractInvoiceReferenceEntity; @Entity @Table(name = "MEF_ALLEGATO_FATTURA") @Validated public class Attachment extends AbstractInvoiceReferenceEntity { private static final long serialVersionUID = 3928788589828828163L; private String compressionAlgorithm; @NotEmpty private byte[] data; private String description; private String format; @NotBlank private String name; public Attachment() { super(); } public Attachment(Invoice invoice) { super(invoice); } @Override @Transient protected List<String> getAdditionalIdValues() { List<String> additionalIdValues = new ArrayList<>(); if(StringUtils.isNotBlank(name)) additionalIdValues.add(name); return Collections.unmodifiableList(additionalIdValues); } public String getCompressionAlgorithm() { return compressionAlgorithm; } public byte[] getData() { return data; } @Lob public String getDescription() { return description; } public String getFormat() { return format; } public String getName() { return name; } public void setCompressionAlgorithm(String compressionAlgorithm) { this.compressionAlgorithm = compressionAlgorithm; } public void setData(byte[] data) { this.data = data; } public void setDescription(String description) { this.description = description; } public void setFormat(String format) { this.format = format; } public void setName(String name) { this.name = name; } }
21,119
https://github.com/kervinck/gigatron-rom/blob/master/Contrib/psr/multiply/src/half-square.asm.py
Github Open Source
Open Source
BSD-2-Clause
2,023
gigatron-rom
kervinck
Python
Code
894
3,692
"""Implementation of multiplication that uses the following identity: a * b = (a² + b² - (a-b)²)/2 We use this to implement multiplication of nibbles, and from that multiplication of bytes. We make use of a lookup table of ⌊n²/2⌋ for n in the range [-15,15], and calculate (⌊a²/2⌋ + ⌊b²/2⌋ - ⌊(a-b)²/2⌋ + (a & b & 1)) - The a & b & 1 term compensates for the fact that (⌊a²/2⌋ + ⌊b²/2⌋ - ⌊(a-b)²/2⌋) is off by one when both a and b are odd. We also have a right-shift by four table. Memory is used as follows: (0x1,0x2) = Result (would be vAC in a real sys function) (0x3) = very brief temporary storage (would be vTmp) (0x4, 0x5) = A, B - Operands, would be sysArgs[0:2] - untouched. (0x6..) = Variables. Would be sysArgs[2:] - but we try to leave the last value untouched. """ import sys from itertools import chain, count import asm from asm import ( AC, C, X, Xpp, Y, adda, align, anda, bne, bra, define, end, fillers, label, ld, ora, pc, st, suba, writeRomFiles, xora, ) DEBUG = False # Set to True to get debugging output # I'm keen to avoid using too many variables. # The comments that this outputs should help me keep things clean class VariableTracker: def __init__(self, size=12, initial_x=6): self._x = initial_x self._current_bindings = ["unused"] * size @staticmethod def _comment_next_instruction(message): # Hack to add a comment on the next instruction, not the previous. address = max(0, asm._romSize) line_comments = asm._comments.setdefault(address, []) line_comments.append(f";{message}") def define(self, name, address, *, suppress_comment=False): assert self._current_bindings[address] in ("dead", "unused") self._current_bindings[address] = name if not suppress_comment: self._comment_next_instruction(f"[${address:02x}] <- {name}.") if DEBUG: print(self) return address def __repr__(self) -> str: return f"{self._current_bindings} x={self._x}" def reset_x(self, new_x): self._x = new_x return new_x def define_from_x_postincrement(self, name, *, suppress_comment=False): assert self._current_bindings[self._x] in ("dead", "unused"), self self._current_bindings[self._x] = name if not suppress_comment: C(f"[${self._x:02x}] <- {name}; x <- {self._x + 1}") self._x += 1 if DEBUG: print(self) def read(self, name, *, suppress_comment=False): if not suppress_comment: self._comment_next_instruction(f"({name})") return self._current_bindings.index(name) def update(self, name, *, suppress_comment=False): if not suppress_comment: self._comment_next_instruction(f"Update {name}") return self._current_bindings.index(name) def kill(self, name, *, suppress_comment=False): address = self._current_bindings.index(name) self._current_bindings[address] = "dead" if not suppress_comment: self._comment_next_instruction(f"({name})") return address def get_name(self, address): return self._current_bindings[address] def assert_x(self, n): assert self._x == n, f"Assert x: have {self._x}, but wanted {n}. {self}" ## Lookup tables are woven through the code, and we need to avoid them. _emit_half_square = lambda i: st(i, [Y, Xpp]) class LookupTableManager: half_square_table = [ (i, _emit_half_square, i**2 // 2, f"[x++] <- ⌊${i:x}²/2⌋") for i in range(0x10) ] half_square_table_inverted = [ (i & 0xFF, _emit_half_square, (i**2 // 2), f"[x++] <- ⌊(${i:x})²/2⌋") for i in range(-1, -0x10, -1) ] right_shift_table = [ (i * 16, ld, i, f"Right-shift by four lookup for ${i:x}x") for i in range(1, 0x10) ] def __init__(self): all_entries = chain( self.half_square_table, self.half_square_table_inverted, self.right_shift_table, ) self.table_entries = iter(sorted(all_entries)) self.next_entry = next(self.table_entries) def emit_next_entry(self): address, emit, value, comment = self.next_entry assert address >= ( pc() & 0xFF ), f"Next address ({address:x}) is before the current PC ({pc() & 0xff:x}) - we missed it!" fillers(until=address) while address == pc() & 0xFF: emit(value) C(comment) address, emit, value, comment = next(self.table_entries) self.next_entry = address, emit, value, comment def finish_tables(self): address, emit, value, comment = self.next_entry assert address >= ( pc() & 0xFF ), f"Next address ({address:x}) is before the current PC ({pc() & 0xff:x}) - we missed it!" fillers(until=address) emit(value) C(comment) for address, emit, value, comment in self.table_entries: fillers(until=address) emit(value) C(comment) vars = VariableTracker() labels = (f".multiply.{i}" for i in count(1)) tables = LookupTableManager() def right_shift(*, emit_next_table_entry=False): next_label = next(labels) bne(AC) C("ac >>= 4") bra(next_label) ld(0) # A nop, in this case if emit_next_table_entry: tables.emit_next_entry() label(next_label) def lookup_and_store_half_square( src, operand_name=None, *, kill=False, emit_next_table_entry=False ): assert (src is not AC) or (operand_name is not None) operand_name = operand_name or src target_name = ( f"⌊{operand_name}²/2⌋" if " " not in operand_name else f"⌊({operand_name})²/2⌋" ) if src is AC: bra(AC) elif kill: bra([vars.kill(src, suppress_comment=True)]) else: bra([vars.read(src, suppress_comment=True)]) vars.define_from_x_postincrement(target_name) next_label = next(labels) bra(next_label) if emit_next_table_entry: tables.emit_next_entry() label(next_label) ### Code starts here define("A", vars.define("A", 0x4, suppress_comment=True)) define("B", vars.define("B", 0x5, suppress_comment=True)) align(0x100) tables.emit_next_entry() label("start") ld([vars.read("A")]) anda(0x0F) st([vars.define("A-low", 0x1)]) xora([vars.read("A")]) right_shift() st([vars.define("A-high", 0x6)]) ld([vars.read("B")]) anda(0xF0) right_shift(emit_next_table_entry=True) st([vars.define("B-high", 0x3)]) # Start product of high-nibbles ld(0, Y) ld(vars.reset_x(0x07), X) suba([vars.read("A-high")]) lookup_and_store_half_square(AC, "A-high - B-high") ld([vars.read("B-high")]) anda([vars.read("A-high")]) anda(0x01) suba([vars.kill("⌊(A-high - B-high)²/2⌋")]) st([vars.define("high-byte total", 0x02)]) # A-low * B-high ld([vars.read("A-low")]) suba([vars.read("B-high")]) lookup_and_store_half_square(AC, "A-low - B-high", emit_next_table_entry=True) ld([vars.read("B-high")]) lookup_and_store_half_square("B-high", kill=True) lookup_and_store_half_square("A-low", emit_next_table_entry=True) anda([vars.read("A")]) anda(0x01) adda([vars.read("⌊A-low²/2⌋")]) adda([vars.read("⌊B-high²/2⌋")]) suba([vars.kill("⌊(A-low - B-high)²/2⌋")]) st([vars.define("A-low * B-high", 0x03)]) anda(0x0F) st([vars.define("low(A-low * B-high)", 0x07)]) xora([vars.kill("A-low * B-high")]) right_shift(emit_next_table_entry=True) adda([vars.kill("⌊B-high²/2⌋")]) adda([vars.read("high-byte total")]) st([vars.update("high-byte total")]) ld(vars.reset_x(0x8), X) ld([vars.read("B")]) anda(0x0F) st([vars.define("B-low", 0x03)]) suba([vars.read("A-high")]) print(vars) lookup_and_store_half_square( AC, operand_name="B-low - A-high", emit_next_table_entry=True ) lookup_and_store_half_square("B-low", kill=True) ld([vars.read("A-high")]) ld(vars.reset_x(0x6), X) lookup_and_store_half_square("A-high", kill=True, emit_next_table_entry=True) anda([vars.read("B")]) anda(0x01) adda([vars.read("⌊B-low²/2⌋")]) adda([vars.read("⌊A-high²/2⌋")]) suba([vars.kill("⌊(B-low - A-high)²/2⌋")]) st([vars.define("B-low * A-high", 0x03)]) anda(0x0F) st([vars.define("low(B-low * A-high)", 0x08)]) xora([vars.kill("B-low * A-high")]) right_shift(emit_next_table_entry=True) adda([vars.kill("⌊A-high²/2⌋")]) adda([vars.read("high-byte total")]) st([vars.update("high-byte total")]) # Product of low-nibbles ld(vars.reset_x(6), X) ld([vars.read("B")]) anda(0x0F) # Because we lost B-low suba([vars.read("A-low")]) lookup_and_store_half_square( AC, operand_name="B-low - A-low", emit_next_table_entry=True ) ld([vars.kill("A-low")]) anda([vars.read("B")]) anda(0x01) adda([vars.kill("⌊B-low²/2⌋")]) adda([vars.kill("⌊A-low²/2⌋")]) suba([vars.kill("⌊(B-low - A-low)²/2⌋")]) st([vars.define("A-low * B-low", 0x3)]) print(vars) # Final sum - 23 cycles anda(0xF) st([vars.define("result low nibble", 0x01)]) xora([vars.kill("A-low * B-low")]) right_shift(emit_next_table_entry=True) adda([vars.kill("low(A-low * B-high)")]) adda([vars.kill("low(B-low * A-high)")]) st([vars.define("temp", 0x3)]) adda(AC) adda(AC) adda(AC) adda(AC) ora([vars.kill("result low nibble")]) st([vars.define("low(result)", 0x01)]) ld([vars.kill("temp")]) anda(0xF0) right_shift(emit_next_table_entry=True) adda([vars.kill("high-byte total")]) st([vars.define("high(result)", 0x2)]) label("end") ld(AC, AC) tables.finish_tables() end() define("result", 0x01) if __name__ == "__main__": writeRomFiles(sys.argv[0])
26,936
https://github.com/jpfreitasalvi/Exercicios-Pascal-Cap03/blob/master/cap3_ex24.pas
Github Open Source
Open Source
MIT
2,020
Exercicios-Pascal-Cap03
jpfreitasalvi
Pascal
Code
98
270
Program qtd_dinheiro; {Faça um programa que receba a quantidade de dinheiro em reais que uma pessoa que vai viajar possui. Ela vai passar por vários países e precisa converter seu dinheiro em dólares, marco alemão e libra esterlina. Sabe-se que a cotação do dólar é de R$ 1,80; do marco alemão, de R$ 2,00; e da libra esterlina, de R$ 3,57. O programa deve fazer as conversões e mostrá-las.} var qtd_dinheiro : real; Begin write('Informe o valor em reais: '); readln(qtd_dinheiro); writeln('Você terá U$D',qtd_dinheiro / 1.80:0:2); writeln('Você terá M$A',qtd_dinheiro / 2.0:0:2); writeln('Você terá LB$',qtd_dinheiro / 3.57:0:2); readln; End.
20,020
https://github.com/Veratics/Maternity-Tracker/blob/master/Dashboard/va.gov.artemis.ui.data/Brokers/NonVACare/NonVACareRepository.cs
Github Open Source
Open Source
Apache-2.0
2,021
Maternity-Tracker
Veratics
C#
Code
651
2,104
// Originally submitted to OSEHRA 2/21/2017 by DSS, Inc. // Authored by DSS, Inc. 2014-2017 using VA.Gov.Artemis.Commands.Dsio.Base; using VA.Gov.Artemis.Commands.Dsio.NonVA; using VA.Gov.Artemis.UI.Data.Brokers.Common; using VA.Gov.Artemis.UI.Data.Models.NonVACare; using VA.Gov.Artemis.Vista.Broker; namespace VA.Gov.Artemis.UI.Data.Brokers.NonVACare { /// <summary> /// Access Non-VA Care Items /// </summary> public class NonVACareRepository: RepositoryBase, INonVACareRepository { public NonVACareRepository(IRpcBroker newBroker): base(newBroker) { } /// <summary> /// Gets a full list of the items, with paging /// </summary> /// <param name="page">The page desired</param> /// <param name="itemsPerPage">The number of items per page</param> /// <returns>An operation result which contains a list of items</returns> public NonVACareItemsResult GetAll(int page, int itemsPerPage) { // *** NOTE: Includes inactive *** return GetList("", page, itemsPerPage, true); } /// <summary> /// Gets a list of items matching a particular type, with paging /// </summary> /// <param name="itemType">The type of items to get</param> /// <param name="page">The page desired</param> /// <param name="itemsPerPage">The number of itemsper page</param> /// <returns>An operation result which contains a list of items</returns> public NonVACareItemsResult GetList(NonVACareItemType itemType, int page, int itemsPerPage, bool includeInactive) { NonVACareItemsResult returnResult; // *** Make the call based on desired item type *** switch (itemType) { case NonVACareItemType.Facility: returnResult = GetList("F", page, itemsPerPage, includeInactive); break; case NonVACareItemType.Provider: returnResult = GetList("P", page, itemsPerPage, includeInactive); break; default: returnResult = GetList("", page, itemsPerPage, includeInactive); break; } return returnResult; } private NonVACareItemsResult GetList(string commandArgument, int page, int itemsPerPage, bool includeInactive) { // *** Get a list of all non va items *** NonVACareItemsResult result = new NonVACareItemsResult(); // *** Create the command *** DsioGetExternalEntityCommand command = new DsioGetExternalEntityCommand(broker); // *** Add the arguments *** command.AddCommandArguments(commandArgument, page, itemsPerPage); // *** Execute the command *** RpcResponse response = command.Execute(); // *** Gather the results *** result.Success = (response.Status == RpcResponseStatus.Success); result.Message = response.InformationalMessage; // *** Check for success *** if (result.Success) { result.TotalResults = command.TotalResults; if (result.TotalResults > 0) { // *** Go through each returned item *** foreach (DsioNonVAItem dsioItem in command.NonVAEntities) { NonVACareItem item = GetNonVACareItem(dsioItem); // *** Add if active or including inactive *** if ((item.Inactive == false) || (includeInactive)) result.Items.Add(item); } } } return result; } private NonVACareItem GetNonVACareItem(DsioNonVAItem dsioItem) { // *** Create a strongly typed item *** NonVACareItem item = new NonVACareItem() { Ien = dsioItem.Ien, Name = dsioItem.EntityName, OriginalName = dsioItem.EntityName, AddressLine1 = dsioItem.Address.StreetLine1, AddressLine2 = dsioItem.Address.StreetLine2, City = dsioItem.Address.City, State = dsioItem.Address.State, ZipCode = dsioItem.Address.ZipCode, //Inactive = (dsioItem.Inactive == "YES") ? true : false, Inactive = (dsioItem.Inactive == "1") ? true : false, PrimaryContact = dsioItem.PrimaryContact }; if (dsioItem.TelephoneList != null) foreach (DsioTelephone dsioTel in dsioItem.TelephoneList) { if (dsioTel.Usage == DsioTelephone.WorkPhoneUsage) item.PhoneNumber = dsioTel.Number; else if (dsioTel.Usage == DsioTelephone.FaxUsage) item.FaxNumber = dsioTel.Number; } switch (dsioItem.EntityType) { case "PROVIDER": case "P": item.ItemType = NonVACareItemType.Provider; break; case "FACILITY": case "F": item.ItemType = NonVACareItemType.Facility; break; default: item.ItemType = NonVACareItemType.Provider; break; } return item; } public IenResult SaveItem(NonVACareItem item) { // *** Creates a new Non VA Care Item *** IenResult result = new IenResult(); // *** Create the command *** DsioSaveExternalEntityCommand command = new DsioSaveExternalEntityCommand(broker); // *** Create the entity to save *** DsioNonVAItem dsioItem = new DsioNonVAItem(); //dsioItem.OriginalEntityName = item.OriginalName; dsioItem.Ien = item.Ien; dsioItem.EntityName = item.Name; dsioItem.Address.StreetLine1 = item.AddressLine1; dsioItem.Address.StreetLine2 = item.AddressLine2; dsioItem.Address.City = item.City; dsioItem.Address.State = item.State; dsioItem.Address.ZipCode = item.ZipCode; dsioItem.TelephoneList.Add(new DsioTelephone(){Number = item.PhoneNumber, Usage = DsioTelephone.WorkPhoneUsage}); dsioItem.TelephoneList.Add(new DsioTelephone() { Number = item.FaxNumber, Usage = DsioTelephone.FaxUsage }); dsioItem.PrimaryContact = item.PrimaryContact; //dsioItem.Inactive = (item.Inactive) ? "YES" : "NO"; dsioItem.Inactive = (item.Inactive) ? "1" : "0"; //dsioItem.EntityType = (item.ItemType== NonVACareItemType.Provider) ? "PROVIDER" : "FACILITY"; dsioItem.EntityType = (item.ItemType == NonVACareItemType.Provider) ? "P" : "F"; // *** Add the arguments *** command.AddCommandArguments(dsioItem); // *** Execute the command *** RpcResponse response = command.Execute(); // *** Gather results *** result.Success = (response.Status == RpcResponseStatus.Success); result.Message = response.InformationalMessage; if (result.Success) result.Ien = command.Ien; return result; } /// <summary> /// Retrieve a single item /// </summary> /// <param name="ien">The unique identifier of the item</param> /// <returns>An operation result containing the item if found</returns> public NonVACareItemsResult GetItem(string ien) { return GetList(ien, 1, 1, true); } } }
5,165
https://github.com/Anamon/basic-games/blob/master/games/Color Computer Magazine/1984-02/Bone Race/game.bas
Github Open Source
Open Source
CC0-1.0
2,021
basic-games
Anamon
Visual Basic
Code
317
820
100 REM * BONE RACE * TRS-80 COLOR BASIC 4K 110 REM * SORCERER'S PUZZLES #5 * RICHARD RAMELLA 120 CLS(0) 130 FOR X=0 TO 60 140 SET(X,Y,5) 150 SET(X,Y+4,5) 160 IF X/4=INT(X/4) THEN FOR Z=Y TO Y+4: SET(X,Z,5): NEXT Z 170 NEXT X 180 FOR A=1 TO 32 190 Z$=Z$+CHR$(143) 200 NEXT A 210 GOSUB 520 220 PRINT Z$ 230 X=2 240 L=0 250 Y=2 260 SET(X,Y,8) 270 G=1 280 A$=INKEY$ 290 IF A$<>"B" AND A$<>"F" THEN 280 300 PRINT @ 130,""; 310 IF A$="B" GOSUB 560: GOTO 280 320 PRINT "FORWARD: "; 330 W=RND(6) 340 GOSUB720 350 E=RND(6) 360 Q=W+E 370 PRINT "DICE"W"+"E" 380 GOSUB 720 390 FOR K=X TO X-1+(Q*4) STEP 4 400 SET(K,Y,8) 410 FOR T=1 TO 150 420 NEXT T 430 N=N+1 440 IF K=62 GOTO 750 450 RESET(K,Y) 460 NEXT K 470 SET(K,Y,8) 480 IF K>50 GOTO 750 490 X=K 500 GOSUB 520 510 GOTO 280 520 FOR A=128 TO 224 STEP 32 530 PRINT @ A,Z$; 540 NEXT A 550 RETURN 560 L=L+1 570 IF L>3 THEN PRINT "CAN'T DO IT": FOR T=1 TO 15: SOUND RND(13)*8,1: NEXT T: GOSUB 520: RETURN 580 PRINT "BACKWARD - TIME";L 590 INPUT "HOW MANY";R 600 RESET(X,Y) 610 FOR K=X TO X+1-(4*R) STEP -4 620 IF K=2 THEN X=2: SET(X,Y,8): GOSUB 520: RETURN 630 SET(K,Y,8) 640 FOR T=1 TO 150 650 NEXT T 660 RESET(K,Y) 670 NEXT K 680 X=K 690 SET(X,Y,8) 700 GOSUB 520 710 RETURN 720 FOR T=1 TO 500 730 NEXT T 740 RETURN 750 PRINT @ 194,""; 760 IF K>58 THEN PRINT "LOSE.";: SOUND 147,3: SOUND 117,3: SOUND 108,3: SOUND 89,3: SOUND 32,6: M=M+1 770 IF K=54 OR K=58 THEN PRINT "WIN";: FOR T=1 TO 4: SOUND 176,1: SOUND 193,1: SOUND 204,1: SOUND 218,1: NEXT T: P=P+1 780 PRINT @ 258,"SCORE: YOU:"P"ME:"M; 790 GOSUB 720 800 GOSUB 720 810 GOSUB 520 820 RESET(62,Y) 830 RESET(K,Y) 840 GOTO 230 850 END
26,845
https://github.com/Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021/blob/master/answers/Archita/Day 7/Q2.cpp
Github Open Source
Open Source
MIT
2,021
30-DaysOfCode-March-2021
Codechef-SRM-NCR-Chapter
C++
Code
63
280
#include <iostream> using namespace std; int main() { int a,b,c,arr[10],n,gt=0; cout<<"Enter the no. of elements in array\n"; cin>>n; cout<<"Enter the elements of array\n"; for(int m=0;m<n;m++) { cin>>arr[m]; } cout<<"enter the values of a,b and c"; cin>>a>>b>>c; for(int i=0;i<(n);i++) { for(int j=(i+1);j<(n-1);j++) { if((arr[i]-arr[j])<=a); { for(int k=(j+1);j<(n-2);j++) { if(((arr[j]-arr[k])<=b)&&((arr[i]-arr[k])<=c)) gt++; } } } } cout<<"\nThe number of good triplets is "<<gt; return 0; }
1,436
https://github.com/tjaktor/shopping/blob/master/src/main/java/com/tjaktor/shopping/service/UserService.java
Github Open Source
Open Source
Apache-2.0
2,017
shopping
tjaktor
Java
Code
29
81
package com.tjaktor.shopping.service; import com.tjaktor.shopping.entity.User; public interface UserService { /** * Find a user by username. * * @param username String * @return User */ public User findByUsername(String username); }
19,093
https://github.com/aserg-ufmg/jmove/blob/master/src/src/br/ufmg/dcc/labsoft/java/jmove/methods/AllMethods.java
Github Open Source
Open Source
MIT
2,019
jmove
aserg-ufmg
Java
Code
1,126
5,141
package br.ufmg.dcc.labsoft.java.jmove.methods; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.ForStatement; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SwitchCase; import org.eclipse.jdt.core.dom.SwitchStatement; import org.eclipse.jdt.core.dom.TryStatement; import br.ufmg.dcc.labsoft.java.jmove.ast.DeepDependencyVisitor; import br.ufmg.dcc.labsoft.java.jmove.basic.AllEntitiesMapping; import br.ufmg.dcc.labsoft.java.jmove.dependencies.AccessFieldDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.AccessMethodDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.AnnotateMethodDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.CreateMethodDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.DeclareLocalVariableDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.DeclareParameterDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.DeclareReturnDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.Dependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.SimpleNameDependency; import br.ufmg.dcc.labsoft.java.jmove.dependencies.ThrowDependency; import br.ufmg.dcc.labsoft.java.jmove.util.DCLUtil; import br.ufmg.dcc.labsoft.java.jmove.utils.ClazzUtil; import br.ufmg.dcc.labsoft.java.jmove.utils.MoveMethod; import br.ufmg.dcc.labsoft.java.jmove.utils.PrintOutput; import br.ufmg.dcc.labsoft.java.jmove.utils.JMoveSignatures; public class AllMethods { private List<MethodJMove> allMethodsList; private int numberOfExcluded; private Map<Integer, IMethod> iMethodMapping; private Set<Integer> moveIspossible; private IProgressMonitor monitor; public AllMethods(List<DeepDependencyVisitor> allDeepDependency, IProgressMonitor monitor) throws JavaModelException { // TODO Auto-generated method stub this.numberOfExcluded = 0; this.allMethodsList = new ArrayList<MethodJMove>(); this.iMethodMapping = new HashMap<Integer, IMethod>(); this.moveIspossible = new HashSet<Integer>(); this.monitor = monitor; createMethodsDependeciesList(allDeepDependency); } private void createMethodsDependeciesList( List<DeepDependencyVisitor> allDeepDependency) throws JavaModelException { float i = 0; monitor.beginTask( "Creating Dependencies for selected Java Project (2/4)", (allDeepDependency.size())); for (DeepDependencyVisitor deep : allDeepDependency) { System.out.printf("Criando metodo %2.2" + "f %c \n", (100) * (++i / allDeepDependency.size()), '%'); // for (IMethod m : deep.getUnit().findPrimaryType().getMethods()) { // System.out.println("element " + m.getElementName() + " " // + m.getDeclaringType().getFullyQualifiedName()); // } // System.out.println(); monitor.worked(1); for (Dependency dep : deep.getDependencies()) { if (dep instanceof AccessMethodDependency) { AccessMethodDependency acDependency = (AccessMethodDependency) dep; // String method = dep.getClassNameA() + "." // + ((AccessMethodDependency) dep).getMethodNameA() // + "()"; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), acDependency.getImethodA()); String methodB = JMoveSignatures.getMethodSignature( dep.getClassNameB(), acDependency.getImethodB()); // String methodB = dep.getClassNameB() + "." // + ((AccessMethodDependency) dep).getMethodNameB() // + "()"; List<String> dependeciesList = new ArrayList<String>(); if (!recursive(sourceClass, methodA, dependecyClass, methodB)) { dependeciesList.add(dependecyClass); dependeciesList.add(methodB); } // System.out.println(sourceClass + " " + methodA // + " classe que depednde e metodo " + dependecyClass // + " " + methodB); putIMethodInMapping(methodA, acDependency.getImethodA()); putIMethodInMapping(methodB, acDependency.getImethodB()); createMethod(methodA, sourceClass, dependeciesList, acDependency.getImethodA()); } else if (dep instanceof AccessFieldDependency) { AccessFieldDependency acFieldDependency = (AccessFieldDependency) dep; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), acFieldDependency.getImethodA()); String field = JMoveSignatures.getFieldSignature( dep.getClassNameB(), acFieldDependency.getiVariableBinding()); // String method = dep.getClassNameA() + "." // + ((AccessFieldDependency) dep).getMethodName() // + "()"; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String field = dep.getClassNameB() + "." // + ((AccessFieldDependency) dep).getFieldName(); List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); dependeciesList.add(field); putIMethodInMapping(methodA, acFieldDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, acFieldDependency.getImethodA()); } else if (dep instanceof SimpleNameDependency) { SimpleNameDependency snDependency = (SimpleNameDependency) dep; // String method = dep.getClassNameA() + "." // + ((SimpleNameDependency) dep).getMethodName() // + "()"; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String field = dep.getClassNameB() + "." // + ((SimpleNameDependency) dep).getVariableName(); String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), snDependency.getImethodA()); String field = JMoveSignatures.getFieldSignature( dep.getClassNameB(), snDependency.getiVariableBinding()); List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); dependeciesList.add(field); putIMethodInMapping(methodA, snDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, snDependency.getImethodA()); } else if (dep instanceof AnnotateMethodDependency) { AnnotateMethodDependency anDependency = (AnnotateMethodDependency) dep; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String method = dep.getClassNameA() + "." // + ((AnnotateMethodDependency) dep).getMethodName() // + "()"; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), anDependency.getImethodA()); List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); putIMethodInMapping(methodA, anDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, anDependency.getImethodA()); } else if (dep instanceof CreateMethodDependency) { CreateMethodDependency cmDependency = (CreateMethodDependency) dep; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), cmDependency.getImethodA()); // String method = dep.getClassNameA() + "." // + ((CreateMethodDependency) dep).getMethodNameA() // + "()"; List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); putIMethodInMapping(methodA, cmDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, cmDependency.getImethodA()); } else if (dep instanceof DeclareParameterDependency) { DeclareParameterDependency dpDependency = (DeclareParameterDependency) dep; // String method = dep.getClassNameA() // + "." // + ((DeclareParameterDependency) dep) // .getMethodName() + "()"; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), dpDependency.getImethodA()); String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String field = dep.getClassNameB() + "." // + ((DeclareParameterDependency) dep).getFieldName(); List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); // dependeciesList.add(field); putIMethodInMapping(methodA, dpDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, dpDependency.getImethodA()); } else if (dep instanceof DeclareReturnDependency) { DeclareReturnDependency drDependency = (DeclareReturnDependency) dep; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), drDependency.getImethodA()); String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String method = dep.getClassNameA() + "." // + ((DeclareReturnDependency) dep).getMethodName() // + "()"; List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); putIMethodInMapping(methodA, drDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, drDependency.getImethodA()); } else if (dep instanceof DeclareLocalVariableDependency) { DeclareLocalVariableDependency dlvDependency = (DeclareLocalVariableDependency) dep; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), dlvDependency.getImethodA()); // String method = dep.getClassNameA() // + "." // + ((DeclareLocalVariableDependency) dep) // .getMethodName() + "()"; String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String field = dep.getClassNameB() // + "." // + ((DeclareLocalVariableDependency) dep) // .getFieldName(); List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); // System.out.println("DeclareLocalVariableDependency"); // System.out.println(dependecyClass); // System.out.println(method); // System.out.println(field); // dependeciesList.add(field); putIMethodInMapping(methodA, dlvDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, dlvDependency.getImethodA()); } else if (dep instanceof ThrowDependency) { ThrowDependency throwDependency = (ThrowDependency) dep; String methodA = JMoveSignatures.getMethodSignature( dep.getClassNameA(), throwDependency.getImethodA()); String sourceClass = dep.getClassNameA(); String dependecyClass = dep.getClassNameB(); // String method = dep.getClassNameA() + "." // + ((ThrowDependency) dep).getMethodName() + "()"; List<String> dependeciesList = new ArrayList<String>(); dependeciesList.add(dependecyClass); putIMethodInMapping(methodA, throwDependency.getImethodA()); createMethod(methodA, sourceClass, dependeciesList, throwDependency.getImethodA()); } } if (monitor != null && monitor.isCanceled()) { if (monitor != null) monitor.done(); throw new OperationCanceledException(); } } // // #............ Imprime dependencias Iterator<MethodJMove> it = allMethodsList.iterator(); while (it.hasNext()) { MethodJMove m = it.next(); PrintOutput.write( AllEntitiesMapping.getInstance().getByID(m.getNameID()) + "\n", "conjuntos"); for (Integer chaves : m.getMethodsDependencies()) { PrintOutput .write(AllEntitiesMapping.getInstance().getByID(chaves) + "\n", "conjuntos"); } PrintOutput.write("\n \n", "conjuntos"); } // #............ } private boolean recursive(String sourceClass, String methodA, String dependecyClass, String methodB) { // TODO Auto-generated method stub if (sourceClass.equals(dependecyClass) && methodA.equals(methodB)) { return true; } return false; } private void createMethod(String methodName, String sourceClass, List<String> dependeciesList, IMethod iMethod) { // TODO Auto-generated method stub int methodId = AllEntitiesMapping.getInstance().createEntityID( methodName); int sourceClassID = AllEntitiesMapping.getInstance().createEntityID( sourceClass); // System.out.println("Aki primeiro "+ sourceClass); MethodJMove method2 = new MethodJMove(methodId, sourceClassID); if (allMethodsList.contains(method2)) { method2 = allMethodsList.get(allMethodsList.indexOf(method2)); method2.setNewMethodsDependencies(dependeciesList); } else { // List<String> moveReachable = MoveMethod // .getpossibleRefactoring(getIMethod(method2)); if (this.getIMethod(method2) != null && MoveMethod.IsRefactoringPossible(this .getIMethod(method2))) { moveIspossible.add(methodId); } allMethodsList.add(method2); method2.setNewMethodsDependencies(dependeciesList); } } private void putIMethodInMapping(String methodName, IMethod iMethod) { // TODO Auto-generated method stub int methodId; methodId = AllEntitiesMapping.getInstance().createEntityID(methodName); iMethodMapping.put(methodId, iMethod); } public IMethod getIMethod(MethodJMove method) { // TODO Auto-generated method stub return iMethodMapping.get(method.getNameID()); } public List<MethodJMove> getAllMethodsList() { return allMethodsList; } public MethodJMove getMethodByID(int methodID) { for (MethodJMove method : allMethodsList) { if (methodID == method.getNameID()) return method; } return null; } public int getNumberOfExcluded() { return numberOfExcluded; } private void setNumberOfExcluded(int numberOfExcluded) { this.numberOfExcluded = numberOfExcluded; } public Set<Integer> getMoveIspossible() { return moveIspossible; } public void excludeDependeciesLessThan(int Numdepedencies) { List<MethodJMove> smallMethod = new ArrayList<MethodJMove>(); if (Numdepedencies > getNumberOfExcluded()) { setNumberOfExcluded(Numdepedencies); for (MethodJMove method : allMethodsList) { if (method.getMethodsDependencies().size() < Numdepedencies) { smallMethod.add(method); } } allMethodsList.removeAll(smallMethod); } } public void excludeConstructors() { Iterator<Entry<Integer, IMethod>> it = iMethodMapping.entrySet() .iterator(); while (it.hasNext()) { Entry<Integer, IMethod> entry = it.next(); IMethod method = entry.getValue(); try { if (method != null && method.isConstructor()) { MethodJMove methodTemp = getMethodByID(entry.getKey()); int index = allMethodsList.indexOf(methodTemp); allMethodsList.remove(index); } } catch (JavaModelException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
12,928
https://github.com/ahxm/cloud/blob/master/cloud-api/src/main/java/com/ans/cloud/model/QUserAccessKey.java
Github Open Source
Open Source
Apache-2.0
null
cloud
ahxm
Java
Code
20
61
package com.ans.cloud.model; import com.ans.cloud.data.model.Query; /** * @author anzhen * @since 2016-03-08 15:07 */ public class QUserAccessKey implements Query { }
43,840
https://github.com/mattbragaw/mqb/blob/master/Mqb.Data/Descriptors/Services/ISpaceService.cs
Github Open Source
Open Source
MIT
null
mqb
mattbragaw
C#
Code
50
243
using Mqb.Descriptors.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Mqb.Descriptors.Services { public interface ISpaceService : ICrudService<ISpace> { Task<IEnumerable<ISpace>> GetByParentOrgIdAsync(string parentOrgId); Task<IPaged<ISpace>> GetPagedByParentOrgIdAsync(string parentOrgId, int pageIndex, int pageSize); Task<IEnumerable<ISpace>> GetByParentSpaceIdAsync(string parentSpaceId); Task<IPaged<ISpace>> GetPagedByParentSpaceIdAsync(string parentSpaceId, int pageIndex, int pageSize); Task<IEnumerable<ISpace>> GetParentChainAsync(string id); Task<bool> DeleteByParentOrgIdAsync(string parentOrgId); Task<bool> DeleteByParentSpaceIdAsync(string parentSpaceId); } }
27,958
https://github.com/seL4/isabelle/blob/master/src/HOL/ex/Perm_Fragments.thy
Github Open Source
Open Source
BSD-3-Clause
2,023
isabelle
seL4
Isabelle
Code
1,391
3,909
(* Author: Florian Haftmann, TU Muenchen *) section \<open>Fragments on permuations\<close> theory Perm_Fragments imports "HOL-Library.Dlist" "HOL-Combinatorics.Perm" begin text \<open>On cycles\<close> context includes permutation_syntax begin lemma cycle_prod_list: "\<langle>a # as\<rangle> = prod_list (map (\<lambda>b. \<langle>a \<leftrightarrow> b\<rangle>) (rev as))" by (induct as) simp_all lemma cycle_append [simp]: "\<langle>a # as @ bs\<rangle> = \<langle>a # bs\<rangle> * \<langle>a # as\<rangle>" proof (induct as rule: cycle.induct) case (3 b c as) then have "\<langle>a # (b # as) @ bs\<rangle> = \<langle>a # bs\<rangle> * \<langle>a # b # as\<rangle>" by simp then have "\<langle>a # as @ bs\<rangle> * \<langle>a \<leftrightarrow> b\<rangle> = \<langle>a # bs\<rangle> * \<langle>a # as\<rangle> * \<langle>a \<leftrightarrow> b\<rangle>" by (simp add: ac_simps) then have "\<langle>a # as @ bs\<rangle> * \<langle>a \<leftrightarrow> b\<rangle> * \<langle>a \<leftrightarrow> b\<rangle> = \<langle>a # bs\<rangle> * \<langle>a # as\<rangle> * \<langle>a \<leftrightarrow> b\<rangle> * \<langle>a \<leftrightarrow> b\<rangle>" by simp then have "\<langle>a # as @ bs\<rangle> = \<langle>a # bs\<rangle> * \<langle>a # as\<rangle>" by (simp add: ac_simps) then show "\<langle>a # (b # c # as) @ bs\<rangle> = \<langle>a # bs\<rangle> * \<langle>a # b # c # as\<rangle>" by (simp add: ac_simps) qed simp_all lemma affected_cycle: "affected \<langle>as\<rangle> \<subseteq> set as" proof (induct as rule: cycle.induct) case (3 a b as) from affected_times have "affected (\<langle>a # as\<rangle> * \<langle>a \<leftrightarrow> b\<rangle>) \<subseteq> affected \<langle>a # as\<rangle> \<union> affected \<langle>a \<leftrightarrow> b\<rangle>" . moreover from 3 have "affected (\<langle>a # as\<rangle>) \<subseteq> insert a (set as)" by simp moreover have "affected \<langle>a \<leftrightarrow> b\<rangle> \<subseteq> {a, b}" by (cases "a = b") (simp_all add: affected_swap) ultimately have "affected (\<langle>a # as\<rangle> * \<langle>a \<leftrightarrow> b\<rangle>) \<subseteq> insert a (insert b (set as))" by blast then show ?case by auto qed simp_all lemma orbit_cycle_non_elem: assumes "a \<notin> set as" shows "orbit \<langle>as\<rangle> a = {a}" unfolding not_in_affected_iff_orbit_eq_singleton [symmetric] using assms affected_cycle [of as] by blast lemma inverse_cycle: assumes "distinct as" shows "inverse \<langle>as\<rangle> = \<langle>rev as\<rangle>" using assms proof (induct as rule: cycle.induct) case (3 a b as) then have *: "inverse \<langle>a # as\<rangle> = \<langle>rev (a # as)\<rangle>" and distinct: "distinct (a # b # as)" by simp_all show " inverse \<langle>a # b # as\<rangle> = \<langle>rev (a # b # as)\<rangle>" proof (cases as rule: rev_cases) case Nil with * show ?thesis by (simp add: swap_sym) next case (snoc cs c) with distinct have "distinct (a # b # cs @ [c])" by simp then have **: "\<langle>a \<leftrightarrow> b\<rangle> * \<langle>c \<leftrightarrow> a\<rangle> = \<langle>c \<leftrightarrow> a\<rangle> * \<langle>c \<leftrightarrow> b\<rangle>" by transfer (auto simp add: fun_eq_iff transpose_def) with snoc * show ?thesis by (simp add: mult.assoc [symmetric]) qed qed simp_all lemma order_cycle_non_elem: assumes "a \<notin> set as" shows "order \<langle>as\<rangle> a = 1" proof - from assms have "orbit \<langle>as\<rangle> a = {a}" by (rule orbit_cycle_non_elem) then have "card (orbit \<langle>as\<rangle> a) = card {a}" by simp then show ?thesis by simp qed lemma orbit_cycle_elem: assumes "distinct as" and "a \<in> set as" shows "orbit \<langle>as\<rangle> a = set as" oops \<comment> \<open>(we need rotation here\<close> lemma order_cycle_elem: assumes "distinct as" and "a \<in> set as" shows "order \<langle>as\<rangle> a = length as" oops text \<open>Adding fixpoints\<close> definition fixate :: "'a \<Rightarrow> 'a perm \<Rightarrow> 'a perm" where "fixate a f = (if a \<in> affected f then f * \<langle>inverse f \<langle>$\<rangle> a \<leftrightarrow> a\<rangle> else f)" lemma affected_fixate_trivial: assumes "a \<notin> affected f" shows "affected (fixate a f) = affected f" using assms by (simp add: fixate_def) lemma affected_fixate_binary_circle: assumes "order f a = 2" shows "affected (fixate a f) = affected f - {a, apply f a}" (is "?A = ?B") proof (rule set_eqI) interpret bijection "apply f" by standard simp fix b from assms order_greater_eq_two_iff [of f a] have "a \<in> affected f" by simp moreover have "apply (f ^ 2) a = a" by (simp add: assms [symmetric]) ultimately show "b \<in> ?A \<longleftrightarrow> b \<in> ?B" by (cases "b \<in> {a, apply (inverse f) a}") (auto simp add: in_affected power2_eq_square apply_inverse apply_times fixate_def) qed lemma affected_fixate_no_binary_circle: assumes "order f a > 2" shows "affected (fixate a f) = affected f - {a}" (is "?A = ?B") proof (rule set_eqI) interpret bijection "apply f" by standard simp fix b from assms order_greater_eq_two_iff [of f a] have "a \<in> affected f" by simp moreover from assms have "apply f (apply f a) \<noteq> a" using apply_power_eq_iff [of f 2 a 0] by (simp add: power2_eq_square apply_times) ultimately show "b \<in> ?A \<longleftrightarrow> b \<in> ?B" by (cases "b \<in> {a, apply (inverse f) a}") (auto simp add: in_affected apply_inverse apply_times fixate_def) qed lemma affected_fixate: "affected (fixate a f) \<subseteq> affected f - {a}" proof - have "a \<notin> affected f \<or> order f a = 2 \<or> order f a > 2" by (auto simp add: not_less dest: affected_order_greater_eq_two) then consider "a \<notin> affected f" | "order f a = 2" | "order f a > 2" by blast then show ?thesis apply cases using affected_fixate_trivial [of a f] affected_fixate_binary_circle [of f a] affected_fixate_no_binary_circle [of f a] by auto qed lemma orbit_fixate_self [simp]: "orbit (fixate a f) a = {a}" proof - have "apply (f * inverse f) a = a" by simp then have "apply f (apply (inverse f) a) = a" by (simp only: apply_times comp_apply) then show ?thesis by (simp add: fixate_def not_in_affected_iff_orbit_eq_singleton [symmetric] in_affected apply_times) qed lemma order_fixate_self [simp]: "order (fixate a f) a = 1" proof - have "card (orbit (fixate a f) a) = card {a}" by simp then show ?thesis by (simp only: card_orbit_eq) simp qed lemma assumes "b \<notin> orbit f a" shows "orbit (fixate b f) a = orbit f a" oops lemma assumes "b \<in> orbit f a" and "b \<noteq> a" shows "orbit (fixate b f) a = orbit f a - {b}" oops text \<open>Distilling cycles from permutations\<close> inductive_set orbits :: "'a perm \<Rightarrow> 'a set set" for f where in_orbitsI: "a \<in> affected f \<Longrightarrow> orbit f a \<in> orbits f" lemma orbits_unfold: "orbits f = orbit f ` affected f" by (auto intro: in_orbitsI elim: orbits.cases) lemma in_orbit_affected: assumes "b \<in> orbit f a" assumes "a \<in> affected f" shows "b \<in> affected f" proof (cases "a = b") case True with assms show ?thesis by simp next case False with assms have "{a, b} \<subseteq> orbit f a" by auto also from assms have "orbit f a \<subseteq> affected f" by (blast intro!: orbit_subset_eq_affected) finally show ?thesis by simp qed lemma Union_orbits [simp]: "\<Union>(orbits f) = affected f" by (auto simp add: orbits.simps intro: in_orbitsI in_orbit_affected) lemma finite_orbits [simp]: "finite (orbits f)" by (simp add: orbits_unfold) lemma card_in_orbits: assumes "A \<in> orbits f" shows "card A \<ge> 2" using assms by cases (auto dest: affected_order_greater_eq_two) lemma disjoint_orbits: assumes "A \<in> orbits f" and "B \<in> orbits f" and "A \<noteq> B" shows "A \<inter> B = {}" using \<open>A \<in> orbits f\<close> apply cases using \<open>B \<in> orbits f\<close> apply cases using \<open>A \<noteq> B\<close> apply (simp_all add: orbit_disjoint) done definition trace :: "'a \<Rightarrow> 'a perm \<Rightarrow> 'a list" where "trace a f = map (\<lambda>n. apply (f ^ n) a) [0..<order f a]" lemma set_trace_eq [simp]: "set (trace a f) = orbit f a" by (auto simp add: trace_def orbit_unfold_image) definition seeds :: "'a perm \<Rightarrow> 'a::linorder list" where "seeds f = sorted_list_of_set (Min ` orbits f)" definition cycles :: "'a perm \<Rightarrow> 'a::linorder list list" where "cycles f = map (\<lambda>a. trace a f) (seeds f)" end text \<open>Misc\<close> lemma (in comm_monoid_list_set) sorted_list_of_set: assumes "finite A" shows "list.F (map h (sorted_list_of_set A)) = set.F h A" proof - from distinct_sorted_list_of_set have "set.F h (set (sorted_list_of_set A)) = list.F (map h (sorted_list_of_set A))" by (rule distinct_set_conv_list) with \<open>finite A\<close> show ?thesis by (simp) qed primrec subtract :: "'a list \<Rightarrow> 'a list \<Rightarrow> 'a list" where "subtract [] ys = ys" | "subtract (x # xs) ys = subtract xs (removeAll x ys)" lemma length_subtract_less_eq [simp]: "length (subtract xs ys) \<le> length ys" proof (induct xs arbitrary: ys) case Nil then show ?case by simp next case (Cons x xs) then have "length (subtract xs (removeAll x ys)) \<le> length (removeAll x ys)" . also have "length (removeAll x ys) \<le> length ys" by simp finally show ?case by simp qed end
1,520
https://github.com/PNNL-Comp-Mass-Spec/DBSchema_PgSQL_DMS/blob/master/dms/sw/sw.add_update_transfer_paths_in_params_using_data_pkg.sql
Github Open Source
Open Source
Apache-2.0
2,023
DBSchema_PgSQL_DMS
PNNL-Comp-Mass-Spec
PLpgSQL
Code
617
1,757
-- -- Name: add_update_transfer_paths_in_params_using_data_pkg(integer, boolean, text, text); Type: PROCEDURE; Schema: sw; Owner: d3l243 -- CREATE OR REPLACE PROCEDURE sw.add_update_transfer_paths_in_params_using_data_pkg(IN _datapackageid integer, INOUT _paramsupdated boolean DEFAULT false, INOUT _message text DEFAULT ''::text, INOUT _returncode text DEFAULT ''::text) LANGUAGE plpgsql AS $$ /**************************************************** ** ** Desc: ** If a job has a data package ID defined, determines the ** appropriate paths for 'CacheFolderPath' and 'TransferFolderPath' ** ** Updates Tmp_Job_Params to have these paths defined if not yet defined or if different ** If Tmp_Job_Params is updated, _paramsUpdated will be set to true ** ** The calling procedure must create and populate table Tmp_Job_Params ** ** CREATE TEMP TABLE Tmp_Job_Params ( ** Section citext, ** Name citext, ** Value citext ** ); ** ** Arguments: ** _dataPackageID If 0 or null, will auto-define using parameter 'DataPackageID' in the Tmp_Job_Params table (in section 'JobParameters') ** _paramsUpdated Output: true if table Tmp_Job_Params was updated ** ** Auth: mem ** Date: 06/16/2016 mem - Initial version ** 06/09/2021 mem - Tabs to spaces ** 06/24/2012 mem - Add parameter DataPackagePath ** 03/24/2023 mem - Capitalize job parameter TransferFolderPath ** 07/27/2023 mem - Ported to PostgreSQL ** *****************************************************/ DECLARE _value text; _dataPkgSharePath text := ''; _dataPkgName text := ''; _xferPath text := ''; _cacheFolderPath text := ''; _cacheRootFolderPath text := ''; _cacheFolderPathOld text := ''; _xferPathOld text := ''; BEGIN _message := ''; _returnCode := ''; --------------------------------------------------- -- Validate the inputs --------------------------------------------------- _dataPackageID := Coalesce(_dataPackageID, 0); _paramsUpdated := false; --------------------------------------------------- -- Update _dataPackageID if 0 yet defined in Tmp_Job_Params --------------------------------------------------- If _dataPackageID <= 0 Then SELECT Value INTO _value FROM Tmp_Job_Params WHERE Section = 'JobParameters' and Name = 'DataPackageID'; If FOUND And Coalesce(_value, '') <> '' Then _dataPackageID := public.try_cast(_value, 0); End If; End If; --------------------------------------------------- -- Get data package info (if one is specified) --------------------------------------------------- If _dataPackageID <> 0 Then SELECT dp.package_name, dpp.share_path INTO _dataPkgName, _dataPkgSharePath FROM dpkg.t_data_package dp INNER JOIN dpkg.v_data_package_paths dpp ON dp.data_pkg_id = dpp.id WHERE dp.data_pkg_id = _dataPackageID; If Not FOUND Then RAISE WARNING 'Data Package ID % not found in dpkg.t_data_package', _dataPackageID; _dataPkgName := ''; _dataPkgSharePath := ''; End If; End If; --------------------------------------------------- -- Check whether job parameter CacheFolderRootPath has a cache root folder path defined --------------------------------------------------- -- Step Tool Default Value for CacheFolderRootPath -- --------------- ------------------------------------- -- PRIDE_Converter \\protoapps\MassIVE_Staging -- MaxQuant \\protoapps\MaxQuant_Staging -- MSFragger \\proto-9\MSFragger_Staging -- DiaNN \\proto-9\DiaNN_Staging -- -- PeptideAtlas \\protoapps\PeptideAtlas_Staging (tool retired in 2020) SELECT Value INTO _cacheRootFolderPath FROM Tmp_Job_Params WHERE Name = 'CacheFolderRootPath'; --------------------------------------------------- -- Define the path parameters --------------------------------------------------- If _dataPackageID > 0 Then -- Lookup paths already defined in Tmp_Job_Params SELECT Value INTO _cacheFolderPathOld FROM Tmp_Job_Params WHERE Section = 'JobParameters' AND Name = 'CacheFolderPath'; SELECT Value INTO _xferPathOld FROM Tmp_Job_Params WHERE Section = 'JobParameters' AND Name = 'TransferFolderPath'; If Coalesce(_cacheRootFolderPath, '') = '' Then _xferPath := _dataPkgSharePath; Else _cacheFolderPath := format('%s\%s_%s', _cacheRootFolderPath, _dataPackageID, REPLACE(_dataPkgName, ' ', '_')); _xferPath := _cacheRootFolderPath; If _cacheFolderPathOld IS DISTINCT FROM _cacheFolderPath Then DELETE FROM Tmp_Job_Params WHERE Name = 'CacheFolderPath'; INSERT INTO Tmp_Job_Params ( Section, Name, Value ) VALUES ( 'JobParameters', 'CacheFolderPath', _cacheFolderPath ); End If; End If; If _xferPathOld IS DISTINCT FROM _xferPath Then DELETE FROM Tmp_Job_Params WHERE Name = 'TransferFolderPath'; INSERT INTO Tmp_Job_Params ( Section, Name, Value ) VALUES ( 'JobParameters', 'TransferFolderPath', _xferPath ); End If; DELETE FROM Tmp_Job_Params WHERE Name = 'DataPackagePath'; INSERT INTO Tmp_Job_Params( Section, Name, Value ) VALUES('JobParameters', 'DataPackagePath', _dataPkgSharePath); _paramsUpdated := true; End If; END $$; ALTER PROCEDURE sw.add_update_transfer_paths_in_params_using_data_pkg(IN _datapackageid integer, INOUT _paramsupdated boolean, INOUT _message text, INOUT _returncode text) OWNER TO d3l243; -- -- Name: PROCEDURE add_update_transfer_paths_in_params_using_data_pkg(IN _datapackageid integer, INOUT _paramsupdated boolean, INOUT _message text, INOUT _returncode text); Type: COMMENT; Schema: sw; Owner: d3l243 -- COMMENT ON PROCEDURE sw.add_update_transfer_paths_in_params_using_data_pkg(IN _datapackageid integer, INOUT _paramsupdated boolean, INOUT _message text, INOUT _returncode text) IS 'AddUpdateTransferPathsInParamsUsingDataPkg';
6,781
https://github.com/lshift/bletchley/blob/master/src/test/java/net/lshift/spki/suiteb/demo/ServerWithEncryption.java
Github Open Source
Open Source
Apache-2.0
2,016
bletchley
lshift
Java
Code
83
390
package net.lshift.spki.suiteb.demo; import static net.lshift.spki.suiteb.SequenceUtils.sequence; import static net.lshift.spki.suiteb.demo.Utilities.emptyByteOpenable; import static net.lshift.spki.suiteb.demo.Utilities.read; import java.io.IOException; import net.lshift.spki.InvalidInputException; import net.lshift.spki.convert.openable.Openable; import net.lshift.spki.suiteb.EncryptionCache; import net.lshift.spki.suiteb.PrivateEncryptionKey; import net.lshift.spki.suiteb.PublicEncryptionKey; import net.lshift.spki.suiteb.SequenceItem; public class ServerWithEncryption extends Server { private final EncryptionCache ephemeral = new EncryptionCache(PrivateEncryptionKey.generate()); private Openable recipientKey = emptyByteOpenable(); public void setRecipientKey(Openable recipientKey) { this.recipientKey = recipientKey; } @Override protected SequenceItem serviceMessage(Service service) throws IOException, InvalidInputException { return encrypt(signedMessage(service)); } protected SequenceItem encrypt(SequenceItem sequence) throws IOException, InvalidInputException { PublicEncryptionKey recipient = (PublicEncryptionKey) read(recipientKey); return sequence(ephemeral.getPublicKey(), ephemeral.encrypt(recipient, sequence)); } }
41,365
https://github.com/reactive-stack-js/reactive-stack-js-rest-frontend-react/blob/master/src/app/pages/header/User.js
Github Open Source
Open Source
Unlicense
2,021
reactive-stack-js-rest-frontend-react
reactive-stack-js
JavaScript
Code
115
464
import _ from "lodash"; import React, {Component} from "react"; import {Link, withRouter} from "react-router-dom"; import {Button, Icon} from "semantic-ui-react"; import "./User.css"; import AuthService from "../../../_reactivestack/auth.service"; class User extends Component { facebook = () => this.props.history.push("/login/facebook"); google = () => this.props.history.push("/login/google"); componentDidUpdate() { if (this.props.location.pathname === "/") return; if (_.startsWith(this.props.location.pathname, "/login")) return; localStorage.setItem("initialPageRequest", this.props.location.pathname); } render() { if (AuthService.loggedIn()) { const user = AuthService.user(); const provider = _.toLower(_.first(_.words(_.get(user, "provider", "")))); const providerId = _.toLower(_.first(_.words(_.get(user, "providerId", "")))); return ( <span> {provider}_{providerId} <Link to="/logout" className="logout">logout</Link> </span> ); } return ( <div id="user-component"> <Button color="blue" className="FacebookButton" onClick={this.facebook}> <Icon className="facebook f icon"></Icon> Login </Button> <Button color="red" className="GoogleButton" onClick={this.google}> <Icon className="google icon"></Icon> Login </Button> </div> ); } } export default withRouter(User);
6,346
https://github.com/andrii-sky/analytics-react-native/blob/master/lib/typescript/src/analytics.d.ts
Github Open Source
Open Source
MIT
null
analytics-react-native
andrii-sky
TypeScript
Code
742
1,595
import type { Logger } from './logger'; import type { DestinationPlugin, PlatformPlugin, Plugin } from './plugin'; import type { Settable, Watchable } from './storage'; import { Config, Context, DeepPartial, GroupTraits, JsonMap, PluginType, SegmentAPIIntegrations, SegmentAPISettings, SegmentEvent, UserInfoState, UserTraits } from './types'; export declare class SegmentClient { private config; private store; private secondsElapsed; private appState; private appStateSubscription; logger: Logger; private flushInterval; private readinessWatcher?; private watchers; private destroyed; private isPendingUpload; private isAddingPlugins; private timeline; private isStorageReady; private pluginsToAdd; private isInitialized; get platformPlugins(): PlatformPlugin[]; /** * Access or subscribe to client context */ readonly context: Watchable<DeepPartial<Context> | undefined> & Settable<DeepPartial<Context>>; /** * Access or subscribe to adTrackingEnabled (also accesible from context) */ readonly adTrackingEnabled: Watchable<boolean>; /** * Access or subscribe to integration settings */ readonly settings: Watchable<SegmentAPIIntegrations | undefined>; /** * Access or suscribe to the events in the timeline */ readonly events: Watchable<SegmentEvent[]>; /** * Access or subscribe to user info (anonymousId, userId, traits) */ readonly userInfo: Watchable<UserInfoState>; /** * Returns the plugins currently loaded in the timeline * @param ofType Type of plugins, defaults to all * @returns List of Plugin objects */ getPlugins(ofType?: PluginType): readonly Plugin[]; /** * Retrieves a copy of the current client configuration */ getConfig(): { writeKey: string; debug?: boolean | undefined; flushAt?: number | undefined; flushInterval?: number | undefined; trackAppLifecycleEvents?: boolean | undefined; retryInterval?: number | undefined; maxBatchSize?: number | undefined; trackDeepLinks?: boolean | undefined; maxEventsToRetry?: number | undefined; defaultSettings?: SegmentAPISettings | undefined; autoAddSegmentDestination?: boolean | undefined; collectDeviceId?: boolean | undefined; }; constructor({ config, logger, store, }: { config: Config; logger: Logger; store: any; }); /** * Initializes the client plugins, settings and subscribers. * Can only be called once. */ init(): Promise<void>; fetchSettings(): Promise<void>; /** * Clears all subscriptions to the store */ private unsubscribeStorageWatchers; /** * There is no garbage collection in JS, which means that any listeners, timeouts and subscriptions * would run until the application closes * * This method exists in case the user for some reason needs to recreate the class instance during runtime. * In this case, they should run client.cleanup() to destroy the listeners in the old client before creating a new one. * * There is a Stage 3 EMCAScript proposal to add a user-defined finalizer, which we could potentially switch to if * it gets approved: https://github.com/tc39/proposal-weakrefs#finalizers */ cleanup(): void; private setupInterval; private setupStorageSubscribers; private setupLifecycleEvents; /** Applies the supplied closure to the currently loaded set of plugins. NOTE: This does not apply to plugins contained within DestinationPlugins. - Parameter closure: A closure that takes an plugin to be operated on as a parameter. */ apply(closure: (plugin: Plugin) => void): void; /** * Adds a new plugin to the currently loaded set. * @param {{ plugin: Plugin, settings?: SegmentAPISettings }} Plugin to be added. Settings are optional if you want to force a configuration instead of the Segment Cloud received one */ add({ plugin, settings, }: { plugin: Plugin; settings?: Plugin extends DestinationPlugin ? SegmentAPISettings : never; }): void; private addPlugin; /** Removes and unloads plugins with a matching name from the system. - Parameter pluginName: An plugin name. */ remove({ plugin }: { plugin: Plugin; }): void; process(incomingEvent: SegmentEvent): void; private trackDeepLinks; private unsubscribeReadinessWatcher; private onStorageReady; private tick; flush(): Promise<void>; screen(name: string, options?: JsonMap): void; track(eventName: string, options?: JsonMap, timestamp?: string): void; identify(userId?: string, userTraits?: UserTraits): void; group(groupId: string, groupTraits?: GroupTraits): void; alias(newUserId: string): void; queueEvent(event: SegmentEvent): void; removeEvents(event: SegmentEvent | SegmentEvent[]): void; /** * Called once when the client is first created * * Detect and save the the currently installed application version * Send application lifecycle events if trackAppLifecycleEvents is enabled * * Exactly one of these events will be sent, depending on the current and previous version:s * Application Installed - no information on the previous version, so it's a fresh install * Application Updated - the previous detected version is different from the current version * Application Opened - the previously detected version is same as the current version */ private checkInstalledVersion; /** * AppState event listener. Called whenever the app state changes. * * Send application lifecycle events if trackAppLifecycleEvents is enabled. * * Application Opened - only when the app state changes from 'inactive' or 'background' to 'active' * The initial event from 'unknown' to 'active' is handled on launch in checkInstalledVersion * Application Backgrounded - when the app state changes from 'inactive' or 'background' to 'active * * @param nextAppState 'active', 'inactive', 'background' or 'unknown' */ private handleAppStateChange; reset(): void; }
32,390
https://github.com/zhytang/angular-admin/blob/master/src/app/services/saHttpLoading/saHttpLoading.service.ts
Github Open Source
Open Source
MIT
2,020
angular-admin
zhytang
TypeScript
Code
169
567
/** * @file Http loading service * @desc app/http-loading * @author Surmon <https://github.com/surmon-china> */ import { Injectable } from '@angular/core'; function replaceMethod(replacer) { return (target, propertyKey, descriptor) => { descriptor.value = replacer(descriptor.value); return descriptor; }; } export type TLoading = boolean; export type TLoadingName = string | number; @Injectable() export class SaHttpLoadingService { private loadings: Map<TLoadingName, boolean> = new Map(); constructor(...names: TLoadingName[]) { names.forEach(name => this.add(name)); } get names(): IterableIterator<TLoadingName> { return this.loadings.keys(); } add(name: TLoadingName): void { if (!this.loadings.has(name)) { this.loadings.set(name, false); } } start(name: TLoadingName): void { this.loadings.set(name, true); } stop(name: TLoadingName): void { this.loadings.set(name, false); } isLoading(name: TLoadingName): boolean { return !!(this.loadings.has(name) && this.loadings.get(name)); } isFinished(name: TLoadingName): boolean { return !this.isLoading(name); } isAllFinished(): boolean { const values = []; this.loadings.forEach(value => values.push(value)); return values.every(Boolean); } promise<T>(name: TLoadingName, promise: Promise<T>): Promise<T> { this.start(name); const stopLoading = () => this.stop(name); promise.then(stopLoading, stopLoading); return promise; } handle(name: string) { const loadings = this; return replaceMethod((origin) => function(...args) { const promise = origin.apply(this, args); return loadings.promise(name, promise); }); } }
38,746
https://github.com/jimbi-o/illuminate/blob/master/src/d3d12/render_pass/d3d12_render_pass_cs_dispatch.h
Github Open Source
Open Source
MIT
null
illuminate
jimbi-o
C
Code
33
167
#ifndef ILLUMINATE_D3D12_RENDER_PASS_CS_DISPATCH_H #define ILLUMINATE_D3D12_RENDER_PASS_CS_DISPATCH_H #include "d3d12_render_pass_common.h" namespace illuminate { class RenderPassCsDispatch { public: static void* Init(RenderPassFuncArgsInit* args, const uint32_t render_pass_index); static void Render(RenderPassFuncArgsRenderCommon* args_common, RenderPassFuncArgsRenderPerPass* args_per_pass); private: RenderPassCsDispatch() = delete; }; } #endif
46,718
https://github.com/ORORRR/numero-number-one/blob/master/app/Resources/views/oeuvres/oeuvre_ajout.html.twig
Github Open Source
Open Source
MIT
null
numero-number-one
ORORRR
Twig
Code
220
981
{% extends 'pageSite.html.twig' %} {% form_theme form 'form/errors.html.twig' %} {% block main %} <div class="container"> <div id="form-ajout-oeuvre" class="text-center border border-light p-5 m-5"> <p class="h3 mb-4"><strong>Ajouter une oeuvre</strong></p> {{ form_start(form) }} {{ form_errors(form) }} {{ form_errors(form.nom) }} {{ form_errors(form.descriptif) }} {{ form_errors(form.categorie) }} {{ form_errors(form.photoPrincipale) }} {{ form_errors(form.groupsImages) }} {{ form_errors(form.auteurs) }} {{ form_errors(form.datePublication) }} {{ form_widget(form.children['nom'], {'attr': {'class': 'form-control mb-4', 'placeholder': 'Nom'} }) }} {{ form_widget(form.children['descriptif'], {'attr': {'class': 'form-control mb-4', 'placeholder': 'Descriptif', 'maxlength' : "512"} }) }} {{ form_widget(form.children['categorie'], {'attr': {'class': 'form-control mb-4'} }) }} {{ form_label(form.children['photoPrincipale'], "Photo principale") }} {{ form_widget(form.children['photoPrincipale'], {'attr': {'class': 'mb-4'} }) }} {% set filePrototype = form_widget(form.groupsImages.vars.prototype.children.photos.vars.prototype) %} {% set groupPrototype = form_widget(form.groupsImages.vars.prototype) %} <div id="data_groups" class="files" data-group-prototype="{{groupPrototype|e('html_attr')}}" data-file-prototype="{{filePrototype|e('html_attr')}}"> <ul id="groups_list"> </ul> </div> {{ form_row(form.children['groupsImages']) }} {{ form_row(form.children['addGroup'], {'attr': {'label': 'Photos secondaires'}})}} {{ form_widget(form.children['auteurs'], {'attr': {'class': 'form-control mb-4', 'placeholder': 'Auteurs'} }) }} <div class="input-group date"> <div class="input-group-prepend"> <span class="input-group-text">Date de publication</span> </div> {{ form_widget(form.children['datePublication']) }} <div class="input-group-append"> <span class="input-group-text" ><i class="fas fa-th"></i></span> </div> </div> {{ form_widget(form.children['save'], {'attr': {'class': 'btn btn-info btn-block my-4'} }) }} {{ form_end(form) }} </div> </div> {% endblock %} {% block javascripts %} {{ parent() }} <script type="text/javascript" src="{{ asset('libraries/bootstrap-datepicker-1.9.0-dist/js/bootstrap-datepicker.min.js') }}"></script> <script> $('#form-ajout-oeuvre .input-group.date').datepicker({ language: "fr", autoclose: true, }); </script> <script src="{{asset('js/loadScripts.js')}}"></script> <script src="{{asset('js/oeuvreDeposit.js')}}"></script> {% endblock %} {% block stylesheets %} {{ parent() }} <link href="{{ asset('libraries/bootstrap-datepicker-1.9.0-dist/css/bootstrap-datepicker3.min.css') }}" rel="stylesheet"/> {% endblock %}
21,917
https://github.com/thinhlv02/lazum3_dalcheeni/blob/master/application/controllers/admin/Phieuluong.php
Github Open Source
Open Source
LicenseRef-scancode-unknown-license-reference, MIT
2,018
lazum3_dalcheeni
thinhlv02
PHP
Code
863
4,858
<?php require APPPATH . "libraries/PHPExcel.php"; Class Phieuluong extends MY_Controller { function __construct() { parent::__construct(); $this->load->model('phieuluong_model'); $this->load->model('employee_model'); $this->load->model('level_model'); $this->load->model('congphatsinh_model'); $input = array(); $input['where'] = array( 'role' => 2 ); $emp = $this->employee_model->get_list($input); $this->data['emp'] = $emp; } function index() { if ($this->input->post('btnAddEvent')) { $employee = $this->input->post('employee'); $from = $this->input->post('txtFrom'); $from = new DateTime($from); $from = $from->getTimestamp(); $to = $this->input->post('txtTo'); $to = new DateTime($to); $to = $to->getTimestamp(); $name_e = $this->employee_model->get_info($employee)->name; // $level_e = $this->level_model->get_info($employee)->name; /*get level name*/ $sql = "SELECT a.`level`, b.`level_name` FROM `dalcheeni_lazum3`.`employee` a JOIN dalcheeni_lazum3.`level` b ON a.`level` = b.`id` WHERE a.`id` = $employee "; $rows = $this->level_model->query($sql); // pre($rows); // return $rows->result(); $this->session->set_userdata('level_e', $rows); // pre($rows); /*end level name*/ $employee = $this->phieuluong_model->demo($employee, $from, $to); $this->data['res'] = $employee; // pre($employee[0]); /*Thêm bảng công phát sinh vào phiếu lương*/ $input_cps = array(); $input_cps['where'] = array( 'name' => $this->input->post('employee'), 'date >=' => $from, 'date <=' => $to ); $congphatsinh = $this->congphatsinh_model->get_list($input_cps); $this->data['congphatsinh'] = $congphatsinh; $this->session->set_userdata('congphatsinh', $congphatsinh); // pre($congphatsinh); /*End Thêm bảng công phát sinh vào phiếu lương*/ $this->session->set_userdata('result', $employee); $this->session->set_userdata('name_e', $name_e); $this->session->set_userdata('from', $from); $this->session->set_userdata('to', $to); } // export data if ($this->input->post('btnExportData')) { $data = $this->session->userdata('result'); $congphatsinh = $this->session->userdata('congphatsinh'); $name_e = $this->session->userdata('name_e'); $level_e = $this->session->userdata('level_e'); $from = $this->session->userdata('from'); $to = $this->session->userdata('to'); // $level_e = $level_e['level_name']; // pre($level_e[0]->level_name); $this->load->library("excel"); $objPHPExcel = new PHPExcel(); /* ADD LOGO */ $objDrawing = new PHPExcel_Worksheet_Drawing(); $objDrawing->setName('Logo'); $objDrawing->setDescription('Logo'); $objDrawing->setPath('public/lichtuan.png'); $objDrawing->setCoordinates('A1'); // set resize to false first $objDrawing->setResizeProportional(false); $objDrawing->setWidthAndHeight(168, 94); $objDrawing->setResizeProportional(true); // set width later // $objDrawing->setWidth(145); $objDrawing->setWorksheet($objPHPExcel->getActiveSheet()); // $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(5); /* END LOGO */ //define center text $center = array( 'alignment' => array( 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, ) ); $objPHPExcel->setActiveSheetIndex(0); $sheet = $objPHPExcel->getActiveSheet(); $objPHPExcel->setActiveSheetIndex(0)->mergeCells('B2:D2'); $sheet->getStyle('B2:D2')->applyFromArray($center); $sheet->setCellValueByColumnAndRow(1, 2, "PHIẾU LƯƠNG CÁ NHÂN"); $objPHPExcel->getActiveSheet()->getStyle('B2:D2')->getFont()->setBold(true); $sheet->getStyle('D2:F2')->applyFromArray($center); $objPHPExcel->getActiveSheet()->getStyle('B5:B7')->getFont()->setBold(true); $sheet2 = $objPHPExcel->getActiveSheet(); $objPHPExcel->setActiveSheetIndex(0)->mergeCells('B3:D3'); $sheet2->setCellValueByColumnAndRow(1, 4, "Từ " . date('d/m/Y', $from) . ' đến ' . date('d/m/Y', $to)); $sheet->getStyle('B3:D3')->applyFromArray($center); $sheet3 = $objPHPExcel->getActiveSheet(); $sheet3->setCellValueByColumnAndRow(1, 5, "Họ và Tên: "); $sheet5 = $objPHPExcel->getActiveSheet(); $sheet5->setCellValueByColumnAndRow(2, 5, $name_e); $sheet8 = $objPHPExcel->getActiveSheet(); $sheet8->setCellValueByColumnAndRow(1, 6, "Chức Vụ: "); $sheet9 = $objPHPExcel->getActiveSheet(); $sheet9->setCellValueByColumnAndRow(2, 6, $level_e[0]->level_name); $sheet6 = $objPHPExcel->getActiveSheet(); $sheet6->setCellValueByColumnAndRow(1, 7, "Đơn vị: "); $sheet7 = $objPHPExcel->getActiveSheet(); $sheet7->setCellValueByColumnAndRow(2, 7, "dalcheeni_lazum3"); // pre($data); //this breaks the width calculation // $sheet->mergeCells('D2:G2'); // $sheet->getColumnDimension('A')->setAutoSize(true); $objPHPExcel->getActiveSheet()->SetCellValue('A9', 'Địa điểm'); $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25); $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(14); $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15); $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15); // $objPHPExcel->getActiveSheet()->getColumnDimension('A9')->setWidth(100); $objPHPExcel->getActiveSheet()->SetCellValue('B9', 'Số NC'); $objPHPExcel->getActiveSheet()->SetCellValue('C9', 'Lương'); $objPHPExcel->getActiveSheet()->SetCellValue('D9', 'Tổng lương'); // công phát sinh $objPHPExcel->getActiveSheet()->SetCellValue('F9', 'Sự kiện'); $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(25); $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(14); $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15); $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15); $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(25); // $objPHPExcel->getActiveSheet()->getColumnDimension('A9')->setWidth(100); $objPHPExcel->getActiveSheet()->SetCellValue('G9', 'Tiền'); $objPHPExcel->getActiveSheet()->SetCellValue('H9', 'Ghi chú'); $objPHPExcel->getActiveSheet()->SetCellValue('I9', 'Loại'); $objPHPExcel->getActiveSheet()->SetCellValue('J9', 'Ngày tháng'); // End công phát sinh $objPHPExcel ->getActiveSheet() ->getStyle('A9:D9') ->getFill() ->setFillType(PHPExcel_Style_Fill::FILL_SOLID) ->getStartColor() ->setRGB('F5DEB3'); //i.e,colorcode=D3D3D3 // $column = 0; // foreach ($tableColumns as $field) { // $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($column, 1, $field); // $column++; // } $i = 10; $total = 0; foreach ($data as $row) { $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $i, $row->name); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(1, $i, number_format($row->nc)); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(2, $i, number_format($row->luong)); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, $i, number_format($row->money)); /*borders*/ $BStyle = array( 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, // 'color' => array('rgb' => '6665ff') ) ) ); $objPHPExcel->getActiveSheet()->getStyle('A' . ($i) . ':D' . ($i))->applyFromArray($BStyle); /*borders*/ $i++; // pre($row); $total += $row->money; } $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $i, 'Tổng Lương'); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, $i, number_format($total)); $objPHPExcel->setActiveSheetIndex(0)->mergeCells('A' . ($i) . ':C' . ($i)); $objPHPExcel ->getActiveSheet() ->getStyle('A' . ($i) . ':D' . ($i)) ->getFill() ->setFillType(PHPExcel_Style_Fill::FILL_SOLID) ->getStartColor() ->setRGB('F5DEB3'); //i.e,colorcode=D3D3D3 // $sheet->mergeCells("G".($row_count+1).":I".($row_count+4)); $i++; $j = $i; $i++; $i++; $i++; $objPHPExcel->setActiveSheetIndex(0)->mergeCells('I' . ($i + 1) . ':J' . ($i + 1)); $sheet->getStyle('I' . ($i + 1) . ':J' . ($i + 1))->applyFromArray($center); $objPHPExcel->setActiveSheetIndex(0)->mergeCells('I' . ($i + 2) . ':J' . ($i + 2)); $sheet->getStyle('I' . ($i + 2) . ':J' . ($i + 2))->applyFromArray($center); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(8, $i + 1, 'Hà Nội, ngày ' . date('d') . ' tháng ' . date('m') . ' năm ' . date('Y')); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(8, $i + 2, 'Người lập '); $objPHPExcel->getActiveSheet()->getStyle('I' . ($i + 1))->getFont()->setBold(true); // $objPHPExcel->getActiveSheet()->getStyle('G' . ($i + 2))->getFont()->setBold(true); // công phát sinh $i = 10; $total_cps = 0; foreach ($congphatsinh as $row) { $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, $i, $row->event); if ($row->type == 0) { $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, $i, number_format($row->money)); } else { $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, $i, '-' . number_format($row->money)); } $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7, $i, $row->note); if ($row->type == 0) { $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(8, $i, 'Công phát sinh'); } else { $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(8, $i, 'Phạt'); } $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(9, $i, date('d-m-Y', $row->date)); /*borders*/ $BStyle = array( 'borders' => array( 'allborders' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, // 'color' => array('rgb' => '6665ff') ) ) ); $objPHPExcel->getActiveSheet()->getStyle('F' . ($i) . ':J' . ($i))->applyFromArray($BStyle); /*borders*/ $i++; // pre($row); if ($row->type == 0) { $total_cps += $row->money; } else { $total_cps -= $row->money; } } $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(5, $i, 'Tổng còn'); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(6, $i, number_format($total_cps)); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(7, $i, 'vnđ'); // end công phát sinh $j++; $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(0, $j, 'Tổng Lương thực'); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(3, $j, number_format($total + $total_cps)); $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow(4, $j, 'vnđ'); // $i++; $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); header("Content-Type: application/vnd.ms-excel"); header('Content-Disposition: attachment; filename="phieuluong.xls"'); $objWriter->save('php://output'); } // /export data $message = $this->session->flashdata('message'); $this->data['message'] = $message; $this->data['temp'] = 'admin/phieuluong/phieuluong'; $this->load->view('admin/layout', $this->data); } // excel public function excel() { require(APPPATH . 'third_party/PHPExcel-1.8/Classes/PHPExcel.php'); require(APPPATH . 'third_party/PHPExcel-1.8/Classes/PHPExcel/Writer/Excel2007.php'); $objPHPExcel = new PHPExcel(); $objPHPExcel->getProperties()->setCreator(""); $objPHPExcel->getProperties()->setLastModifiedBy(""); $objPHPExcel->getProperties()->setTitle(""); $objPHPExcel->getProperties()->setSubject(""); $objPHPExcel->getProperties()->setDescription(""); $objPHPExcel->setActiveSheetIndex(0); $objPHPExcel->getActiveSheet()->SetCellValue('A1', 'Địa điểm'); $objPHPExcel->getActiveSheet()->SetCellValue('B1', 'Số NC'); $objPHPExcel->getActiveSheet()->SetCellValue('C1', 'Lương'); $objPHPExcel->getActiveSheet()->SetCellValue('D1', 'Tổng lương'); if ($this->input->post('btnAddEvent')) { $employee = $this->input->post('employee'); $from = $this->input->post('txtFrom'); $from = new DateTime($from); $from = $from->getTimestamp(); $to = $this->input->post('txtTo'); $to = new DateTime($to); $to = $to->getTimestamp(); // pre($SERVICE_NUMBER_NAME); // $input['where'] = array( // 'COMMAND_CODE_NAME' => $COMMAND_CODE_NAME, // 'SUB_CP_ID' => $SUB_CP_ID // ); $employee = $this->phieuluong_model->demo($employee, $from, $to); $this->data['res'] = $employee; pre($employee); // echo '<prev>'; // print_r($employee); // echo '</prev>'; } $row = 2; } // /excel }
19,429
https://github.com/tlk-emb/PhoenixCMS/blob/master/home_page_local/rel/home_page/lib/timex-3.5.0/priv/translations/ja/LC_MESSAGES/relative_time.po
Github Open Source
Open Source
Apache-2.0
2,020
PhoenixCMS
tlk-emb
Gettext Catalog
Code
494
2,177
# # `msgid`s in this file come from POT (.pot) files. # # # # Do not add, change, or remove `msgid`s manually here as # # they're tied to the ones in the corresponding POT file # # (with the same domain). # # # # Use `mix gettext.extract --merge` or `mix gettext.merge` # # to merge POT files into PO files. msgid "" msgstr "" "Language: ja\n" "Plural-Forms: nplurals=1; plural=0;\n" "Project-Id-Version: \n" "POT-Creation-Date: \n" "PO-Revision-Date: \n" "Last-Translator: \n" "Language-Team: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "X-Generator: Poedit 1.8.7\n" #: lib/l10n/translator.ex:237 msgid "last month" msgstr "先月" #: lib/l10n/translator.ex:243 msgid "last week" msgstr "先週" #: lib/l10n/translator.ex:231 msgid "last year" msgstr "去年" #: lib/l10n/translator.ex:239 msgid "next month" msgstr "来月" #: lib/l10n/translator.ex:245 msgid "next week" msgstr "来週" #: lib/l10n/translator.ex:233 msgid "next year" msgstr "来年" #: lib/l10n/translator.ex:238 msgid "this month" msgstr "今月" #: lib/l10n/translator.ex:244 msgid "this week" msgstr "今週" #: lib/l10n/translator.ex:232 msgid "this year" msgstr "今年" #: lib/l10n/translator.ex:250 msgid "today" msgstr "今日" #: lib/l10n/translator.ex:251 msgid "tomorrow" msgstr "明日" #: lib/l10n/translator.ex:249 msgid "yesterday" msgstr "昨日" #: lib/l10n/translator.ex:253 msgid "%{count} day ago" msgid_plural "%{count} days ago" msgstr[0] "%{count}日前" #: lib/l10n/translator.ex:278 msgid "%{count} hour ago" msgid_plural "%{count} hours ago" msgstr[0] "%{count}時間前" #: lib/l10n/translator.ex:281 msgid "%{count} minute ago" msgid_plural "%{count} minutes ago" msgstr[0] "%{count}分前" #: lib/l10n/translator.ex:241 msgid "%{count} month ago" msgid_plural "%{count} months ago" msgstr[0] "%{count}ヶ月前" #: lib/l10n/translator.ex:284 msgid "%{count} second ago" msgid_plural "%{count} seconds ago" msgstr[0] "%{count}秒前" #: lib/l10n/translator.ex:247 msgid "%{count} week ago" msgid_plural "%{count} weeks ago" msgstr[0] "%{count}週間前" #: lib/l10n/translator.ex:235 msgid "%{count} year ago" msgid_plural "%{count} years ago" msgstr[0] "%{count}年前" #: lib/l10n/translator.ex:252 msgid "in %{count} day" msgid_plural "in %{count} days" msgstr[0] "%{count}日後" #: lib/l10n/translator.ex:277 msgid "in %{count} hour" msgid_plural "in %{count} hours" msgstr[0] "%{count}時間後" #: lib/l10n/translator.ex:280 msgid "in %{count} minute" msgid_plural "in %{count} minutes" msgstr[0] "%{count}分後" #: lib/l10n/translator.ex:240 msgid "in %{count} month" msgid_plural "in %{count} months" msgstr[0] "%{count}ヶ月後" #: lib/l10n/translator.ex:283 msgid "in %{count} second" msgid_plural "in %{count} seconds" msgstr[0] "%{count}秒後" #: lib/l10n/translator.ex:246 msgid "in %{count} week" msgid_plural "in %{count} weeks" msgstr[0] "%{count}週間後" #: lib/l10n/translator.ex:234 msgid "in %{count} year" msgid_plural "in %{count} years" msgstr[0] "%{count}年後" #: lib/l10n/translator.ex:267 msgid "last friday" msgstr "先週の金曜日" #: lib/l10n/translator.ex:255 msgid "last monday" msgstr "先週の月曜日" #: lib/l10n/translator.ex:270 msgid "last saturday" msgstr "先週の土曜日" #: lib/l10n/translator.ex:273 msgid "last sunday" msgstr "先週の日曜日" #: lib/l10n/translator.ex:264 msgid "last thursday" msgstr "先週の木曜日" #: lib/l10n/translator.ex:258 msgid "last tuesday" msgstr "先週の火曜日" #: lib/l10n/translator.ex:261 msgid "last wednesday" msgstr "先週の水曜日" #: lib/l10n/translator.ex:269 msgid "next friday" msgstr "来週の金曜日" #: lib/l10n/translator.ex:257 msgid "next monday" msgstr "来週の月曜日" #: lib/l10n/translator.ex:272 msgid "next saturday" msgstr "来週の土曜日" #: lib/l10n/translator.ex:275 msgid "next sunday" msgstr "来週の日曜日" #: lib/l10n/translator.ex:266 msgid "next thursday" msgstr "来週の木曜日" #: lib/l10n/translator.ex:260 msgid "next tuesday" msgstr "来週の火曜日" #: lib/l10n/translator.ex:263 msgid "next wednesday" msgstr "来週の水曜日" #: lib/l10n/translator.ex:268 msgid "this friday" msgstr "今週の金曜日" #: lib/l10n/translator.ex:256 msgid "this monday" msgstr "今週の月曜日" #: lib/l10n/translator.ex:271 msgid "this saturday" msgstr "今週の土曜日" #: lib/l10n/translator.ex:274 msgid "this sunday" msgstr "今週の日曜日" #: lib/l10n/translator.ex:265 msgid "this thursday" msgstr "今週の木曜日" #: lib/l10n/translator.ex:259 msgid "this tuesday" msgstr "今週の火曜日" #: lib/l10n/translator.ex:262 msgid "this wednesday" msgstr "今週の水曜日" #: lib/l10n/translator.ex:286 msgid "now" msgstr ""
1,352
https://github.com/shaojiankui/iOS10-Runtime-Headers/blob/master/protocols/UISearchDisplayDelegate.h
Github Open Source
Open Source
MIT
2,018
iOS10-Runtime-Headers
shaojiankui
C
Code
62
368
/* Generated by RuntimeBrowser. */ @protocol UISearchDisplayDelegate <NSObject> @optional - (void)searchDisplayController:(UISearchDisplayController *)arg1 didHideSearchResultsTableView:(UITableView *)arg2; - (void)searchDisplayController:(UISearchDisplayController *)arg1 didLoadSearchResultsTableView:(UITableView *)arg2; - (void)searchDisplayController:(UISearchDisplayController *)arg1 didShowSearchResultsTableView:(UITableView *)arg2; - (bool)searchDisplayController:(UISearchDisplayController *)arg1 shouldReloadTableForSearchScope:(long long)arg2; - (bool)searchDisplayController:(UISearchDisplayController *)arg1 shouldReloadTableForSearchString:(NSString *)arg2; - (void)searchDisplayController:(UISearchDisplayController *)arg1 willHideSearchResultsTableView:(UITableView *)arg2; - (void)searchDisplayController:(UISearchDisplayController *)arg1 willShowSearchResultsTableView:(UITableView *)arg2; - (void)searchDisplayController:(UISearchDisplayController *)arg1 willUnloadSearchResultsTableView:(UITableView *)arg2; - (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController *)arg1; - (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)arg1; - (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)arg1; - (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)arg1; @end
34,397
https://github.com/Scottx86-64/dotfiles-1/blob/master/source/pkgsrc/lang/mozjs78/patches/patch-js_src_threading_posix_PosixThread.cpp
Github Open Source
Open Source
Unlicense
2,021
dotfiles-1
Scottx86-64
C++
Code
50
218
$NetBSD: patch-js_src_threading_posix_PosixThread.cpp,v 1.1 2020/12/06 10:50:03 nia Exp $ illumos pthreads don't have pthread_setname_np. --- js/src/threading/posix/PosixThread.cpp.orig 2020-11-04 10:52:03.000000000 +0000 +++ js/src/threading/posix/PosixThread.cpp @@ -103,6 +103,8 @@ void ThisThread::SetName(const char* nam rv = 0; #elif defined(__NetBSD__) rv = pthread_setname_np(pthread_self(), "%s", (void*)name); +#elif defined(__sun) + rv = 0; #else rv = pthread_setname_np(pthread_self(), name); #endif
26,340
https://github.com/ValtoFrameworks/bsf/blob/master/Source/Scripting/bsfScript/Serialization/BsManagedSerializableField.h
Github Open Source
Open Source
MIT
2,019
bsf
ValtoFrameworks
C
Code
2,359
8,720
//********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #pragma once #include "BsScriptEnginePrerequisites.h" #include "Reflection/BsIReflectable.h" namespace bs { /** @addtogroup bsfScript * @{ */ /** * Contains data that can be used for identifying a field in an object when cross referenced with the object type. * * @note * Essentially a light-weight identifier for the field so that we don't need to store entire field type for each field * when serializing. Instead field types are stored separately and we just use this object for lookup. */ class BS_SCR_BE_EXPORT ManagedSerializableFieldKey : public IReflectable { public: ManagedSerializableFieldKey() = default; ManagedSerializableFieldKey(UINT16 typeId, UINT16 fieldId); /** * Creates a new field key. * * @param[in] typeId Unique ID of the parent type the field belongs to. See ManagedSerializableTypeInfoObject. * @param[in] fieldId Unique ID of the field within its parent class. See ManagedSerializableObjectInfo. */ static SPtr<ManagedSerializableFieldKey> create(UINT16 typeId, UINT16 fieldId); UINT16 mTypeId = 0; UINT16 mFieldId = 0; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ScriptSerializableFieldDataKeyRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains value of a single field in a managed object. This class can contain any data type and should be overridden * for specific types. * * Stored values can be serialized and stored for later use, and deserialized back to managed objects when needed. You * must call serialize() before performing RTTI serialization. After field data has been serialized you should not call * any methods on it before calling deserialize(). */ class BS_SCR_BE_EXPORT ManagedSerializableFieldData : public IReflectable { public: virtual ~ManagedSerializableFieldData() = default; /** * Creates a new data wrapper for some field data. * * @param[in] typeInfo Type of the data we're storing. * @param[in] value Managed boxed value to store in the field. Value will be copied into the internal buffer * and stored. */ static SPtr<ManagedSerializableFieldData> create(const SPtr<ManagedSerializableTypeInfo>& typeInfo, MonoObject* value); /** * Creates a new data wrapper containing default instance of the provided type. * * @param[in] typeInfo Type of the data we're storing. */ static SPtr<ManagedSerializableFieldData> createDefault(const SPtr<ManagedSerializableTypeInfo>& typeInfo); /** * Returns the internal value. * * @param[in] typeInfo Type of the data we're looking to retrieve. This isn't required for actually retrieving * the data but is used as an extra check to ensure the field contains the data type we're * looking for. * @return Pointer to the internal serialized data. Caller must ensure the pointer is cast to the * proper type. */ virtual void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) = 0; /** * Boxes the internal value and returns it. * * @param[in] typeInfo Type of the data we're looking to retrieve. This isn't required for actually retrieving * the data but is used as an extra check to ensure the field contains the data type we're * looking for. * @return Boxed representation of the internal value. */ virtual MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) = 0; /** * Checks if the internal value stored in this object matches the value stored in another. Does shallow comparison * for complex objects. */ virtual bool equals(const SPtr<ManagedSerializableFieldData>& other) = 0; /** Returns a hash value for the internally stored value. */ virtual size_t getHash() = 0; /** * Serializes the internal value so that it may be stored and deserialized later. * * @note * This is generally only relevant for complex objects, as primitive types have their values copied and serialized * automatically whenever field data is created. */ virtual void serialize() { } /** Deserializes the internal value so that the managed instance can be retrieved. */ virtual void deserialize() { } private: /** * Creates a new data wrapper for some field data. * * @param[in] typeInfo Type of the data we're storing. * @param[in] value Managed boxed value to store in the field. Value will be copied into the internal buffer * and stored. * @param[in] allowNull Determines should null values be allowed. If false the objects with null values will * instead be instantiated to their default values. */ static SPtr<ManagedSerializableFieldData> create(const SPtr<ManagedSerializableTypeInfo>& typeInfo, MonoObject* value, bool allowNull); /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** Contains type and value of a single field in an object. */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataEntry : public IReflectable { public: static SPtr<ManagedSerializableFieldDataEntry> create(const SPtr<ManagedSerializableFieldKey>& key, const SPtr<ManagedSerializableFieldData>& value); SPtr<ManagedSerializableFieldKey> mKey; SPtr<ManagedSerializableFieldData> mValue; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataEntryRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains boolean field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataBool : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataBool() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; bool value = false; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataBoolRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains wide character field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataChar : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataChar() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; wchar_t value = 0; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataCharRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains signed 8-bit integer field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataI8 : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataI8() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; INT8 value = 0; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataI8RTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains unsigned 8-bit integer field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataU8 : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataU8() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; UINT8 value = 0; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataU8RTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains signed 16-bit integer field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataI16 : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataI16() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; INT16 value = 0; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataI16RTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains unsigned 16-bit field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataU16 : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataU16() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; UINT16 value = 0; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataU16RTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains signed 32-bit integer field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataI32 : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataI32() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; INT32 value = 0; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataI32RTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains unsigned 32-bit integer field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataU32 : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataU32() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; UINT32 value = 0; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataU32RTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains signed 64-bit integer field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataI64 : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataI64() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; INT64 value = 0; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataI64RTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains unsigned 64-bit integer field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataU64 : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataU64() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; UINT64 value = 0; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataU64RTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains single precision floating point field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataFloat : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataFloat() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; float value = 0.0f; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataFloatRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains double precision floating point field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataDouble : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataDouble() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; double value = 0.0; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataDoubleRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains wide character string field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataString : public ManagedSerializableFieldData { public: ManagedSerializableFieldDataString() = default; /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; WString value; bool isNull = false; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataStringRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains resource reference field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataResourceRef : public ManagedSerializableFieldData { public: /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; HResource value; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataResourceRefRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains game object reference field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataGameObjectRef : public ManagedSerializableFieldData { public: /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; HGameObject value; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataGameObjectRefRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains field data for a native object implementing IReflectable. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataReflectableRef : public ManagedSerializableFieldData { public: /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; SPtr<IReflectable> value; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldReflectableRefRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains complex object field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataObject : public ManagedSerializableFieldData { public: /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; /** @copydoc ManagedSerializableFieldData::serialize */ void serialize() override; /** @copydoc ManagedSerializableFieldData::deserialize */ void deserialize() override; SPtr<ManagedSerializableObject> value; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataObjectRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains array field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataArray : public ManagedSerializableFieldData { public: /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; /** @copydoc ManagedSerializableFieldData::serialize */ void serialize() override; /** @copydoc ManagedSerializableFieldData::deserialize */ void deserialize() override; SPtr<ManagedSerializableArray> value; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataArrayRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains list field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataList : public ManagedSerializableFieldData { public: /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; /** @copydoc ManagedSerializableFieldData::serialize */ void serialize() override; /** @copydoc ManagedSerializableFieldData::deserialize */ void deserialize() override; SPtr<ManagedSerializableList> value; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataListRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** * Contains dictionary field data. * * @copydoc ManagedSerializableFieldData */ class BS_SCR_BE_EXPORT ManagedSerializableFieldDataDictionary : public ManagedSerializableFieldData { public: /** @copydoc ManagedSerializableFieldData::getValue */ void* getValue(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::getValueBoxed */ MonoObject* getValueBoxed(const SPtr<ManagedSerializableTypeInfo>& typeInfo) override; /** @copydoc ManagedSerializableFieldData::equals */ bool equals(const SPtr<ManagedSerializableFieldData>& other) override; /** @copydoc ManagedSerializableFieldData::getHash */ size_t getHash() override; /** @copydoc ManagedSerializableFieldData::serialize */ void serialize() override; /** @copydoc ManagedSerializableFieldData::deserialize */ void deserialize() override; SPtr<ManagedSerializableDictionary> value; /************************************************************************/ /* RTTI */ /************************************************************************/ public: friend class ManagedSerializableFieldDataDictionaryRTTI; static RTTITypeBase* getRTTIStatic(); RTTITypeBase* getRTTI() const override; }; /** @} */ }
48,789
https://github.com/yashkundu/ToDo-Web-App/blob/master/src/tasks/api/serializers.py
Github Open Source
Open Source
bzip2-1.0.6
null
ToDo-Web-App
yashkundu
Python
Code
74
226
from rest_framework import serializers from tasks.models import Task from accounts.api.serializers import UserPublicSerializer class TaskSerializer(serializers.ModelSerializer): user = UserPublicSerializer(read_only=True) class Meta: model = Task fields = [ 'user', 'task', 'is_completed', 'timestamp', 'id' ] read_only_fields = ['user'] def vaidate(self, data): task = data.get('task', None) if task == '': task = None if task is None: raise serializers.ValidationError('Task cannot be empty.') return data class TaskInlineSerializer(TaskSerializer): class Meta: model = Task fields = [ 'id', 'task', 'is_completed', 'timestamp' ]
16,549
https://github.com/BryanMendoza0309/ProyectoFinal/blob/master/app/Http/Controllers/ProveedorController.php
Github Open Source
Open Source
MIT
null
ProyectoFinal
BryanMendoza0309
PHP
Code
264
1,155
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Producto; use App\Stock; use App\Provedor; class ProveedorController extends Controller { public function load(Request $request) { $ListaProvedor=Provedor::all(); if ($request->ajax()) { return response()->json($ListaProvedor->toArray()); }else{ return view('adminlte::Paginas.Proveedores',compact('ListaProvedor'));; } } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $ListaProvedor=Provedor::all(); if ($request->ajax()) { return response()->json($ListaProvedor->toArray()); }else{ return view('adminlte::Paginas.Proveedores',compact('ListaProvedor')); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { if ($request->ajax()) { $tipo=new Provedor(); $tipo->nombreProvedor=$request->nombreProvedor; $tipo->tlfProvedor=$request->tlfProvedor; $tipo->direccion=$request->direccion; $tipo->caracteristicaProvedor=$request->caracteristicaProvedor; $tipo->eliminadolog=true; $tipo->save(); $id=$tipo->id; return response()->json(['mensaje'=>'Datos Ingresados Correctamente','id'=>$id]); } // return response()->json(['mensaje'=>'Datos Ingresados Correctamente','id'=>$tipo->id]); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $provedoredit=Provedor::find($id); return response()->json($provedoredit); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $provedoredit=Provedor::find($id); $provedoredit->nombreProvedor=$request->nombreProvedor; $provedoredit->tlfProvedor=$request->tlfProvedor; $provedoredit->direccion=$request->direccion; $provedoredit->caracteristicaProvedor=$request->caracteristicaProvedor; $provedoredit->save(); return response()->json(["mensaje"=>"listo"]); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $ListaProvedor=Provedor::find($id); $ListaProvedor->eliminadolog=false; $producto=Producto::all(); $stock2=Stock::all()->where('provedor_id',$id); foreach ( $stock2 as &$valor) { foreach ($producto as &$valor2) { if($valor2->stock_id==$valor->id){ $valor2->eliminadolog = false; $valor2->save(); } } $valor->eliminadolog = false; $valor->save(); } $ListaProvedor->save(); return response()->json(["mensaje"=>"listo"]); } }
13,458
https://github.com/ropensci/webchem/blob/master/man/get_chebiid.Rd
Github Open Source
Open Source
MIT
2,023
webchem
ropensci
R
Code
485
1,324
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/chebi.R \name{get_chebiid} \alias{get_chebiid} \title{Retrieve Lite Entity (identifiers) from ChEBI} \usage{ get_chebiid( query, from = c("all", "chebi id", "chebi name", "definition", "name", "iupac name", "citations", "registry numbers", "manual xrefs", "automatic xrefs", "formula", "mass", "monoisotopic mass", "charge", "inchi", "inchikey", "smiles", "species"), match = c("all", "best", "first", "ask", "na"), max_res = 200, stars = c("all", "two only", "three only"), verbose = getOption("verbose"), ... ) } \arguments{ \item{query}{character; search term.} \item{from}{character; type of input. \code{"all"} searches all types and \code{"name"} searches all names. Other options include \code{'chebi id'}, \code{'chebi name'}, \code{'definition'}, \code{'iupac name'}, \code{'citations'}, \code{'registry numbers'}, \code{'manual xrefs'}, \code{'automatic xrefs'}, \code{'formula'}, \code{'mass'}, \code{'monoisotopic mass'},\code{'charge'}, \code{'inchi'}, \code{'inchikey'}, \code{'smiles'}, and \code{'species'}} \item{match}{character; How should multiple hits be handled?, \code{"all"} all matches are returned, \code{"best"} the best matching (by the ChEBI searchscore) is returned, \code{"ask"} enters an interactive mode and the user is asked for input, \code{"na"} returns NA if multiple hits are found.} \item{max_res}{integer; maximum number of results to be retrieved from the web service} \item{stars}{character; "three only" restricts results to those manualy annotated by the ChEBI team.} \item{verbose}{logical; should a verbose output be printed on the console?} \item{...}{currently unused} } \value{ returns a list of data.frames containing a chebiid, a chebiasciiname, a searchscore and stars if matches were found. If not, data.frame(NA) is returned } \description{ Returns a data.frame with a ChEBI entity ID (chebiid), a ChEBI entity name (chebiasciiname), a search score (searchscore) and stars (stars) using the SOAP protocol: \url{https://www.ebi.ac.uk/chebi/webServices.do} } \examples{ \dontrun{ # might fail if API is not available get_chebiid('Glyphosate') get_chebiid('BPGDAMSIGCZZLK-UHFFFAOYSA-N') # multiple inputs comp <- c('Iron', 'Aspirin', 'BPGDAMSIGCZZLK-UHFFFAOYSA-N') get_chebiid(comp) } } \references{ Hastings J, Owen G, Dekker A, Ennis M, Kale N, Muthukrishnan V, Turner S, Swainston N, Mendes P, Steinbeck C. (2016). ChEBI in 2016: Improved services and an expanding collection of metabfolites. Nucleic Acids Res. Hastings, J., de Matos, P., Dekker, A., Ennis, M., Harsha, B., Kale, N., Muthukrishnan, V., Owen, G., Turner, S., Williams, M., and Steinbeck, C. (2013) The ChEBI reference database and ontology for biologically relevant chemistry: enhancements for 2013. Nucleic Acids Res. de Matos, P., Alcantara, R., Dekker, A., Ennis, M., Hastings, J., Haug, K., Spiteri, I., Turner, S., and Steinbeck, C. (2010) Chemical entities of biological interest: an update. Nucleic Acids Res. Degtyarenko, K., Hastings, J., de Matos, P., and Ennis, M. (2009). ChEBI: an open bioinformatics and cheminformatics resource. Current protocols in bioinformatics / editoral board, Andreas D. Baxevanis et al., Chapter 14. Degtyarenko, K., de Matos, P., Ennis, M., Hastings, J., Zbinden, M., McNaught, A., Alcántara, R., Darsow, M., Guedj, M. and Ashburner, M. (2008) ChEBI: a database and ontology for chemical entities of biological interest. Nucleic Acids Res. 36, D344–D350. Eduard Szöcs, Tamás Stirling, Eric R. Scott, Andreas Scharmüller, Ralf B. Schäfer (2020). webchem: An R Package to Retrieve Chemical Information from the Web. Journal of Statistical Software, 93(13). \doi{10.18637/jss.v093.i13}. }
4,630
https://github.com/rasp30024/roll20-api-scripts/blob/master/Vector Math/1.0/VecMath.js
Github Open Source
Open Source
MIT
2,022
roll20-api-scripts
rasp30024
JavaScript
Code
1,545
4,682
/** * This is a small library for (mostly 2D) vector mathematics. * Internally, the vectors used by this library are simple arrays of numbers. * The functions provided by this library do not alter the input vectors, * treating each vector as an immutable object. */ var VecMath = (function() { /** * Adds two vectors. * @param {vec} a * @param {vec} b * @return {vec} */ var add = function(a, b) { var result = []; for(var i=0; i<a.length; i++) { result[i] = a[i] + b[i]; } return result; }; /** * Creates a cloned copy of a vector. * @param {vec} v * @return {vec} */ var clone = function(v) { var result = []; for(var i=0; i < v.length; i++) { result.push(v[i]); } return result; }; /** * Returns an array representing the cross product of two 3D vectors. * @param {vec3} a * @param {vec3} b * @return {vec3} */ var cross = function(a, b) { var x = a[1]*b[2] - a[2]*b[1]; var y = a[2]*b[0] - a[0]*b[2]; var z = a[0]*b[1] - a[1]*b[0]; return [x, y, z]; }; /** * Returns the degree of a vector - the number of dimensions it has. * @param {vec} vector * @return {int} */ var degree = function(vector) { return vector.length; }; /** * Computes the distance between two points. * @param {vec} pt1 * @param {vec} pt2 * @return {number} */ var dist = function(pt1, pt2) { var v = vec(pt1, pt2); return length(v); }; /** * Returns the dot product of two vectors. * @param {vec} a * @param {vec} b * @return {number} */ var dot = function(a, b) { var result = 0; for(var i = 0; i < a.length; i++) { result += a[i]*b[i]; } return result; }; /** * Tests if two vectors are equal. * @param {vec} a * @param {vec} b * @param {float} [tolerance] A tolerance threshold for comparing vector * components. * @return {boolean} true iff the each of the vectors' corresponding * components are equal. */ var equal = function(a, b, tolerance) { if(a.length != b.length) return false; for(var i=0; i<a.length; i++) { if(tolerance !== undefined) { if(Math.abs(a[i] - b[i]) > tolerance) { return false; } } else if(a[i] != b[i]) return false; } return true; }; /** * Returns the length of a vector. * @param {vec} vector * @return {number} */ var length = function(vector) { var length = 0; for(var i=0; i < vector.length; i++) { length += vector[i]*vector[i]; } return Math.sqrt(length); }; /** * Computes the normalization of a vector - its unit vector. * @param {vec} v * @return {vec} */ var normalize = function(v) { var vHat = []; var vLength = length(v); for(var i=0; i < v.length; i++) { vHat[i] = v[i]/vLength; } return vHat; }; /** * Computes the projection of vector b onto vector a. * @param {vec} a * @param {vec} b * @return {vec} */ var projection = function(a, b) { var scalar = scalarProjection(a, b); var aHat = normalize(a); return scale(aHat, scalar); }; /** * Computes the distance from a point to an infinitely stretching line. * Works for either 2D or 3D points. * @param {vec2 || vec3} pt * @param {vec2 || vec3} linePt1 A point on the line. * @param {vec2 || vec3} linePt2 Another point on the line. * @return {number} */ var ptLineDist = function(pt, linePt1, linePt2) { var a = vec(linePt1, linePt2); var b = vec(linePt1, pt); // Make 2D vectors 3D to compute the cross product. if(!a[2]) a[2] = 0; if(!b[2]) b[2] = 0; var aHat = normalize(a); var aHatCrossB = cross(aHat, b); return length(aHatCrossB); }; /** * Computes the distance from a point to a line segment. * Works for either 2D or 3D points. * @param {vec2 || vec3} pt * @param {vec2 || vec3} linePt1 The start point of the segment. * @param {vec2 || vec3} linePt2 The end point of the segment. * @return {number} */ var ptSegDist = function(pt, linePt1, linePt2) { var a = vec(linePt1, linePt2); var b = vec(linePt1, pt); var aDotb = dot(a,b); // Is pt behind linePt1? if(aDotb < 0) { return length(vec(pt, linePt1)); } // Is pt after linePt2? else if(aDotb > dot(a,a)) { return length(vec(pt, linePt2)); } // Pt must be between linePt1 and linePt2. else { return ptLineDist(pt, linePt1, linePt2); } }; /** * Computes the scalar projection of b onto a. * @param {vec2} a * @param {vec2} b * @return {vec2} */ var scalarProjection = function(a, b) { var aDotB = dot(a, b); var aLength = length(a); return aDotB/aLength; }; /** * Computes a scaled vector. * @param {vec2} v * @param {number} scalar * @return {vec2} */ var scale = function(v, scalar) { var result = []; for(var i=0; i<v.length; i++) { result[i] = v[i]*scalar; } return result; }; /** * Computes the difference of two vectors. * @param {vec} a * @param {vec} b * @return {vec} */ var sub = function(a, b) { var result = []; for(var i=0; i<a.length; i++) { result.push(a[i] - b[i]); } return result; }; /** * Returns the vector from pt1 to pt2. * @param {vec} pt1 * @param {vec} pt2 * @return {vec} */ var vec = function(pt1, pt2) { var result = []; for(var i=0; i<pt1.length; i++) { result.push( pt2[i] - pt1[i] ); } return result; }; // The exposed API. return { add: add, clone: clone, cross: cross, degree: degree, dist: dist, dot: dot, equal: equal, length: length, normalize: normalize, projection: projection, ptLineDist: ptLineDist, ptSegDist: ptSegDist, scalarProjection: scalarProjection, scale: scale, sub: sub, vec: vec }; })(); // Perform unit tests. Inform us in the log if any test fails. Otherwise, // succeed silently. (function() { /** * Does a unit test. If the test evaluates to false, then it displays with * a message that the unit test failed. Otherwise it passes silently. * @param {boolean} test Some expression to test. * @param {string} failMsg A message displayed if the test fails. */ var assert = function(test, failMsg) { if(!test) { log("UNIT TEST FAILED: " + failMsg); } }; var a = [1, 5]; var b = [17, -8]; // VecMath.equal assert( VecMath.equal([2, -3, 4, 8], [2, -3, 4, 8]), "VecMath.equal([2, -3, 4, 8], [2, -3, 4, 8])" ); assert( !VecMath.equal([1, 3, 5], [-2, 4, -6]), "!VecMath.equal([1, 3, 5], [-2, 4, -6])" ); assert( !VecMath.equal([1, 3, 5], [1, 3, 4]), "!VecMath.equal([1, 3, 5], [1, 3, 4])" ); assert( !VecMath.equal([1,2,3], [1,2]), "!VecMath.equal([1,2,3], [1,2])" ); assert( !VecMath.equal([1,2], [1,2,3]), "!VecMath.equal([1,2], [1,2,3])" ); // VecMath.add assert( VecMath.equal( VecMath.add([1, 2, 3], [3, -5, 10]), [4, -3, 13] ), "VecMath.add([1, 2, 3], [3, -5, 10]) equals [4, -3, 13]" ); assert( VecMath.equal( VecMath.add([0, 0, 0], [1, 2, 3]), [1, 2, 3] ), "VecMath.add([0, 0, 0], [1, 2, 3]) equals [1, 2, 3]" ); // VecMath.clone assert( VecMath.equal( VecMath.clone(a), a), "VecMath.equal( VecMath.clone(a), a)" ); assert( VecMath.clone(a) != a, "VecMath.clone(a) != a" ); // VecMath.cross assert( VecMath.equal( VecMath.cross([1, 0, 0], [0, 1, 0]), [0, 0, 1] ), "VecMath.cross([1, 0, 0], [0, 1, 0]) equals [0, 0, 1]" ); assert( VecMath.equal( VecMath.cross([1,2,3], [-10, 3, 5]), [1, -35, 23] ), "VecMath.cross([1,2,3], [-10, 3, 5]) equals [1, -35, 23]" ); // VecMath.degree assert( VecMath.degree([1,2,3]) == 3, "VecMath.degree([1,2,3]) == 3" ); assert( VecMath.degree([1]) == 1, "VecMath.degree([1]) == 1" ); assert( VecMath.degree([1,1,1,1,1]) == 5, "VecMath.degree([1,1,1,1,1]) == 5" ); // VecMath.dist assert( VecMath.dist([1,2], [4,6]) == 5, "VecMath.dist([1,2], [4,6]) == 5" ); assert( VecMath.dist([3,4], [-3, -4]) == 10, "VecMath.dist([3,4], [-3, -4]) == 10" ); // VecMath.dot assert( VecMath.dot([1, 2, 3], [-1, -2, -3]) == -14, "VecMath.dot([1, 2, 3], [-1, -2, -3]) == -14" ); assert( VecMath.dot([1,0], [0,1]) == 0, "VecMath.dot([1,0], [0,1]) == 0" ); assert( VecMath.dot([1,0], [0,-1]) == 0, "VecMath.dot([1,0], [0,-1]) == 0" ); assert( VecMath.dot([1,0], [-1, 0]) == -1, "VecMath.dot([1,0], [-1, 0]) == -1" ); assert( VecMath.dot([1,0], [1, 0]) == 1, "VecMath.dot([1,0], [1, 0]) == 1" ); // VecMath.length assert( VecMath.length([1,0,0]) == 1, "VecMath.length([1,0,0]) == 1" ); assert( VecMath.length([3,4]) == 5, "VecMath.length([3,4]) == 5" ); assert( VecMath.length([-3, 0, 4, 0]) == 5, "VecMath.length([-3, 0, 4, 0]) == 5" ); // VecMath.normalize assert( VecMath.equal( VecMath.normalize([3,0]), [1, 0] ), "VecMath.normalize([3,0]) equals [1,0]" ); assert( VecMath.equal( VecMath.normalize([0,-3]), [0, -1] ), "VecMath.normalize([0,-3]) equals [0,-1]" ); // VecMath.projection assert( VecMath.equal( VecMath.projection([5,0], [3, 4]), [3, 0] ), "VecMath.projection([5,0], [3, 4]) equals [3, 0]" ); assert( VecMath.equal( VecMath.projection([5,5], [0, 6]), [3, 3], 0.001 ), "VecMath.projection([5,5], [0, 6]) equals [3, 3]" ); // VecMath.ptLineDist assert( VecMath.ptLineDist([0,3], [-100,5], [100,5]) == 2, "VecMath.ptLineDist([0,3], [-100,5], [100,5]) == 2" ); assert( VecMath.ptLineDist([3,0], [5,5], [5,10]) == 2, "VecMath.ptLineDist([3,0], [5,5], [5,10]) == 2" ); // VecMath.ptSegDist assert( VecMath.ptSegDist([0,3], [-5,5], [5,5]) == 2, "VecMath.ptSegDist([0,3], [-5,5], [5,5]) == 2" ); assert( VecMath.ptSegDist([3,0], [5,-5], [5,5]) == 2, "VecMath.ptSegDist([3,0], [5,-5], [5,5]) == 2" ); assert( VecMath.ptSegDist([3,4], [-5,0], [0,0]) == 5, "VecMath.ptSegDist([3,4], [-5,0], [0,0]) == 5" ); assert( VecMath.ptSegDist([-2,-4], [1,0], [5,0]) == 5, "VecMath.ptSegDist([-2,-4], [1,0], [5,0]) == 5" ); // VecMath.scalarProjection assert( VecMath.scalarProjection([5,0], [3, 4]) == 3, "VecMath.scalarProjection([5,0], [3, 4]) == 3" ); // VecMath.scale assert( VecMath.equal( VecMath.scale([1,-2,3], 6), [6, -12, 18] ), "VecMath.scale([1,-2,3], 6) equals [6, -12, 18]" ); // VecMath.sub assert( VecMath.equal( VecMath.sub([10, 8, 6], [-4, 6, 1]), [14, 2, 5] ), "VecMath.sub([10, 8, 6], [-4, 6, 1]) equals [14, 2, 5]" ); // VecMath.vec assert( VecMath.equal( VecMath.vec([1,1], [3,4]), [2,3] ), "VecMath.vec([1,1], [3,4]) equals [2,3]" ); })();
50,782
https://github.com/hileamlakB/GBK/blob/master/utils/str_util_adv2.c
Github Open Source
Open Source
MIT
null
GBK
hileamlakB
C
Code
221
558
#include "../gbk.h" /** *findd - finds the number occurance of tof in str *@str: string to be searched *@tof: string to fid *Return: the number of times teh delimeter ocures */ int findd(char *str, char *tof) { char *tokenized = NULL, *new = NULL; int i = 0; if (_strlen(tof) > _strlen(str)) return (0); new = _strdup(str); tokenized = _strtok(new, tof, 1); while (tokenized != NULL) { i++; tokenized = _strtok(NULL, tof, 1); } free(new); /*icase tofind is at th end*/ if (_strcmps(str + _strlen(str) - _strlen(tof), tof) == 1) i++; return (i - 1); } /** *fnrep - finds and replaces part of a string *@str: manipulated string (must be malloced) * this string should also be freed by the caller *@torep: subset of str to be replaced *@repwith: string to replace torep *Return: 0 on sucess and -1 on faliure */ int fnrep(char **str, char *torep, char *repwith) { char *tokenized = NULL, *tmp, *new = smalloc(1); int rep = 0, tor = findd(*str, torep), newlen = 0; tokenized = _strtok(*str, torep, 1); *new = '\0'; while (tokenized != NULL) { newlen = _strlen(new) + _strlen(tokenized) + _strlen(repwith); tmp = srealloc(new, newlen + 2); new = tmp; _strcat(new, tokenized); if (rep < tor) _strcat(new, repwith); rep++, tokenized = _strtok(NULL, torep, 1); } free(*str); *str = new; return (0); }
3,960
https://github.com/microg/GmsCore/blob/master/play-services-core/src/main/kotlin/org/microg/gms/auth/AuthPrefs.kt
Github Open Source
Open Source
Apache-2.0
2,023
GmsCore
microg
Kotlin
Code
48
202
package org.microg.gms.auth import android.content.Context import org.microg.gms.settings.SettingsContract import org.microg.gms.settings.SettingsContract.Auth object AuthPrefs { @JvmStatic fun isTrustGooglePermitted(context: Context): Boolean { return SettingsContract.getSettings(context, Auth.getContentUri(context), arrayOf(Auth.TRUST_GOOGLE)) { c -> c.getInt(0) != 0 } } @JvmStatic fun isAuthVisible(context: Context): Boolean { return SettingsContract.getSettings(context, Auth.getContentUri(context), arrayOf(Auth.VISIBLE)) { c -> c.getInt(0) != 0 } } }
17,247
https://github.com/RumbleFrog/Source-Map-Thumbnails/blob/master/meta/meta.go
Github Open Source
Open Source
MIT
2,018
Source-Map-Thumbnails
RumbleFrog
Go
Code
82
255
package meta type Angle_t struct { Pitch float64 Yaw float64 } type Coordinate_t [3]float64 type Position_t struct { Coordinate Coordinate_t Angle Angle_t } type Map_t struct { Name string Count int Positions []Position_t } func (a Angle_t) IsEqual(oa Angle_t) bool { return (a.Pitch == oa.Pitch && a.Yaw == oa.Yaw) } func (c Coordinate_t) IsEqual(oc Coordinate_t) bool { return (c[0] == oc[0] && c[1] == oc[1] && c[2] == oc[2]) } func (p Position_t) IsEqual(op Position_t) bool { return p.Coordinate.IsEqual(op.Coordinate) && p.Angle.IsEqual(op.Angle) }
23,057
https://github.com/alizarion/java-design-patterns/blob/master/command/src/main/java/com/iluwatar/App.java
Github Open Source
Open Source
MIT
2,021
java-design-patterns
alizarion
Java
Code
70
203
package com.iluwatar; /** * * In Command pattern actions are objects that can * be executed and undone. The commands in this example * are spells cast by the wizard on the goblin. * */ public class App { public static void main( String[] args ) { Wizard wizard = new Wizard(); Goblin goblin = new Goblin(); goblin.printStatus(); wizard.castSpell(new ShrinkSpell(), goblin); goblin.printStatus(); wizard.castSpell(new InvisibilitySpell(), goblin); goblin.printStatus(); wizard.undoLastSpell(); goblin.printStatus(); } }
14,149
https://github.com/Aaron120413/tools/blob/master/watermark/watermark_image.py
Github Open Source
Open Source
MIT
2,021
tools
Aaron120413
Python
Code
109
348
# coding=utf-8 import os import sys import fitz ''' pip install pymupdf ''' if len(sys.argv) < 2: print("use watermark.py filename.pdf") exit(0) if not os.path.exists(sys.argv[1]): print("file not exists") exit(0) dirname = os.path.dirname(__file__) if not os.path.exists("output"): os.makedirs('output') doc = fitz.open(sys.argv[1]) for nr in range(len(doc)): images = doc.getPageImageList(nr) if not images: continue maxsize = 0 image = None for var in images: size = var[2] * var[3] if maxsize < size: image = var maxsize = size xref = image[0] pix = fitz.Pixmap(doc, xref) name = f"output/{nr}.png" if pix.n < 5: # this is GRAY or RGB pix.writePNG(name) else: # CMYK: convert to RGB first pix1 = fitz.Pixmap(fitz.csRGB, pix) pix1.writePNG(name) print(name, pix)
35,376
https://github.com/Personalhomeman/VFSForGit/blob/master/ProjFS.Linux/PrjFSLib.Linux.Managed/Interop/ProjFS.cs
Github Open Source
Open Source
MIT
2,022
VFSForGit
Personalhomeman
C#
Code
581
1,968
using System; using System.Runtime.InteropServices; namespace PrjFSLib.Linux.Interop { internal partial class ProjFS { private const string PrjFSLibPath = "libprojfs.so"; private const string ProviderIdAttrName = "vfsforgit.providerid"; private const string ContentIdAttrName = "vfsforgit.contentid"; private const string StateAttrName = "empty"; private readonly IntPtr providerIdAttrNamePtr = Marshal.StringToHGlobalAnsi(ProviderIdAttrName); private readonly IntPtr contentIdAttrNamePtr = Marshal.StringToHGlobalAnsi(ContentIdAttrName); private readonly IntPtr stateAttrNamePtr = Marshal.StringToHGlobalAnsi(StateAttrName); private readonly IntPtr handle; private ProjFS(IntPtr handle) { this.handle = handle; } public delegate int EventHandler(ref Event ev); public static ProjFS New( string lowerdir, string mountdir, Handlers handlers, string[] argv) { IntPtr handle = _New( lowerdir, mountdir, ref handlers, (uint)Marshal.SizeOf<Handlers>(), IntPtr.Zero, argv.Length, argv); if (handle == IntPtr.Zero) { return null; } return new ProjFS(handle); } public int Start() { return _Start(this.handle); } public void Stop() { _Stop(this.handle); } public Result CreateProjDir( string relativePath, uint fileMode) { return _CreateProjDir( this.handle, relativePath, fileMode, new Attr[0], 0).ToResult(); } public Result CreateProjFile( string relativePath, ulong fileSize, uint fileMode, byte[] providerId, byte[] contentId) { unsafe { fixed (byte* providerIdPtr = providerId, contentIdPtr = contentId) { Attr[] attrs = new[] { new Attr { Name = (byte*)this.providerIdAttrNamePtr, Value = providerIdPtr, Size = providerId.Length }, new Attr { Name = (byte*)this.contentIdAttrNamePtr, Value = contentIdPtr, Size = contentId.Length } }; return _CreateProjFile( this.handle, relativePath, fileSize, fileMode, attrs, (uint)attrs.Length).ToResult(); } } } public Result CreateProjSymlink( string relativePath, string symlinkTarget) { return _CreateProjSymlink( this.handle, relativePath, symlinkTarget).ToResult(); } public Result GetProjAttrs( string relativePath, byte[] providerId, byte[] contentId) { unsafe { fixed (byte* providerIdPtr = providerId, contentIdPtr = contentId) { Attr[] attrs = new[] { new Attr { Name = (byte*)this.providerIdAttrNamePtr, Value = providerIdPtr, Size = providerId.Length }, new Attr { Name = (byte*)this.contentIdAttrNamePtr, Value = contentIdPtr, Size = contentId.Length } }; return _GetProjAttrs( this.handle, relativePath, attrs, (uint)attrs.Length).ToResult(); } } } public Result GetProjState( string relativePath, out ProjectionState state) { unsafe { byte stateAttr; Attr[] attrs = new[] { new Attr { Name = (byte*)this.stateAttrNamePtr, Value = &stateAttr, Size = 1 } }; int res = _GetProjAttrs( this.handle, relativePath, attrs, (uint)attrs.Length); Result result = res.ToResult(); if (result == Result.Success) { if (attrs[0].Size == -1) { state = ProjectionState.Full; } else if (stateAttr == 'n') { state = ProjectionState.Hydrated; } else if (stateAttr == 'y') { state = ProjectionState.Empty; } else { state = ProjectionState.Invalid; result = Result.Invalid; } } else if (res == Errno.Constants.EPERM) { // EPERM returned when inode is neither file nor directory state = ProjectionState.Unknown; result = Result.Invalid; } else { state = ProjectionState.Invalid; } return result; } } [DllImport(PrjFSLibPath, EntryPoint = "projfs_new")] private static extern IntPtr _New( string lowerdir, string mountdir, ref Handlers handlers, uint handlers_size, IntPtr user_data, int argc, string[] argv); [DllImport(PrjFSLibPath, EntryPoint = "projfs_start")] private static extern int _Start( IntPtr fs); [DllImport(PrjFSLibPath, EntryPoint = "projfs_stop")] private static extern IntPtr _Stop( IntPtr fs); [DllImport(PrjFSLibPath, EntryPoint = "projfs_create_proj_dir")] private static extern int _CreateProjDir( IntPtr fs, string relativePath, uint fileMode, Attr[] attrs, uint nattrs); [DllImport(PrjFSLibPath, EntryPoint = "projfs_create_proj_file")] private static extern int _CreateProjFile( IntPtr fs, string relativePath, ulong fileSize, uint fileMode, Attr[] attrs, uint nattrs); [DllImport(PrjFSLibPath, EntryPoint = "projfs_create_proj_symlink")] private static extern int _CreateProjSymlink( IntPtr fs, string relativePath, string symlinkTarget); [DllImport(PrjFSLibPath, EntryPoint = "projfs_get_attrs")] private static extern int _GetProjAttrs( IntPtr fs, string relativePath, [In, Out] Attr[] attrs, uint nattrs); [StructLayout(LayoutKind.Sequential)] public struct Event { public IntPtr Fs; public ulong Mask; public int Pid; public IntPtr Path; public IntPtr TargetPath; public int Fd; } [StructLayout(LayoutKind.Sequential)] public struct Handlers { public EventHandler HandleProjEvent; public EventHandler HandleNotifyEvent; public EventHandler HandlePermEvent; } [StructLayout(LayoutKind.Sequential)] public unsafe struct Attr { public byte* Name; public byte* Value; public long Size; } } }
35,486
https://github.com/isabella232/dart-sdk/blob/master/lib/src/configcat_cache.dart
Github Open Source
Open Source
MIT
null
dart-sdk
isabella232
Dart
Code
122
236
/// A cache API used to make custom cache implementations. abstract class ConfigCatCache { /// Child classes has to implement this method, the [ConfigCatClient] is /// using it to get the actual value from the cache. /// /// [key] is the key of the cache entry. Future<String> read(String key); /// Child classes has to implement this method, the [ConfigCatClient] is /// using it to set the actual cached value. /// /// [key] is the key of the cache entry. /// [value] is the new value to cache. Future<void> write(String key, String value); } /// Represents a null cache. class NullConfigCatCache extends ConfigCatCache { @override Future<String> read(String key) { return Future.value(''); } @override Future<void> write(String key, String value) { return Future.value(); } }
11,130
https://github.com/maksis/airdcpp-webui/blob/master/src/types/ui/widgets.ts
Github Open Source
Open Source
MIT
2,015
airdcpp-webui
maksis
TypeScript
Code
86
253
import { FormFieldDefinition } from './form'; import { ModuleActions } from './actions'; import { ModuleTranslator } from './modules'; export interface WidgetSettings<SettingsT = object> { widget: SettingsT; name?: string; } export interface WidgetProps<SettingsT = object> { componentId: string; settings: SettingsT; widgetT: ModuleTranslator; rootWidgetT: ModuleTranslator; //toWidgetI18nKey: (key?: string) => string; } export interface Widget { typeId: string; component: React.ComponentType<WidgetProps>; access?: string; alwaysShow?: boolean; name: string; icon: string; size: { w: number; h: number; minH: number; minW: number; }; actionMenu?: { actions: ModuleActions<void>; ids: string[]; }; formSettings?: FormFieldDefinition[]; }
9,098
https://github.com/maiome/malibu/blob/master/src/malibu/util/args.py
Github Open Source
Open Source
Unlicense
null
malibu
maiome
Python
Code
980
2,735
# -*- coding: utf-8 -*- import sys class ArgumentParser(object): OPTION_SINGLE = 1 OPTION_PARAMETERIZED = 2 PARAM_SHORT = 1 PARAM_LONG = 2 @classmethod def from_argv(cls): """ Creates an ArgumentParser engine with args from sys.argv[]. """ return cls(sys.argv) def __init__(self, args, mapping={}): """ Initializes an ArgumentParser instance. Parses out things that we already know, like args[0] (should be the executable script). """ try: self.exec_file = args[0] except: self.exec_file = '' self.__args = args self._default_types = { ArgumentParser.PARAM_SHORT: ArgumentParser.OPTION_SINGLE, ArgumentParser.PARAM_LONG: ArgumentParser.OPTION_SINGLE } self._opt_types = {} self._mapping = mapping self._aliases = {} self._descriptions = {} self.options = {} self.parameters = [] def __enter__(self): return self def __exit__(self, exc_type, exc_val, traceback): return None def param_defined(self, param): """ Checks all of the various ways a parameter can be a defined to see if the given parameter actually is defined. :param str param: Parameter to check for :return: parameter is defined :rtype: bool """ if param.startswith('-'): param = param.lstrip('-') is_typed = param in self._opt_types is_mapped = param in self._mapping is_described = False for _p in self.get_option_descriptions().keys(): if param in _p: is_described = True continue return is_typed or is_mapped or is_described def set_default_param_type(self, param_type, opt=OPTION_SINGLE): """ Sets the default type map that a parameter will be treated as. Can help force more uniform arguments without having to pre-define options. :param int param_type: Parameter type (PARAM_LONG, PARAM_SHORT) :param int opt: Option type (OPTION_PARAMETERIZED, OPTION_SINGLE) :return: none :rtype: None """ self._default_types[param_type] = opt def add_option(self, option, desc=None, optype=OPTION_SINGLE, aliases=[], map_name=None): """ Convenience method which takes care of typing, mapping, describing, and aliasing an option. :param str option: Option to add. :param str desc: String description of option. :param int optype: Option type (single or parameterized) :param list aliases: List of aliases to create for this option. :param str map_name: Mapping bucket to map all options to. :return: none :rtype: None """ if not optype: if len(option) > 1: optype = self._default_types[self.PARAM_LONG] elif len(option) == 1: optype = self._default_types[self.PARAM_SHORT] else: raise ValueError("Length of `option` is less than 1") self.add_option_type(option, optype, aliases) self.add_option_description(option, desc) if desc else None if not map_name: map_name = option self.add_option_mapping(option, map_name, aliases) if option not in self._aliases: self._aliases.update({ option: set(aliases), }) else: self._aliases[option].update(aliases) def add_option_type(self, option, opt=OPTION_SINGLE, aliases=[]): """ Adds a type mapping to a specific option. Allowed types are OPTION_SINGLE and OPTION_PARAMETERIZED. Also accepts aliases, which will be typed the same as `option`. :param str option: Option to set type for :param int opt: Option type (OPTION_PARAMETERIZED, OPTION_SINGLE) :return: none :rtype: None """ self._opt_types[option] = opt for alias in aliases: self._opt_types[alias] = opt def add_option_mapping(self, option, map_name, aliases=[]): """ Maps a option value (-a, -g, --thing, etc.) to a full word or phrase that will be stored in the options dictionary after parsing is finished. Makes option usage easier. :param str option: Option to map from :param str map_name: Option name to map to :return: none :rtype: None """ if not map_name: map_name = option self._mapping[option] = map_name for alias in aliases: self._mapping[alias] = map_name def add_option_description(self, option, description): """ Adds a helpful description for an argument. Is returned when get_option_descriptions is called. :param str option: Option to describe :param str description: Description of option :return: none :rtype: None """ self._descriptions[option] = description def get_option_aliases(self, option): """ Returns a set of the aliases for `option`. :param str option: Option to get aliases for. :return: Set of aliases or none :rtype: set or None """ return self._aliases.get(option, None) def get_formatted_option_aliases(self, option): """ Returns a list of strings, which are option aliases with the appropriate leader (-, --) prepended. :param str option: Option to get aliases for. :return: List of aliases or none :rtype: list or None """ opt_aliases = self.get_option_aliases(option) if not opt_aliases: return None aliases = [] for alias in opt_aliases: if len(alias) == 1: # flag aliases.append('-' + alias) elif len(alias) > 1 and option.startswith('-'): aliases.append(alias) elif len(alias) > 1 and not option.startswith('--'): aliases.append('--' + alias) return aliases def get_option_descriptions(self): """ Returns a map of options to their respective descriptions. Good for printing out a series of help messages describing usage. :param bool merge_aliases: Return combined option+alias keys? :return: Dictionary of option => description pairs :rtype: dict """ processed_descriptions = {} for option, description in self._descriptions.items(): if len(option) == 1: # This is a flag. Prepend a dash. option = '-' + option processed_descriptions.update({option: description}) elif len(option) > 1 and option.startswith('--'): # Option. Append blindly. processed_descriptions.update({option: description}) elif len(option) > 1 and not option.startswith('--'): # Option. Append double-dash. option = '--' + option processed_descriptions.update({option: description}) else: # What is this? Blindly append. processed_descriptions.update({option: description}) return processed_descriptions def parse(self): """ Parses out the args into the mappings provided in self.mapping, stores the result in self.options. :return: none :rtype: None """ waiting_argument = None for param in self.__args: if param[0] in ['"', "'"]: param = param.lstrip(param[0]) if param[-1] in ['"', "'"]: param = param.rstrip(param[-1]) if param.startswith('--'): # Long option mapping. paraml = param[2:] if '=' in paraml: param, value = paraml.split('=') # Store a PARAMETERIZED option type, if none exists. if param not in self._opt_types: self.add_option_type( param, ArgumentParser.OPTION_PARAMETERIZED) else: param = paraml if param not in self._opt_types: self.add_option_type( param, self._default_types[ArgumentParser.PARAM_LONG]) store_as = param if param in self._mapping: self.options.update({self._mapping[param]: True}) store_as = self._mapping[param] else: self.options.update({param: True}) if param in self._opt_types: ptype = self._opt_types[param] if ptype == ArgumentParser.OPTION_PARAMETERIZED: if '=' in paraml: # Option is long and contains the value. self.options.update({store_as: value}) waiting_argument = None else: waiting_argument = store_as elif param.startswith('-') and not self.param_defined(param): # Starts with a -, but is not a defined parameter. if waiting_argument is not None: self.options.update({waiting_argument: param}) waiting_argument = None else: self.parameters.append(param) continue elif param.startswith('-'): # Short option mapping. param = param[1:] for opt in param: store_as = opt if opt in self._mapping: self.options.update({self._mapping[opt]: True}) store_as = self._mapping[opt] else: self.options.update({opt: True}) if opt in self._opt_types: ptype = self._opt_types[opt] if ptype == ArgumentParser.OPTION_PARAMETERIZED: waiting_argument = store_as else: # Option parameter or command parameter. if waiting_argument is not None: self.options.update({waiting_argument: param}) waiting_argument = None else: self.parameters.append(param)
45,429
https://github.com/thedestiny/spring-framework/blob/master/src/docs/asciidoc/web/webflux-webclient.adoc
Github Open Source
Open Source
Apache-2.0
null
spring-framework
thedestiny
AsciiDoc
Code
1,446
4,303
[[webflux-client]] = WebClient Spring WebFlux includes a reactive, non-blocking `WebClient` for performing HTTP requests using a functional-style API that exposes Reactor `Flux` and `Mono` types, see <<web-reactive.adoc#webflux-reactive-libraries>>. The client relies on the same <<web-reactive.adoc#webflux-codecs,codecs>> that WebFlux server applications use to work with request and response content. Internally `WebClient` delegates to an HTTP client library. By default it uses https://github.com/reactor/reactor-netty[Reactor Netty], there is built-in support for the Jetty https://github.com/jetty-project/jetty-reactive-httpclient[reactive HtpClient], and others can be plugged in through a `ClientHttpConnector`. [[webflux-client-builder]] == Configuration The simplest way to create a `WebClient` is through one of the static factory methods: * `WebClient.create()` * `WebClient.create(String baseUrl)` The above uses Reactor Netty `HttpClient` from "io.projectreactor.netty:reactor-netty" with default settings and participates in global resources such for event loop threads and a connection pool, see <<webflux-client-builder-reactor, Reactor Netty configuration>>. The `WebClient.Builder` can be used for access to further options: * `uriBuilderFactory` -- customized `UriBuilderFactory` to use as a base URL. * `defaultHeader` -- headers for every request. * `defaultCookie)` -- cookies for every request. * `defaultRequest` -- `Consumer` to customize every request. * `filter` -- client filter for every request. * `exchangeStrategies` -- HTTP message reader/writer customizations. * `clientConnector` -- HTTP client library settings. For example, to configure <<web-reactive.adoc#webflux-codecs,HTTP codecs>>: [source,java,intent=0] [subs="verbatim,quotes"] ---- ExchangeStrategies strategies = ExchangeStrategies.builder() .codecs(configurer -> { // ... }) .build(); WebClient client = WebClient.builder() .exchangeStrategies(strategies) .build(); ---- Once built a `WebClient` instance is immutable. However, you can clone it, and build a modified copy without affecting the original instance: [source,java,intent=0] [subs="verbatim,quotes"] ---- WebClient client1 = WebClient.builder() .filter(filterA).filter(filterB).build(); WebClient client2 = client1.mutate() .filter(filterC).filter(filterD).build(); // client1 has filterA, filterB // client2 has filterA, filterB, filterC, filterD ---- [[webflux-client-builder-reactor]] === Reactor Netty To customize Reactor Netty settings: [source,java,intent=0] [subs="verbatim,quotes"] ---- HttpClient httpClient = HttpClient.create() httpClient.secure(sslSpec -> ...); ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient); WebClient webClient = WebClient.builder().clientConnector(connector).build(); ---- By default `HttpClient` participates in the global Reactor Netty resources held in `reactor.netty.http.HttpResources`, including event loop threads and a connection pool. This is the recommended mode since fixed, shared resources are preferred for event loop concurrency. In this mode global resources remain active until the process exits. If the server is timed with the process, there is typically no need for an explicit shutdown. However if the server can start or stop in-process, e.g. Spring MVC application deployed as a WAR, you can declare a Spring-managed bean of type `ReactorResourceFactory` with `globalResources=true` (the default) to ensure the Reactor Netty global resources are shut down when the Spring `ApplicationContext` is closed: [source,java,intent=0] [subs="verbatim,quotes"] ---- @Bean public ReactorResourceFactory reactorResourceFactory() { return new ReactorResourceFactory(); } ---- You may also choose not to participate in the global Reactor Netty resources. However keep in mind in this mode the burden is on you to ensure all Reactor Netty client and server instances use shared resources: [source,java,intent=0] [subs="verbatim,quotes"] ---- @Bean public ReactorResourceFactory resourceFactory() { ReactorResourceFactory factory = new ReactorResourceFactory(); factory.setGlobalResources(false); // <1> return factory; } @Bean public WebClient webClient() { Function<HttpClient, HttpClient> mapper = client -> { // Further customizations... }; ClientHttpConnector connector = new ReactorClientHttpConnector(resourceFactory(), mapper); // <2> return WebClient.builder().clientConnector(connector).build(); // <3> } ---- <1> Create resources independent of global ones. <2> Use `ReactorClientHttpConnector` constructor with resource factory. <3> Plug the connector into the `WebClient.Builder`. [[webflux-client-retrieve]] == Retrieve The `retrieve()` method is the easiest way to get a response body and decode it: [source,java,intent=0] [subs="verbatim,quotes"] ---- WebClient client = WebClient.create("http://example.org"); Mono<Person> result = client.get() .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON) .retrieve() .bodyToMono(Person.class); ---- You can also get a stream of objects decoded from the response: [source,java,intent=0] [subs="verbatim,quotes"] ---- Flux<Quote> result = client.get() .uri("/quotes").accept(MediaType.TEXT_EVENT_STREAM) .retrieve() .bodyToFlux(Quote.class); ---- By default, responses with 4xx or 5xx status codes result in an `WebClientResponseException` or one of its HTTP status specific sub-classes such as `WebClientResponseException.BadRequest`, `WebClientResponseException.NotFound`, and others. You can also use the `onStatus` method to customize the resulting exception: [source,java,intent=0] [subs="verbatim,quotes"] ---- Mono<Person> result = client.get() .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON) .retrieve() .onStatus(HttpStatus::is4xxServerError, response -> ...) .onStatus(HttpStatus::is5xxServerError, response -> ...) .bodyToMono(Person.class); ---- [[webflux-client-exchange]] == Exchange The `exchange()` method provides more control. The below example is equivalent to `retrieve()` but also provides access to the `ClientResponse`: [source,java,intent=0] [subs="verbatim,quotes"] ---- Mono<Person> result = client.get() .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON) .exchange() .flatMap(response -> response.bodyToMono(Person.class)); ---- At this level you can also create a full `ResponseEntity`: [source,java,intent=0] [subs="verbatim,quotes"] ---- Mono<ResponseEntity<Person>> result = client.get() .uri("/persons/{id}", id).accept(MediaType.APPLICATION_JSON) .exchange() .flatMap(response -> response.toEntity(Person.class)); ---- Note that unlike `retrieve()`, with `exchange()` there are no automatic error signals for 4xx and 5xx responses. You have to check the status code and decide how to proceed. [CAUTION] ==== When using `exchange()` you must always use any of the body or toEntity methods of `ClientResponse` to ensure resources are released and to avoid potential issues with HTTP connection pooling. You can use `bodyToMono(Void.class)` if no response content is expected. However keep in mind that if the response does have content, the connection will be closed and will not be placed back in the pool. ==== [[webflux-client-body]] == Request body The request body can be encoded from an Object: [source,java,intent=0] [subs="verbatim,quotes"] ---- Mono<Person> personMono = ... ; Mono<Void> result = client.post() .uri("/persons/{id}", id) .contentType(MediaType.APPLICATION_JSON) .body(personMono, Person.class) .retrieve() .bodyToMono(Void.class); ---- You can also have a stream of objects encoded: [source,java,intent=0] [subs="verbatim,quotes"] ---- Flux<Person> personFlux = ... ; Mono<Void> result = client.post() .uri("/persons/{id}", id) .contentType(MediaType.APPLICATION_STREAM_JSON) .body(personFlux, Person.class) .retrieve() .bodyToMono(Void.class); ---- Or if you have the actual value, use the `syncBody` shortcut method: [source,java,intent=0] [subs="verbatim,quotes"] ---- Person person = ... ; Mono<Void> result = client.post() .uri("/persons/{id}", id) .contentType(MediaType.APPLICATION_JSON) .syncBody(person) .retrieve() .bodyToMono(Void.class); ---- [[webflux-client-body-form]] === Form data To send form data, provide a `MultiValueMap<String, String>` as the body. Note that the content is automatically set to `"application/x-www-form-urlencoded"` by the `FormHttpMessageWriter`: [source,java,intent=0] [subs="verbatim,quotes"] ---- MultiValueMap<String, String> formData = ... ; Mono<Void> result = client.post() .uri("/path", id) .syncBody(formData) .retrieve() .bodyToMono(Void.class); ---- You can also supply form data in-line via `BodyInserters`: [source,java,intent=0] [subs="verbatim,quotes"] ---- import static org.springframework.web.reactive.function.BodyInserters.*; Mono<Void> result = client.post() .uri("/path", id) .body(fromFormData("k1", "v1").with("k2", "v2")) .retrieve() .bodyToMono(Void.class); ---- [[webflux-client-body-multipart]] === Multipart data To send multipart data, you need to provide a `MultiValueMap<String, ?>` whose values are either Objects representing part content, or `HttpEntity` representing the content and headers for a part. `MultipartBodyBuilder` provides a convenient API to prepare a multipart request: [source,java,intent=0] [subs="verbatim,quotes"] ---- MultipartBodyBuilder builder = new MultipartBodyBuilder(); builder.part("fieldPart", "fieldValue"); builder.part("filePart", new FileSystemResource("...logo.png")); builder.part("jsonPart", new Person("Jason")); MultiValueMap<String, HttpEntity<?>> parts = builder.build(); ---- In most cases you do not have to specify the `Content-Type` for each part. The content type is determined automatically based on the `HttpMessageWriter` chosen to serialize it, or in the case of a `Resource` based on the file extension. If necessary you can explicitly provide the `MediaType` to use for each part through one fo the overloaded builder `part` methods. Once a `MultiValueMap` is prepared, the easiest way to pass it to the the `WebClient` is through the `syncBody` method: [source,java,intent=0] [subs="verbatim,quotes"] ---- MultipartBodyBuilder builder = ...; Mono<Void> result = client.post() .uri("/path", id) .syncBody(**builder.build()**) .retrieve() .bodyToMono(Void.class); ---- If the `MultiValueMap` contains at least one non-String value, which could also be represent regular form data (i.e. "application/x-www-form-urlencoded"), you don't have to set the `Content-Type` to "multipart/form-data". This is always the case when using `MultipartBodyBuilder` which ensures an `HttpEntity` wrapper. As an alternative to `MultipartBodyBuilder`, you can also provide multipart content, inline-style, through the built-in `BodyInserters`. For example: [source,java,intent=0] [subs="verbatim,quotes"] ---- import static org.springframework.web.reactive.function.BodyInserters.*; Mono<Void> result = client.post() .uri("/path", id) .body(fromMultipartData("fieldPart", "value").with("filePart", resource)) .retrieve() .bodyToMono(Void.class); ---- [[webflux-client-filter]] == Client Filters You can register a client filter (`ExchangeFilterFunction`) through the `WebClient.Builder` in order to intercept and/or modify requests: [source,java,intent=0] [subs="verbatim,quotes"] ---- WebClient client = WebClient.builder() .filter((request, next) -> { ClientRequest filtered = ClientRequest.from(request) .header("foo", "bar") .build(); return next.exchange(filtered); }) .build(); ---- This can be used for cross-cutting concerns such as authentication. The example below uses a filter for basic authentication through a static factory method: [source,java,intent=0] [subs="verbatim,quotes"] ---- // static import of ExchangeFilterFunctions.basicAuthentication WebClient client = WebClient.builder() .filter(basicAuthentication("user", "password")) .build(); ---- Filters apply globally to every request. To change how a filter's behavior for a specific request, you can add request attributes to the `ClientRequest` that can then be accessed by all filters in the chain: [source,java,intent=0] [subs="verbatim,quotes"] ---- WebClient client = WebClient.builder() .filter((request, next) -> { Optional<Object> usr = request.attribute("myAttribute"); // ... }) .build(); client.get().uri("http://example.org/") .attribute("myAttribute", "...") .retrieve() .bodyToMono(Void.class); } ---- You can also replicate an existing `WebClient`, and insert new filters or remove already registered filters. In the example below, a basic authentication filter is inserted at index 0: [source,java,intent=0] [subs="verbatim,quotes"] ---- // static import of ExchangeFilterFunctions.basicAuthentication WebClient client = webClient.mutate() .filters(filterList -> { filterList.add(0, basicAuthentication("user", "password")); }) .build(); ---- [[webflux-client-testing]] == Testing To test code that uses the `WebClient`, you can use a mock web server such as the https://github.com/square/okhttp#mockwebserver[OkHttp MockWebServer]. To see example use, check https://github.com/spring-projects/spring-framework/blob/master/spring-webflux/src/test/java/org/springframework/web/reactive/function/client/WebClientIntegrationTests.java[WebClientIntegrationTests] in the Spring Framework tests, or the https://github.com/square/okhttp/tree/master/samples/static-server[static-server] sample in the OkHttp repository.
8,576
https://github.com/waldyrious/cosmopolitan/blob/master/libc/nt/ws2_32/WahCloseHandleHelper.s
Github Open Source
Open Source
0BSD
2,021
cosmopolitan
waldyrious
GAS
Code
4
42
.include "o/libc/nt/codegen.inc" .imp ws2_32,__imp_WahCloseHandleHelper,WahCloseHandleHelper,167
24,885
https://github.com/tu95ctv/28022017/blob/master/static/js/rnoc_js.js
Github Open Source
Open Source
MIT
2,017
28022017
tu95ctv
JavaScript
Code
4,948
19,888
var modelClassDict = { "su_co": "SuCo", "trang_thai": "TrangThai", "nguyen_nhan": "NguyenNhan", "thiet_bi": "ThietBi", "thao_tac_lien_quan": "ThaoTacLienQuan", "doi_tac": "DoiTac", "du_an": "DuAn", "component_lien_quan": "Component", "lenh_lien_quan": 'Lenh', }; var last_add_item SLASH_DISTINCTION = '/' $(document).ready(function() { var option_khong_tu_dong_search_tram option_khong_tu_dong_search_tram = $('input#id_khong_search_tu_dong_tram').prop('checked') $(".search-w input[type=text]").keyup(function(e) { if (e.keyCode == 13) { form_table_handle(e, 'intended_for_enter_search') } }); //.show-form-modal $(this).on('click', '#mll-form-table-wrapper span.input-group-addon,#modal-on-mll-tables span.input-group-addon,a.manager-a-form-select-link,select#id_chon_loai_de_quan_ly,.edit-entry-btn-on-table,form#model-manager input[type=submit],.show-modal-form-link,a.show-modal-form-link_allow_edit,a.searchtable_header_sort,.search-botton,.search-manager-botton,input.what_g_choice', form_table_handle) function form_table_handle(e, intended_for, abitrary_url, sort_field) { console.log("okkkkkkkkkkkkkkkkk first") return_sau_cuoi = false class_value = $(this).attr("class") is_no_show_return_form = false //is_both_table = "both form and table" is_table = true is_form = true form_table_template = "normal form template" //'form_on_modal' hieu_ung_sau_load_form_va_table = "khong hieu ung" if (intended_for) { closest_wrapper = $(e.target).closest('div.form-table-wrapper') } else { closest_wrapper = $(this).closest('div.form-table-wrapper') } id_closest_wrapper = closest_wrapper.attr('id') // no importaince var table_object is_get_table_request_get_parameter = false //table_name = '' // table_name dung de xac dinh table , sau khi submit form o modal se hien thi o day, trong truong hop force_allow_edit thi table_name attr se bi xoa if (intended_for == 'intended_for_autocomplete') { is_table = true is_form = true closest_wrapper = $('#form-table-of-tram-info') id_closest_wrapper = 'form-table-of-tram-info' url = abitrary_url type = "GET" data = {} console.log("$('input#id_khong_search_tu_dong').prop('checked')", $('input#id_khong_search_tu_dong').prop('checked')) if ($('input#id_khong_search_tu_dong').prop('checked')) { url = updateURLParameter(url, 'search_tu_dong_table_mll', 'no') } else { url = updateURLParameter(url, 'search_tu_dong_table_mll', 'yes') } if (name_attr_global != 'object') { hieu_ung_sau_load_form_va_table = 'active tram-form-toogle-li' } console.log('sort_field', sort_field) if (sort_field == 'SN1' || sort_field == 'SN2') { hieu_ung_sau_load_form_va_table = 'active thong-tin-tram toogle' } else if (sort_field == '3G') { hieu_ung_sau_load_form_va_table = 'active thong-tin-3g toogle' } else if (sort_field == '2G') { hieu_ung_sau_load_form_va_table = 'active thong-tin-2g toogle' } else if (sort_field == '4G') { hieu_ung_sau_load_form_va_table = 'active thong-tin-4g toogle' } } else if (intended_for == 'intended_for_manager_autocomplete') { is_both_table = "both form and table" is_table = true is_form = true closest_wrapper = wrapper_attr_global url = abitrary_url type = "GET" data = {} //@@@@@@@@@@@@@@@ } else if (intended_for == 'intended_for_enter_search' || class_value.indexOf('search-botton') > -1) { var query; // if (intended_for == 'intended_for_enter_search') { //NHAN ENTER textinput = $(e.target) //query = $(e.target).val(); } else { //KICK BUTTON textinput = $(this).closest('.search-w').find('input[type=text]') } if (textinput.hasClass('inputtext_for_model')) { var query; //wrapper_attr_global = $(e.target).closest('.form-table-wrapper') //query = wrapper_attr_global.find('#text-search-manager-input').val().split('3G_'); query = textinput.val() url = wrapper_attr_global.find('form').attr('action') url = updateURLParameter(url, 'query_main_search_by_button', query) is_both_table = 'table only' type = "GET" data = {} } else { console.log('tu day', e) var query; query = textinput.val() url = "/omckv2/modelmanager/TramForm/new/" url = updateURLParameter(url, 'query_main_search_by_button', query) is_both_table = 'table only' type = "GET" data = {} hieu_ung_sau_load_form_va_table = 'active tram-table-toogle-li' if (id_closest_wrapper = 'form-table-of-tram-info_dang_le_ra') { closest_wrapper = $('#form-table-of-tram-info') id_closest_wrapper = closest_wrapper.attr('id') // no importaince } } } else if (class_value.indexOf('input-group-addon') > -1) { dtuong_before_submit = $(this) find_glyphicon_calendar = $(this).find('.glyphicon-calendar') if (find_glyphicon_calendar.length > 0) { return true } console.log('dtuong_before_submit', dtuong_before_submit.attr('class')) href_id = $(this).find('span.glyphicon').attr("href_id") near_input = $(this).closest('.input-group').find('input[type=text]') near_input_value = near_input.val() console.log('near_input_value 1', near_input_value) if (typeof href_id === "undefined") { console.log('near_input_value 2', near_input_value) if (near_input_value == '') { href_id = "new" } else { href_id = near_input_value console.log('near_input_value 3', near_input_value) } } name = modelClassDict[near_input.attr("name")] + 'Form' url = "/omckv2/modelmanager/" + name + "/" + href_id + "/" is_table = false if (href_id == 'new') { if (name_attr_global == 'thao_tac_lien_quan' || name_attr_global == 'lenh_lien_quan' || name_attr_global == 'component_lien_quan') { input_text_to_Name_field = last_add_item } else { input_text_to_Name_field = near_input.val() } hieu_ung_sau_load_form_va_table = 'input text to Name field' } form_table_template = 'form_on_modal' closest_table_name = closest_wrapper.find('table').attr('name') if (closest_table_name && href_id != 'new') { $('#modal-on-mll-table').attr('table_name', closest_table_name) } else { $('#modal-on-mll-table').removeAttr('table_name') } type = "GET" data = {} } else if (class_value.indexOf('search-manager-botton') > -1) { wrapper_attr_global = $(e.target).closest('.form-table-wrapper') query = wrapper_attr_global.find('#text-search-manager-input').val().split('3G_'); url = wrapper_attr_global.find('form').attr('action') url = updateURLParameter(url, 'query_main_search_by_button', query) is_both_table = 'table only' type = "GET" data = {} } else if (class_value.indexOf('what_g_choice') > -1) { return_sau_cuoi = true value = $(this).val() $(this).prop("checked", true) console.log('what_g_choice*****', value) is_table = true is_form = false closest_wrapper = $('#form-table-of-tram-info') id_closest_wrapper = 'form-table-of-tram-info' is_get_table_request_get_parameter = true console.log('is_get_table_request_get_parameter', is_get_table_request_get_parameter) url = "/omckv2/modelmanager/TramForm/new/" if (is_get_table_request_get_parameter) { console.log('tai sao khogn vao day') get_parameter_toggle = '' var table_contain_div if (table_object) { table_contain_div = table_object } else { if (id_closest_wrapper == 'form-table-of-tram-info') { table_contain_div = $('#tram-table') console.log('tau muon cai nay') } else { table_contain_div = closest_wrapper } } url = update_parameter_from_table_parameter(table_contain_div, url) } url = updateURLParameter(url, 'what_g_choice', value) type = "GET" data = {} } else if (class_value.indexOf('searchtable_header_sort') > -1) { is_table = true is_form = false is_both_table = 'table only' url = $(this).attr('href') if (id_closest_wrapper == 'edit-history-wrapper-div') { console.log('$(this)', $(this).attr('class')) closest_i_want = $(this).closest('div#form-table-of-tram-info') console.log('closest_i_want', closest_i_want) console.log('0closest_i_want', closest_i_want.attr('id')) if (closest_i_want.attr('id') != 'form-table-of-tram-info') { closest_i_want = $(this).closest('div#mll-form-table-wrapper') console.log('2closest_i_want', closest_i_want) if (closest_i_want.attr('id') != 'mll-form-table-wrapper') { return false } else { console.log('3closest_i_want', closest_i_want.attr('id')) url = updateURLParameter(url, 'model_name', 'Mll') tram_id = closest_i_want.find('#id_id').val() console.log('tram_id', tram_id) } } else { url = updateURLParameter(url, 'model_name', 'Tram') tram_id = $('#form-table-of-tram-info').find('#id_id').val() console.log('tram_id', tram_id) } url = updateURLParameter(url, 'edited_object_id', tram_id) url = removeParam('tramid', url) //url = url.replace(/&?tramid=([^&]$|[^&]*?&)/i, "") console.log('###########url new', url) } type = "GET" data = {} } else if (class_value.indexOf('edit-entry-btn-on-table') > -1) { is_both_table = "form only" is_table = false is_form = true url = closest_wrapper.find('form#model-manager').attr('action') entry_id = $(this).attr('id') url = url.replace(/\/\w+\/$/g, '/' + entry_id + '/') console.log('url', url) if (id_closest_wrapper == 'form-table-of-tram-info') { hieu_ung_sau_load_form_va_table = 'active tram-form-toogle-li' } else { hieu_ung_sau_load_form_va_table = "edit-entry" } type = "GET" data = {} } else if (class_value.indexOf('manager-form-select') > -1) { is_table = true is_form = true //url = $('#id_chon_loai_de_quan_ly option:selected').val() url = $(this).val() //url = new va method = get type = "GET" data = {} hieu_ung_sau_load_form_va_table = "show search box" } else if (class_value.indexOf('manager-a-form-select-link') > -1) { is_table = true is_form = true url = $(this).attr('href') type = "GET" data = {} hieu_ung_sau_load_form_va_table = "show search box 2" } else if (class_value.indexOf('show-modal-form-link') > -1) { is_table = false url = $(this).attr("href") ///omckv2/show-modal-form-link/ThietBiForm/1/ form_table_template = 'form_on_modal' table_name = $(this).closest('table').attr('name') if (table_name) { $('#modal-on-mll-table').attr('table_name', table_name) } else { $('#modal-on-mll-table').removeAttr('table_name') } type = "GET" data = {} if (class_value.indexOf('add-comment') > -1 || class_value.indexOf('Nhan-Tin-UngCuu') > -1) { console.log('dfaslkdfjl') mll_id = $(this).closest("tr").find('td.id').html() url = updateURLParameter(url, 'selected_instance_mll', mll_id) } else if (class_value.indexOf('tinh-hinh-mang') > -1) { console.log('tinh hinh mang.****') yesterday_or_other = $('#bcn-select').val() console.log('yesterday_or_other*****', yesterday_or_other) url = updateURLParameter(url, 'yesterday_or_other', yesterday_or_other) data = $('#option-bcn-form').serialize() url = url + '&' + data if (yesterday_or_other == 'theotable') { url = update_parameter_from_table_parameter($('#bcmll .table-manager'), url) console.log('vao day di please') } is_table = true } else if (class_value.indexOf('force_allow_edit') > -1) { url = updateURLParameter(url, 'force_allow_edit', 'True') $('#modal-on-mll-table').removeAttr('table_name') } else if (class_value.indexOf('downloadscript') > -1) { is_table = true tram_id = $(this).closest('form').find('input[name=id]').val() console.log('tram_id', tram_id) url = updateURLParameter(url, 'tram_id_for_same_ntp', tram_id) hieu_ung_sau_load_form_va_table = 'add class overflow for table' console.log('!@#$!@#$1') } } else if (class_value.indexOf('cancel-btn') > -1) { //cancle buton duoc nhan. is_table = true is_form = true url = $(this).closest('form').attr("action").replace(/\/\d+\//g, '/new/') type = "GET" data = {} } else if (class_value.indexOf('loc-btn') > -1) { is_table = true is_form = true url = $(this).closest('form').attr("action") + '?loc=true' type = "GET" data = $(this).closest('form').serialize() if (id_closest_wrapper == 'form-table-of-tram-info') { hieu_ung_sau_load_form_va_table = 'active tram-table-toogle-li' } //Nhan nut submit } else if (class_value.indexOf('submit-btn') > -1) { // ca truong hop add and edit url = $(this).closest('form').attr("action") if ($(this).val() == 'EDIT' || $(this).val() == 'Update to db') { var edit_reason_value = '' while (edit_reason_value == '') { edit_reason_value = prompt("please give the reason", ""); } if (edit_reason_value == null) { return false } } if (id_closest_wrapper == "manager-modal") { console.log('sdsdsdsdsdsds') table_name = $('#modal-on-mll-table').attr('table_name') if (table_name) { // mac du add new commnent hay la edit trang_thai, hay thiet bi thi cung phai is_get_table_request_get_parameter = true is_get_table_request_get_parameter = true table_object = $('table[name=' + table_name + ']').closest('div.table-manager') url = updateURLParameter(url, 'table_name', table_name) is_both_table = "both form and table" is_table = true is_form = true if (url.indexOf('CommentForm') > -1 && $(this).val() == 'ADD NEW') { hieu_ung_sau_load_form_va_table = "change style for add command to edit command" } } else { console.log('khong co table object, nhugn nut duoc bam van o trong modal') if (class_value.indexOf('edit-ntp') > -1) { is_get_table_request_get_parameter = true is_table = true is_form = true url = removeParam('update_all_same_vlan_sites', url) } else if (class_value.indexOf('update_all_same_vlan_sites') > -1) { url = updateURLParameter(url, 'update_all_same_vlan_sites', 'yes') is_get_table_request_get_parameter = true is_both_table = "both form and table" is_table = true is_form = true } else { // truong hop config ca, hoac la truong hop add new foreinkey is_table = false is_form = true is_get_table_request_get_parameter = false patt = /([^/]*?)Form\/(.*?)\// res = patt.exec(url) form_name = res[1] if (form_name == 'UserProfile') { hieu_ung_sau_load_form_va_table = "update ca truc info" } else if (form_name == 'ThaoTacLienQuan') { //dtuong_before_submit.attr //near_input = dtuong_before_submit.closest('.input-group').find('input[type=text]') near_input = dtuong_before_submit.closest('.input-group').find('input[type=text]') console.log("serach lai", near_input.val()) //near_input.trigger('focus') near_input.focus() near_input.autocomplete("search", near_input.val()) } } } } else { // submit trong normal form url = $(this).closest('form').attr("action") if (id_closest_wrapper == 'profile-loc-ca') { console.log('khong show 2 nut cancel va loc') is_table = false is_form = true khong_show_2_nut_cancel_va_loc = true url = updateURLParameter(url, 'khong_show_2_nut_cancel_va_loc', khong_show_2_nut_cancel_va_loc) } else { is_table = true is_form = true if ($(this).val() == 'EDIT') { is_get_table_request_get_parameter = true } else { is_get_table_request_get_parameter = false } } } console.log('is_get_table_request_get_parameter2', is_get_table_request_get_parameter) //get context cua table if (is_get_table_request_get_parameter) { console.log('tai sao khogn vao day') get_parameter_toggle = '' var table_contain_div if (table_object) { table_contain_div = table_object } else { if (id_closest_wrapper == 'form-table-of-tram-info') { table_contain_div = $('#tram-table') console.log('tau muon cai nay') } else { table_contain_div = closest_wrapper } } url = update_parameter_from_table_parameter(table_contain_div, url) if (!table_object) { url = removeParam('table_name', url) } } if (edit_reason_value) { url = updateURLParameter(url, 'edit_reason', edit_reason_value) } console.log('##after add edit_reason', url) type = "POST" data = $(this).closest('form').serialize() } else { console.log('not yet handle ') return false } url = updateURLParameter(url, 'form-table-template', form_table_template) url = updateURLParameter(url, 'is_form', is_form) url = updateURLParameter(url, 'is_table', is_table) if (id_closest_wrapper == 'mll-form-table-wrapper' && is_table) { loc_cas = $('select[name="loc_ca"]').val() if (loc_cas) { newpara = loc_cas.join("d4"); } else { newpara = "None" } url = updateURLParameter(url, 'loc_ca', newpara) } patt = /Form\/(.*?)\// res = patt.exec(url) new_or_id = res[1] if (is_form && type == "POST") { is_update_icon_if_edit_form = true } else { is_update_icon_if_edit_form = false } $.ajax({ type: type, url: url, data: data, // serializes the form's elements. success: function(data) { switch (form_table_template) { case "normal form template": if (is_form & !is_no_show_return_form) { formdata = $(data).find('.form-manager_r').html() if (id_closest_wrapper == 'form-table-of-tram-info') { obj = $('#tram-form') } else { obj = closest_wrapper.children('.form-manager') } formdata = update_icon_info_after_load_edit_form(is_update_icon_if_edit_form, formdata) assign_and_fadeoutfadein(obj, formdata) } if (is_table) { //||table_name la truong hop submit modal form chi load lai phai table(gui di yeu cau xu ly form va table, nhung chi muon hien thi table thoi) tabledata = $(data).find('.table-manager_r').html() if (table_object) { obj = table_object //table_object = table-manager-object } else if (id_closest_wrapper == 'form-table-of-tram-info') { obj = $('#tram-table') } else { obj = closest_wrapper.children('.table-manager') } must_shown_tab_ok = false if (obj.attr('id') == 'tram-table' & hieu_ung_sau_load_form_va_table == 'active tram-table-toogle-li' & $('#tram-table-toogle').attr('class').indexOf('active') == -1) { console.log('i click it...............') //$('#tram-table-toogle-li a').trigger('click') $('.nav-tabs a[href="#tram-table-toogle"]').tab('show') must_shown_tab_ok = true } if (must_shown_tab_ok) { $('#tram-manager-lenh-nav-tab-wrapper-div .nav-tabs a').on('shown.bs.tab', function() { assign_and_fadeoutfadein(obj, tabledata) scrolify_fix_table_header(obj.find('table.table-bordered'), 580); // 160 is height $('#tram-manager-lenh-nav-tab-wrapper-div .nav-tabs a').unbind('shown.bs.tab'); }); return false } else { assign_and_fadeoutfadein(obj, tabledata) scrolify_fix_table_header(obj.find('table.table-bordered'), 580); // 160 is height } if (intended_for == 'intended_for_autocomplete' && !$('input#id_khong_search_tu_dong').prop('checked')) { table2data = $(data).find('.table-manager_r2').html() obj = $('div#mll-form-table-wrapper > div.table-manager') assign_and_fadeoutfadein(obj, table2data) scrolify_fix_table_header(obj.find('table.table-bordered'), 580); // 160 is height } } break; case 'form_on_modal': // chi xay ra trong truong hop click vao link show-modal { formdata = $(data).find('.wrapper-modal').html() formdata = update_icon_info_after_load_edit_form(is_update_icon_if_edit_form, formdata) $("#modal-on-mll-table").html(formdata) $("#modal-on-mll-table").modal() } break; } if (hieu_ung_sau_load_form_va_table == 'edit-entry') { var navigationFn = { goToSection: function(id) { $('html, body').animate({ scrollTop: $(id).offset().top }, 0); } } navigationFn.goToSection('#' + id_closest_wrapper + ' ' + '.form-manager'); return false } else if (hieu_ung_sau_load_form_va_table == "hide modal") { $("#modal-on-mll-table").modal("hide") } else if (hieu_ung_sau_load_form_va_table == 'add class overflow for table') { console.log('!@#$!@#$2') new_attr = $('#manager-modal').find('.table-manager').attr('class') + ' overflow' $('#manager-modal').find('.table-manager').attr('class', new_attr) } else if (hieu_ung_sau_load_form_va_table == "show search box") { $('#manager #search-manager-group').show() } else if (hieu_ung_sau_load_form_va_table == "show search box 2") { $('#manager #search-manager-group').show() $("#dropdown-toggle-manager").dropdown("toggle"); } else if (hieu_ung_sau_load_form_va_table == 'active tram-form-toogle-li') { $('#tram-form-toogle-li a').trigger('click') } else if (hieu_ung_sau_load_form_va_table == 'active thong-tin-tram toogle') { $('#tram-form-toogle-li a').trigger('click') $('a[href="#thong-tin-tram"]').trigger('click') } else if (hieu_ung_sau_load_form_va_table == 'active thong-tin-3g toogle') { $('#tram-form-toogle-li a').trigger('click') $('a[href="#thong-tin-3g"]').trigger('click') } else if (hieu_ung_sau_load_form_va_table == 'active thong-tin-2g toogle') { $('#tram-form-toogle-li a').trigger('click') $('a[href="#thong-tin-2g"]').trigger('click') } else if (hieu_ung_sau_load_form_va_table == 'active thong-tin-4g toogle') { $('#tram-form-toogle-li a').trigger('click') $('a[href="#thong-tin-4g"]').trigger('click') } else if (hieu_ung_sau_load_form_va_table == "update ca truc info") { ca_moi_chon = closest_wrapper.find('select#id_ca_truc option:selected').html() console.log('@@@@ca_moi_chon', ca_moi_chon) $('span#ca-dang-truc').html('Ca ' + ca_moi_chon) } else if (hieu_ung_sau_load_form_va_table == "change style for add command to edit command") { dtuong = $('#modal-on-mll-table h4.add-command-modal-title') dtuong.css("background-color", "#ec971f") } else if (hieu_ung_sau_load_form_va_table == 'input text to Name field') { $('div#manager-modal input#id_Name').val(input_text_to_Name_field) } }, error: function(request, status, error) { error = error.toUpperCase() console.log('bi loi 400 hoac 403', error,typeof(error)) if (error == 'FORBIDDEN') { //403 console.log(request.responseText) data = $(request.responseText).find('#info_for_alert_box').html() alert(data); } else if (error == 'BAD REQUEST') { console.log('bi loi 400') formdata = $(request.responseText).find('.form-manager_r').html() if (id_closest_wrapper == 'form-table-of-tram-info') { console.log("##########1") obj = $('#tram-form') } else { console.log("##########2") obj = closest_wrapper.children('.form-manager') } obj.html(formdata); } } }); return return_sau_cuoi; //ajax thi phai co cai nay. khong thi , gia su click link thi } $(this).on('click', '#submit-id-copy-tin-nhan', function() { copyToClipboard(document.getElementById("id_noi_dung_tin_nhan")); return false }) $(this).on('click', '#submit-id-copy-bao-cao', function() { console.log('dfasdfdsfslkdjflkalklkdfjlkd') copyToClipboard(document.getElementById("id_noi_dung_bao_cao")); return false }) var obj_autocomplete = { create: function() { $(this).data('ui-autocomplete')._renderItem = function(ul, item) { return $(' <li class="abc" ' + 'thietbi="' + item.label + '">') .append("<a>" + '<b>' + item.label + '</b>' + "<br>" + '<span class="std">' + item.desc + '</span>' + "</a>") .appendTo(ul); } }, search: function(e, ui) { console.log('dang search') showloading = false name_attr_global = $(e.target).attr("name") wrapper_attr_global = $(e.target).closest('.form-table-wrapper') }, source: function(request, response) { query = request.term $.get('/omckv2/autocomplete/', { query: query, name_attr: name_attr_global }, function(data) { return_data = data['key_for_list_of_item_dict'] if (query == 'tatca') { number_dau_hieu_co_add = 0 is_curent_add = 0 response(return_data) return false } if (name_attr_global == "doi_tac" || name_attr_global == "nguyen_nhan" || name_attr_global == "du_an" || name_attr_global == "su_co" || name_attr_global == "thiet_bi" || name_attr_global == "trang_thai") { dtuong = wrapper_attr_global.find('#div_id_' + name_attr_global + ' .glyphicon') if (data['dau_hieu_co_add']) { //if + au new show_only_glyphicon(dtuong, 'glyphicon-log-in') dtuong.attr('href_id', "new") } else { show_only_glyphicon(dtuong, 'glyphicon-info-sign') dtuong.attr('href_id', data['href_id']) } } else if (name_attr_global == "thao_tac_lien_quan" || name_attr_global == "lenh_lien_quan" || name_attr_global == "component_lien_quan") { dtuong = wrapper_attr_global.find('#div_id_' + name_attr_global + ' .glyphicon') is_curent_add = data['curent_add'] number_dau_hieu_co_add = data['dau_hieu_co_add'] //0,1,2 console.log('number_dau_hieu_co_add trong source', number_dau_hieu_co_add) if (number_dau_hieu_co_add) { //co add show_only_glyphicon(dtuong, 'glyphicon-log-in') dtuong.html(number_dau_hieu_co_add) dtuong.attr('href_id', "new") last_add_item = data['last_add_item'] } else { show_only_glyphicon(dtuong, 'glyphicon-info-sign') dtuong.attr('href_id', data['href_id']) } } response(return_data) }) }, select: function(event, ui) { dtuong = wrapper_attr_global.find('#div_id_' + name_attr_global + ' .glyphicon') if (name_attr_global == "specific_problem_m2m") { this.value = ui.item['label'] + SLASH_DISTINCTION } else if (name_attr_global == "doi_tac") { if (ui.item['desc'] == "chưa có sdt" || !ui.item['desc']) { this.value = ui.item['label'] } else { this.value = ui.item['label'] + SLASH_DISTINCTION + ui.item['desc']; } show_only_glyphicon(dtuong, 'glyphicon-info-sign') dtuong.attr("href_id", ui.item['id']) } else if (name_attr_global == 'thao_tac_lien_quan' || name_attr_global == 'lenh_lien_quan' || name_attr_global == 'component_lien_quan') { var terms = split(this.value); // remove the current input current_input = terms.pop().replace('\s+', ''); x = number_dau_hieu_co_add - is_curent_add // add the selected item terms.push(ui.item['label']); // add placeholder to get the comma-and-space at the end terms.push(""); this.value = terms.join(", "); //x chinh la dau hieu co add if (x) { //if dau_hieu_co_add show_only_glyphicon(dtuong, 'glyphicon-log-in') dtuong.html(x) dtuong.attr("dau_phon", 'new') dtuong.attr("href_id", 'new') } else { console.log("ui.item['id']", ui.item['id']) show_only_glyphicon(dtuong, 'glyphicon-info-sign') dtuong.html('') dtuong.attr("href_id", ui.item['id']) } } else { if (name_attr_global == 'nguyen_nhan' || name_attr_global == 'du_an' || name_attr_global == 'su_co' || name_attr_global == "thiet_bi" || name_attr_global == "trang_thai") { show_only_glyphicon(dtuong, 'glyphicon-info-sign') dtuong.attr("href_id", ui.item['id']) } this.value = ui.item['label'] } return false } } $(this).on("focus", ".autocomplete", function() { if (!$(this).data("autocomplete")) { $(this).autocomplete(obj_autocomplete) } }); $(this).on('click', ".autocomplete,.autocomplete_search_tram,.autocomplete_search_manager", function() { value = $(this).val() if (value.length === 0) { value = 'tatca' if ($(this).hasClass('autocomplete')) { } } $(this).autocomplete("search", value) }); $(this).on("keyup", ".autocomplete", function() { if ($(this).val().length === 0) { closest_wrapper = $(this).closest('div.form-table-wrapper') doituong = closest_wrapper.find('#div_id_' + name_attr_global + ' .glyphicon') show_only_glyphicon(dtuong, 'glyphicon-plus') doituong.removeAttr("href_id") if ($(this).attr('name') == 'thao_tac_lien_quan' || $(this).attr('name') == 'lenh_lien_quan' || $(this).attr('name') == 'component_lien_quan') { doituong.html('') } } }); $(this).on("focus", ".autocomplete_search_tram", function() { $(this).autocomplete({ create: function() { $(this).data('ui-autocomplete')._renderItem = function(ul, item) { return $('<li class="li-select-in-autocomplete-result">').append( $('<div>').append('<b>' + '<span class="greencolor">' + item.sort_field + ":</span>" + '<span class="">' + item.label + '</span>' + '</b>') .append('<div class="table-type-wrapper">' + '<div class="wrapper-a-tr"><div class="wrapper-dt-autocomplete" >' + '<span class="tram_field_name">SN1: </span>' + '<span class="chontram" type-tram = "SN1" type-thiet-bi = "2G&3G">' + item.sn1 + '</span>' + '</div>' + '<div class="wrapper-dt-autocomplete" >' + '<span class="tram_field_name">SN2: </span>' + '<span class="chontram" type-tram = "SN2" type-thiet-bi = "2G&3G">' + item.sn2 + '</span>' + '</div></div>' + '<div class="wrapper-a-tr"><div class="wrapper-dt-autocomplete" >' + '<span class="tram_field_name">3G: </span>' + '<span class="chontram" type-tram = "3G" type-thiet-bi = "' + item.s3g_thietbi + '">' + item.s3g + '</span>' + '</div>' + '<div class="wrapper-dt-autocomplete" >' + '<span class="tram_field_name">2G: </span>' + '<span class="chontram" type-tram = "2G" type-thiet-bi = "' + item.s2g_thietbi + '">' + item.s2g + '</span>' + '</div></div>' + '<div class="wrapper-a-tr"><div class="wrapper-dt-autocomplete" >' + '<span class="tram_field_name">4G: </span>' + '<span class="chontram" type-tram = "4G" type-thiet-bi = "' + item.s4g_thietbi + '">' + item.s4g + '</span>' + '</div>' + '<div class="wrapper-dt-autocomplete" >' + '<span class="tram_field_name">Booster: </span>' + '<span class="chontram" type-tram = "Booster" type-thiet-bi = "' + item.booster_thietbi + '">' + item.booster + '</span>' + '</div>' + '</div>' + '</div>')) .appendTo(ul) } }, focus: function(event, ui) { event.preventDefault(); // Prevent the default focus behavior. return false; }, search: function(e, ui) { showloading = false name_attr_global = $(e.target).attr("name") //name_attr_global de phan biet cai search o top of page or at mllfilter }, source: function(request, response) { console.log('name_attr_global', name_attr_global) var query = extractLast(request.term) $.get('/omckv2/autocomplete/', { query: query, name_attr: name_attr_global }, function(data) { return_data = data['key_for_list_of_item_dict'] response(return_data) }) }, select: function(event, ui) { doituongvuaclick = $(event.toElement) if (doituongvuaclick.attr('class') == 'chontram') { sort_field = doituongvuaclick.attr('type-tram') console.log('sort_field', sort_field) thiet_bi = doituongvuaclick.attr('type-thiet-bi') value_select = event.toElement.innerText } else { sort_field = ui.item.sort_field value_select = ui.item['label'] thiet_bi = ui.item.thiet_bi } /* if (name_attr_global == "object") { var terms = split(this.value); // remove the current input terms.pop(); // add the selected item terms.push(value_select); // add placeholder to get the comma-and-space at the end terms.push(""); this.value = terms.join(", "); } else { this.value = value_select; //this.value tuc la gia tri hien thi trong input text } */ var terms = split(this.value); // remove the current input terms.pop(); // add the selected item terms.push(value_select); // add placeholder to get the comma-and-space at the end terms.push(""); this.value = terms.join(", "); if (name_attr_global == "object") { $('#id_site_name').val(ui.item.site_name_1) thiet_bi_input_text = $('#mll-form-table-wrapper input#id_thiet_bi') thiet_bi_input_text.val(thiet_bi) dtuong = thiet_bi_input_text.closest('.input-group').find('.glyphicon') show_only_glyphicon(dtuong, 'glyphicon-info-sign') thiet_bis = thiet_bi.split('/') console.log('thiet_bi888', thiet_bi) $('select#id_type_2g_or_3g option:contains("' + thiet_bis[2] + '")').prop('selected', true); $('select#id_brand option:contains("' + thiet_bis[1] + '")').prop('selected', true); } option_khong_tu_dong_search_tram = $('input#id_khong_search_tu_dong_tram').prop('checked') if (!(option_khong_tu_dong_search_tram && name_attr_global == "object")) { form_table_handle(event, 'intended_for_autocomplete', '/omckv2/modelmanager/TramForm/' + ui.item.id + '/?tramid=' + ui.item.id, sort_field) } return false // return thuoc ve select : } }) //close autocompltete }); $(this).on("focus", ".autocomplete_search_manager", function(e) { $(this).autocomplete({ create: function() { $(this).data('ui-autocomplete')._renderItem = function(ul, item) { return $(' <li class="abc" ' + 'thietbi="' + item.label + '">') .append("<a>" + '<b>' + item.label + '</b>' + "<br>" + '<span class="std">' + item.desc + '</span>' + "</a>") .appendTo(ul); } }, focus: function(event, ui) { event.preventDefault(); // Prevent the default focus behavior. return false; }, search: function(e, ui) { name_attr_global = $(e.target).attr("name") //name_attr_global de phan biet cai search o top of page or at mllfilter wrapper_attr_global = $(e.target).closest('.form-table-wrapper') model_attr_global = wrapper_attr_global.find('form').attr('action') patt = /\/(\w*?)Form\//i res = patt.exec(model_attr_global) console.log('model_attr_global', res[1]) model_attr_global = res[1] }, source: function(request, response) { console.log('name_attr_global', name_attr_global) var query = extractLast(request.term) $.get('/omckv2/autocomplete/', { query: query, name_attr: name_attr_global, model_attr_global: model_attr_global }, function(data) { response(data['key_for_list_of_item_dict']) //response(projects) }) }, select: function(event, ui) { this.value = ui.item['label'] form_table_handle(event, 'intended_for_manager_autocomplete', '/omckv2/modelmanager/' + model_attr_global + 'Form/' + ui.item.id + '/?tramid=' + ui.item.id) return false // return thuoc ve select : } }) //close autocompltete }); //LENH Chon lenh var counter = 0; $(this).on('click', 'table.lenh-table > tbody >tr >td.selection>input[type=checkbox] ', function() { this_check_box = $(this) chosing_row_id = this_check_box.closest("tr").find('td.id').html() is_check_state_before_click = this_check_box.is(':checked') console.log('is_check', is_check_state_before_click) if (false) { /* bo chon 1 row*/ console.log(chosing_row_id) $("table#selected-lenh-table").find("td.id").filter(function() { var id = $(this).html(); if (id == chosing_row_id) { $(this).parent().remove(); var index = choosed_command_array_global.indexOf(id); if (index > -1) { choosed_command_array_global.splice(index, 1); } counter = $('#selected-lenh-table tr').length - 1; console.log('ban da bo chon 1 row lenh', choosed_command_array_global) } }) /* close brace for filter function*/ } /* close if*/ else { this_check_box.prop("checked", true) counter = counter + 1 var newrowcopy = $('<tr>'); this_check_box.closest("tr").find('td').each(function(i, v) { this_td = $(this) if (!this_td.hasClass("selection") && i < 5) { /*khong add nhung selection data*/ var this_td_html = $(this).prop('outerHTML') //cu newrowcopy.append(this_td_html) } }); command = this_check_box.closest('tr').find('td.command').html() var reg = /\[(thamso.*?)\]/g; var matches_thamso_attribute_sets = [] var found while (found = reg.exec(command)) { console.log('found.index', found.index, 'found', found, '\nreg.lastIndex', reg.lastIndex) matches_thamso_attribute_sets.push(found[1]); reg.lastIndex = found.index + 1; } newtd = $('<td>') $.each(matches_thamso_attribute_sets, function(index, thamso_name) { newtd.append($('<p>').html(thamso_name)) newtd.append($('<input/>').attr({ type: 'text', id: thamso_name })) }) if (command.indexOf('[TG]') > -1) { newtd.append($('<p>').html('chon TG 1800')) newtd.append($('<input/>').attr({ type: 'checkbox', class: "chon-TG-1800" })) } newtd.append('<div><input type="button" class="ibtnDel" value="Delete"><input type="button" class="move up" value="Up"><input type="button" class="move down" value="Down"></div></td>') newrowcopy.append(newtd); $("table#selected-lenh-table>tbody").append(newrowcopy) choosed_command_array_global.push(chosing_row_id) console.log(choosed_command_array_global) } }); // LENH xoa 1 lenh trong table chon lenh $("table#selected-lenh-table").on("click", ".ibtnDel", function(event) { is_ton_tai_them_1_tr_id = false tr_id = $(this).closest("tr").find('td.id').html() $(this).closest("tr").remove(); $("table#selected-lenh-table").find('tbody tr td.id').each(function() { if (this.html() == tr_id) { is_ton_tai_them_1_tr_id = true } }) if (!is_ton_tai_them_1_tr_id) { $('table.lenh-table').find('tr td input[value =' + tr_id + ']').attr('checked', false) counter -= 1 } }); //LENH generate $(this).on('click', '.generate-command', function() { var command_set_many_tram = ""; $('.tram-table > tbody > tr').each(function() { var command_set_one_tram = ""; var tram_row = $(this) $('#selected-lenh-table > tbody > tr').each(function() { tr = $(this) var one_command = $(this).find('td.command').html(); var reg = /\[(.+?)\]/g; var matches_tram_attribute_sets = [] var found while (found = reg.exec(one_command)) { matches_tram_attribute_sets.push(found[1]); reg.lastIndex = found.index + 1; } $.each(matches_tram_attribute_sets, function(index, tram_attribute) { value = tram_row.find('td.' + tram_attribute.split(" ").join("_")).html() console.log('tram_attribute 2', tram_attribute) if (tram_attribute == 'Site ID 3G') { value = value.replace(/^ERI_3G_/g, '') } else if (tram_attribute == 'Site ID 2G') { value = value.replace(/^SRN_2G_/g, '') } else if (tram_attribute.indexOf('thamso') > -1) { value = tr.find('input#' + tram_attribute).val() } else if (tram_attribute == 'TG') { is_check = tr.find('input.chon-TG-1800') is_check = is_check.is(":checked") if (is_check) { value = tram_row.find('td.' + 'TG_1800').html() } } one_command = one_command.replace('[' + tram_attribute + ']', value) }); command_set_one_tram += one_command + '\n\n\n' }); command_set_many_tram += command_set_one_tram + '\n\n' }); $('textarea.command-erea').val(command_set_many_tram); console.log(command_set_many_tram) }); $(this).on('click', 'table#selected-lenh-table tbody tr td input.move', function() { var row = $(this).closest('tr'); if ($(this).hasClass('up')) row.prev().before(row); else row.next().after(row); }); $(this).on('click', '.link_to_download_scipt', function() { form = $(this).closest('form') var data = form.serialize() if (form.find('#id_ntpServerIpAddressPrimary').val() == '' || form.find('#id_ntpServerIpAddress1').val() == '') { alert('kiem tra lai may cai o trong kia') return false } site_id = $('#form-table-of-tram-info').find('input#id_id').val() var win = window.open('/omckv2/download_script_ntp/' + '?site_id=' + site_id + '&' + data); if (win) { //Browser has allowed it to be opened $("#config_ca_modal").modal("hide"); win.focus(); } else { //Broswer has blocked it alert('Please allow popups for this site'); } return false }) $(this).on('click', '.download-bcn', function() { console.log('i love you thannk you') id = $(this).attr('id') //id =='download-bcn' data = $('#option-bcn-form').serialize() url = $(this).attr('href') url = url + '&' + data console.log('new url **********', url) yesterday_or_other = $('#bcn-select').val() url = updateURLParameter(url, 'download-bcn', 'yes') //url = updateURLParameter(url, 'yesterday_or_other', yesterday_or_other) if (yesterday_or_other == 'theotable') { url = update_parameter_from_table_parameter($('#bcmll .table-manager'), url) } if (id == 'download-keo-dai') { url = updateURLParameter(url, 'download-keo-dai', 'yes') } var win = window.open(url); if (win) { //Browser has allowed it to be opened win.focus(); } else { //Broswer has blocked it alert('Please allow popups for this site'); } return false }) $(this).on("click", ".btnEdit", function() { var array_td_need_edit = [] //array la chua nhung index cua td can edit var par = $(this).parent().parent(); wrapper_table = $(this).closest('table') table_class = wrapper_table.attr("class") //tr if (table_class.indexOf('history-table') > -1) { array_td_need_edit = [4] } else if (table_class.indexOf('doi_tac-table') > -1) { array_td_need_edit = [1, 2, 3, 4, 5, 6] } this_rows = par.children('td') var total = this_rows.length; this_rows.each(function(i, v) { this_html = $(this).text() this_html = ((this_html == "—") ? "" : this_html) if (array_td_need_edit.indexOf(i) > -1) { $(this).html("<input type='text' id='" + $(this).attr("class") + "' value='" + this_html + "'/>"); } else if (i == total - 1) { $(this).html("<img src='media/images/disk.png' class='btnSave'/>"); } }) }); $(this).on("click", ".btnSave", function() { wrapper_table = $(this).closest('table') table_class = wrapper_table.attr("class") table_div = $(this).closest('div.table-div') url = wrapper_table.attr("table-action") table = $(this).closest('.table-manager') var trow = $(this).parent().parent(); //tr history_search_id = trow.find('td.id').html() var row = { action: "edit" }; row.history_search_id = history_search_id trow.find('input,select,textarea').each(function() { row[$(this).attr('id')] = $(this).val(); }); if (table_class.indexOf('history-table') > 0) { $.get(url, row, function(data) { table.html(data) }); } else if (table_class.indexOf('doi_tac-table') > 0) { $.get(url, row, function(data) { console.log(data); $('#table-doitac').html(data); }); } }); $(this).on("click", ".btnDelete", function() { wrapper_table = $(this).closest('table') table_div = $(this).closest('.table-manager') table_class = wrapper_table.attr("class") url = wrapper_table.attr("table-action") var trow = $(this).parent().parent(); //tr history_search_id = trow.find('td.id').html() if (table_class.indexOf('history-table')) { $("#myModal").find('div#id-deleted-object').html("Doi tuong xoa co id " + history_search_id) if (confirm("Are you sure?")) { $.get(url, { "action": "delete", "history_search_id": history_search_id }, function(data) { table_div.html(data); }); return false; //url = '/omckv2/edit_history_search/', } } }); $('.datetimepicker').datetimepicker({ format: DT_FORMAT, }); $('.datetimepicker_bcn').datetimepicker({ format: BCN_DT_FORMAT, }); $('.datetimepicker_only_date').datetimepicker({ viewMode: 'days', format: DATE_FORMAT, }); $('.mySelect2').select2({ width: '100%' }); $('.selectmultiple').select2({ width: '100%' }) $('#modal-on-mll-table').on('hidden.bs.modal', function(e) { // do something... $(this).empty() }) $(this).on('click', '#replace-carrier-return', function() { value = $('#mll-form-table-wrapper #id_specific_problem_m2m').val().replace('\n', '').replace('\r', '') console.log('iloveyuou', value) $('#mll-form-table-wrapper #id_specific_problem_m2m').val(value) }) scrolify_fix_table_header($('#mll-table-id'), 580); // 160 is height scrolify_fix_table_header($('#tram-table-id'), 580); // 160 is height $("#loading").hide(); $('#submit-id-command-cancel').hide() $(this).on("ajaxStart", function() { if (showloading == true) { $("#loading").show(); } showloading = true }) // $(this).on('click', "input[type=submit]", function() { // $("input[type=submit]").removeAttr("clicked"); // $(this).attr("clicked", "true"); // }); $(this).ajaxComplete(function(event, xhr, settings) { $("#loading").hide(); $('.datetimepicker_bcn').datetimepicker({ format: BCN_DT_FORMAT }); $('.datetimepicker').datetimepicker({ format: DT_FORMAT, }); $('.datetimepicker_only_date').datetimepicker({ viewMode: 'days', format: DATE_FORMAT, }); $('.mySelect2').select2({ width: '100%' }); $('.selectmultiple').select2({ width: '100%' }) }); }); //END READY DOCUMENT function split(val) { return val.split(/,\s*/); } function extractLast(term) { return split(term).pop(); } function update_icon_info_after_load_edit_form(is_update_icon_if_edit_form, formdata_html_text) { if (is_update_icon_if_edit_form) { formdata = $(formdata_html_text) formdata.find('.glyphicon-plus').each(function(index) { near_input = $(this).closest('.input-group').find('input[type=text]') near_input_value = near_input.val() if (near_input_value != '') { show_only_glyphicon($(this), 'glyphicon-info-sign') } }) } return formdata } function updateURLParameter(url, param, paramVal) { var newAdditionalURL = ""; var tempArray = url.split("?"); var baseURL = tempArray[0]; var additionalURL = tempArray[1]; var temp = ""; if (additionalURL) { tempArray = additionalURL.split("&"); for (i = 0; i < tempArray.length; i++) { if (tempArray[i].split('=')[0] != param) { newAdditionalURL += temp + tempArray[i]; temp = "&"; } } } var rows_txt = temp + "" + param + "=" + paramVal; return baseURL + "?" + newAdditionalURL + rows_txt; } function copyToClipboard(elem) { // create hidden text element, if it doesn't already exist var targetId = "_hiddenCopyText_"; var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA"; var origSelectionStart, origSelectionEnd; if (isInput) { // can just use the original source element for the selection and copy target = elem; origSelectionStart = elem.selectionStart; origSelectionEnd = elem.selectionEnd; } else { // must use a temporary form element for the selection and copy target = document.getElementById(targetId); if (!target) { var target = document.createElement("textarea"); target.style.position = "absolute"; target.style.left = "-9999px"; target.style.top = "0"; target.id = targetId; document.body.appendChild(target); } target.textContent = elem.textContent; } // select the content var currentFocus = document.activeElement; target.focus(); target.setSelectionRange(0, target.value.length); // copy the selection var succeed; try { succeed = document.execCommand("copy"); } catch (e) { succeed = false; } // restore original focus if (currentFocus && typeof currentFocus.focus === "function") { currentFocus.focus(); } if (isInput) { // restore prior selection elem.setSelectionRange(origSelectionStart, origSelectionEnd); } else { // clear temporary content target.textContent = ""; } return succeed; } var glyphicon_ARRAYS = ['glyphicon-info-sign', 'glyphicon-plus', 'glyphicon-log-in'] function show_only_glyphicon(dtuong, glyphicon_str) { glyphicon_ARRAYS_copy = glyphicon_ARRAYS glyphicon_ARRAYS_copy = jQuery.grep(glyphicon_ARRAYS_copy, function(value) { return value != glyphicon_str; }); for (i = 0; i < glyphicon_ARRAYS_copy.length; i++) { dtuong.removeClass(glyphicon_ARRAYS_copy[i]) } dtuong.addClass(glyphicon_str) } function toggleDesAsc(additionalURL) { var newAdditionalURL = ""; tempArray = additionalURL.split("&"); for (i = 0; i < tempArray.length; i++) { key = tempArray[i].split('=')[0] if (key != 'sort') { newAdditionalURL += "&" + tempArray[i]; } else { paraValue = tempArray[i].split('=')[1] if (paraValue.indexOf('-') > -1) { console.log('paraValue co - la', paraValue) paraValue = paraValue.replace('-', '') } else { paraValue = '-' + paraValue } newAdditionalURL += "&" + key + '=' + paraValue; } } return newAdditionalURL } function update_parameter_from_table_parameter(table_contain_div, url) { desc_th = table_contain_div.find('th.desc:first') if (desc_th.length == 0) { asc_th = table_contain_div.find('th.asc:first') if (asc_th.length == 0) { href = table_contain_div.find('.searchtable_header_sort:first').attr('href') console.log('khong co asc hoac desc o table') } else { href = asc_th.find('.searchtable_header_sort').attr('href') console.log('co asc class o table', asc_th.length, asc_th.attr('class')) } } else { console.log('co desc class o table', desc_th.length, desc_th.attr('class'), desc_th, desc_th.outerHTML) href = desc_th.find('a').attr('href') } get_question_mark = href.indexOf('?') get_parameter = href.substring(get_question_mark + 1) get_parameter_toggle = toggleDesAsc(get_parameter) if (url.indexOf('?') > -1) { url = url + get_parameter_toggle } else { url = url + '?' + get_parameter_toggle.replace('&', '') console.log('@@@@@@@url', url) } return url } var showloading = true var choosed_command_array_global = [] var model_attr_global var name_attr_global var wrapper_attr_global var BCN_DT_FORMAT = 'HH:mm:SS DD/MM/YYYY' var DT_FORMAT = 'HH:mm DD/MM/YYYY' var DATE_FORMAT = 'DD/MM/YYYY' // D4 fadeIn fadeOut function d4fadeOutFadeIn(jqueryobject, datahtml) { jqueryobject.fadeOut(300); jqueryobject.html(datahtml).fadeIn(300); jqueryobject.attr('site_id', ui.item.value) }; function assign_and_fadeoutfadein(jqueryobject, datahtml) { if (datahtml) { jqueryobject.fadeOut(300); jqueryobject.html(datahtml).fadeIn(300); } }; function map_init2(myCenter) { var mapProp = { center: myCenter, zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("googleMap1"), mapProp); var marker = new google.maps.Marker({ position: myCenter, }); marker.setMap(map); } function show_map_from_longlat() { long = parseFloat($('#id_Long_3G').val().replace(',', '.')); lat = parseFloat($('#id_Lat_3G').val().replace(',', '.')); try { myCenter = new google.maps.LatLng(lat, long); map_init2(myCenter) } catch (err) {} } function removeParam(key, sourceURL) { var rtn = sourceURL.split("?")[0], param, params_arr = [], queryString = (sourceURL.indexOf("?") !== -1) ? sourceURL.split("?")[1] : ""; if (queryString !== "") { params_arr = queryString.split("&"); for (var i = params_arr.length - 1; i >= 0; i -= 1) { param = params_arr[i].split("=")[0]; if (param === key) { params_arr.splice(i, 1); } } rtn = rtn + "?" + params_arr.join("&"); } return rtn; } function scrolify_fix_table_header(tblAsJQueryObject, height) { var oTbl = tblAsJQueryObject; // for very large tables you can remove the four lines below // and wrap the table with <div> in the mark-up and assign // height and overflow property var oTblDiv = $("<div/>"); oTbl_height = oTbl.height() console.log('oTbl_height', oTbl_height) if (oTbl_height < height) { return false } oTblDiv.css({ 'max-height': height, 'width': oTbl.width() }); //oTblDiv.css('overflow-y','auto').css('overflow-x','initial'); oTblDiv.attr('class', 'oveflow-y-only') oTbl.wrap(oTblDiv); // save original width oTbl.attr("data-item-original-width", oTbl.width()); oTbl.find('thead tr th').each(function() { $(this).attr("data-item-original-width", $(this).width()); }); oTbl.find('tbody tr:eq(0) td').each(function() { $(this).attr("data-item-original-width", $(this).width()); }); // clone the original table var newTbl = oTbl.clone(); // remove table header from original table oTbl.find('thead tr').remove(); // remove table body from new table newTbl.find('tbody tr').remove(); oTbl.parent().parent().prepend(newTbl); newTbl.wrap("<div/>"); // replace ORIGINAL COLUMN width newTbl.width(newTbl.attr('data-item-original-width')); newTbl.find('thead tr th').each(function() { $(this).width($(this).attr("data-item-original-width")); }); oTbl.width(oTbl.attr('data-item-original-width')); oTbl.find('tbody tr:eq(0) td').each(function() { $(this).width($(this).attr("data-item-original-width")); }); } function hasClass(element, cls) { return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1; } var dtuong_before_submit
10,564
https://github.com/nagyist/marketcetera/blob/master/trunk/modules/strategy/src/test/sample_data/inputs/send_other.rb
Github Open Source
Open Source
Apache-2.0
2,023
marketcetera
nagyist
Ruby
Code
43
169
require 'java' java_import org.marketcetera.strategy.ruby.Strategy java_import org.marketcetera.trade.Equity java_import java.math.BigDecimal java_import java.lang.System java_import java.lang.Boolean class SendOther < Strategy def on_ask(ask) if(get_property("sendNull") != nil) send nil return end if(get_property("sendString") != nil) send "test string" return end if(get_property("sendTwo") != nil) send BigDecimal::ONE send BigDecimal::TEN end end end
34,012
https://github.com/dongzm/yyg/blob/master/system/modules/vote/tpl/vote.list.tpl.php
Github Open Source
Open Source
MIT
2,017
yyg
dongzm
PHP
Code
142
864
<?php defined('G_IN_ADMIN')or exit('No permission resources.'); ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>后台首页</title> <link rel="stylesheet" href="<?php echo G_GLOBAL_STYLE; ?>/global/css/global.css" type="text/css"> <link rel="stylesheet" href="<?php echo G_GLOBAL_STYLE; ?>/global/css/style.css" type="text/css"> <style> body{ background-color:#fff} </style> </head> <body> <script> function vote(id){ if(confirm("确定删除该投票")){ window.location.href="<?php echo G_MODULE_PATH;?>/vote_admin/del?id="+id; } } </script> <div class="header lr10"> <?php echo $this->headerment();?> </div> <div class="bk10"></div> <div class="table-list lr10"> <table width="100%" cellspacing="0"> <thead> <tr align="center"> <th width="5%" height="30">ID</th> <th width="30%">标题</th> <th width="10%">投票数</th> <th width="10%">开始时间</th> <th width="10%">结束时间</th> <th width="10%">发表时间</th> <th width="30%">管理操作</th> </tr> </thead> <tbody> <?php foreach($vote as $v) { ?> <tr align="center" class="mgr_tr"> <td ><?php echo $v['vote_id'];?></td> <td><?php echo $v['vote_title'];?></td> <td><?php echo _strcut($v['vote_number'],25);?></td> <td class="number"><?php echo date('Y-m-d',$v['vote_starttime']);?></td> <td><?php echo date('Y-m-d',$v['vote_endtime']);?></td> <td><?php echo date('Y-m-d',$v['vote_sendtime']);?></td> <td class="action"> <span>[<a href="<?php echo G_MODULE_PATH;?>/vote_admin/vote_total/<?php echo $v['vote_id'];?>">统计</a>]</span> <span>[<a href="<?php echo G_MODULE_PATH;?>/vote_admin/vote_update/<?php echo $v['vote_id'];?>">修改</a>]</span> <span>[<a href="<?php echo G_MODULE_PATH;?>/vote_admin/del/<?php echo $v['vote_id'];?>">删除</a>]</span></td> </tr> <?php } ?> </tbody> </table> </div><!--table_list end--> </body> </html>
50,386
https://github.com/Zooll8/nightlife-coordinator/blob/master/src/store/initialState.js
Github Open Source
Open Source
MIT
2,017
nightlife-coordinator
Zooll8
JavaScript
Code
22
55
const initialState = { auth: { value: false, user: {} }, search: { data: [], isLoading: false } }; export default initialState;
35,308
https://github.com/Thraka/QuickPak-Pro-DOS/blob/master/source/DEMOPULL.MAK
Github Open Source
Open Source
LicenseRef-scancode-public-domain
2,018
QuickPak-Pro-DOS
Thraka
Makefile
Code
2
15
DEMOPULL.BAS PULLDOWN.BAS
38,450
https://github.com/BasLee/textrepo/blob/master/textrepo-app/src/main/java/nl/knaw/huc/api/ResultType.java
Github Open Source
Open Source
Apache-2.0
null
textrepo
BasLee
Java
Code
61
199
package nl.knaw.huc.api; import com.fasterxml.jackson.annotation.JsonProperty; import nl.knaw.huc.core.Type; public class ResultType { private final short id; private final String name; private final String mimetype; public ResultType(Type type) { this.id = type.getId(); this.name = type.getName(); this.mimetype = type.getMimetype(); } @JsonProperty public short getId() { return id; } @JsonProperty public String getName() { return name; } @JsonProperty public String getMimetype() { return mimetype; } }
22,355
https://github.com/dotnetcore/Util/blob/master/test/Util.Generators.Razor.Tests.Integration/RazorTemplateTest.cs
Github Open Source
Open Source
MIT
2,023
Util
dotnetcore
C#
Code
135
412
using System.IO; using System.Threading.Tasks; using Util.Generators.Contexts; using Util.Helpers; using Util.Templates; using Xunit; namespace Util.Generators.Razor.Tests.Integration { /// <summary> /// Razor模板测试 /// </summary> public class RazorTemplateTest { /// <summary> /// 模板引擎 /// </summary> private readonly ITemplateEngine _templateEngine; /// <summary> /// 测试初始化 /// </summary> public RazorTemplateTest( ITemplateEngine templateEngine ) { _templateEngine = templateEngine; } /// <summary> /// 测试渲染模板 /// </summary> [Fact] public async Task TestRender() { var path = Common.GetPhysicalPath( "Templates/Test1/Template.cshtml" ); var template = new RazorTemplate( _templateEngine, new FileInfo( path ) ); var generatorContext = new GeneratorContext { TemplateRootPath = Common.GetPhysicalPath( "~/Templates" ), OutputRootPath = Common.GetPhysicalPath( "~/Output" ) }; var projectContext = new ProjectContext( generatorContext ) { Name = "test" }; var entityContext = new EntityContext( projectContext, "Hello" ); var result = await template.RenderAsync( entityContext ); Assert.Equal( "Hello,World", result ); Assert.Equal( "Test1", entityContext.Output.RelativeRootPath ); } } }
3,594
https://github.com/zuwome/kongxia/blob/master/kongxia/Views/Home/home/view/ZZHomeStatusView.h
Github Open Source
Open Source
MIT
null
kongxia
zuwome
C
Code
53
177
// // ZZHomeStatusView.h // zuwome // // Created by angBiu on 16/9/13. // Copyright © 2016年 zz. All rights reserved. // #import <UIKit/UIKit.h> /** 首页 -- 飞机 新人标志 */ @interface ZZHomeStatusView : UIView @property (nonatomic, strong) UIImageView *bgImgView; @property (nonatomic, strong) UILabel *statusLabel; @property (nonatomic, strong) UIImageView *statusImgView; - (void)setUser:(ZZUser *)user type:(NSInteger)type; @end
9,258
https://github.com/mvangoor/pzs-ng/blob/master/scripts/logtrimmer/logtrimmer.sh
Github Open Source
Open Source
BSD-3-Clause
2,020
pzs-ng
mvangoor
Shell
Code
94
275
#!/bin/bash # config # ########## # Where do I find your logs? logdir=/glftpd/ftp-data/logs # Enter here the names of the logs you wish trimmed. # The format is: <logname>:<# of lines to keep> logfiles="error.log:500 glftpd.log:1000 login.log:100 request.log:100 xferlog:1000" today="`date +"%a %b %d %H:%M:%S %Y"`" ################# # end of config # for logline in $logfiles; do logfile=`echo $logline | cut -d ':' -f 1` loglines=`echo $logline | cut -d ':' -f 2` tail -n $loglines ${logdir}/${logfile} > ${logdir}/${logfile}.temp echo "$today -- Logfile turned over --" >> ${logdir}/${logfile}.temp cat ${logdir}/${logfile}.temp > ${logdir}/${logfile} rm -f ${logdir}/${logfile}.temp done
48,454
https://github.com/geek/vidi-dashboard/blob/master/server/vidi.js
Github Open Source
Open Source
MIT
2,016
vidi-dashboard
geek
JavaScript
Code
252
709
'use strict' var Path = require('path') var Boom = require('boom') var Package = require('../package.json') var ClientRoutes = require('./routes/client') var UserRoutes = require('./routes/user') module.exports = function (server, options, next) { // Set our realitive path (for our routes) var relativePath = Path.join(__dirname, '../dist/') server.realm.settings.files.relativeTo = relativePath // Session stuff server.state('session', { ttl: 24 * 60 * 60 * 1000, isSecure: true, path: '/', encoding: 'base64json' }) // Wire up our http routes, these are // mostly for managing the dashboard. server.route(ClientRoutes) server.route(UserRoutes) // Only allow connections from localhost server.select('web').ext('onRequest', function (request, reply) { var host = request.raw.req.connection.address().address if (host !== '127.0.0.1') { return reply(Boom.forbidden()) } return reply.continue() }) // Set up our seneca plugins var seneca = server.seneca seneca.use(require('./plugins/seneca-pubsub-decorator')) seneca.client({type: 'tcp', port: '3055', pin: 'role:user, cmd:*'}) // Set up a default user seneca.act({ role: 'user', cmd: 'register', name: process.env.USER_NAME || 'Admin', email: process.env.USER_EMAIL || 'admin@vidi.com', password: process.env.USER_PASS || 'vidi' }) // Handle subscription wireup. This is very naive right // now, only handles a single subscription. seneca.subscribe({role: 'metrics', cmd: 'sub'}, function (msg) { var uri = '/metrics/' + msg.source + '/' + msg.metric server.subscription(uri) // Sometimes an interval is all you need for real-time data setInterval(function () { seneca.act({role: msg.role, source: msg.source, metric: msg.metric}, function (err, data) { if (err) { //console.log(err.stack || err) return } if (data) { server.publish(uri, data) } }) }, 1000) }) next() } // Hapi uses this metadata. It's convention to provide // it even though we are actually the same package. module.exports.attributes = { pkg: Package }
31,968
https://github.com/zlikun/zlikun-algorithm-python/blob/master/sort/shell/ShellSort2.py
Github Open Source
Open Source
Apache-2.0
null
zlikun-algorithm-python
zlikun
Python
Code
128
400
#!/usr/bin/env python # -- coding: utf-8 -- """ @AUTHOR : zlikun <zlikun-dev@hotmail.com> @DATE : 2019/03/12 19:23:03 @DESC : 希尔排序,就换种写法而已 """ numbers = [8, 231, 244, 32, 221, 248, 8, 153, 142, 235] def shell_sort(lst: "list"): for gap in gap_generator(len(lst)): for i in range(gap, len(lst), gap): sentinel = lst[i] j = i - gap while j > 0 and sentinel < lst[j]: lst[j + gap], lst[j] = lst[j], sentinel j -= gap def gap_generator(length): """ 缩小增量序列生成器 :param length: :return: """ gap = length // 2 while gap > 0: yield gap gap //= 2 if __name__ == '__main__': # 排序前: [8, 231, 244, 32, 221, 248, 8, 153, 142, 235] print('排序前:', numbers) # 执行排序 shell_sort(numbers) # 排序后: [8, 8, 32, 142, 153, 221, 231, 235, 244, 248] print('排序后:', numbers)
13,397
https://github.com/mdclyburn/tock/blob/master/chips/rp2040/src/pio.rs
Github Open Source
Open Source
ECL-2.0, Apache-2.0, MIT-0, MIT
null
tock
mdclyburn
Rust
Code
2,032
6,933
//! Programmable I/O peripheral. use core::cell::Cell; use core::default::Default; use kernel::errorcode::ErrorCode; use kernel::utilities::cells::OptionalCell; use kernel::utilities::registers::interfaces::{ ReadWriteable, Writeable }; use kernel::utilities::registers::{ register_bitfields, register_structs, ReadOnly, ReadWrite, WriteOnly, }; use kernel::utilities::StaticRef; #[repr(C)] struct StateMachineControl { clkdiv: ReadWrite<u32, SM_CLKDIV::Register>, execctrl: ReadWrite<u32, SM_EXECCTRL::Register>, shiftctrl: ReadWrite<u32, SM_SHIFTCTRL::Register>, addr: ReadOnly<u32, SM_ADDR::Register>, instr: ReadWrite<u32, SM_INSTR::Register>, pinctrl: ReadWrite<u32, SM_PINCTRL::Register>, } #[repr(C)] struct InterruptControl { inte: ReadWrite<u32, INTx::Register>, intf: ReadWrite<u32, INTx::Register>, ints: ReadOnly<u32, INTx::Register>, } register_structs! { PIORegisters { // PIO control (0x000 => ctrl: ReadWrite<u32, CTRL::Register>), // FIFO status (0x004 => fstat: ReadOnly<u32, FSTAT::Register>), // FIFO debug (0x008 => fdebug: ReadWrite<u32, FDEBUG::Register>), // FIFO levels (0x00c => flevel: ReadOnly<u32, FLEVEL::Register>), // TX FIFO entries (0x010 => txf: [WriteOnly<u32, TXF::Register>; 4]), // RX FIFO entries (0x020 => rxf: [ReadOnly<u32, RXF::Register>; 4]), // IRQ (0x030 => irq: ReadWrite<u32, IRQ::Register>), // IRQ force (0x034 => irq_force: WriteOnly<u32, IRQ_FORCE::Register>), // Input sync bypass (0x038 => input_sync_bypass: ReadWrite<u32, INPUT_SYNC_BYPASS::Register>), // Debug pad output (0x03c => dbg_padout: ReadOnly<u32, DBG_PADOUT::Register>), // Debug pad output enable (0x040 => dbg_padoe: ReadOnly<u32, DBG_PADOE::Register>), // Debug configuration info (0x044 => dbg_cfginfo: ReadOnly<u32, DBG_CFGINFO::Register>), // Instruction memory (0x048 => instr_mem: [WriteOnly<u32, INSTR_MEM::Register>; 32]), // State machine control (0x0c8 => sm_ctrl: [StateMachineControl; 4]), // Raw interrupts (0x128 => intr: ReadOnly<u32, INTx::Register>), // Interrupt enable/force/status (0x12c => int: [InterruptControl; 2]), (0x144 => @END), } } register_bitfields! [ u32, CTRL [ CLKDIV_RESTART OFFSET(8) NUMBITS(4), SM_RESTART OFFSET(4) NUMBITS(4), SM_ENABLE OFFSET(0) NUMBITS(4), ], FSTAT [ TXEMPTY OFFSET(24) NUMBITS(4), TXFULL OFFSET(16) NUMBITS(4), RXEMPTY OFFSET(8) NUMBITS(4), RXFULL OFFSET(0) NUMBITS(4), ], FDEBUG [ TXSTALL OFFSET(24) NUMBITS(4), TXOVER OFFSET(16) NUMBITS(4), RXUNDER OFFSET(8) NUMBITS(4), RXSTALL OFFSET(0) NUMBITS(4), ], FLEVEL [ RX3 OFFSET(28) NUMBITS(4), TX3 OFFSET(24) NUMBITS(4), RX2 OFFSET(20) NUMBITS(4), TX2 OFFSET(16) NUMBITS(4), RX1 OFFSET(12) NUMBITS(4), TX1 OFFSET(8) NUMBITS(4), RX0 OFFSET(4) NUMBITS(4), TX0 OFFSET(0) NUMBITS(4), ], TXF [ ENTRY OFFSET(0) NUMBITS(32), ], RXF [ ENTRY OFFSET(0) NUMBITS(32), ], IRQ [ FLAGS OFFSET(0) NUMBITS(8), ], IRQ_FORCE [ FLAGS OFFSET(0) NUMBITS(8), ], INPUT_SYNC_BYPASS [ BITFIELD OFFSET(0) NUMBITS(32), ], DBG_PADOUT [ BITFIELD OFFSET(0) NUMBITS(32), ], DBG_PADOE [ BITFIELD OFFSET(0) NUMBITS(32), ], DBG_CFGINFO [ IMEM_SIZE OFFSET(16) NUMBITS(6), SM_COUNT OFFSET(8) NUMBITS(4), FIFO_DEPTH OFFSET(0) NUMBITS(6), ], INSTR_MEM [ INSTRUCTION OFFSET(0) NUMBITS(16), ], SM_CLKDIV [ INT OFFSET(16) NUMBITS(16), FRAC OFFSET(8) NUMBITS(8), ], SM_EXECCTRL [ EXEC_STALLED OFFSET(31) NUMBITS(1), SIDE_EN OFFSET(30) NUMBITS(1), SIDE_PINDIR OFFSET(29) NUMBITS(1), JMP_PIN OFFSET(24) NUMBITS(5), OUT_EN_SEL OFFSET(19) NUMBITS(5), INLINE_OUT_EN OFFSET(18) NUMBITS(1), OUT_STICKY OFFSET(17) NUMBITS(1), WRAP_TOP OFFSET(12) NUMBITS(5), WRAP_BOTTOM OFFSET(7) NUMBITS(5), STATUS_SEL OFFSET(4) NUMBITS(1), STATUS_N OFFSET(0) NUMBITS(4), ], SM_SHIFTCTRL [ FJOIN_RX OFFSET(31) NUMBITS(1), FJOIN_TX OFFSET(30) NUMBITS(1), PULL_THRESH OFFSET(25) NUMBITS(5), PUSH_THRESH OFFSET(20) NUMBITS(5), OUT_SHIFTDIR OFFSET(19) NUMBITS(1), IN_SHIFTDIR OFFSET(18) NUMBITS(1), AUTOPULL OFFSET(17) NUMBITS(1), AUTOPUSH OFFSET(16) NUMBITS(1), ], SM_ADDR [ ADDR OFFSET(0) NUMBITS(5), ], SM_INSTR [ INSTR OFFSET(0) NUMBITS(16), ], SM_PINCTRL [ SIDESET_COUNT OFFSET(29) NUMBITS(3), SET_COUNT OFFSET(26) NUMBITS(3), OUT_COUNT OFFSET(20) NUMBITS(6), IN_BASE OFFSET(15) NUMBITS(5), SIDESET_BASE OFFSET(10) NUMBITS(5), SET_BASE OFFSET(5) NUMBITS(5), OUT_BASE OFFSET(0) NUMBITS(5), ], INTx [ SM3 OFFSET(11) NUMBITS(1), SM2 OFFSET(10) NUMBITS(1), SM1 OFFSET(9) NUMBITS(1), SM0 OFFSET(8) NUMBITS(1), SM3_TXNFULL OFFSET(7) NUMBITS(1), SM2_TXNFULL OFFSET(6) NUMBITS(1), SM1_TXNFULL OFFSET(5) NUMBITS(1), SM0_TXNFULL OFFSET(4) NUMBITS(1), SM3_RXNEMPTY OFFSET(3) NUMBITS(1), SM2_RXNEMPTY OFFSET(3) NUMBITS(1), SM1_RXNEMPTY OFFSET(3) NUMBITS(1), SM0_RXNEMPTY OFFSET(3) NUMBITS(1), ], ]; const PIO0_BASE_ADDRESS: usize = 0x5020_0000; const PIO1_BASE_ADDRESS: usize = 0x5030_0000; const PIO0: StaticRef<PIORegisters> = unsafe { StaticRef::new(PIO0_BASE_ADDRESS as *const PIORegisters) }; const PIO1: StaticRef<PIORegisters> = unsafe { StaticRef::new(PIO1_BASE_ADDRESS as *const PIORegisters) }; /// FIFO to use for the MOV x, STATUS instruction in [`Parameters`]. #[derive(Clone, Copy, PartialEq)] pub enum StatusSelectFIFO { /// Use the transmit FIFO. Transmit, /// Use the receive FIFO. Receive, } /// How to allocate FIFO space for a state machine. #[derive(Clone, Copy)] pub enum FIFOAllocation { /// Transmit and receive FIFOs have the same size. Balanced, /// Transmit FIFO steals the receive FIFO's storage. Transmit, /// Receive FIFO steals the transmit FIFO's storage. Receive, } /// Direction to shift data entering/leaving shift registers. #[derive(Clone, Copy)] #[repr(u32)] pub enum ShiftDirection { /// Shift data left. Left = 0, /// Shift data right. Right = 1, } /// Autopush/autopull configuration. #[derive(Clone, Copy)] pub enum Autoshift { /// Do not autopush/autopull. Off, /// Autopush/autopull the specified number of bits. On(u8), } /// Configuration for a PIO block. #[derive(Clone, Copy)] pub struct Parameters { // CLOCKDIV /// Clock divider for the state machine; 16-bit integer, 8-bit fractional. pub clock_divider: (u16, u8), // EXECCTRL /// Whether to use the MSB of delay/side-set field to make side-setting optional. /// /// Refer to SMx_EXECCTRL's SIDE_EN bitfield in the datasheet. pub side_set_enables: bool, /// Whether side-setting affects pin directions instead of pin values. pub side_set_pindir: bool, /// Number GPIO pin to use as a condition for JMP PIN. pub jmp_pin: u8, /// Which data bit to use for inline OUT enable. pub out_enable_bit: u8, /// Use a bit of OUT data as an auxiliary write enable. pub inline_out_enable: bool, /// Continuously assert the most recent OUT or SET to the pins. pub out_sticky: bool, /// Address to wrap to `wrap_bottom` from. pub wrap_top: u8, /// Address to wrap to when execution reaches `wrap_top`. pub wrap_bottom: u8, /// Comparison used for the MOV x, STATUS instruction. /// /// Refer to SMx_EXECCTRL's STATUS_SEL bitfield in the datasheet. pub status_source: StatusSelectFIFO, /// Comparison level for the MOV x, STATUS instruction. pub status_source_level: u8, // SHIFTCTRL /// How to allocate FIFO storage. pub fifo_allocation: FIFOAllocation, /// Direction to shift out from the OSR. pub osr_direction: ShiftDirection, /// Direction to shift into the ISR. pub isr_direction: ShiftDirection, /// Pull data into the output shift register upon reaching a threshold. pub autopull: Autoshift, /// Push data out of the input shift register upon reaching a threshold. pub autopush: Autoshift, // PINCTRL /// Number of MSBs to use for the for side-set (up to 5). pub side_set_count: u8, /// Number of pins to assert with a SET instruction. pub set_count: u8, /// Number of pins to assert with an OUT instruction. pub out_count: u8, /// First pin number mapped to the LSB of the IN data bus. pub in_base_pin: u8, /// First pin number mapped to the LSB of side-set data. pub side_set_base_pin: u8, /// First pin number mapped to the LSB of SET data. pub set_base_pin: u8, /// First pin number mapped to the LSB of OUT data. pub out_base_pin: u8, /// Initial pin direction configuration; a bit set means the pin is initially an output. pub initial_pindir: u8, } impl Default for Parameters { /// Produces the default configuration for a PIO block. /// /// The default values for parameters come from the RP2040 datasheet. /// These numbers are meant to be a safe default and not necessarily a usable default. fn default() -> Parameters { Parameters { clock_divider: (0, 0), side_set_enables: false, side_set_pindir: false, jmp_pin: 0, out_enable_bit: 0, inline_out_enable: false, out_sticky: false, wrap_top: 0x1f, wrap_bottom: 0x00, status_source: StatusSelectFIFO::Transmit, status_source_level: 0, fifo_allocation: FIFOAllocation::Balanced, osr_direction: ShiftDirection::Right, isr_direction: ShiftDirection::Right, autopull: Autoshift::Off, autopush: Autoshift::Off, side_set_count: 0, set_count: 5, out_count: 0, in_base_pin: 0, side_set_base_pin: 0, set_base_pin: 0, out_base_pin: 0, initial_pindir: 0b00000, } } } /// PIO block identifier. /// /// The PIOs have four interrupt lines: /// two lines for each of the two blocks. /// PIO0 controls PIO0_IRQ0 and PIO0_IRQ1, /// and PIO1 controls PIO1_IRQ0 and PIO1_IRQ1. /// The pair of this type and [`InterruptLine`] identify one of the four interrupt lines. #[derive(Clone, Copy)] #[allow(non_camel_case_types)] #[repr(u8)] pub enum BlockID { PIO0 = 0, PIO1 = 1, } /// PIO IRQ line. /// /// The PIOs have four interrupt lines: /// two lines for each of the two blocks. /// PIO0 controls PIO0_IRQ0 and PIO0_IRQ1, /// and PIO1 controls PIO1_IRQ0 and PIO1_IRQ1. /// The pair of this type and [`BlockID`] identify one of the four interrupt lines. #[derive(Clone, Copy)] #[allow(non_camel_case_types)] #[repr(u8)] pub enum InterruptLine { IRQ0 = 0, IRQ1 = 1, } #[derive(Clone, Copy)] #[repr(u8)] /// PIO state machine identifier. pub enum StateMachine { /// State machine 0. SM0 = 0, /// State machine 1. SM1 = 1, /// State machine 2. SM2 = 2, /// State machine 3. SM3 = 3, } /// Interrupt context information. #[derive(Clone, Copy)] pub enum Interrupt { /// A state machine raised an interrupt. Flag(StateMachine), /// A state machine's transmission FIFO has available space. TransmitNotFull(StateMachine), /// A state machine's reception FIFO has new data available. ReceiveNotEmpty(StateMachine), } /// Handler to receive notice of a PIO block's events. pub trait PIOBlockClient { /// Handler called by [`PIOBlock`] when the PIO peripheral raises an interrupt. fn interrupt_raised(&self, pio_block: &PIOBlock); } /// Binary-encoded SET. const ENC_INSTR_SET: u16 = 0b111_00000_000_00000; /// PIO peripheral instance. pub struct PIOBlock { registers: StaticRef<PIORegisters>, _client: OptionalCell<&'static dyn PIOBlockClient>, } impl PIOBlock { /// Set up the PIO block state machines. fn configure(&self, instructions: &[u16], sm_params: &[Option<&Parameters>; 4], interrupt_when: &[Interrupt], interrupt_on: InterruptLine) { // SM_ENABLE mask built by the loop. let mut enabled_machines = 0; for sm_no in 0..4 { enabled_machines >>= 1; if let Some(params) = sm_params[sm_no] { // CLKDIV register setup. let clkdiv = SM_CLKDIV::INT.val(params.clock_divider.0 as u32).value | SM_CLKDIV::FRAC.val(params.clock_divider.1 as u32).value; // EXECCTRL register setup. let execctrl = SM_EXECCTRL::SIDE_EN.val(if params.side_set_enables { 1 } else { 0 }).value | SM_EXECCTRL::SIDE_PINDIR.val(if params.side_set_pindir { 1 } else { 0 }).value | SM_EXECCTRL::JMP_PIN.val(params.jmp_pin as u32).value | SM_EXECCTRL::OUT_EN_SEL.val(params.out_enable_bit as u32).value | SM_EXECCTRL::INLINE_OUT_EN.val(if params.inline_out_enable { 1 } else { 0 }).value | SM_EXECCTRL::OUT_STICKY.val(if params.out_sticky { 1 } else { 0 }).value | SM_EXECCTRL::WRAP_TOP.val(params.wrap_top as u32).value | SM_EXECCTRL::WRAP_BOTTOM.val(params.wrap_bottom as u32).value | SM_EXECCTRL::STATUS_SEL.val(if params.status_source == StatusSelectFIFO::Transmit { 0 } else { 1 }).value | SM_EXECCTRL::STATUS_N.val(params.status_source_level as u32).value; // SHIFTCTRL let (fjoin_rx, fjoin_tx) = match params.fifo_allocation { FIFOAllocation::Balanced => (0, 0), FIFOAllocation::Receive => (1, 0), FIFOAllocation::Transmit => (0, 1), }; let (autopull, pull_threshold) = match params.autopull { Autoshift::Off => (0, 0), Autoshift::On(threshold) => (1, threshold), }; let (autopush, push_threshold) = match params.autopush { Autoshift::Off => (0, 0), Autoshift::On(threshold) => (1, threshold), }; let shiftctrl = SM_SHIFTCTRL::FJOIN_RX.val(fjoin_rx).value | SM_SHIFTCTRL::FJOIN_TX.val(fjoin_tx).value | SM_SHIFTCTRL::PULL_THRESH.val(pull_threshold as u32).value | SM_SHIFTCTRL::PUSH_THRESH.val(push_threshold as u32).value | SM_SHIFTCTRL::OUT_SHIFTDIR.val(params.osr_direction as u32).value | SM_SHIFTCTRL::IN_SHIFTDIR.val(params.isr_direction as u32).value | SM_SHIFTCTRL::AUTOPULL.val(autopull).value | SM_SHIFTCTRL::AUTOPUSH.val(autopush).value; let pinctrl = SM_PINCTRL::SIDESET_COUNT.val(params.side_set_count as u32).value | SM_PINCTRL::SET_COUNT.val(params.set_count as u32).value | SM_PINCTRL::OUT_COUNT.val(params.out_count as u32).value | SM_PINCTRL::IN_BASE.val(params.in_base_pin as u32).value | SM_PINCTRL::SIDESET_BASE.val(params.side_set_base_pin as u32).value | SM_PINCTRL::SET_BASE.val(params.set_base_pin as u32).value | SM_PINCTRL::OUT_BASE.val(params.out_base_pin as u32).value; // Configure the initial pin direction for side-set pins. // We must do this prior to actually setting the final settings. self.registers.sm_ctrl[sm_no] .pinctrl .modify(SM_PINCTRL::SET_BASE.val(params.side_set_base_pin as u32)); let side_set_pindirs_instr = { let mut pin_mask = 0; for i in 0..params.side_set_count { pin_mask |= 1 << i } ENC_INSTR_SET | 0b000_00000_100_00000 // Set PINDIRS. | pin_mask }; self.registers.sm_ctrl[sm_no].instr.set(side_set_pindirs_instr as u32); // Apply settings to registers. self.registers.sm_ctrl[sm_no].clkdiv.set(clkdiv); self.registers.sm_ctrl[sm_no].execctrl.set(execctrl); self.registers.sm_ctrl[sm_no].shiftctrl.set(shiftctrl); self.registers.sm_ctrl[sm_no].pinctrl.set(pinctrl); // Configure the initial pin direction for set pins. // This allows the PIOASM to shrink by not forcing the program to set this state. let set_pindirs_instr = ENC_INSTR_SET | 0b000_00000_100_00000 // Set PINDIRS. | params.initial_pindir as u16; self.registers.sm_ctrl[sm_no].instr.set(set_pindirs_instr as u32); // Start the state machine. enabled_machines |= 1 << 3; } } // Write instructions to instruction memory. for (idx, instr) in (0..32).zip(instructions) { self.registers.instr_mem[idx].set(*instr as u32) } // Enable the requested interrupt reasons. let mut inte = 0; for reason in interrupt_when { inte |= match reason { Interrupt::Flag(sm_id) => 1 << (8 + *sm_id as u8), Interrupt::TransmitNotFull(sm_id) => 1 << (4 + *sm_id as u8), Interrupt::ReceiveNotEmpty(sm_id) => 1 << (0 + *sm_id as u8), }; } self.registers.int[interrupt_on as usize].inte.set(inte); // Enable the state machines that have configurations. self.registers.ctrl.modify(CTRL::SM_ENABLE.val(enabled_machines)); } /// Returns the reason(s) for an interrupt. /// /// A client may call this function multiple times until it returns `None`. pub fn next_pending(&self) -> Option<Interrupt> { unimplemented!() } /// Interrupt handler for a specific PIO block. fn handle_interrupt(&self, _irq_line: InterruptLine) { unimplemented!() } } /// PIO instance. pub struct PIO { allocated: Cell<u8>, pio_blocks: [PIOBlock; 2], } impl PIO { /// Create a new PIO interface. pub const fn new() -> PIO { PIO { allocated: Cell::new(0), pio_blocks: [ PIOBlock { registers: PIO0, _client: OptionalCell::empty(), }, PIOBlock { registers: PIO1, _client: OptionalCell::empty(), } ], } } /// Handle a PIO interrupt. /// /// Passes on interrupt information to the PIO block software context for handling /// along with the interrupt line that is responsible for the interrupt. pub fn handle_interrupt(&self, interrupting_block: BlockID, irq_line: InterruptLine) { self.pio_blocks[interrupting_block as usize].handle_interrupt(irq_line); } /// Configure a PIO block. pub fn configure(&'static self, instructions: &[u16], params: &[Option<&Parameters>; 4], interrupt_when: &[Interrupt], interrupt_on: InterruptLine) -> Result<&'static PIOBlock, ErrorCode> { let block_no = self.allocated.get(); if block_no as usize >= self.pio_blocks.len() { Err(ErrorCode::BUSY) } else { let pio_block_idx = self.allocated.get(); let pio_block = &self.pio_blocks[pio_block_idx as usize]; pio_block.configure(instructions, params, interrupt_when, interrupt_on); self.allocated.set(pio_block_idx+1); Ok(pio_block) } } }
46,631
https://github.com/dreamonegit/payonehub/blob/master/app/Http/Controllers/AdminController.php
Github Open Source
Open Source
MIT
null
payonehub
dreamonegit
PHP
Code
172
710
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Intervention\Image\ImageManagerStatic as Image; use Storage; use Auth, Validator; use App\User; use DB; class AdminController extends Controller { public function __construct() { $this->user = new User(); } public function index(){ $this->data['title'] = 'Home'; return view('admin.index', $this->data); } public function myprofile(){ //echo auth::user()->id; exit; $this->data['title'] = 'My Profile'; return view('admin.myprofile', $this->data); } public function updateprofile(Request $request){ $user = User::where('id',auth::user()->id)->first(); $user->name = $request->input('name'); $user->email = $request->input('email'); $user->mobile = $request->input('mobile'); $user->status = $request->input('status'); $image = $profile_images = ''; if ($request->file('profile_image')) { $image = $request->file('profile_image'); $profile_images = 'Profile_image' . time() . '_' . $image->getClientOriginalName(); $image_resize = Image::make($image->getRealPath()); $image_resize->save(storage_path('app/public/profileimage/' .$profile_images)); $user->profile_image = $profile_images; } $user->save(); return redirect()->back()->with('message', 'Successfully profile is update...'); } public function resetpassword(Request $request){ $this->data['title'] = 'Reset Password'; return view('admin.resetpassword', $this->data); } public function updatepassword(Request $request){ $validator = Validator::make($request->all(), [ 'current_password' => 'required', 'new_password' => 'required', 'new_confirm_password' => 'same:new_password', ]); if ($validator->fails()) { $messages = $validator->messages(); return redirect()->back()->withErrors($messages)->withInput($request->all()); } if (!Hash::check($request->current_password, auth()->user()->password)) { return redirect()->back()->with('message', 'Current password is wrong...'); } User::find(auth()->user()->id)->update(['password'=> Hash::make($request->new_password)]); return redirect()->back()->with('message', 'Successfully password is updated...'); } }
46,022
https://github.com/reakain/ClimberSpider/blob/master/ClimberSpider/Assets/Scripts/UI/QuitHandler.cs
Github Open Source
Open Source
MIT
null
ClimberSpider
reakain
C#
Code
243
800
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace UIControls { public class QuitHandler : MonoBehaviour { public CanvasGroup uiCanvasGroup; public CanvasGroup confirmQuitCanvasGroup; public CanvasGroup splashCanvasGroup; bool splashMenuVisible = true; bool uiMenuVisible = false; bool confirmMenuVisible = false; void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { uiMenuVisible = !uiMenuVisible; } else if (Input.GetKeyDown(KeyCode.H)) { splashMenuVisible = !splashMenuVisible; } splashCanvasGroup.alpha = 0; splashCanvasGroup.interactable = false; splashCanvasGroup.blocksRaycasts = false; uiCanvasGroup.alpha = 0; uiCanvasGroup.interactable = false; uiCanvasGroup.blocksRaycasts = false; confirmQuitCanvasGroup.alpha = 0; confirmQuitCanvasGroup.interactable = false; confirmQuitCanvasGroup.blocksRaycasts = false; if (uiMenuVisible) { uiCanvasGroup.alpha = 1; uiCanvasGroup.interactable = true; uiCanvasGroup.blocksRaycasts = true; if (confirmMenuVisible) { uiCanvasGroup.alpha = 0.5f; confirmQuitCanvasGroup.alpha = 1; confirmQuitCanvasGroup.interactable = true; confirmQuitCanvasGroup.blocksRaycasts = true; } } else { confirmMenuVisible = false; if (splashMenuVisible) { splashCanvasGroup.alpha = 1; splashCanvasGroup.interactable = true; splashCanvasGroup.blocksRaycasts = true; } } } /*// Use this for initialization private void Awake() { //disable the quit confirmation panel DoConfirmQuitNo(); } */ /// <summary> /// Called if clicked on No (confirmation) /// </summary> public void DoConfirmQuitNo() { Debug.Log("Back to the game"); confirmMenuVisible = false; } /// <summary> /// Called if clicked on Yes (confirmation) /// </summary> public void DoConfirmQuitYes() { Debug.Log("Ok bye bye"); Application.Quit(); } /// <summary> /// Called if clicked on Quit /// </summary> public void DoQuit() { Debug.Log("Check form quit confirmation"); confirmMenuVisible = true; } /// <summary> /// Called if clicked on new game (example) /// </summary> public void DoNewGame() { Debug.Log("Launch a new game"); } public void DoInstructionsClose() { splashMenuVisible = false; } } }
4,204
https://github.com/zuoxiaobai/zuo-statistics/blob/master/peach-fe/src/components/LeftMenu.vue
Github Open Source
Open Source
MIT
2,022
zuo-statistics
zuoxiaobai
Vue
Code
308
1,224
<template> <div class="app-left" :class="{ 'expand-menu': !menuCollapse }"> <div class="app-left-top"> <div class="alt-left"> <img class="cursor-pointer" src="@/assets/peach.png" :title="title" @click="gotoHome" /> <h1>{{ title }}</h1> </div> <div class="alt-collapse" @click="menuCollapse = !menuCollapse"> <el-icon :title="menuCollapse ? '展开' : '收起'"> <Expand v-if="menuCollapse" /> <Fold v-else /> </el-icon> </div> </div> <div class="app-left-menu"> <el-menu class="el-menu-vertical-demo" :default-active="activeMenu" :router="true" active-text-color="#2846dc" :collapse="menuCollapse" @open="handleOpen" @close="handleClose" @select="selectMenu" > <el-menu-item index="home" :route="{ name: 'home' }"> <el-icon title="首页"><House /></el-icon> <span>首页</span> </el-menu-item> <el-menu-item index="websiteSummary" :route="{ name: 'websiteSummary' }" > <el-icon title="概览"><PieChart /></el-icon> <span>概览</span> </el-menu-item> <el-menu-item index="accessAnalysis" :route="{ name: 'accessAnalysis' }" > <el-icon title="实时访客"><Histogram /></el-icon> <span>实时访客</span> </el-menu-item> </el-menu> </div> </div> </template> <script setup lang="ts"> import { computed, ref } from "vue"; import { useRouter } from "vue-router"; import { House, Histogram, PieChart, Expand, Fold, } from "@element-plus/icons-vue"; import router from "@/router"; const title = ref("Peach"); const menuCollapse = ref(false); const activeMenu = computed(() => { let router = useRouter(); let curRouteName = router.currentRoute.value.name; return curRouteName; }); const selectMenu: (data: string) => void = (data) => { console.log(data); }; const handleOpen = () => { console.log("handleOpen"); }; const handleClose = () => { console.log("handleClose"); }; const gotoHome = () => { router.push("/"); }; </script> <style lang="scss" scoped> .app-left { position: fixed; left: 0; z-index: 5; height: 100%; width: 64px; flex-shrink: 0; transition: width 0.6s; background-color: #fff; :deep(.el-menu) { border-right: none; .el-menu-item { border-left: 5px solid #fff; } .el-menu-item.is-active { background-color: #fafbff; border-left: 5px solid #2d4bdc; } } &.expand-menu { width: 200px; .app-left-top { flex-direction: row; height: 60px; } h1 { display: block !important; } } .app-left-top { @include flex-center(); flex-direction: column; justify-content: space-between; height: 120px; padding: 20px; box-sizing: border-box; box-shadow: 5px 5px 10px #efefef; .alt-left { @include flex-center(); } .alt-left img { width: 45px; height: 45px; } .alt-left h1 { display: none; margin-left: 4px; font-size: 18px; font-weight: bold; color: #414359; } .alt-collapse { @include flex-center(); font-size: 18px; color: #666; } } .app-left-menu { margin-top: 20px; } } </style>
31,297
https://github.com/cjango/mall-order/blob/master/src/Order/Models/OrderLog.php
Github Open Source
Open Source
MIT
null
mall-order
cjango
PHP
Code
106
381
<?php namespace Jason\Order\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\MorphTo; class OrderLog extends Model { const UPDATED_AT = null; protected $guarded = []; /** * Notes: 设置用户 * @Author: <C.Jason> * @Date: 2019/11/22 3:51 下午 * @param $user */ public function setUserAttribute($user) { if (!is_null($user)) { $this->attributes['user_type'] = get_class($user) ?? null; $this->attributes['user_id'] = $user->id ?? 0; } } /** * Notes: 所属订单 * @Author: <C.Jason> * @Date: 2019/11/20 1:50 下午 * @return BelongsTo */ public function order(): BelongsTo { return $this->belongsTo(Order::class); } /** * Notes: 操作用户 * @Author: <C.Jason> * @Date: 2019/11/20 1:50 下午 * @return MorphTo */ public function user(): MorphTo { return $this->morphTo(); } }
34,022
https://github.com/joelong01/Catan/blob/master/MainPage/Settlements and Roads/SettlementCtrl.xaml.cs
Github Open Source
Open Source
MIT
null
Catan
joelong01
C#
Code
111
375
using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236 namespace Catan10 { public sealed partial class SettlementCtrl : UserControl { public SettlementCtrl() { this.InitializeComponent(); } public static readonly DependencyProperty PlayerColorProperty = DependencyProperty.Register("PlayerColor", typeof(Color), typeof(SettlementCtrl), new PropertyMetadata(Colors.Blue, PlayerColorChanged)); public static readonly DependencyProperty CastleColorProperty = DependencyProperty.Register("CastleColor", typeof(Color), typeof(CityCtrl), new PropertyMetadata(Colors.Black)); public Color CastleColor { get => (Color)GetValue(CastleColorProperty); private set => SetValue(CastleColorProperty, value); } public Color PlayerColor { get => (Color)GetValue(PlayerColorProperty); set => SetValue(PlayerColorProperty, value); } private static void PlayerColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SettlementCtrl depPropClass = d as SettlementCtrl; Color depPropValue = (Color)e.NewValue; depPropClass.SetPlayerColor(depPropValue); } private void SetPlayerColor(Color color) { CastleColor = StaticHelpers.BackgroundToForegroundColorDictionary[color]; } } }
39,171
https://github.com/juicycleff/node-eventstore-client/blob/master/src/systemData/inspectionResult.js
Github Open Source
Open Source
MIT
2,020
node-eventstore-client
juicycleff
JavaScript
Code
26
83
function InspectionResult(decision, description, tcpEndPoint, secureTcpEndPoint) { this.decision = decision; this.description = description; this.tcpEndPoint = tcpEndPoint || null; this.secureTcpEndPoint = secureTcpEndPoint || null; } module.exports = InspectionResult;
37,031
https://github.com/qch-china/my-php7/blob/master/my_test/example.php
Github Open Source
Open Source
PHP-3.01
null
my-php7
qch-china
PHP
Code
4
12
<?php echo "hello world\n";
47,504
https://github.com/daniel-007/molly_wallet/blob/master/frontend/src/pages/Login/KeyStoreMigrate.vue
Github Open Source
Open Source
MIT
2,020
molly_wallet
daniel-007
Vue
Code
542
2,225
<template> <div class="container"> <div class="row"> <div class="col-12"> <form ref="textareaform" @submit.prevent="form" class="container"> <div class="row"> <div class="col mx-auto login-box"> <div class="input-box"> <div> <label class="control-label" >Select your P12 file</label > <file-selector v-model="keystorePath" :placeholder="keystorePath" action="SelectFile2" /> </div> <div> <fg-input style="margin-bottom: 0.125em" type="text" label="Key Alias" v-model="alias" :placeholder="alias" @input="validCheck()" /> </div> <div> <label class="control-label"> <span>Keystore Password </span> <span style="color: #db6e44; font-size: 0.875em"> (NOTE: Use this password for future logins) </span> </label> <password-input style="margin: 0" v-model="keystorePassword" :validate="false" @input="validCheck()" /> </div> <div> <password-input v-model="KeyPassword" label="Key Password" :validate="false" @input="validCheck()" /> </div> </div> <div class="button-box"> <div class="container"> <div class="row"> <div class="col"> <p-button class="btn-secondary" block :disabled="!valid" @click.native="migrate()" > <span style="display: block"> COMPLETE MIGRATION</span> </p-button> </div> </div> <div class="row"> <div class="col"> <!-- <p class="text-right">Don't have a wallet yet? Create one <a href="javascript:void(0)" @click="newWallet()">here!</a></p> --> </div> </div> </div> </div> </div> </div> </form> </div> </div> <page-overlay text="Loading..." :isActive="overlay" /> </div> </template> <script> import Swal from "sweetalert2/dist/sweetalert2"; export default { name: "keystore-migrate", data: () => ({ keystorePassword: "", KeyPassword: "", overlay: false, valid: false, }), computed: { keystorePath: { get() { return this.$store.state.wallet.keystorePath; }, set(value) { this.$store.commit("wallet/setKeystorePath", value); }, }, alias: { get() { return this.$store.state.wallet.alias; }, set(value) { this.$store.commit("wallet/setAlias", value); }, }, }, methods: { validCheck: function() { this.valid = this.keystorePassword && this.KeyPassword && this.alias && this.keystorePath; }, completeMigration: function() { this.$router.push({ name: "keystore migration complete", params: { title: "Molly Wallet migration wizard", message: "You have completed the Molly Wallet password migration!", }, }); }, migrate: function() { var self = this; if (self.keystorePath) { self.$Progress.start(); self.overlay = true; window.backend.WalletApplication.MigrateWallet( self.keystorePath, self.keystorePassword, self.KeyPassword, self.alias ).then((filePath) => { if (filePath) { self.overlay = false; self.$Progress.finish(); this.$store.dispatch("wallet/reset").then(() => { this.$router.push({ name: "keystore migration complete", params: { title: "Molly Wallet migration wizard", filePath: filePath, message: "Congratulations! You have completed the Molly Wallet file migration!", } }); }); } else { self.overlay = false; self.$Progress.fail(); } }, (error) => { self.overlay = false; self.$Progress.finish(); Swal.fire("Unable to migrate file", error, "error"); } ); } }, login: function() { var self = this; self.$Progress.start(); self.overlay = true; window.backend.WalletApplication.Login( self.keystorePath, self.keystorePassword, self.KeyPassword, self.alias ).then((result) => { if (result) { window.backend.WalletApplication.GetUserTheme().then((darkMode) => self.$store.commit("wallet/setDarkMode", darkMode) ); window.backend.WalletApplication.GetWalletTag().then((walletTag) => self.$store.commit("wallet/setLabel", walletTag) ); window.backend.WalletApplication.GetImagePath().then((imagePath) => self.$store.commit("wallet/setImgPath", imagePath) ); self.overlay = false; self.$Progress.finish(); self.$store.commit("app/setIsLoggedIn", true); window.backend.WalletApplication.CheckTermsOfService().then( (result) => { self.$store.commit("wallet/setTermsOfService", result); if (result) { self.$router.push({ name: "loading", params: { message: "Getting your $DAG Wallet ready..." }, }); } else { self.$router.push({ name: "accept terms of service", params: { message: "Terms of Service" }, }); } } ); } else { self.overlay = false; self.$Progress.finish(); } }); }, }, }; </script> <style scoped lang="scss"> .login-box { max-width: 29rem; min-width: 29rem; padding-bottom: 2rem; } .input-box > div { margin-bottom: 1.875em; } .btn-secondary { background: #db6e44; border: 0.0625rem solid #db6e44; font-family: Poppins; font-style: normal; font-weight: 500; font-size: 0.75rem; line-height: 1.125rem; text-align: center; letter-spacing: 0.1em; border-radius: 0.25rem; color: #ffffff; &:hover { background: #af5836; border: 0.0625rem solid #af5836; } &:active, &:focus { background: #db6e44 !important; border: 0.0625rem solid #db6e44 !important; } &:active { outline-color: #db6e44 !important; outline-width: 0; } &:disabled { background: #e9a88f !important; border: 0.0625rem solid #e9a88f !important; } } .button-box .container { margin-left: 0em; margin-right: 0em; padding-left: 0em; padding-right: 0em; } .button-box .container .row { margin-left: 0em; margin-right: 0em; padding-left: 0em; padding-right: 0em; margin-top: 1.25em; } .button-box .container .row [class^="col"] { margin-left: 0em; margin-right: 0em; padding-left: 0em; padding-right: 0em; } </style>
47,562
https://github.com/JkzsJk/Sample-DotNet/blob/master/samples/aspnet/WebApi/Todo/Todo.WindowsStore/AppSettings.cs
Github Open Source
Open Source
Apache-2.0
2,022
Sample-DotNet
JkzsJk
C#
Code
136
492
using Account.Client; using System.Collections.Generic; using System.Linq; using Windows.Security.Credentials; using Windows.Storage; namespace Todo.WindowsStore { public class AppSettings : IAccessTokenStore { const string AccessTokenKey = "TodoAccessToken"; const string TodoResource = "Todo"; ApplicationDataContainer roamingSettings = ApplicationData.Current.RoamingSettings; PasswordVault passwordVault = new PasswordVault(); public string AccessToken { get { return roamingSettings.Values[AccessTokenKey] as string; } set { roamingSettings.Values[AccessTokenKey] = value; } } IEnumerable<PasswordCredential> GetPasswordCredentials() { return passwordVault.RetrieveAll().Where(cred => cred.Resource == TodoResource); } public PasswordCredential GetPasswordCredential() { return GetPasswordCredentials().FirstOrDefault(); } public void ClearPasswordCredentials() { foreach (PasswordCredential passwordCredential in GetPasswordCredentials()) { passwordVault.Remove(passwordCredential); } } public void ChangePasswordCredential(string username, string newPassword) { PasswordCredential passwordCredential = GetPasswordCredentials().Where(cred => cred.UserName == username).FirstOrDefault(); if (passwordCredential != null) { passwordVault.Remove(passwordCredential); passwordCredential.Password = newPassword; passwordVault.Add(passwordCredential); } } public void SavePasswordCredential(string username, string password) { passwordVault.Add(new PasswordCredential(TodoResource, username, password)); } public void LogOff() { AccessToken = null; ClearPasswordCredentials(); } } }
50,535
https://github.com/DataBiosphere/jade-data-repo/blob/master/datarepo-clienttests/src/main/java/scripts/testscripts/BillingProfileOwnerHandoffTest.java
Github Open Source
Open Source
BSD-3-Clause
2,022
jade-data-repo
DataBiosphere
Java
Code
192
670
package scripts.testscripts; import bio.terra.datarepo.model.BillingProfileModel; import java.util.List; import java.util.UUID; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import runner.config.TestUserSpecification; import scripts.testscripts.baseclasses.BillingProfileUsers; import scripts.utils.tdrwrapper.DataRepoWrap; public class BillingProfileOwnerHandoffTest extends BillingProfileUsers { private static final Logger logger = LoggerFactory.getLogger(BillingProfileOwnerHandoffTest.class); private String stewardsEmail; /** Public constructor so that this class can be instantiated via reflection. */ public BillingProfileOwnerHandoffTest() { super(); } public void setup(List<TestUserSpecification> testUsers) throws Exception { super.setup(testUsers); } public void setParameters(List<String> parameters) throws Exception { if (parameters == null || parameters.size() == 0) { throw new IllegalArgumentException( "Must provide a number of files to load in the parameters list"); } else { stewardsEmail = parameters.get(0); } } public void userJourney(TestUserSpecification testUser) throws Exception { BillingProfileModel profile = null; DataRepoWrap ownerUser1Api = DataRepoWrap.wrapFactory(ownerUser1, server); DataRepoWrap ownerUser2Api = DataRepoWrap.wrapFactory(ownerUser2, server); DataRepoWrap userUserApi = DataRepoWrap.wrapFactory(userUser, server); try { profile = ownerUser1Api.createProfile(billingAccount, "profile_permission_test", true); UUID profileId = profile.getId(); ownerUser1Api.addProfilePolicyMember(profileId, "owner", userUser.userEmail); userUserApi.deleteProfilePolicyMember(profileId, "owner", ownerUser2.userEmail); // Make sure removed owner can perform none of the operations testOperations(ownerUser2Api, RoleState.NONE, profileId); userUserApi.addProfilePolicyMember(profileId, "owner", ownerUser2.userEmail); testOperations(ownerUser2Api, RoleState.OWNER, profileId); ownerUser2Api.deleteProfile(profileId); profile = null; } catch (Exception e) { logger.error("Error in journey", e); e.printStackTrace(); throw e; } finally { if (profile != null) { ownerUser1Api.deleteProfile(profile.getId()); } } } }
9,807
https://github.com/thomashanahan/app-nestjs/blob/master/src/gamingConsoles/dto/findManyGamingConsole.dto.ts
Github Open Source
Open Source
MIT
null
app-nestjs
thomashanahan
TypeScript
Code
80
225
import { ValidateNested, IsOptional } from 'class-validator'; import { Type } from 'class-transformer'; import { ApiModelProperty } from '@nestjs/swagger'; import { QueryFilterDto } from '../../shared/dto/queryFilter.dto'; import { FindGamingConsoleDto } from './findGamingConsole.dto'; export class FindManyGamingConsoleDto extends QueryFilterDto { @IsOptional() @ValidateNested({ each: true }) @ApiModelProperty({ required: false }) @Type(() => FindGamingConsoleDto) readonly where?: FindGamingConsoleDto; @IsOptional() @ApiModelProperty({ required: false }) // @ValidateNested({ each: true }) // @Type(() => FindGamingConsoleDto) readonly sortBy?: { [K in keyof FindGamingConsoleDto]: 'ASC' | 'DESC' } | {}; }
22,813